Bounds-checking elimination explained

In computer science, bounds-checking elimination is a compiler optimization useful in programming languages or runtime systems 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.[1] 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.

Implementations

In natively compiled languages

One technique for bounds-checking elimination is to use a typed static single assignment form representation and for each array to 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 and C# 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.[2] [3]

External links

Notes and References

  1. Book: Steven Muchnick. Muchnick and Associates. Advanced Compiler Design Implementation. registration. bounds-checking elimination.. 15 August 1997. Morgan Kaufmann. 978-1-55860-320-2.
  2. Web site: Deep dive into assembly code from Java . Kawaguchi . Kohsuke . 2008-03-30 . 2008-04-02 . https://web.archive.org/web/20080402034758/http://weblogs.java.net/blog/kohsuke/archive/2008/03/deep_dive_into.html . 2008-04-02 . dead.
  3. Web site: Fast, Effective Code Generation in a Just-In-Time Java Compiler. Intel Corporation. 2007-06-22.