Skip to content

Commit 90be48c

Browse files
committed
ARM64 intrinsic for Log2
1 parent cc04050 commit 90be48c

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

src/libraries/System.Private.CoreLib/src/System/Numerics/BitOperations.cs

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,12 @@ public static int LeadingZeroCount(ulong value)
115115
[CLSCompliant(false)]
116116
public static int Log2(uint value)
117117
{
118+
// Enforce conventional contract 0->0 (Log(0) is undefined)
119+
if (value == 0)
120+
{
121+
return 0;
122+
}
123+
118124
// value lzcnt actual expected
119125
// ..0000 32 0 0 (by convention, guard clause)
120126
// ..0001 31 31-31 0
@@ -124,16 +130,15 @@ public static int Log2(uint value)
124130
// 1000.. 0 31-0 31
125131
if (Lzcnt.IsSupported)
126132
{
127-
// Enforce conventional contract 0->0 (Log(0) is undefined)
128-
if (value == 0)
129-
{
130-
return 0;
131-
}
132-
133133
// LZCNT contract is 0->32
134134
return 31 - (int)Lzcnt.LeadingZeroCount(value);
135135
}
136136

137+
if (ArmBase.IsSupported)
138+
{
139+
return 31 - (int)ArmBase.LeadingZeroCount(value);
140+
}
141+
137142
// Fallback contract is 0->0
138143
return Log2SoftwareFallback(value);
139144
}
@@ -147,18 +152,23 @@ public static int Log2(uint value)
147152
[CLSCompliant(false)]
148153
public static int Log2(ulong value)
149154
{
150-
if (Lzcnt.X64.IsSupported)
155+
// Enforce conventional contract 0->0 (Log(0) is undefined)
156+
if (value == 0)
151157
{
152-
// Enforce conventional contract 0->0 (Log(0) is undefined)
153-
if (value == 0)
154-
{
155-
return 0;
156-
}
158+
return 0;
159+
}
157160

161+
if (Lzcnt.X64.IsSupported)
162+
{
158163
// LZCNT contract is 0->64
159164
return 63 - (int)Lzcnt.X64.LeadingZeroCount(value);
160165
}
161166

167+
if (ArmBase.Arm64.IsSupported)
168+
{
169+
return 63 - (int)ArmBase.Arm64.LeadingZeroCount(value);
170+
}
171+
162172
uint hi = (uint)(value >> 32);
163173

164174
if (hi == 0)

0 commit comments

Comments
 (0)