dotnet/roslyn

Conditionnally skip over Add/Sub/Or when used with a ternary and constant zero

オープン

#68,050 opened on 2023/05/02

 (4 件のコメント) (0 件のリアクション) (0 人の担当者)C# (4,257 件のフォーク)batch import
Area-CompilersCode Gen Qualityhelp wanted

Repository metrics

Stars
 (20,414 個のスター)
PR merge metrics
 (PR metrics pending)

説明

When operations + - | (Add, Subtract, Bitwise-Or) are used with a ternary operator, in which one of the expression evaluates to a constant 0, I would expect the IL to just skip over that operation

(suggestion could be expanded to Multiply/Divide by ternary with constant 1, or Bitwise-And with ~0)

Version Used: sdk\7.0.203

Steps to Reproduce:

Here is my test code, with ChatInviteFlags being a [Flags] enum:

var ci = (ChatInviteFlags)int.Parse(Console.ReadLine());

int flags = 1024 |
	(ci.HasFlag(ChatInviteFlags.broadcast) ? 32 : 0) |
	(ci.HasFlag(ChatInviteFlags.pub) ? 64 : 0) |
	(ci.HasFlag(ChatInviteFlags.megagroup) ? 128 : 0);

Console.WriteLine(flags);

Expected Behavior: I would expect the OR operations to be optimized by skipping over them entirely when the ternary conditions are false:

	IL_0021: brfalse.s IL_0026
	IL_0023: ldc.i4.s 32
	IL_0025: or

Actual Behavior: Here is the IL currently generated:

	IL_0021: brtrue.s IL_0026
	IL_0023: ldc.i4.0
	IL_0024: br.s IL_0028
	IL_0026: ldc.i4.s 32
	IL_0028: or

コントリビューターガイド