Skip to content

Commit 007df05

Browse files
authored
[JIT] - X64 - Peephole optimization to possibly skip emitting and reg, -1 (#80468)
* Optimize 'x & -1' to a cast * Check for small type * Update gentree.cpp * Use peephole optimization instead as it catches more cases * Simplify logic * Fix comment. Added test case. * Update IntAnd.cs * Check for set flags * Check explicitly for TYP_INT
1 parent f60d188 commit 007df05

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

src/coreclr/jit/codegenxarch.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -998,6 +998,17 @@ void CodeGen::genCodeForBinary(GenTreeOp* treeNode)
998998
src = op2;
999999
}
10001000

1001+
// We can skip emitting 'and reg0, -1` if we know that the upper 32bits of 'reg0' are zero'ed.
1002+
if (compiler->opts.OptimizationEnabled())
1003+
{
1004+
if ((oper == GT_AND) && (targetType == TYP_INT) && !treeNode->gtSetFlags() && op2->IsIntegralConst(-1) &&
1005+
emit->AreUpper32BitsZero(targetReg))
1006+
{
1007+
genProduceReg(treeNode);
1008+
return;
1009+
}
1010+
}
1011+
10011012
// try to use an inc or dec
10021013
if (oper == GT_ADD && !varTypeIsFloating(treeNode) && src->isContainedIntOrIImmed() && !treeNode->gtOverflowEx())
10031014
{

src/tests/JIT/opt/And/IntAnd.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System;
5+
using System.Runtime.CompilerServices;
6+
7+
namespace CodeGenTests
8+
{
9+
class IntAnd
10+
{
11+
[MethodImpl(MethodImplOptions.NoInlining)]
12+
static uint Test_And_UInt32_MaxValue(uint i)
13+
{
14+
// X64: mov
15+
16+
// X64-NOT: and
17+
return i & UInt32.MaxValue;
18+
}
19+
20+
static int Main()
21+
{
22+
if (Test_And_UInt32_MaxValue(1234) != 1234)
23+
return 0;
24+
25+
return 100;
26+
}
27+
}
28+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<OutputType>Exe</OutputType>
4+
</PropertyGroup>
5+
<PropertyGroup>
6+
<DebugType>None</DebugType>
7+
<Optimize>True</Optimize>
8+
</PropertyGroup>
9+
<ItemGroup>
10+
<Compile Include="$(MSBuildProjectName).cs">
11+
<HasDisasmCheck>true</HasDisasmCheck>
12+
</Compile>
13+
14+
<CLRTestEnvironmentVariable Include="DOTNET_TieredCompilation" Value="0" />
15+
<CLRTestEnvironmentVariable Include="DOTNET_JITMinOpts" Value="0" />
16+
</ItemGroup>
17+
</Project>

0 commit comments

Comments
 (0)