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"
24 const auto &literal = Node.getValue();
25 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
26 return literal.convertToFloat() == 0.5f;
27 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
28 return literal.convertToDouble() == 0.5;
33 void IncorrectRoundingsCheck::registerMatchers(MatchFinder *MatchFinder) {
35 auto FloatHalf = floatLiteral(floatHalf());
38 auto FloatType = expr(hasType(realFloatingPointType()));
42 auto FloatOrCastHalf =
44 implicitCastExpr(FloatType, has(ignoringParenImpCasts(FloatHalf))));
48 auto OneSideHalf = anyOf(allOf(hasLHS(FloatOrCastHalf), hasRHS(FloatType)),
49 allOf(hasRHS(FloatOrCastHalf), hasLHS(FloatType)));
53 MatchFinder->addMatcher(
54 traverse(ast_type_traits::TK_AsIs,
55 implicitCastExpr(hasImplicitDestinationType(isInteger()),
56 ignoringParenCasts(binaryOperator(
57 hasOperatorName(
"+"), OneSideHalf)))
62 void IncorrectRoundingsCheck::check(
const MatchFinder::MatchResult &Result) {
63 const auto *CastExpr = Result.Nodes.getNodeAs<ImplicitCastExpr>(
"CastExpr");
64 diag(CastExpr->getBeginLoc(),
65 "casting (double + 0.5) to integer leads to incorrect rounding; "
66 "consider using lround (#include <cmath>) instead");