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/FoldingSet.h"
20#include "llvm/ADT/SmallBitVector.h"
21#include "llvm/Support/FormatVariadic.h"
44 return Value < Result;
49 return !Left && !Right;
51 Left = Left->IgnoreParens();
52 Right = Right->IgnoreParens();
55 if (Left->getStmtClass() != Right->getStmtClass())
59 Expr::const_child_iterator LeftIter = Left->child_begin();
60 Expr::const_child_iterator RightIter = Right->child_begin();
61 while (LeftIter != Left->child_end() && RightIter != Right->child_end()) {
63 dyn_cast_or_null<Expr>(*RightIter)))
68 if (LeftIter != Left->child_end() || RightIter != Right->child_end())
72 switch (Left->getStmtClass()) {
76 case Stmt::CharacterLiteralClass:
77 return cast<CharacterLiteral>(Left)->getValue() ==
78 cast<CharacterLiteral>(Right)->getValue();
79 case Stmt::IntegerLiteralClass: {
80 llvm::APInt LeftLit = cast<IntegerLiteral>(Left)->getValue();
81 llvm::APInt RightLit = cast<IntegerLiteral>(Right)->getValue();
82 return LeftLit.getBitWidth() == RightLit.getBitWidth() &&
85 case Stmt::FloatingLiteralClass:
86 return cast<FloatingLiteral>(Left)->getValue().bitwiseIsEqual(
87 cast<FloatingLiteral>(Right)->getValue());
88 case Stmt::StringLiteralClass:
89 return cast<StringLiteral>(Left)->getBytes() ==
90 cast<StringLiteral>(Right)->getBytes();
91 case Stmt::CXXOperatorCallExprClass:
92 return cast<CXXOperatorCallExpr>(Left)->getOperator() ==
93 cast<CXXOperatorCallExpr>(Right)->getOperator();
94 case Stmt::DependentScopeDeclRefExprClass:
95 if (cast<DependentScopeDeclRefExpr>(Left)->getDeclName() !=
96 cast<DependentScopeDeclRefExpr>(Right)->getDeclName())
98 return cast<DependentScopeDeclRefExpr>(Left)->getQualifier() ==
99 cast<DependentScopeDeclRefExpr>(Right)->getQualifier();
100 case Stmt::DeclRefExprClass:
101 return cast<DeclRefExpr>(Left)->getDecl() ==
102 cast<DeclRefExpr>(Right)->getDecl();
103 case Stmt::MemberExprClass:
104 return cast<MemberExpr>(Left)->getMemberDecl() ==
105 cast<MemberExpr>(Right)->getMemberDecl();
106 case Stmt::CXXFoldExprClass:
107 return cast<CXXFoldExpr>(Left)->getOperator() ==
108 cast<CXXFoldExpr>(Right)->getOperator();
109 case Stmt::CXXFunctionalCastExprClass:
110 case Stmt::CStyleCastExprClass:
111 return cast<ExplicitCastExpr>(Left)->getTypeAsWritten() ==
112 cast<ExplicitCastExpr>(Right)->getTypeAsWritten();
113 case Stmt::CallExprClass:
114 case Stmt::ImplicitCastExprClass:
115 case Stmt::ArraySubscriptExprClass:
117 case Stmt::UnaryOperatorClass:
118 if (cast<UnaryOperator>(Left)->isIncrementDecrementOp())
120 return cast<UnaryOperator>(Left)->getOpcode() ==
121 cast<UnaryOperator>(Right)->getOpcode();
122 case Stmt::BinaryOperatorClass:
123 if (cast<BinaryOperator>(Left)->isAssignmentOp())
125 return cast<BinaryOperator>(Left)->getOpcode() ==
126 cast<BinaryOperator>(Right)->getOpcode();
127 case Stmt::UnaryExprOrTypeTraitExprClass:
128 const auto *LeftUnaryExpr = cast<UnaryExprOrTypeTraitExpr>(Left);
129 const auto *RightUnaryExpr = cast<UnaryExprOrTypeTraitExpr>(Right);
130 if (LeftUnaryExpr->isArgumentType() && RightUnaryExpr->isArgumentType())
131 return LeftUnaryExpr->getKind() == RightUnaryExpr->getKind() &&
132 LeftUnaryExpr->getArgumentType() ==
133 RightUnaryExpr->getArgumentType();
134 if (!LeftUnaryExpr->isArgumentType() && !RightUnaryExpr->isArgumentType())
136 RightUnaryExpr->getArgumentExpr());
145 const APSInt &ValueLHS,
146 BinaryOperatorKind OpcodeRHS,
147 const APSInt &ValueRHS) {
148 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
149 "Values must be ordered");
151 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0)
152 return OpcodeLHS == OpcodeRHS;
155 APSInt ValueLhsPlus1;
156 return ((OpcodeLHS == BO_LE && OpcodeRHS == BO_LT) ||
157 (OpcodeLHS == BO_GT && OpcodeRHS == BO_GE)) &&
159 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0;
165 const APSInt &ValueLHS,
166 BinaryOperatorKind OpcodeRHS,
167 const APSInt &ValueRHS) {
168 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
169 "Values must be ordered");
172 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
175 return OpcodeRHS == BO_NE || OpcodeRHS == BO_GT || OpcodeRHS == BO_LT;
177 return OpcodeRHS == BO_EQ;
179 return OpcodeRHS == BO_GT;
181 return OpcodeRHS == BO_LT;
183 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
185 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
192 if ((OpcodeLHS == BO_EQ || OpcodeLHS == BO_LT || OpcodeLHS == BO_LE) &&
193 (OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE))
197 APSInt ValueLhsPlus1;
198 if (OpcodeLHS == BO_GT && OpcodeRHS == BO_LT &&
200 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
209 const APSInt &ValueLHS,
210 BinaryOperatorKind OpcodeRHS,
211 const APSInt &ValueRHS) {
212 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
213 "Values must be ordered");
216 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
219 return OpcodeRHS == BO_NE;
221 return OpcodeRHS == BO_EQ;
223 return OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
225 return OpcodeRHS == BO_GE;
227 return OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
229 return OpcodeRHS == BO_LE;
236 APSInt ValueLhsPlus1;
237 if (OpcodeLHS == BO_LE && OpcodeRHS == BO_GE &&
239 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
243 if ((OpcodeLHS == BO_GT || OpcodeLHS == BO_GE) &&
244 (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE))
249 if (OpcodeLHS == BO_NE && OpcodeRHS == BO_NE)
256 const APSInt &ValueLHS,
257 BinaryOperatorKind OpcodeRHS,
258 const APSInt &ValueRHS) {
259 int Comparison = APSInt::compareValues(ValueLHS, ValueRHS);
262 return OpcodeRHS == BO_EQ && Comparison == 0;
264 return (OpcodeRHS == BO_NE && Comparison == 0) ||
265 (OpcodeRHS == BO_EQ && Comparison != 0) ||
266 (OpcodeRHS == BO_LT && Comparison >= 0) ||
267 (OpcodeRHS == BO_LE && Comparison > 0) ||
268 (OpcodeRHS == BO_GT && Comparison <= 0) ||
269 (OpcodeRHS == BO_GE && Comparison < 0);
272 return ((OpcodeRHS == BO_LT && Comparison >= 0) ||
273 (OpcodeRHS == BO_LE && Comparison > 0) ||
274 (OpcodeRHS == BO_EQ && Comparison > 0));
276 return ((OpcodeRHS == BO_GT && Comparison <= 0) ||
277 (OpcodeRHS == BO_GE && Comparison < 0) ||
278 (OpcodeRHS == BO_EQ && Comparison < 0));
280 return (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE || OpcodeRHS == BO_EQ) &&
283 return (OpcodeRHS == BO_GT || OpcodeRHS == BO_GE || OpcodeRHS == BO_EQ) &&
292 if (Opcode == BO_Sub) {
299static OverloadedOperatorKind
getOp(
const BinaryOperator *Op) {
300 return BinaryOperator::getOverloadedOperator(Op->getOpcode());
303static OverloadedOperatorKind
getOp(
const CXXOperatorCallExpr *Op) {
304 if (Op->getNumArgs() != 2)
306 return Op->getOperator();
309static std::pair<const Expr *, const Expr *>
311 return {Op->getLHS()->IgnoreParenImpCasts(),
312 Op->getRHS()->IgnoreParenImpCasts()};
315static std::pair<const Expr *, const Expr *>
317 return {Op->getArg(0)->IgnoreParenImpCasts(),
318 Op->getArg(1)->IgnoreParenImpCasts()};
321template <
typename TExpr>
323 OverloadedOperatorKind OpKind) {
324 const auto *AsTExpr = dyn_cast_or_null<TExpr>(TheExpr);
325 if (AsTExpr &&
getOp(AsTExpr) == OpKind)
333template <
typename TExpr,
unsigned N>
335 SmallVector<const Expr *, N> &AllOperands,
336 OverloadedOperatorKind OpKind) {
338 const std::pair<const Expr *, const Expr *> Operands =
getOperands(BinOp);
345 AllOperands.push_back(Part);
349template <
typename TExpr>
351 OverloadedOperatorKind OpKind,
352 ASTContext &Context) {
354 const DynTypedNodeList Parents = Context.getParents(*TheExpr);
355 for (DynTypedNode DynParent : Parents) {
356 if (
const auto *Parent = DynParent.get<Expr>()) {
357 bool Skip = isa<ParenExpr>(Parent) || isa<ImplicitCastExpr>(Parent) ||
358 isa<FullExpr>(Parent) ||
359 isa<MaterializeTemporaryExpr>(Parent);
370template <
typename TExpr>
373 ast_matchers::internal::BoundNodesTreeBuilder *Builder,
374 ASTContext &Context) {
375 const OverloadedOperatorKind OpKind =
getOp(TheExpr);
376 if (OpKind == OO_None)
380 const std::pair<const Expr *, const Expr *> Operands =
getOperands(TheExpr);
390 SmallVector<const Expr *, 4> AllOperands;
395 size_t NumOperands = AllOperands.size();
396 llvm::SmallBitVector Duplicates(NumOperands);
397 for (
size_t I = 0; I < NumOperands; I++) {
400 bool FoundDuplicates =
false;
402 for (
size_t J = I + 1; J < NumOperands; J++) {
403 if (AllOperands[J]->HasSideEffects(Context))
407 FoundDuplicates =
true;
409 Builder->setBinding(SmallString<11>(llvm::formatv(
"duplicate{0}", J)),
410 DynTypedNode::create(*AllOperands[J]));
415 Builder->setBinding(SmallString<11>(llvm::formatv(
"duplicate{0}", I)),
416 DynTypedNode::create(*AllOperands[I]));
419 return Duplicates.any();
425 if (Node.isInstantiationDependent())
427 return Node.isIntegerConstantExpr(Finder->getASTContext());
430AST_MATCHER(BinaryOperator, operandsAreEquivalent) {
434AST_MATCHER(BinaryOperator, nestedOperandsAreEquivalent) {
438AST_MATCHER(ConditionalOperator, expressionsAreEquivalent) {
443 return Node.getNumArgs() == 2 &&
447AST_MATCHER(CXXOperatorCallExpr, nestedParametersAreEquivalent) {
451AST_MATCHER(BinaryOperator, binaryOperatorIsInMacro) {
452 return Node.getOperatorLoc().isMacroID();
455AST_MATCHER(ConditionalOperator, conditionalOperatorIsInMacro) {
456 return Node.getQuestionLoc().isMacroID() || Node.getColonLoc().isMacroID();
459AST_MATCHER(Expr, isMacro) {
return Node.getExprLoc().isMacroID(); }
461AST_MATCHER_P(Expr, expandedByMacro, ArrayRef<llvm::StringLiteral>, Names) {
462 const SourceManager &SM = Finder->getASTContext().getSourceManager();
463 const LangOptions &LO = Finder->getASTContext().getLangOpts();
464 SourceLocation Loc = Node.getExprLoc();
465 while (Loc.isMacroID()) {
466 StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LO);
467 if (llvm::is_contained(Names, MacroName))
469 Loc = SM.getImmediateMacroCallerLoc(Loc);
477static ast_matchers::internal::Matcher<Expr>
479 std::string CstId = (Id +
"-const").str();
480 return expr(isIntegerConstantExpr()).bind(CstId);
487 StringRef Id, APSInt &
Value,
488 const Expr *&ConstExpr) {
489 std::string CstId = (Id +
"-const").str();
490 ConstExpr = Result.Nodes.getNodeAs<Expr>(CstId);
493 std::optional<llvm::APSInt> R =
494 ConstExpr->getIntegerConstantExpr(*Result.Context);
503 StringRef Id, APSInt &
Value) {
504 const Expr *ConstExpr =
nullptr;
511 std::string SymId = (Id +
"-sym").str();
512 return ignoringParenImpCasts(
513 expr(unless(isIntegerConstantExpr())).bind(SymId));
519 StringRef Id,
const Expr *&SymExpr) {
520 std::string SymId = (Id +
"-sym").str();
521 if (
const auto *Node = Result.Nodes.getNodeAs<Expr>(SymId)) {
530static ast_matchers::internal::Matcher<Expr>
532 const auto BinOpCstExpr =
533 expr(anyOf(binaryOperator(hasAnyOperatorName(
"+",
"|",
"&"),
536 binaryOperator(hasOperatorName(
"-"),
540 return ignoringParenImpCasts(BinOpCstExpr);
547 StringRef Id, BinaryOperatorKind &Opcode,
548 const Expr *&Symbol, APSInt &
Value) {
549 if (
const auto *BinExpr = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
550 Opcode = BinExpr->getOpcode();
558static ast_matchers::internal::Matcher<Expr>
560 std::string CastId = (Id +
"-cast").str();
561 std::string SwapId = (Id +
"-swap").str();
562 std::string NegateId = (Id +
"-negate").str();
563 std::string OverloadId = (Id +
"-overload").str();
564 std::string ConstId = (Id +
"-const").str();
566 const auto RelationalExpr = ignoringParenImpCasts(binaryOperator(
567 isComparisonOperator(), expr().bind(Id),
575 const auto CastExpr =
576 implicitCastExpr(hasCastKind(CK_IntegralToBoolean),
580 const auto NegateRelationalExpr =
581 unaryOperator(hasOperatorName(
"!"),
582 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))
586 const auto NegateNegateRelationalExpr =
587 unaryOperator(hasOperatorName(
"!"),
588 hasUnaryOperand(unaryOperator(
589 hasOperatorName(
"!"),
590 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))));
592 const auto OverloadedOperatorExpr =
594 hasAnyOverloadedOperatorName(
"==",
"!=",
"<",
"<=",
">",
">="),
596 unless(isMacro()), unless(isInTemplateInstantiation()),
597 anyOf(hasLHS(ignoringParenImpCasts(integerLiteral().bind(ConstId))),
598 hasRHS(ignoringParenImpCasts(integerLiteral().bind(ConstId)))))
601 return anyOf(RelationalExpr, CastExpr, NegateRelationalExpr,
602 NegateNegateRelationalExpr, OverloadedOperatorExpr);
608 return ParamType->isReferenceType() &&
609 !ParamType.getNonReferenceType().isConstQualified();
620 bool CheckSecondParam) {
621 const auto *OperatorDecl =
622 dyn_cast_or_null<FunctionDecl>(OperatorCall->getCalleeDecl());
628 unsigned ParamCount = OperatorDecl->getNumParams();
633 if (ParamCount == 1 &&
634 !OperatorDecl->getType()->castAs<FunctionType>()->isConst())
640 return CheckSecondParam && ParamCount == 2 &&
647 const MatchFinder::MatchResult &Result, StringRef Id,
648 const Expr *&OperandExpr, BinaryOperatorKind &Opcode,
const Expr *&Symbol,
649 APSInt &
Value,
const Expr *&ConstExpr) {
650 std::string CastId = (Id +
"-cast").str();
651 std::string SwapId = (Id +
"-swap").str();
652 std::string NegateId = (Id +
"-negate").str();
653 std::string OverloadId = (Id +
"-overload").str();
655 if (
const auto *Bin = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
657 Opcode = Bin->getOpcode();
662 }
else if (
const auto *Cast = Result.Nodes.getNodeAs<CastExpr>(CastId)) {
666 Value = APSInt(32,
false);
667 }
else if (
const auto *OverloadedOperatorExpr =
668 Result.Nodes.getNodeAs<CXXOperatorCallExpr>(OverloadId)) {
672 bool IntegerConstantIsFirstArg =
false;
674 if (
const auto *Arg = OverloadedOperatorExpr->getArg(1)) {
675 if (!Arg->isValueDependent() &&
676 !Arg->isIntegerConstantExpr(*Result.Context)) {
677 IntegerConstantIsFirstArg =
true;
678 if (
const auto *Arg = OverloadedOperatorExpr->getArg(0)) {
679 if (!Arg->isValueDependent() &&
680 !Arg->isIntegerConstantExpr(*Result.Context))
688 Symbol = OverloadedOperatorExpr->getArg(IntegerConstantIsFirstArg ? 1 : 0);
689 OperandExpr = OverloadedOperatorExpr;
690 Opcode = BinaryOperator::getOverloadedOpcode(
691 OverloadedOperatorExpr->getOperator());
696 if (!BinaryOperator::isComparisonOp(Opcode))
701 if (IntegerConstantIsFirstArg)
702 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
712 if (Result.Nodes.getNodeAs<Expr>(SwapId))
713 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
714 if (Result.Nodes.getNodeAs<Expr>(NegateId))
715 Opcode = BinaryOperator::negateComparisonOp(Opcode);
721 const ASTContext *AstCtx) {
722 const auto *LhsBinOp = dyn_cast<BinaryOperator>(BinOp->getLHS());
723 const auto *RhsBinOp = dyn_cast<BinaryOperator>(BinOp->getRHS());
725 if (!LhsBinOp || !RhsBinOp)
728 auto IsIntegerConstantExpr = [AstCtx](
const Expr *E) {
729 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
732 if ((IsIntegerConstantExpr(LhsBinOp->getLHS()) ||
733 IsIntegerConstantExpr(LhsBinOp->getRHS())) &&
734 (IsIntegerConstantExpr(RhsBinOp->getLHS()) ||
735 IsIntegerConstantExpr(RhsBinOp->getRHS())))
741 const BinaryOperator *&BinOp,
const ASTContext *AstCtx) {
745 const Expr *Lhs = BinOp->getLHS();
746 const Expr *Rhs = BinOp->getRHS();
751 auto IsDefineExpr = [AstCtx](
const Expr *E) {
752 const SourceRange Lsr = E->getSourceRange();
753 if (!Lsr.getBegin().isMacroID() || E->isValueDependent() ||
754 !E->isIntegerConstantExpr(*AstCtx))
759 return IsDefineExpr(Lhs) || IsDefineExpr(Rhs);
766 BinaryOperatorKind &MainOpcode,
767 BinaryOperatorKind &SideOpcode,
768 const Expr *&LhsConst,
769 const Expr *&RhsConst,
770 const ASTContext *AstCtx) {
772 "Both sides of binary operator must be constant expressions!");
774 MainOpcode = BinOp->getOpcode();
776 const auto *BinOpLhs = cast<BinaryOperator>(BinOp->getLHS());
777 const auto *BinOpRhs = cast<BinaryOperator>(BinOp->getRHS());
779 auto IsIntegerConstantExpr = [AstCtx](
const Expr *E) {
780 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
783 LhsConst = IsIntegerConstantExpr(BinOpLhs->getLHS()) ? BinOpLhs->getLHS()
784 : BinOpLhs->getRHS();
785 RhsConst = IsIntegerConstantExpr(BinOpRhs->getLHS()) ? BinOpRhs->getLHS()
786 : BinOpRhs->getRHS();
788 if (!LhsConst || !RhsConst)
791 assert(BinOpLhs->getOpcode() == BinOpRhs->getOpcode() &&
792 "Sides of the binary operator must be equivalent expressions!");
794 SideOpcode = BinOpLhs->getOpcode();
800 const SourceManager &SM) {
801 if (T1.getKind() != T2.getKind())
803 if (T1.isNot(tok::raw_identifier))
805 if (T1.getLength() != T2.getLength())
807 return StringRef(SM.getCharacterData(T1.getLocation()), T1.getLength()) ==
808 StringRef(SM.getCharacterData(T2.getLocation()), T2.getLength());
812 const SourceManager &SM) {
813 return SM.getExpansionLoc(ExprSR.getEnd()) == T.getLocation();
821 const ASTContext *AstCtx) {
822 if (!LhsExpr || !RhsExpr)
824 const SourceRange Lsr = LhsExpr->getSourceRange();
825 const SourceRange Rsr = RhsExpr->getSourceRange();
826 if (!Lsr.getBegin().isMacroID() || !Rsr.getBegin().isMacroID())
829 const SourceManager &SM = AstCtx->getSourceManager();
830 const LangOptions &LO = AstCtx->getLangOpts();
832 std::pair<FileID, unsigned> LsrLocInfo =
833 SM.getDecomposedLoc(SM.getExpansionLoc(Lsr.getBegin()));
834 std::pair<FileID, unsigned> RsrLocInfo =
835 SM.getDecomposedLoc(SM.getExpansionLoc(Rsr.getBegin()));
836 llvm::MemoryBufferRef MB = SM.getBufferOrFake(LsrLocInfo.first);
838 const char *LTokenPos = MB.getBufferStart() + LsrLocInfo.second;
839 const char *RTokenPos = MB.getBufferStart() + RsrLocInfo.second;
840 Lexer LRawLex(SM.getLocForStartOfFile(LsrLocInfo.first), LO,
841 MB.getBufferStart(), LTokenPos, MB.getBufferEnd());
842 Lexer RRawLex(SM.getLocForStartOfFile(RsrLocInfo.first), LO,
843 MB.getBufferStart(), RTokenPos, MB.getBufferEnd());
847 LRawLex.LexFromRawLexer(LTok);
848 RRawLex.LexFromRawLexer(RTok);
849 }
while (!LTok.is(tok::eof) && !RTok.is(tok::eof) &&
859 const Expr *&RhsExpr) {
860 if (!LhsExpr || !RhsExpr)
863 const SourceLocation LhsLoc = LhsExpr->getExprLoc();
864 const SourceLocation RhsLoc = RhsExpr->getExprLoc();
866 return LhsLoc.isMacroID() != RhsLoc.isMacroID();
870 const llvm::StringRef Right) {
875 llvm::StringRef L = Left.trim();
876 llvm::StringRef R = Right.trim();
877 while (!L.empty() && !R.empty()) {
880 if (L.empty() && R.empty())
883 if (L.front() != R.front())
888 return L.empty() && R.empty();
892 const ASTContext *Context) {
897 const Expr *Lhs = BinOp->getLHS();
898 const Expr *Rhs = BinOp->getRHS();
899 const SourceManager &SM = Context->getSourceManager();
901 const SourceRange Lsr = Lhs->getSourceRange();
902 const SourceRange Rsr = Rhs->getSourceRange();
903 if (Lsr.getBegin().isMacroID()) {
905 if (Rsr.getBegin().isMacroID()) {
907 const llvm::StringRef L = Lexer::getSourceText(
908 CharSourceRange::getTokenRange(Lsr), SM, Context->getLangOpts());
909 const llvm::StringRef R = Lexer::getSourceText(
910 CharSourceRange::getTokenRange(Rsr), SM, Context->getLangOpts());
916 const auto *Lil = dyn_cast<IntegerLiteral>(Lhs);
917 const auto *Ril = dyn_cast<IntegerLiteral>(Rhs);
919 return Lil->getValue() == Ril->getValue();
921 const auto *Lbl = dyn_cast<CXXBoolLiteralExpr>(Lhs);
922 const auto *Rbl = dyn_cast<CXXBoolLiteralExpr>(Rhs);
924 return Lbl->getValue() == Rbl->getValue();
930 const auto BannedIntegerLiteral =
932 const auto IsInUnevaluatedContext = expr(anyOf(
933 hasAncestor(expr(hasUnevaluatedContext())), hasAncestor(typeLoc())));
938 binaryOperator(anyOf(isComparisonOperator(),
939 hasAnyOperatorName(
"-",
"/",
"%",
"|",
"&",
940 "^",
"&&",
"||",
"=")),
941 operandsAreEquivalent(),
943 unless(isInTemplateInstantiation()),
944 unless(binaryOperatorIsInMacro()),
945 unless(hasAncestor(arraySubscriptExpr())),
946 unless(hasDescendant(BannedIntegerLiteral)),
947 unless(IsInUnevaluatedContext))
954 binaryOperator(hasAnyOperatorName(
"|",
"&",
"||",
"&&",
"^"),
955 nestedOperandsAreEquivalent(),
957 unless(isInTemplateInstantiation()),
958 unless(binaryOperatorIsInMacro()),
960 unless(hasDescendant(BannedIntegerLiteral)),
961 unless(IsInUnevaluatedContext))
962 .bind(
"nested-duplicates"),
968 conditionalOperator(expressionsAreEquivalent(),
970 unless(conditionalOperatorIsInMacro()),
971 unless(isInTemplateInstantiation()),
972 unless(IsInUnevaluatedContext))
980 hasAnyOverloadedOperatorName(
"-",
"/",
"%",
"|",
"&",
"^",
981 "==",
"!=",
"<",
"<=",
">",
982 ">=",
"&&",
"||",
"="),
983 parametersAreEquivalent(),
985 unless(isMacro()), unless(isInTemplateInstantiation()),
986 unless(IsInUnevaluatedContext))
993 hasAnyOverloadedOperatorName(
"|",
"&",
"||",
"&&",
"^"),
994 nestedParametersAreEquivalent(), argumentCountIs(2),
996 unless(isMacro()), unless(isInTemplateInstantiation()),
997 unless(IsInUnevaluatedContext))
998 .bind(
"nested-duplicates"),
1005 hasImplicitDestinationType(isInteger()),
1007 hasOperatorName(
"!"),
1008 hasUnaryOperand(ignoringParenImpCasts(binaryOperator(
1009 hasAnyOperatorName(
"|",
"&"),
1011 binaryOperator(hasAnyOperatorName(
"|",
"&")),
1013 hasRHS(integerLiteral())))))
1014 .bind(
"logical-bitwise-confusion")),
1015 unless(IsInUnevaluatedContext))),
1022 hasOperatorName(
"&"),
1023 hasOperands(ignoringParenImpCasts(binaryOperator(
1024 hasOperatorName(
"<<"),
1025 hasRHS(ignoringParenImpCasts(
1026 integerLiteral().bind(
"shift-const"))))),
1027 ignoringParenImpCasts(
1028 integerLiteral().bind(
"and-const"))),
1029 unless(IsInUnevaluatedContext))
1030 .bind(
"left-right-shift-confusion")),
1046 traverse(TK_AsIs, binaryOperator(isComparisonOperator(),
1047 hasOperands(BinOpCstLeft, CstRight),
1048 unless(IsInUnevaluatedContext))
1049 .bind(
"binop-const-compare-to-const")),
1056 binaryOperator(isComparisonOperator(),
1057 anyOf(allOf(hasLHS(BinOpCstLeft), hasRHS(SymRight)),
1058 allOf(hasLHS(SymRight), hasRHS(BinOpCstLeft))),
1059 unless(IsInUnevaluatedContext))
1060 .bind(
"binop-const-compare-to-sym")),
1066 binaryOperator(isComparisonOperator(), hasLHS(BinOpCstLeft),
1067 hasRHS(BinOpCstRight),
1069 unless(operandsAreEquivalent()),
1070 unless(IsInUnevaluatedContext))
1071 .bind(
"binop-const-compare-to-binop-const")),
1083 binaryOperator(hasAnyOperatorName(
"||",
"&&"),
1084 hasLHS(ComparisonLeft), hasRHS(ComparisonRight),
1086 unless(operandsAreEquivalent()),
1087 unless(IsInUnevaluatedContext))
1088 .bind(
"comparisons-of-symbol-and-const")),
1092void RedundantExpressionCheck::checkArithmeticExpr(
1093 const MatchFinder::MatchResult &Result) {
1094 APSInt LhsValue, RhsValue;
1095 const Expr *LhsSymbol =
nullptr, *RhsSymbol =
nullptr;
1096 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1098 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1099 "binop-const-compare-to-sym")) {
1100 BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1108 if (LhsOpcode == BO_Add || LhsOpcode == BO_Sub) {
1109 if ((LhsValue != 0 && Opcode == BO_EQ) ||
1110 (LhsValue == 0 && Opcode == BO_NE))
1111 diag(ComparisonOperator->getOperatorLoc(),
1112 "logical expression is always false");
1113 else if ((LhsValue == 0 && Opcode == BO_EQ) ||
1114 (LhsValue != 0 && Opcode == BO_NE))
1115 diag(ComparisonOperator->getOperatorLoc(),
1116 "logical expression is always true");
1118 }
else if (
const auto *ComparisonOperator =
1119 Result.Nodes.getNodeAs<BinaryOperator>(
1120 "binop-const-compare-to-binop-const")) {
1121 BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1134 if (LhsOpcode == BO_Add && RhsOpcode == BO_Add) {
1135 if ((Opcode == BO_EQ && APSInt::compareValues(LhsValue, RhsValue) == 0) ||
1136 (Opcode == BO_NE && APSInt::compareValues(LhsValue, RhsValue) != 0)) {
1137 diag(ComparisonOperator->getOperatorLoc(),
1138 "logical expression is always true");
1139 }
else if ((Opcode == BO_EQ &&
1140 APSInt::compareValues(LhsValue, RhsValue) != 0) ||
1142 APSInt::compareValues(LhsValue, RhsValue) == 0)) {
1143 diag(ComparisonOperator->getOperatorLoc(),
1144 "logical expression is always false");
1151 return (Opcode == BO_And || Opcode == BO_AndAssign) &&
Value == 0;
1156 return (Opcode == BO_Or || Opcode == BO_OrAssign) &&
~Value == 0;
1160 return ((Opcode == BO_Or || Opcode == BO_OrAssign) &&
Value == 0) ||
1161 ((Opcode == BO_And || Opcode == BO_AndAssign) &&
~Value == 0);
1164void RedundantExpressionCheck::checkBitwiseExpr(
1165 const MatchFinder::MatchResult &Result) {
1166 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1167 "binop-const-compare-to-const")) {
1168 BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1170 APSInt LhsValue, RhsValue;
1171 const Expr *LhsSymbol =
nullptr;
1172 BinaryOperatorKind LhsOpcode{};
1178 uint64_t LhsConstant = LhsValue.getZExtValue();
1179 uint64_t RhsConstant = RhsValue.getZExtValue();
1180 SourceLocation Loc = ComparisonOperator->getOperatorLoc();
1183 if (LhsOpcode == BO_And && (LhsConstant & RhsConstant) != RhsConstant) {
1184 if (Opcode == BO_EQ)
1185 diag(Loc,
"logical expression is always false");
1186 else if (Opcode == BO_NE)
1187 diag(Loc,
"logical expression is always true");
1191 if (LhsOpcode == BO_Or && (LhsConstant | RhsConstant) != RhsConstant) {
1192 if (Opcode == BO_EQ)
1193 diag(Loc,
"logical expression is always false");
1194 else if (Opcode == BO_NE)
1195 diag(Loc,
"logical expression is always true");
1197 }
else if (
const auto *IneffectiveOperator =
1198 Result.Nodes.getNodeAs<BinaryOperator>(
1199 "ineffective-bitwise")) {
1201 const Expr *Sym =
nullptr, *ConstExpr =
nullptr;
1208 if ((
Value != 0 && ~
Value != 0) || Sym->getExprLoc().isMacroID())
1211 SourceLocation Loc = IneffectiveOperator->getOperatorLoc();
1213 BinaryOperatorKind Opcode = IneffectiveOperator->getOpcode();
1215 diag(Loc,
"expression always evaluates to 0");
1217 SourceRange ConstExprRange(ConstExpr->getBeginLoc(),
1218 ConstExpr->getEndLoc());
1219 StringRef ConstExprText = Lexer::getSourceText(
1220 CharSourceRange::getTokenRange(ConstExprRange), *Result.SourceManager,
1221 Result.Context->getLangOpts());
1223 diag(Loc,
"expression always evaluates to '%0'") << ConstExprText;
1226 SourceRange SymExprRange(Sym->getBeginLoc(), Sym->getEndLoc());
1228 StringRef ExprText = Lexer::getSourceText(
1229 CharSourceRange::getTokenRange(SymExprRange), *Result.SourceManager,
1230 Result.Context->getLangOpts());
1232 diag(Loc,
"expression always evaluates to '%0'") << ExprText;
1237void RedundantExpressionCheck::checkRelationalExpr(
1238 const MatchFinder::MatchResult &Result) {
1239 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1240 "comparisons-of-symbol-and-const")) {
1243 BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1245 const Expr *LhsExpr =
nullptr, *RhsExpr =
nullptr;
1246 const Expr *LhsSymbol =
nullptr, *RhsSymbol =
nullptr;
1247 const Expr *LhsConst =
nullptr, *RhsConst =
nullptr;
1248 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1249 APSInt LhsValue, RhsValue;
1252 Result,
"lhs", LhsExpr, LhsOpcode, LhsSymbol, LhsValue, LhsConst) ||
1254 Result,
"rhs", RhsExpr, RhsOpcode, RhsSymbol, RhsValue, RhsConst) ||
1259 if (APSInt::compareValues(LhsValue, RhsValue) > 0) {
1260 std::swap(LhsExpr, RhsExpr);
1261 std::swap(LhsValue, RhsValue);
1262 std::swap(LhsSymbol, RhsSymbol);
1263 std::swap(LhsOpcode, RhsOpcode);
1271 if ((Opcode == BO_LAnd || Opcode == BO_LOr) &&
1273 diag(ComparisonOperator->getOperatorLoc(),
1274 "equivalent expression on both sides of logical operator");
1278 if (Opcode == BO_LAnd) {
1280 diag(ComparisonOperator->getOperatorLoc(),
1281 "logical expression is always false");
1283 diag(LhsExpr->getExprLoc(),
"expression is redundant");
1285 diag(RhsExpr->getExprLoc(),
"expression is redundant");
1289 if (Opcode == BO_LOr) {
1291 diag(ComparisonOperator->getOperatorLoc(),
1292 "logical expression is always true");
1294 diag(RhsExpr->getExprLoc(),
"expression is redundant");
1296 diag(LhsExpr->getExprLoc(),
"expression is redundant");
1303 if (
const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>(
"binary")) {
1327 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
1328 const Expr *RHS = BinOp->getRHS()->IgnoreParenImpCasts();
1329 const BinaryOperator::Opcode Op = BinOp->getOpcode();
1330 const bool OpEqualEQorNE = ((Op == BO_EQ) || (Op == BO_NE));
1332 const auto *DeclRef1 = dyn_cast<DeclRefExpr>(LHS);
1333 const auto *DeclRef2 = dyn_cast<DeclRefExpr>(RHS);
1334 const auto *FloatLit1 = dyn_cast<FloatingLiteral>(LHS);
1335 const auto *FloatLit2 = dyn_cast<FloatingLiteral>(RHS);
1337 if (DeclRef1 && DeclRef2 &&
1338 DeclRef1->getType()->hasFloatingRepresentation() &&
1339 DeclRef2->getType()->hasFloatingRepresentation() &&
1340 (DeclRef1->getDecl() == DeclRef2->getDecl()) && OpEqualEQorNE) {
1344 if (FloatLit1 && FloatLit2 &&
1345 FloatLit1->getValue().bitwiseIsEqual(FloatLit2->getValue()) &&
1351 BinOp, Result.Context)) {
1352 const Expr *LhsConst =
nullptr, *RhsConst =
nullptr;
1353 BinaryOperatorKind MainOpcode{}, SideOpcode{};
1356 LhsConst, RhsConst, Result.Context))
1367 diag(BinOp->getOperatorLoc(),
"both sides of operator are equivalent");
1370 if (
const auto *CondOp =
1371 Result.Nodes.getNodeAs<ConditionalOperator>(
"cond")) {
1372 const Expr *TrueExpr = CondOp->getTrueExpr();
1373 const Expr *FalseExpr = CondOp->getFalseExpr();
1378 diag(CondOp->getColonLoc(),
1379 "'true' and 'false' expressions are equivalent");
1382 if (
const auto *Call = Result.Nodes.getNodeAs<CXXOperatorCallExpr>(
"call")) {
1386 diag(Call->getOperatorLoc(),
1387 "both sides of overloaded operator are equivalent");
1390 if (
const auto *Op = Result.Nodes.getNodeAs<Expr>(
"nested-duplicates")) {
1391 const auto *Call = dyn_cast<CXXOperatorCallExpr>(Op);
1396 Call ?
"overloaded operator has equivalent nested operands"
1397 :
"operator has equivalent nested operands";
1399 const auto Diag = diag(Op->getExprLoc(),
Message);
1400 for (
const auto &KeyValue : Result.Nodes.getMap()) {
1401 if (StringRef(KeyValue.first).starts_with(
"duplicate"))
1402 Diag << KeyValue.second.getSourceRange();
1406 if (
const auto *NegateOperator =
1407 Result.Nodes.getNodeAs<UnaryOperator>(
"logical-bitwise-confusion")) {
1408 SourceLocation OperatorLoc = NegateOperator->getOperatorLoc();
1412 "ineffective logical negation operator used; did you mean '~'?");
1413 SourceLocation LogicalNotLocation = OperatorLoc.getLocWithOffset(1);
1415 if (!LogicalNotLocation.isMacroID())
1416 Diag << FixItHint::CreateReplacement(
1417 CharSourceRange::getCharRange(OperatorLoc, LogicalNotLocation),
"~");
1420 if (
const auto *BinaryAndExpr = Result.Nodes.getNodeAs<BinaryOperator>(
1421 "left-right-shift-confusion")) {
1422 const auto *ShiftingConst = Result.Nodes.getNodeAs<Expr>(
"shift-const");
1423 assert(ShiftingConst &&
"Expr* 'ShiftingConst' is nullptr!");
1424 std::optional<llvm::APSInt> ShiftingValue =
1425 ShiftingConst->getIntegerConstantExpr(*Result.Context);
1430 const auto *AndConst = Result.Nodes.getNodeAs<Expr>(
"and-const");
1431 assert(AndConst &&
"Expr* 'AndCont' is nullptr!");
1432 std::optional<llvm::APSInt> AndValue =
1433 AndConst->getIntegerConstantExpr(*Result.Context);
1440 if (AndValue->getActiveBits() > *ShiftingValue)
1443 auto Diag = diag(BinaryAndExpr->getOperatorLoc(),
1444 "ineffective bitwise and operation");
1452 checkArithmeticExpr(Result);
1460 checkBitwiseExpr(Result);
1468 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 llvm::StringLiteral 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 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 bool exprEvaluatesToSymbolic(BinaryOperatorKind Opcode, APSInt Value)
static ast_matchers::internal::Matcher< Expr > matchSymbolicExpr(StringRef Id)
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 areStringsSameIgnoreSpaces(const llvm::StringRef Left, const llvm::StringRef Right)
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 bool exprEvaluatesToBitwiseNegatedZero(BinaryOperatorKind Opcode, APSInt Value)
static OverloadedOperatorKind getOp(const BinaryOperator *Op)
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 exprEvaluatesToZero(BinaryOperatorKind Opcode, APSInt Value)
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 canOverloadedOperatorArgsBeModified(const CXXOperatorCallExpr *OperatorCall, bool CheckSecondParam)