tcbrindle / flux

A C++20 library for sequence-orientated programming
https://tristanbrindle.com/flux/
Boost Software License 1.0
472 stars 29 forks source link

Use compile-time bounds checking when possible #137

Closed tcbrindle closed 9 months ago

tcbrindle commented 9 months ago

We know that the compiler, when optimising, can remove runtime bounds checks when it can prove that they will never fail.

If would be nice if we could have the converse as well: if the compiler can prove that a "runtime" bounds check is certain to fail, then that should be a compile error.

And that's what this PR does. It uses GCC's __builtin_constant_p to ask whether the index and size parameters are known constants, and if they are (and the bounds check fails) it tries to call the flux::static_bound_check_failed() function. This function is undefined, but more importantly it's marked with the [[gnu::error]] attribute, meaning that we'll get a compile error rather than a linker error, hopefully with a nice backtrace.

This works with GCC and Clang, at -O1 or above (presumably, when enough constant-folding happens in the front end). Otherwise, we'll get a runtime error as normal.

The extra checks can be disabled by defining FLUX_DISABLE_STATIC_BOUNDS_CHECKING before #include-ing Flux.

Thanks to @mattkretz for showing me this trick and suggesting I use it in Flux!

codecov[bot] commented 9 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Comparison is base (7b4cdf6) 97.70% compared to head (78cef5f) 97.71%. Report is 1 commits behind head on main.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #137 +/- ## ======================================= Coverage 97.70% 97.71% ======================================= Files 67 67 Lines 2400 2402 +2 ======================================= + Hits 2345 2347 +2 Misses 55 55 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.