clang-tools 24.0.0git
RedundantExpressionCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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 "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Basic/LLVM.h"
14#include "clang/Basic/SourceLocation.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Lex/Lexer.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/APSInt.h"
19#include "llvm/ADT/SmallBitVector.h"
20#include "llvm/Support/FormatVariadic.h"
21#include "llvm/Support/raw_ostream.h"
22#include <algorithm>
23#include <cassert>
24#include <cstdint>
25#include <optional>
26#include <string>
27
28using namespace clang::ast_matchers;
29using namespace clang::tidy::matchers;
30
31namespace clang::tidy::misc {
32using llvm::APSInt;
33
34static constexpr StringRef KnownBannedMacroNames[] = {
35 "EAGAIN",
36 "EWOULDBLOCK",
37 "SIGCLD",
38 "SIGCHLD",
39};
40
41static bool incrementWithoutOverflow(const APSInt &Value, APSInt &Result) {
42 Result = Value;
43 ++Result;
44 return Value < Result;
45}
46
47static bool areEquivalentDeclRefExpr(const DeclRefExpr *L,
48 const DeclRefExpr *R) {
49 if (L->getDecl() != R->getDecl())
50 return false;
51
52 const PrintingPolicy &Policy =
53 L->getDecl()->getASTContext().getPrintingPolicy();
54
55 if (L->hasQualifier() && R->hasQualifier()) {
56 std::string LQual, RQual;
57 llvm::raw_string_ostream LOS(LQual), ROS(RQual);
58 L->getQualifier().print(LOS, Policy);
59 R->getQualifier().print(ROS, Policy);
60 if (LQual != RQual)
61 return false;
62 }
63
64 if (L->hasExplicitTemplateArgs() != R->hasExplicitTemplateArgs())
65 return false;
66 if (L->hasExplicitTemplateArgs()) {
67 if (L->getNumTemplateArgs() != R->getNumTemplateArgs())
68 return false;
69
70 return llvm::equal(L->template_arguments(), R->template_arguments(),
71 [&Policy](const TemplateArgumentLoc &LArg,
72 const TemplateArgumentLoc &RArg) {
73 std::string LStr, RStr;
74 llvm::raw_string_ostream LOS(LStr), ROS(RStr);
75 LArg.getArgument().print(Policy, LOS, true);
76 RArg.getArgument().print(Policy, ROS, true);
77 return LStr == RStr;
78 });
79 }
80 return true;
81}
82
83static bool areEquivalentExpr(const Expr *Left, const Expr *Right) {
84 if (!Left || !Right)
85 return !Left && !Right;
86
87 Left = Left->IgnoreParens();
88 Right = Right->IgnoreParens();
89
90 // Compare classes.
91 if (Left->getStmtClass() != Right->getStmtClass())
92 return false;
93
94 // Compare children.
95 Expr::const_child_iterator LeftIter = Left->child_begin();
96 Expr::const_child_iterator RightIter = Right->child_begin();
97 while (LeftIter != Left->child_end() && RightIter != Right->child_end()) {
98 if (!areEquivalentExpr(dyn_cast_or_null<Expr>(*LeftIter),
99 dyn_cast_or_null<Expr>(*RightIter)))
100 return false;
101 ++LeftIter;
102 ++RightIter;
103 }
104 if (LeftIter != Left->child_end() || RightIter != Right->child_end())
105 return false;
106
107 // Perform extra checks.
108 switch (Left->getStmtClass()) {
109 default:
110 return false;
111
112 case Stmt::CharacterLiteralClass:
113 return cast<CharacterLiteral>(Left)->getValue() ==
114 cast<CharacterLiteral>(Right)->getValue();
115 case Stmt::IntegerLiteralClass: {
116 const llvm::APInt LeftLit = cast<IntegerLiteral>(Left)->getValue();
117 const llvm::APInt RightLit = cast<IntegerLiteral>(Right)->getValue();
118 return LeftLit.getBitWidth() == RightLit.getBitWidth() &&
119 LeftLit == RightLit;
120 }
121 case Stmt::FloatingLiteralClass:
122 return cast<FloatingLiteral>(Left)->getValue().bitwiseIsEqual(
123 cast<FloatingLiteral>(Right)->getValue());
124 case Stmt::StringLiteralClass:
125 return cast<StringLiteral>(Left)->getBytes() ==
126 cast<StringLiteral>(Right)->getBytes();
127 case Stmt::CXXOperatorCallExprClass:
128 return cast<CXXOperatorCallExpr>(Left)->getOperator() ==
129 cast<CXXOperatorCallExpr>(Right)->getOperator();
130 case Stmt::DependentScopeDeclRefExprClass:
131 if (cast<DependentScopeDeclRefExpr>(Left)->getDeclName() !=
132 cast<DependentScopeDeclRefExpr>(Right)->getDeclName())
133 return false;
134 return cast<DependentScopeDeclRefExpr>(Left)->getQualifier() ==
135 cast<DependentScopeDeclRefExpr>(Right)->getQualifier();
136 case Stmt::DeclRefExprClass:
137 return areEquivalentDeclRefExpr(cast<DeclRefExpr>(Left),
138 cast<DeclRefExpr>(Right));
139 case Stmt::MemberExprClass:
140 return cast<MemberExpr>(Left)->getMemberDecl() ==
141 cast<MemberExpr>(Right)->getMemberDecl();
142 case Stmt::CXXFoldExprClass:
143 return cast<CXXFoldExpr>(Left)->getOperator() ==
144 cast<CXXFoldExpr>(Right)->getOperator();
145 case Stmt::CXXFunctionalCastExprClass:
146 case Stmt::CStyleCastExprClass:
147 return cast<ExplicitCastExpr>(Left)->getTypeAsWritten() ==
148 cast<ExplicitCastExpr>(Right)->getTypeAsWritten();
149 case Stmt::CallExprClass:
150 case Stmt::ImplicitCastExprClass:
151 case Stmt::ArraySubscriptExprClass:
152 return true;
153 case Stmt::UnaryOperatorClass:
154 if (cast<UnaryOperator>(Left)->isIncrementDecrementOp())
155 return false;
156 return cast<UnaryOperator>(Left)->getOpcode() ==
157 cast<UnaryOperator>(Right)->getOpcode();
158 case Stmt::BinaryOperatorClass:
159 if (cast<BinaryOperator>(Left)->isAssignmentOp())
160 return false;
161 return cast<BinaryOperator>(Left)->getOpcode() ==
162 cast<BinaryOperator>(Right)->getOpcode();
163 case Stmt::UnaryExprOrTypeTraitExprClass:
164 const auto *LeftUnaryExpr = cast<UnaryExprOrTypeTraitExpr>(Left);
165 const auto *RightUnaryExpr = cast<UnaryExprOrTypeTraitExpr>(Right);
166 if (LeftUnaryExpr->isArgumentType() && RightUnaryExpr->isArgumentType())
167 return LeftUnaryExpr->getKind() == RightUnaryExpr->getKind() &&
168 LeftUnaryExpr->getArgumentType() ==
169 RightUnaryExpr->getArgumentType();
170 if (!LeftUnaryExpr->isArgumentType() && !RightUnaryExpr->isArgumentType())
171 return areEquivalentExpr(LeftUnaryExpr->getArgumentExpr(),
172 RightUnaryExpr->getArgumentExpr());
173
174 return false;
175 }
176}
177
178// For a given expression 'x', returns whether the ranges covered by the
179// relational operators are equivalent (i.e. x <= 4 is equivalent to x < 5).
180static bool areEquivalentRanges(BinaryOperatorKind OpcodeLHS,
181 const APSInt &ValueLHS,
182 BinaryOperatorKind OpcodeRHS,
183 const APSInt &ValueRHS) {
184 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
185 "Values must be ordered");
186 // Handle the case where constants are the same: x <= 4 <==> x <= 4.
187 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0)
188 return OpcodeLHS == OpcodeRHS;
189
190 // Handle the case where constants are off by one: x <= 4 <==> x < 5.
191 APSInt ValueLhsPlus1;
192 return ((OpcodeLHS == BO_LE && OpcodeRHS == BO_LT) ||
193 (OpcodeLHS == BO_GT && OpcodeRHS == BO_GE)) &&
194 incrementWithoutOverflow(ValueLHS, ValueLhsPlus1) &&
195 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0;
196}
197
198// For a given expression 'x', returns whether the ranges covered by the
199// relational operators are fully disjoint (i.e. x < 4 and x > 7).
200static bool areExclusiveRanges(BinaryOperatorKind OpcodeLHS,
201 const APSInt &ValueLHS,
202 BinaryOperatorKind OpcodeRHS,
203 const APSInt &ValueRHS) {
204 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
205 "Values must be ordered");
206
207 // Handle cases where the constants are the same.
208 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
209 switch (OpcodeLHS) {
210 case BO_EQ:
211 return OpcodeRHS == BO_NE || OpcodeRHS == BO_GT || OpcodeRHS == BO_LT;
212 case BO_NE:
213 return OpcodeRHS == BO_EQ;
214 case BO_LE:
215 return OpcodeRHS == BO_GT;
216 case BO_GE:
217 return OpcodeRHS == BO_LT;
218 case BO_LT:
219 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
220 case BO_GT:
221 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
222 default:
223 return false;
224 }
225 }
226
227 // Handle cases where the constants are different.
228 if ((OpcodeLHS == BO_EQ || OpcodeLHS == BO_LT || OpcodeLHS == BO_LE) &&
229 (OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE))
230 return true;
231
232 // Handle the case where constants are off by one: x > 5 && x < 6.
233 APSInt ValueLhsPlus1;
234 if (OpcodeLHS == BO_GT && OpcodeRHS == BO_LT &&
235 incrementWithoutOverflow(ValueLHS, ValueLhsPlus1) &&
236 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
237 return true;
238
239 return false;
240}
241
242// Returns whether the ranges covered by the union of both relational
243// expressions cover the whole domain (i.e. x < 10 and x > 0).
244static bool rangesFullyCoverDomain(BinaryOperatorKind OpcodeLHS,
245 const APSInt &ValueLHS,
246 BinaryOperatorKind OpcodeRHS,
247 const APSInt &ValueRHS) {
248 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
249 "Values must be ordered");
250
251 // Handle cases where the constants are the same: x < 5 || x >= 5.
252 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
253 switch (OpcodeLHS) {
254 case BO_EQ:
255 return OpcodeRHS == BO_NE;
256 case BO_NE:
257 return OpcodeRHS == BO_EQ;
258 case BO_LE:
259 return OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
260 case BO_LT:
261 return OpcodeRHS == BO_GE;
262 case BO_GE:
263 return OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
264 case BO_GT:
265 return OpcodeRHS == BO_LE;
266 default:
267 return false;
268 }
269 }
270
271 // Handle the case where constants are off by one: x <= 4 || x >= 5.
272 APSInt ValueLhsPlus1;
273 if (OpcodeLHS == BO_LE && OpcodeRHS == BO_GE &&
274 incrementWithoutOverflow(ValueLHS, ValueLhsPlus1) &&
275 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
276 return true;
277
278 // Handle cases where the constants are different: x > 4 || x <= 7.
279 if ((OpcodeLHS == BO_GT || OpcodeLHS == BO_GE) &&
280 (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE))
281 return true;
282
283 // Handle cases where constants are different but both ops are !=, like:
284 // x != 5 || x != 10
285 if (OpcodeLHS == BO_NE && OpcodeRHS == BO_NE)
286 return true;
287
288 return false;
289}
290
291static bool rangeSubsumesRange(BinaryOperatorKind OpcodeLHS,
292 const APSInt &ValueLHS,
293 BinaryOperatorKind OpcodeRHS,
294 const APSInt &ValueRHS) {
295 const int Comparison = APSInt::compareValues(ValueLHS, ValueRHS);
296 switch (OpcodeLHS) {
297 case BO_EQ:
298 return OpcodeRHS == BO_EQ && Comparison == 0;
299 case BO_NE:
300 return (OpcodeRHS == BO_NE && Comparison == 0) ||
301 (OpcodeRHS == BO_EQ && Comparison != 0) ||
302 (OpcodeRHS == BO_LT && Comparison >= 0) ||
303 (OpcodeRHS == BO_LE && Comparison > 0) ||
304 (OpcodeRHS == BO_GT && Comparison <= 0) ||
305 (OpcodeRHS == BO_GE && Comparison < 0);
306
307 case BO_LT:
308 return ((OpcodeRHS == BO_LT && Comparison >= 0) ||
309 (OpcodeRHS == BO_LE && Comparison > 0) ||
310 (OpcodeRHS == BO_EQ && Comparison > 0));
311 case BO_GT:
312 return ((OpcodeRHS == BO_GT && Comparison <= 0) ||
313 (OpcodeRHS == BO_GE && Comparison < 0) ||
314 (OpcodeRHS == BO_EQ && Comparison < 0));
315 case BO_LE:
316 return (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE || OpcodeRHS == BO_EQ) &&
317 Comparison >= 0;
318 case BO_GE:
319 return (OpcodeRHS == BO_GT || OpcodeRHS == BO_GE || OpcodeRHS == BO_EQ) &&
320 Comparison <= 0;
321 default:
322 return false;
323 }
324}
325
326static void transformSubToCanonicalAddExpr(BinaryOperatorKind &Opcode,
327 APSInt &Value) {
328 if (Opcode == BO_Sub) {
329 Opcode = BO_Add;
330 Value = -Value;
331 }
332}
333
334// to use in the template below
335static OverloadedOperatorKind getOp(const BinaryOperator *Op) {
336 return BinaryOperator::getOverloadedOperator(Op->getOpcode());
337}
338
339static OverloadedOperatorKind getOp(const CXXOperatorCallExpr *Op) {
340 if (Op->getNumArgs() != 2)
341 return OO_None;
342 return Op->getOperator();
343}
344
345static std::pair<const Expr *, const Expr *>
346getOperands(const BinaryOperator *Op) {
347 return {Op->getLHS()->IgnoreParenImpCasts(),
348 Op->getRHS()->IgnoreParenImpCasts()};
349}
350
351static std::pair<const Expr *, const Expr *>
352getOperands(const CXXOperatorCallExpr *Op) {
353 return {Op->getArg(0)->IgnoreParenImpCasts(),
354 Op->getArg(1)->IgnoreParenImpCasts()};
355}
356
357template <typename TExpr>
358static const TExpr *checkOpKind(const Expr *TheExpr,
359 OverloadedOperatorKind OpKind) {
360 const auto *AsTExpr = dyn_cast_or_null<TExpr>(TheExpr);
361 if (AsTExpr && getOp(AsTExpr) == OpKind)
362 return AsTExpr;
363
364 return nullptr;
365}
366
367// returns true if a subexpression has two directly equivalent operands and
368// is already handled by operands/parametersAreEquivalent
369template <typename TExpr, unsigned N>
370static bool collectOperands(const Expr *Part,
371 SmallVector<const Expr *, N> &AllOperands,
372 OverloadedOperatorKind OpKind) {
373 if (const auto *BinOp = checkOpKind<TExpr>(Part, OpKind)) {
374 const std::pair<const Expr *, const Expr *> Operands = getOperands(BinOp);
375 if (areEquivalentExpr(Operands.first, Operands.second))
376 return true;
377 return collectOperands<TExpr>(Operands.first, AllOperands, OpKind) ||
378 collectOperands<TExpr>(Operands.second, AllOperands, OpKind);
379 }
380
381 AllOperands.push_back(Part);
382 return false;
383}
384
385template <typename TExpr>
386static bool hasSameOperatorParent(const Expr *TheExpr,
387 OverloadedOperatorKind OpKind,
388 ASTContext &Context) {
389 // IgnoreParenImpCasts logic in reverse: skip surrounding uninteresting nodes
390 const DynTypedNodeList Parents = Context.getParents(*TheExpr);
391 for (const DynTypedNode DynParent : Parents) {
392 if (const auto *Parent = DynParent.get<Expr>()) {
393 const bool Skip =
394 isa<ParenExpr>(Parent) || isa<ImplicitCastExpr>(Parent) ||
395 isa<FullExpr>(Parent) || isa<MaterializeTemporaryExpr>(Parent);
396 if (Skip && hasSameOperatorParent<TExpr>(Parent, OpKind, Context))
397 return true;
398 if (checkOpKind<TExpr>(Parent, OpKind))
399 return true;
400 }
401 }
402
403 return false;
404}
405
406static bool isSameRawIdentifierToken(const Token &T1, const Token &T2,
407 const SourceManager &SM) {
408 if (T1.getKind() != T2.getKind())
409 return false;
410 if (T1.isNot(tok::raw_identifier))
411 return true;
412 if (T1.getLength() != T2.getLength())
413 return false;
414 return StringRef(SM.getCharacterData(T1.getLocation()), T1.getLength()) ==
415 StringRef(SM.getCharacterData(T2.getLocation()), T2.getLength());
416}
417
418static bool isTokAtEndOfExpr(SourceRange ExprSR, Token T,
419 const SourceManager &SM) {
420 return SM.getExpansionLoc(ExprSR.getEnd()) == T.getLocation();
421}
422
423/// Returns true if both LhsExpr and RhsExpr are
424/// macro expressions and they are expanded
425/// from different macros.
426static bool areExprsFromDifferentMacros(const Expr *LhsExpr,
427 const Expr *RhsExpr,
428 const ASTContext *AstCtx) {
429 if (!LhsExpr || !RhsExpr)
430 return false;
431 const SourceRange Lsr = LhsExpr->getSourceRange();
432 const SourceRange Rsr = RhsExpr->getSourceRange();
433 if (!Lsr.getBegin().isMacroID() || !Rsr.getBegin().isMacroID())
434 return false;
435
436 const SourceManager &SM = AstCtx->getSourceManager();
437 const LangOptions &LO = AstCtx->getLangOpts();
438
439 const std::pair<FileID, unsigned> LsrLocInfo =
440 SM.getDecomposedLoc(SM.getExpansionLoc(Lsr.getBegin()));
441 const std::pair<FileID, unsigned> RsrLocInfo =
442 SM.getDecomposedLoc(SM.getExpansionLoc(Rsr.getBegin()));
443 const llvm::MemoryBufferRef MB = SM.getBufferOrFake(LsrLocInfo.first);
444
445 const char *LTokenPos = MB.getBufferStart() + LsrLocInfo.second;
446 const char *RTokenPos = MB.getBufferStart() + RsrLocInfo.second;
447 Lexer LRawLex(SM.getLocForStartOfFile(LsrLocInfo.first), LO,
448 MB.getBufferStart(), LTokenPos, MB.getBufferEnd());
449 Lexer RRawLex(SM.getLocForStartOfFile(RsrLocInfo.first), LO,
450 MB.getBufferStart(), RTokenPos, MB.getBufferEnd());
451
452 Token LTok, RTok;
453 do { // Compare the expressions token-by-token.
454 LRawLex.LexFromRawLexer(LTok);
455 RRawLex.LexFromRawLexer(RTok);
456 } while (!LTok.is(tok::eof) && !RTok.is(tok::eof) &&
457 isSameRawIdentifierToken(LTok, RTok, SM) &&
458 !isTokAtEndOfExpr(Lsr, LTok, SM) &&
459 !isTokAtEndOfExpr(Rsr, RTok, SM));
460 return (!isTokAtEndOfExpr(Lsr, LTok, SM) ||
461 !isTokAtEndOfExpr(Rsr, RTok, SM)) ||
462 !isSameRawIdentifierToken(LTok, RTok, SM);
463}
464
465static bool areExprsMacroAndNonMacro(const Expr *&LhsExpr,
466 const Expr *&RhsExpr) {
467 if (!LhsExpr || !RhsExpr)
468 return false;
469
470 const SourceLocation LhsLoc = LhsExpr->getExprLoc();
471 const SourceLocation RhsLoc = RhsExpr->getExprLoc();
472
473 return LhsLoc.isMacroID() != RhsLoc.isMacroID();
474}
475
476template <typename TExpr>
477static bool
478markDuplicateOperands(const TExpr *TheExpr,
479 ast_matchers::internal::BoundNodesTreeBuilder *Builder,
480 ASTContext &Context) {
481 const OverloadedOperatorKind OpKind = getOp(TheExpr);
482 if (OpKind == OO_None)
483 return false;
484 // if there are no nested operators of the same kind, it's handled by
485 // operands/parametersAreEquivalent
486 const std::pair<const Expr *, const Expr *> Operands = getOperands(TheExpr);
487 if (!(checkOpKind<TExpr>(Operands.first, OpKind) ||
488 checkOpKind<TExpr>(Operands.second, OpKind)))
489 return false;
490
491 // if parent is the same kind of operator, it's handled by a previous call to
492 // markDuplicateOperands
493 if (hasSameOperatorParent<TExpr>(TheExpr, OpKind, Context))
494 return false;
495
497 if (collectOperands<TExpr>(Operands.first, AllOperands, OpKind))
498 return false;
499 if (collectOperands<TExpr>(Operands.second, AllOperands, OpKind))
500 return false;
501 const size_t NumOperands = AllOperands.size();
502 llvm::SmallBitVector Duplicates(NumOperands);
503 for (size_t I = 0; I < NumOperands; I++) {
504 if (Duplicates[I])
505 continue;
506 bool FoundDuplicates = false;
507
508 for (size_t J = I + 1; J < NumOperands; J++) {
509 if (AllOperands[J]->HasSideEffects(Context))
510 break;
511
512 const Expr *Lhs = AllOperands[I];
513 const Expr *Rhs = AllOperands[J];
514 if (!areEquivalentExpr(Lhs, Rhs) ||
515 areExprsFromDifferentMacros(Lhs, Rhs, &Context) ||
516 areExprsMacroAndNonMacro(Lhs, Rhs))
517 continue;
518
519 FoundDuplicates = true;
520 Duplicates.set(J);
521 Builder->setBinding(SmallString<11>(llvm::formatv("duplicate{0}", J)),
522 DynTypedNode::create(*Rhs));
523 }
524
525 if (FoundDuplicates)
526 Builder->setBinding(SmallString<11>(llvm::formatv("duplicate{0}", I)),
527 DynTypedNode::create(*AllOperands[I]));
528 }
529
530 return Duplicates.any();
531}
532
533namespace {
534
535AST_MATCHER(Expr, isIntegerConstantExpr) {
536 if (Node.isInstantiationDependent())
537 return false;
538 return Node.isIntegerConstantExpr(Finder->getASTContext());
539}
540
541AST_MATCHER(BinaryOperator, operandsAreEquivalent) {
542 return areEquivalentExpr(Node.getLHS(), Node.getRHS());
543}
544
545AST_MATCHER(BinaryOperator, nestedOperandsAreEquivalent) {
546 return markDuplicateOperands(&Node, Builder, Finder->getASTContext());
547}
548
549AST_MATCHER(ConditionalOperator, expressionsAreEquivalent) {
550 return areEquivalentExpr(Node.getTrueExpr(), Node.getFalseExpr());
551}
552
553AST_MATCHER(CallExpr, parametersAreEquivalent) {
554 return Node.getNumArgs() == 2 &&
555 areEquivalentExpr(Node.getArg(0), Node.getArg(1));
556}
557
558AST_MATCHER(CXXOperatorCallExpr, nestedParametersAreEquivalent) {
559 return markDuplicateOperands(&Node, Builder, Finder->getASTContext());
560}
561
562AST_MATCHER(BinaryOperator, binaryOperatorIsInMacro) {
563 return Node.getOperatorLoc().isMacroID();
564}
565
566AST_MATCHER(ConditionalOperator, conditionalOperatorIsInMacro) {
567 return Node.getQuestionLoc().isMacroID() || Node.getColonLoc().isMacroID();
568}
569
570AST_MATCHER_P(Expr, expandedByMacro, ArrayRef<StringRef>, Names) {
571 const SourceManager &SM = Finder->getASTContext().getSourceManager();
572 const LangOptions &LO = Finder->getASTContext().getLangOpts();
573 SourceLocation Loc = Node.getExprLoc();
574 while (Loc.isMacroID()) {
575 const StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LO);
576 if (llvm::is_contained(Names, MacroName))
577 return true;
578 Loc = SM.getImmediateMacroCallerLoc(Loc);
579 }
580 return false;
581}
582
583} // namespace
584
585// Returns a matcher for integer constant expressions.
586static ast_matchers::internal::Matcher<Expr>
588 const std::string CstId = (Id + "-const").str();
589 return expr(isIntegerConstantExpr()).bind(CstId);
590}
591
592// Retrieves the integer expression matched by 'matchIntegerConstantExpr' with
593// name 'Id' and stores it into 'ConstExpr', the value of the expression is
594// stored into `Value`.
595static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result,
596 StringRef Id, APSInt &Value,
597 const Expr *&ConstExpr) {
598 const std::string CstId = (Id + "-const").str();
599 ConstExpr = Result.Nodes.getNodeAs<Expr>(CstId);
600 if (!ConstExpr)
601 return false;
602 std::optional<llvm::APSInt> R =
603 ConstExpr->getIntegerConstantExpr(*Result.Context);
604 if (!R)
605 return false;
606 Value = *R;
607 return true;
608}
609
610// Overloaded `retrieveIntegerConstantExpr` for compatibility.
611static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result,
612 StringRef Id, APSInt &Value) {
613 const Expr *ConstExpr = nullptr;
614 return retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr);
615}
616
617// Returns a matcher for symbolic expressions (matches every expression except
618// ingeter constant expressions).
619static ast_matchers::internal::Matcher<Expr> matchSymbolicExpr(StringRef Id) {
620 const std::string SymId = (Id + "-sym").str();
621 return ignoringParenImpCasts(
622 expr(unless(isIntegerConstantExpr())).bind(SymId));
623}
624
625// Retrieves the expression matched by 'matchSymbolicExpr' with name 'Id' and
626// stores it into 'SymExpr'.
627static bool retrieveSymbolicExpr(const MatchFinder::MatchResult &Result,
628 StringRef Id, const Expr *&SymExpr) {
629 const std::string SymId = (Id + "-sym").str();
630 if (const auto *Node = Result.Nodes.getNodeAs<Expr>(SymId)) {
631 SymExpr = Node;
632 return true;
633 }
634 return false;
635}
636
637// Match a binary operator between a symbolic expression and an integer constant
638// expression.
639static ast_matchers::internal::Matcher<Expr>
641 const auto BinOpCstExpr =
642 expr(anyOf(binaryOperator(hasAnyOperatorName("+", "|", "&"),
643 hasOperands(matchSymbolicExpr(Id),
645 binaryOperator(hasOperatorName("-"),
646 hasLHS(matchSymbolicExpr(Id)),
647 hasRHS(matchIntegerConstantExpr(Id)))))
648 .bind(Id);
649 return ignoringParenImpCasts(BinOpCstExpr);
650}
651
652// Retrieves sub-expressions matched by 'matchBinOpIntegerConstantExpr' with
653// name 'Id'.
654static bool
655retrieveBinOpIntegerConstantExpr(const MatchFinder::MatchResult &Result,
656 StringRef Id, BinaryOperatorKind &Opcode,
657 const Expr *&Symbol, APSInt &Value) {
658 if (const auto *BinExpr = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
659 Opcode = BinExpr->getOpcode();
660 return retrieveSymbolicExpr(Result, Id, Symbol) &&
661 retrieveIntegerConstantExpr(Result, Id, Value);
662 }
663 return false;
664}
665
666// Matches relational expressions: 'Expr <op> k' (i.e. x < 2, x != 3, 12 <= x).
667static ast_matchers::internal::Matcher<Expr>
669 const std::string CastId = (Id + "-cast").str();
670 const std::string SwapId = (Id + "-swap").str();
671 const std::string NegateId = (Id + "-negate").str();
672 const std::string OverloadId = (Id + "-overload").str();
673 const std::string ConstId = (Id + "-const").str();
674
675 const auto RelationalExpr = ignoringParenImpCasts(binaryOperator(
676 isComparisonOperator(), expr().bind(Id),
677 anyOf(allOf(hasLHS(matchSymbolicExpr(Id)),
678 hasRHS(matchIntegerConstantExpr(Id))),
679 allOf(hasLHS(matchIntegerConstantExpr(Id)),
680 hasRHS(matchSymbolicExpr(Id)), expr().bind(SwapId)))));
681
682 // A cast can be matched as a comparator to zero. (i.e. if (x) is equivalent
683 // to if (x != 0)).
684 const auto CastExpr =
685 implicitCastExpr(hasCastKind(CK_IntegralToBoolean),
686 hasSourceExpression(matchSymbolicExpr(Id)))
687 .bind(CastId);
688
689 const auto NegateRelationalExpr =
690 unaryOperator(hasOperatorName("!"),
691 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))
692 .bind(NegateId);
693
694 // Do not bind to double negation.
695 const auto NegateNegateRelationalExpr =
696 unaryOperator(hasOperatorName("!"),
697 hasUnaryOperand(unaryOperator(
698 hasOperatorName("!"),
699 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))));
700
701 const auto OverloadedOperatorExpr =
702 cxxOperatorCallExpr(
703 hasAnyOverloadedOperatorName("==", "!=", "<", "<=", ">", ">="),
704 // Filter noisy false positives.
705 unless(isMacroID()), unless(isInTemplateInstantiation()),
706 anyOf(hasLHS(ignoringParenImpCasts(integerLiteral().bind(ConstId))),
707 hasRHS(ignoringParenImpCasts(integerLiteral().bind(ConstId)))))
708 .bind(OverloadId);
709
710 return anyOf(RelationalExpr, CastExpr, NegateRelationalExpr,
711 NegateNegateRelationalExpr, OverloadedOperatorExpr);
712}
713
714// Checks whether a function param is non constant reference type, and may
715// be modified in the function.
716static bool isNonConstReferenceType(QualType ParamType) {
717 return ParamType->isReferenceType() &&
718 !ParamType.getNonReferenceType().isConstQualified();
719}
720
721// Checks whether the arguments of an overloaded operator can be modified in the
722// function.
723// For operators that take an instance and a constant as arguments, only the
724// first argument (the instance) needs to be checked, since the constant itself
725// is a temporary expression. Whether the second parameter is checked is
726// controlled by the parameter `ParamsToCheckCount`.
727static bool
728canOverloadedOperatorArgsBeModified(const CXXOperatorCallExpr *OperatorCall,
729 bool CheckSecondParam) {
730 const auto *OperatorDecl =
731 dyn_cast_or_null<FunctionDecl>(OperatorCall->getCalleeDecl());
732 // if we can't find the declaration, conservatively assume it can modify
733 // arguments
734 if (!OperatorDecl)
735 return true;
736
737 const unsigned ParamCount = OperatorDecl->getNumParams();
738
739 // Overloaded operators declared inside a class have only one param.
740 // These functions must be declared const in order to not be able to modify
741 // the instance of the class they are called through.
742 if (ParamCount == 1 &&
743 !OperatorDecl->getType()->castAs<FunctionType>()->isConst())
744 return true;
745
746 if (isNonConstReferenceType(OperatorDecl->getParamDecl(0)->getType()))
747 return true;
748
749 return CheckSecondParam && ParamCount == 2 &&
750 isNonConstReferenceType(OperatorDecl->getParamDecl(1)->getType());
751}
752
753// Retrieves sub-expressions matched by 'matchRelationalIntegerConstantExpr'
754// with name 'Id'.
756 const MatchFinder::MatchResult &Result, StringRef Id,
757 const Expr *&OperandExpr, BinaryOperatorKind &Opcode, const Expr *&Symbol,
758 APSInt &Value, const Expr *&ConstExpr) {
759 const std::string CastId = (Id + "-cast").str();
760 const std::string SwapId = (Id + "-swap").str();
761 const std::string NegateId = (Id + "-negate").str();
762 const std::string OverloadId = (Id + "-overload").str();
763
764 if (const auto *Bin = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
765 // Operand received with explicit comparator.
766 Opcode = Bin->getOpcode();
767 OperandExpr = Bin;
768
769 if (!retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr))
770 return false;
771 } else if (const auto *Cast = Result.Nodes.getNodeAs<CastExpr>(CastId)) {
772 // Operand received with implicit comparator (cast).
773 Opcode = BO_NE;
774 OperandExpr = Cast;
775 Value = APSInt(32, false);
776 } else if (const auto *OverloadedOperatorExpr =
777 Result.Nodes.getNodeAs<CXXOperatorCallExpr>(OverloadId)) {
778 if (canOverloadedOperatorArgsBeModified(OverloadedOperatorExpr, false))
779 return false;
780
781 bool IntegerConstantIsFirstArg = false;
782
783 if (const auto *Arg = OverloadedOperatorExpr->getArg(1)) {
784 if (!Arg->isValueDependent() &&
785 !Arg->isIntegerConstantExpr(*Result.Context)) {
786 IntegerConstantIsFirstArg = true;
787 if (const auto *Arg = OverloadedOperatorExpr->getArg(0)) {
788 if (!Arg->isValueDependent() &&
789 !Arg->isIntegerConstantExpr(*Result.Context))
790 return false;
791 } else {
792 return false;
793 }
794 }
795 } else {
796 return false;
797 }
798
799 Symbol = OverloadedOperatorExpr->getArg(IntegerConstantIsFirstArg ? 1 : 0);
800 OperandExpr = OverloadedOperatorExpr;
801 Opcode = BinaryOperator::getOverloadedOpcode(
802 OverloadedOperatorExpr->getOperator());
803
804 if (!retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr))
805 return false;
806
807 if (!BinaryOperator::isComparisonOp(Opcode))
808 return false;
809
810 // The call site of this function expects the constant on the RHS,
811 // so change the opcode accordingly.
812 if (IntegerConstantIsFirstArg)
813 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
814
815 return true;
816 } else {
817 return false;
818 }
819
820 if (!retrieveSymbolicExpr(Result, Id, Symbol))
821 return false;
822
823 if (Result.Nodes.getNodeAs<Expr>(SwapId))
824 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
825 if (Result.Nodes.getNodeAs<Expr>(NegateId))
826 Opcode = BinaryOperator::negateComparisonOp(Opcode);
827 return true;
828}
829
830// Checks for expressions like (X == 4) && (Y != 9)
831static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp,
832 const ASTContext *AstCtx) {
833 const auto *LhsBinOp = dyn_cast<BinaryOperator>(BinOp->getLHS());
834 const auto *RhsBinOp = dyn_cast<BinaryOperator>(BinOp->getRHS());
835
836 if (!LhsBinOp || !RhsBinOp)
837 return false;
838
839 const auto IsIntegerConstantExpr = [AstCtx](const Expr *E) {
840 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
841 };
842
843 if ((IsIntegerConstantExpr(LhsBinOp->getLHS()) ||
844 IsIntegerConstantExpr(LhsBinOp->getRHS())) &&
845 (IsIntegerConstantExpr(RhsBinOp->getLHS()) ||
846 IsIntegerConstantExpr(RhsBinOp->getRHS())))
847 return true;
848 return false;
849}
850
852 const BinaryOperator *&BinOp, const ASTContext *AstCtx) {
853 if (areSidesBinaryConstExpressions(BinOp, AstCtx))
854 return true;
855
856 const Expr *Lhs = BinOp->getLHS();
857 const Expr *Rhs = BinOp->getRHS();
858
859 if (!Lhs || !Rhs)
860 return false;
861
862 const auto IsDefineExpr = [AstCtx](const Expr *E) {
863 const SourceRange Lsr = E->getSourceRange();
864 if (!Lsr.getBegin().isMacroID() || E->isValueDependent() ||
865 !E->isIntegerConstantExpr(*AstCtx))
866 return false;
867 return true;
868 };
869
870 return IsDefineExpr(Lhs) || IsDefineExpr(Rhs);
871}
872
873// Retrieves integer constant subexpressions from binary operator expressions
874// that have two equivalent sides.
875// E.g.: from (X == 5) && (X == 5) retrieves 5 and 5.
876static bool retrieveConstExprFromBothSides(const BinaryOperator *&BinOp,
877 BinaryOperatorKind &MainOpcode,
878 BinaryOperatorKind &SideOpcode,
879 const Expr *&LhsConst,
880 const Expr *&RhsConst,
881 const ASTContext *AstCtx) {
882 assert(areSidesBinaryConstExpressions(BinOp, AstCtx) &&
883 "Both sides of binary operator must be constant expressions!");
884
885 MainOpcode = BinOp->getOpcode();
886
887 const auto *BinOpLhs = cast<BinaryOperator>(BinOp->getLHS());
888 const auto *BinOpRhs = cast<BinaryOperator>(BinOp->getRHS());
889
890 const auto IsIntegerConstantExpr = [AstCtx](const Expr *E) {
891 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
892 };
893
894 LhsConst = IsIntegerConstantExpr(BinOpLhs->getLHS()) ? BinOpLhs->getLHS()
895 : BinOpLhs->getRHS();
896 RhsConst = IsIntegerConstantExpr(BinOpRhs->getLHS()) ? BinOpRhs->getLHS()
897 : BinOpRhs->getRHS();
898
899 if (!LhsConst || !RhsConst)
900 return false;
901
902 assert(BinOpLhs->getOpcode() == BinOpRhs->getOpcode() &&
903 "Sides of the binary operator must be equivalent expressions!");
904
905 SideOpcode = BinOpLhs->getOpcode();
906
907 return true;
908}
909
910static bool areStringsSameIgnoreSpaces(const StringRef Left,
911 const StringRef Right) {
912 if (Left == Right)
913 return true;
914
915 // Do running comparison ignoring spaces
916 StringRef L = Left.trim();
917 StringRef R = Right.trim();
918 while (!L.empty() && !R.empty()) {
919 L = L.ltrim();
920 R = R.ltrim();
921 if (L.empty() && R.empty())
922 return true;
923 // If symbol compared are different ==> strings are not the same
924 if (L.front() != R.front())
925 return false;
926 L = L.drop_front();
927 R = R.drop_front();
928 }
929 return L.empty() && R.empty();
930}
931
932static bool areExprsSameMacroOrLiteral(const BinaryOperator *BinOp,
933 const ASTContext *Context) {
934 if (!BinOp)
935 return false;
936
937 const Expr *Lhs = BinOp->getLHS();
938 const Expr *Rhs = BinOp->getRHS();
939 const SourceManager &SM = Context->getSourceManager();
940
941 const SourceRange Lsr = Lhs->getSourceRange();
942 const SourceRange Rsr = Rhs->getSourceRange();
943 if (Lsr.getBegin().isMacroID()) {
944 // Left is macro so right macro too
945 if (Rsr.getBegin().isMacroID()) {
946 // Both sides are macros so they are same macro or literal
947 const StringRef L = Lexer::getSourceText(
948 CharSourceRange::getTokenRange(Lsr), SM, Context->getLangOpts());
949 const StringRef R = Lexer::getSourceText(
950 CharSourceRange::getTokenRange(Rsr), SM, Context->getLangOpts());
951 return areStringsSameIgnoreSpaces(L, R);
952 }
953 // Left is macro but right is not so they are not same macro or literal
954 return false;
955 }
956 const auto *Lil = dyn_cast<IntegerLiteral>(Lhs);
957 const auto *Ril = dyn_cast<IntegerLiteral>(Rhs);
958 if (Lil && Ril)
959 return Lil->getValue() == Ril->getValue();
960
961 const auto *Lbl = dyn_cast<CXXBoolLiteralExpr>(Lhs);
962 const auto *Rbl = dyn_cast<CXXBoolLiteralExpr>(Rhs);
963 if (Lbl && Rbl)
964 return Lbl->getValue() == Rbl->getValue();
965
966 return false;
967}
968
970 const auto BannedIntegerLiteral =
971 integerLiteral(expandedByMacro(KnownBannedMacroNames));
972 const auto IsInUnevaluatedContext = expr(anyOf(
973 hasAncestor(expr(hasUnevaluatedContext())), hasAncestor(typeLoc())));
974
975 // Binary with equivalent operands, like (X != 2 && X != 2).
976 Finder->addMatcher(
977 traverse(TK_AsIs,
978 binaryOperator(anyOf(isComparisonOperator(),
979 hasAnyOperatorName("-", "/", "%", "|", "&",
980 "^", "&&", "||", "=")),
981 operandsAreEquivalent(),
982 // Filter noisy false positives.
983 unless(isInTemplateInstantiation()),
984 unless(binaryOperatorIsInMacro()),
985 unless(hasAncestor(arraySubscriptExpr())),
986 unless(hasDescendant(BannedIntegerLiteral)),
987 unless(IsInUnevaluatedContext))
988 .bind("binary")),
989 this);
990
991 // Logical or bitwise operator with equivalent nested operands, like (X && Y
992 // && X) or (X && (Y && X))
993 Finder->addMatcher(
994 binaryOperator(hasAnyOperatorName("|", "&", "||", "&&", "^"),
995 nestedOperandsAreEquivalent(),
996 // Filter noisy false positives.
997 unless(isInTemplateInstantiation()),
998 unless(binaryOperatorIsInMacro()),
999 // TODO: if the banned macros are themselves duplicated
1000 unless(hasDescendant(BannedIntegerLiteral)),
1001 unless(IsInUnevaluatedContext))
1002 .bind("nested-duplicates"),
1003 this);
1004
1005 // Conditional (ternary) operator with equivalent operands, like (Y ? X : X).
1006 Finder->addMatcher(
1007 traverse(TK_AsIs,
1008 conditionalOperator(expressionsAreEquivalent(),
1009 // Filter noisy false positives.
1010 unless(conditionalOperatorIsInMacro()),
1011 unless(isInTemplateInstantiation()),
1012 unless(IsInUnevaluatedContext))
1013 .bind("cond")),
1014 this);
1015
1016 // Overloaded operators with equivalent operands.
1017 Finder->addMatcher(
1018 traverse(TK_AsIs,
1019 cxxOperatorCallExpr(
1020 hasAnyOverloadedOperatorName("-", "/", "%", "|", "&", "^",
1021 "==", "!=", "<", "<=", ">",
1022 ">=", "&&", "||", "="),
1023 parametersAreEquivalent(),
1024 // Filter noisy false positives.
1025 unless(isMacroID()), unless(isInTemplateInstantiation()),
1026 unless(IsInUnevaluatedContext))
1027 .bind("call")),
1028 this);
1029
1030 // Overloaded operators with equivalent operands.
1031 Finder->addMatcher(
1032 cxxOperatorCallExpr(
1033 hasAnyOverloadedOperatorName("|", "&", "||", "&&", "^"),
1034 nestedParametersAreEquivalent(), argumentCountIs(2),
1035 // Filter noisy false positives.
1036 unless(isMacroID()), unless(isInTemplateInstantiation()),
1037 unless(IsInUnevaluatedContext))
1038 .bind("nested-duplicates"),
1039 this);
1040
1041 // Match expressions like: !(1 | 2 | 3)
1042 Finder->addMatcher(
1043 traverse(TK_AsIs,
1044 implicitCastExpr(
1045 hasImplicitDestinationType(isInteger()),
1046 has(unaryOperator(
1047 hasOperatorName("!"),
1048 hasUnaryOperand(ignoringParenImpCasts(binaryOperator(
1049 hasAnyOperatorName("|", "&"),
1050 hasLHS(anyOf(
1051 binaryOperator(hasAnyOperatorName("|", "&")),
1052 integerLiteral())),
1053 hasRHS(integerLiteral())))))
1054 .bind("logical-bitwise-confusion")),
1055 unless(IsInUnevaluatedContext))),
1056 this);
1057
1058 // Match expressions like: (X << 8) & 0xFF
1059 Finder->addMatcher(
1060 traverse(TK_AsIs,
1061 binaryOperator(
1062 hasOperatorName("&"),
1063 hasOperands(ignoringParenImpCasts(binaryOperator(
1064 hasOperatorName("<<"),
1065 hasRHS(ignoringParenImpCasts(
1066 integerLiteral().bind("shift-const"))))),
1067 ignoringParenImpCasts(
1068 integerLiteral().bind("and-const"))),
1069 unless(IsInUnevaluatedContext))
1070 .bind("left-right-shift-confusion")),
1071 this);
1072
1073 // Match common expressions and apply more checks to find redundant
1074 // sub-expressions.
1075 // a) Expr <op> K1 == K2
1076 // b) Expr <op> K1 == Expr
1077 // c) Expr <op> K1 == Expr <op> K2
1078 // see: 'checkArithmeticExpr' and 'checkBitwiseExpr'
1079 const auto BinOpCstLeft = matchBinOpIntegerConstantExpr("lhs");
1080 const auto BinOpCstRight = matchBinOpIntegerConstantExpr("rhs");
1081 const auto CstRight = matchIntegerConstantExpr("rhs");
1082 const auto SymRight = matchSymbolicExpr("rhs");
1083
1084 // Match expressions like: x <op> 0xFF == 0xF00.
1085 Finder->addMatcher(
1086 traverse(TK_AsIs, binaryOperator(isComparisonOperator(),
1087 hasOperands(BinOpCstLeft, CstRight),
1088 unless(IsInUnevaluatedContext))
1089 .bind("binop-const-compare-to-const")),
1090 this);
1091
1092 // Match expressions like: x <op> 0xFF == x.
1093 Finder->addMatcher(
1094 traverse(
1095 TK_AsIs,
1096 binaryOperator(isComparisonOperator(),
1097 anyOf(allOf(hasLHS(BinOpCstLeft), hasRHS(SymRight)),
1098 allOf(hasLHS(SymRight), hasRHS(BinOpCstLeft))),
1099 unless(IsInUnevaluatedContext))
1100 .bind("binop-const-compare-to-sym")),
1101 this);
1102
1103 // Match expressions like: x <op> 10 == x <op> 12.
1104 Finder->addMatcher(
1105 traverse(TK_AsIs,
1106 binaryOperator(isComparisonOperator(), hasLHS(BinOpCstLeft),
1107 hasRHS(BinOpCstRight),
1108 // Already reported as redundant.
1109 unless(operandsAreEquivalent()),
1110 unless(IsInUnevaluatedContext))
1111 .bind("binop-const-compare-to-binop-const")),
1112 this);
1113
1114 // Match relational expressions combined with logical operators and find
1115 // redundant sub-expressions.
1116 // see: 'checkRelationalExpr'
1117
1118 // Match expressions like: x < 2 && x > 2.
1119 const auto ComparisonLeft = matchRelationalIntegerConstantExpr("lhs");
1120 const auto ComparisonRight = matchRelationalIntegerConstantExpr("rhs");
1121 Finder->addMatcher(
1122 traverse(TK_AsIs,
1123 binaryOperator(hasAnyOperatorName("||", "&&"),
1124 hasLHS(ComparisonLeft), hasRHS(ComparisonRight),
1125 // Already reported as redundant.
1126 unless(operandsAreEquivalent()),
1127 unless(IsInUnevaluatedContext))
1128 .bind("comparisons-of-symbol-and-const")),
1129 this);
1130}
1131
1132void RedundantExpressionCheck::checkArithmeticExpr(
1133 const MatchFinder::MatchResult &Result) {
1134 APSInt LhsValue, RhsValue;
1135 const Expr *LhsSymbol = nullptr, *RhsSymbol = nullptr;
1136 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1137
1138 if (const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1139 "binop-const-compare-to-sym")) {
1140 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1141 if (!retrieveBinOpIntegerConstantExpr(Result, "lhs", LhsOpcode, LhsSymbol,
1142 LhsValue) ||
1143 !retrieveSymbolicExpr(Result, "rhs", RhsSymbol) ||
1144 !areEquivalentExpr(LhsSymbol, RhsSymbol))
1145 return;
1146
1147 // Check expressions: x + k == x or x - k == x.
1148 if (LhsOpcode == BO_Add || LhsOpcode == BO_Sub) {
1149 if ((LhsValue != 0 && Opcode == BO_EQ) ||
1150 (LhsValue == 0 && Opcode == BO_NE))
1151 diag(ComparisonOperator->getOperatorLoc(),
1152 "logical expression is always false");
1153 else if ((LhsValue == 0 && Opcode == BO_EQ) ||
1154 (LhsValue != 0 && Opcode == BO_NE))
1155 diag(ComparisonOperator->getOperatorLoc(),
1156 "logical expression is always true");
1157 }
1158 } else if (const auto *ComparisonOperator =
1159 Result.Nodes.getNodeAs<BinaryOperator>(
1160 "binop-const-compare-to-binop-const")) {
1161 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1162
1163 if (!retrieveBinOpIntegerConstantExpr(Result, "lhs", LhsOpcode, LhsSymbol,
1164 LhsValue) ||
1165 !retrieveBinOpIntegerConstantExpr(Result, "rhs", RhsOpcode, RhsSymbol,
1166 RhsValue) ||
1167 !areEquivalentExpr(LhsSymbol, RhsSymbol))
1168 return;
1169
1170 transformSubToCanonicalAddExpr(LhsOpcode, LhsValue);
1171 transformSubToCanonicalAddExpr(RhsOpcode, RhsValue);
1172
1173 // Check expressions: x + 1 == x + 2 or x + 1 != x + 2.
1174 if (LhsOpcode == BO_Add && RhsOpcode == BO_Add) {
1175 if ((Opcode == BO_EQ && APSInt::compareValues(LhsValue, RhsValue) == 0) ||
1176 (Opcode == BO_NE && APSInt::compareValues(LhsValue, RhsValue) != 0)) {
1177 diag(ComparisonOperator->getOperatorLoc(),
1178 "logical expression is always true");
1179 } else if ((Opcode == BO_EQ &&
1180 APSInt::compareValues(LhsValue, RhsValue) != 0) ||
1181 (Opcode == BO_NE &&
1182 APSInt::compareValues(LhsValue, RhsValue) == 0)) {
1183 diag(ComparisonOperator->getOperatorLoc(),
1184 "logical expression is always false");
1185 }
1186 }
1187 }
1188}
1189
1190static bool exprEvaluatesToZero(BinaryOperatorKind Opcode,
1191 const APSInt &Value) {
1192 return (Opcode == BO_And || Opcode == BO_AndAssign) && Value == 0;
1193}
1194
1195static bool exprEvaluatesToBitwiseNegatedZero(BinaryOperatorKind Opcode,
1196 const APSInt &Value) {
1197 return (Opcode == BO_Or || Opcode == BO_OrAssign) && ~Value == 0;
1198}
1199
1200static bool exprEvaluatesToSymbolic(BinaryOperatorKind Opcode,
1201 const APSInt &Value) {
1202 return ((Opcode == BO_Or || Opcode == BO_OrAssign) && Value == 0) ||
1203 ((Opcode == BO_And || Opcode == BO_AndAssign) && ~Value == 0);
1204}
1205
1206void RedundantExpressionCheck::checkBitwiseExpr(
1207 const MatchFinder::MatchResult &Result) {
1208 if (const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1209 "binop-const-compare-to-const")) {
1210 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1211
1212 APSInt LhsValue, RhsValue;
1213 const Expr *LhsSymbol = nullptr;
1214 BinaryOperatorKind LhsOpcode{};
1215 if (!retrieveBinOpIntegerConstantExpr(Result, "lhs", LhsOpcode, LhsSymbol,
1216 LhsValue) ||
1217 !retrieveIntegerConstantExpr(Result, "rhs", RhsValue))
1218 return;
1219
1220 const unsigned ConstantWidth =
1221 std::max(LhsValue.getBitWidth(), RhsValue.getBitWidth());
1222 const llvm::APInt LhsConstant = LhsValue.extOrTrunc(ConstantWidth);
1223 const llvm::APInt RhsConstant = RhsValue.extOrTrunc(ConstantWidth);
1224 const SourceLocation Loc = ComparisonOperator->getOperatorLoc();
1225
1226 // Check expression: x & k1 == k2 (i.e. x & 0xFF == 0xF00)
1227 if (LhsOpcode == BO_And && (LhsConstant & RhsConstant) != RhsConstant) {
1228 if (Opcode == BO_EQ)
1229 diag(Loc, "logical expression is always false");
1230 else if (Opcode == BO_NE)
1231 diag(Loc, "logical expression is always true");
1232 }
1233
1234 // Check expression: x | k1 == k2 (i.e. x | 0xFF == 0xF00)
1235 if (LhsOpcode == BO_Or && (LhsConstant | RhsConstant) != RhsConstant) {
1236 if (Opcode == BO_EQ)
1237 diag(Loc, "logical expression is always false");
1238 else if (Opcode == BO_NE)
1239 diag(Loc, "logical expression is always true");
1240 }
1241 } else if (const auto *IneffectiveOperator =
1242 Result.Nodes.getNodeAs<BinaryOperator>(
1243 "ineffective-bitwise")) {
1244 APSInt Value;
1245 const Expr *Sym = nullptr, *ConstExpr = nullptr;
1246
1247 if (!retrieveSymbolicExpr(Result, "ineffective-bitwise", Sym) ||
1248 !retrieveIntegerConstantExpr(Result, "ineffective-bitwise", Value,
1249 ConstExpr))
1250 return;
1251
1252 if ((Value != 0 && ~Value != 0) || Sym->getExprLoc().isMacroID())
1253 return;
1254
1255 const SourceLocation Loc = IneffectiveOperator->getOperatorLoc();
1256
1257 const BinaryOperatorKind Opcode = IneffectiveOperator->getOpcode();
1258 if (exprEvaluatesToZero(Opcode, Value)) {
1259 diag(Loc, "expression always evaluates to 0");
1260 } else if (exprEvaluatesToBitwiseNegatedZero(Opcode, Value)) {
1261 const SourceRange ConstExprRange(ConstExpr->getBeginLoc(),
1262 ConstExpr->getEndLoc());
1263 const StringRef ConstExprText = Lexer::getSourceText(
1264 CharSourceRange::getTokenRange(ConstExprRange), *Result.SourceManager,
1265 Result.Context->getLangOpts());
1266
1267 diag(Loc, "expression always evaluates to '%0'") << ConstExprText;
1268
1269 } else if (exprEvaluatesToSymbolic(Opcode, Value)) {
1270 const SourceRange SymExprRange(Sym->getBeginLoc(), Sym->getEndLoc());
1271
1272 const StringRef ExprText = Lexer::getSourceText(
1273 CharSourceRange::getTokenRange(SymExprRange), *Result.SourceManager,
1274 Result.Context->getLangOpts());
1275
1276 diag(Loc, "expression always evaluates to '%0'") << ExprText;
1277 }
1278 }
1279}
1280
1281void RedundantExpressionCheck::checkRelationalExpr(
1282 const MatchFinder::MatchResult &Result) {
1283 if (const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1284 "comparisons-of-symbol-and-const")) {
1285 // Matched expressions are: (x <op> k1) <REL> (x <op> k2).
1286 // E.g.: (X < 2) && (X > 4)
1287 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1288
1289 const Expr *LhsExpr = nullptr, *RhsExpr = nullptr;
1290 const Expr *LhsSymbol = nullptr, *RhsSymbol = nullptr;
1291 const Expr *LhsConst = nullptr, *RhsConst = nullptr;
1292 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1293 APSInt LhsValue, RhsValue;
1294
1296 Result, "lhs", LhsExpr, LhsOpcode, LhsSymbol, LhsValue, LhsConst) ||
1298 Result, "rhs", RhsExpr, RhsOpcode, RhsSymbol, RhsValue, RhsConst) ||
1299 !areEquivalentExpr(LhsSymbol, RhsSymbol))
1300 return;
1301
1302 // Bring expr to a canonical form: smallest constant must be on the left.
1303 if (APSInt::compareValues(LhsValue, RhsValue) > 0) {
1304 std::swap(LhsExpr, RhsExpr);
1305 std::swap(LhsValue, RhsValue);
1306 std::swap(LhsSymbol, RhsSymbol);
1307 std::swap(LhsOpcode, RhsOpcode);
1308 }
1309
1310 // Constants come from two different macros, or one of them is a macro.
1311 if (areExprsFromDifferentMacros(LhsConst, RhsConst, Result.Context) ||
1312 areExprsMacroAndNonMacro(LhsConst, RhsConst))
1313 return;
1314
1315 if ((Opcode == BO_LAnd || Opcode == BO_LOr) &&
1316 areEquivalentRanges(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
1317 diag(ComparisonOperator->getOperatorLoc(),
1318 "equivalent expression on both sides of logical operator");
1319 return;
1320 }
1321
1322 if (Opcode == BO_LAnd) {
1323 if (areExclusiveRanges(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
1324 diag(ComparisonOperator->getOperatorLoc(),
1325 "logical expression is always false");
1326 } else if (rangeSubsumesRange(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
1327 diag(LhsExpr->getExprLoc(), "expression is redundant");
1328 } else if (rangeSubsumesRange(RhsOpcode, RhsValue, LhsOpcode, LhsValue)) {
1329 diag(RhsExpr->getExprLoc(), "expression is redundant");
1330 }
1331 }
1332
1333 if (Opcode == BO_LOr) {
1334 if (rangesFullyCoverDomain(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
1335 diag(ComparisonOperator->getOperatorLoc(),
1336 "logical expression is always true");
1337 } else if (rangeSubsumesRange(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
1338 diag(RhsExpr->getExprLoc(), "expression is redundant");
1339 } else if (rangeSubsumesRange(RhsOpcode, RhsValue, LhsOpcode, LhsValue)) {
1340 diag(LhsExpr->getExprLoc(), "expression is redundant");
1341 }
1342 }
1343 }
1344}
1345
1346void RedundantExpressionCheck::check(const MatchFinder::MatchResult &Result) {
1347 if (const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>("binary")) {
1348 // If the expression's constants are macros, check whether they are
1349 // intentional.
1350
1351 //
1352 // Special case for floating-point representation.
1353 //
1354 // If expressions on both sides of comparison operator are of type float,
1355 // then for some comparison operators no warning shall be
1356 // reported even if the expressions are identical from a symbolic point of
1357 // view. Comparison between expressions, declared variables and literals
1358 // are treated differently.
1359 //
1360 // != and == between float literals that have the same value should NOT
1361 // warn. < > between float literals that have the same value SHOULD warn.
1362 //
1363 // != and == between the same float declaration should NOT warn.
1364 // < > between the same float declaration SHOULD warn.
1365 //
1366 // != and == between eq. expressions that evaluates into float
1367 // should NOT warn.
1368 // < > between eq. expressions that evaluates into float
1369 // should NOT warn.
1370 //
1371 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
1372 const Expr *RHS = BinOp->getRHS()->IgnoreParenImpCasts();
1373 const BinaryOperator::Opcode Op = BinOp->getOpcode();
1374 const bool OpEqualEQorNE = ((Op == BO_EQ) || (Op == BO_NE));
1375
1376 const auto *DeclRef1 = dyn_cast<DeclRefExpr>(LHS);
1377 const auto *DeclRef2 = dyn_cast<DeclRefExpr>(RHS);
1378 const auto *FloatLit1 = dyn_cast<FloatingLiteral>(LHS);
1379 const auto *FloatLit2 = dyn_cast<FloatingLiteral>(RHS);
1380
1381 if (DeclRef1 && DeclRef2 &&
1382 DeclRef1->getType()->hasFloatingRepresentation() &&
1383 DeclRef2->getType()->hasFloatingRepresentation() &&
1384 (DeclRef1->getDecl() == DeclRef2->getDecl()) && OpEqualEQorNE) {
1385 return;
1386 }
1387
1388 if (FloatLit1 && FloatLit2 &&
1389 FloatLit1->getValue().bitwiseIsEqual(FloatLit2->getValue()) &&
1390 OpEqualEQorNE) {
1391 return;
1392 }
1393
1395 BinOp, Result.Context)) {
1396 const Expr *LhsConst = nullptr, *RhsConst = nullptr;
1397 BinaryOperatorKind MainOpcode{}, SideOpcode{};
1398 if (areSidesBinaryConstExpressions(BinOp, Result.Context)) {
1399 if (!retrieveConstExprFromBothSides(BinOp, MainOpcode, SideOpcode,
1400 LhsConst, RhsConst, Result.Context))
1401 return;
1402
1403 if (areExprsFromDifferentMacros(LhsConst, RhsConst, Result.Context) ||
1404 areExprsMacroAndNonMacro(LhsConst, RhsConst))
1405 return;
1406 } else {
1407 if (!areExprsSameMacroOrLiteral(BinOp, Result.Context))
1408 return;
1409 }
1410 }
1411 diag(BinOp->getOperatorLoc(), "both sides of operator are equivalent");
1412 }
1413
1414 if (const auto *CondOp =
1415 Result.Nodes.getNodeAs<ConditionalOperator>("cond")) {
1416 const Expr *TrueExpr = CondOp->getTrueExpr();
1417 const Expr *FalseExpr = CondOp->getFalseExpr();
1418
1419 if (areExprsFromDifferentMacros(TrueExpr, FalseExpr, Result.Context) ||
1420 areExprsMacroAndNonMacro(TrueExpr, FalseExpr))
1421 return;
1422 diag(CondOp->getColonLoc(),
1423 "'true' and 'false' expressions are equivalent");
1424 }
1425
1426 if (const auto *Call = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("call")) {
1428 return;
1429
1430 diag(Call->getOperatorLoc(),
1431 "both sides of overloaded operator are equivalent");
1432 }
1433
1434 if (const auto *Op = Result.Nodes.getNodeAs<Expr>("nested-duplicates")) {
1435 const auto *Call = dyn_cast<CXXOperatorCallExpr>(Op);
1436 if (Call && canOverloadedOperatorArgsBeModified(Call, true))
1437 return;
1438
1439 const StringRef Message =
1440 Call ? "overloaded operator has equivalent nested operands"
1441 : "operator has equivalent nested operands";
1442
1443 const auto Diag = diag(Op->getExprLoc(), Message);
1444 for (const auto &KeyValue : Result.Nodes.getMap())
1445 if (StringRef(KeyValue.first).starts_with("duplicate"))
1446 Diag << KeyValue.second.getSourceRange();
1447 }
1448
1449 if (const auto *NegateOperator =
1450 Result.Nodes.getNodeAs<UnaryOperator>("logical-bitwise-confusion")) {
1451 const SourceLocation OperatorLoc = NegateOperator->getOperatorLoc();
1452
1453 const auto Diag =
1454 diag(OperatorLoc,
1455 "ineffective logical negation operator used; did you mean '~'?");
1456 const SourceLocation LogicalNotLocation = OperatorLoc.getLocWithOffset(1);
1457
1458 if (!LogicalNotLocation.isMacroID())
1459 Diag << FixItHint::CreateReplacement(
1460 CharSourceRange::getCharRange(OperatorLoc, LogicalNotLocation), "~");
1461 }
1462
1463 if (const auto *BinaryAndExpr = Result.Nodes.getNodeAs<BinaryOperator>(
1464 "left-right-shift-confusion")) {
1465 const auto *ShiftingConst = Result.Nodes.getNodeAs<Expr>("shift-const");
1466 assert(ShiftingConst && "Expr* 'ShiftingConst' is nullptr!");
1467 std::optional<llvm::APSInt> ShiftingValue =
1468 ShiftingConst->getIntegerConstantExpr(*Result.Context);
1469
1470 if (!ShiftingValue)
1471 return;
1472
1473 const auto *AndConst = Result.Nodes.getNodeAs<Expr>("and-const");
1474 assert(AndConst && "Expr* 'AndCont' is nullptr!");
1475 std::optional<llvm::APSInt> AndValue =
1476 AndConst->getIntegerConstantExpr(*Result.Context);
1477 if (!AndValue)
1478 return;
1479
1480 // If ShiftingConst is shifted left with more bits than the position of the
1481 // leftmost 1 in the bit representation of AndValue, AndConstant is
1482 // ineffective.
1483 if (AndValue->getActiveBits() > *ShiftingValue)
1484 return;
1485
1486 const auto Diag = diag(BinaryAndExpr->getOperatorLoc(),
1487 "ineffective bitwise and operation");
1488 }
1489
1490 // Check for the following bound expressions:
1491 // - "binop-const-compare-to-sym",
1492 // - "binop-const-compare-to-binop-const",
1493 // Produced message:
1494 // -> "logical expression is always false/true"
1495 checkArithmeticExpr(Result);
1496
1497 // Check for the following bound expression:
1498 // - "binop-const-compare-to-const",
1499 // - "ineffective-bitwise"
1500 // Produced message:
1501 // -> "logical expression is always false/true"
1502 // -> "expression always evaluates to ..."
1503 checkBitwiseExpr(Result);
1504
1505 // Check for te following bound expression:
1506 // - "comparisons-of-symbol-and-const",
1507 // Produced messages:
1508 // -> "equivalent expression on both sides of logical operator",
1509 // -> "logical expression is always false/true"
1510 // -> "expression is redundant"
1511 checkRelationalExpr(Result);
1512}
1513
1514} // namespace clang::tidy::misc
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
AST_MATCHER(BinaryOperator, isRelationalOperator)
static bool areExprsFromDifferentMacros(const Expr *LhsExpr, const Expr *RhsExpr, const ASTContext *AstCtx)
Returns true if both LhsExpr and RhsExpr are macro expressions and they are expanded from different m...
static const TExpr * checkOpKind(const Expr *TheExpr, OverloadedOperatorKind OpKind)
static constexpr StringRef KnownBannedMacroNames[]
static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp, const ASTContext *AstCtx)
static bool markDuplicateOperands(const TExpr *TheExpr, ast_matchers::internal::BoundNodesTreeBuilder *Builder, ASTContext &Context)
static bool areEquivalentDeclRefExpr(const DeclRefExpr *L, const DeclRefExpr *R)
static bool collectOperands(const Expr *Part, SmallVector< const Expr *, N > &AllOperands, OverloadedOperatorKind OpKind)
static std::pair< const Expr *, const Expr * > getOperands(const BinaryOperator *Op)
static constexpr StringRef Message
static bool retrieveConstExprFromBothSides(const BinaryOperator *&BinOp, BinaryOperatorKind &MainOpcode, BinaryOperatorKind &SideOpcode, const Expr *&LhsConst, const Expr *&RhsConst, const ASTContext *AstCtx)
static void transformSubToCanonicalAddExpr(BinaryOperatorKind &Opcode, APSInt &Value)
static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result, StringRef Id, APSInt &Value, const Expr *&ConstExpr)
static bool retrieveRelationalIntegerConstantExpr(const MatchFinder::MatchResult &Result, StringRef Id, const Expr *&OperandExpr, BinaryOperatorKind &Opcode, const Expr *&Symbol, APSInt &Value, const Expr *&ConstExpr)
static bool rangeSubsumesRange(BinaryOperatorKind OpcodeLHS, const APSInt &ValueLHS, BinaryOperatorKind OpcodeRHS, const APSInt &ValueRHS)
static bool areExclusiveRanges(BinaryOperatorKind OpcodeLHS, const APSInt &ValueLHS, BinaryOperatorKind OpcodeRHS, const APSInt &ValueRHS)
static ast_matchers::internal::Matcher< Expr > matchSymbolicExpr(StringRef Id)
static bool areStringsSameIgnoreSpaces(const StringRef Left, const StringRef Right)
static bool incrementWithoutOverflow(const APSInt &Value, APSInt &Result)
static bool areExprsMacroAndNonMacro(const Expr *&LhsExpr, const Expr *&RhsExpr)
static bool isSameRawIdentifierToken(const Token &T1, const Token &T2, const SourceManager &SM)
static bool areSidesBinaryConstExpressionsOrDefinesOrIntegerConstant(const BinaryOperator *&BinOp, const ASTContext *AstCtx)
static bool isTokAtEndOfExpr(SourceRange ExprSR, Token T, const SourceManager &SM)
static bool areEquivalentExpr(const Expr *Left, const Expr *Right)
static bool rangesFullyCoverDomain(BinaryOperatorKind OpcodeLHS, const APSInt &ValueLHS, BinaryOperatorKind OpcodeRHS, const APSInt &ValueRHS)
static bool isNonConstReferenceType(QualType ParamType)
static ast_matchers::internal::Matcher< Expr > matchIntegerConstantExpr(StringRef Id)
static OverloadedOperatorKind getOp(const BinaryOperator *Op)
static bool exprEvaluatesToBitwiseNegatedZero(BinaryOperatorKind Opcode, const APSInt &Value)
static ast_matchers::internal::Matcher< Expr > matchBinOpIntegerConstantExpr(StringRef Id)
static bool hasSameOperatorParent(const Expr *TheExpr, OverloadedOperatorKind OpKind, ASTContext &Context)
static bool retrieveSymbolicExpr(const MatchFinder::MatchResult &Result, StringRef Id, const Expr *&SymExpr)
static bool areEquivalentRanges(BinaryOperatorKind OpcodeLHS, const APSInt &ValueLHS, BinaryOperatorKind OpcodeRHS, const APSInt &ValueRHS)
static bool areExprsSameMacroOrLiteral(const BinaryOperator *BinOp, const ASTContext *Context)
static bool retrieveBinOpIntegerConstantExpr(const MatchFinder::MatchResult &Result, StringRef Id, BinaryOperatorKind &Opcode, const Expr *&Symbol, APSInt &Value)
static ast_matchers::internal::Matcher< Expr > matchRelationalIntegerConstantExpr(StringRef Id)
static bool exprEvaluatesToSymbolic(BinaryOperatorKind Opcode, const APSInt &Value)
static bool exprEvaluatesToZero(BinaryOperatorKind Opcode, const APSInt &Value)
static bool canOverloadedOperatorArgsBeModified(const CXXOperatorCallExpr *OperatorCall, bool CheckSecondParam)