Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vectorize IndexOfAnyExcept<T>(T value) #73488

Merged
merged 3 commits into from
Aug 10, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion src/libraries/System.Memory/tests/Span/IndexOfAnyExcept.T.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,49 @@ public class IndexOfAnyExceptTests_Byte : IndexOfAnyExceptTests<byte> { protecte
public class IndexOfAnyExceptTests_Char : IndexOfAnyExceptTests<char> { protected override char Create(int value) => (char)value; }
public class IndexOfAnyExceptTests_Int32 : IndexOfAnyExceptTests<int> { protected override int Create(int value) => value; }
public class IndexOfAnyExceptTests_Int64 : IndexOfAnyExceptTests<long> { protected override long Create(int value) => value; }
public class IndexOfAnyExceptTests_String : IndexOfAnyExceptTests<string> { protected override string Create(int value) => ((char)value).ToString(); }
public class IndexOfAnyExceptTests_Record : IndexOfAnyExceptTests<SimpleRecord> { protected override SimpleRecord Create(int value) => new SimpleRecord(value); }
public class IndexOfAnyExceptTests_String : IndexOfAnyExceptTests<string>
{
protected override string Create(int value) => ((char)value).ToString();

[Theory]

[InlineData(new string[] { null, "a", "a", "a", "a" }, new string[] { "a" }, 0)]
[InlineData(new string[] { "a", "a", null, "a", "a" }, new string[] { "a" }, 2)]
[InlineData(new string[] { "a", "a", "a", "a", "a" }, new string[] { null }, 0)]
[InlineData(new string[] { null, null, null, null, null }, new string[] { null }, -1)]
[InlineData(new string[] { null, null, null, null, "a" }, new string[] { null }, 4)]

[InlineData(new string[] { null, "a", "a", "a", "a" }, new string[] { "a", null }, -1)]
[InlineData(new string[] { null, null, null, null, "a" }, new string[] { null, "a" }, -1)]
[InlineData(new string[] { "a", "a", null, "a", "a" }, new string[] { "a", "b" }, 2)]
[InlineData(new string[] { "a", "a", "a", "a", "a" }, new string[] { null, null, }, 0)]
[InlineData(new string[] { null, null, null, null, null }, new string[] { null, null }, -1)]

[InlineData(new string[] { null, "a", "a", "a", "a" }, new string[] { "a", null, null }, -1)]
[InlineData(new string[] { null, null, null, null, "a" }, new string[] { null, null, "a" }, -1)]
[InlineData(new string[] { "a", "a", null, "a", "a" }, new string[] { "a", "b", null }, -1)]
[InlineData(new string[] { "a", "a", null, "a", "a" }, new string[] { "a", "a", "a" }, 2)]
[InlineData(new string[] { "a", "a", "a", "a", "a" }, new string[] { null, null, null }, 0)]
[InlineData(new string[] { null, null, null, null, null }, new string[] { null, null, null }, -1)]

public void SearchingNulls(string[] input, string[] targets, int expected)
{
Assert.Equal(expected, input.AsSpan().IndexOfAnyExcept(targets));
switch (targets.Length)
{
case 1:
Assert.Equal(expected, input.AsSpan().IndexOfAnyExcept(targets[0]));
break;
case 2:
Assert.Equal(expected, input.AsSpan().IndexOfAnyExcept(targets[0], targets[1]));
break;
case 3:
Assert.Equal(expected, input.AsSpan().IndexOfAnyExcept(targets[0], targets[1], targets[2]));
break;
}
}
}

public record SimpleRecord(int Value);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -500,17 +500,48 @@ public static int IndexOfAnyExcept<T>(this Span<T> span, ReadOnlySpan<T> values)
/// The index in the span of the first occurrence of any value other than <paramref name="value"/>.
/// If all of the values are <paramref name="value"/>, returns -1.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOfAnyExcept<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T>
{
for (int i = 0; i < span.Length; i++)
if (RuntimeHelpers.IsBitwiseEquatable<T>())
{
if (!EqualityComparer<T>.Default.Equals(span[i], value))
if (Unsafe.SizeOf<T>() == sizeof(byte))
{
return i;
return SpanHelpers.IndexOfAnyExceptValueType(
ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)),
Unsafe.As<T, byte>(ref value),
span.Length);
}

if (Unsafe.SizeOf<T>() == sizeof(short))
{
return SpanHelpers.IndexOfAnyExceptValueType(
ref Unsafe.As<T, short>(ref MemoryMarshal.GetReference(span)),
Unsafe.As<T, short>(ref value),
span.Length);
}

if (Unsafe.SizeOf<T>() == sizeof(int))
{
return SpanHelpers.IndexOfAnyExceptValueType(
ref Unsafe.As<T, int>(ref MemoryMarshal.GetReference(span)),
Unsafe.As<T, int>(ref value),
span.Length);
}

if (Unsafe.SizeOf<T>() == sizeof(long))
{
return SpanHelpers.IndexOfAnyExceptValueType(
ref Unsafe.As<T, long>(ref MemoryMarshal.GetReference(span)),
Unsafe.As<T, long>(ref value),
span.Length);
}
}

