gchatelet updated this revision to Diff 172778.
gchatelet marked 7 inline comments as done.
gchatelet added a comment.

- Addressing comments and enhancing diagnostics


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53488

Files:
  clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
  clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst
  test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp

Index: test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
===================================================================
--- test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
+++ test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
@@ -1,4 +1,5 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-narrowing-conversions %t
+// RUN: %check_clang_tidy %s cppcoreguidelines-narrowing-conversions %t -- --
+// -target x86_64-unknown-linux
 
 float ceil(float);
 namespace std {
@@ -9,12 +10,12 @@
 namespace floats {
 
 struct ConvertsToFloat {
-  operator float() const { return 0.5; }
+  operator float() const { return 0.5f; }
 };
 
-float operator "" _Pa(unsigned long long);
+float operator"" _float(unsigned long long);
 
-void not_ok(double d) {
+void narrow_double_to_int_not_ok(double d) {
   int i = 0;
   i = d;
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
@@ -24,11 +25,11 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = ConvertsToFloat();
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i = 15_Pa;
+  i = 15_float;
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
 }
 
-void not_ok_binary_ops(double d) {
+void narrow_double_to_int_not_ok_binary_ops(double d) {
   int i = 0;
   i += 0.5;
   // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
@@ -38,7 +39,7 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   // We warn on the following even though it's not dangerous because there is no
   // reason to use a double literal here.
-  // TODO(courbet): Provide an automatic fix.
+  // TODO: Provide an automatic fix if the number is exactly representable in the destination type.
   i += 2.0;
   // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += 2.0f;
@@ -52,6 +53,234 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
 }
 
+double operator"" _double(unsigned long long);
+
+float narrow_double_to_float_return() {
+  return 0.5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: narrowing conversion from 'double' to 'float' [cppcoreguidelines-narrowing-conversions]
+}
+
+void narrow_double_to_float_not_ok(double d) {
+  float f;
+  f = d;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'double' to 'float' [cppcoreguidelines-narrowing-conversions]
+  f = 0.5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'double' to 'float' [cppcoreguidelines-narrowing-conversions]
+  f = 15_double;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'double' to 'float' [cppcoreguidelines-narrowing-conversions]
+}
+
+void narrow_double_to_float_not_ok_binary_ops(double d) {
+  float f;
+  f += 0.5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'float' [cppcoreguidelines-narrowing-conversions]
+  f += d;
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'float' [cppcoreguidelines-narrowing-conversions]
+  // We warn on the following even though it's not dangerous because there is no reason to use a double literal here.
+  // TODO: Provide an automatic fix if the number is exactly representable in the destination type.
+  f += 2.0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'float' [cppcoreguidelines-narrowing-conversions]
+
+  f *= 0.5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'float' [cppcoreguidelines-narrowing-conversions]
+  f /= 0.5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'float' [cppcoreguidelines-narrowing-conversions]
+  f += (double)0.5f;
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'float' [cppcoreguidelines-narrowing-conversions]
+}
+
+void narrow_integer_to_floating() {
+  {
+    long long ll; // 64 bits
+    float f = ll; // doesn't fit in 24 bits
+    // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: narrowing conversion from 'long long' to 'float' [cppcoreguidelines-narrowing-conversions]
+    double d = ll; // doesn't fit in 53 bits.
+    // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: narrowing conversion from 'long long' to 'double' [cppcoreguidelines-narrowing-conversions]
+  }
+  {
+    int i;       // 32 bits
+    float f = i; // doesn't fit in 24 bits
+    // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: narrowing conversion from 'int' to 'float' [cppcoreguidelines-narrowing-conversions]
+    double d = i; // fits in 53 bits.
+  }
+  {
+    short n1, n2;
+    float f = n1 + n2; // 'n1 + n2' is of type 'int' because of integer rules
+    // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: narrowing conversion from 'int' to 'float' [cppcoreguidelines-narrowing-conversions]
+  }
+  {
+    short s;      // 16 bits
+    float f = s;  // fits in 24 bits
+    double d = s; // fits in 53 bits.
+  }
+}
+
+void narrow_integer_to_unsigned_integer_is_ok() {
+  char c;
+  short s;
+  int i;
+  long l;
+  long long ll;
+
+  unsigned char uc;
+  unsigned short us;
+  unsigned int ui;
+  unsigned long ul;
+  unsigned long long ull;
+
+  ui = c;
+  uc = s;
+  uc = i;
+  uc = l;
+  uc = ll;
+
+  uc = uc;
+  uc = us;
+  uc = ui;
+  uc = ul;
+  uc = ull;
+}
+
+void narrow_integer_to_signed_integer_is_not_ok() {
+  char c;
+  short s;
+  int i;
+  long l;
+  long long ll;
+
+  unsigned char uc;
+  unsigned short us;
+  unsigned int ui;
+  unsigned long ul;
+  unsigned long long ull;
+
+  c = c;
+  c = s;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'short' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  c = i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'int' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  c = l;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'long' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  c = ll;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'long long' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+
+  c = uc;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'unsigned char' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  c = us;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'unsigned short' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  c = ui;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'unsigned int' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  c = ul;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'unsigned long' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  c = ull;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'unsigned long long' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+
+  i = c;
+  i = s;
+  i = i;
+  i = l;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'long' to 'int' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  i = ll;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'long long' to 'int' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+
+  i = uc;
+  i = us;
+  i = ui;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'unsigned int' to 'int' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  i = ul;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'unsigned long' to 'int' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  i = ull;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'unsigned long long' to 'int' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+
+  ll = c;
+  ll = s;
+  ll = i;
+  ll = l;
+  ll = ll;
+
+  ll = uc;
+  ll = us;
+  ll = ui;
+  ll = ul;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from 'unsigned long' to 'long long' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  ll = ull;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from 'unsigned long long' to 'long long' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+}
+
+void narrow_constant_to_unsigned_integer_is_ok() {
+  unsigned char uc1 = 0;
+  unsigned char uc2 = 255;
+  unsigned char uc3 = -1;  // unsigned dst type is well defined.
+  unsigned char uc4 = 256; // unsigned dst type is well defined.
+  unsigned short us1 = 0;
+  unsigned short us2 = 65535;
+  unsigned short us3 = -1;    // unsigned dst type is well defined.
+  unsigned short us4 = 65536; // unsigned dst type is well defined.
+}
+
+void narrow_constant_to_signed_integer_is_not_ok() {
+  char c1 = -128;
+  char c2 = 127;
+  char c3 = -129;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: narrowing conversion from constant value -129 (0x00000000FFFFFF7F) of type 'int' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  char c4 = 128;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: narrowing conversion from constant value 128 (0x0000000000000080) of type 'int' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+
+  short s1 = -32768;
+  short s2 = 32767;
+  short s3 = -32769;
+  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: narrowing conversion from constant value -32769 (0x00000000FFFF7FFF) of type 'int' to 'short' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  short s4 = 32768;
+  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: narrowing conversion from constant value 32768 (0x0000000000008000) of type 'int' to 'short' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+}
+
+void narrow_conditional_operator_contant_to_unsigned_is_ok(bool b) {
+  // conversion to unsigned dst type is well defined.
+  unsigned char c1 = b ? 1 : 0;
+  unsigned char c2 = b ? 1 : 256;
+  unsigned char c3 = b ? -1 : 0;
+}
+
+void narrow_conditional_operator_contant_to_signed_is_not_ok(bool b) {
+  char uc1 = b ? 1 : 0;
+  char uc2 = b ? 1 : 128;
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: narrowing conversion from constant value 128 (0x0000000000000080) of type 'int' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+  char uc3 = b ? -129 : 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: narrowing conversion from constant value -129 (0x00000000FFFFFF7F) of type 'int' to 'char' is implementation-defined [cppcoreguidelines-narrowing-conversions]
+}
+
+void narrow_constant_to_floating_point() {
+  float f_ok = 1ULL << 24;              // fits in 24 bits mantissa.
+  float f_not_ok = (1ULL << 24) + 1ULL; // doesn't fit in 24 bits mantissa.
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: narrowing conversion from constant value 16777217 of type 'unsigned long long' to 'float' [cppcoreguidelines-narrowing-conversions]
+  double d_ok = 1ULL << 53;              // fits in 53 bits mantissa.
+  double d_not_ok = (1ULL << 53) + 1ULL; // doesn't fit in 53 bits mantissa.
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: narrowing conversion from constant value 9007199254740993 of type 'unsigned long long' to 'double' [cppcoreguidelines-narrowing-conversions]
+}
+
+void casting_integer_to_bool_is_ok() {
+  int i;
+  while (i) {
+  }
+  for (; i;) {
+  }
+  if (i) {
+  }
+}
+
+void casting_float_to_bool_is_not_ok() {
+  float f;
+  while (f) {
+    // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: narrowing conversion from 'float' to 'bool' [cppcoreguidelines-narrowing-conversions]
+  }
+  for (; f;) {
+    // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: narrowing conversion from 'float' to 'bool' [cppcoreguidelines-narrowing-conversions]
+  }
+  if (f) {
+    // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'bool' [cppcoreguidelines-narrowing-conversions]
+  }
+}
+
 void ok(double d) {
   int i = 0;
   i = 1;
@@ -89,15 +318,19 @@
 
 void template_context() {
   f(1, 2);
+  f(1, .5f);
   f(1, .5);
+  f(1, .5l);
 }
 
 #define DERP(i, j) (i += j)
 
 void macro_context() {
   int i = 0;
   DERP(i, 2);
+  DERP(i, .5f);
   DERP(i, .5);
+  DERP(i, .5l);
 }
 
-}  // namespace floats
+} // namespace floats
Index: docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst
===================================================================
--- docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst
+++ docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst
@@ -10,13 +10,17 @@
 This rule is part of the "Expressions and statements" profile of the C++ Core
 Guidelines, corresponding to rule ES.46. See
 
-https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-narrowing.
+https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es46-avoid-lossy-narrowing-truncating-arithmetic-conversions.
 
-We enforce only part of the guideline, more specifically, we flag:
- - All floating-point to integer conversions that are not marked by an explicit
-   cast (c-style or ``static_cast``). For example: ``int i = 0; i += 0.1;``,
-   ``void f(int); f(0.1);``,
- - All applications of binary operators where the left-hand-side is an integer
-   and the right-hand-size is a floating-point. For example:
-   ``int i; i+= 0.1;``.
+We enforce only part of the guideline, more specifically, we flag narrowing conversions from:
+ - an integer to a narrower integer (e.g. ``char`` to ``unsigned char``),
+ - an integer to a narrower floating-point (e.g. ``uint64_t`` to ``float``),
+ - a floating-point to an integer (e.g. ``double`` to ``int``),
+ - a floating-point to a narrower floating-point (e.g. ``double`` to ``float``).
 
+This check will flag:
+ - All narrowing conversions that are not marked by an explicit cast (c-style or
+   ``static_cast``). For example: ``int i = 0; i += 0.1;``,
+   ``void f(int); f(0.1);``,
+ - All applications of binary operators with a narrowing conversions.
+   For example: ``int i; i+= 0.1;``.
Index: docs/ReleaseNotes.rst
===================================================================
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -182,6 +182,11 @@
   <clang-tidy/checks/readability-redundant-smartptr-get>` check does not warn
   about calls inside macros anymore by default.
 
+- The :doc:`cppcoreguidelines-narrowing-conversions
+  <clang-tidy/checks/cppcoreguidelines-narrowing-conversions>` check now
+  detects narrowing conversions between floating-point types
+  (e.g. ``double`` to ``float``).
+
 Improvements to include-fixer
 -----------------------------
 
Index: clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
===================================================================
--- clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
+++ clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
@@ -28,6 +28,27 @@
       : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+
+private:
+  void diagIfNarrowType(const ASTContext &Context, SourceLocation SourceLoc,
+                        const Expr *Lhs, const Expr *Rhs);
+
+  void diagIfNarrowConstantIntegral(const ASTContext &Context,
+                                    SourceLocation SourceLoc, const Expr *Lhs,
+                                    const Expr *Rhs,
+                                    const llvm::APSInt &RhsIntegerConstant);
+
+  bool diagIfNarrowConstant(const ASTContext &Context, SourceLocation SourceLoc,
+                            const Expr *Lhs, const Expr *Rhs);
+
+  bool diagIfNarrowConstantInConditionalOperator(const ASTContext &Context,
+                                                 SourceLocation SourceLoc,
+                                                 const Expr *Lhs,
+                                                 const Expr *Rhs);
+
+  void diagIfNarrower(const ASTContext &Context, SourceLocation BeginLoc,
+                      SourceLocation SourceLoc, const Expr *Lhs,
+                      const Expr *Rhs);
 };
 
 } // namespace cppcoreguidelines
Index: clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
===================================================================
--- clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
+++ clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
@@ -9,60 +9,300 @@
 
 #include "NarrowingConversionsCheck.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Type.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/APSInt.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Mutex.h"
+
+#include <cstdint>
 
 using namespace clang::ast_matchers;
 
 namespace clang {
 namespace tidy {
 namespace cppcoreguidelines {
 
-// FIXME: Check double -> float truncation. Pay attention to casts:
 void NarrowingConversionsCheck::registerMatchers(MatchFinder *Finder) {
   // ceil() and floor() are guaranteed to return integers, even though the type
   // is not integral.
-  const auto IsCeilFloorCall = callExpr(callee(functionDecl(
-      hasAnyName("::ceil", "::std::ceil", "::floor", "::std::floor"))));
-
-  const auto IsFloatExpr =
-      expr(hasType(realFloatingPointType()), unless(IsCeilFloorCall));
+  const auto IsCeilFloorCallExpr = expr(callExpr(callee(functionDecl(
+      hasAnyName("::ceil", "::std::ceil", "::floor", "::std::floor")))));
 
-  // casts:
+  // Casts:
   //   i = 0.5;
   //   void f(int); f(0.5);
-  Finder->addMatcher(implicitCastExpr(hasImplicitDestinationType(isInteger()),
-                                      hasSourceExpression(IsFloatExpr),
-                                      unless(hasParent(castExpr())),
-                                      unless(isInTemplateInstantiation()))
-                         .bind("cast"),
-                     this);
+  Finder->addMatcher(
+      implicitCastExpr(hasImplicitDestinationType(builtinType()),
+                       hasSourceExpression(hasType(builtinType())),
+                       unless(hasSourceExpression(IsCeilFloorCallExpr)),
+                       unless(hasParent(castExpr())),
+                       unless(isInTemplateInstantiation()))
+          .bind("cast"),
+      this);
 
   // Binary operators:
   //   i += 0.5;
-  Finder->addMatcher(
-      binaryOperator(isAssignmentOperator(),
-                     // The `=` case generates an implicit cast which is covered
-                     // by the previous matcher.
-                     unless(hasOperatorName("=")),
-                     hasLHS(hasType(isInteger())), hasRHS(IsFloatExpr),
-                     unless(isInTemplateInstantiation()))
-          .bind("op"),
-      this);
+  Finder->addMatcher(binaryOperator(isAssignmentOperator(),
+                                    hasLHS(expr(hasType(builtinType()))),
+                                    hasRHS(expr(hasType(builtinType()))),
+                                    unless(hasRHS(IsCeilFloorCallExpr)),
+                                    unless(isInTemplateInstantiation()),
+                                    // The `=` case generates an implicit cast
+                                    // which is covered by the previous matcher.
+                                    unless(hasOperatorName("=")))
+                         .bind("binary_op"),
+                     this);
 }
 
-void NarrowingConversionsCheck::check(const MatchFinder::MatchResult &Result) {
-  if (const auto *Op = Result.Nodes.getNodeAs<BinaryOperator>("op")) {
-    if (Op->getBeginLoc().isMacroID())
+static const BuiltinType *getBuiltinType(const Expr *E) {
+  if (const Type *T = E->getType().getCanonicalType().getTypePtrOrNull())
+    return T->getAs<BuiltinType>();
+  return nullptr;
+}
+
+namespace {
+
+struct IntegerRange {
+  bool Contains(const IntegerRange &From) const {
+    return (llvm::APSInt::compareValues(Lower, From.Lower) <= 0) &&
+           (llvm::APSInt::compareValues(Upper, From.Upper) >= 0);
+  }
+
+  bool Contains(const llvm::APSInt &Value) const {
+    return (llvm::APSInt::compareValues(Lower, Value) <= 0) &&
+           (llvm::APSInt::compareValues(Upper, Value) >= 0);
+  }
+
+  llvm::APSInt Lower;
+  llvm::APSInt Upper;
+};
+
+} // namespace
+
+static IntegerRange createFromType(const ASTContext &Context,
+                                   const BuiltinType *T) {
+  assert(T && "T must not be nullptr");
+  if (T->isFloatingPoint()) {
+    unsigned PrecisionBits = llvm::APFloatBase::semanticsPrecision(
+        Context.getFloatTypeSemantics(T->desugar()));
+    // Contrary to two's complement integer, floating point values are
+    // symmetric and have the same number of positive and negative values.
+    // The range of valid integer for a floating point value is:
+    // [-2^PrecisionBits, 2^PrecisionBits]
+
+    // Values are created with PrecisionBits plus two bytes:
+    // - One to express the missing negative value of 2's complement
+    //   representation.
+    // - One for the sign.
+    llvm::APSInt UpperValue(PrecisionBits + 2, /*isUnsigned*/ false);
+    UpperValue.setBit(PrecisionBits);
+    llvm::APSInt LowerValue(PrecisionBits + 2, /*isUnsigned*/ false);
+    LowerValue.setBit(PrecisionBits);
+    LowerValue.setSignBit();
+    return {LowerValue, UpperValue};
+  }
+  if (T->isSignedInteger())
+    return {llvm::APSInt::getMinValue(Context.getTypeSize(T), false),
+            llvm::APSInt::getMaxValue(Context.getTypeSize(T), false)};
+  if (T->isUnsignedInteger())
+    return {llvm::APSInt::getMinValue(Context.getTypeSize(T), true),
+            llvm::APSInt::getMaxValue(Context.getTypeSize(T), true)};
+
+  llvm::errs() << "Unhandled type " << T->getName(Context.getPrintingPolicy())
+               << "\n";
+  llvm_unreachable("Unhandled type");
+}
+
+static bool isWideEnoughToHold(const ASTContext &Context,
+                               const BuiltinType *FromType,
+                               const BuiltinType *ToType) {
+  IntegerRange FromIntegerRange = createFromType(Context, FromType);
+  IntegerRange ToIntegerRange = createFromType(Context, ToType);
+  return ToIntegerRange.Contains(FromIntegerRange);
+}
+
+static bool isWideEnoughToHold(const ASTContext &Context,
+                               const llvm::APSInt &IntegerConstant,
+                               const BuiltinType *ToType) {
+  IntegerRange ToIntegerRange = createFromType(Context, ToType);
+  return ToIntegerRange.Contains(IntegerConstant);
+}
+
+static QualType getUnqualifiedType(const Expr *Expr) {
+  return Expr->getType().getUnqualifiedType();
+}
+
+static llvm::SmallString<64> getValueAsString(const llvm::APSInt &Value,
+                                              uint64_t HexBytes) {
+  llvm::SmallString<64> Str;
+  Value.toString(Str, 10);
+  if (HexBytes > 0) {
+    Str.append(" (0x");
+    llvm::SmallString<32> HexValue;
+    Value.toStringUnsigned(HexValue, 16);
+    for (size_t I = HexValue.size(); I < (HexBytes / 2); ++I)
+      Str.append("0");
+    Str.append(HexValue);
+    Str.append(")");
+  }
+  return Str;
+}
+
+void NarrowingConversionsCheck::diagIfNarrowType(const ASTContext &Context,
+                                                 SourceLocation SourceLoc,
+                                                 const Expr *Lhs,
+                                                 const Expr *Rhs) {
+  const BuiltinType *ToType = getBuiltinType(Lhs);
+  const BuiltinType *FromType = getBuiltinType(Rhs);
+  if (ToType == FromType || ToType == nullptr || FromType == nullptr ||
+      ToType->isInstantiationDependentType() ||
+      FromType->isInstantiationDependentType())
+    return;
+
+  if (FromType->isRealFloatingType() && ToType->isIntegerType()) {
+    diag(SourceLoc, "narrowing conversion from %0 to %1")
+        << getUnqualifiedType(Rhs) << getUnqualifiedType(Lhs);
+    return;
+  }
+
+  if (FromType->isIntegerType() && ToType->isIntegerType()) {
+    // Integer to Bool type conversions are well defined and not considered as a
+    // narrowing. The following clang tidy already flags invalid boolean
+    // conversions.
+    // https://clang.llvm.org/extra/clang-tidy/checks/readability-implicit-bool-conversion.html
+    if ((ToType->getKind() == BuiltinType::Bool) ||
+        (FromType->getKind() == BuiltinType::Bool))
+      return;
+    // Conversions to unsigned integer are well defined and follow modulo 2
+    // arithmetic.
+    if (ToType->isUnsignedInteger())
       return;
-    diag(Op->getOperatorLoc(), "narrowing conversion from %0 to %1")
-        << Op->getRHS()->getType() << Op->getLHS()->getType();
+    // Destination type is signed, narrowing would lead to implementation
+    // defined behavior.
+    if (!isWideEnoughToHold(Context, FromType, ToType))
+      diag(SourceLoc,
+           "narrowing conversion from %0 to %1 is implementation-defined")
+          << getUnqualifiedType(Rhs) << getUnqualifiedType(Lhs);
+    return;
+  }
+
+  // TODO: Guard by an Option since this is expected to trigger often.
+  if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
+    if (ToType->getKind() < FromType->getKind())
+      diag(SourceLoc, "narrowing conversion from %0 to %1")
+          << getUnqualifiedType(Rhs) << getUnqualifiedType(Lhs);
+    return;
+  }
+
+  if (FromType->isIntegerType() && ToType->isRealFloatingType()) {
+    if (!isWideEnoughToHold(Context, FromType, ToType))
+      diag(SourceLoc, "narrowing conversion from %0 to %1")
+          << getUnqualifiedType(Rhs) << getUnqualifiedType(Lhs);
+    return;
+  }
+
+  llvm::errs() << "Unhandled from type "
+               << FromType->getName(Context.getPrintingPolicy()) << "or to type"
+               << ToType->getName(Context.getPrintingPolicy()) << "\n";
+  llvm_unreachable("Unhandled case");
+}
+
+void NarrowingConversionsCheck::diagIfNarrowConstantIntegral(
+    const ASTContext &Context, SourceLocation SourceLoc, const Expr *Lhs,
+    const Expr *Rhs, const llvm::APSInt &RhsIntegerConstant) {
+  const BuiltinType *ToType = getBuiltinType(Lhs);
+  const BuiltinType *FromType = getBuiltinType(Rhs);
+  assert(ToType && "Lhs must be a builtin type");
+  assert(FromType && "Rhs must be a builtin type");
+  assert(FromType->isInteger() && "Rhs is integer constant");
+  // The AST already handles promotion rules so we're only checking conversion
+  // rules (https://en.cppreference.com/w/cpp/language/implicit_conversion).
+
+  if (ToType->isBooleanType())
+    return; // conversion to bool value is well defined.
+
+  if (ToType->isUnsignedInteger())
+    return; // conversion to unsigned integer value is well defined.
+
+  // Narrowing from an integer to a signed integer is implementation-defined.
+  if (ToType->isSignedInteger() &&
+      !isWideEnoughToHold(Context, RhsIntegerConstant, ToType)) {
+    diag(SourceLoc, "narrowing conversion from constant value %0 of type %1 to "
+                    "%2 is implementation-defined")
+        << getValueAsString(RhsIntegerConstant, Context.getTypeSize(FromType))
+        << getUnqualifiedType(Rhs) << getUnqualifiedType(Lhs);
     return;
   }
-  const auto *Cast = Result.Nodes.getNodeAs<ImplicitCastExpr>("cast");
-  if (Cast->getBeginLoc().isMacroID())
+
+  // Narrowing from an integer to a floating point type.
+  if (ToType->isFloatingPoint() &&
+      !isWideEnoughToHold(Context, RhsIntegerConstant, ToType)) {
+    diag(SourceLoc,
+         "narrowing conversion from constant value %0 of type %1 to %2")
+        << getValueAsString(RhsIntegerConstant, /*NoHex*/ 0)
+        << getUnqualifiedType(Rhs) << getUnqualifiedType(Lhs);
     return;
-  diag(Cast->getExprLoc(), "narrowing conversion from %0 to %1")
-      << Cast->getSubExpr()->getType() << Cast->getType();
+  }
+}
+
+bool NarrowingConversionsCheck::diagIfNarrowConstant(const ASTContext &Context,
+                                                     SourceLocation SourceLoc,
+                                                     const Expr *Lhs,
+                                                     const Expr *Rhs) {
+  if (Lhs->isInstantiationDependent() || Rhs->isInstantiationDependent())
+    return false;
+
+  llvm::APSInt IntegerConstant;
+  if (Rhs->isIntegerConstantExpr(IntegerConstant, Context)) {
+    diagIfNarrowConstantIntegral(Context, SourceLoc, Lhs, Rhs, IntegerConstant);
+    return true;
+  }
+
+  // TODO: Handle floating point constant conversions as well.
+
+  return false;
+}
+
+bool NarrowingConversionsCheck::diagIfNarrowConstantInConditionalOperator(
+    const ASTContext &Context, SourceLocation SourceLoc, const Expr *Lhs,
+    const Expr *Rhs) {
+  if (const auto *CO = llvm::dyn_cast<ConditionalOperator>(Rhs)) {
+    // We create variables so we make sure both sides of the
+    // ConditionalOperator are evaluated, the || operator would shortciruit
+    // the second call otherwise.
+    bool NarrowLhs = diagIfNarrowConstant(Context, CO->getLHS()->getExprLoc(),
+                                          Lhs, CO->getLHS());
+    bool NarrowRhs = diagIfNarrowConstant(Context, CO->getRHS()->getExprLoc(),
+                                          Lhs, CO->getRHS());
+    return NarrowLhs || NarrowRhs;
+  }
+  return false;
+}
+
+void NarrowingConversionsCheck::diagIfNarrower(const ASTContext &Context,
+                                               SourceLocation BeginLoc,
+                                               SourceLocation SourceLoc,
+                                               const Expr *Lhs,
+                                               const Expr *Rhs) {
+  if (BeginLoc.isMacroID())
+    return;
+  if (diagIfNarrowConstantInConditionalOperator(Context, SourceLoc, Lhs, Rhs))
+    return;
+  if (diagIfNarrowConstant(Context, SourceLoc, Lhs, Rhs))
+    return;
+  diagIfNarrowType(Context, SourceLoc, Lhs, Rhs);
+}
+
+void NarrowingConversionsCheck::check(const MatchFinder::MatchResult &Result) {
+  if (const auto *Op = Result.Nodes.getNodeAs<BinaryOperator>("binary_op"))
+    return diagIfNarrower(*Result.Context, Op->getBeginLoc(),
+                          Op->getOperatorLoc(), Op->getLHS(), Op->getRHS());
+  if (const auto *Cast = Result.Nodes.getNodeAs<ImplicitCastExpr>("cast"))
+    return diagIfNarrower(*Result.Context, Cast->getBeginLoc(),
+                          Cast->getExprLoc(), Cast, Cast->getSubExpr());
+  llvm_unreachable("must be binary operator or cast expression");
 }
 
 } // namespace cppcoreguidelines
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to