[JIT] - X64 - Peephole optimization to possibly skip emitting `and reg, -1` (#80468)
authorWill Smith <lol.tihan@gmail.com>
Fri, 27 Jan 2023 03:43:27 +0000 (19:43 -0800)
committerGitHub <noreply@github.com>
Fri, 27 Jan 2023 03:43:27 +0000 (19:43 -0800)
* 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

src/coreclr/jit/codegenxarch.cpp
src/tests/JIT/opt/And/IntAnd.cs [new file with mode: 0644]
src/tests/JIT/opt/And/IntAnd.csproj [new file with mode: 0644]

index 5c1c261..c4a839f 100644 (file)
@@ -998,6 +998,17 @@ void CodeGen::genCodeForBinary(GenTreeOp* treeNode)
         src = op2;
     }
 
+    // We can skip emitting 'and reg0, -1` if we know that the upper 32bits of 'reg0' are zero'ed.
+    if (compiler->opts.OptimizationEnabled())
+    {
+        if ((oper == GT_AND) && (targetType == TYP_INT) && !treeNode->gtSetFlags() && op2->IsIntegralConst(-1) &&
+            emit->AreUpper32BitsZero(targetReg))
+        {
+            genProduceReg(treeNode);
+            return;
+        }
+    }
+
     // try to use an inc or dec
     if (oper == GT_ADD && !varTypeIsFloating(treeNode) && src->isContainedIntOrIImmed() && !treeNode->gtOverflowEx())
     {
diff --git a/src/tests/JIT/opt/And/IntAnd.cs b/src/tests/JIT/opt/And/IntAnd.cs
new file mode 100644 (file)
index 0000000..80fb37b
--- /dev/null
@@ -0,0 +1,28 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.CompilerServices;
+
+namespace CodeGenTests
+{
+    class IntAnd
+    {
+        [MethodImpl(MethodImplOptions.NoInlining)]
+        static uint Test_And_UInt32_MaxValue(uint i)
+        {
+            // X64: mov
+            
+            // X64-NOT: and
+            return i & UInt32.MaxValue;
+        }
+
+        static int Main()
+        {
+            if (Test_And_UInt32_MaxValue(1234) != 1234)
+                return 0;
+
+            return 100;
+        }
+    }
+}
diff --git a/src/tests/JIT/opt/And/IntAnd.csproj b/src/tests/JIT/opt/And/IntAnd.csproj
new file mode 100644 (file)
index 0000000..42a89c8
--- /dev/null
@@ -0,0 +1,17 @@
+<Project Sdk="Microsoft.NET.Sdk">
+  <PropertyGroup>
+    <OutputType>Exe</OutputType>
+  </PropertyGroup>
+  <PropertyGroup>
+    <DebugType>None</DebugType>
+    <Optimize>True</Optimize>
+  </PropertyGroup>
+  <ItemGroup>
+    <Compile Include="$(MSBuildProjectName).cs">
+      <HasDisasmCheck>true</HasDisasmCheck>
+    </Compile>
+
+    <CLRTestEnvironmentVariable Include="DOTNET_TieredCompilation" Value="0" />
+    <CLRTestEnvironmentVariable Include="DOTNET_JITMinOpts" Value="0" />
+  </ItemGroup>
+</Project>