Gabor Horvath | 0b16c10 | 2017-08-10 13:30:30 +0000 | [diff] [blame] | 1 | //===--- IntegerDivisionCheck.cpp - clang-tidy-----------------------------===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 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 |
Gabor Horvath | 0b16c10 | 2017-08-10 13:30:30 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "IntegerDivisionCheck.h" |
| 10 | #include "clang/AST/ASTContext.h" |
| 11 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 | |
| 13 | using namespace clang::ast_matchers; |
| 14 | |
| 15 | namespace clang { |
| 16 | namespace tidy { |
| 17 | namespace bugprone { |
| 18 | |
| 19 | void IntegerDivisionCheck::registerMatchers(MatchFinder *Finder) { |
| 20 | const auto IntType = hasType(isInteger()); |
| 21 | |
Nathan James | 97572fa | 2020-03-10 00:42:21 +0000 | [diff] [blame] | 22 | const auto BinaryOperators = binaryOperator( |
| 23 | hasAnyOperatorName("%", "<<", ">>", "<<", "^", "|", "&", "||", "&&", "<", |
| 24 | ">", "<=", ">=", "==", "!=")); |
Gabor Horvath | 0b16c10 | 2017-08-10 13:30:30 +0000 | [diff] [blame] | 25 | |
Nathan James | 97572fa | 2020-03-10 00:42:21 +0000 | [diff] [blame] | 26 | const auto UnaryOperators = unaryOperator(hasAnyOperatorName("~", "!")); |
Gabor Horvath | 0b16c10 | 2017-08-10 13:30:30 +0000 | [diff] [blame] | 27 | |
| 28 | const auto Exceptions = |
| 29 | anyOf(BinaryOperators, conditionalOperator(), binaryConditionalOperator(), |
| 30 | callExpr(IntType), explicitCastExpr(IntType), UnaryOperators); |
| 31 | |
| 32 | Finder->addMatcher( |
Stephen Kelly | a72307c | 2019-11-12 15:15:56 +0000 | [diff] [blame] | 33 | traverse(ast_type_traits::TK_AsIs, |
| 34 | binaryOperator( |
| 35 | hasOperatorName("/"), hasLHS(expr(IntType)), |
| 36 | hasRHS(expr(IntType)), |
| 37 | hasAncestor(castExpr(hasCastKind(CK_IntegralToFloating)) |
| 38 | .bind("FloatCast")), |
| 39 | unless(hasAncestor(expr( |
| 40 | Exceptions, |
| 41 | hasAncestor(castExpr(equalsBoundNode("FloatCast"))))))) |
| 42 | .bind("IntDiv")), |
Gabor Horvath | 0b16c10 | 2017-08-10 13:30:30 +0000 | [diff] [blame] | 43 | this); |
| 44 | } |
| 45 | |
| 46 | void IntegerDivisionCheck::check(const MatchFinder::MatchResult &Result) { |
| 47 | const auto *IntDiv = Result.Nodes.getNodeAs<BinaryOperator>("IntDiv"); |
Stephen Kelly | 43465bf | 2018-08-09 22:42:26 +0000 | [diff] [blame] | 48 | diag(IntDiv->getBeginLoc(), "result of integer division used in a floating " |
Gabor Horvath | 0b16c10 | 2017-08-10 13:30:30 +0000 | [diff] [blame] | 49 | "point context; possible loss of precision"); |
| 50 | } |
| 51 | |
| 52 | } // namespace bugprone |
| 53 | } // namespace tidy |
| 54 | } // namespace clang |