dotnet/roslyn

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

開放

#68,050 建立於 2023年5月2日

 (4 則留言) (0 個反應) (0 位負責人)C# (4,257 個分叉)batch import
Area-CompilersCode Gen Qualityhelp wanted

倉庫指標

星標
 (20,414 顆星)
PR 合併指標
 (PR 指標待抓取)

描述

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

貢獻者指南