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/ASTMatchers/ASTMatchFinder.h" |
11 | #include "clang/ASTMatchers/ASTMatchers.h" |
12 | |
13 | using namespace clang::ast_matchers; |
14 | |
15 | namespace clang::tidy::bugprone { |
16 | |
17 | static llvm::APFloat getHalf(const llvm::fltSemantics &Semantics) { |
18 | return llvm::APFloat(Semantics, 1U) / llvm::APFloat(Semantics, 2U); |
19 | } |
20 | |
21 | namespace { |
22 | AST_MATCHER(FloatingLiteral, floatHalf) { |
23 | return Node.getValue() == getHalf(Semantics: Node.getSemantics()); |
24 | } |
25 | } // namespace |
26 | |
27 | void IncorrectRoundingsCheck::registerMatchers(MatchFinder *MatchFinder) { |
28 | // Match a floating literal with value 0.5. |
29 | auto FloatHalf = floatLiteral(floatHalf()); |
30 | |
31 | // Match a floating point expression. |
32 | auto FloatType = expr(hasType(InnerMatcher: realFloatingPointType())); |
33 | |
34 | // Find expressions of cast to int of the sum of a floating point expression |
35 | // and 0.5. |
36 | MatchFinder->addMatcher( |
37 | NodeMatch: traverse(TK: TK_AsIs, |
38 | InnerMatcher: implicitCastExpr( |
39 | hasImplicitDestinationType(InnerMatcher: isInteger()), |
40 | ignoringParenCasts(InnerMatcher: binaryOperator( |
41 | hasOperatorName(Name: "+"), hasOperands(Matcher1: FloatType, Matcher2: FloatType), |
42 | hasEitherOperand(InnerMatcher: ignoringParenImpCasts(InnerMatcher: FloatHalf))))) |
43 | .bind(ID: "CastExpr")), |
44 | Action: this); |
45 | } |
46 | |
47 | void IncorrectRoundingsCheck::check(const MatchFinder::MatchResult &Result) { |
48 | const auto *CastExpr = Result.Nodes.getNodeAs<ImplicitCastExpr>(ID: "CastExpr"); |
49 | diag(Loc: CastExpr->getBeginLoc(), |
50 | Description: "casting (double + 0.5) to integer leads to incorrect rounding; " |
51 | "consider using lround (#include <cmath>) instead"); |
52 | } |
53 | |
54 | } // namespace clang::tidy::bugprone |
55 |