/
ASCIIUtility.cs
1918 lines (1548 loc) · 83.8 KB
/
ASCIIUtility.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
using System.Runtime.Intrinsics.X86;
namespace System.Text
{
internal static partial class ASCIIUtility
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool AllBytesInUInt64AreAscii(ulong value)
{
// If the high bit of any byte is set, that byte is non-ASCII.
return (value & UInt64HighBitsOnlyMask) == 0;
}
/// <summary>
/// Returns <see langword="true"/> iff all chars in <paramref name="value"/> are ASCII.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool AllCharsInUInt32AreAscii(uint value)
{
return (value & ~0x007F007Fu) == 0;
}
/// <summary>
/// Returns <see langword="true"/> iff all chars in <paramref name="value"/> are ASCII.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool AllCharsInUInt64AreAscii(ulong value)
{
return (value & ~0x007F007F_007F007Ful) == 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetIndexOfFirstNonAsciiByteInLane_AdvSimd(Vector128<byte> value, Vector128<byte> bitmask)
{
if (!AdvSimd.Arm64.IsSupported || !BitConverter.IsLittleEndian)
{
throw new PlatformNotSupportedException();
}
// extractedBits[i] = (value[i] >> 7) & (1 << (12 * (i % 2)));
Vector128<byte> mostSignificantBitIsSet = AdvSimd.ShiftRightArithmetic(value.AsSByte(), 7).AsByte();
Vector128<byte> extractedBits = AdvSimd.And(mostSignificantBitIsSet, bitmask);
// collapse mask to lower bits
extractedBits = AdvSimd.Arm64.AddPairwise(extractedBits, extractedBits);
ulong mask = extractedBits.AsUInt64().ToScalar();
// calculate the index
int index = BitOperations.TrailingZeroCount(mask) >> 2;
Debug.Assert((mask != 0) ? index < 16 : index >= 16);
return index;
}
/// <summary>
/// Given a DWORD which represents two packed chars in machine-endian order,
/// <see langword="true"/> iff the first char (in machine-endian order) is ASCII.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private static bool FirstCharInUInt32IsAscii(uint value)
{
return (BitConverter.IsLittleEndian && (value & 0xFF80u) == 0)
|| (!BitConverter.IsLittleEndian && (value & 0xFF800000u) == 0);
}
/// <summary>
/// Returns the index in <paramref name="pBuffer"/> where the first non-ASCII byte is found.
/// Returns <paramref name="bufferLength"/> if the buffer is empty or all-ASCII.
/// </summary>
/// <returns>An ASCII byte is defined as 0x00 - 0x7F, inclusive.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe nuint GetIndexOfFirstNonAsciiByte(byte* pBuffer, nuint bufferLength)
{
// If SSE2 is supported, use those specific intrinsics instead of the generic vectorized
// code below. This has two benefits: (a) we can take advantage of specific instructions like
// pmovmskb which we know are optimized, and (b) we can avoid downclocking the processor while
// this method is running.
return (Sse2.IsSupported || (AdvSimd.Arm64.IsSupported && BitConverter.IsLittleEndian))
? GetIndexOfFirstNonAsciiByte_Intrinsified(pBuffer, bufferLength)
: GetIndexOfFirstNonAsciiByte_Default(pBuffer, bufferLength);
}
private static unsafe nuint GetIndexOfFirstNonAsciiByte_Default(byte* pBuffer, nuint bufferLength)
{
// Squirrel away the original buffer reference. This method works by determining the exact
// byte reference where non-ASCII data begins, so we need this base value to perform the
// final subtraction at the end of the method to get the index into the original buffer.
byte* pOriginalBuffer = pBuffer;
// Before we drain off byte-by-byte, try a generic vectorized loop.
// Only run the loop if we have at least two vectors we can pull out.
// Note use of SBYTE instead of BYTE below; we're using the two's-complement
// representation of negative integers to act as a surrogate for "is ASCII?".
if (Vector.IsHardwareAccelerated && bufferLength >= 2 * (uint)Vector<sbyte>.Count)
{
uint SizeOfVectorInBytes = (uint)Vector<sbyte>.Count; // JIT will make this a const
if (Vector.GreaterThanOrEqualAll(Unsafe.ReadUnaligned<Vector<sbyte>>(pBuffer), Vector<sbyte>.Zero))
{
// The first several elements of the input buffer were ASCII. Bump up the pointer to the
// next aligned boundary, then perform aligned reads from here on out until we find non-ASCII
// data or we approach the end of the buffer. It's possible we'll reread data; this is ok.
byte* pFinalVectorReadPos = pBuffer + bufferLength - SizeOfVectorInBytes;
pBuffer = (byte*)(((nuint)pBuffer + SizeOfVectorInBytes) & ~(nuint)(SizeOfVectorInBytes - 1));
#if DEBUG
long numBytesRead = pBuffer - pOriginalBuffer;
Debug.Assert(0 < numBytesRead && numBytesRead <= SizeOfVectorInBytes, "We should've made forward progress of at least one byte.");
Debug.Assert((nuint)numBytesRead <= bufferLength, "We shouldn't have read past the end of the input buffer.");
#endif
Debug.Assert(pBuffer <= pFinalVectorReadPos, "Should be able to read at least one vector.");
do
{
Debug.Assert((nuint)pBuffer % SizeOfVectorInBytes == 0, "Vector read should be aligned.");
if (Vector.LessThanAny(Unsafe.Read<Vector<sbyte>>(pBuffer), Vector<sbyte>.Zero))
{
break; // found non-ASCII data
}
pBuffer += SizeOfVectorInBytes;
} while (pBuffer <= pFinalVectorReadPos);
// Adjust the remaining buffer length for the number of elements we just consumed.
bufferLength -= (nuint)pBuffer;
bufferLength += (nuint)pOriginalBuffer;
}
}
// At this point, the buffer length wasn't enough to perform a vectorized search, or we did perform
// a vectorized search and encountered non-ASCII data. In either case go down a non-vectorized code
// path to drain any remaining ASCII bytes.
//
// We're going to perform unaligned reads, so prefer 32-bit reads instead of 64-bit reads.
// This also allows us to perform more optimized bit twiddling tricks to count the number of ASCII bytes.
uint currentUInt32;
// Try reading 64 bits at a time in a loop.
for (; bufferLength >= 8; bufferLength -= 8)
{
currentUInt32 = Unsafe.ReadUnaligned<uint>(pBuffer);
uint nextUInt32 = Unsafe.ReadUnaligned<uint>(pBuffer + 4);
if (!AllBytesInUInt32AreAscii(currentUInt32 | nextUInt32))
{
// One of these two values contains non-ASCII bytes.
// Figure out which one it is, then put it in 'current' so that we can drain the ASCII bytes.
if (AllBytesInUInt32AreAscii(currentUInt32))
{
currentUInt32 = nextUInt32;
pBuffer += 4;
}
goto FoundNonAsciiData;
}
pBuffer += 8; // consumed 8 ASCII bytes
}
// From this point forward we don't need to update bufferLength.
// Try reading 32 bits.
if ((bufferLength & 4) != 0)
{
currentUInt32 = Unsafe.ReadUnaligned<uint>(pBuffer);
if (!AllBytesInUInt32AreAscii(currentUInt32))
{
goto FoundNonAsciiData;
}
pBuffer += 4;
}
// Try reading 16 bits.
if ((bufferLength & 2) != 0)
{
currentUInt32 = Unsafe.ReadUnaligned<ushort>(pBuffer);
if (!AllBytesInUInt32AreAscii(currentUInt32))
{
if (!BitConverter.IsLittleEndian)
{
currentUInt32 <<= 16;
}
goto FoundNonAsciiData;
}
pBuffer += 2;
}
// Try reading 8 bits
if ((bufferLength & 1) != 0)
{
// If the buffer contains non-ASCII data, the comparison below will fail, and
// we'll end up not incrementing the buffer reference.
if (*(sbyte*)pBuffer >= 0)
{
pBuffer++;
}
}
Finish:
nuint totalNumBytesRead = (nuint)pBuffer - (nuint)pOriginalBuffer;
return totalNumBytesRead;
FoundNonAsciiData:
Debug.Assert(!AllBytesInUInt32AreAscii(currentUInt32), "Shouldn't have reached this point if we have an all-ASCII input.");
// The method being called doesn't bother looking at whether the high byte is ASCII. There are only
// two scenarios: (a) either one of the earlier bytes is not ASCII and the search terminates before
// we get to the high byte; or (b) all of the earlier bytes are ASCII, so the high byte must be
// non-ASCII. In both cases we only care about the low 24 bits.
pBuffer += CountNumberOfLeadingAsciiBytesFromUInt32WithSomeNonAsciiData(currentUInt32);
goto Finish;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool ContainsNonAsciiByte_Sse2(uint sseMask)
{
Debug.Assert(sseMask != uint.MaxValue);
Debug.Assert(Sse2.IsSupported);
return sseMask != 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool ContainsNonAsciiByte_AdvSimd(uint advSimdIndex)
{
Debug.Assert(advSimdIndex != uint.MaxValue);
Debug.Assert(AdvSimd.IsSupported);
return advSimdIndex < 16;
}
private static unsafe nuint GetIndexOfFirstNonAsciiByte_Intrinsified(byte* pBuffer, nuint bufferLength)
{
// JIT turns the below into constants
uint SizeOfVector128 = (uint)Unsafe.SizeOf<Vector128<byte>>();
nuint MaskOfAllBitsInVector128 = (nuint)(SizeOfVector128 - 1);
Debug.Assert(Sse2.IsSupported || AdvSimd.Arm64.IsSupported, "Sse2 or AdvSimd64 required.");
Debug.Assert(BitConverter.IsLittleEndian, "This SSE2/Arm64 implementation assumes little-endian.");
Vector128<byte> bitmask = BitConverter.IsLittleEndian ?
Vector128.Create((ushort)0x1001).AsByte() :
Vector128.Create((ushort)0x0110).AsByte();
uint currentSseMask = uint.MaxValue, secondSseMask = uint.MaxValue;
uint currentAdvSimdIndex = uint.MaxValue, secondAdvSimdIndex = uint.MaxValue;
byte* pOriginalBuffer = pBuffer;
// This method is written such that control generally flows top-to-bottom, avoiding
// jumps as much as possible in the optimistic case of a large enough buffer and
// "all ASCII". If we see non-ASCII data, we jump out of the hot paths to targets
// after all the main logic.
if (bufferLength < SizeOfVector128)
{
goto InputBufferLessThanOneVectorInLength; // can't vectorize; drain primitives instead
}
// Read the first vector unaligned.
if (Sse2.IsSupported)
{
currentSseMask = (uint)Sse2.MoveMask(Sse2.LoadVector128(pBuffer)); // unaligned load
if (ContainsNonAsciiByte_Sse2(currentSseMask))
{
goto FoundNonAsciiDataInCurrentChunk;
}
}
else if (AdvSimd.Arm64.IsSupported)
{
currentAdvSimdIndex = (uint)GetIndexOfFirstNonAsciiByteInLane_AdvSimd(AdvSimd.LoadVector128(pBuffer), bitmask); // unaligned load
if (ContainsNonAsciiByte_AdvSimd(currentAdvSimdIndex))
{
goto FoundNonAsciiDataInCurrentChunk;
}
}
else
{
throw new PlatformNotSupportedException();
}
// If we have less than 32 bytes to process, just go straight to the final unaligned
// read. There's no need to mess with the loop logic in the middle of this method.
if (bufferLength < 2 * SizeOfVector128)
{
goto IncrementCurrentOffsetBeforeFinalUnalignedVectorRead;
}
// Now adjust the read pointer so that future reads are aligned.
pBuffer = (byte*)(((nuint)pBuffer + SizeOfVector128) & ~(nuint)MaskOfAllBitsInVector128);
#if DEBUG
long numBytesRead = pBuffer - pOriginalBuffer;
Debug.Assert(0 < numBytesRead && numBytesRead <= SizeOfVector128, "We should've made forward progress of at least one byte.");
Debug.Assert((nuint)numBytesRead <= bufferLength, "We shouldn't have read past the end of the input buffer.");
#endif
// Adjust the remaining length to account for what we just read.
bufferLength += (nuint)pOriginalBuffer;
bufferLength -= (nuint)pBuffer;
// The buffer is now properly aligned.
// Read 2 vectors at a time if possible.
if (bufferLength >= 2 * SizeOfVector128)
{
byte* pFinalVectorReadPos = (byte*)((nuint)pBuffer + bufferLength - 2 * SizeOfVector128);
// After this point, we no longer need to update the bufferLength value.
do
{
if (Sse2.IsSupported)
{
Vector128<byte> firstVector = Sse2.LoadAlignedVector128(pBuffer);
Vector128<byte> secondVector = Sse2.LoadAlignedVector128(pBuffer + SizeOfVector128);
currentSseMask = (uint)Sse2.MoveMask(firstVector);
secondSseMask = (uint)Sse2.MoveMask(secondVector);
if (ContainsNonAsciiByte_Sse2(currentSseMask | secondSseMask))
{
goto FoundNonAsciiDataInInnerLoop;
}
}
else if (AdvSimd.Arm64.IsSupported)
{
Vector128<byte> firstVector = AdvSimd.LoadVector128(pBuffer);
Vector128<byte> secondVector = AdvSimd.LoadVector128(pBuffer + SizeOfVector128);
currentAdvSimdIndex = (uint)GetIndexOfFirstNonAsciiByteInLane_AdvSimd(firstVector, bitmask);
secondAdvSimdIndex = (uint)GetIndexOfFirstNonAsciiByteInLane_AdvSimd(secondVector, bitmask);
if (ContainsNonAsciiByte_AdvSimd(currentAdvSimdIndex) || ContainsNonAsciiByte_AdvSimd(secondAdvSimdIndex))
{
goto FoundNonAsciiDataInInnerLoop;
}
}
else
{
throw new PlatformNotSupportedException();
}
pBuffer += 2 * SizeOfVector128;
} while (pBuffer <= pFinalVectorReadPos);
}
// We have somewhere between 0 and (2 * vector length) - 1 bytes remaining to read from.
// Since the above loop doesn't update bufferLength, we can't rely on its absolute value.
// But we _can_ rely on it to tell us how much remaining data must be drained by looking
// at what bits of it are set. This works because had we updated it within the loop above,
// we would've been adding 2 * SizeOfVector128 on each iteration, but we only care about
// bits which are less significant than those that the addition would've acted on.
// If there is fewer than one vector length remaining, skip the next aligned read.
if ((bufferLength & SizeOfVector128) == 0)
{
goto DoFinalUnalignedVectorRead;
}
// At least one full vector's worth of data remains, so we can safely read it.
// Remember, at this point pBuffer is still aligned.
if (Sse2.IsSupported)
{
currentSseMask = (uint)Sse2.MoveMask(Sse2.LoadAlignedVector128(pBuffer));
if (ContainsNonAsciiByte_Sse2(currentSseMask))
{
goto FoundNonAsciiDataInCurrentChunk;
}
}
else if (AdvSimd.Arm64.IsSupported)
{
currentAdvSimdIndex = (uint)GetIndexOfFirstNonAsciiByteInLane_AdvSimd(AdvSimd.LoadVector128(pBuffer), bitmask);
if (ContainsNonAsciiByte_AdvSimd(currentAdvSimdIndex))
{
goto FoundNonAsciiDataInCurrentChunk;
}
}
else
{
throw new PlatformNotSupportedException();
}
IncrementCurrentOffsetBeforeFinalUnalignedVectorRead:
pBuffer += SizeOfVector128;
DoFinalUnalignedVectorRead:
if (((byte)bufferLength & MaskOfAllBitsInVector128) != 0)
{
// Perform an unaligned read of the last vector.
// We need to adjust the pointer because we're re-reading data.
pBuffer += (bufferLength & MaskOfAllBitsInVector128) - SizeOfVector128;
if (Sse2.IsSupported)
{
currentSseMask = (uint)Sse2.MoveMask(Sse2.LoadVector128(pBuffer)); // unaligned load
if (ContainsNonAsciiByte_Sse2(currentSseMask))
{
goto FoundNonAsciiDataInCurrentChunk;
}
}
else if (AdvSimd.Arm64.IsSupported)
{
currentAdvSimdIndex = (uint)GetIndexOfFirstNonAsciiByteInLane_AdvSimd(AdvSimd.LoadVector128(pBuffer), bitmask); // unaligned load
if (ContainsNonAsciiByte_AdvSimd(currentAdvSimdIndex))
{
goto FoundNonAsciiDataInCurrentChunk;
}
}
else
{
throw new PlatformNotSupportedException();
}
pBuffer += SizeOfVector128;
}
Finish:
return (nuint)pBuffer - (nuint)pOriginalBuffer; // and we're done!
FoundNonAsciiDataInInnerLoop:
// If the current (first) mask isn't the mask that contains non-ASCII data, then it must
// instead be the second mask. If so, skip the entire first mask and drain ASCII bytes
// from the second mask.
if (Sse2.IsSupported)
{
if (!ContainsNonAsciiByte_Sse2(currentSseMask))
{
pBuffer += SizeOfVector128;
currentSseMask = secondSseMask;
}
}
else if (AdvSimd.IsSupported)
{
if (!ContainsNonAsciiByte_AdvSimd(currentAdvSimdIndex))
{
pBuffer += SizeOfVector128;
currentAdvSimdIndex = secondAdvSimdIndex;
}
}
else
{
throw new PlatformNotSupportedException();
}
FoundNonAsciiDataInCurrentChunk:
if (Sse2.IsSupported)
{
// The mask contains - from the LSB - a 0 for each ASCII byte we saw, and a 1 for each non-ASCII byte.
// Tzcnt is the correct operation to count the number of zero bits quickly. If this instruction isn't
// available, we'll fall back to a normal loop.
Debug.Assert(ContainsNonAsciiByte_Sse2(currentSseMask), "Shouldn't be here unless we see non-ASCII data.");
pBuffer += (uint)BitOperations.TrailingZeroCount(currentSseMask);
}
else if (AdvSimd.Arm64.IsSupported)
{
Debug.Assert(ContainsNonAsciiByte_AdvSimd(currentAdvSimdIndex), "Shouldn't be here unless we see non-ASCII data.");
pBuffer += currentAdvSimdIndex;
}
else
{
throw new PlatformNotSupportedException();
}
goto Finish;
FoundNonAsciiDataInCurrentDWord:
uint currentDWord;
Debug.Assert(!AllBytesInUInt32AreAscii(currentDWord), "Shouldn't be here unless we see non-ASCII data.");
pBuffer += CountNumberOfLeadingAsciiBytesFromUInt32WithSomeNonAsciiData(currentDWord);
goto Finish;
InputBufferLessThanOneVectorInLength:
// These code paths get hit if the original input length was less than one vector in size.
// We can't perform vectorized reads at this point, so we'll fall back to reading primitives
// directly. Note that all of these reads are unaligned.
Debug.Assert(bufferLength < SizeOfVector128);
// QWORD drain
if ((bufferLength & 8) != 0)
{
if (UIntPtr.Size == sizeof(ulong))
{
// If we can use 64-bit tzcnt to count the number of leading ASCII bytes, prefer it.
ulong candidateUInt64 = Unsafe.ReadUnaligned<ulong>(pBuffer);
if (!AllBytesInUInt64AreAscii(candidateUInt64))
{
// Clear everything but the high bit of each byte, then tzcnt.
// Remember to divide by 8 at the end to convert bit count to byte count.
candidateUInt64 &= UInt64HighBitsOnlyMask;
pBuffer += (nuint)(BitOperations.TrailingZeroCount(candidateUInt64) >> 3);
goto Finish;
}
}
else
{
// If we can't use 64-bit tzcnt, no worries. We'll just do 2x 32-bit reads instead.
currentDWord = Unsafe.ReadUnaligned<uint>(pBuffer);
uint nextDWord = Unsafe.ReadUnaligned<uint>(pBuffer + 4);
if (!AllBytesInUInt32AreAscii(currentDWord | nextDWord))
{
// At least one of the values wasn't all-ASCII.
// We need to figure out which one it was and stick it in the currentMask local.
if (AllBytesInUInt32AreAscii(currentDWord))
{
currentDWord = nextDWord; // this one is the culprit
pBuffer += 4;
}
goto FoundNonAsciiDataInCurrentDWord;
}
}
pBuffer += 8; // successfully consumed 8 ASCII bytes
}
// DWORD drain
if ((bufferLength & 4) != 0)
{
currentDWord = Unsafe.ReadUnaligned<uint>(pBuffer);
if (!AllBytesInUInt32AreAscii(currentDWord))
{
goto FoundNonAsciiDataInCurrentDWord;
}
pBuffer += 4; // successfully consumed 4 ASCII bytes
}
// WORD drain
// (We movzx to a DWORD for ease of manipulation.)
if ((bufferLength & 2) != 0)
{
currentDWord = Unsafe.ReadUnaligned<ushort>(pBuffer);
if (!AllBytesInUInt32AreAscii(currentDWord))
{
// We only care about the 0x0080 bit of the value. If it's not set, then we
// increment currentOffset by 1. If it's set, we don't increment it at all.
pBuffer += (nuint)((nint)(sbyte)currentDWord >> 7) + 1;
goto Finish;
}
pBuffer += 2; // successfully consumed 2 ASCII bytes
}
// BYTE drain
if ((bufferLength & 1) != 0)
{
// sbyte has non-negative value if byte is ASCII.
if (*(sbyte*)(pBuffer) >= 0)
{
pBuffer++; // successfully consumed a single byte
}
}
goto Finish;
}
/// <summary>
/// Returns the index in <paramref name="pBuffer"/> where the first non-ASCII char is found.
/// Returns <paramref name="bufferLength"/> if the buffer is empty or all-ASCII.
/// </summary>
/// <returns>An ASCII char is defined as 0x0000 - 0x007F, inclusive.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe nuint GetIndexOfFirstNonAsciiChar(char* pBuffer, nuint bufferLength /* in chars */)
{
// If SSE2/ASIMD is supported, use those specific intrinsics instead of the generic vectorized
// code below. This has two benefits: (a) we can take advantage of specific instructions like
// pmovmskb which we know are optimized, and (b) we can avoid downclocking the processor while
// this method is running.
return ((Sse2.IsSupported || AdvSimd.IsSupported) && BitConverter.IsLittleEndian)
? GetIndexOfFirstNonAsciiChar_Intrinsified(pBuffer, bufferLength)
: GetIndexOfFirstNonAsciiChar_Default(pBuffer, bufferLength);
}
private static unsafe nuint GetIndexOfFirstNonAsciiChar_Default(char* pBuffer, nuint bufferLength /* in chars */)
{
// Squirrel away the original buffer reference.This method works by determining the exact
// char reference where non-ASCII data begins, so we need this base value to perform the
// final subtraction at the end of the method to get the index into the original buffer.
char* pOriginalBuffer = pBuffer;
#if SYSTEM_PRIVATE_CORELIB
Debug.Assert(bufferLength <= nuint.MaxValue / sizeof(char));
#endif
// Before we drain off char-by-char, try a generic vectorized loop.
// Only run the loop if we have at least two vectors we can pull out.
if (Vector.IsHardwareAccelerated && bufferLength >= 2 * (uint)Vector<ushort>.Count)
{
uint SizeOfVectorInChars = (uint)Vector<ushort>.Count; // JIT will make this a const
uint SizeOfVectorInBytes = (uint)Vector<byte>.Count; // JIT will make this a const
Vector<ushort> maxAscii = new Vector<ushort>(0x007F);
if (Vector.LessThanOrEqualAll(Unsafe.ReadUnaligned<Vector<ushort>>(pBuffer), maxAscii))
{
// The first several elements of the input buffer were ASCII. Bump up the pointer to the
// next aligned boundary, then perform aligned reads from here on out until we find non-ASCII
// data or we approach the end of the buffer. It's possible we'll reread data; this is ok.
char* pFinalVectorReadPos = pBuffer + bufferLength - SizeOfVectorInChars;
pBuffer = (char*)(((nuint)pBuffer + SizeOfVectorInBytes) & ~(nuint)(SizeOfVectorInBytes - 1));
#if DEBUG
long numCharsRead = pBuffer - pOriginalBuffer;
Debug.Assert(0 < numCharsRead && numCharsRead <= SizeOfVectorInChars, "We should've made forward progress of at least one char.");
Debug.Assert((nuint)numCharsRead <= bufferLength, "We shouldn't have read past the end of the input buffer.");
#endif
Debug.Assert(pBuffer <= pFinalVectorReadPos, "Should be able to read at least one vector.");
do
{
Debug.Assert((nuint)pBuffer % SizeOfVectorInChars == 0, "Vector read should be aligned.");
if (Vector.GreaterThanAny(Unsafe.Read<Vector<ushort>>(pBuffer), maxAscii))
{
break; // found non-ASCII data
}
pBuffer += SizeOfVectorInChars;
} while (pBuffer <= pFinalVectorReadPos);
// Adjust the remaining buffer length for the number of elements we just consumed.
bufferLength -= ((nuint)pBuffer - (nuint)pOriginalBuffer) / sizeof(char);
}
}
// At this point, the buffer length wasn't enough to perform a vectorized search, or we did perform
// a vectorized search and encountered non-ASCII data. In either case go down a non-vectorized code
// path to drain any remaining ASCII chars.
//
// We're going to perform unaligned reads, so prefer 32-bit reads instead of 64-bit reads.
// This also allows us to perform more optimized bit twiddling tricks to count the number of ASCII chars.
uint currentUInt32;
// Try reading 64 bits at a time in a loop.
for (; bufferLength >= 4; bufferLength -= 4) // 64 bits = 4 * 16-bit chars
{
currentUInt32 = Unsafe.ReadUnaligned<uint>(pBuffer);
uint nextUInt32 = Unsafe.ReadUnaligned<uint>(pBuffer + 4 / sizeof(char));
if (!AllCharsInUInt32AreAscii(currentUInt32 | nextUInt32))
{
// One of these two values contains non-ASCII chars.
// Figure out which one it is, then put it in 'current' so that we can drain the ASCII chars.
if (AllCharsInUInt32AreAscii(currentUInt32))
{
currentUInt32 = nextUInt32;
pBuffer += 2;
}
goto FoundNonAsciiData;
}
pBuffer += 4; // consumed 4 ASCII chars
}
// From this point forward we don't need to keep track of the remaining buffer length.
// Try reading 32 bits.
if ((bufferLength & 2) != 0) // 32 bits = 2 * 16-bit chars
{
currentUInt32 = Unsafe.ReadUnaligned<uint>(pBuffer);
if (!AllCharsInUInt32AreAscii(currentUInt32))
{
goto FoundNonAsciiData;
}
pBuffer += 2;
}
// Try reading 16 bits.
// No need to try an 8-bit read after this since we're working with chars.
if ((bufferLength & 1) != 0)
{
// If the buffer contains non-ASCII data, the comparison below will fail, and
// we'll end up not incrementing the buffer reference.
if (*pBuffer <= 0x007F)
{
pBuffer++;
}
}
Finish:
nuint totalNumBytesRead = (nuint)pBuffer - (nuint)pOriginalBuffer;
Debug.Assert(totalNumBytesRead % sizeof(char) == 0, "Total number of bytes read should be even since we're working with chars.");
return totalNumBytesRead / sizeof(char); // convert byte count -> char count before returning
FoundNonAsciiData:
Debug.Assert(!AllCharsInUInt32AreAscii(currentUInt32), "Shouldn't have reached this point if we have an all-ASCII input.");
// We don't bother looking at the second char - only the first char.
if (FirstCharInUInt32IsAscii(currentUInt32))
{
pBuffer++;
}
goto Finish;
}
private static unsafe nuint GetIndexOfFirstNonAsciiChar_Intrinsified(char* pBuffer, nuint bufferLength /* in chars */)
{
// This method contains logic optimized using vector instructions for both x64 and Arm64.
// Much of the logic in this method will be elided by JIT once we determine which specific ISAs we support.
// Quick check for empty inputs.
if (bufferLength == 0)
{
return 0;
}
// JIT turns the below into constants
uint SizeOfVector128InBytes = (uint)Unsafe.SizeOf<Vector128<byte>>();
uint SizeOfVector128InChars = SizeOfVector128InBytes / sizeof(char);
Debug.Assert(Sse2.IsSupported || AdvSimd.Arm64.IsSupported, "Should've been checked by caller.");
Debug.Assert(BitConverter.IsLittleEndian, "This SSE2/Arm64 assumes little-endian.");
Vector128<ushort> firstVector, secondVector;
uint currentMask;
char* pOriginalBuffer = pBuffer;
if (bufferLength < SizeOfVector128InChars)
{
goto InputBufferLessThanOneVectorInLength; // can't vectorize; drain primitives instead
}
// This method is written such that control generally flows top-to-bottom, avoiding
// jumps as much as possible in the optimistic case of "all ASCII". If we see non-ASCII
// data, we jump out of the hot paths to targets at the end of the method.
#if SYSTEM_PRIVATE_CORELIB
Debug.Assert(bufferLength <= nuint.MaxValue / sizeof(char));
#endif
// Read the first vector unaligned.
firstVector = Vector128.LoadUnsafe(ref *(ushort*)pBuffer);
if (VectorContainsNonAsciiChar(firstVector))
{
goto FoundNonAsciiDataInFirstVector;
}
// If we have less than 32 bytes to process, just go straight to the final unaligned
// read. There's no need to mess with the loop logic in the middle of this method.
// Adjust the remaining length to account for what we just read.
// For the remainder of this code path, bufferLength will be in bytes, not chars.
bufferLength <<= 1; // chars to bytes
if (bufferLength < 2 * SizeOfVector128InBytes)
{
goto IncrementCurrentOffsetBeforeFinalUnalignedVectorRead;
}
// Now adjust the read pointer so that future reads are aligned.
pBuffer = (char*)(((nuint)pBuffer + SizeOfVector128InBytes) & ~(nuint)(SizeOfVector128InBytes - 1));
#if DEBUG
long numCharsRead = pBuffer - pOriginalBuffer;
Debug.Assert(0 < numCharsRead && numCharsRead <= SizeOfVector128InChars, "We should've made forward progress of at least one char.");
Debug.Assert((nuint)numCharsRead <= bufferLength, "We shouldn't have read past the end of the input buffer.");
#endif
// Adjust remaining buffer length.
nuint numBytesRead = ((nuint)pBuffer - (nuint)pOriginalBuffer);
bufferLength -= numBytesRead;
// The buffer is now properly aligned.
// Read 2 vectors at a time if possible.
if (bufferLength >= 2 * SizeOfVector128InBytes)
{
char* pFinalVectorReadPos = (char*)((nuint)pBuffer + bufferLength - 2 * SizeOfVector128InBytes);
// After this point, we no longer need to update the bufferLength value.
do
{
firstVector = Vector128.LoadUnsafe(ref *(ushort*)pBuffer);
secondVector = Vector128.LoadUnsafe(ref *(ushort*)pBuffer, SizeOfVector128InChars);
Vector128<ushort> combinedVector = firstVector | secondVector;
if (VectorContainsNonAsciiChar(combinedVector))
{
goto FoundNonAsciiDataInFirstOrSecondVector;
}
pBuffer += 2 * SizeOfVector128InChars;
} while (pBuffer <= pFinalVectorReadPos);
}
// We have somewhere between 0 and (2 * vector length) - 1 bytes remaining to read from.
// Since the above loop doesn't update bufferLength, we can't rely on its absolute value.
// But we _can_ rely on it to tell us how much remaining data must be drained by looking
// at what bits of it are set. This works because had we updated it within the loop above,
// we would've been adding 2 * SizeOfVector128 on each iteration, but we only care about
// bits which are less significant than those that the addition would've acted on.
// If there is fewer than one vector length remaining, skip the next aligned read.
// Remember, at this point bufferLength is measured in bytes, not chars.
if ((bufferLength & SizeOfVector128InBytes) == 0)
{
goto DoFinalUnalignedVectorRead;
}
// At least one full vector's worth of data remains, so we can safely read it.
// Remember, at this point pBuffer is still aligned.
firstVector = Vector128.LoadUnsafe(ref *(ushort*)pBuffer);
if (VectorContainsNonAsciiChar(firstVector))
{
goto FoundNonAsciiDataInFirstVector;
}
IncrementCurrentOffsetBeforeFinalUnalignedVectorRead:
pBuffer += SizeOfVector128InChars;
DoFinalUnalignedVectorRead:
if (((byte)bufferLength & (SizeOfVector128InBytes - 1)) != 0)
{
// Perform an unaligned read of the last vector.
// We need to adjust the pointer because we're re-reading data.
pBuffer = (char*)((byte*)pBuffer + (bufferLength & (SizeOfVector128InBytes - 1)) - SizeOfVector128InBytes);
firstVector = Vector128.LoadUnsafe(ref *(ushort*)pBuffer);
if (VectorContainsNonAsciiChar(firstVector))
{
goto FoundNonAsciiDataInFirstVector;
}
pBuffer += SizeOfVector128InChars;
}
Finish:
Debug.Assert(((nuint)pBuffer - (nuint)pOriginalBuffer) % 2 == 0, "Shouldn't have incremented any pointer by an odd byte count.");
return ((nuint)pBuffer - (nuint)pOriginalBuffer) / sizeof(char); // and we're done! (remember to adjust for char count)
FoundNonAsciiDataInFirstOrSecondVector:
// We don't know if the first or the second vector contains non-ASCII data. Check the first
// vector, and if that's all-ASCII then the second vector must be the culprit. Either way
// we'll make sure the first vector local is the one that contains the non-ASCII data.
if (VectorContainsNonAsciiChar(firstVector))
{
goto FoundNonAsciiDataInFirstVector;
}
// Wasn't the first vector; must be the second.
pBuffer += SizeOfVector128InChars;
firstVector = secondVector;
FoundNonAsciiDataInFirstVector:
if (Sse2.IsSupported)
{
// The operation below forces the 0x8000 bit of each WORD to be set iff the WORD element
// has value >= 0x0800 (non-ASCII). Then we'll treat the vector as a BYTE vector in order
// to extract the mask. Reminder: the 0x0080 bit of each WORD should be ignored.
Vector128<ushort> asciiMaskForAddSaturate = Vector128.Create((ushort)0x7F80);
const uint NonAsciiDataSeenMask = 0b_1010_1010_1010_1010; // used for determining whether 'currentMask' contains non-ASCII data
currentMask = (uint)Sse2.MoveMask(Sse2.AddSaturate(firstVector, asciiMaskForAddSaturate).AsByte());
currentMask &= NonAsciiDataSeenMask;
// Now, the mask contains - from the LSB - a 0b00 pair for each ASCII char we saw, and a 0b10 pair for each non-ASCII char.
//
// (Keep endianness in mind in the below examples.)
// A non-ASCII char followed by two ASCII chars is 0b..._00_00_10. (tzcnt = 1)
// An ASCII char followed by two non-ASCII chars is 0b..._10_10_00. (tzcnt = 3)
// Two ASCII chars followed by a non-ASCII char is 0b..._10_00_00. (tzcnt = 5)
//
// This means tzcnt = 2 * numLeadingAsciiChars + 1. We can conveniently take advantage of the fact
// that the 2x multiplier already matches the char* stride length, then just subtract 1 at the end to
// compute the correct final ending pointer value.
Debug.Assert(currentMask != 0, "Shouldn't be here unless we see non-ASCII data.");
pBuffer = (char*)((byte*)pBuffer + (uint)BitOperations.TrailingZeroCount(currentMask) - 1);
}
else if (AdvSimd.Arm64.IsSupported)
{
// The following operation sets all the bits in a WORD to 1 where a non-ASCII char is found (otherwise to 0)
// in the vector. Then narrow each char to a byte by taking its top byte. Now the bottom-half (64-bits)
// of the vector contains 0xFFFF for non-ASCII and 0x0000 for ASCII char. We then find the index of the
// first non-ASCII char by counting number of trailing zeros representing ASCII chars before it.
Vector128<ushort> largestAsciiValue = Vector128.Create((ushort)0x007F);
Vector128<byte> compareResult = AdvSimd.CompareGreaterThan(firstVector, largestAsciiValue).AsByte();
ulong asciiCompareMask = AdvSimd.Arm64.UnzipOdd(compareResult, compareResult).AsUInt64().ToScalar();
// Compare mask now contains 8 bits for each 16-bit char. Divide it by 8 to get to the first non-ASCII byte.
pBuffer += BitOperations.TrailingZeroCount(asciiCompareMask) >> 3;
}
else
{
throw new PlatformNotSupportedException();
}
goto Finish;
FoundNonAsciiDataInCurrentDWord:
uint currentDWord;
Debug.Assert(!AllCharsInUInt32AreAscii(currentDWord), "Shouldn't be here unless we see non-ASCII data.");
if (FirstCharInUInt32IsAscii(currentDWord))
{
pBuffer++; // skip past the ASCII char
}
goto Finish;
InputBufferLessThanOneVectorInLength:
// These code paths get hit if the original input length was less than one vector in size.
// We can't perform vectorized reads at this point, so we'll fall back to reading primitives
// directly. Note that all of these reads are unaligned.
// Reminder: If this code path is hit, bufferLength is still a char count, not a byte count.
// We skipped the code path that multiplied the count by sizeof(char).
Debug.Assert(bufferLength < SizeOfVector128InChars);
// QWORD drain
if ((bufferLength & 4) != 0)
{
if (UIntPtr.Size == sizeof(ulong))