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"
22#include "llvm/Support/raw_ostream.h"
45 return Value < Result;
49 const DeclRefExpr *R) {
50 if (L->getDecl() != R->getDecl())
53 const PrintingPolicy &Policy =
54 L->getDecl()->getASTContext().getPrintingPolicy();
56 if (L->hasQualifier() && R->hasQualifier()) {
57 std::string LQual, RQual;
58 llvm::raw_string_ostream LOS(LQual), ROS(RQual);
59 L->getQualifier().print(LOS, Policy);
60 R->getQualifier().print(ROS, Policy);
65 if (L->hasExplicitTemplateArgs() != R->hasExplicitTemplateArgs())
67 if (L->hasExplicitTemplateArgs()) {
68 if (L->getNumTemplateArgs() != R->getNumTemplateArgs())
71 return llvm::equal(L->template_arguments(), R->template_arguments(),
72 [&Policy](
const TemplateArgumentLoc &LArg,
73 const TemplateArgumentLoc &RArg) {
74 std::string LStr, RStr;
75 llvm::raw_string_ostream LOS(LStr), ROS(RStr);
76 LArg.getArgument().print(Policy, LOS, true);
77 RArg.getArgument().print(Policy, ROS, true);
86 return !Left && !Right;
88 Left = Left->IgnoreParens();
89 Right = Right->IgnoreParens();
92 if (Left->getStmtClass() != Right->getStmtClass())
96 Expr::const_child_iterator LeftIter = Left->child_begin();
97 Expr::const_child_iterator RightIter = Right->child_begin();
98 while (LeftIter != Left->child_end() && RightIter != Right->child_end()) {
100 dyn_cast_or_null<Expr>(*RightIter)))
105 if (LeftIter != Left->child_end() || RightIter != Right->child_end())
109 switch (Left->getStmtClass()) {
113 case Stmt::CharacterLiteralClass:
114 return cast<CharacterLiteral>(Left)->getValue() ==
115 cast<CharacterLiteral>(Right)->getValue();
116 case Stmt::IntegerLiteralClass: {
117 const llvm::APInt LeftLit = cast<IntegerLiteral>(Left)->getValue();
118 const llvm::APInt RightLit = cast<IntegerLiteral>(Right)->getValue();
119 return LeftLit.getBitWidth() == RightLit.getBitWidth() &&
122 case Stmt::FloatingLiteralClass:
123 return cast<FloatingLiteral>(Left)->getValue().bitwiseIsEqual(
124 cast<FloatingLiteral>(Right)->getValue());
125 case Stmt::StringLiteralClass:
126 return cast<StringLiteral>(Left)->getBytes() ==
127 cast<StringLiteral>(Right)->getBytes();
128 case Stmt::CXXOperatorCallExprClass:
129 return cast<CXXOperatorCallExpr>(Left)->getOperator() ==
130 cast<CXXOperatorCallExpr>(Right)->getOperator();
131 case Stmt::DependentScopeDeclRefExprClass:
132 if (cast<DependentScopeDeclRefExpr>(Left)->getDeclName() !=
133 cast<DependentScopeDeclRefExpr>(Right)->getDeclName())
135 return cast<DependentScopeDeclRefExpr>(Left)->getQualifier() ==
136 cast<DependentScopeDeclRefExpr>(Right)->getQualifier();
137 case Stmt::DeclRefExprClass:
139 cast<DeclRefExpr>(Right));
140 case Stmt::MemberExprClass:
141 return cast<MemberExpr>(Left)->getMemberDecl() ==
142 cast<MemberExpr>(Right)->getMemberDecl();
143 case Stmt::CXXFoldExprClass:
144 return cast<CXXFoldExpr>(Left)->getOperator() ==
145 cast<CXXFoldExpr>(Right)->getOperator();
146 case Stmt::CXXFunctionalCastExprClass:
147 case Stmt::CStyleCastExprClass:
148 return cast<ExplicitCastExpr>(Left)->getTypeAsWritten() ==
149 cast<ExplicitCastExpr>(Right)->getTypeAsWritten();
150 case Stmt::CallExprClass:
151 case Stmt::ImplicitCastExprClass:
152 case Stmt::ArraySubscriptExprClass:
154 case Stmt::UnaryOperatorClass:
155 if (cast<UnaryOperator>(Left)->isIncrementDecrementOp())
157 return cast<UnaryOperator>(Left)->getOpcode() ==
158 cast<UnaryOperator>(Right)->getOpcode();
159 case Stmt::BinaryOperatorClass:
160 if (cast<BinaryOperator>(Left)->isAssignmentOp())
162 return cast<BinaryOperator>(Left)->getOpcode() ==
163 cast<BinaryOperator>(Right)->getOpcode();
164 case Stmt::UnaryExprOrTypeTraitExprClass:
165 const auto *LeftUnaryExpr = cast<UnaryExprOrTypeTraitExpr>(Left);
166 const auto *RightUnaryExpr = cast<UnaryExprOrTypeTraitExpr>(Right);
167 if (LeftUnaryExpr->isArgumentType() && RightUnaryExpr->isArgumentType())
168 return LeftUnaryExpr->getKind() == RightUnaryExpr->getKind() &&
169 LeftUnaryExpr->getArgumentType() ==
170 RightUnaryExpr->getArgumentType();
171 if (!LeftUnaryExpr->isArgumentType() && !RightUnaryExpr->isArgumentType())
173 RightUnaryExpr->getArgumentExpr());
182 const APSInt &ValueLHS,
183 BinaryOperatorKind OpcodeRHS,
184 const APSInt &ValueRHS) {
185 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
186 "Values must be ordered");
188 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0)
189 return OpcodeLHS == OpcodeRHS;
192 APSInt ValueLhsPlus1;
193 return ((OpcodeLHS == BO_LE && OpcodeRHS == BO_LT) ||
194 (OpcodeLHS == BO_GT && OpcodeRHS == BO_GE)) &&
196 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0;
202 const APSInt &ValueLHS,
203 BinaryOperatorKind OpcodeRHS,
204 const APSInt &ValueRHS) {
205 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
206 "Values must be ordered");
209 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
212 return OpcodeRHS == BO_NE || OpcodeRHS == BO_GT || OpcodeRHS == BO_LT;
214 return OpcodeRHS == BO_EQ;
216 return OpcodeRHS == BO_GT;
218 return OpcodeRHS == BO_LT;
220 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
222 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
229 if ((OpcodeLHS == BO_EQ || OpcodeLHS == BO_LT || OpcodeLHS == BO_LE) &&
230 (OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE))
234 APSInt ValueLhsPlus1;
235 if (OpcodeLHS == BO_GT && OpcodeRHS == BO_LT &&
237 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
246 const APSInt &ValueLHS,
247 BinaryOperatorKind OpcodeRHS,
248 const APSInt &ValueRHS) {
249 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
250 "Values must be ordered");
253 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
256 return OpcodeRHS == BO_NE;
258 return OpcodeRHS == BO_EQ;
260 return OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
262 return OpcodeRHS == BO_GE;
264 return OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
266 return OpcodeRHS == BO_LE;
273 APSInt ValueLhsPlus1;
274 if (OpcodeLHS == BO_LE && OpcodeRHS == BO_GE &&
276 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
280 if ((OpcodeLHS == BO_GT || OpcodeLHS == BO_GE) &&
281 (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE))
286 if (OpcodeLHS == BO_NE && OpcodeRHS == BO_NE)
293 const APSInt &ValueLHS,
294 BinaryOperatorKind OpcodeRHS,
295 const APSInt &ValueRHS) {
296 const int Comparison = APSInt::compareValues(ValueLHS, ValueRHS);
299 return OpcodeRHS == BO_EQ && Comparison == 0;
301 return (OpcodeRHS == BO_NE && Comparison == 0) ||
302 (OpcodeRHS == BO_EQ && Comparison != 0) ||
303 (OpcodeRHS == BO_LT && Comparison >= 0) ||
304 (OpcodeRHS == BO_LE && Comparison > 0) ||
305 (OpcodeRHS == BO_GT && Comparison <= 0) ||
306 (OpcodeRHS == BO_GE && Comparison < 0);
309 return ((OpcodeRHS == BO_LT && Comparison >= 0) ||
310 (OpcodeRHS == BO_LE && Comparison > 0) ||
311 (OpcodeRHS == BO_EQ && Comparison > 0));
313 return ((OpcodeRHS == BO_GT && Comparison <= 0) ||
314 (OpcodeRHS == BO_GE && Comparison < 0) ||
315 (OpcodeRHS == BO_EQ && Comparison < 0));
317 return (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE || OpcodeRHS == BO_EQ) &&
320 return (OpcodeRHS == BO_GT || OpcodeRHS == BO_GE || OpcodeRHS == BO_EQ) &&
329 if (Opcode == BO_Sub) {
336static OverloadedOperatorKind
getOp(
const BinaryOperator *Op) {
337 return BinaryOperator::getOverloadedOperator(Op->getOpcode());
340static OverloadedOperatorKind
getOp(
const CXXOperatorCallExpr *Op) {
341 if (Op->getNumArgs() != 2)
343 return Op->getOperator();
346static std::pair<const Expr *, const Expr *>
348 return {Op->getLHS()->IgnoreParenImpCasts(),
349 Op->getRHS()->IgnoreParenImpCasts()};
352static std::pair<const Expr *, const Expr *>
354 return {Op->getArg(0)->IgnoreParenImpCasts(),
355 Op->getArg(1)->IgnoreParenImpCasts()};
358template <
typename TExpr>
360 OverloadedOperatorKind OpKind) {
361 const auto *AsTExpr = dyn_cast_or_null<TExpr>(TheExpr);
362 if (AsTExpr &&
getOp(AsTExpr) == OpKind)
370template <
typename TExpr,
unsigned N>
373 OverloadedOperatorKind OpKind) {
375 const std::pair<const Expr *, const Expr *> Operands =
getOperands(BinOp);
382 AllOperands.push_back(Part);
386template <
typename TExpr>
388 OverloadedOperatorKind OpKind,
389 ASTContext &Context) {
391 const DynTypedNodeList Parents = Context.getParents(*TheExpr);
392 for (
const DynTypedNode DynParent : Parents) {
393 if (
const auto *Parent = DynParent.get<Expr>()) {
395 isa<ParenExpr>(Parent) || isa<ImplicitCastExpr>(Parent) ||
396 isa<FullExpr>(Parent) || isa<MaterializeTemporaryExpr>(Parent);
408 const SourceManager &SM) {
409 if (T1.getKind() != T2.getKind())
411 if (T1.isNot(tok::raw_identifier))
413 if (T1.getLength() != T2.getLength())
415 return StringRef(SM.getCharacterData(T1.getLocation()), T1.getLength()) ==
416 StringRef(SM.getCharacterData(T2.getLocation()), T2.getLength());
420 const SourceManager &SM) {
421 return SM.getExpansionLoc(ExprSR.getEnd()) == T.getLocation();
429 const ASTContext *AstCtx) {
430 if (!LhsExpr || !RhsExpr)
432 const SourceRange Lsr = LhsExpr->getSourceRange();
433 const SourceRange Rsr = RhsExpr->getSourceRange();
434 if (!Lsr.getBegin().isMacroID() || !Rsr.getBegin().isMacroID())
437 const SourceManager &SM = AstCtx->getSourceManager();
438 const LangOptions &LO = AstCtx->getLangOpts();
440 const std::pair<FileID, unsigned> LsrLocInfo =
441 SM.getDecomposedLoc(SM.getExpansionLoc(Lsr.getBegin()));
442 const std::pair<FileID, unsigned> RsrLocInfo =
443 SM.getDecomposedLoc(SM.getExpansionLoc(Rsr.getBegin()));
444 const llvm::MemoryBufferRef MB = SM.getBufferOrFake(LsrLocInfo.first);
446 const char *LTokenPos = MB.getBufferStart() + LsrLocInfo.second;
447 const char *RTokenPos = MB.getBufferStart() + RsrLocInfo.second;
448 Lexer LRawLex(SM.getLocForStartOfFile(LsrLocInfo.first), LO,
449 MB.getBufferStart(), LTokenPos, MB.getBufferEnd());
450 Lexer RRawLex(SM.getLocForStartOfFile(RsrLocInfo.first), LO,
451 MB.getBufferStart(), RTokenPos, MB.getBufferEnd());
455 LRawLex.LexFromRawLexer(LTok);
456 RRawLex.LexFromRawLexer(RTok);
457 }
while (!LTok.is(tok::eof) && !RTok.is(tok::eof) &&
467 const Expr *&RhsExpr) {
468 if (!LhsExpr || !RhsExpr)
471 const SourceLocation LhsLoc = LhsExpr->getExprLoc();
472 const SourceLocation RhsLoc = RhsExpr->getExprLoc();
474 return LhsLoc.isMacroID() != RhsLoc.isMacroID();
477template <
typename TExpr>
480 ast_matchers::internal::BoundNodesTreeBuilder *Builder,
481 ASTContext &Context) {
482 const OverloadedOperatorKind OpKind =
getOp(TheExpr);
483 if (OpKind == OO_None)
487 const std::pair<const Expr *, const Expr *> Operands =
getOperands(TheExpr);
502 const size_t NumOperands = AllOperands.size();
503 llvm::SmallBitVector Duplicates(NumOperands);
504 for (
size_t I = 0; I < NumOperands; I++) {
507 bool FoundDuplicates =
false;
509 for (
size_t J = I + 1; J < NumOperands; J++) {
510 if (AllOperands[J]->HasSideEffects(Context))
513 const Expr *Lhs = AllOperands[I];
514 const Expr *Rhs = AllOperands[J];
520 FoundDuplicates =
true;
522 Builder->setBinding(SmallString<11>(llvm::formatv(
"duplicate{0}", J)),
523 DynTypedNode::create(*Rhs));
527 Builder->setBinding(SmallString<11>(llvm::formatv(
"duplicate{0}", I)),
528 DynTypedNode::create(*AllOperands[I]));
531 return Duplicates.any();
537 if (Node.isInstantiationDependent())
539 return Node.isIntegerConstantExpr(Finder->getASTContext());
542AST_MATCHER(BinaryOperator, operandsAreEquivalent) {
546AST_MATCHER(BinaryOperator, nestedOperandsAreEquivalent) {
550AST_MATCHER(ConditionalOperator, expressionsAreEquivalent) {
555 return Node.getNumArgs() == 2 &&
559AST_MATCHER(CXXOperatorCallExpr, nestedParametersAreEquivalent) {
563AST_MATCHER(BinaryOperator, binaryOperatorIsInMacro) {
564 return Node.getOperatorLoc().isMacroID();
567AST_MATCHER(ConditionalOperator, conditionalOperatorIsInMacro) {
568 return Node.getQuestionLoc().isMacroID() || Node.getColonLoc().isMacroID();
571AST_MATCHER(Expr, isMacro) {
return Node.getExprLoc().isMacroID(); }
573AST_MATCHER_P(Expr, expandedByMacro, ArrayRef<StringRef>, Names) {
574 const SourceManager &SM = Finder->getASTContext().getSourceManager();
575 const LangOptions &LO = Finder->getASTContext().getLangOpts();
576 SourceLocation Loc = Node.getExprLoc();
577 while (Loc.isMacroID()) {
578 const StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LO);
579 if (llvm::is_contained(Names, MacroName))
581 Loc = SM.getImmediateMacroCallerLoc(Loc);
589static ast_matchers::internal::Matcher<Expr>
591 const std::string CstId = (Id +
"-const").str();
592 return expr(isIntegerConstantExpr()).bind(CstId);
599 StringRef Id, APSInt &Value,
600 const Expr *&ConstExpr) {
601 const std::string CstId = (Id +
"-const").str();
602 ConstExpr = Result.Nodes.getNodeAs<Expr>(CstId);
605 std::optional<llvm::APSInt> R =
606 ConstExpr->getIntegerConstantExpr(*Result.Context);
615 StringRef Id, APSInt &Value) {
616 const Expr *ConstExpr =
nullptr;
623 const std::string SymId = (Id +
"-sym").str();
624 return ignoringParenImpCasts(
625 expr(unless(isIntegerConstantExpr())).bind(SymId));
631 StringRef Id,
const Expr *&SymExpr) {
632 const std::string SymId = (Id +
"-sym").str();
633 if (
const auto *Node = Result.Nodes.getNodeAs<Expr>(SymId)) {
642static ast_matchers::internal::Matcher<Expr>
644 const auto BinOpCstExpr =
645 expr(anyOf(binaryOperator(hasAnyOperatorName(
"+",
"|",
"&"),
648 binaryOperator(hasOperatorName(
"-"),
652 return ignoringParenImpCasts(BinOpCstExpr);
659 StringRef Id, BinaryOperatorKind &Opcode,
660 const Expr *&Symbol, APSInt &Value) {
661 if (
const auto *BinExpr = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
662 Opcode = BinExpr->getOpcode();
670static ast_matchers::internal::Matcher<Expr>
672 const std::string CastId = (Id +
"-cast").str();
673 const std::string SwapId = (Id +
"-swap").str();
674 const std::string NegateId = (Id +
"-negate").str();
675 const std::string OverloadId = (Id +
"-overload").str();
676 const std::string ConstId = (Id +
"-const").str();
678 const auto RelationalExpr = ignoringParenImpCasts(binaryOperator(
679 isComparisonOperator(), expr().bind(Id),
687 const auto CastExpr =
688 implicitCastExpr(hasCastKind(CK_IntegralToBoolean),
692 const auto NegateRelationalExpr =
693 unaryOperator(hasOperatorName(
"!"),
694 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))
698 const auto NegateNegateRelationalExpr =
699 unaryOperator(hasOperatorName(
"!"),
700 hasUnaryOperand(unaryOperator(
701 hasOperatorName(
"!"),
702 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))));
704 const auto OverloadedOperatorExpr =
706 hasAnyOverloadedOperatorName(
"==",
"!=",
"<",
"<=",
">",
">="),
708 unless(isMacro()), unless(isInTemplateInstantiation()),
709 anyOf(hasLHS(ignoringParenImpCasts(integerLiteral().bind(ConstId))),
710 hasRHS(ignoringParenImpCasts(integerLiteral().bind(ConstId)))))
713 return anyOf(RelationalExpr, CastExpr, NegateRelationalExpr,
714 NegateNegateRelationalExpr, OverloadedOperatorExpr);
720 return ParamType->isReferenceType() &&
721 !ParamType.getNonReferenceType().isConstQualified();
732 bool CheckSecondParam) {
733 const auto *OperatorDecl =
734 dyn_cast_or_null<FunctionDecl>(OperatorCall->getCalleeDecl());
740 const unsigned ParamCount = OperatorDecl->getNumParams();
745 if (ParamCount == 1 &&
746 !OperatorDecl->getType()->castAs<FunctionType>()->isConst())
752 return CheckSecondParam && ParamCount == 2 &&
759 const MatchFinder::MatchResult &Result, StringRef Id,
760 const Expr *&OperandExpr, BinaryOperatorKind &Opcode,
const Expr *&Symbol,
761 APSInt &Value,
const Expr *&ConstExpr) {
762 const std::string CastId = (Id +
"-cast").str();
763 const std::string SwapId = (Id +
"-swap").str();
764 const std::string NegateId = (Id +
"-negate").str();
765 const std::string OverloadId = (Id +
"-overload").str();
767 if (
const auto *Bin = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
769 Opcode = Bin->getOpcode();
774 }
else if (
const auto *Cast = Result.Nodes.getNodeAs<CastExpr>(CastId)) {
778 Value = APSInt(32,
false);
779 }
else if (
const auto *OverloadedOperatorExpr =
780 Result.Nodes.getNodeAs<CXXOperatorCallExpr>(OverloadId)) {
784 bool IntegerConstantIsFirstArg =
false;
786 if (
const auto *Arg = OverloadedOperatorExpr->getArg(1)) {
787 if (!Arg->isValueDependent() &&
788 !Arg->isIntegerConstantExpr(*Result.Context)) {
789 IntegerConstantIsFirstArg =
true;
790 if (
const auto *Arg = OverloadedOperatorExpr->getArg(0)) {
791 if (!Arg->isValueDependent() &&
792 !Arg->isIntegerConstantExpr(*Result.Context))
802 Symbol = OverloadedOperatorExpr->getArg(IntegerConstantIsFirstArg ? 1 : 0);
803 OperandExpr = OverloadedOperatorExpr;
804 Opcode = BinaryOperator::getOverloadedOpcode(
805 OverloadedOperatorExpr->getOperator());
810 if (!BinaryOperator::isComparisonOp(Opcode))
815 if (IntegerConstantIsFirstArg)
816 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
826 if (Result.Nodes.getNodeAs<Expr>(SwapId))
827 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
828 if (Result.Nodes.getNodeAs<Expr>(NegateId))
829 Opcode = BinaryOperator::negateComparisonOp(Opcode);
835 const ASTContext *AstCtx) {
836 const auto *LhsBinOp = dyn_cast<BinaryOperator>(BinOp->getLHS());
837 const auto *RhsBinOp = dyn_cast<BinaryOperator>(BinOp->getRHS());
839 if (!LhsBinOp || !RhsBinOp)
842 auto IsIntegerConstantExpr = [AstCtx](
const Expr *E) {
843 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
846 if ((IsIntegerConstantExpr(LhsBinOp->getLHS()) ||
847 IsIntegerConstantExpr(LhsBinOp->getRHS())) &&
848 (IsIntegerConstantExpr(RhsBinOp->getLHS()) ||
849 IsIntegerConstantExpr(RhsBinOp->getRHS())))
855 const BinaryOperator *&BinOp,
const ASTContext *AstCtx) {
859 const Expr *Lhs = BinOp->getLHS();
860 const Expr *Rhs = BinOp->getRHS();
865 auto IsDefineExpr = [AstCtx](
const Expr *E) {
866 const SourceRange Lsr = E->getSourceRange();
867 if (!Lsr.getBegin().isMacroID() || E->isValueDependent() ||
868 !E->isIntegerConstantExpr(*AstCtx))
873 return IsDefineExpr(Lhs) || IsDefineExpr(Rhs);
880 BinaryOperatorKind &MainOpcode,
881 BinaryOperatorKind &SideOpcode,
882 const Expr *&LhsConst,
883 const Expr *&RhsConst,
884 const ASTContext *AstCtx) {
886 "Both sides of binary operator must be constant expressions!");
888 MainOpcode = BinOp->getOpcode();
890 const auto *BinOpLhs = cast<BinaryOperator>(BinOp->getLHS());
891 const auto *BinOpRhs = cast<BinaryOperator>(BinOp->getRHS());
893 auto IsIntegerConstantExpr = [AstCtx](
const Expr *E) {
894 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
897 LhsConst = IsIntegerConstantExpr(BinOpLhs->getLHS()) ? BinOpLhs->getLHS()
898 : BinOpLhs->getRHS();
899 RhsConst = IsIntegerConstantExpr(BinOpRhs->getLHS()) ? BinOpRhs->getLHS()
900 : BinOpRhs->getRHS();
902 if (!LhsConst || !RhsConst)
905 assert(BinOpLhs->getOpcode() == BinOpRhs->getOpcode() &&
906 "Sides of the binary operator must be equivalent expressions!");
908 SideOpcode = BinOpLhs->getOpcode();
914 const StringRef Right) {
919 StringRef L = Left.trim();
920 StringRef R = Right.trim();
921 while (!L.empty() && !R.empty()) {
924 if (L.empty() && R.empty())
927 if (L.front() != R.front())
932 return L.empty() && R.empty();
936 const ASTContext *Context) {
940 const Expr *Lhs = BinOp->getLHS();
941 const Expr *Rhs = BinOp->getRHS();
942 const SourceManager &SM = Context->getSourceManager();
944 const SourceRange Lsr = Lhs->getSourceRange();
945 const SourceRange Rsr = Rhs->getSourceRange();
946 if (Lsr.getBegin().isMacroID()) {
948 if (Rsr.getBegin().isMacroID()) {
950 const StringRef L = Lexer::getSourceText(
951 CharSourceRange::getTokenRange(Lsr), SM, Context->getLangOpts());
952 const StringRef R = Lexer::getSourceText(
953 CharSourceRange::getTokenRange(Rsr), SM, Context->getLangOpts());
959 const auto *Lil = dyn_cast<IntegerLiteral>(Lhs);
960 const auto *Ril = dyn_cast<IntegerLiteral>(Rhs);
962 return Lil->getValue() == Ril->getValue();
964 const auto *Lbl = dyn_cast<CXXBoolLiteralExpr>(Lhs);
965 const auto *Rbl = dyn_cast<CXXBoolLiteralExpr>(Rhs);
967 return Lbl->getValue() == Rbl->getValue();
973 const auto BannedIntegerLiteral =
975 const auto IsInUnevaluatedContext = expr(anyOf(
976 hasAncestor(expr(hasUnevaluatedContext())), hasAncestor(typeLoc())));
981 binaryOperator(anyOf(isComparisonOperator(),
982 hasAnyOperatorName(
"-",
"/",
"%",
"|",
"&",
983 "^",
"&&",
"||",
"=")),
984 operandsAreEquivalent(),
986 unless(isInTemplateInstantiation()),
987 unless(binaryOperatorIsInMacro()),
988 unless(hasAncestor(arraySubscriptExpr())),
989 unless(hasDescendant(BannedIntegerLiteral)),
990 unless(IsInUnevaluatedContext))
997 binaryOperator(hasAnyOperatorName(
"|",
"&",
"||",
"&&",
"^"),
998 nestedOperandsAreEquivalent(),
1000 unless(isInTemplateInstantiation()),
1001 unless(binaryOperatorIsInMacro()),
1003 unless(hasDescendant(BannedIntegerLiteral)),
1004 unless(IsInUnevaluatedContext))
1005 .bind(
"nested-duplicates"),
1011 conditionalOperator(expressionsAreEquivalent(),
1013 unless(conditionalOperatorIsInMacro()),
1014 unless(isInTemplateInstantiation()),
1015 unless(IsInUnevaluatedContext))
1022 cxxOperatorCallExpr(
1023 hasAnyOverloadedOperatorName(
"-",
"/",
"%",
"|",
"&",
"^",
1024 "==",
"!=",
"<",
"<=",
">",
1025 ">=",
"&&",
"||",
"="),
1026 parametersAreEquivalent(),
1028 unless(isMacro()), unless(isInTemplateInstantiation()),
1029 unless(IsInUnevaluatedContext))
1035 cxxOperatorCallExpr(
1036 hasAnyOverloadedOperatorName(
"|",
"&",
"||",
"&&",
"^"),
1037 nestedParametersAreEquivalent(), argumentCountIs(2),
1039 unless(isMacro()), unless(isInTemplateInstantiation()),
1040 unless(IsInUnevaluatedContext))
1041 .bind(
"nested-duplicates"),
1048 hasImplicitDestinationType(isInteger()),
1050 hasOperatorName(
"!"),
1051 hasUnaryOperand(ignoringParenImpCasts(binaryOperator(
1052 hasAnyOperatorName(
"|",
"&"),
1054 binaryOperator(hasAnyOperatorName(
"|",
"&")),
1056 hasRHS(integerLiteral())))))
1057 .bind(
"logical-bitwise-confusion")),
1058 unless(IsInUnevaluatedContext))),
1065 hasOperatorName(
"&"),
1066 hasOperands(ignoringParenImpCasts(binaryOperator(
1067 hasOperatorName(
"<<"),
1068 hasRHS(ignoringParenImpCasts(
1069 integerLiteral().bind(
"shift-const"))))),
1070 ignoringParenImpCasts(
1071 integerLiteral().bind(
"and-const"))),
1072 unless(IsInUnevaluatedContext))
1073 .bind(
"left-right-shift-confusion")),
1089 traverse(TK_AsIs, binaryOperator(isComparisonOperator(),
1090 hasOperands(BinOpCstLeft, CstRight),
1091 unless(IsInUnevaluatedContext))
1092 .bind(
"binop-const-compare-to-const")),
1099 binaryOperator(isComparisonOperator(),
1100 anyOf(allOf(hasLHS(BinOpCstLeft), hasRHS(SymRight)),
1101 allOf(hasLHS(SymRight), hasRHS(BinOpCstLeft))),
1102 unless(IsInUnevaluatedContext))
1103 .bind(
"binop-const-compare-to-sym")),
1109 binaryOperator(isComparisonOperator(), hasLHS(BinOpCstLeft),
1110 hasRHS(BinOpCstRight),
1112 unless(operandsAreEquivalent()),
1113 unless(IsInUnevaluatedContext))
1114 .bind(
"binop-const-compare-to-binop-const")),
1126 binaryOperator(hasAnyOperatorName(
"||",
"&&"),
1127 hasLHS(ComparisonLeft), hasRHS(ComparisonRight),
1129 unless(operandsAreEquivalent()),
1130 unless(IsInUnevaluatedContext))
1131 .bind(
"comparisons-of-symbol-and-const")),
1135void RedundantExpressionCheck::checkArithmeticExpr(
1136 const MatchFinder::MatchResult &Result) {
1137 APSInt LhsValue, RhsValue;
1138 const Expr *LhsSymbol =
nullptr, *RhsSymbol =
nullptr;
1139 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1141 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1142 "binop-const-compare-to-sym")) {
1143 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1151 if (LhsOpcode == BO_Add || LhsOpcode == BO_Sub) {
1152 if ((LhsValue != 0 && Opcode == BO_EQ) ||
1153 (LhsValue == 0 && Opcode == BO_NE))
1154 diag(ComparisonOperator->getOperatorLoc(),
1155 "logical expression is always false");
1156 else if ((LhsValue == 0 && Opcode == BO_EQ) ||
1157 (LhsValue != 0 && Opcode == BO_NE))
1158 diag(ComparisonOperator->getOperatorLoc(),
1159 "logical expression is always true");
1161 }
else if (
const auto *ComparisonOperator =
1162 Result.Nodes.getNodeAs<BinaryOperator>(
1163 "binop-const-compare-to-binop-const")) {
1164 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1177 if (LhsOpcode == BO_Add && RhsOpcode == BO_Add) {
1178 if ((Opcode == BO_EQ && APSInt::compareValues(LhsValue, RhsValue) == 0) ||
1179 (Opcode == BO_NE && APSInt::compareValues(LhsValue, RhsValue) != 0)) {
1180 diag(ComparisonOperator->getOperatorLoc(),
1181 "logical expression is always true");
1182 }
else if ((Opcode == BO_EQ &&
1183 APSInt::compareValues(LhsValue, RhsValue) != 0) ||
1185 APSInt::compareValues(LhsValue, RhsValue) == 0)) {
1186 diag(ComparisonOperator->getOperatorLoc(),
1187 "logical expression is always false");
1194 const APSInt &Value) {
1195 return (Opcode == BO_And || Opcode == BO_AndAssign) && Value == 0;
1199 const APSInt &Value) {
1200 return (Opcode == BO_Or || Opcode == BO_OrAssign) && ~Value == 0;
1204 const APSInt &Value) {
1205 return ((Opcode == BO_Or || Opcode == BO_OrAssign) && Value == 0) ||
1206 ((Opcode == BO_And || Opcode == BO_AndAssign) && ~Value == 0);
1209void RedundantExpressionCheck::checkBitwiseExpr(
1210 const MatchFinder::MatchResult &Result) {
1211 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1212 "binop-const-compare-to-const")) {
1213 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1215 APSInt LhsValue, RhsValue;
1216 const Expr *LhsSymbol =
nullptr;
1217 BinaryOperatorKind LhsOpcode{};
1223 const unsigned ConstantWidth =
1224 std::max(LhsValue.getBitWidth(), RhsValue.getBitWidth());
1225 const llvm::APInt LhsConstant = LhsValue.extOrTrunc(ConstantWidth);
1226 const llvm::APInt RhsConstant = RhsValue.extOrTrunc(ConstantWidth);
1227 const SourceLocation Loc = ComparisonOperator->getOperatorLoc();
1230 if (LhsOpcode == BO_And && (LhsConstant & RhsConstant) != RhsConstant) {
1231 if (Opcode == BO_EQ)
1232 diag(Loc,
"logical expression is always false");
1233 else if (Opcode == BO_NE)
1234 diag(Loc,
"logical expression is always true");
1238 if (LhsOpcode == BO_Or && (LhsConstant | RhsConstant) != RhsConstant) {
1239 if (Opcode == BO_EQ)
1240 diag(Loc,
"logical expression is always false");
1241 else if (Opcode == BO_NE)
1242 diag(Loc,
"logical expression is always true");
1244 }
else if (
const auto *IneffectiveOperator =
1245 Result.Nodes.getNodeAs<BinaryOperator>(
1246 "ineffective-bitwise")) {
1248 const Expr *Sym =
nullptr, *ConstExpr =
nullptr;
1255 if ((Value != 0 && ~Value != 0) || Sym->getExprLoc().isMacroID())
1258 const SourceLocation Loc = IneffectiveOperator->getOperatorLoc();
1260 const BinaryOperatorKind Opcode = IneffectiveOperator->getOpcode();
1262 diag(Loc,
"expression always evaluates to 0");
1264 const SourceRange ConstExprRange(ConstExpr->getBeginLoc(),
1265 ConstExpr->getEndLoc());
1266 const StringRef ConstExprText = Lexer::getSourceText(
1267 CharSourceRange::getTokenRange(ConstExprRange), *Result.SourceManager,
1268 Result.Context->getLangOpts());
1270 diag(Loc,
"expression always evaluates to '%0'") << ConstExprText;
1273 const SourceRange SymExprRange(Sym->getBeginLoc(), Sym->getEndLoc());
1275 const StringRef ExprText = Lexer::getSourceText(
1276 CharSourceRange::getTokenRange(SymExprRange), *Result.SourceManager,
1277 Result.Context->getLangOpts());
1279 diag(Loc,
"expression always evaluates to '%0'") << ExprText;
1284void RedundantExpressionCheck::checkRelationalExpr(
1285 const MatchFinder::MatchResult &Result) {
1286 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1287 "comparisons-of-symbol-and-const")) {
1290 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1292 const Expr *LhsExpr =
nullptr, *RhsExpr =
nullptr;
1293 const Expr *LhsSymbol =
nullptr, *RhsSymbol =
nullptr;
1294 const Expr *LhsConst =
nullptr, *RhsConst =
nullptr;
1295 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1296 APSInt LhsValue, RhsValue;
1299 Result,
"lhs", LhsExpr, LhsOpcode, LhsSymbol, LhsValue, LhsConst) ||
1301 Result,
"rhs", RhsExpr, RhsOpcode, RhsSymbol, RhsValue, RhsConst) ||
1306 if (APSInt::compareValues(LhsValue, RhsValue) > 0) {
1307 std::swap(LhsExpr, RhsExpr);
1308 std::swap(LhsValue, RhsValue);
1309 std::swap(LhsSymbol, RhsSymbol);
1310 std::swap(LhsOpcode, RhsOpcode);
1318 if ((Opcode == BO_LAnd || Opcode == BO_LOr) &&
1320 diag(ComparisonOperator->getOperatorLoc(),
1321 "equivalent expression on both sides of logical operator");
1325 if (Opcode == BO_LAnd) {
1327 diag(ComparisonOperator->getOperatorLoc(),
1328 "logical expression is always false");
1330 diag(LhsExpr->getExprLoc(),
"expression is redundant");
1332 diag(RhsExpr->getExprLoc(),
"expression is redundant");
1336 if (Opcode == BO_LOr) {
1338 diag(ComparisonOperator->getOperatorLoc(),
1339 "logical expression is always true");
1341 diag(RhsExpr->getExprLoc(),
"expression is redundant");
1343 diag(LhsExpr->getExprLoc(),
"expression is redundant");
1350 if (
const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>(
"binary")) {
1374 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
1375 const Expr *RHS = BinOp->getRHS()->IgnoreParenImpCasts();
1376 const BinaryOperator::Opcode Op = BinOp->getOpcode();
1377 const bool OpEqualEQorNE = ((Op == BO_EQ) || (Op == BO_NE));
1379 const auto *DeclRef1 = dyn_cast<DeclRefExpr>(LHS);
1380 const auto *DeclRef2 = dyn_cast<DeclRefExpr>(RHS);
1381 const auto *FloatLit1 = dyn_cast<FloatingLiteral>(LHS);
1382 const auto *FloatLit2 = dyn_cast<FloatingLiteral>(RHS);
1384 if (DeclRef1 && DeclRef2 &&
1385 DeclRef1->getType()->hasFloatingRepresentation() &&
1386 DeclRef2->getType()->hasFloatingRepresentation() &&
1387 (DeclRef1->getDecl() == DeclRef2->getDecl()) && OpEqualEQorNE) {
1391 if (FloatLit1 && FloatLit2 &&
1392 FloatLit1->getValue().bitwiseIsEqual(FloatLit2->getValue()) &&
1398 BinOp, Result.Context)) {
1399 const Expr *LhsConst =
nullptr, *RhsConst =
nullptr;
1400 BinaryOperatorKind MainOpcode{}, SideOpcode{};
1403 LhsConst, RhsConst, Result.Context))
1414 diag(BinOp->getOperatorLoc(),
"both sides of operator are equivalent");
1417 if (
const auto *CondOp =
1418 Result.Nodes.getNodeAs<ConditionalOperator>(
"cond")) {
1419 const Expr *TrueExpr = CondOp->getTrueExpr();
1420 const Expr *FalseExpr = CondOp->getFalseExpr();
1425 diag(CondOp->getColonLoc(),
1426 "'true' and 'false' expressions are equivalent");
1429 if (
const auto *Call = Result.Nodes.getNodeAs<CXXOperatorCallExpr>(
"call")) {
1433 diag(Call->getOperatorLoc(),
1434 "both sides of overloaded operator are equivalent");
1437 if (
const auto *Op = Result.Nodes.getNodeAs<Expr>(
"nested-duplicates")) {
1438 const auto *Call = dyn_cast<CXXOperatorCallExpr>(Op);
1443 Call ?
"overloaded operator has equivalent nested operands"
1444 :
"operator has equivalent nested operands";
1446 const auto Diag = diag(Op->getExprLoc(),
Message);
1447 for (
const auto &KeyValue : Result.Nodes.getMap())
1448 if (StringRef(KeyValue.first).starts_with(
"duplicate"))
1449 Diag << KeyValue.second.getSourceRange();
1452 if (
const auto *NegateOperator =
1453 Result.Nodes.getNodeAs<UnaryOperator>(
"logical-bitwise-confusion")) {
1454 const SourceLocation OperatorLoc = NegateOperator->getOperatorLoc();
1458 "ineffective logical negation operator used; did you mean '~'?");
1459 const SourceLocation LogicalNotLocation = OperatorLoc.getLocWithOffset(1);
1461 if (!LogicalNotLocation.isMacroID())
1462 Diag << FixItHint::CreateReplacement(
1463 CharSourceRange::getCharRange(OperatorLoc, LogicalNotLocation),
"~");
1466 if (
const auto *BinaryAndExpr = Result.Nodes.getNodeAs<BinaryOperator>(
1467 "left-right-shift-confusion")) {
1468 const auto *ShiftingConst = Result.Nodes.getNodeAs<Expr>(
"shift-const");
1469 assert(ShiftingConst &&
"Expr* 'ShiftingConst' is nullptr!");
1470 std::optional<llvm::APSInt> ShiftingValue =
1471 ShiftingConst->getIntegerConstantExpr(*Result.Context);
1476 const auto *AndConst = Result.Nodes.getNodeAs<Expr>(
"and-const");
1477 assert(AndConst &&
"Expr* 'AndCont' is nullptr!");
1478 std::optional<llvm::APSInt> AndValue =
1479 AndConst->getIntegerConstantExpr(*Result.Context);
1486 if (AndValue->getActiveBits() > *ShiftingValue)
1489 auto Diag = diag(BinaryAndExpr->getOperatorLoc(),
1490 "ineffective bitwise and operation");
1498 checkArithmeticExpr(Result);
1506 checkBitwiseExpr(Result);
1514 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)