In computer science, bounds-checking elimination is a compiler optimization useful in programming languages or runtimes that enforce bounds checking, the practice of checking every index into an array to verify that the index is within the defined valid range of indexes. Its goal is to detect which of these indexing operations do not need to be validated at runtime, and eliminating those checks.
One common example is accessing an array element, modifying it, and storing the modified value in the same array at the same location. Normally, this example would result in a bounds check when the element is read from the array and a second bounds check when the modified element is stored using the same array index. Bounds-checking elimination could eliminate the second check if the compiler or runtime can determine that neither the array size nor the index could change between the two array operations.
Another example occurs when a programmer loops over the elements of the array, and the loop condition guarantees that the index is within the bounds of the array. It may be difficult to detect that the programmer's manual check renders the automatic check redundant. However, it may still be possible for the compiler or runtime to perform proper bounds-checking elimination in this case.
In natively compiled languages
One technique for bounds-checking elimination is to use a typed static single assignment form representation and for each array create a new type representing a safe index for that particular array. The first use of a value as an array index results in a runtime type cast (and appropriate check), but subsequently the safe index value can be used without a type cast, without sacrificing correctness or safety.
In JIT-compiled languages
Just-in-time compiled languages such as Java often check indexes at runtime before accessing arrays. Some just-in-time compilers such as HotSpot are able to eliminate some of these checks if they discover that the index is always within the correct range, or if an earlier check would have already thrown an exception.
- Kawaguchi, Kohsuke (2008-03-30). "Deep dive into assembly code from Java". Retrieved 2008-04-02.
- "Fast, Effective Code Generation in a Just-In-Time Java Compiler" (PDF). Intel Corporation. Retrieved 2007-06-22.
- W. Amme, J. von Ronne, M. Franz. Using the SafeTSA Representation to Boost the Performance of an Existing Java Virtual Machine (2002).