| 1 | //===--- IncorrectRoundingsCheck.cpp - clang-tidy ------------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "IncorrectRoundingsCheck.h" |
| 10 | #include "clang/AST/DeclBase.h" |
| 11 | #include "clang/AST/Type.h" |
| 12 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| 13 | #include "clang/ASTMatchers/ASTMatchers.h" |
| 14 | #include "clang/Lex/Lexer.h" |
| 15 | |
| 16 | using namespace clang::ast_matchers; |
| 17 | |
| 18 | namespace clang::tidy::bugprone { |
| 19 | |
| 20 | namespace { |
| 21 | AST_MATCHER(FloatingLiteral, floatHalf) { |
| 22 | const auto &Literal = Node.getValue(); |
| 23 | if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle()) |
| 24 | return Literal.convertToFloat() == 0.5f; |
| 25 | if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble()) |
| 26 | return Literal.convertToDouble() == 0.5; |
| 27 | return false; |
| 28 | } |
| 29 | } // namespace |
| 30 | |
| 31 | void IncorrectRoundingsCheck::registerMatchers(MatchFinder *MatchFinder) { |
| 32 | // Match a floating literal with value 0.5. |
| 33 | auto FloatHalf = floatLiteral(floatHalf()); |
| 34 | |
| 35 | // Match a floating point expression. |
| 36 | auto FloatType = expr(hasType(realFloatingPointType())); |
| 37 | |
| 38 | // Match a floating literal of 0.5 or a floating literal of 0.5 implicitly. |
| 39 | // cast to floating type. |
| 40 | auto FloatOrCastHalf = |
| 41 | anyOf(FloatHalf, |
| 42 | implicitCastExpr(FloatType, has(ignoringParenImpCasts(FloatHalf)))); |
| 43 | |
| 44 | // Match if either the LHS or RHS is a floating literal of 0.5 or a floating |
| 45 | // literal of 0.5 and the other is of type double or vice versa. |
| 46 | auto OneSideHalf = anyOf(allOf(hasLHS(FloatOrCastHalf), hasRHS(FloatType)), |
| 47 | allOf(hasRHS(FloatOrCastHalf), hasLHS(FloatType))); |
| 48 | |
| 49 | // Find expressions of cast to int of the sum of a floating point expression |
| 50 | // and 0.5. |
| 51 | MatchFinder->addMatcher( |
| 52 | traverse(TK_AsIs, |
| 53 | implicitCastExpr(hasImplicitDestinationType(isInteger()), |
| 54 | ignoringParenCasts(binaryOperator( |
| 55 | hasOperatorName("+"), OneSideHalf))) |
| 56 | .bind("CastExpr")), |
| 57 | this); |
| 58 | } |
| 59 | |
| 60 | void IncorrectRoundingsCheck::check(const MatchFinder::MatchResult &Result) { |
| 61 | const auto *CastExpr = Result.Nodes.getNodeAs<ImplicitCastExpr>("CastExpr"); |
| 62 | diag(CastExpr->getBeginLoc(), |
| 63 | "casting (double + 0.5) to integer leads to incorrect rounding; " |
| 64 | "consider using lround (#include <cmath>) instead"); |
| 65 | } |
| 66 | |
| 67 | } // namespace clang::tidy::bugprone |