Skip to content

Commit ab02319

Browse files
authored
[clang-tidy] fix wrong float to float conversion check when floating point type is not standard type (#122637)
compare type kind is the wrong way to compare floating point type compatibility. more generic compatibility check is needed.
1 parent ad56f62 commit ab02319

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -513,7 +513,9 @@ void NarrowingConversionsCheck::handleFloatingCast(const ASTContext &Context,
513513
return;
514514
}
515515
const BuiltinType *FromType = getBuiltinType(Rhs);
516-
if (ToType->getKind() < FromType->getKind())
516+
if (!llvm::APFloatBase::isRepresentableBy(
517+
Context.getFloatTypeSemantics(FromType->desugar()),
518+
Context.getFloatTypeSemantics(ToType->desugar())))
517519
diagNarrowType(SourceLoc, Lhs, Rhs);
518520
}
519521
}

clang-tools-extra/docs/ReleaseNotes.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,11 @@ Changes in existing checks
210210
<clang-tidy/checks/bugprone/forwarding-reference-overload>` check by fixing
211211
a crash when determining if an ``enable_if[_t]`` was found.
212212

213+
- Improve :doc:`bugprone-narrowing-conversions
214+
<clang-tidy/checks/bugprone/narrowing-conversions>` to avoid incorrect check
215+
results when floating point type is not ``float``, ``double`` and
216+
``long double``.
217+
213218
- Improved :doc:`bugprone-optional-value-conversion
214219
<clang-tidy/checks/bugprone/optional-value-conversion>` to support detecting
215220
conversion directly by ``std::make_unique`` and ``std::make_shared``.

clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-narrowingfloatingpoint-option.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,15 @@ void narrow_double_to_float_not_ok(double d) {
3636
f = narrow_double_to_float_return();
3737
}
3838

39+
float narrow_float16_to_float_return(_Float16 f) {
40+
return f;
41+
}
42+
43+
_Float16 narrow_float_to_float16_return(float f) {
44+
return f;
45+
// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: narrowing conversion from 'float' to '_Float16' [bugprone-narrowing-conversions]
46+
}
47+
3948
void narrow_fp_constants() {
4049
float f;
4150
f = 0.5; // [dcl.init.list] 7.2 : in-range fp constant to narrower float is not a narrowing.

0 commit comments

Comments
 (0)