return -1;
return SpanHelpers.IndexOfAnyExcept(
ref MemoryMarshal.GetReference(span),
value,
span.Length);
}

/// <summary>Searches for the first index of any value other than the specified <paramref name="value0"/> or <paramref name="value1"/>.</summary>
Expand Down
72 changes: 72 additions & 0 deletions src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
Expand Down Expand Up @@ -1147,6 +1148,77 @@ public static int LastIndexOfAny<T>(ref T searchSpace, int searchSpaceLength, re
return -1; // not found
}

public static int IndexOfAnyExcept<T>(ref T searchSpace, T value0, int length)
{
Debug.Assert(length >= 0, "Expected non-negative length");

for (int i = 0; i < length; i++)
{
if (!EqualityComparer<T>.Default.Equals(Unsafe.Add(ref searchSpace, i), value0))
{
return i;
}
}

return -1;
}

public static int IndexOfAnyExceptValueType<T>(ref T searchSpace, T value0, int length) where T : struct, IEquatable<T>
{
Debug.Assert(length >= 0, "Expected non-negative length");
Debug.Assert(value0 is byte or short or int or long, "Expected caller to normalize to one of these types");

if (!Vector128.IsHardwareAccelerated || length < Vector128<T>.Count)
{
for (int i = 0; i < length; i++)
{
if (!Unsafe.Add(ref searchSpace, i).Equals(value0))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just wondering, do you have the disassembly the JIT emits for this?

I'd expect it emits a cmp reg, [addr] (where reg contains value0), but I know there were some issues with Unsafe.Add being converted to an [addr] before.

{
return i;
}
}
}
else
{
Vector128<T> notEquals, value0Vector = Vector128.Create(value0);
ref T current = ref searchSpace;
ref T oneVectorAwayFromEnd = ref Unsafe.Add(ref searchSpace, length - Vector128<T>.Count);

// Loop until either we've finished all elements or there's less than a vector's-worth remaining.
do
{
notEquals = ~Vector128.Equals(value0Vector, Vector128.LoadUnsafe(ref current));
if (notEquals != Vector128<T>.Zero)
{
return ComputeIndex(ref searchSpace, ref current, notEquals);
}

current = ref Unsafe.Add(ref current, Vector128<T>.Count);
}
while (!Unsafe.IsAddressGreaterThan(ref current, ref oneVectorAwayFromEnd));

// If any elements remain, process the last vector in the search space.
if ((uint)length % Vector128<T>.Count != 0)
{
notEquals = ~Vector128.Equals(value0Vector, Vector128.LoadUnsafe(ref oneVectorAwayFromEnd));
if (notEquals != Vector128<T>.Zero)
{
return ComputeIndex(ref searchSpace, ref oneVectorAwayFromEnd, notEquals);
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int ComputeIndex(ref T searchSpace, ref T current, Vector128<T> notEquals)
{
uint notEqualsElements = notEquals.ExtractMostSignificantBits();
int index = BitOperations.TrailingZeroCount(notEqualsElements);
return index + (int)(Unsafe.ByteOffset(ref searchSpace, ref current) / Unsafe.SizeOf<T>());
}
}

return -1;
}

public static bool SequenceEqual<T>(ref T first, ref T second, int length) where T : IEquatable<T>
{
Debug.Assert(length >= 0);
Expand Down