Use compile-time bounds checking when possible #137
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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!