RFR: 8336759: C2: int counted loop with long limit not recognized as counted loop [v3]

Roland Westrelin roland at openjdk.org
Thu Dec 5 12:44:40 UTC 2024


On Wed, 4 Dec 2024 16:11:58 GMT, Kangcheng Xu <kxu at openjdk.org> wrote:

>> This patch implements [JDK-8336759](https://bugs.openjdk.org/browse/JDK-8336759) that recognizes int counted loops with long limits.
>> 
>> Currently, patterns like `for ( int i =...; i < long_limit; ...)` where int `i` is implicitly promoted to long (i.e., `(long) i < long_limit`) is not recognized as (int) counted loop. This patch speculatively and optimistically converts long limits to ints and deoptimize if the limit is outside int range, allowing more optimization opportunities. 
>> 
>> In other words, it transforms 
>> 
>> 
>> for (int i = 0; (long) i < long_limit; i++) {...}
>> 
>> 
>> to 
>> 
>> 
>> if (int_min <= long_limit && long_limit <= int_max ) {
>>     for (int i = 0;  i < (int) long_limit; i++) {...}
>> } else {
>>     trap: loop_limit_check
>> }
>> 
>> 
>> This could benefit calls to APIs like `long MemorySegment#byteSize()` when iterating over a long limit.
>
> Kangcheng Xu has updated the pull request incrementally with three additional commits since the last revision:
> 
>  - Update src/hotspot/share/opto/loopnode.cpp
>    
>    Co-authored-by: Christian Hagedorn <christian.hagedorn at oracle.com>
>  - Update src/hotspot/share/opto/loopnode.cpp
>    
>    Co-authored-by: Christian Hagedorn <christian.hagedorn at oracle.com>
>  - Update src/hotspot/share/opto/loopnode.cpp
>    
>    Co-authored-by: Christian Hagedorn <christian.hagedorn at oracle.com>

It would be nice to refactor the code so the part where the exit condition is modified, transformation into a counted loop is attempted and if it fails the exit condition is restored back to what it was can be avoided.

`is_counted_loop()` roughly is:

if (loop_pattern_matches_counted_loop()) {
  transform_into_counted_loop();
}

Maybe the code can be refactored that way so that then `convert_to_counted_loop_with_speculative_long_limit` can be something like:

if (loop_pattern_matches_counted_loop()) {
  // convert CmpL to CmpI
  transform_into_counted_loop();
}

You would likely need to extract the check for:


  Node* cmp = loop_exit_test(back_control, loop, incr, limit, bt, cl_prob);
  if (cmp == nullptr || cmp->Opcode() != Op_Cmp(iv_bt)) {


out of `loop_pattern_matches_counted_loop()` so `convert_to_counted_loop_with_speculative_long_limit` can pattern match the exit condition it expects

-------------

PR Comment: https://git.openjdk.org/jdk/pull/22449#issuecomment-2520215899


More information about the hotspot-compiler-dev mailing list