llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
29.15k stars 12.03k forks source link

[clang-tidy] false positives on check "bugprone-implicit-widening-of-multiplication-result" #58709

Open m9710797 opened 2 years ago

m9710797 commented 2 years ago

Hi,

I like this check: https://clang.llvm.org/extra/clang-tidy/checks/bugprone/implicit-widening-of-multiplication-result.html Though in my code base over half of the reported cases are false positives.

I've prepared some minimal example to demonstrate the problem:

https://godbolt.org/z/6M4Kj1sd6

int constant(int* p)
{
    return p[3 * 4];
}

int in_range(int*p, unsigned char u8)
{
    return p[0x4000 * u8];
}

In the first function the multiplication is done on constants (could be integer literals or constexpr variables). The calculated index remains the same whether we do the multiplication before or after the widening.

The second function is similar: whatever the value of the u8 variable (0..255), the result of the multiplication will never overflow, and thus the order of the widening and multiplication operations doesn't make a difference.

I have no idea how difficult it would be to extend clang-tidy to recognize and filter these cases (possibly behind an option). But it would be useful to me. Thanks!

llvmbot commented 2 years ago

@llvm/issue-subscribers-clang-tidy

cwarner-8702 commented 4 months ago

A PR was merged yesterday that should suppress warnings for signed integer types when the result of the expression can be calculated at compile time (unsigned integers are a little more complicated, so it may take a bit longer): https://github.com/llvm/llvm-project/commit/f964e8a3f9ef9789f9075694cb887d0b3986d304

Calculating the result based on the minimum and maximum possible limits of one of the operands is an interesting idea!