dotnet/runtime

JIT: A case of needing `JitOptRepeat=3` for constant folding and conditional move

Open

#124,700 建立於 2026年2月21日

在 GitHub 查看
 (7 留言) (0 反應) (0 負責人)C# (17,886 star) (5,445 fork)batch import
area-CodeGen-coreclrhelp wantedoptimization

描述

Consider this (https://godbolt.org/z/7b4qsdKTa):

static int Unoptimized(int a, int b)
{
    int num = 0;

    if (a == b)
    {
        num += 3;
    }
    if (a == b)
    {
        num++;
    }
    if (a == b)
    {
        num++;
    }

    return num;
}

which compiles into:

G_M13546_IG02:  ;; offset=0x0000
       xor      eax, eax
       cmp      ecx, edx
       jne      SHORT G_M13546_IG04
						;; size=6 bbWeight=1 PerfScore 1.50

G_M13546_IG03:  ;; offset=0x0006
       mov      eax, 3
       inc      eax
       inc      eax
						;; size=9 bbWeight=0.50 PerfScore 0.38

As can be seen the mov + inc + inc chain is not constant folded. Having JitOptRepeat=2 fixes that:

G_M13546_IG02:  ;; offset=0x0000
       xor      eax, eax
       cmp      ecx, edx
       jne      SHORT G_M13546_IG04
						;; size=6 bbWeight=1 PerfScore 1.50

G_M13546_IG03:  ;; offset=0x0006
       mov      eax, 5
						;; size=5 bbWeight=0.50 PerfScore 0.12

However, there is still a jump. To get a conditional move we need JitOptRepeat=3:

G_M13546_IG02:  ;; offset=0x0000
       xor      eax, eax
       mov      r8d, 5
       cmp      ecx, edx
       cmove    eax, r8d
						;; size=14 bbWeight=1 PerfScore 1.00

The codegen is now equivalent to return (a == b) ? 5 : 0;

貢獻者指南