clang-tools  9.0.0svn
RedundantExpressionCheck.cpp
Go to the documentation of this file.
1 //===--- RedundantExpressionCheck.cpp - clang-tidy-------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 #include "../utils/Matchers.h"
11 #include "../utils/OptionsUtils.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/Basic/LLVM.h"
15 #include "clang/Basic/SourceLocation.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Lex/Lexer.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/APSInt.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/Support/Casting.h"
22 #include <algorithm>
23 #include <cassert>
24 #include <cstdint>
25 #include <string>
26 #include <vector>
27 
28 using namespace clang::ast_matchers;
29 using namespace clang::tidy::matchers;
30 
31 namespace clang {
32 namespace tidy {
33 namespace misc {
34 namespace {
35 using llvm::APSInt;
36 
37 static constexpr llvm::StringLiteral KnownBannedMacroNames[] = {
38  "EAGAIN",
39  "EWOULDBLOCK",
40  "SIGCLD",
41  "SIGCHLD",
42 };
43 
44 static bool incrementWithoutOverflow(const APSInt &Value, APSInt &Result) {
45  Result = Value;
46  ++Result;
47  return Value < Result;
48 }
49 
50 static bool areEquivalentNameSpecifier(const NestedNameSpecifier *Left,
51  const NestedNameSpecifier *Right) {
52  llvm::FoldingSetNodeID LeftID, RightID;
53  Left->Profile(LeftID);
54  Right->Profile(RightID);
55  return LeftID == RightID;
56 }
57 
58 static bool areEquivalentExpr(const Expr *Left, const Expr *Right) {
59  if (!Left || !Right)
60  return !Left && !Right;
61 
62  Left = Left->IgnoreParens();
63  Right = Right->IgnoreParens();
64 
65  // Compare classes.
66  if (Left->getStmtClass() != Right->getStmtClass())
67  return false;
68 
69  // Compare children.
70  Expr::const_child_iterator LeftIter = Left->child_begin();
71  Expr::const_child_iterator RightIter = Right->child_begin();
72  while (LeftIter != Left->child_end() && RightIter != Right->child_end()) {
73  if (!areEquivalentExpr(dyn_cast<Expr>(*LeftIter),
74  dyn_cast<Expr>(*RightIter)))
75  return false;
76  ++LeftIter;
77  ++RightIter;
78  }
79  if (LeftIter != Left->child_end() || RightIter != Right->child_end())
80  return false;
81 
82  // Perform extra checks.
83  switch (Left->getStmtClass()) {
84  default:
85  return false;
86 
87  case Stmt::CharacterLiteralClass:
88  return cast<CharacterLiteral>(Left)->getValue() ==
89  cast<CharacterLiteral>(Right)->getValue();
90  case Stmt::IntegerLiteralClass: {
91  llvm::APInt LeftLit = cast<IntegerLiteral>(Left)->getValue();
92  llvm::APInt RightLit = cast<IntegerLiteral>(Right)->getValue();
93  return LeftLit.getBitWidth() == RightLit.getBitWidth() &&
94  LeftLit == RightLit;
95  }
96  case Stmt::FloatingLiteralClass:
97  return cast<FloatingLiteral>(Left)->getValue().bitwiseIsEqual(
98  cast<FloatingLiteral>(Right)->getValue());
99  case Stmt::StringLiteralClass:
100  return cast<StringLiteral>(Left)->getBytes() ==
101  cast<StringLiteral>(Right)->getBytes();
102  case Stmt::CXXOperatorCallExprClass:
103  return cast<CXXOperatorCallExpr>(Left)->getOperator() ==
104  cast<CXXOperatorCallExpr>(Right)->getOperator();
105  case Stmt::DependentScopeDeclRefExprClass:
106  if (cast<DependentScopeDeclRefExpr>(Left)->getDeclName() !=
107  cast<DependentScopeDeclRefExpr>(Right)->getDeclName())
108  return false;
109  return areEquivalentNameSpecifier(
110  cast<DependentScopeDeclRefExpr>(Left)->getQualifier(),
111  cast<DependentScopeDeclRefExpr>(Right)->getQualifier());
112  case Stmt::DeclRefExprClass:
113  return cast<DeclRefExpr>(Left)->getDecl() ==
114  cast<DeclRefExpr>(Right)->getDecl();
115  case Stmt::MemberExprClass:
116  return cast<MemberExpr>(Left)->getMemberDecl() ==
117  cast<MemberExpr>(Right)->getMemberDecl();
118  case Stmt::CXXFunctionalCastExprClass:
119  case Stmt::CStyleCastExprClass:
120  return cast<ExplicitCastExpr>(Left)->getTypeAsWritten() ==
121  cast<ExplicitCastExpr>(Right)->getTypeAsWritten();
122  case Stmt::CallExprClass:
123  case Stmt::ImplicitCastExprClass:
124  case Stmt::ArraySubscriptExprClass:
125  return true;
126  case Stmt::UnaryOperatorClass:
127  if (cast<UnaryOperator>(Left)->isIncrementDecrementOp())
128  return false;
129  return cast<UnaryOperator>(Left)->getOpcode() ==
130  cast<UnaryOperator>(Right)->getOpcode();
131  case Stmt::BinaryOperatorClass:
132  return cast<BinaryOperator>(Left)->getOpcode() ==
133  cast<BinaryOperator>(Right)->getOpcode();
134  }
135 }
136 
137 // For a given expression 'x', returns whether the ranges covered by the
138 // relational operators are equivalent (i.e. x <= 4 is equivalent to x < 5).
139 static bool areEquivalentRanges(BinaryOperatorKind OpcodeLHS,
140  const APSInt &ValueLHS,
141  BinaryOperatorKind OpcodeRHS,
142  const APSInt &ValueRHS) {
143  assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
144  "Values must be ordered");
145  // Handle the case where constants are the same: x <= 4 <==> x <= 4.
146  if (APSInt::compareValues(ValueLHS, ValueRHS) == 0)
147  return OpcodeLHS == OpcodeRHS;
148 
149  // Handle the case where constants are off by one: x <= 4 <==> x < 5.
150  APSInt ValueLHS_plus1;
151  return ((OpcodeLHS == BO_LE && OpcodeRHS == BO_LT) ||
152  (OpcodeLHS == BO_GT && OpcodeRHS == BO_GE)) &&
153  incrementWithoutOverflow(ValueLHS, ValueLHS_plus1) &&
154  APSInt::compareValues(ValueLHS_plus1, ValueRHS) == 0;
155 }
156 
157 // For a given expression 'x', returns whether the ranges covered by the
158 // relational operators are fully disjoint (i.e. x < 4 and x > 7).
159 static bool areExclusiveRanges(BinaryOperatorKind OpcodeLHS,
160  const APSInt &ValueLHS,
161  BinaryOperatorKind OpcodeRHS,
162  const APSInt &ValueRHS) {
163  assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
164  "Values must be ordered");
165 
166  // Handle cases where the constants are the same.
167  if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
168  switch (OpcodeLHS) {
169  case BO_EQ:
170  return OpcodeRHS == BO_NE || OpcodeRHS == BO_GT || OpcodeRHS == BO_LT;
171  case BO_NE:
172  return OpcodeRHS == BO_EQ;
173  case BO_LE:
174  return OpcodeRHS == BO_GT;
175  case BO_GE:
176  return OpcodeRHS == BO_LT;
177  case BO_LT:
178  return OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
179  case BO_GT:
180  return OpcodeRHS == BO_EQ || OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
181  default:
182  return false;
183  }
184  }
185 
186  // Handle cases where the constants are different.
187  if ((OpcodeLHS == BO_EQ || OpcodeLHS == BO_LT || OpcodeLHS == BO_LE) &&
188  (OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE))
189  return true;
190 
191  // Handle the case where constants are off by one: x > 5 && x < 6.
192  APSInt ValueLHS_plus1;
193  if (OpcodeLHS == BO_GT && OpcodeRHS == BO_LT &&
194  incrementWithoutOverflow(ValueLHS, ValueLHS_plus1) &&
195  APSInt::compareValues(ValueLHS_plus1, ValueRHS) == 0)
196  return true;
197 
198  return false;
199 }
200 
201 // Returns whether the ranges covered by the union of both relational
202 // expressions cover the whole domain (i.e. x < 10 and x > 0).
203 static bool rangesFullyCoverDomain(BinaryOperatorKind OpcodeLHS,
204  const APSInt &ValueLHS,
205  BinaryOperatorKind OpcodeRHS,
206  const APSInt &ValueRHS) {
207  assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
208  "Values must be ordered");
209 
210  // Handle cases where the constants are the same: x < 5 || x >= 5.
211  if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
212  switch (OpcodeLHS) {
213  case BO_EQ:
214  return OpcodeRHS == BO_NE;
215  case BO_NE:
216  return OpcodeRHS == BO_EQ;
217  case BO_LE:
218  return OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
219  case BO_LT:
220  return OpcodeRHS == BO_GE;
221  case BO_GE:
222  return OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
223  case BO_GT:
224  return OpcodeRHS == BO_LE;
225  default:
226  return false;
227  }
228  }
229 
230  // Handle the case where constants are off by one: x <= 4 || x >= 5.
231  APSInt ValueLHS_plus1;
232  if (OpcodeLHS == BO_LE && OpcodeRHS == BO_GE &&
233  incrementWithoutOverflow(ValueLHS, ValueLHS_plus1) &&
234  APSInt::compareValues(ValueLHS_plus1, ValueRHS) == 0)
235  return true;
236 
237  // Handle cases where the constants are different: x > 4 || x <= 7.
238  if ((OpcodeLHS == BO_GT || OpcodeLHS == BO_GE) &&
239  (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE))
240  return true;
241 
242  // Handle cases where constants are different but both ops are !=, like:
243  // x != 5 || x != 10
244  if (OpcodeLHS == BO_NE && OpcodeRHS == BO_NE)
245  return true;
246 
247  return false;
248 }
249 
250 static bool rangeSubsumesRange(BinaryOperatorKind OpcodeLHS,
251  const APSInt &ValueLHS,
252  BinaryOperatorKind OpcodeRHS,
253  const APSInt &ValueRHS) {
254  int Comparison = APSInt::compareValues(ValueLHS, ValueRHS);
255  switch (OpcodeLHS) {
256  case BO_EQ:
257  return OpcodeRHS == BO_EQ && Comparison == 0;
258  case BO_NE:
259  return (OpcodeRHS == BO_NE && Comparison == 0) ||
260  (OpcodeRHS == BO_EQ && Comparison != 0) ||
261  (OpcodeRHS == BO_LT && Comparison >= 0) ||
262  (OpcodeRHS == BO_LE && Comparison > 0) ||
263  (OpcodeRHS == BO_GT && Comparison <= 0) ||
264  (OpcodeRHS == BO_GE && Comparison < 0);
265 
266  case BO_LT:
267  return ((OpcodeRHS == BO_LT && Comparison >= 0) ||
268  (OpcodeRHS == BO_LE && Comparison > 0) ||
269  (OpcodeRHS == BO_EQ && Comparison > 0));
270  case BO_GT:
271  return ((OpcodeRHS == BO_GT && Comparison <= 0) ||
272  (OpcodeRHS == BO_GE && Comparison < 0) ||
273  (OpcodeRHS == BO_EQ && Comparison < 0));
274  case BO_LE:
275  return (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE || OpcodeRHS == BO_EQ) &&
276  Comparison >= 0;
277  case BO_GE:
278  return (OpcodeRHS == BO_GT || OpcodeRHS == BO_GE || OpcodeRHS == BO_EQ) &&
279  Comparison <= 0;
280  default:
281  return false;
282  }
283 }
284 
285 static void transformSubToCanonicalAddExpr(BinaryOperatorKind &Opcode,
286  APSInt &Value) {
287  if (Opcode == BO_Sub) {
288  Opcode = BO_Add;
289  Value = -Value;
290  }
291 }
292 
293 AST_MATCHER(Expr, isIntegerConstantExpr) {
294  if (Node.isInstantiationDependent())
295  return false;
296  return Node.isIntegerConstantExpr(Finder->getASTContext());
297 }
298 
299 AST_MATCHER(BinaryOperator, operandsAreEquivalent) {
300  return areEquivalentExpr(Node.getLHS(), Node.getRHS());
301 }
302 
303 AST_MATCHER(ConditionalOperator, expressionsAreEquivalent) {
304  return areEquivalentExpr(Node.getTrueExpr(), Node.getFalseExpr());
305 }
306 
307 AST_MATCHER(CallExpr, parametersAreEquivalent) {
308  return Node.getNumArgs() == 2 &&
309  areEquivalentExpr(Node.getArg(0), Node.getArg(1));
310 }
311 
312 AST_MATCHER(BinaryOperator, binaryOperatorIsInMacro) {
313  return Node.getOperatorLoc().isMacroID();
314 }
315 
316 AST_MATCHER(ConditionalOperator, conditionalOperatorIsInMacro) {
317  return Node.getQuestionLoc().isMacroID() || Node.getColonLoc().isMacroID();
318 }
319 
320 AST_MATCHER(Expr, isMacro) { return Node.getExprLoc().isMacroID(); }
321 
322 AST_MATCHER_P(Expr, expandedByMacro, ArrayRef<llvm::StringLiteral>, Names) {
323  const SourceManager &SM = Finder->getASTContext().getSourceManager();
324  const LangOptions &LO = Finder->getASTContext().getLangOpts();
325  SourceLocation Loc = Node.getExprLoc();
326  while (Loc.isMacroID()) {
327  StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LO);
328  if (llvm::is_contained(Names, MacroName))
329  return true;
330  Loc = SM.getImmediateMacroCallerLoc(Loc);
331  }
332  return false;
333 }
334 
335 // Returns a matcher for integer constant expressions.
336 static ast_matchers::internal::Matcher<Expr>
337 matchIntegerConstantExpr(StringRef Id) {
338  std::string CstId = (Id + "-const").str();
339  return expr(isIntegerConstantExpr()).bind(CstId);
340 }
341 
342 // Retrieves the integer expression matched by 'matchIntegerConstantExpr' with
343 // name 'Id' and stores it into 'ConstExpr', the value of the expression is
344 // stored into `Value`.
345 static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result,
346  StringRef Id, APSInt &Value,
347  const Expr *&ConstExpr) {
348  std::string CstId = (Id + "-const").str();
349  ConstExpr = Result.Nodes.getNodeAs<Expr>(CstId);
350  return ConstExpr && ConstExpr->isIntegerConstantExpr(Value, *Result.Context);
351 }
352 
353 // Overloaded `retrieveIntegerConstantExpr` for compatibility.
354 static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result,
355  StringRef Id, APSInt &Value) {
356  const Expr *ConstExpr = nullptr;
357  return retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr);
358 }
359 
360 // Returns a matcher for symbolic expressions (matches every expression except
361 // ingeter constant expressions).
362 static ast_matchers::internal::Matcher<Expr> matchSymbolicExpr(StringRef Id) {
363  std::string SymId = (Id + "-sym").str();
364  return ignoringParenImpCasts(
365  expr(unless(isIntegerConstantExpr())).bind(SymId));
366 }
367 
368 // Retrieves the expression matched by 'matchSymbolicExpr' with name 'Id' and
369 // stores it into 'SymExpr'.
370 static bool retrieveSymbolicExpr(const MatchFinder::MatchResult &Result,
371  StringRef Id, const Expr *&SymExpr) {
372  std::string SymId = (Id + "-sym").str();
373  if (const auto *Node = Result.Nodes.getNodeAs<Expr>(SymId)) {
374  SymExpr = Node;
375  return true;
376  }
377  return false;
378 }
379 
380 // Match a binary operator between a symbolic expression and an integer constant
381 // expression.
382 static ast_matchers::internal::Matcher<Expr>
383 matchBinOpIntegerConstantExpr(StringRef Id) {
384  const auto BinOpCstExpr =
385  expr(
386  anyOf(binaryOperator(anyOf(hasOperatorName("+"), hasOperatorName("|"),
387  hasOperatorName("&")),
388  hasEitherOperand(matchSymbolicExpr(Id)),
389  hasEitherOperand(matchIntegerConstantExpr(Id))),
390  binaryOperator(hasOperatorName("-"),
391  hasLHS(matchSymbolicExpr(Id)),
392  hasRHS(matchIntegerConstantExpr(Id)))))
393  .bind(Id);
394  return ignoringParenImpCasts(BinOpCstExpr);
395 }
396 
397 // Retrieves sub-expressions matched by 'matchBinOpIntegerConstantExpr' with
398 // name 'Id'.
399 static bool
400 retrieveBinOpIntegerConstantExpr(const MatchFinder::MatchResult &Result,
401  StringRef Id, BinaryOperatorKind &Opcode,
402  const Expr *&Symbol, APSInt &Value) {
403  if (const auto *BinExpr = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
404  Opcode = BinExpr->getOpcode();
405  return retrieveSymbolicExpr(Result, Id, Symbol) &&
406  retrieveIntegerConstantExpr(Result, Id, Value);
407  }
408  return false;
409 }
410 
411 // Matches relational expressions: 'Expr <op> k' (i.e. x < 2, x != 3, 12 <= x).
412 static ast_matchers::internal::Matcher<Expr>
413 matchRelationalIntegerConstantExpr(StringRef Id) {
414  std::string CastId = (Id + "-cast").str();
415  std::string SwapId = (Id + "-swap").str();
416  std::string NegateId = (Id + "-negate").str();
417  std::string OverloadId = (Id + "-overload").str();
418 
419  const auto RelationalExpr = ignoringParenImpCasts(binaryOperator(
420  isComparisonOperator(), expr().bind(Id),
421  anyOf(allOf(hasLHS(matchSymbolicExpr(Id)),
422  hasRHS(matchIntegerConstantExpr(Id))),
423  allOf(hasLHS(matchIntegerConstantExpr(Id)),
424  hasRHS(matchSymbolicExpr(Id)), expr().bind(SwapId)))));
425 
426  // A cast can be matched as a comparator to zero. (i.e. if (x) is equivalent
427  // to if (x != 0)).
428  const auto CastExpr =
429  implicitCastExpr(hasCastKind(CK_IntegralToBoolean),
430  hasSourceExpression(matchSymbolicExpr(Id)))
431  .bind(CastId);
432 
433  const auto NegateRelationalExpr =
434  unaryOperator(hasOperatorName("!"),
435  hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))
436  .bind(NegateId);
437 
438  // Do not bind to double negation.
439  const auto NegateNegateRelationalExpr =
440  unaryOperator(hasOperatorName("!"),
441  hasUnaryOperand(unaryOperator(
442  hasOperatorName("!"),
443  hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))));
444 
445  const auto OverloadedOperatorExpr =
446  cxxOperatorCallExpr(
447  anyOf(hasOverloadedOperatorName("=="),
448  hasOverloadedOperatorName("!="), hasOverloadedOperatorName("<"),
449  hasOverloadedOperatorName("<="), hasOverloadedOperatorName(">"),
450  hasOverloadedOperatorName(">=")),
451  // Filter noisy false positives.
452  unless(isMacro()), unless(isInTemplateInstantiation()))
453  .bind(OverloadId);
454 
455  return anyOf(RelationalExpr, CastExpr, NegateRelationalExpr,
456  NegateNegateRelationalExpr, OverloadedOperatorExpr);
457 }
458 
459 // Checks whether a function param is non constant reference type, and may
460 // be modified in the function.
461 static bool isNonConstReferenceType(QualType ParamType) {
462  return ParamType->isReferenceType() &&
463  !ParamType.getNonReferenceType().isConstQualified();
464 }
465 
466 // Checks whether the arguments of an overloaded operator can be modified in the
467 // function.
468 // For operators that take an instance and a constant as arguments, only the
469 // first argument (the instance) needs to be checked, since the constant itself
470 // is a temporary expression. Whether the second parameter is checked is
471 // controlled by the parameter `ParamsToCheckCount`.
472 static bool
473 canOverloadedOperatorArgsBeModified(const FunctionDecl *OperatorDecl,
474  bool checkSecondParam) {
475  unsigned ParamCount = OperatorDecl->getNumParams();
476 
477  // Overloaded operators declared inside a class have only one param.
478  // These functions must be declared const in order to not be able to modify
479  // the instance of the class they are called through.
480  if (ParamCount == 1 &&
481  !OperatorDecl->getType()->getAs<FunctionType>()->isConst())
482  return true;
483 
484  if (isNonConstReferenceType(OperatorDecl->getParamDecl(0)->getType()))
485  return true;
486 
487  return checkSecondParam && ParamCount == 2 &&
488  isNonConstReferenceType(OperatorDecl->getParamDecl(1)->getType());
489 }
490 
491 // Retrieves sub-expressions matched by 'matchRelationalIntegerConstantExpr'
492 // with name 'Id'.
493 static bool retrieveRelationalIntegerConstantExpr(
494  const MatchFinder::MatchResult &Result, StringRef Id,
495  const Expr *&OperandExpr, BinaryOperatorKind &Opcode, const Expr *&Symbol,
496  APSInt &Value, const Expr *&ConstExpr) {
497  std::string CastId = (Id + "-cast").str();
498  std::string SwapId = (Id + "-swap").str();
499  std::string NegateId = (Id + "-negate").str();
500  std::string OverloadId = (Id + "-overload").str();
501 
502  if (const auto *Bin = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
503  // Operand received with explicit comparator.
504  Opcode = Bin->getOpcode();
505  OperandExpr = Bin;
506 
507  if (!retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr))
508  return false;
509  } else if (const auto *Cast = Result.Nodes.getNodeAs<CastExpr>(CastId)) {
510  // Operand received with implicit comparator (cast).
511  Opcode = BO_NE;
512  OperandExpr = Cast;
513  Value = APSInt(32, false);
514  } else if (const auto *OverloadedOperatorExpr =
515  Result.Nodes.getNodeAs<CXXOperatorCallExpr>(OverloadId)) {
516  const auto *OverloadedFunctionDecl = dyn_cast_or_null<FunctionDecl>(OverloadedOperatorExpr->getCalleeDecl());
517  if (!OverloadedFunctionDecl)
518  return false;
519 
520  if (canOverloadedOperatorArgsBeModified(OverloadedFunctionDecl, false))
521  return false;
522 
523  if (canOverloadedOperatorArgsBeModified(OverloadedFunctionDecl, false))
524  return false;
525 
526  if (!OverloadedOperatorExpr->getArg(1)->isIntegerConstantExpr(
527  Value, *Result.Context))
528  return false;
529 
530  Symbol = OverloadedOperatorExpr->getArg(0);
531  OperandExpr = OverloadedOperatorExpr;
532  Opcode = BinaryOperator::getOverloadedOpcode(OverloadedOperatorExpr->getOperator());
533 
534  return BinaryOperator::isComparisonOp(Opcode);
535  } else {
536  return false;
537  }
538 
539  if (!retrieveSymbolicExpr(Result, Id, Symbol))
540  return false;
541 
542  if (Result.Nodes.getNodeAs<Expr>(SwapId))
543  Opcode = BinaryOperator::reverseComparisonOp(Opcode);
544  if (Result.Nodes.getNodeAs<Expr>(NegateId))
545  Opcode = BinaryOperator::negateComparisonOp(Opcode);
546  return true;
547 }
548 
549 // Checks for expressions like (X == 4) && (Y != 9)
550 static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp, const ASTContext *AstCtx) {
551  const auto *LhsBinOp = dyn_cast<BinaryOperator>(BinOp->getLHS());
552  const auto *RhsBinOp = dyn_cast<BinaryOperator>(BinOp->getRHS());
553 
554  if (!LhsBinOp || !RhsBinOp)
555  return false;
556 
557  if ((LhsBinOp->getLHS()->isIntegerConstantExpr(*AstCtx) ||
558  LhsBinOp->getRHS()->isIntegerConstantExpr(*AstCtx)) &&
559  (RhsBinOp->getLHS()->isIntegerConstantExpr(*AstCtx) ||
560  RhsBinOp->getRHS()->isIntegerConstantExpr(*AstCtx)))
561  return true;
562  return false;
563 }
564 
565 // Retrieves integer constant subexpressions from binary operator expressions
566 // that have two equivalent sides.
567 // E.g.: from (X == 5) && (X == 5) retrieves 5 and 5.
568 static bool retrieveConstExprFromBothSides(const BinaryOperator *&BinOp,
569  BinaryOperatorKind &MainOpcode,
570  BinaryOperatorKind &SideOpcode,
571  const Expr *&LhsConst,
572  const Expr *&RhsConst,
573  const ASTContext *AstCtx) {
574  assert(areSidesBinaryConstExpressions(BinOp, AstCtx) &&
575  "Both sides of binary operator must be constant expressions!");
576 
577  MainOpcode = BinOp->getOpcode();
578 
579  const auto *BinOpLhs = cast<BinaryOperator>(BinOp->getLHS());
580  const auto *BinOpRhs = cast<BinaryOperator>(BinOp->getRHS());
581 
582  LhsConst = BinOpLhs->getLHS()->isIntegerConstantExpr(*AstCtx)
583  ? BinOpLhs->getLHS()
584  : BinOpLhs->getRHS();
585  RhsConst = BinOpRhs->getLHS()->isIntegerConstantExpr(*AstCtx)
586  ? BinOpRhs->getLHS()
587  : BinOpRhs->getRHS();
588 
589  if (!LhsConst || !RhsConst)
590  return false;
591 
592  assert(BinOpLhs->getOpcode() == BinOpRhs->getOpcode() &&
593  "Sides of the binary operator must be equivalent expressions!");
594 
595  SideOpcode = BinOpLhs->getOpcode();
596 
597  return true;
598 }
599 
600 static bool areExprsFromDifferentMacros(const Expr *LhsExpr,
601  const Expr *RhsExpr,
602  const ASTContext *AstCtx) {
603  if (!LhsExpr || !RhsExpr)
604  return false;
605 
606  SourceLocation LhsLoc = LhsExpr->getExprLoc();
607  SourceLocation RhsLoc = RhsExpr->getExprLoc();
608 
609  if (!LhsLoc.isMacroID() || !RhsLoc.isMacroID())
610  return false;
611 
612  const SourceManager &SM = AstCtx->getSourceManager();
613  const LangOptions &LO = AstCtx->getLangOpts();
614 
615  return !(Lexer::getImmediateMacroName(LhsLoc, SM, LO) ==
616  Lexer::getImmediateMacroName(RhsLoc, SM, LO));
617 }
618 
619 static bool areExprsMacroAndNonMacro(const Expr *&LhsExpr,
620  const Expr *&RhsExpr) {
621  if (!LhsExpr || !RhsExpr)
622  return false;
623 
624  SourceLocation LhsLoc = LhsExpr->getExprLoc();
625  SourceLocation RhsLoc = RhsExpr->getExprLoc();
626 
627  return LhsLoc.isMacroID() != RhsLoc.isMacroID();
628 }
629 } // namespace
630 
631 void RedundantExpressionCheck::registerMatchers(MatchFinder *Finder) {
632  const auto AnyLiteralExpr = ignoringParenImpCasts(
633  anyOf(cxxBoolLiteral(), characterLiteral(), integerLiteral()));
634 
635  const auto BannedIntegerLiteral =
636  integerLiteral(expandedByMacro(KnownBannedMacroNames));
637 
638  // Binary with equivalent operands, like (X != 2 && X != 2).
639  Finder->addMatcher(
640  binaryOperator(anyOf(hasOperatorName("-"), hasOperatorName("/"),
641  hasOperatorName("%"), hasOperatorName("|"),
642  hasOperatorName("&"), hasOperatorName("^"),
643  matchers::isComparisonOperator(),
644  hasOperatorName("&&"), hasOperatorName("||"),
645  hasOperatorName("=")),
646  operandsAreEquivalent(),
647  // Filter noisy false positives.
648  unless(isInTemplateInstantiation()),
649  unless(binaryOperatorIsInMacro()),
650  unless(hasType(realFloatingPointType())),
651  unless(hasEitherOperand(hasType(realFloatingPointType()))),
652  unless(hasLHS(AnyLiteralExpr)),
653  unless(hasDescendant(BannedIntegerLiteral)))
654  .bind("binary"),
655  this);
656 
657  // Conditional (trenary) operator with equivalent operands, like (Y ? X : X).
658  Finder->addMatcher(conditionalOperator(expressionsAreEquivalent(),
659  // Filter noisy false positives.
660  unless(conditionalOperatorIsInMacro()),
661  unless(isInTemplateInstantiation()))
662  .bind("cond"),
663  this);
664 
665  // Overloaded operators with equivalent operands.
666  Finder->addMatcher(
667  cxxOperatorCallExpr(
668  anyOf(
669  hasOverloadedOperatorName("-"), hasOverloadedOperatorName("/"),
670  hasOverloadedOperatorName("%"), hasOverloadedOperatorName("|"),
671  hasOverloadedOperatorName("&"), hasOverloadedOperatorName("^"),
672  hasOverloadedOperatorName("=="), hasOverloadedOperatorName("!="),
673  hasOverloadedOperatorName("<"), hasOverloadedOperatorName("<="),
674  hasOverloadedOperatorName(">"), hasOverloadedOperatorName(">="),
675  hasOverloadedOperatorName("&&"), hasOverloadedOperatorName("||"),
676  hasOverloadedOperatorName("=")),
677  parametersAreEquivalent(),
678  // Filter noisy false positives.
679  unless(isMacro()), unless(isInTemplateInstantiation()))
680  .bind("call"),
681  this);
682 
683  // Match expressions like: !(1 | 2 | 3)
684  Finder->addMatcher(
685  implicitCastExpr(
686  hasImplicitDestinationType(isInteger()),
687  has(unaryOperator(
688  hasOperatorName("!"),
689  hasUnaryOperand(ignoringParenImpCasts(binaryOperator(
690  anyOf(hasOperatorName("|"), hasOperatorName("&")),
691  hasLHS(anyOf(binaryOperator(anyOf(hasOperatorName("|"),
692  hasOperatorName("&"))),
693  integerLiteral())),
694  hasRHS(integerLiteral())))))
695  .bind("logical-bitwise-confusion"))),
696  this);
697 
698  // Match expressions like: (X << 8) & 0xFF
699  Finder->addMatcher(
700  binaryOperator(hasOperatorName("&"),
701  hasEitherOperand(ignoringParenImpCasts(binaryOperator(
702  hasOperatorName("<<"),
703  hasRHS(ignoringParenImpCasts(
704  integerLiteral().bind("shift-const")))))),
705  hasEitherOperand(ignoringParenImpCasts(
706  integerLiteral().bind("and-const"))))
707  .bind("left-right-shift-confusion"),
708  this);
709 
710  // Match common expressions and apply more checks to find redundant
711  // sub-expressions.
712  // a) Expr <op> K1 == K2
713  // b) Expr <op> K1 == Expr
714  // c) Expr <op> K1 == Expr <op> K2
715  // see: 'checkArithmeticExpr' and 'checkBitwiseExpr'
716  const auto BinOpCstLeft = matchBinOpIntegerConstantExpr("lhs");
717  const auto BinOpCstRight = matchBinOpIntegerConstantExpr("rhs");
718  const auto CstRight = matchIntegerConstantExpr("rhs");
719  const auto SymRight = matchSymbolicExpr("rhs");
720 
721  // Match expressions like: x <op> 0xFF == 0xF00.
722  Finder->addMatcher(binaryOperator(isComparisonOperator(),
723  hasEitherOperand(BinOpCstLeft),
724  hasEitherOperand(CstRight))
725  .bind("binop-const-compare-to-const"),
726  this);
727 
728  // Match expressions like: x <op> 0xFF == x.
729  Finder->addMatcher(
730  binaryOperator(isComparisonOperator(),
731  anyOf(allOf(hasLHS(BinOpCstLeft), hasRHS(SymRight)),
732  allOf(hasLHS(SymRight), hasRHS(BinOpCstLeft))))
733  .bind("binop-const-compare-to-sym"),
734  this);
735 
736  // Match expressions like: x <op> 10 == x <op> 12.
737  Finder->addMatcher(binaryOperator(isComparisonOperator(),
738  hasLHS(BinOpCstLeft), hasRHS(BinOpCstRight),
739  // Already reported as redundant.
740  unless(operandsAreEquivalent()))
741  .bind("binop-const-compare-to-binop-const"),
742  this);
743 
744  // Match relational expressions combined with logical operators and find
745  // redundant sub-expressions.
746  // see: 'checkRelationalExpr'
747 
748  // Match expressions like: x < 2 && x > 2.
749  const auto ComparisonLeft = matchRelationalIntegerConstantExpr("lhs");
750  const auto ComparisonRight = matchRelationalIntegerConstantExpr("rhs");
751  Finder->addMatcher(
752  binaryOperator(anyOf(hasOperatorName("||"), hasOperatorName("&&")),
753  hasLHS(ComparisonLeft), hasRHS(ComparisonRight),
754  // Already reported as redundant.
755  unless(operandsAreEquivalent()))
756  .bind("comparisons-of-symbol-and-const"),
757  this);
758 }
759 
760 void RedundantExpressionCheck::checkArithmeticExpr(
761  const MatchFinder::MatchResult &Result) {
762  APSInt LhsValue, RhsValue;
763  const Expr *LhsSymbol = nullptr, *RhsSymbol = nullptr;
764  BinaryOperatorKind LhsOpcode, RhsOpcode;
765 
766  if (const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
767  "binop-const-compare-to-sym")) {
768  BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
769  if (!retrieveBinOpIntegerConstantExpr(Result, "lhs", LhsOpcode, LhsSymbol,
770  LhsValue) ||
771  !retrieveSymbolicExpr(Result, "rhs", RhsSymbol) ||
772  !areEquivalentExpr(LhsSymbol, RhsSymbol))
773  return;
774 
775  // Check expressions: x + k == x or x - k == x.
776  if (LhsOpcode == BO_Add || LhsOpcode == BO_Sub) {
777  if ((LhsValue != 0 && Opcode == BO_EQ) ||
778  (LhsValue == 0 && Opcode == BO_NE))
779  diag(ComparisonOperator->getOperatorLoc(),
780  "logical expression is always false");
781  else if ((LhsValue == 0 && Opcode == BO_EQ) ||
782  (LhsValue != 0 && Opcode == BO_NE))
783  diag(ComparisonOperator->getOperatorLoc(),
784  "logical expression is always true");
785  }
786  } else if (const auto *ComparisonOperator =
787  Result.Nodes.getNodeAs<BinaryOperator>(
788  "binop-const-compare-to-binop-const")) {
789  BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
790 
791  if (!retrieveBinOpIntegerConstantExpr(Result, "lhs", LhsOpcode, LhsSymbol,
792  LhsValue) ||
793  !retrieveBinOpIntegerConstantExpr(Result, "rhs", RhsOpcode, RhsSymbol,
794  RhsValue) ||
795  !areEquivalentExpr(LhsSymbol, RhsSymbol))
796  return;
797 
798  transformSubToCanonicalAddExpr(LhsOpcode, LhsValue);
799  transformSubToCanonicalAddExpr(RhsOpcode, RhsValue);
800 
801  // Check expressions: x + 1 == x + 2 or x + 1 != x + 2.
802  if (LhsOpcode == BO_Add && RhsOpcode == BO_Add) {
803  if ((Opcode == BO_EQ && APSInt::compareValues(LhsValue, RhsValue) == 0) ||
804  (Opcode == BO_NE && APSInt::compareValues(LhsValue, RhsValue) != 0)) {
805  diag(ComparisonOperator->getOperatorLoc(),
806  "logical expression is always true");
807  } else if ((Opcode == BO_EQ &&
808  APSInt::compareValues(LhsValue, RhsValue) != 0) ||
809  (Opcode == BO_NE &&
810  APSInt::compareValues(LhsValue, RhsValue) == 0)) {
811  diag(ComparisonOperator->getOperatorLoc(),
812  "logical expression is always false");
813  }
814  }
815  }
816 }
817 
818 static bool exprEvaluatesToZero(BinaryOperatorKind Opcode, APSInt Value) {
819  return (Opcode == BO_And || Opcode == BO_AndAssign) && Value == 0;
820 }
821 
822 static bool exprEvaluatesToBitwiseNegatedZero(BinaryOperatorKind Opcode,
823  APSInt Value) {
824  return (Opcode == BO_Or || Opcode == BO_OrAssign) && ~Value == 0;
825 }
826 
827 static bool exprEvaluatesToSymbolic(BinaryOperatorKind Opcode, APSInt Value) {
828  return ((Opcode == BO_Or || Opcode == BO_OrAssign) && Value == 0) ||
829  ((Opcode == BO_And || Opcode == BO_AndAssign) && ~Value == 0);
830 }
831 
832 
833 void RedundantExpressionCheck::checkBitwiseExpr(
834  const MatchFinder::MatchResult &Result) {
835  if (const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
836  "binop-const-compare-to-const")) {
837  BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
838 
839  APSInt LhsValue, RhsValue;
840  const Expr *LhsSymbol = nullptr;
841  BinaryOperatorKind LhsOpcode;
842  if (!retrieveBinOpIntegerConstantExpr(Result, "lhs", LhsOpcode, LhsSymbol,
843  LhsValue) ||
844  !retrieveIntegerConstantExpr(Result, "rhs", RhsValue))
845  return;
846 
847  uint64_t LhsConstant = LhsValue.getZExtValue();
848  uint64_t RhsConstant = RhsValue.getZExtValue();
849  SourceLocation Loc = ComparisonOperator->getOperatorLoc();
850 
851  // Check expression: x & k1 == k2 (i.e. x & 0xFF == 0xF00)
852  if (LhsOpcode == BO_And && (LhsConstant & RhsConstant) != RhsConstant) {
853  if (Opcode == BO_EQ)
854  diag(Loc, "logical expression is always false");
855  else if (Opcode == BO_NE)
856  diag(Loc, "logical expression is always true");
857  }
858 
859  // Check expression: x | k1 == k2 (i.e. x | 0xFF == 0xF00)
860  if (LhsOpcode == BO_Or && (LhsConstant | RhsConstant) != RhsConstant) {
861  if (Opcode == BO_EQ)
862  diag(Loc, "logical expression is always false");
863  else if (Opcode == BO_NE)
864  diag(Loc, "logical expression is always true");
865  }
866  } else if (const auto *IneffectiveOperator =
867  Result.Nodes.getNodeAs<BinaryOperator>(
868  "ineffective-bitwise")) {
869  APSInt Value;
870  const Expr *Sym = nullptr, *ConstExpr = nullptr;
871 
872  if (!retrieveSymbolicExpr(Result, "ineffective-bitwise", Sym) ||
873  !retrieveIntegerConstantExpr(Result, "ineffective-bitwise", Value,
874  ConstExpr))
875  return;
876 
877  if((Value != 0 && ~Value != 0) || Sym->getExprLoc().isMacroID())
878  return;
879 
880  SourceLocation Loc = IneffectiveOperator->getOperatorLoc();
881 
882  BinaryOperatorKind Opcode = IneffectiveOperator->getOpcode();
883  if (exprEvaluatesToZero(Opcode, Value)) {
884  diag(Loc, "expression always evaluates to 0");
885  } else if (exprEvaluatesToBitwiseNegatedZero(Opcode, Value)) {
886  SourceRange ConstExprRange(ConstExpr->getBeginLoc(),
887  ConstExpr->getEndLoc());
888  StringRef ConstExprText = Lexer::getSourceText(
889  CharSourceRange::getTokenRange(ConstExprRange), *Result.SourceManager,
890  Result.Context->getLangOpts());
891 
892  diag(Loc, "expression always evaluates to '%0'") << ConstExprText;
893 
894  } else if (exprEvaluatesToSymbolic(Opcode, Value)) {
895  SourceRange SymExprRange(Sym->getBeginLoc(), Sym->getEndLoc());
896 
897  StringRef ExprText = Lexer::getSourceText(
898  CharSourceRange::getTokenRange(SymExprRange), *Result.SourceManager,
899  Result.Context->getLangOpts());
900 
901  diag(Loc, "expression always evaluates to '%0'") << ExprText;
902  }
903  }
904 }
905 
906 void RedundantExpressionCheck::checkRelationalExpr(
907  const MatchFinder::MatchResult &Result) {
908  if (const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
909  "comparisons-of-symbol-and-const")) {
910  // Matched expressions are: (x <op> k1) <REL> (x <op> k2).
911  // E.g.: (X < 2) && (X > 4)
912  BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
913 
914  const Expr *LhsExpr = nullptr, *RhsExpr = nullptr;
915  const Expr *LhsSymbol = nullptr, *RhsSymbol = nullptr;
916  const Expr *LhsConst = nullptr, *RhsConst = nullptr;
917  BinaryOperatorKind LhsOpcode, RhsOpcode;
918  APSInt LhsValue, RhsValue;
919 
920  if (!retrieveRelationalIntegerConstantExpr(
921  Result, "lhs", LhsExpr, LhsOpcode, LhsSymbol, LhsValue, LhsConst) ||
922  !retrieveRelationalIntegerConstantExpr(
923  Result, "rhs", RhsExpr, RhsOpcode, RhsSymbol, RhsValue, RhsConst) ||
924  !areEquivalentExpr(LhsSymbol, RhsSymbol))
925  return;
926 
927  // Bring expr to a canonical form: smallest constant must be on the left.
928  if (APSInt::compareValues(LhsValue, RhsValue) > 0) {
929  std::swap(LhsExpr, RhsExpr);
930  std::swap(LhsValue, RhsValue);
931  std::swap(LhsSymbol, RhsSymbol);
932  std::swap(LhsOpcode, RhsOpcode);
933  }
934 
935  // Constants come from two different macros, or one of them is a macro.
936  if (areExprsFromDifferentMacros(LhsConst, RhsConst, Result.Context) ||
937  areExprsMacroAndNonMacro(LhsConst, RhsConst))
938  return;
939 
940  if ((Opcode == BO_LAnd || Opcode == BO_LOr) &&
941  areEquivalentRanges(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
942  diag(ComparisonOperator->getOperatorLoc(),
943  "equivalent expression on both sides of logical operator");
944  return;
945  }
946 
947  if (Opcode == BO_LAnd) {
948  if (areExclusiveRanges(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
949  diag(ComparisonOperator->getOperatorLoc(),
950  "logical expression is always false");
951  } else if (rangeSubsumesRange(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
952  diag(LhsExpr->getExprLoc(), "expression is redundant");
953  } else if (rangeSubsumesRange(RhsOpcode, RhsValue, LhsOpcode, LhsValue)) {
954  diag(RhsExpr->getExprLoc(), "expression is redundant");
955  }
956  }
957 
958  if (Opcode == BO_LOr) {
959  if (rangesFullyCoverDomain(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
960  diag(ComparisonOperator->getOperatorLoc(),
961  "logical expression is always true");
962  } else if (rangeSubsumesRange(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
963  diag(RhsExpr->getExprLoc(), "expression is redundant");
964  } else if (rangeSubsumesRange(RhsOpcode, RhsValue, LhsOpcode, LhsValue)) {
965  diag(LhsExpr->getExprLoc(), "expression is redundant");
966  }
967  }
968  }
969 }
970 
971 void RedundantExpressionCheck::check(const MatchFinder::MatchResult &Result) {
972  if (const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>("binary")) {
973  // If the expression's constants are macros, check whether they are
974  // intentional.
975  if (areSidesBinaryConstExpressions(BinOp, Result.Context)) {
976  const Expr *LhsConst = nullptr, *RhsConst = nullptr;
977  BinaryOperatorKind MainOpcode, SideOpcode;
978 
979  if (!retrieveConstExprFromBothSides(BinOp, MainOpcode, SideOpcode,
980  LhsConst, RhsConst, Result.Context))
981  return;
982 
983  if (areExprsFromDifferentMacros(LhsConst, RhsConst, Result.Context) ||
984  areExprsMacroAndNonMacro(LhsConst, RhsConst))
985  return;
986  }
987 
988  diag(BinOp->getOperatorLoc(), "both sides of operator are equivalent");
989  }
990 
991  if (const auto *CondOp =
992  Result.Nodes.getNodeAs<ConditionalOperator>("cond")) {
993  const Expr *TrueExpr = CondOp->getTrueExpr();
994  const Expr *FalseExpr = CondOp->getFalseExpr();
995 
996  if (areExprsFromDifferentMacros(TrueExpr, FalseExpr, Result.Context) ||
997  areExprsMacroAndNonMacro(TrueExpr, FalseExpr))
998  return;
999  diag(CondOp->getColonLoc(),
1000  "'true' and 'false' expressions are equivalent");
1001  }
1002 
1003  if (const auto *Call = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("call")) {
1004  const auto *OverloadedFunctionDecl = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1005  if (!OverloadedFunctionDecl)
1006  return;
1007 
1008  if (canOverloadedOperatorArgsBeModified(OverloadedFunctionDecl, true))
1009  return;
1010 
1011  diag(Call->getOperatorLoc(),
1012  "both sides of overloaded operator are equivalent");
1013  }
1014 
1015  if (const auto *NegateOperator =
1016  Result.Nodes.getNodeAs<UnaryOperator>("logical-bitwise-confusion")) {
1017  SourceLocation OperatorLoc = NegateOperator->getOperatorLoc();
1018 
1019  auto Diag =
1020  diag(OperatorLoc,
1021  "ineffective logical negation operator used; did you mean '~'?");
1022  SourceLocation LogicalNotLocation = OperatorLoc.getLocWithOffset(1);
1023 
1024  if (!LogicalNotLocation.isMacroID())
1025  Diag << FixItHint::CreateReplacement(
1026  CharSourceRange::getCharRange(OperatorLoc, LogicalNotLocation), "~");
1027  }
1028 
1029  if (const auto *BinaryAndExpr = Result.Nodes.getNodeAs<BinaryOperator>(
1030  "left-right-shift-confusion")) {
1031  const auto *ShiftingConst = Result.Nodes.getNodeAs<Expr>("shift-const");
1032  assert(ShiftingConst && "Expr* 'ShiftingConst' is nullptr!");
1033  APSInt ShiftingValue;
1034 
1035  if (!ShiftingConst->isIntegerConstantExpr(ShiftingValue, *Result.Context))
1036  return;
1037 
1038  const auto *AndConst = Result.Nodes.getNodeAs<Expr>("and-const");
1039  assert(AndConst && "Expr* 'AndCont' is nullptr!");
1040  APSInt AndValue;
1041  if (!AndConst->isIntegerConstantExpr(AndValue, *Result.Context))
1042  return;
1043 
1044  // If ShiftingConst is shifted left with more bits than the position of the
1045  // leftmost 1 in the bit representation of AndValue, AndConstant is
1046  // ineffective.
1047  if (AndValue.getActiveBits() > ShiftingValue)
1048  return;
1049 
1050  auto Diag = diag(BinaryAndExpr->getOperatorLoc(),
1051  "ineffective bitwise and operation");
1052  }
1053 
1054  // Check for the following bound expressions:
1055  // - "binop-const-compare-to-sym",
1056  // - "binop-const-compare-to-binop-const",
1057  // Produced message:
1058  // -> "logical expression is always false/true"
1059  checkArithmeticExpr(Result);
1060 
1061  // Check for the following bound expression:
1062  // - "binop-const-compare-to-const",
1063  // - "ineffective-bitwise"
1064  // Produced message:
1065  // -> "logical expression is always false/true"
1066  // -> "expression always evaluates to ..."
1067  checkBitwiseExpr(Result);
1068 
1069  // Check for te following bound expression:
1070  // - "comparisons-of-symbol-and-const",
1071  // Produced messages:
1072  // -> "equivalent expression on both sides of logical operator",
1073  // -> "logical expression is always false/true"
1074  // -> "expression is redundant"
1075  checkRelationalExpr(Result);
1076 }
1077 
1078 } // namespace misc
1079 } // namespace tidy
1080 } // namespace clang
SourceLocation Loc
&#39;#&#39; location in the include directive
static bool exprEvaluatesToZero(BinaryOperatorKind Opcode, APSInt Value)
static bool exprEvaluatesToSymbolic(BinaryOperatorKind Opcode, APSInt Value)
static bool exprEvaluatesToBitwiseNegatedZero(BinaryOperatorKind Opcode, APSInt Value)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
AST_MATCHER_P(NamedDecl, matchesAnyListedName, std::vector< std::string >, NameList)
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: Rename.cpp:25