-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathYarrJIT.cpp
More file actions
7537 lines (6451 loc) · 373 KB
/
YarrJIT.cpp
File metadata and controls
7537 lines (6451 loc) · 373 KB
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
/*
* Copyright (C) 2009-2026 Apple Inc. All rights reserved.
* Copyright (C) 2019-2026 the V8 project authors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "YarrJIT.h"
#include "AllowMacroScratchRegisterUsage.h"
#include "CCallHelpers.h"
#include "LinkBuffer.h"
#include "Options.h"
#include "ProbeContext.h"
#if ENABLE(YARR_JIT_BACKREFERENCES_FOR_16BIT_EXPRS)
#include "JITThunks.h"
#endif
#include "VM.h"
#include "Yarr.h"
#include "YarrCanonicalize.h"
#include "YarrDisassembler.h"
#include "YarrJITRegisters.h"
#include "YarrMatchingContextHolder.h"
#include <wtf/ASCIICType.h>
#include <wtf/BitVector.h>
#include <wtf/HexNumber.h>
#include <wtf/ListDump.h>
#include <wtf/MathExtras.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/Threading.h>
#include <wtf/text/MakeString.h>
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
#if ENABLE(YARR_JIT)
namespace JSC { namespace Yarr {
namespace YarrJITInternal {
static constexpr bool verbose = false;
}
static constexpr int32_t errorCodePoint = -1;
#if ENABLE(YARR_JIT_UNICODE_EXPRESSIONS)
enum class TryReadUnicodeCharGenFirstNonBMPOptimization { DontUseOptimization, UseOptimization };
static MacroAssemblerCodeRef<JITThunkPtrTag> tryReadUnicodeCharSlowThunkGenerator(VM&);
#if ENABLE(YARR_JIT_UNICODE_CAN_INCREMENT_INDEX_FOR_NON_BMP)
static MacroAssemblerCodeRef<JITThunkPtrTag> tryReadUnicodeCharIncForNonBMPSlowThunkGenerator(VM&);
#endif
#endif
#if ENABLE(YARR_JIT_BACKREFERENCES_FOR_16BIT_EXPRS)
JSC_DECLARE_NOEXCEPT_JIT_OPERATION(operationAreCanonicallyEquivalent, bool, (unsigned, unsigned, CanonicalMode));
static MacroAssemblerCodeRef<JITThunkPtrTag> areCanonicallyEquivalentThunkGenerator(VM&);
// Since the generator areCanonicallyEquivalentThunkGenerator() needs to be static,
// we set the incoming argument registers to the thunk here and ASSERT at runtime
// that they match.
#if CPU(ARM64)
static constexpr GPRReg areCanonicallyEquivalentCharArgReg = ARM64Registers::x6;
static constexpr GPRReg areCanonicallyEquivalentPattCharArgReg = ARM64Registers::x7;
static constexpr GPRReg areCanonicallyEquivalentCanonicalModeArgReg = ARM64Registers::x10;
#elif CPU(X86_64)
static constexpr GPRReg areCanonicallyEquivalentCharArgReg = X86Registers::eax;
static constexpr GPRReg areCanonicallyEquivalentPattCharArgReg = X86Registers::r9;
static constexpr GPRReg areCanonicallyEquivalentCanonicalModeArgReg = X86Registers::r13;
// The thunk code assumes that we return the result to areCanonicallyEquivalentCharArgReg.
static_assert(areCanonicallyEquivalentCharArgReg == GPRInfo::returnValueGPR);
#endif
#endif
WTF_MAKE_TZONE_ALLOCATED_IMPL(BoyerMooreBitmap);
WTF_MAKE_TZONE_ALLOCATED_IMPL(BoyerMooreFastCandidates);
WTF_MAKE_TZONE_ALLOCATED_IMPL(YarrBoyerMooreData);
WTF_MAKE_TZONE_ALLOCATED_IMPL(YarrCodeBlock);
#if CPU(ARM64E)
JSC_ANNOTATE_JIT_OPERATION_RETURN(vmEntryToYarrJITAfter);
#endif
// We should pick the less frequently appearing character as a BM search's anchor to make BM search more and more efficient.
// This class takes some samples from the passed subject string to put weight on characters so that we can pick an optimal one adaptively.
class SubjectSampler {
public:
static constexpr unsigned sampleSize = 128;
explicit SubjectSampler(CharSize charSize)
: m_is8Bit(charSize == CharSize::Char8)
{
}
int32_t frequency(char16_t character) const
{
if (!m_size)
return 1;
return static_cast<int32_t>(m_samples[character & BoyerMooreBitmap::mapMask]) * sampleSize / m_size;
}
void sample(StringView string)
{
unsigned half = string.length() > sampleSize ? (string.length() - sampleSize) / 2 : 0;
unsigned end = std::min(string.length(), half + sampleSize);
if (string.is8Bit()) {
auto characters8 = string.span8();
for (unsigned i = half; i < end; ++i)
add(characters8[i]);
} else {
auto characters16 = string.span16();
for (unsigned i = half; i < end; ++i)
add(characters16[i]);
}
}
void dump() const
{
dataLogLn("Sampling Results size:(", m_size, ")");
for (unsigned i = 0; i < BoyerMooreBitmap::mapSize; ++i)
dataLogLn(" [", makeString(pad(' ', 3, i)), "] ", m_samples[i]);
}
bool is8Bit() const { return m_is8Bit; }
private:
inline void add(char16_t character)
{
++m_size;
++m_samples[character & BoyerMooreBitmap::mapMask];
}
std::array<uint8_t, BoyerMooreBitmap::mapSize> m_samples { };
uint8_t m_size { };
bool m_is8Bit { true };
};
void BoyerMooreFastCandidates::dump(PrintStream& out) const
{
if (!isValid()) {
out.print("isValid:(false)");
return;
}
out.print("isValid:(true),characters:(", listDump(m_characters), ")");
}
class BoyerMooreInfo {
WTF_MAKE_NONCOPYABLE(BoyerMooreInfo);
WTF_MAKE_TZONE_ALLOCATED(BoyerMooreInfo);
public:
static constexpr unsigned maxLength = 32;
explicit BoyerMooreInfo(CharSize charSize, unsigned length)
: m_characters(length)
, m_charSize(charSize)
{
ASSERT(this->length() <= maxLength);
}
unsigned length() const { return m_characters.size(); }
void shortenLength(unsigned length)
{
if (length <= this->length())
m_characters.shrink(length);
}
void set(unsigned index, char32_t character)
{
m_characters[index].add(m_charSize, character);
}
void setAll(unsigned index)
{
m_characters[index].setAll();
}
void addCharacters(unsigned index, const Vector<char32_t>& characters)
{
m_characters[index].addCharacters(m_charSize, characters);
}
void addRanges(unsigned index, const Vector<CharacterRange>& range)
{
m_characters[index].addRanges(m_charSize, range);
}
static UniqueRef<BoyerMooreInfo> create(CharSize charSize, unsigned length)
{
return makeUniqueRef<BoyerMooreInfo>(charSize, length);
}
std::optional<std::tuple<unsigned, unsigned>> findWorthwhileCharacterSequenceForLookahead(const SubjectSampler&) const;
std::tuple<BoyerMooreBitmap::Map, BoyerMooreFastCandidates> createCandidateBitmap(unsigned begin, unsigned end) const;
void dump(PrintStream&) const;
private:
std::tuple<int32_t, unsigned, unsigned> findBestCharacterSequence(const SubjectSampler&, unsigned numberOfCandidatesLimit) const;
Vector<BoyerMooreBitmap> m_characters;
CharSize m_charSize;
};
WTF_MAKE_TZONE_ALLOCATED_IMPL(BoyerMooreInfo);
std::tuple<int32_t, unsigned, unsigned> BoyerMooreInfo::findBestCharacterSequence(const SubjectSampler& sampler, unsigned numberOfCandidatesLimit) const
{
int32_t biggestPoint = INT32_MIN;
unsigned beginResult = 0;
unsigned endResult = 0;
for (unsigned index = 0; index < length();) {
while (index < length() && m_characters[index].count() > numberOfCandidatesLimit)
++index;
if (index == length())
break;
unsigned begin = index;
BoyerMooreBitmap::Map map { };
for (; index < length() && m_characters[index].count() <= numberOfCandidatesLimit; ++index)
map.merge(m_characters[index].map());
int32_t frequency = 0;
map.forEachSetBit([&](unsigned index) {
frequency += sampler.frequency(index);
});
// Cutoff at 50%. If we could encounter the character more than 50%, then BM search would be useless probably.
int32_t matchingProbability = (BoyerMooreBitmap::mapSize / 2) - frequency;
int32_t point = (index - begin) * matchingProbability;
if (point > biggestPoint) {
biggestPoint = point;
beginResult = begin;
endResult = index;
}
}
return std::tuple { biggestPoint, beginResult, endResult };
}
std::optional<std::tuple<unsigned, unsigned>> BoyerMooreInfo::findWorthwhileCharacterSequenceForLookahead(const SubjectSampler& sampler) const
{
// If candiates-per-character becomes larger, then sequence is not profitable since this sequence will match against
// too many characters. But if we limit candiates-per-character smaller, it is possible that we only find very short
// character sequence. We start with low limit, then enlarging the limit to find more and more profitable
// character sequence.
int32_t biggestPoint = INT32_MIN;
unsigned begin = 0;
unsigned end = 0;
constexpr unsigned maxCandidatesPerCharacter = 32;
static_assert(maxCandidatesPerCharacter < BoyerMooreBitmap::mapSize);
for (unsigned limit = 4; limit < maxCandidatesPerCharacter; limit *= 2) {
auto [newPoint, newBegin, newEnd] = findBestCharacterSequence(sampler, limit);
if (newPoint > biggestPoint) {
biggestPoint = newPoint;
begin = newBegin;
end = newEnd;
}
}
if (biggestPoint < 0)
return std::nullopt;
return std::tuple { begin, end };
}
std::tuple<BoyerMooreBitmap::Map, BoyerMooreFastCandidates> BoyerMooreInfo::createCandidateBitmap(unsigned begin, unsigned end) const
{
BoyerMooreBitmap::Map map { };
BoyerMooreFastCandidates charactersFastPath;
for (unsigned index = begin; index < end; ++index) {
auto& bmBitmap = m_characters[index];
map.merge(bmBitmap.map());
charactersFastPath.merge(bmBitmap.charactersFastPath());
}
return std::tuple { WTF::move(map), WTF::move(charactersFastPath) };
}
void BoyerMooreInfo::dump(PrintStream& out) const
{
out.println("BoyerMooreInfo size:(", m_characters.size(), ")");
unsigned index = 0;
for (auto& map : m_characters)
out.println(" [", makeString(pad(' ', 3, index++)), "] ", map);
}
void BoyerMooreBitmap::dump(PrintStream& out) const
{
out.print(m_map);
}
// SIMD multi-pattern search info for alternation patterns.
// For patterns like /agggtaaa|tttaccct/i, extracts the first 4 bytes of each alternative
// and creates masks for parallel SIMD comparison across multiple starting positions.
//
// Load input at 4 offsets (0,1,2,3), apply mask, compare as 4-byte words.
// This checks 4 consecutive starting positions per 16-byte SIMD register.
//
// FIXME: Currently we are only supporting 2 alternative cases at first, aligned to V8's optimization.
// We will extend it to 1 and 3 later.
struct MaskedAlternativeInfo {
private:
WTF_MAKE_TZONE_ALLOCATED(MaskedAlternativeInfo);
public:
static constexpr unsigned maxAlternatives = 2; // Support 2 alternatives initially
static constexpr unsigned patternBytes = 4; // Match first 4 bytes
static constexpr unsigned thresholdForDistinctCharacters = 16;
// Per-alternative pattern data
struct Alternative {
uint32_t chars { 0 }; // First 4 bytes as little-endian uint32
uint32_t mask { 0 }; // Mask for case-insensitive matching (0xFF = exact, 0xDF = case-insensitive)
};
std::array<Alternative, maxAlternatives> alternatives { };
unsigned numAlternatives { 0 };
uint32_t minPatternLength { 0 }; // Minimum length across alternatives
// Compute mask and char value for a character class that makes all members equivalent
// Returns false if the class is too complex (e.g., ranges spanning many bits, inverted class)
static bool computeMaskForCharacterClass(const CharacterClass& charClass, bool ignoreCase, uint8_t& outChar, uint8_t& outMask)
{
// Don't handle inverted classes or classes with ranges for now
// Only handle simple character sets like [acg] or [cgt]
if (charClass.m_matches.isEmpty())
return false;
if (!charClass.m_ranges.isEmpty())
return false;
if (!charClass.m_matchesUnicode.isEmpty() || !charClass.m_rangesUnicode.isEmpty())
return false;
// Collect all characters (and their case variants if ignoreCase)
Vector<uint8_t, 32> chars;
for (char32_t ch : charClass.m_matches) {
if (!isASCII(ch))
return false; // ASCII only
if (ignoreCase && isASCIIAlpha(ch)) {
chars.append(toASCIILower(static_cast<uint8_t>(ch)));
chars.append(toASCIIUpper(static_cast<uint8_t>(ch)));
} else
chars.append(static_cast<uint8_t>(ch));
if (chars.size() > thresholdForDistinctCharacters)
return false;
}
if (chars.isEmpty() || chars.size() > thresholdForDistinctCharacters)
return false;
// Compute XOR of all differing bits
uint8_t differingBits = 0;
for (unsigned i = 1; i < chars.size(); ++i)
differingBits |= (chars[0] ^ chars[i]);
// Mask clears all differing bits
outMask = ~differingBits;
// The character value is any character ANDed with the mask (they all produce the same result)
outChar = chars[0] & outMask;
return true;
}
// Create from a disjunction with exactly 2 fixed alternatives
// Returns invalid info if the pattern doesn't qualify for this optimization
static std::optional<MaskedAlternativeInfo> create(const PatternDisjunction& disjunction, bool ignoreCase, CharSize charSize)
{
MaskedAlternativeInfo info;
// Only support Latin1 (8-bit) for now
if (charSize != CharSize::Char8)
return std::nullopt;
// Need exactly 2 alternatives
auto& alternatives = disjunction.m_alternatives;
if (alternatives.size() != maxAlternatives)
return std::nullopt;
// Both alternatives must have at least 4 characters and be fixed-size
info.minPatternLength = UINT32_MAX;
for (unsigned i = 0; i < maxAlternatives; ++i) {
const PatternAlternative* alt = alternatives[i].get();
if (!alt->m_hasFixedSize)
return std::nullopt;
if (alt->m_minimumSize < patternBytes)
return std::nullopt;
info.minPatternLength = std::min(info.minPatternLength, alt->m_minimumSize);
// Extract first 4 characters - can be simple characters or character classes
uint32_t chars = 0;
uint32_t mask = 0;
unsigned charIndex = 0;
for (const PatternTerm& term : alt->m_terms) {
if (charIndex >= patternBytes)
break;
if (term.quantityType != QuantifierType::FixedCount || term.quantityMinCount != 1)
return std::nullopt; // No quantifiers
uint8_t byteChar = 0;
uint8_t byteMask = 0xFF;
if (term.type == PatternTerm::Type::PatternCharacter) {
char32_t ch = term.patternCharacter;
if (!isASCII(ch))
return std::nullopt; // ASCII only for now
byteChar = static_cast<uint8_t>(ch);
// Mask: 0xDF for case-insensitive letters, 0xFF for exact match
if (ignoreCase && isASCIIAlpha(ch))
byteMask = 0xDF; // Clear bit 5 to normalize case
} else if (term.type == PatternTerm::Type::CharacterClass) {
// Handle character class by computing a mask that makes all members equivalent
if (term.m_invert)
return std::nullopt; // Don't handle inverted classes
if (!computeMaskForCharacterClass(*term.characterClass, ignoreCase, byteChar, byteMask))
return std::nullopt; // Class too complex
} else
return std::nullopt; // Unsupported term type
// Build the 4-byte pattern (little-endian)
chars |= static_cast<uint32_t>(byteChar) << (charIndex * 8);
mask |= static_cast<uint32_t>(byteMask) << (charIndex * 8);
++charIndex;
}
if (charIndex < patternBytes)
return std::nullopt; // Not enough characters
info.alternatives[i].chars = chars;
info.alternatives[i].mask = mask;
}
info.numAlternatives = 2;
return info;
}
};
WTF_MAKE_TZONE_ALLOCATED_IMPL(MaskedAlternativeInfo);
static constexpr MacroAssembler::TrustedImm32 surrogateTagMask = MacroAssembler::TrustedImm32(0xdc00dc00);
static constexpr MacroAssembler::TrustedImm32 surrogatePairTags = MacroAssembler::TrustedImm32(0xdc00d800);
#if ENABLE(YARR_JIT_UNICODE_EXPRESSIONS)
template<TryReadUnicodeCharGenFirstNonBMPOptimization useNonBMPOptimization>
void tryReadUnicodeCharImpl(VM& vm, CCallHelpers& jit, MacroAssembler::RegisterID resultReg)
{
MacroAssembler::JumpList slowCases;
MacroAssembler::JumpList isBMP;
MacroAssembler::JumpList done;
YarrJITDefaultRegisters regs;
if (resultReg != regs.regT0)
jit.swap(regs.regT0, resultReg);
// Check if we can read two UTF-16 characters at once.
jit.add64(MacroAssembler::TrustedImm32(4), regs.regUnicodeInputAndTrail, regs.unicodeAndSubpatternIdTemp);
slowCases.append(jit.branchPtr(MacroAssembler::Above, regs.unicodeAndSubpatternIdTemp, regs.endOfStringAddress));
// Load and try to process two UTF-16 characters.
// If they are a proper surrogate pair, compute the non-BMP codepoint.
jit.load32(MacroAssembler::Address(regs.regUnicodeInputAndTrail), resultReg);
#if CPU(ARM64)
jit.and32AndSetFlags(surrogateTagMask, resultReg, regs.unicodeAndSubpatternIdTemp);
isBMP.append(jit.branch(MacroAssembler::Zero));
#else
jit.and32(surrogateTagMask, resultReg, regs.unicodeAndSubpatternIdTemp);
isBMP.append(jit.branch32(MacroAssembler::Equal, regs.unicodeAndSubpatternIdTemp, MacroAssembler::TrustedImm32(0)));
#endif
slowCases.append(jit.branch32(MacroAssembler::NotEqual, regs.unicodeAndSubpatternIdTemp, surrogatePairTags));
// Create the UTF32 character from the surrogate pair.
#if CPU(ARM64)
jit.urshift32(resultReg, MacroAssembler::TrustedImm32(16), regs.unicodeAndSubpatternIdTemp);
jit.insertBitField32(resultReg, MacroAssembler::TrustedImm32(10), MacroAssembler::TrustedImm32(10), regs.unicodeAndSubpatternIdTemp);
jit.add32(MacroAssembler::TrustedImm32(0x10000), regs.unicodeAndSubpatternIdTemp, resultReg);
#else
jit.and32(MacroAssembler::TrustedImm32(0xffff), resultReg, regs.unicodeAndSubpatternIdTemp);
jit.lshift32(MacroAssembler::TrustedImm32(10), regs.unicodeAndSubpatternIdTemp);
jit.urshift32(resultReg, MacroAssembler::TrustedImm32(16), resultReg);
jit.getEffectiveAddress(MacroAssembler::BaseIndex(regs.unicodeAndSubpatternIdTemp, resultReg, MacroAssembler::TimesOne, -U16_SURROGATE_OFFSET), resultReg);
#endif
#if ENABLE(YARR_JIT_UNICODE_CAN_INCREMENT_INDEX_FOR_NON_BMP)
if (useNonBMPOptimization == TryReadUnicodeCharGenFirstNonBMPOptimization::UseOptimization)
jit.move(MacroAssembler::TrustedImm32(1), regs.firstCharacterAdditionalReadSize);
#endif
done.append(jit.jump());
isBMP.link(jit);
jit.and32(MacroAssembler::TrustedImm32(0xffff), resultReg);
done.append(jit.jump());
slowCases.link(&jit);
#if ENABLE(YARR_JIT_UNICODE_CAN_INCREMENT_INDEX_FOR_NON_BMP)
if constexpr (useNonBMPOptimization == TryReadUnicodeCharGenFirstNonBMPOptimization::UseOptimization)
jit.nearCallThunk(CodeLocationLabel { vm.getCTIStub(tryReadUnicodeCharIncForNonBMPSlowThunkGenerator).template retaggedCode<NoPtrTag>() });
else
#endif
jit.nearCallThunk(CodeLocationLabel { vm.getCTIStub(tryReadUnicodeCharSlowThunkGenerator).template retaggedCode<NoPtrTag>() });
done.link(&jit);
if (resultReg != regs.regT0)
jit.swap(regs.regT0, resultReg);
}
template<TryReadUnicodeCharGenFirstNonBMPOptimization useNonBMPOptimization>
void tryReadUnicodeCharSlowImpl(CCallHelpers& jit)
{
MacroAssembler::JumpList bmpOnly;
MacroAssembler::JumpList isBMP;
MacroAssembler::JumpList notSurrogatePair;
MacroAssembler::JumpList checkForDanglingSurrogates;
MacroAssembler::JumpList bmpDone;
MacroAssembler::JumpList haveResult;
YarrJITDefaultRegisters regs;
// This code generator is used to build two variations of a character reader that handles Unicode non-BMP surrogate pairs.
// This code generator is used to build thunks or as inline code. Its "calling convention" is unconventional.
// It assumes the following registers are already populated with these values:
// regs.regUnicodeInputAndTrail is the string address to start reading from.
// regs.input contains the pointer of the beginning of the string.
// regs.endOfStringAddress contains the address one past the end of the string.
// For architectures that put the surrogate masks and tags in registers,
// regs.surrogateTagMask contains 0xdc00dc00 and regs.surrogatePairTags contains 0xdc00d800.
// When the YARR_JIT_UNICODE_CAN_INCREMENT_INDEX_FOR_NON_BMP optimization is enabled and used,
// regs.firstCharacterAdditionalReadSize is used to advance 2 characters when we read a non-BMP codepoint.
// regs.unicodeAndSubpatternIdTemp is used as a temporary.
// The result is returned via regs.regT0.
auto resultReg = regs.regT0;
// Check if we can read two UTF-16 characters at once.
jit.add64(MacroAssembler::TrustedImm32(4), regs.regUnicodeInputAndTrail, regs.unicodeAndSubpatternIdTemp);
bmpOnly.append(jit.branchPtr(MacroAssembler::Above, regs.unicodeAndSubpatternIdTemp, regs.endOfStringAddress));
// Load and try to process two UTF-16 characters.
// If they are a proper surrogate pair, compute the non-BMP codepoint.
jit.load32(MacroAssembler::Address(regs.regUnicodeInputAndTrail), resultReg);
#if CPU(ARM64)
jit.and32AndSetFlags(surrogateTagMask, resultReg, regs.unicodeAndSubpatternIdTemp);
isBMP.append(jit.branch(MacroAssembler::Zero));
#else
jit.and32(surrogateTagMask, resultReg, regs.unicodeAndSubpatternIdTemp);
isBMP.append(jit.branch32(MacroAssembler::Equal, regs.unicodeAndSubpatternIdTemp, MacroAssembler::TrustedImm32(0)));
#endif
// if it is surrogate pair, we already handled it in the inlined code.
// Check if we can return the dangling surrogate or if it is part of a valid pair where the leading surrogate
// that is offset one character before the load pointer.
jit.and32(MacroAssembler::TrustedImm32(0xffff), regs.unicodeAndSubpatternIdTemp);
// If it is a leading surrogate, the check above proved that it wasn't followed by a trailing surrogate.
// If so fall through, otherwise perform other dangling checks.
checkForDanglingSurrogates.append(jit.branch32(MacroAssembler::Equal, regs.unicodeAndSubpatternIdTemp, MacroAssembler::TrustedImm32(0xdc00)));
isBMP.link(jit);
jit.and32(MacroAssembler::TrustedImm32(0xffff), resultReg);
jit.ret();
checkForDanglingSurrogates.link(&jit);
// Remove the second character that we loaded.
jit.and32(MacroAssembler::TrustedImm32(0xffff), resultReg);
MacroAssembler::Label checkForDanglingSurrogatesLabel(&jit);
// Can ew read the prior character?
jit.subPtr(MacroAssembler::TrustedImm32(2), regs.regUnicodeInputAndTrail);
// If not, we branch to return the dangling surrogate.
bmpDone.append(jit.branchPtr(MacroAssembler::Below, regs.regUnicodeInputAndTrail, regs.input));
// Load the prior character and check if it is a leading surrogate.
jit.load16Unaligned(MacroAssembler::Address(regs.regUnicodeInputAndTrail), regs.regUnicodeInputAndTrail);
jit.and32(surrogateTagMask, regs.regUnicodeInputAndTrail, regs.unicodeAndSubpatternIdTemp);
// It wasn't a leading surrogate, so return the original dangling surrogate.
bmpDone.append(jit.branch32(MacroAssembler::NotEqual, regs.unicodeAndSubpatternIdTemp, MacroAssembler::TrustedImm32(0xd800)));
// The prior characters was a leading surrogate, Ecma262 says that this is an error, so return the error code point.
jit.move(MacroAssembler::TrustedImm32(errorCodePoint), resultReg);
bmpDone.append(jit.jump());
bmpOnly.link(&jit);
// Can't read two characters, then just read one.
jit.load16Unaligned(MacroAssembler::Address(regs.regUnicodeInputAndTrail), resultReg);
// Is the character a trailing surrogate?
jit.and32(surrogateTagMask, resultReg, regs.unicodeAndSubpatternIdTemp);
// If so, branch back to handle the possibility that we loaded the second surrogate of a proper pair.
jit.branch32(MacroAssembler::Equal, regs.unicodeAndSubpatternIdTemp, MacroAssembler::TrustedImm32(0xdc00)).linkTo(checkForDanglingSurrogatesLabel, jit);
bmpDone.link(&jit);
haveResult.link(&jit);
}
#endif // ENABLE(YARR_JIT_UNICODE_EXPRESSIONS)
template<class YarrJITRegs = YarrJITDefaultRegisters>
class YarrGenerator final : public YarrJITInfo {
class MatchTargets {
public:
enum class PreferredTarget : uint8_t {
NoPreference = 0,
PreferMatchSucceeded = 1,
MatchFailFallThrough = PreferMatchSucceeded,
PreferMatchFailed = 2,
MatchSuccessFallThrough = PreferMatchFailed
};
MatchTargets(PreferredTarget preferredTarget = PreferredTarget::NoPreference)
: m_preferredTarget(preferredTarget)
{ }
MatchTargets(MacroAssembler::JumpList& matchDest)
: m_matchSucceededTargets(&matchDest)
, m_preferredTarget(PreferredTarget::PreferMatchSucceeded)
{ }
MatchTargets(MacroAssembler::JumpList& compareDest, PreferredTarget preferredTarget)
: m_preferredTarget(preferredTarget)
{
if (preferredTarget == PreferredTarget::PreferMatchFailed)
m_matchFailedTargets = &compareDest;
else
m_matchSucceededTargets = &compareDest;
}
MatchTargets(MacroAssembler::JumpList& matchDest, MacroAssembler::JumpList& failDest, PreferredTarget preferredTarget = PreferredTarget::NoPreference)
: m_matchSucceededTargets(&matchDest)
, m_matchFailedTargets(&failDest)
, m_preferredTarget(preferredTarget)
{ }
PreferredTarget preferredTarget()
{
return m_preferredTarget;
}
bool hasSucceedTarget()
{
return m_matchSucceededTargets != nullptr;
}
bool hasFailedTarget()
{
return m_matchFailedTargets != nullptr;
}
MacroAssembler::JumpList& matchSucceeded() { return *m_matchSucceededTargets; }
MacroAssembler::JumpList& matchFailed() { return *m_matchFailedTargets; }
void appendSucceeded(MacroAssembler::Jump jump)
{
ASSERT(m_matchSucceededTargets != nullptr);
m_matchSucceededTargets->append(jump);
}
void appendFailed(MacroAssembler::Jump jump)
{
ASSERT(m_matchFailedTargets != nullptr);
m_matchFailedTargets->append(jump);
}
private:
MacroAssembler::JumpList* m_matchSucceededTargets { nullptr };
MacroAssembler::JumpList* m_matchFailedTargets { nullptr };
PreferredTarget m_preferredTarget;
};
#if ENABLE(YARR_JIT_ALL_PARENS_EXPRESSIONS)
struct ParenContextSizes {
size_t m_numSubpatterns;
size_t m_numDuplicateNamedCaptures;
size_t m_frameSlots;
ParenContextSizes(size_t numSubpatterns, size_t numDuplicateNamedCaptures, size_t frameSlots)
: m_numSubpatterns(numSubpatterns)
, m_numDuplicateNamedCaptures(numDuplicateNamedCaptures)
, m_frameSlots(frameSlots)
{
}
size_t numSubpatterns() { return m_numSubpatterns; }
size_t numDuplicateNamedCaptures() { return m_numDuplicateNamedCaptures; }
size_t frameSlots() { return m_frameSlots; }
};
struct ParenContext {
struct ParenContext* next;
struct BeginAndMatchAmount {
uint32_t begin;
uint32_t matchAmount;
} beginAndMatchAmount;
uint32_t end;
uintptr_t returnAddress;
struct Subpatterns {
unsigned start;
unsigned end;
} subpatterns[0];
unsigned duplicateNamedCaptures[0];
uintptr_t frameSlots[0];
static size_t sizeFor(ParenContextSizes& parenContextSizes)
{
return sizeof(ParenContext) + sizeof(Subpatterns) * parenContextSizes.numSubpatterns() + sizeof(unsigned) * (parenContextSizes.numDuplicateNamedCaptures()) + sizeof(uintptr_t) * parenContextSizes.frameSlots();
}
static constexpr ptrdiff_t nextOffset()
{
return offsetof(ParenContext, next);
}
static constexpr ptrdiff_t beginOffset()
{
return offsetof(ParenContext, beginAndMatchAmount) + offsetof(BeginAndMatchAmount, begin);
}
static constexpr ptrdiff_t matchAmountOffset()
{
return offsetof(ParenContext, beginAndMatchAmount) + offsetof(BeginAndMatchAmount, matchAmount);
}
static constexpr ptrdiff_t endOffset()
{
return offsetof(ParenContext, end);
}
static constexpr ptrdiff_t returnAddressOffset()
{
return offsetof(ParenContext, returnAddress);
}
static constexpr ptrdiff_t subpatternOffset(size_t subpattern)
{
return offsetof(ParenContext, subpatterns) + (subpattern - 1) * sizeof(Subpatterns);
}
static constexpr ptrdiff_t duplicateNamedCaptureOffset(ParenContextSizes& parenContextSizes, size_t namedCapture)
{
return offsetof(ParenContext, subpatterns) + (parenContextSizes.numSubpatterns()) * sizeof(Subpatterns) + (namedCapture - 1) * sizeof(unsigned);
}
static ptrdiff_t savedFrameOffset(ParenContextSizes& parenContextSizes)
{
return offsetof(ParenContext, subpatterns) + (parenContextSizes.numSubpatterns()) * sizeof(Subpatterns) + (parenContextSizes.numDuplicateNamedCaptures()) * sizeof(unsigned);
}
};
void allocateParenContext(MacroAssembler::RegisterID result)
{
m_hitMatchLimit.append(m_jit.branchSub32(MacroAssembler::Zero, MacroAssembler::TrustedImm32(1), m_regs.remainingMatchCount));
// Try to allocate from freelist first.
MacroAssembler::Jump allocateFromStack;
if (m_regs.freelistRegister != InvalidGPRReg) {
allocateFromStack = m_jit.branchTestPtr(MacroAssembler::Zero, m_regs.freelistRegister);
m_jit.move(m_regs.freelistRegister, result);
m_jit.loadPtr(MacroAssembler::Address(m_regs.freelistRegister, ParenContext::nextOffset()), m_regs.freelistRegister);
} else {
m_jit.loadPtr(MacroAssembler::Address(m_regs.matchingContext, MatchingContextHolder::offsetOfFreeList()), result);
allocateFromStack = m_jit.branchTestPtr(MacroAssembler::Zero, result);
m_jit.transferPtr(MacroAssembler::Address(result, ParenContext::nextOffset()), MacroAssembler::Address(m_regs.matchingContext, MatchingContextHolder::offsetOfFreeList()));
}
auto done = m_jit.jump();
// Freelist is null, allocate from stack.
allocateFromStack.link(&m_jit);
size_t parenContextSize = WTF::roundUpToMultipleOf<stackAlignmentBytes()>(ParenContext::sizeFor(m_parenContextSizes));
m_jit.subPtr(MacroAssembler::stackPointerRegister, MacroAssembler::TrustedImm32(static_cast<int32_t>(parenContextSize)), result);
m_abortExecution.append(m_jit.branchPtr(MacroAssembler::Above, MacroAssembler::Address(m_regs.matchingContext, MatchingContextHolder::offsetOfStackLimit()), result));
m_jit.move(result, MacroAssembler::stackPointerRegister);
done.link(&m_jit);
}
void freeParenContext(MacroAssembler::RegisterID headPtrRegister)
{
if (m_regs.freelistRegister != InvalidGPRReg) {
m_jit.storePtr(m_regs.freelistRegister, MacroAssembler::Address(headPtrRegister, ParenContext::nextOffset()));
m_jit.move(headPtrRegister, m_regs.freelistRegister);
} else {
m_jit.transferPtr(MacroAssembler::Address(m_regs.matchingContext, MatchingContextHolder::offsetOfFreeList()), MacroAssembler::Address(headPtrRegister, ParenContext::nextOffset()));
m_jit.storePtr(headPtrRegister, MacroAssembler::Address(m_regs.matchingContext, MatchingContextHolder::offsetOfFreeList()));
}
}
void storeBeginAndMatchAmountToParenContext(MacroAssembler::RegisterID beginGPR, MacroAssembler::RegisterID matchAmountGPR, MacroAssembler::RegisterID parenContextGPR)
{
static_assert(ParenContext::beginOffset() + 4 == ParenContext::matchAmountOffset());
m_jit.storePair32(beginGPR, matchAmountGPR, parenContextGPR, MacroAssembler::TrustedImm32(ParenContext::beginOffset()));
}
void loadBeginAndMatchAmountFromParenContext(MacroAssembler::RegisterID parenContextGPR, MacroAssembler::RegisterID beginGPR, MacroAssembler::RegisterID matchAmountGPR)
{
static_assert(ParenContext::beginOffset() + 4 == ParenContext::matchAmountOffset());
m_jit.loadPair32(parenContextGPR, MacroAssembler::TrustedImm32(ParenContext::beginOffset()), beginGPR, matchAmountGPR);
}
void saveParenContext(MacroAssembler::RegisterID parenContextReg, MacroAssembler::RegisterID tempReg, unsigned firstSubpattern, unsigned lastSubpattern, unsigned subpatternBaseFrameLocation, bool clearCapturesAfterSave = true, bool useBeginIndexFromFrame = false)
{
BitVector duplicateNamedCaptureGroups;
bool hasNamedCaptures = m_pattern.hasDuplicateNamedCaptureGroups();
// For FixedCount saved at END, use frame.beginIndex (iteration start) instead of m_regs.index (current position).
// This is needed because content's backtrack expects beginIndex to be the iteration start.
// Also we store m_regs.index to endOffset so we save both begin and end.
if (useBeginIndexFromFrame) {
loadFromFrame(subpatternBaseFrameLocation + BackTrackInfoParentheses::beginIndex(), tempReg);
m_jit.store32(tempReg, MacroAssembler::Address(parenContextReg, ParenContext::beginOffset()));
loadFromFrame(subpatternBaseFrameLocation + BackTrackInfoParentheses::matchAmountIndex(), tempReg);
m_jit.store32(tempReg, MacroAssembler::Address(parenContextReg, ParenContext::matchAmountOffset()));
m_jit.store32(m_regs.index, MacroAssembler::Address(parenContextReg, ParenContext::endOffset()));
} else {
loadFromFrame(subpatternBaseFrameLocation + BackTrackInfoParentheses::matchAmountIndex(), tempReg);
storeBeginAndMatchAmountToParenContext(m_regs.index, tempReg, parenContextReg);
}
loadFromFrame(subpatternBaseFrameLocation + BackTrackInfoParentheses::returnAddressIndex(), tempReg);
m_jit.storePtr(tempReg, MacroAssembler::Address(parenContextReg, ParenContext::returnAddressOffset()));
if (shouldRecordSubpatterns()) {
for (unsigned subpattern = firstSubpattern; subpattern <= lastSubpattern; subpattern++) {
static_assert(is64Bit());
m_jit.transfer64(subpatternStartAddress(subpattern), MacroAssembler::Address(parenContextReg, ParenContext::subpatternOffset(subpattern)));
if (hasNamedCaptures) {
unsigned duplicateNamedGroup = m_pattern.m_duplicateNamedGroupForSubpatternId[subpattern];
if (duplicateNamedGroup)
duplicateNamedCaptureGroups.set(duplicateNamedGroup);
}
// For Greedy/NonGreedy, clear captures after saving at BEGIN (before iteration runs).
// For FixedCount, we save at END and should NOT clear (iteration already set them).
if (clearCapturesAfterSave)
clearSubpattern(subpattern);
}
for (unsigned duplicateNamedGroupId : duplicateNamedCaptureGroups) {
loadDuplicateNamedGroupSubpatternId(duplicateNamedGroupId, tempReg);
m_jit.store32(tempReg, MacroAssembler::Address(parenContextReg, ParenContext::duplicateNamedCaptureOffset(m_parenContextSizes, duplicateNamedGroupId)));
if (clearCapturesAfterSave)
storeDuplicateNamedGroupSubpatternId(duplicateNamedGroupId, 0);
}
}
subpatternBaseFrameLocation += YarrStackSpaceForBackTrackInfoParentheses;
for (unsigned frameLocation = subpatternBaseFrameLocation; frameLocation < m_parenContextSizes.frameSlots(); frameLocation++) {
loadFromFrame(frameLocation, tempReg);
m_jit.storePtr(tempReg, MacroAssembler::Address(parenContextReg, ParenContext::savedFrameOffset(m_parenContextSizes) + frameLocation * sizeof(uintptr_t)));
}
}
void restoreParenContext(MacroAssembler::RegisterID parenContextReg, MacroAssembler::RegisterID tempReg, unsigned firstSubpattern, unsigned lastSubpattern, unsigned subpatternBaseFrameLocation)
{
BitVector duplicateNamedCaptureGroups;
bool hasNamedCaptures = m_pattern.hasDuplicateNamedCaptureGroups();
loadBeginAndMatchAmountFromParenContext(parenContextReg, m_regs.index, tempReg);
storeToFrame(m_regs.index, subpatternBaseFrameLocation + BackTrackInfoParentheses::beginIndex());
storeToFrame(tempReg, subpatternBaseFrameLocation + BackTrackInfoParentheses::matchAmountIndex());
m_jit.loadPtr(MacroAssembler::Address(parenContextReg, ParenContext::returnAddressOffset()), tempReg);
storeToFrame(tempReg, subpatternBaseFrameLocation + BackTrackInfoParentheses::returnAddressIndex());
if (shouldRecordSubpatterns()) {
for (unsigned subpattern = firstSubpattern; subpattern <= lastSubpattern; subpattern++) {
static_assert(is64Bit());
m_jit.transfer64(MacroAssembler::Address(parenContextReg, ParenContext::subpatternOffset(subpattern)), subpatternStartAddress(subpattern));
if (hasNamedCaptures) {
unsigned duplicateNamedGroup = m_pattern.m_duplicateNamedGroupForSubpatternId[subpattern];
if (duplicateNamedGroup)
duplicateNamedCaptureGroups.set(duplicateNamedGroup);
}
}
for (unsigned duplicateNamedGroupId : duplicateNamedCaptureGroups) {
m_jit.load32(MacroAssembler::Address(parenContextReg, ParenContext::duplicateNamedCaptureOffset(m_parenContextSizes, duplicateNamedGroupId)), tempReg);
storeDuplicateNamedGroupSubpatternIdFromReg(duplicateNamedGroupId, tempReg);
}
}
subpatternBaseFrameLocation += YarrStackSpaceForBackTrackInfoParentheses;
for (unsigned frameLocation = subpatternBaseFrameLocation; frameLocation < m_parenContextSizes.frameSlots(); frameLocation++) {
m_jit.loadPtr(MacroAssembler::Address(parenContextReg, ParenContext::savedFrameOffset(m_parenContextSizes) + frameLocation * sizeof(uintptr_t)), tempReg);
storeToFrame(tempReg, frameLocation);
}
}
#endif
void optimizeAlternative(PatternAlternative* alternative)
{
if (!alternative->m_terms.size())
return;
for (unsigned i = 0; i < alternative->m_terms.size() - 1; ++i) {
PatternTerm& term = alternative->m_terms[i];
PatternTerm& nextTerm = alternative->m_terms[i + 1];
// We can move BMP only character classes after fixed character terms.
// When not decoding surrogate pairs (Char8 mode), only swap if the character class
// has no non-BMP characters and is not inverted. Otherwise the swapped pattern could
// be passed to byteCodeCompilePattern (on JIT allocation failure) and then executed
// against a Char16 string where the changed term order would cause misreads of
// surrogate pairs. An inverted class like [^a] has BMP-only class data but can match
// non-BMP characters (variable width in UTF-16), so it must not be swapped either.
if ((term.type == PatternTerm::Type::CharacterClass)
&& (term.quantityType == QuantifierType::FixedCount)
&& !term.m_invert
&& ((!m_decodeSurrogatePairs && !term.characterClass->hasNonBMPCharacters()) || term.characterClass->hasOneCharacterSize())
&& (nextTerm.type == PatternTerm::Type::PatternCharacter)
&& (nextTerm.quantityType == QuantifierType::FixedCount)) {
PatternTerm termCopy = term;
alternative->m_terms[i] = nextTerm;
alternative->m_terms[i + 1] = termCopy;
}
}
}
constexpr static unsigned MaximumCharacterClassSizeForBitTest = 8 * sizeof(UCPURegister);
using CharacterBitSet = WTF::BitSet<MaximumCharacterClassSizeForBitTest>;
void matchCharacterClassByBitTest(MacroAssembler::RegisterID character, MacroAssembler::RegisterID scratch, MacroAssembler::JumpList& matchDest, char32_t min, char32_t max, CharacterBitSet mask)
{
switch (mask.count()) {
case 0:
return;
case 1:
case 2:
case 3:
case 4:
// If the set is small enough, still defer to a series of branches.
mask.forEachSetBit([&](size_t value) {
matchDest.append(m_jit.branch32(MacroAssembler::Equal, character, MacroAssembler::TrustedImm32(min + value)));
return IterationStatus::Continue;
});
break;
default: {
// Otherwise, actually perform the bit test.
#if CPU(REGISTER64)
m_jit.sub32(character, MacroAssembler::Imm32(static_cast<unsigned>(min)), scratch);
MacroAssembler::Jump notInVector = m_jit.branch32(MacroAssembler::Above, scratch, MacroAssembler::TrustedImm32(max - min));
m_jit.lshift64(MacroAssembler::TrustedImm32(1), scratch, scratch);
matchDest.append(m_jit.branchTest64(MacroAssembler::NonZero, scratch, MacroAssembler::TrustedImm64(mask.storage()[0])));
#else
m_jit.sub32(character, MacroAssembler::Imm32(static_cast<unsigned>(min)), scratch);
MacroAssembler::Jump notInVector = m_jit.branch32(MacroAssembler::Above, scratch, MacroAssembler::TrustedImm32(max - min));
m_jit.lshift32(MacroAssembler::TrustedImm32(1), scratch, scratch);
matchDest.append(m_jit.branchTest32(MacroAssembler::NonZero, scratch, MacroAssembler::TrustedImm32(mask.storage()[0])));
#endif
notInVector.link(&m_jit);
}
}
}
void matchCharacterClassSet(MacroAssembler::RegisterID character, MacroAssembler::RegisterID scratch, MacroAssembler::JumpList& matchDest, std::span<const char32_t> matches)
{
if (matches.empty())
return;
if (matches.size() == 1) {
matchDest.append(m_jit.branch32(MacroAssembler::Equal, character, MacroAssembler::Imm32(static_cast<unsigned>(matches.front()))));
return;
}
// If we have multiple matches close together (not necessarily contiguous), we
// can try a biased bitmask - subtract the minimum match from the character,
// then see if it's present in a precomputed mask. We keep the bitset size quite
// small in order to keep it easy to materialize - this approach lets us avoid
// a load or lookup table in favor of just masking against an immediate.
char32_t min = matches.front();
char32_t max = matches.back();
ASSERT(max > min);
if ((max - min) < MaximumCharacterClassSizeForBitTest) {
CharacterBitSet mask;
for (char32_t character : matches)
mask.set(character - min);
matchCharacterClassByBitTest(character, scratch, matchDest, min, max, mask);
return;
}
// We have too many matches to handle in a single set, but we may be able to
// recursively group some of our matches together. Worst case, we just do a
// character-by-character match. Greedily matching is potentially suboptimal,
// but I doubt worth spending time doing better.