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 {
19 namespace tidy {
20 namespace bugprone {
21 
22 namespace {
AST_MATCHER(FloatingLiteral,floatHalf)23 AST_MATCHER(FloatingLiteral, floatHalf) {
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;
29   return false;
30 }
31 } // namespace
32 
registerMatchers(MatchFinder * MatchFinder)33 void IncorrectRoundingsCheck::registerMatchers(MatchFinder *MatchFinder) {
34   // Match a floating literal with value 0.5.
35   auto FloatHalf = floatLiteral(floatHalf());
36 
37   // Match a floating point expression.
38   auto FloatType = expr(hasType(realFloatingPointType()));
39 
40   // Match a floating literal of 0.5 or a floating literal of 0.5 implicitly.
41   // cast to floating type.
42   auto FloatOrCastHalf =
43       anyOf(FloatHalf,
44             implicitCastExpr(FloatType, has(ignoringParenImpCasts(FloatHalf))));
45 
46   // Match if either the LHS or RHS is a floating literal of 0.5 or a floating
47   // literal of 0.5 and the other is of type double or vice versa.
48   auto OneSideHalf = anyOf(allOf(hasLHS(FloatOrCastHalf), hasRHS(FloatType)),
49                            allOf(hasRHS(FloatOrCastHalf), hasLHS(FloatType)));
50 
51   // Find expressions of cast to int of the sum of a floating point expression
52   // and 0.5.
53   MatchFinder->addMatcher(
54       traverse(TK_AsIs,
55                implicitCastExpr(hasImplicitDestinationType(isInteger()),
56                                 ignoringParenCasts(binaryOperator(
57                                     hasOperatorName("+"), OneSideHalf)))
58                    .bind("CastExpr")),
59       this);
60 }
61 
check(const MatchFinder::MatchResult & Result)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");
67 }
68 
69 } // namespace bugprone
70 } // namespace tidy
71 } // namespace clang
72