1 //===--- IntegerDivisionCheck.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 "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 22 const auto BinaryOperators = binaryOperator( 23 hasAnyOperatorName("%", "<<", ">>", "<<", "^", "|", "&", "||", "&&", "<", 24 ">", "<=", ">=", "==", "!=")); 25 26 const auto UnaryOperators = unaryOperator(hasAnyOperatorName("~", "!")); 27 28 const auto Exceptions = 29 anyOf(BinaryOperators, conditionalOperator(), binaryConditionalOperator(), 30 callExpr(IntType), explicitCastExpr(IntType), UnaryOperators); 31 32 Finder->addMatcher( 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")), 43 this); 44 } 45 46 void IntegerDivisionCheck::check(const MatchFinder::MatchResult &Result) { 47 const auto *IntDiv = Result.Nodes.getNodeAs<BinaryOperator>("IntDiv"); 48 diag(IntDiv->getBeginLoc(), "result of integer division used in a floating " 49 "point context; possible loss of precision"); 50 } 51 52 } // namespace bugprone 53 } // namespace tidy 54 } // namespace clang 55