KEMBAR78
JIT: Optimize counted loops by reversing them · Issue #100915 · dotnet/runtime · GitHub
Skip to content

JIT: Optimize counted loops by reversing them #100915

@jakobbotsch

Description

@jakobbotsch

The JIT should be able to optimize counted loops like

private static void Foo()
{
    for (int i = 0; i < 100; i++)
    {
        Bar();
    }
}

to the equivalent downwards counting loop, which is more efficient on both x64 and arm64.

Current codegen:
x64:

G_M35517_IG02:  ;; offset=0x0005
       xor      ebx, ebx
						;; size=2 bbWeight=1 PerfScore 0.25

G_M35517_IG03:  ;; offset=0x0007
       call     [RangeCheck_Overflow:Bar()]
       inc      ebx
       cmp      ebx, 100
       jl       SHORT G_M35517_IG03
						;; size=13 bbWeight=4 PerfScore 18.00

arm64:

G_M35517_IG02:  ;; offset=0x000C
            mov     w19, wzr
						;; size=4 bbWeight=1 PerfScore 0.50

G_M35517_IG03:  ;; offset=0x0010
            movz    x0, #0x6820      // code for Program:Bar()
            movk    x0, #0x6A29 LSL #16
            movk    x0, #0x7FF9 LSL #32
            ldr     x0, [x0]
            blr     x0
            add     w19, w19, #1
            cmp     w19, #100
            blt     G_M35517_IG03
						;; size=32 bbWeight=4 PerfScore 30.00

Expected codegen:
x64:

G_M35517_IG02:  ;; offset=0x0005
       mov      ebx, 100
						;; size=5 bbWeight=1 PerfScore 0.25

G_M35517_IG03:  ;; offset=0x000A
       call     [RangeCheck_Overflow:Bar()]
       dec      ebx
       jne      SHORT G_M35517_IG03
						;; size=10 bbWeight=4 PerfScore 17.00

arm64:

G_M35517_IG02:  ;; offset=0x000C
            mov     w19, #100
						;; size=4 bbWeight=1 PerfScore 0.50

G_M35517_IG03:  ;; offset=0x0010
            movz    x0, #0x6820      // code for Program:Bar()
            movk    x0, #0x6A2B LSL #16
            movk    x0, #0x7FF9 LSL #32
            ldr     x0, [x0]
            blr     x0
            sub     w19, w19, #1
            cbnz    w19, G_M35517_IG03
						;; size=28 bbWeight=4 PerfScore 28.00

Metadata

Metadata

Assignees

Labels

Priority:2Work that is important, but not critical for the releasearea-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions