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"
44 return Value < Result;
48 const DeclRefExpr *R) {
49 if (L->getDecl() != R->getDecl())
52 const PrintingPolicy &Policy =
53 L->getDecl()->getASTContext().getPrintingPolicy();
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);
64 if (L->hasExplicitTemplateArgs() != R->hasExplicitTemplateArgs())
66 if (L->hasExplicitTemplateArgs()) {
67 if (L->getNumTemplateArgs() != R->getNumTemplateArgs())
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);
85 return !Left && !Right;
87 Left = Left->IgnoreParens();
88 Right = Right->IgnoreParens();
91 if (Left->getStmtClass() != Right->getStmtClass())
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()) {
99 dyn_cast_or_null<Expr>(*RightIter)))
104 if (LeftIter != Left->child_end() || RightIter != Right->child_end())
108 switch (Left->getStmtClass()) {
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() &&
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())
134 return cast<DependentScopeDeclRefExpr>(Left)->getQualifier() ==
135 cast<DependentScopeDeclRefExpr>(Right)->getQualifier();
136 case Stmt::DeclRefExprClass:
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:
153 case Stmt::UnaryOperatorClass:
154 if (cast<UnaryOperator>(Left)->isIncrementDecrementOp())
156 return cast<UnaryOperator>(Left)->getOpcode() ==
157 cast<UnaryOperator>(Right)->getOpcode();
158 case Stmt::BinaryOperatorClass:
159 if (cast<BinaryOperator>(Left)->isAssignmentOp())
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())
172 RightUnaryExpr->getArgumentExpr());
181 const APSInt &ValueLHS,
182 BinaryOperatorKind OpcodeRHS,
183 const APSInt &ValueRHS) {
184 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
185 "Values must be ordered");
187 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0)
188 return OpcodeLHS == OpcodeRHS;
191 APSInt ValueLhsPlus1;
192 return ((OpcodeLHS == BO_LE && OpcodeRHS == BO_LT) ||
193 (OpcodeLHS == BO_GT && OpcodeRHS == BO_GE)) &&
195 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0;
201 const APSInt &ValueLHS,
202 BinaryOperatorKind OpcodeRHS,
203 const APSInt &ValueRHS) {
204 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
205 "Values must be ordered");
208 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
211 return OpcodeRHS == BO_NE || OpcodeRHS == BO_GT || OpcodeRHS == BO_LT;
213 return OpcodeRHS == BO_EQ;
215 return OpcodeRHS == BO_GT;
217 return OpcodeRHS == BO_LT;
219 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
221 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
228 if ((OpcodeLHS == BO_EQ || OpcodeLHS == BO_LT || OpcodeLHS == BO_LE) &&
229 (OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE))
233 APSInt ValueLhsPlus1;
234 if (OpcodeLHS == BO_GT && OpcodeRHS == BO_LT &&
236 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
245 const APSInt &ValueLHS,
246 BinaryOperatorKind OpcodeRHS,
247 const APSInt &ValueRHS) {
248 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
249 "Values must be ordered");
252 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
255 return OpcodeRHS == BO_NE;
257 return OpcodeRHS == BO_EQ;
259 return OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
261 return OpcodeRHS == BO_GE;
263 return OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
265 return OpcodeRHS == BO_LE;
272 APSInt ValueLhsPlus1;
273 if (OpcodeLHS == BO_LE && OpcodeRHS == BO_GE &&
275 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
279 if ((OpcodeLHS == BO_GT || OpcodeLHS == BO_GE) &&
280 (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE))
285 if (OpcodeLHS == BO_NE && OpcodeRHS == BO_NE)
292 const APSInt &ValueLHS,
293 BinaryOperatorKind OpcodeRHS,
294 const APSInt &ValueRHS) {
295 const int Comparison = APSInt::compareValues(ValueLHS, ValueRHS);
298 return OpcodeRHS == BO_EQ && Comparison == 0;
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);
308 return ((OpcodeRHS == BO_LT && Comparison >= 0) ||
309 (OpcodeRHS == BO_LE && Comparison > 0) ||
310 (OpcodeRHS == BO_EQ && Comparison > 0));
312 return ((OpcodeRHS == BO_GT && Comparison <= 0) ||
313 (OpcodeRHS == BO_GE && Comparison < 0) ||
314 (OpcodeRHS == BO_EQ && Comparison < 0));
316 return (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE || OpcodeRHS == BO_EQ) &&
319 return (OpcodeRHS == BO_GT || OpcodeRHS == BO_GE || OpcodeRHS == BO_EQ) &&
328 if (Opcode == BO_Sub) {
335static OverloadedOperatorKind
getOp(
const BinaryOperator *Op) {
336 return BinaryOperator::getOverloadedOperator(Op->getOpcode());
339static OverloadedOperatorKind
getOp(
const CXXOperatorCallExpr *Op) {
340 if (Op->getNumArgs() != 2)
342 return Op->getOperator();
345static std::pair<const Expr *, const Expr *>
347 return {Op->getLHS()->IgnoreParenImpCasts(),
348 Op->getRHS()->IgnoreParenImpCasts()};
351static std::pair<const Expr *, const Expr *>
353 return {Op->getArg(0)->IgnoreParenImpCasts(),
354 Op->getArg(1)->IgnoreParenImpCasts()};
357template <
typename TExpr>
359 OverloadedOperatorKind OpKind) {
360 const auto *AsTExpr = dyn_cast_or_null<TExpr>(TheExpr);
361 if (AsTExpr &&
getOp(AsTExpr) == OpKind)
369template <
typename TExpr,
unsigned N>
372 OverloadedOperatorKind OpKind) {
374 const std::pair<const Expr *, const Expr *> Operands =
getOperands(BinOp);
381 AllOperands.push_back(Part);
385template <
typename TExpr>
387 OverloadedOperatorKind OpKind,
388 ASTContext &Context) {
390 const DynTypedNodeList Parents = Context.getParents(*TheExpr);
391 for (
const DynTypedNode DynParent : Parents) {
392 if (
const auto *Parent = DynParent.get<Expr>()) {
394 isa<ParenExpr>(Parent) || isa<ImplicitCastExpr>(Parent) ||
395 isa<FullExpr>(Parent) || isa<MaterializeTemporaryExpr>(Parent);
407 const SourceManager &SM) {
408 if (T1.getKind() != T2.getKind())
410 if (T1.isNot(tok::raw_identifier))
412 if (T1.getLength() != T2.getLength())
414 return StringRef(SM.getCharacterData(T1.getLocation()), T1.getLength()) ==
415 StringRef(SM.getCharacterData(T2.getLocation()), T2.getLength());
419 const SourceManager &SM) {
420 return SM.getExpansionLoc(ExprSR.getEnd()) == T.getLocation();
428 const ASTContext *AstCtx) {
429 if (!LhsExpr || !RhsExpr)
431 const SourceRange Lsr = LhsExpr->getSourceRange();
432 const SourceRange Rsr = RhsExpr->getSourceRange();
433 if (!Lsr.getBegin().isMacroID() || !Rsr.getBegin().isMacroID())
436 const SourceManager &SM = AstCtx->getSourceManager();
437 const LangOptions &LO = AstCtx->getLangOpts();
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);
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());
454 LRawLex.LexFromRawLexer(LTok);
455 RRawLex.LexFromRawLexer(RTok);
456 }
while (!LTok.is(tok::eof) && !RTok.is(tok::eof) &&
466 const Expr *&RhsExpr) {
467 if (!LhsExpr || !RhsExpr)
470 const SourceLocation LhsLoc = LhsExpr->getExprLoc();
471 const SourceLocation RhsLoc = RhsExpr->getExprLoc();
473 return LhsLoc.isMacroID() != RhsLoc.isMacroID();
476template <
typename TExpr>
479 ast_matchers::internal::BoundNodesTreeBuilder *Builder,
480 ASTContext &Context) {
481 const OverloadedOperatorKind OpKind =
getOp(TheExpr);
482 if (OpKind == OO_None)
486 const std::pair<const Expr *, const Expr *> Operands =
getOperands(TheExpr);
501 const size_t NumOperands = AllOperands.size();
502 llvm::SmallBitVector Duplicates(NumOperands);
503 for (
size_t I = 0; I < NumOperands; I++) {
506 bool FoundDuplicates =
false;
508 for (
size_t J = I + 1; J < NumOperands; J++) {
509 if (AllOperands[J]->HasSideEffects(Context))
512 const Expr *Lhs = AllOperands[I];
513 const Expr *Rhs = AllOperands[J];
519 FoundDuplicates =
true;
521 Builder->setBinding(SmallString<11>(llvm::formatv(
"duplicate{0}", J)),
522 DynTypedNode::create(*Rhs));
526 Builder->setBinding(SmallString<11>(llvm::formatv(
"duplicate{0}", I)),
527 DynTypedNode::create(*AllOperands[I]));
530 return Duplicates.any();
536 if (Node.isInstantiationDependent())
538 return Node.isIntegerConstantExpr(Finder->getASTContext());
541AST_MATCHER(BinaryOperator, operandsAreEquivalent) {
545AST_MATCHER(BinaryOperator, nestedOperandsAreEquivalent) {
549AST_MATCHER(ConditionalOperator, expressionsAreEquivalent) {
554 return Node.getNumArgs() == 2 &&
558AST_MATCHER(CXXOperatorCallExpr, nestedParametersAreEquivalent) {
562AST_MATCHER(BinaryOperator, binaryOperatorIsInMacro) {
563 return Node.getOperatorLoc().isMacroID();
566AST_MATCHER(ConditionalOperator, conditionalOperatorIsInMacro) {
567 return Node.getQuestionLoc().isMacroID() || Node.getColonLoc().isMacroID();
570AST_MATCHER(Expr, isMacro) {
return Node.getExprLoc().isMacroID(); }
572AST_MATCHER_P(Expr, expandedByMacro, ArrayRef<StringRef>, Names) {
573 const SourceManager &SM = Finder->getASTContext().getSourceManager();
574 const LangOptions &LO = Finder->getASTContext().getLangOpts();
575 SourceLocation Loc = Node.getExprLoc();
576 while (Loc.isMacroID()) {
577 const StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LO);
578 if (llvm::is_contained(Names, MacroName))
580 Loc = SM.getImmediateMacroCallerLoc(Loc);
588static ast_matchers::internal::Matcher<Expr>
590 const std::string CstId = (Id +
"-const").str();
591 return expr(isIntegerConstantExpr()).bind(CstId);
598 StringRef Id, APSInt &Value,
599 const Expr *&ConstExpr) {
600 const std::string CstId = (Id +
"-const").str();
601 ConstExpr = Result.Nodes.getNodeAs<Expr>(CstId);
604 std::optional<llvm::APSInt> R =
605 ConstExpr->getIntegerConstantExpr(*Result.Context);
614 StringRef Id, APSInt &Value) {
615 const Expr *ConstExpr =
nullptr;
622 const std::string SymId = (Id +
"-sym").str();
623 return ignoringParenImpCasts(
624 expr(unless(isIntegerConstantExpr())).bind(SymId));
630 StringRef Id,
const Expr *&SymExpr) {
631 const std::string SymId = (Id +
"-sym").str();
632 if (
const auto *Node = Result.Nodes.getNodeAs<Expr>(SymId)) {
641static ast_matchers::internal::Matcher<Expr>
643 const auto BinOpCstExpr =
644 expr(anyOf(binaryOperator(hasAnyOperatorName(
"+",
"|",
"&"),
647 binaryOperator(hasOperatorName(
"-"),
651 return ignoringParenImpCasts(BinOpCstExpr);
658 StringRef Id, BinaryOperatorKind &Opcode,
659 const Expr *&Symbol, APSInt &Value) {
660 if (
const auto *BinExpr = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
661 Opcode = BinExpr->getOpcode();
669static ast_matchers::internal::Matcher<Expr>
671 const std::string CastId = (Id +
"-cast").str();
672 const std::string SwapId = (Id +
"-swap").str();
673 const std::string NegateId = (Id +
"-negate").str();
674 const std::string OverloadId = (Id +
"-overload").str();
675 const std::string ConstId = (Id +
"-const").str();
677 const auto RelationalExpr = ignoringParenImpCasts(binaryOperator(
678 isComparisonOperator(), expr().bind(Id),
686 const auto CastExpr =
687 implicitCastExpr(hasCastKind(CK_IntegralToBoolean),
691 const auto NegateRelationalExpr =
692 unaryOperator(hasOperatorName(
"!"),
693 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))
697 const auto NegateNegateRelationalExpr =
698 unaryOperator(hasOperatorName(
"!"),
699 hasUnaryOperand(unaryOperator(
700 hasOperatorName(
"!"),
701 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))));
703 const auto OverloadedOperatorExpr =
705 hasAnyOverloadedOperatorName(
"==",
"!=",
"<",
"<=",
">",
">="),
707 unless(isMacro()), unless(isInTemplateInstantiation()),
708 anyOf(hasLHS(ignoringParenImpCasts(integerLiteral().bind(ConstId))),
709 hasRHS(ignoringParenImpCasts(integerLiteral().bind(ConstId)))))
712 return anyOf(RelationalExpr, CastExpr, NegateRelationalExpr,
713 NegateNegateRelationalExpr, OverloadedOperatorExpr);
719 return ParamType->isReferenceType() &&
720 !ParamType.getNonReferenceType().isConstQualified();
731 bool CheckSecondParam) {
732 const auto *OperatorDecl =
733 dyn_cast_or_null<FunctionDecl>(OperatorCall->getCalleeDecl());
739 const unsigned ParamCount = OperatorDecl->getNumParams();
744 if (ParamCount == 1 &&
745 !OperatorDecl->getType()->castAs<FunctionType>()->isConst())
751 return CheckSecondParam && ParamCount == 2 &&
758 const MatchFinder::MatchResult &Result, StringRef Id,
759 const Expr *&OperandExpr, BinaryOperatorKind &Opcode,
const Expr *&Symbol,
760 APSInt &Value,
const Expr *&ConstExpr) {
761 const std::string CastId = (Id +
"-cast").str();
762 const std::string SwapId = (Id +
"-swap").str();
763 const std::string NegateId = (Id +
"-negate").str();
764 const std::string OverloadId = (Id +
"-overload").str();
766 if (
const auto *Bin = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
768 Opcode = Bin->getOpcode();
773 }
else if (
const auto *Cast = Result.Nodes.getNodeAs<CastExpr>(CastId)) {
777 Value = APSInt(32,
false);
778 }
else if (
const auto *OverloadedOperatorExpr =
779 Result.Nodes.getNodeAs<CXXOperatorCallExpr>(OverloadId)) {
783 bool IntegerConstantIsFirstArg =
false;
785 if (
const auto *Arg = OverloadedOperatorExpr->getArg(1)) {
786 if (!Arg->isValueDependent() &&
787 !Arg->isIntegerConstantExpr(*Result.Context)) {
788 IntegerConstantIsFirstArg =
true;
789 if (
const auto *Arg = OverloadedOperatorExpr->getArg(0)) {
790 if (!Arg->isValueDependent() &&
791 !Arg->isIntegerConstantExpr(*Result.Context))
801 Symbol = OverloadedOperatorExpr->getArg(IntegerConstantIsFirstArg ? 1 : 0);
802 OperandExpr = OverloadedOperatorExpr;
803 Opcode = BinaryOperator::getOverloadedOpcode(
804 OverloadedOperatorExpr->getOperator());
809 if (!BinaryOperator::isComparisonOp(Opcode))
814 if (IntegerConstantIsFirstArg)
815 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
825 if (Result.Nodes.getNodeAs<Expr>(SwapId))
826 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
827 if (Result.Nodes.getNodeAs<Expr>(NegateId))
828 Opcode = BinaryOperator::negateComparisonOp(Opcode);
834 const ASTContext *AstCtx) {
835 const auto *LhsBinOp = dyn_cast<BinaryOperator>(BinOp->getLHS());
836 const auto *RhsBinOp = dyn_cast<BinaryOperator>(BinOp->getRHS());
838 if (!LhsBinOp || !RhsBinOp)
841 const auto IsIntegerConstantExpr = [AstCtx](
const Expr *E) {
842 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
845 if ((IsIntegerConstantExpr(LhsBinOp->getLHS()) ||
846 IsIntegerConstantExpr(LhsBinOp->getRHS())) &&
847 (IsIntegerConstantExpr(RhsBinOp->getLHS()) ||
848 IsIntegerConstantExpr(RhsBinOp->getRHS())))
854 const BinaryOperator *&BinOp,
const ASTContext *AstCtx) {
858 const Expr *Lhs = BinOp->getLHS();
859 const Expr *Rhs = BinOp->getRHS();
864 const auto IsDefineExpr = [AstCtx](
const Expr *E) {
865 const SourceRange Lsr = E->getSourceRange();
866 if (!Lsr.getBegin().isMacroID() || E->isValueDependent() ||
867 !E->isIntegerConstantExpr(*AstCtx))
872 return IsDefineExpr(Lhs) || IsDefineExpr(Rhs);
879 BinaryOperatorKind &MainOpcode,
880 BinaryOperatorKind &SideOpcode,
881 const Expr *&LhsConst,
882 const Expr *&RhsConst,
883 const ASTContext *AstCtx) {
885 "Both sides of binary operator must be constant expressions!");
887 MainOpcode = BinOp->getOpcode();
889 const auto *BinOpLhs = cast<BinaryOperator>(BinOp->getLHS());
890 const auto *BinOpRhs = cast<BinaryOperator>(BinOp->getRHS());
892 const auto IsIntegerConstantExpr = [AstCtx](
const Expr *E) {
893 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
896 LhsConst = IsIntegerConstantExpr(BinOpLhs->getLHS()) ? BinOpLhs->getLHS()
897 : BinOpLhs->getRHS();
898 RhsConst = IsIntegerConstantExpr(BinOpRhs->getLHS()) ? BinOpRhs->getLHS()
899 : BinOpRhs->getRHS();
901 if (!LhsConst || !RhsConst)
904 assert(BinOpLhs->getOpcode() == BinOpRhs->getOpcode() &&
905 "Sides of the binary operator must be equivalent expressions!");
907 SideOpcode = BinOpLhs->getOpcode();
913 const StringRef Right) {
918 StringRef L = Left.trim();
919 StringRef R = Right.trim();
920 while (!L.empty() && !R.empty()) {
923 if (L.empty() && R.empty())
926 if (L.front() != R.front())
931 return L.empty() && R.empty();
935 const ASTContext *Context) {
939 const Expr *Lhs = BinOp->getLHS();
940 const Expr *Rhs = BinOp->getRHS();
941 const SourceManager &SM = Context->getSourceManager();
943 const SourceRange Lsr = Lhs->getSourceRange();
944 const SourceRange Rsr = Rhs->getSourceRange();
945 if (Lsr.getBegin().isMacroID()) {
947 if (Rsr.getBegin().isMacroID()) {
949 const StringRef L = Lexer::getSourceText(
950 CharSourceRange::getTokenRange(Lsr), SM, Context->getLangOpts());
951 const StringRef R = Lexer::getSourceText(
952 CharSourceRange::getTokenRange(Rsr), SM, Context->getLangOpts());
958 const auto *Lil = dyn_cast<IntegerLiteral>(Lhs);
959 const auto *Ril = dyn_cast<IntegerLiteral>(Rhs);
961 return Lil->getValue() == Ril->getValue();
963 const auto *Lbl = dyn_cast<CXXBoolLiteralExpr>(Lhs);
964 const auto *Rbl = dyn_cast<CXXBoolLiteralExpr>(Rhs);
966 return Lbl->getValue() == Rbl->getValue();
972 const auto BannedIntegerLiteral =
974 const auto IsInUnevaluatedContext = expr(anyOf(
975 hasAncestor(expr(hasUnevaluatedContext())), hasAncestor(typeLoc())));
980 binaryOperator(anyOf(isComparisonOperator(),
981 hasAnyOperatorName(
"-",
"/",
"%",
"|",
"&",
982 "^",
"&&",
"||",
"=")),
983 operandsAreEquivalent(),
985 unless(isInTemplateInstantiation()),
986 unless(binaryOperatorIsInMacro()),
987 unless(hasAncestor(arraySubscriptExpr())),
988 unless(hasDescendant(BannedIntegerLiteral)),
989 unless(IsInUnevaluatedContext))
996 binaryOperator(hasAnyOperatorName(
"|",
"&",
"||",
"&&",
"^"),
997 nestedOperandsAreEquivalent(),
999 unless(isInTemplateInstantiation()),
1000 unless(binaryOperatorIsInMacro()),
1002 unless(hasDescendant(BannedIntegerLiteral)),
1003 unless(IsInUnevaluatedContext))
1004 .bind(
"nested-duplicates"),
1010 conditionalOperator(expressionsAreEquivalent(),
1012 unless(conditionalOperatorIsInMacro()),
1013 unless(isInTemplateInstantiation()),
1014 unless(IsInUnevaluatedContext))
1021 cxxOperatorCallExpr(
1022 hasAnyOverloadedOperatorName(
"-",
"/",
"%",
"|",
"&",
"^",
1023 "==",
"!=",
"<",
"<=",
">",
1024 ">=",
"&&",
"||",
"="),
1025 parametersAreEquivalent(),
1027 unless(isMacro()), unless(isInTemplateInstantiation()),
1028 unless(IsInUnevaluatedContext))
1034 cxxOperatorCallExpr(
1035 hasAnyOverloadedOperatorName(
"|",
"&",
"||",
"&&",
"^"),
1036 nestedParametersAreEquivalent(), argumentCountIs(2),
1038 unless(isMacro()), unless(isInTemplateInstantiation()),
1039 unless(IsInUnevaluatedContext))
1040 .bind(
"nested-duplicates"),
1047 hasImplicitDestinationType(isInteger()),
1049 hasOperatorName(
"!"),
1050 hasUnaryOperand(ignoringParenImpCasts(binaryOperator(
1051 hasAnyOperatorName(
"|",
"&"),
1053 binaryOperator(hasAnyOperatorName(
"|",
"&")),
1055 hasRHS(integerLiteral())))))
1056 .bind(
"logical-bitwise-confusion")),
1057 unless(IsInUnevaluatedContext))),
1064 hasOperatorName(
"&"),
1065 hasOperands(ignoringParenImpCasts(binaryOperator(
1066 hasOperatorName(
"<<"),
1067 hasRHS(ignoringParenImpCasts(
1068 integerLiteral().bind(
"shift-const"))))),
1069 ignoringParenImpCasts(
1070 integerLiteral().bind(
"and-const"))),
1071 unless(IsInUnevaluatedContext))
1072 .bind(
"left-right-shift-confusion")),
1088 traverse(TK_AsIs, binaryOperator(isComparisonOperator(),
1089 hasOperands(BinOpCstLeft, CstRight),
1090 unless(IsInUnevaluatedContext))
1091 .bind(
"binop-const-compare-to-const")),
1098 binaryOperator(isComparisonOperator(),
1099 anyOf(allOf(hasLHS(BinOpCstLeft), hasRHS(SymRight)),
1100 allOf(hasLHS(SymRight), hasRHS(BinOpCstLeft))),
1101 unless(IsInUnevaluatedContext))
1102 .bind(
"binop-const-compare-to-sym")),
1108 binaryOperator(isComparisonOperator(), hasLHS(BinOpCstLeft),
1109 hasRHS(BinOpCstRight),
1111 unless(operandsAreEquivalent()),
1112 unless(IsInUnevaluatedContext))
1113 .bind(
"binop-const-compare-to-binop-const")),
1125 binaryOperator(hasAnyOperatorName(
"||",
"&&"),
1126 hasLHS(ComparisonLeft), hasRHS(ComparisonRight),
1128 unless(operandsAreEquivalent()),
1129 unless(IsInUnevaluatedContext))
1130 .bind(
"comparisons-of-symbol-and-const")),
1134void RedundantExpressionCheck::checkArithmeticExpr(
1135 const MatchFinder::MatchResult &Result) {
1136 APSInt LhsValue, RhsValue;
1137 const Expr *LhsSymbol =
nullptr, *RhsSymbol =
nullptr;
1138 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1140 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1141 "binop-const-compare-to-sym")) {
1142 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1150 if (LhsOpcode == BO_Add || LhsOpcode == BO_Sub) {
1151 if ((LhsValue != 0 && Opcode == BO_EQ) ||
1152 (LhsValue == 0 && Opcode == BO_NE))
1153 diag(ComparisonOperator->getOperatorLoc(),
1154 "logical expression is always false");
1155 else if ((LhsValue == 0 && Opcode == BO_EQ) ||
1156 (LhsValue != 0 && Opcode == BO_NE))
1157 diag(ComparisonOperator->getOperatorLoc(),
1158 "logical expression is always true");
1160 }
else if (
const auto *ComparisonOperator =
1161 Result.Nodes.getNodeAs<BinaryOperator>(
1162 "binop-const-compare-to-binop-const")) {
1163 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1176 if (LhsOpcode == BO_Add && RhsOpcode == BO_Add) {
1177 if ((Opcode == BO_EQ && APSInt::compareValues(LhsValue, RhsValue) == 0) ||
1178 (Opcode == BO_NE && APSInt::compareValues(LhsValue, RhsValue) != 0)) {
1179 diag(ComparisonOperator->getOperatorLoc(),
1180 "logical expression is always true");
1181 }
else if ((Opcode == BO_EQ &&
1182 APSInt::compareValues(LhsValue, RhsValue) != 0) ||
1184 APSInt::compareValues(LhsValue, RhsValue) == 0)) {
1185 diag(ComparisonOperator->getOperatorLoc(),
1186 "logical expression is always false");
1193 const APSInt &Value) {
1194 return (Opcode == BO_And || Opcode == BO_AndAssign) && Value == 0;
1198 const APSInt &Value) {
1199 return (Opcode == BO_Or || Opcode == BO_OrAssign) && ~Value == 0;
1203 const APSInt &Value) {
1204 return ((Opcode == BO_Or || Opcode == BO_OrAssign) && Value == 0) ||
1205 ((Opcode == BO_And || Opcode == BO_AndAssign) && ~Value == 0);
1208void RedundantExpressionCheck::checkBitwiseExpr(
1209 const MatchFinder::MatchResult &Result) {
1210 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1211 "binop-const-compare-to-const")) {
1212 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1214 APSInt LhsValue, RhsValue;
1215 const Expr *LhsSymbol =
nullptr;
1216 BinaryOperatorKind LhsOpcode{};
1222 const unsigned ConstantWidth =
1223 std::max(LhsValue.getBitWidth(), RhsValue.getBitWidth());
1224 const llvm::APInt LhsConstant = LhsValue.extOrTrunc(ConstantWidth);
1225 const llvm::APInt RhsConstant = RhsValue.extOrTrunc(ConstantWidth);
1226 const SourceLocation Loc = ComparisonOperator->getOperatorLoc();
1229 if (LhsOpcode == BO_And && (LhsConstant & RhsConstant) != RhsConstant) {
1230 if (Opcode == BO_EQ)
1231 diag(Loc,
"logical expression is always false");
1232 else if (Opcode == BO_NE)
1233 diag(Loc,
"logical expression is always true");
1237 if (LhsOpcode == BO_Or && (LhsConstant | RhsConstant) != RhsConstant) {
1238 if (Opcode == BO_EQ)
1239 diag(Loc,
"logical expression is always false");
1240 else if (Opcode == BO_NE)
1241 diag(Loc,
"logical expression is always true");
1243 }
else if (
const auto *IneffectiveOperator =
1244 Result.Nodes.getNodeAs<BinaryOperator>(
1245 "ineffective-bitwise")) {
1247 const Expr *Sym =
nullptr, *ConstExpr =
nullptr;
1254 if ((Value != 0 && ~Value != 0) || Sym->getExprLoc().isMacroID())
1257 const SourceLocation Loc = IneffectiveOperator->getOperatorLoc();
1259 const BinaryOperatorKind Opcode = IneffectiveOperator->getOpcode();
1261 diag(Loc,
"expression always evaluates to 0");
1263 const SourceRange ConstExprRange(ConstExpr->getBeginLoc(),
1264 ConstExpr->getEndLoc());
1265 const StringRef ConstExprText = Lexer::getSourceText(
1266 CharSourceRange::getTokenRange(ConstExprRange), *Result.SourceManager,
1267 Result.Context->getLangOpts());
1269 diag(Loc,
"expression always evaluates to '%0'") << ConstExprText;
1272 const SourceRange SymExprRange(Sym->getBeginLoc(), Sym->getEndLoc());
1274 const StringRef ExprText = Lexer::getSourceText(
1275 CharSourceRange::getTokenRange(SymExprRange), *Result.SourceManager,
1276 Result.Context->getLangOpts());
1278 diag(Loc,
"expression always evaluates to '%0'") << ExprText;
1283void RedundantExpressionCheck::checkRelationalExpr(
1284 const MatchFinder::MatchResult &Result) {
1285 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1286 "comparisons-of-symbol-and-const")) {
1289 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1291 const Expr *LhsExpr =
nullptr, *RhsExpr =
nullptr;
1292 const Expr *LhsSymbol =
nullptr, *RhsSymbol =
nullptr;
1293 const Expr *LhsConst =
nullptr, *RhsConst =
nullptr;
1294 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1295 APSInt LhsValue, RhsValue;
1298 Result,
"lhs", LhsExpr, LhsOpcode, LhsSymbol, LhsValue, LhsConst) ||
1300 Result,
"rhs", RhsExpr, RhsOpcode, RhsSymbol, RhsValue, RhsConst) ||
1305 if (APSInt::compareValues(LhsValue, RhsValue) > 0) {
1306 std::swap(LhsExpr, RhsExpr);
1307 std::swap(LhsValue, RhsValue);
1308 std::swap(LhsSymbol, RhsSymbol);
1309 std::swap(LhsOpcode, RhsOpcode);
1317 if ((Opcode == BO_LAnd || Opcode == BO_LOr) &&
1319 diag(ComparisonOperator->getOperatorLoc(),
1320 "equivalent expression on both sides of logical operator");
1324 if (Opcode == BO_LAnd) {
1326 diag(ComparisonOperator->getOperatorLoc(),
1327 "logical expression is always false");
1329 diag(LhsExpr->getExprLoc(),
"expression is redundant");
1331 diag(RhsExpr->getExprLoc(),
"expression is redundant");
1335 if (Opcode == BO_LOr) {
1337 diag(ComparisonOperator->getOperatorLoc(),
1338 "logical expression is always true");
1340 diag(RhsExpr->getExprLoc(),
"expression is redundant");
1342 diag(LhsExpr->getExprLoc(),
"expression is redundant");
1349 if (
const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>(
"binary")) {
1373 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
1374 const Expr *RHS = BinOp->getRHS()->IgnoreParenImpCasts();
1375 const BinaryOperator::Opcode Op = BinOp->getOpcode();
1376 const bool OpEqualEQorNE = ((Op == BO_EQ) || (Op == BO_NE));
1378 const auto *DeclRef1 = dyn_cast<DeclRefExpr>(LHS);
1379 const auto *DeclRef2 = dyn_cast<DeclRefExpr>(RHS);
1380 const auto *FloatLit1 = dyn_cast<FloatingLiteral>(LHS);
1381 const auto *FloatLit2 = dyn_cast<FloatingLiteral>(RHS);
1383 if (DeclRef1 && DeclRef2 &&
1384 DeclRef1->getType()->hasFloatingRepresentation() &&
1385 DeclRef2->getType()->hasFloatingRepresentation() &&
1386 (DeclRef1->getDecl() == DeclRef2->getDecl()) && OpEqualEQorNE) {
1390 if (FloatLit1 && FloatLit2 &&
1391 FloatLit1->getValue().bitwiseIsEqual(FloatLit2->getValue()) &&
1397 BinOp, Result.Context)) {
1398 const Expr *LhsConst =
nullptr, *RhsConst =
nullptr;
1399 BinaryOperatorKind MainOpcode{}, SideOpcode{};
1402 LhsConst, RhsConst, Result.Context))
1413 diag(BinOp->getOperatorLoc(),
"both sides of operator are equivalent");
1416 if (
const auto *CondOp =
1417 Result.Nodes.getNodeAs<ConditionalOperator>(
"cond")) {
1418 const Expr *TrueExpr = CondOp->getTrueExpr();
1419 const Expr *FalseExpr = CondOp->getFalseExpr();
1424 diag(CondOp->getColonLoc(),
1425 "'true' and 'false' expressions are equivalent");
1428 if (
const auto *Call = Result.Nodes.getNodeAs<CXXOperatorCallExpr>(
"call")) {
1432 diag(Call->getOperatorLoc(),
1433 "both sides of overloaded operator are equivalent");
1436 if (
const auto *Op = Result.Nodes.getNodeAs<Expr>(
"nested-duplicates")) {
1437 const auto *Call = dyn_cast<CXXOperatorCallExpr>(Op);
1442 Call ?
"overloaded operator has equivalent nested operands"
1443 :
"operator has equivalent nested operands";
1445 const auto Diag = diag(Op->getExprLoc(),
Message);
1446 for (
const auto &KeyValue : Result.Nodes.getMap())
1447 if (StringRef(KeyValue.first).starts_with(
"duplicate"))
1448 Diag << KeyValue.second.getSourceRange();
1451 if (
const auto *NegateOperator =
1452 Result.Nodes.getNodeAs<UnaryOperator>(
"logical-bitwise-confusion")) {
1453 const SourceLocation OperatorLoc = NegateOperator->getOperatorLoc();
1457 "ineffective logical negation operator used; did you mean '~'?");
1458 const SourceLocation LogicalNotLocation = OperatorLoc.getLocWithOffset(1);
1460 if (!LogicalNotLocation.isMacroID())
1461 Diag << FixItHint::CreateReplacement(
1462 CharSourceRange::getCharRange(OperatorLoc, LogicalNotLocation),
"~");
1465 if (
const auto *BinaryAndExpr = Result.Nodes.getNodeAs<BinaryOperator>(
1466 "left-right-shift-confusion")) {
1467 const auto *ShiftingConst = Result.Nodes.getNodeAs<Expr>(
"shift-const");
1468 assert(ShiftingConst &&
"Expr* 'ShiftingConst' is nullptr!");
1469 std::optional<llvm::APSInt> ShiftingValue =
1470 ShiftingConst->getIntegerConstantExpr(*Result.Context);
1475 const auto *AndConst = Result.Nodes.getNodeAs<Expr>(
"and-const");
1476 assert(AndConst &&
"Expr* 'AndCont' is nullptr!");
1477 std::optional<llvm::APSInt> AndValue =
1478 AndConst->getIntegerConstantExpr(*Result.Context);
1485 if (AndValue->getActiveBits() > *ShiftingValue)
1488 const auto Diag = diag(BinaryAndExpr->getOperatorLoc(),
1489 "ineffective bitwise and operation");
1497 checkArithmeticExpr(Result);
1505 checkBitwiseExpr(Result);
1513 checkRelationalExpr(Result);
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)