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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
|
/*
* Copyright (C) 2009 Apple Inc. 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 "RegexJIT.h"
#include "ASCIICType.h"
#include "JSGlobalData.h"
#include "LinkBuffer.h"
#include "MacroAssembler.h"
#include "RegexCompiler.h"
#include "pcre.h" // temporary, remove when fallback is removed.
#if ENABLE(YARR_JIT)
using namespace WTF;
namespace JSC { namespace Yarr {
class RegexGenerator : private MacroAssembler {
friend void jitCompileRegex(JSGlobalData* globalData, RegexCodeBlock& jitObject, const UString& pattern, unsigned& numSubpatterns, const char*& error, bool ignoreCase, bool multiline);
#if CPU(ARM)
static const RegisterID input = ARMRegisters::r0;
static const RegisterID index = ARMRegisters::r1;
static const RegisterID length = ARMRegisters::r2;
static const RegisterID output = ARMRegisters::r4;
static const RegisterID regT0 = ARMRegisters::r5;
static const RegisterID regT1 = ARMRegisters::r6;
static const RegisterID returnRegister = ARMRegisters::r0;
#elif CPU(X86)
static const RegisterID input = X86Registers::eax;
static const RegisterID index = X86Registers::edx;
static const RegisterID length = X86Registers::ecx;
static const RegisterID output = X86Registers::edi;
static const RegisterID regT0 = X86Registers::ebx;
static const RegisterID regT1 = X86Registers::esi;
static const RegisterID returnRegister = X86Registers::eax;
#elif CPU(X86_64)
static const RegisterID input = X86Registers::edi;
static const RegisterID index = X86Registers::esi;
static const RegisterID length = X86Registers::edx;
static const RegisterID output = X86Registers::ecx;
static const RegisterID regT0 = X86Registers::eax;
static const RegisterID regT1 = X86Registers::ebx;
static const RegisterID returnRegister = X86Registers::eax;
#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];
if ((term.type == PatternTerm::TypeCharacterClass)
&& (term.quantityType == QuantifierFixedCount)
&& (nextTerm.type == PatternTerm::TypePatternCharacter)
&& (nextTerm.quantityType == QuantifierFixedCount)) {
PatternTerm termCopy = term;
alternative->m_terms[i] = nextTerm;
alternative->m_terms[i + 1] = termCopy;
}
}
}
void matchCharacterClassRange(RegisterID character, JumpList& failures, JumpList& matchDest, const CharacterRange* ranges, unsigned count, unsigned* matchIndex, const UChar* matches, unsigned matchCount)
{
do {
// pick which range we're going to generate
int which = count >> 1;
char lo = ranges[which].begin;
char hi = ranges[which].end;
// check if there are any ranges or matches below lo. If not, just jl to failure -
// if there is anything else to check, check that first, if it falls through jmp to failure.
if ((*matchIndex < matchCount) && (matches[*matchIndex] < lo)) {
Jump loOrAbove = branch32(GreaterThanOrEqual, character, Imm32((unsigned short)lo));
// generate code for all ranges before this one
if (which)
matchCharacterClassRange(character, failures, matchDest, ranges, which, matchIndex, matches, matchCount);
while ((*matchIndex < matchCount) && (matches[*matchIndex] < lo)) {
matchDest.append(branch32(Equal, character, Imm32((unsigned short)matches[*matchIndex])));
++*matchIndex;
}
failures.append(jump());
loOrAbove.link(this);
} else if (which) {
Jump loOrAbove = branch32(GreaterThanOrEqual, character, Imm32((unsigned short)lo));
matchCharacterClassRange(character, failures, matchDest, ranges, which, matchIndex, matches, matchCount);
failures.append(jump());
loOrAbove.link(this);
} else
failures.append(branch32(LessThan, character, Imm32((unsigned short)lo)));
while ((*matchIndex < matchCount) && (matches[*matchIndex] <= hi))
++*matchIndex;
matchDest.append(branch32(LessThanOrEqual, character, Imm32((unsigned short)hi)));
// fall through to here, the value is above hi.
// shuffle along & loop around if there are any more matches to handle.
unsigned next = which + 1;
ranges += next;
count -= next;
} while (count);
}
void matchCharacterClass(RegisterID character, JumpList& matchDest, const CharacterClass* charClass)
{
Jump unicodeFail;
if (charClass->m_matchesUnicode.size() || charClass->m_rangesUnicode.size()) {
Jump isAscii = branch32(LessThanOrEqual, character, Imm32(0x7f));
if (charClass->m_matchesUnicode.size()) {
for (unsigned i = 0; i < charClass->m_matchesUnicode.size(); ++i) {
UChar ch = charClass->m_matchesUnicode[i];
matchDest.append(branch32(Equal, character, Imm32(ch)));
}
}
if (charClass->m_rangesUnicode.size()) {
for (unsigned i = 0; i < charClass->m_rangesUnicode.size(); ++i) {
UChar lo = charClass->m_rangesUnicode[i].begin;
UChar hi = charClass->m_rangesUnicode[i].end;
Jump below = branch32(LessThan, character, Imm32(lo));
matchDest.append(branch32(LessThanOrEqual, character, Imm32(hi)));
below.link(this);
}
}
unicodeFail = jump();
isAscii.link(this);
}
if (charClass->m_ranges.size()) {
unsigned matchIndex = 0;
JumpList failures;
matchCharacterClassRange(character, failures, matchDest, charClass->m_ranges.begin(), charClass->m_ranges.size(), &matchIndex, charClass->m_matches.begin(), charClass->m_matches.size());
while (matchIndex < charClass->m_matches.size())
matchDest.append(branch32(Equal, character, Imm32((unsigned short)charClass->m_matches[matchIndex++])));
failures.link(this);
} else if (charClass->m_matches.size()) {
// optimization: gather 'a','A' etc back together, can mask & test once.
Vector<char> matchesAZaz;
for (unsigned i = 0; i < charClass->m_matches.size(); ++i) {
char ch = charClass->m_matches[i];
if (m_pattern.m_ignoreCase) {
if (isASCIILower(ch)) {
matchesAZaz.append(ch);
continue;
}
if (isASCIIUpper(ch))
continue;
}
matchDest.append(branch32(Equal, character, Imm32((unsigned short)ch)));
}
if (unsigned countAZaz = matchesAZaz.size()) {
or32(Imm32(32), character);
for (unsigned i = 0; i < countAZaz; ++i)
matchDest.append(branch32(Equal, character, Imm32(matchesAZaz[i])));
}
}
if (charClass->m_matchesUnicode.size() || charClass->m_rangesUnicode.size())
unicodeFail.link(this);
}
// Jumps if input not available; will have (incorrectly) incremented already!
Jump jumpIfNoAvailableInput(unsigned countToCheck)
{
add32(Imm32(countToCheck), index);
return branch32(Above, index, length);
}
Jump jumpIfAvailableInput(unsigned countToCheck)
{
add32(Imm32(countToCheck), index);
return branch32(BelowOrEqual, index, length);
}
Jump checkInput()
{
return branch32(BelowOrEqual, index, length);
}
Jump atEndOfInput()
{
return branch32(Equal, index, length);
}
Jump notAtEndOfInput()
{
return branch32(NotEqual, index, length);
}
Jump jumpIfCharEquals(UChar ch, int inputPosition)
{
return branch16(Equal, BaseIndex(input, index, TimesTwo, inputPosition * sizeof(UChar)), Imm32(ch));
}
Jump jumpIfCharNotEquals(UChar ch, int inputPosition)
{
return branch16(NotEqual, BaseIndex(input, index, TimesTwo, inputPosition * sizeof(UChar)), Imm32(ch));
}
void readCharacter(int inputPosition, RegisterID reg)
{
load16(BaseIndex(input, index, TimesTwo, inputPosition * sizeof(UChar)), reg);
}
void storeToFrame(RegisterID reg, unsigned frameLocation)
{
poke(reg, frameLocation);
}
void storeToFrame(Imm32 imm, unsigned frameLocation)
{
poke(imm, frameLocation);
}
DataLabelPtr storeToFrameWithPatch(unsigned frameLocation)
{
return storePtrWithPatch(ImmPtr(0), Address(stackPointerRegister, frameLocation * sizeof(void*)));
}
void loadFromFrame(unsigned frameLocation, RegisterID reg)
{
peek(reg, frameLocation);
}
void loadFromFrameAndJump(unsigned frameLocation)
{
jump(Address(stackPointerRegister, frameLocation * sizeof(void*)));
}
struct AlternativeBacktrackRecord {
DataLabelPtr dataLabel;
Label backtrackLocation;
AlternativeBacktrackRecord(DataLabelPtr dataLabel, Label backtrackLocation)
: dataLabel(dataLabel)
, backtrackLocation(backtrackLocation)
{
}
};
struct TermGenerationState {
TermGenerationState(PatternDisjunction* disjunction, unsigned checkedTotal)
: disjunction(disjunction)
, checkedTotal(checkedTotal)
{
}
void resetAlternative()
{
isBackTrackGenerated = false;
alt = 0;
}
bool alternativeValid()
{
return alt < disjunction->m_alternatives.size();
}
void nextAlternative()
{
++alt;
}
PatternAlternative* alternative()
{
return disjunction->m_alternatives[alt];
}
void resetTerm()
{
ASSERT(alternativeValid());
t = 0;
}
bool termValid()
{
ASSERT(alternativeValid());
return t < alternative()->m_terms.size();
}
void nextTerm()
{
ASSERT(alternativeValid());
++t;
}
PatternTerm& term()
{
ASSERT(alternativeValid());
return alternative()->m_terms[t];
}
PatternTerm& lookaheadTerm()
{
ASSERT(alternativeValid());
ASSERT((t + 1) < alternative()->m_terms.size());
return alternative()->m_terms[t + 1];
}
bool isSinglePatternCharacterLookaheadTerm()
{
ASSERT(alternativeValid());
return ((t + 1) < alternative()->m_terms.size())
&& (lookaheadTerm().type == PatternTerm::TypePatternCharacter)
&& (lookaheadTerm().quantityType == QuantifierFixedCount)
&& (lookaheadTerm().quantityCount == 1);
}
int inputOffset()
{
return term().inputPosition - checkedTotal;
}
void jumpToBacktrack(Jump jump, MacroAssembler* masm)
{
if (isBackTrackGenerated)
jump.linkTo(backtrackLabel, masm);
else
backTrackJumps.append(jump);
}
void jumpToBacktrack(JumpList& jumps, MacroAssembler* masm)
{
if (isBackTrackGenerated)
jumps.linkTo(backtrackLabel, masm);
else
backTrackJumps.append(jumps);
}
bool plantJumpToBacktrackIfExists(MacroAssembler* masm)
{
if (isBackTrackGenerated) {
masm->jump(backtrackLabel);
return true;
}
return false;
}
void addBacktrackJump(Jump jump)
{
backTrackJumps.append(jump);
}
void setBacktrackGenerated(Label label)
{
isBackTrackGenerated = true;
backtrackLabel = label;
}
void linkAlternativeBacktracks(MacroAssembler* masm)
{
isBackTrackGenerated = false;
backTrackJumps.link(masm);
}
void linkAlternativeBacktracksTo(Label label, MacroAssembler* masm)
{
isBackTrackGenerated = false;
backTrackJumps.linkTo(label, masm);
}
void propagateBacktrackingFrom(TermGenerationState& nestedParenthesesState, MacroAssembler* masm)
{
jumpToBacktrack(nestedParenthesesState.backTrackJumps, masm);
if (nestedParenthesesState.isBackTrackGenerated)
setBacktrackGenerated(nestedParenthesesState.backtrackLabel);
}
PatternDisjunction* disjunction;
int checkedTotal;
private:
unsigned alt;
unsigned t;
JumpList backTrackJumps;
Label backtrackLabel;
bool isBackTrackGenerated;
};
void generateAssertionBOL(TermGenerationState& state)
{
PatternTerm& term = state.term();
if (m_pattern.m_multiline) {
const RegisterID character = regT0;
JumpList matchDest;
if (!term.inputPosition)
matchDest.append(branch32(Equal, index, Imm32(state.checkedTotal)));
readCharacter(state.inputOffset() - 1, character);
matchCharacterClass(character, matchDest, m_pattern.newlineCharacterClass());
state.jumpToBacktrack(jump(), this);
matchDest.link(this);
} else {
// Erk, really should poison out these alternatives early. :-/
if (term.inputPosition)
state.jumpToBacktrack(jump(), this);
else
state.jumpToBacktrack(branch32(NotEqual, index, Imm32(state.checkedTotal)), this);
}
}
void generateAssertionEOL(TermGenerationState& state)
{
PatternTerm& term = state.term();
if (m_pattern.m_multiline) {
const RegisterID character = regT0;
JumpList matchDest;
if (term.inputPosition == state.checkedTotal)
matchDest.append(atEndOfInput());
readCharacter(state.inputOffset(), character);
matchCharacterClass(character, matchDest, m_pattern.newlineCharacterClass());
state.jumpToBacktrack(jump(), this);
matchDest.link(this);
} else {
if (term.inputPosition == state.checkedTotal)
state.jumpToBacktrack(notAtEndOfInput(), this);
// Erk, really should poison out these alternatives early. :-/
else
state.jumpToBacktrack(jump(), this);
}
}
// Also falls though on nextIsNotWordChar.
void matchAssertionWordchar(TermGenerationState& state, JumpList& nextIsWordChar, JumpList& nextIsNotWordChar)
{
const RegisterID character = regT0;
PatternTerm& term = state.term();
if (term.inputPosition == state.checkedTotal)
nextIsNotWordChar.append(atEndOfInput());
readCharacter(state.inputOffset(), character);
matchCharacterClass(character, nextIsWordChar, m_pattern.wordcharCharacterClass());
}
void generateAssertionWordBoundary(TermGenerationState& state)
{
const RegisterID character = regT0;
PatternTerm& term = state.term();
Jump atBegin;
JumpList matchDest;
if (!term.inputPosition)
atBegin = branch32(Equal, index, Imm32(state.checkedTotal));
readCharacter(state.inputOffset() - 1, character);
matchCharacterClass(character, matchDest, m_pattern.wordcharCharacterClass());
if (!term.inputPosition)
atBegin.link(this);
// We fall through to here if the last character was not a wordchar.
JumpList nonWordCharThenWordChar;
JumpList nonWordCharThenNonWordChar;
if (term.invertOrCapture) {
matchAssertionWordchar(state, nonWordCharThenNonWordChar, nonWordCharThenWordChar);
nonWordCharThenWordChar.append(jump());
} else {
matchAssertionWordchar(state, nonWordCharThenWordChar, nonWordCharThenNonWordChar);
nonWordCharThenNonWordChar.append(jump());
}
state.jumpToBacktrack(nonWordCharThenNonWordChar, this);
// We jump here if the last character was a wordchar.
matchDest.link(this);
JumpList wordCharThenWordChar;
JumpList wordCharThenNonWordChar;
if (term.invertOrCapture) {
matchAssertionWordchar(state, wordCharThenNonWordChar, wordCharThenWordChar);
wordCharThenWordChar.append(jump());
} else {
matchAssertionWordchar(state, wordCharThenWordChar, wordCharThenNonWordChar);
// This can fall-though!
}
state.jumpToBacktrack(wordCharThenWordChar, this);
nonWordCharThenWordChar.link(this);
wordCharThenNonWordChar.link(this);
}
void generatePatternCharacterSingle(TermGenerationState& state)
{
const RegisterID character = regT0;
UChar ch = state.term().patternCharacter;
if (m_pattern.m_ignoreCase && isASCIIAlpha(ch)) {
readCharacter(state.inputOffset(), character);
or32(Imm32(32), character);
state.jumpToBacktrack(branch32(NotEqual, character, Imm32(Unicode::toLower(ch))), this);
} else {
ASSERT(!m_pattern.m_ignoreCase || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
state.jumpToBacktrack(jumpIfCharNotEquals(ch, state.inputOffset()), this);
}
}
void generatePatternCharacterPair(TermGenerationState& state)
{
const RegisterID character = regT0;
UChar ch1 = state.term().patternCharacter;
UChar ch2 = state.lookaheadTerm().patternCharacter;
int mask = 0;
int chPair = ch1 | (ch2 << 16);
if (m_pattern.m_ignoreCase) {
if (isASCIIAlpha(ch1))
mask |= 32;
if (isASCIIAlpha(ch2))
mask |= 32 << 16;
}
if (mask) {
load32WithUnalignedHalfWords(BaseIndex(input, index, TimesTwo, state.inputOffset() * sizeof(UChar)), character);
or32(Imm32(mask), character);
state.jumpToBacktrack(branch32(NotEqual, character, Imm32(chPair | mask)), this);
} else
state.jumpToBacktrack(branch32WithUnalignedHalfWords(NotEqual, BaseIndex(input, index, TimesTwo, state.inputOffset() * sizeof(UChar)), Imm32(chPair)), this);
}
void generatePatternCharacterFixed(TermGenerationState& state)
{
const RegisterID character = regT0;
const RegisterID countRegister = regT1;
PatternTerm& term = state.term();
UChar ch = term.patternCharacter;
move(index, countRegister);
sub32(Imm32(term.quantityCount), countRegister);
Label loop(this);
if (m_pattern.m_ignoreCase && isASCIIAlpha(ch)) {
load16(BaseIndex(input, countRegister, TimesTwo, (state.inputOffset() + term.quantityCount) * sizeof(UChar)), character);
or32(Imm32(32), character);
state.jumpToBacktrack(branch32(NotEqual, character, Imm32(Unicode::toLower(ch))), this);
} else {
ASSERT(!m_pattern.m_ignoreCase || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
state.jumpToBacktrack(branch16(NotEqual, BaseIndex(input, countRegister, TimesTwo, (state.inputOffset() + term.quantityCount) * sizeof(UChar)), Imm32(ch)), this);
}
add32(Imm32(1), countRegister);
branch32(NotEqual, countRegister, index).linkTo(loop, this);
}
void generatePatternCharacterGreedy(TermGenerationState& state)
{
const RegisterID character = regT0;
const RegisterID countRegister = regT1;
PatternTerm& term = state.term();
UChar ch = term.patternCharacter;
move(Imm32(0), countRegister);
JumpList failures;
Label loop(this);
failures.append(atEndOfInput());
if (m_pattern.m_ignoreCase && isASCIIAlpha(ch)) {
readCharacter(state.inputOffset(), character);
or32(Imm32(32), character);
failures.append(branch32(NotEqual, character, Imm32(Unicode::toLower(ch))));
} else {
ASSERT(!m_pattern.m_ignoreCase || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
failures.append(jumpIfCharNotEquals(ch, state.inputOffset()));
}
add32(Imm32(1), countRegister);
add32(Imm32(1), index);
branch32(NotEqual, countRegister, Imm32(term.quantityCount)).linkTo(loop, this);
failures.append(jump());
Label backtrackBegin(this);
loadFromFrame(term.frameLocation, countRegister);
state.jumpToBacktrack(branchTest32(Zero, countRegister), this);
sub32(Imm32(1), countRegister);
sub32(Imm32(1), index);
failures.link(this);
storeToFrame(countRegister, term.frameLocation);
state.setBacktrackGenerated(backtrackBegin);
}
void generatePatternCharacterNonGreedy(TermGenerationState& state)
{
const RegisterID character = regT0;
const RegisterID countRegister = regT1;
PatternTerm& term = state.term();
UChar ch = term.patternCharacter;
move(Imm32(0), countRegister);
Jump firstTimeDoNothing = jump();
Label hardFail(this);
sub32(countRegister, index);
state.jumpToBacktrack(jump(), this);
Label backtrackBegin(this);
loadFromFrame(term.frameLocation, countRegister);
atEndOfInput().linkTo(hardFail, this);
branch32(Equal, countRegister, Imm32(term.quantityCount), hardFail);
if (m_pattern.m_ignoreCase && isASCIIAlpha(ch)) {
readCharacter(state.inputOffset(), character);
or32(Imm32(32), character);
branch32(NotEqual, character, Imm32(Unicode::toLower(ch))).linkTo(hardFail, this);
} else {
ASSERT(!m_pattern.m_ignoreCase || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
jumpIfCharNotEquals(ch, state.inputOffset()).linkTo(hardFail, this);
}
add32(Imm32(1), countRegister);
add32(Imm32(1), index);
firstTimeDoNothing.link(this);
storeToFrame(countRegister, term.frameLocation);
state.setBacktrackGenerated(backtrackBegin);
}
void generateCharacterClassSingle(TermGenerationState& state)
{
const RegisterID character = regT0;
PatternTerm& term = state.term();
JumpList matchDest;
readCharacter(state.inputOffset(), character);
matchCharacterClass(character, matchDest, term.characterClass);
if (term.invertOrCapture)
state.jumpToBacktrack(matchDest, this);
else {
state.jumpToBacktrack(jump(), this);
matchDest.link(this);
}
}
void generateCharacterClassFixed(TermGenerationState& state)
{
const RegisterID character = regT0;
const RegisterID countRegister = regT1;
PatternTerm& term = state.term();
move(index, countRegister);
sub32(Imm32(term.quantityCount), countRegister);
Label loop(this);
JumpList matchDest;
load16(BaseIndex(input, countRegister, TimesTwo, (state.inputOffset() + term.quantityCount) * sizeof(UChar)), character);
matchCharacterClass(character, matchDest, term.characterClass);
if (term.invertOrCapture)
state.jumpToBacktrack(matchDest, this);
else {
state.jumpToBacktrack(jump(), this);
matchDest.link(this);
}
add32(Imm32(1), countRegister);
branch32(NotEqual, countRegister, index).linkTo(loop, this);
}
void generateCharacterClassGreedy(TermGenerationState& state)
{
const RegisterID character = regT0;
const RegisterID countRegister = regT1;
PatternTerm& term = state.term();
move(Imm32(0), countRegister);
JumpList failures;
Label loop(this);
failures.append(atEndOfInput());
if (term.invertOrCapture) {
readCharacter(state.inputOffset(), character);
matchCharacterClass(character, failures, term.characterClass);
} else {
JumpList matchDest;
readCharacter(state.inputOffset(), character);
matchCharacterClass(character, matchDest, term.characterClass);
failures.append(jump());
matchDest.link(this);
}
add32(Imm32(1), countRegister);
add32(Imm32(1), index);
branch32(NotEqual, countRegister, Imm32(term.quantityCount)).linkTo(loop, this);
failures.append(jump());
Label backtrackBegin(this);
loadFromFrame(term.frameLocation, countRegister);
state.jumpToBacktrack(branchTest32(Zero, countRegister), this);
sub32(Imm32(1), countRegister);
sub32(Imm32(1), index);
failures.link(this);
storeToFrame(countRegister, term.frameLocation);
state.setBacktrackGenerated(backtrackBegin);
}
void generateCharacterClassNonGreedy(TermGenerationState& state)
{
const RegisterID character = regT0;
const RegisterID countRegister = regT1;
PatternTerm& term = state.term();
move(Imm32(0), countRegister);
Jump firstTimeDoNothing = jump();
Label hardFail(this);
sub32(countRegister, index);
state.jumpToBacktrack(jump(), this);
Label backtrackBegin(this);
loadFromFrame(term.frameLocation, countRegister);
atEndOfInput().linkTo(hardFail, this);
branch32(Equal, countRegister, Imm32(term.quantityCount), hardFail);
JumpList matchDest;
readCharacter(state.inputOffset(), character);
matchCharacterClass(character, matchDest, term.characterClass);
if (term.invertOrCapture)
matchDest.linkTo(hardFail, this);
else {
jump(hardFail);
matchDest.link(this);
}
add32(Imm32(1), countRegister);
add32(Imm32(1), index);
firstTimeDoNothing.link(this);
storeToFrame(countRegister, term.frameLocation);
state.setBacktrackGenerated(backtrackBegin);
}
void generateParenthesesDisjunction(PatternTerm& parenthesesTerm, TermGenerationState& state, unsigned alternativeFrameLocation)
{
ASSERT((parenthesesTerm.type == PatternTerm::TypeParenthesesSubpattern) || (parenthesesTerm.type == PatternTerm::TypeParentheticalAssertion));
ASSERT(parenthesesTerm.quantityCount == 1);
PatternDisjunction* disjunction = parenthesesTerm.parentheses.disjunction;
unsigned preCheckedCount = ((parenthesesTerm.quantityType == QuantifierFixedCount) && (parenthesesTerm.type != PatternTerm::TypeParentheticalAssertion)) ? disjunction->m_minimumSize : 0;
if (disjunction->m_alternatives.size() == 1) {
state.resetAlternative();
ASSERT(state.alternativeValid());
PatternAlternative* alternative = state.alternative();
optimizeAlternative(alternative);
int countToCheck = alternative->m_minimumSize - preCheckedCount;
if (countToCheck) {
ASSERT((parenthesesTerm.type == PatternTerm::TypeParentheticalAssertion) || (parenthesesTerm.quantityType != QuantifierFixedCount));
// FIXME: This is quite horrible. The call to 'plantJumpToBacktrackIfExists'
// will be forced to always trampoline into here, just to decrement the index.
// Ick.
Jump skip = jump();
Label backtrackBegin(this);
sub32(Imm32(countToCheck), index);
state.addBacktrackJump(jump());
skip.link(this);
state.setBacktrackGenerated(backtrackBegin);
state.jumpToBacktrack(jumpIfNoAvailableInput(countToCheck), this);
state.checkedTotal += countToCheck;
}
for (state.resetTerm(); state.termValid(); state.nextTerm())
generateTerm(state);
state.checkedTotal -= countToCheck;
} else {
JumpList successes;
for (state.resetAlternative(); state.alternativeValid(); state.nextAlternative()) {
PatternAlternative* alternative = state.alternative();
optimizeAlternative(alternative);
ASSERT(alternative->m_minimumSize >= preCheckedCount);
int countToCheck = alternative->m_minimumSize - preCheckedCount;
if (countToCheck) {
state.addBacktrackJump(jumpIfNoAvailableInput(countToCheck));
state.checkedTotal += countToCheck;
}
for (state.resetTerm(); state.termValid(); state.nextTerm())
generateTerm(state);
// Matched an alternative.
DataLabelPtr dataLabel = storeToFrameWithPatch(alternativeFrameLocation);
successes.append(jump());
// Alternative did not match.
Label backtrackLocation(this);
// Can we backtrack the alternative? - if so, do so. If not, just fall through to the next one.
state.plantJumpToBacktrackIfExists(this);
state.linkAlternativeBacktracks(this);
if (countToCheck) {
sub32(Imm32(countToCheck), index);
state.checkedTotal -= countToCheck;
}
m_backtrackRecords.append(AlternativeBacktrackRecord(dataLabel, backtrackLocation));
}
// We fall through to here when the last alternative fails.
// Add a backtrack out of here for the parenthese handling code to link up.
state.addBacktrackJump(jump());
// Generate a trampoline for the parens code to backtrack to, to retry the
// next alternative.
state.setBacktrackGenerated(label());
loadFromFrameAndJump(alternativeFrameLocation);
// FIXME: both of the above hooks are a little inefficient, in that you
// may end up trampolining here, just to trampoline back out to the
// parentheses code, or vice versa. We can probably eliminate a jump
// by restructuring, but coding this way for now for simplicity during
// development.
successes.link(this);
}
}
void generateParenthesesSingle(TermGenerationState& state)
{
const RegisterID indexTemporary = regT0;
PatternTerm& term = state.term();
PatternDisjunction* disjunction = term.parentheses.disjunction;
ASSERT(term.quantityCount == 1);
unsigned preCheckedCount = ((term.quantityCount == 1) && (term.quantityType == QuantifierFixedCount)) ? disjunction->m_minimumSize : 0;
unsigned parenthesesFrameLocation = term.frameLocation;
unsigned alternativeFrameLocation = parenthesesFrameLocation;
if (term.quantityType != QuantifierFixedCount)
alternativeFrameLocation += RegexStackSpaceForBackTrackInfoParenthesesOnce;
// optimized case - no capture & no quantifier can be handled in a light-weight manner.
if (!term.invertOrCapture && (term.quantityType == QuantifierFixedCount)) {
TermGenerationState parenthesesState(disjunction, state.checkedTotal);
generateParenthesesDisjunction(state.term(), parenthesesState, alternativeFrameLocation);
// this expects that any backtracks back out of the parentheses will be in the
// parenthesesState's backTrackJumps vector, and that if they need backtracking
// they will have set an entry point on the parenthesesState's backtrackLabel.
state.propagateBacktrackingFrom(parenthesesState, this);
} else {
Jump nonGreedySkipParentheses;
Label nonGreedyTryParentheses;
if (term.quantityType == QuantifierGreedy)
storeToFrame(Imm32(1), parenthesesFrameLocation);
else if (term.quantityType == QuantifierNonGreedy) {
storeToFrame(Imm32(0), parenthesesFrameLocation);
nonGreedySkipParentheses = jump();
nonGreedyTryParentheses = label();
storeToFrame(Imm32(1), parenthesesFrameLocation);
}
// store the match start index
if (term.invertOrCapture) {
int inputOffset = state.inputOffset() - preCheckedCount;
if (inputOffset) {
move(index, indexTemporary);
add32(Imm32(inputOffset), indexTemporary);
store32(indexTemporary, Address(output, (term.parentheses.subpatternId << 1) * sizeof(int)));
} else
store32(index, Address(output, (term.parentheses.subpatternId << 1) * sizeof(int)));
}
// generate the body of the parentheses
TermGenerationState parenthesesState(disjunction, state.checkedTotal);
generateParenthesesDisjunction(state.term(), parenthesesState, alternativeFrameLocation);
// store the match end index
if (term.invertOrCapture) {
int inputOffset = state.inputOffset();
if (inputOffset) {
move(index, indexTemporary);
add32(Imm32(state.inputOffset()), indexTemporary);
store32(indexTemporary, Address(output, ((term.parentheses.subpatternId << 1) + 1) * sizeof(int)));
} else
store32(index, Address(output, ((term.parentheses.subpatternId << 1) + 1) * sizeof(int)));
}
Jump success = jump();
// A failure AFTER the parens jumps here
Label backtrackFromAfterParens(this);
if (term.quantityType == QuantifierGreedy) {
// If this is zero we have now tested with both with and without the parens.
loadFromFrame(parenthesesFrameLocation, indexTemporary);
state.jumpToBacktrack(branchTest32(Zero, indexTemporary), this);
} else if (term.quantityType == QuantifierNonGreedy) {
// If this is zero we have now tested with both with and without the parens.
loadFromFrame(parenthesesFrameLocation, indexTemporary);
branchTest32(Zero, indexTemporary).linkTo(nonGreedyTryParentheses, this);
}
parenthesesState.plantJumpToBacktrackIfExists(this);
// A failure WITHIN the parens jumps here
parenthesesState.linkAlternativeBacktracks(this);
if (term.invertOrCapture) {
store32(Imm32(-1), Address(output, (term.parentheses.subpatternId << 1) * sizeof(int)));
store32(Imm32(-1), Address(output, ((term.parentheses.subpatternId << 1) + 1) * sizeof(int)));
}
if (term.quantityType == QuantifierGreedy)
storeToFrame(Imm32(0), parenthesesFrameLocation);
else
state.jumpToBacktrack(jump(), this);
state.setBacktrackGenerated(backtrackFromAfterParens);
if (term.quantityType == QuantifierNonGreedy)
nonGreedySkipParentheses.link(this);
success.link(this);
}
}
void generateParentheticalAssertion(TermGenerationState& state)
{
PatternTerm& term = state.term();
PatternDisjunction* disjunction = term.parentheses.disjunction;
ASSERT(term.quantityCount == 1);
ASSERT(term.quantityType == QuantifierFixedCount);
unsigned parenthesesFrameLocation = term.frameLocation;
unsigned alternativeFrameLocation = parenthesesFrameLocation + RegexStackSpaceForBackTrackInfoParentheticalAssertion;
int countCheckedAfterAssertion = state.checkedTotal - term.inputPosition;
if (term.invertOrCapture) {
// Inverted case
storeToFrame(index, parenthesesFrameLocation);
state.checkedTotal -= countCheckedAfterAssertion;
if (countCheckedAfterAssertion)
sub32(Imm32(countCheckedAfterAssertion), index);
TermGenerationState parenthesesState(disjunction, state.checkedTotal);
generateParenthesesDisjunction(state.term(), parenthesesState, alternativeFrameLocation);
// Success! - which means - Fail!
loadFromFrame(parenthesesFrameLocation, index);
state.jumpToBacktrack(jump(), this);
// And fail means success.
parenthesesState.linkAlternativeBacktracks(this);
loadFromFrame(parenthesesFrameLocation, index);
state.checkedTotal += countCheckedAfterAssertion;
} else {
// Normal case
storeToFrame(index, parenthesesFrameLocation);
state.checkedTotal -= countCheckedAfterAssertion;
if (countCheckedAfterAssertion)
sub32(Imm32(countCheckedAfterAssertion), index);
TermGenerationState parenthesesState(disjunction, state.checkedTotal);
generateParenthesesDisjunction(state.term(), parenthesesState, alternativeFrameLocation);
// Success! - which means - Success!
loadFromFrame(parenthesesFrameLocation, index);
Jump success = jump();
parenthesesState.linkAlternativeBacktracks(this);
loadFromFrame(parenthesesFrameLocation, index);
state.jumpToBacktrack(jump(), this);
success.link(this);
state.checkedTotal += countCheckedAfterAssertion;
}
}
void generateTerm(TermGenerationState& state)
{
PatternTerm& term = state.term();
switch (term.type) {
case PatternTerm::TypeAssertionBOL:
generateAssertionBOL(state);
break;
case PatternTerm::TypeAssertionEOL:
generateAssertionEOL(state);
break;
case PatternTerm::TypeAssertionWordBoundary:
generateAssertionWordBoundary(state);
break;
case PatternTerm::TypePatternCharacter:
switch (term.quantityType) {
case QuantifierFixedCount:
if (term.quantityCount == 1) {
if (state.isSinglePatternCharacterLookaheadTerm() && (state.lookaheadTerm().inputPosition == (term.inputPosition + 1))) {
generatePatternCharacterPair(state);
state.nextTerm();
} else
generatePatternCharacterSingle(state);
} else
generatePatternCharacterFixed(state);
break;
case QuantifierGreedy:
generatePatternCharacterGreedy(state);
break;
case QuantifierNonGreedy:
generatePatternCharacterNonGreedy(state);
break;
}
break;
case PatternTerm::TypeCharacterClass:
switch (term.quantityType) {
case QuantifierFixedCount:
if (term.quantityCount == 1)
generateCharacterClassSingle(state);
else
generateCharacterClassFixed(state);
break;
case QuantifierGreedy:
generateCharacterClassGreedy(state);
break;
case QuantifierNonGreedy:
generateCharacterClassNonGreedy(state);
break;
}
break;
case PatternTerm::TypeBackReference:
m_generationFailed = true;
break;
case PatternTerm::TypeForwardReference:
break;
case PatternTerm::TypeParenthesesSubpattern:
if ((term.quantityCount == 1) && !term.parentheses.isCopy)
generateParenthesesSingle(state);
else
m_generationFailed = true;
break;
case PatternTerm::TypeParentheticalAssertion:
generateParentheticalAssertion(state);
break;
}
}
void generateDisjunction(PatternDisjunction* disjunction)
{
TermGenerationState state(disjunction, 0);
state.resetAlternative();
// Plant a check to see if there is sufficient input available to run the first alternative.
// Jumping back to the label 'firstAlternative' will get to this check, jumping to
// 'firstAlternativeInputChecked' will jump directly to matching the alternative having
// skipped this check.
Label firstAlternative(this);
// check availability for the next alternative
int countCheckedForCurrentAlternative = 0;
int countToCheckForFirstAlternative = 0;
bool hasShorterAlternatives = false;
JumpList notEnoughInputForPreviousAlternative;
if (state.alternativeValid()) {
PatternAlternative* alternative = state.alternative();
countToCheckForFirstAlternative = alternative->m_minimumSize;
state.checkedTotal += countToCheckForFirstAlternative;
if (countToCheckForFirstAlternative)
notEnoughInputForPreviousAlternative.append(jumpIfNoAvailableInput(countToCheckForFirstAlternative));
countCheckedForCurrentAlternative = countToCheckForFirstAlternative;
}
Label firstAlternativeInputChecked(this);
while (state.alternativeValid()) {
// Track whether any alternatives are shorter than the first one.
hasShorterAlternatives = hasShorterAlternatives || (countCheckedForCurrentAlternative < countToCheckForFirstAlternative);
PatternAlternative* alternative = state.alternative();
optimizeAlternative(alternative);
for (state.resetTerm(); state.termValid(); state.nextTerm())
generateTerm(state);
// If we get here, the alternative matched.
if (m_pattern.m_body->m_callFrameSize)
addPtr(Imm32(m_pattern.m_body->m_callFrameSize * sizeof(void*)), stackPointerRegister);
ASSERT(index != returnRegister);
if (m_pattern.m_body->m_hasFixedSize) {
move(index, returnRegister);
if (alternative->m_minimumSize)
sub32(Imm32(alternative->m_minimumSize), returnRegister);
} else
pop(returnRegister);
store32(index, Address(output, 4));
store32(returnRegister, output);
generateReturn();
state.nextAlternative();
// if there are any more alternatives, plant the check for input before looping.
if (state.alternativeValid()) {
PatternAlternative* nextAlternative = state.alternative();
int countToCheckForNextAlternative = nextAlternative->m_minimumSize;
if (countCheckedForCurrentAlternative > countToCheckForNextAlternative) { // CASE 1: current alternative was longer than the next one.
// If we get here, there the last input checked failed.
notEnoughInputForPreviousAlternative.link(this);
// Check if sufficent input available to run the next alternative
notEnoughInputForPreviousAlternative.append(jumpIfNoAvailableInput(countToCheckForNextAlternative - countCheckedForCurrentAlternative));
// We are now in the correct state to enter the next alternative; this add is only required
// to mirror and revert operation of the sub32, just below.
add32(Imm32(countCheckedForCurrentAlternative - countToCheckForNextAlternative), index);
// If we get here, there the last input checked passed.
state.linkAlternativeBacktracks(this);
// No need to check if we can run the next alternative, since it is shorter -
// just update index.
sub32(Imm32(countCheckedForCurrentAlternative - countToCheckForNextAlternative), index);
} else if (countCheckedForCurrentAlternative < countToCheckForNextAlternative) { // CASE 2: next alternative is longer than the current one.
// If we get here, there the last input checked failed.
// If there is insufficient input to run the current alternative, and the next alternative is longer,
// then there is definitely not enough input to run it - don't even check. Just adjust index, as if
// we had checked.
notEnoughInputForPreviousAlternative.link(this);
add32(Imm32(countToCheckForNextAlternative - countCheckedForCurrentAlternative), index);
notEnoughInputForPreviousAlternative.append(jump());
// The next alternative is longer than the current one; check the difference.
state.linkAlternativeBacktracks(this);
notEnoughInputForPreviousAlternative.append(jumpIfNoAvailableInput(countToCheckForNextAlternative - countCheckedForCurrentAlternative));
} else { // CASE 3: Both alternatives are the same length.
ASSERT(countCheckedForCurrentAlternative == countToCheckForNextAlternative);
// If the next alterative is the same length as this one, then no need to check the input -
// if there was sufficent input to run the current alternative then there is sufficient
// input to run the next one; if not, there isn't.
state.linkAlternativeBacktracks(this);
}
state.checkedTotal -= countCheckedForCurrentAlternative;
countCheckedForCurrentAlternative = countToCheckForNextAlternative;
state.checkedTotal += countCheckedForCurrentAlternative;
}
}
// If we get here, all Alternatives failed...
state.checkedTotal -= countCheckedForCurrentAlternative;
// How much more input need there be to be able to retry from the first alternative?
// examples:
// /yarr_jit/ or /wrec|pcre/
// In these examples we need check for one more input before looping.
// /yarr_jit|pcre/
// In this case we need check for 5 more input to loop (+4 to allow for the first alterative
// being four longer than the last alternative checked, and another +1 to effectively move
// the start position along by one).
// /yarr|rules/ or /wrec|notsomuch/
// In these examples, provided that there was sufficient input to have just been matching for
// the second alternative we can loop without checking for available input (since the second
// alternative is longer than the first). In the latter example we need to decrement index
// (by 4) so the start position is only progressed by 1 from the last iteration.
int incrementForNextIter = (countToCheckForFirstAlternative - countCheckedForCurrentAlternative) + 1;
// First, deal with the cases where there was sufficient input to try the last alternative.
if (incrementForNextIter > 0) // We need to check for more input anyway, fall through to the checking below.
state.linkAlternativeBacktracks(this);
else if (m_pattern.m_body->m_hasFixedSize && !incrementForNextIter) // No need to update anything, link these backtracks straight to the to pof the loop!
state.linkAlternativeBacktracksTo(firstAlternativeInputChecked, this);
else { // no need to check the input, but we do have some bookkeeping to do first.
state.linkAlternativeBacktracks(this);
// Where necessary update our preserved start position.
if (!m_pattern.m_body->m_hasFixedSize) {
move(index, regT0);
sub32(Imm32(countCheckedForCurrentAlternative - 1), regT0);
poke(regT0, m_pattern.m_body->m_callFrameSize);
}
// Update index if necessary, and loop (without checking).
if (incrementForNextIter)
add32(Imm32(incrementForNextIter), index);
jump().linkTo(firstAlternativeInputChecked, this);
}
notEnoughInputForPreviousAlternative.link(this);
// Update our idea of the start position, if we're tracking this.
if (!m_pattern.m_body->m_hasFixedSize) {
if (countCheckedForCurrentAlternative - 1) {
move(index, regT0);
sub32(Imm32(countCheckedForCurrentAlternative - 1), regT0);
poke(regT0, m_pattern.m_body->m_callFrameSize);
} else
poke(index, m_pattern.m_body->m_callFrameSize);
}
// Check if there is sufficent input to run the first alternative again.
jumpIfAvailableInput(incrementForNextIter).linkTo(firstAlternativeInputChecked, this);
// No - insufficent input to run the first alteranative, are there any other alternatives we
// might need to check? If so, the last check will have left the index incremented by
// (countToCheckForFirstAlternative + 1), so we need test whether countToCheckForFirstAlternative
// LESS input is available, to have the effect of just progressing the start position by 1
// from the last iteration. If this check passes we can just jump up to the check associated
// with the first alternative in the loop. This is a bit sad, since we'll end up trying the
// first alternative again, and this check will fail (otherwise the check planted just above
// here would have passed). This is a bit sad, however it saves trying to do something more
// complex here in compilation, and in the common case we should end up coallescing the checks.
//
// FIXME: a nice improvement here may be to stop trying to match sooner, based on the least
// of the minimum-alternative-lengths. E.g. if I have two alternatives of length 200 and 150,
// and a string of length 100, we'll end up looping index from 0 to 100, checking whether there
// is sufficient input to run either alternative (constantly failing). If there had been only
// one alternative, or if the shorter alternative had come first, we would have terminated
// immediately. :-/
if (hasShorterAlternatives)
jumpIfAvailableInput(-countToCheckForFirstAlternative).linkTo(firstAlternative, this);
// index will now be a bit garbled (depending on whether 'hasShorterAlternatives' is true,
// it has either been incremented by 1 or by (countToCheckForFirstAlternative + 1) ...
// but since we're about to return a failure this doesn't really matter!)
unsigned frameSize = m_pattern.m_body->m_callFrameSize;
if (!m_pattern.m_body->m_hasFixedSize)
++frameSize;
if (frameSize)
addPtr(Imm32(frameSize * sizeof(void*)), stackPointerRegister);
move(Imm32(-1), returnRegister);
generateReturn();
}
void generateEnter()
{
#if CPU(X86_64)
push(X86Registers::ebp);
move(stackPointerRegister, X86Registers::ebp);
push(X86Registers::ebx);
#elif CPU(X86)
push(X86Registers::ebp);
move(stackPointerRegister, X86Registers::ebp);
// TODO: do we need spill registers to fill the output pointer if there are no sub captures?
push(X86Registers::ebx);
push(X86Registers::edi);
push(X86Registers::esi);
// load output into edi (2 = saved ebp + return address).
#if COMPILER(MSVC)
loadPtr(Address(X86Registers::ebp, 2 * sizeof(void*)), input);
loadPtr(Address(X86Registers::ebp, 3 * sizeof(void*)), index);
loadPtr(Address(X86Registers::ebp, 4 * sizeof(void*)), length);
loadPtr(Address(X86Registers::ebp, 5 * sizeof(void*)), output);
#else
loadPtr(Address(X86Registers::ebp, 2 * sizeof(void*)), output);
#endif
#elif CPU(ARM)
push(ARMRegisters::r4);
push(ARMRegisters::r5);
push(ARMRegisters::r6);
move(ARMRegisters::r3, output);
#endif
}
void generateReturn()
{
#if CPU(X86_64)
pop(X86Registers::ebx);
pop(X86Registers::ebp);
#elif CPU(X86)
pop(X86Registers::esi);
pop(X86Registers::edi);
pop(X86Registers::ebx);
pop(X86Registers::ebp);
#elif CPU(ARM)
pop(ARMRegisters::r6);
pop(ARMRegisters::r5);
pop(ARMRegisters::r4);
#endif
ret();
}
public:
RegexGenerator(RegexPattern& pattern)
: m_pattern(pattern)
, m_generationFailed(false)
{
}
void generate()
{
generateEnter();
// TODO: do I really want this on the stack?
if (!m_pattern.m_body->m_hasFixedSize)
push(index);
if (m_pattern.m_body->m_callFrameSize)
subPtr(Imm32(m_pattern.m_body->m_callFrameSize * sizeof(void*)), stackPointerRegister);
generateDisjunction(m_pattern.m_body);
}
void compile(JSGlobalData* globalData, RegexCodeBlock& jitObject)
{
generate();
LinkBuffer patchBuffer(this, globalData->executableAllocator.poolForSize(size()));
for (unsigned i = 0; i < m_backtrackRecords.size(); ++i)
patchBuffer.patch(m_backtrackRecords[i].dataLabel, patchBuffer.locationOf(m_backtrackRecords[i].backtrackLocation));
jitObject.set(patchBuffer.finalizeCode());
}
bool generationFailed()
{
return m_generationFailed;
}
private:
RegexPattern& m_pattern;
Vector<AlternativeBacktrackRecord> m_backtrackRecords;
bool m_generationFailed;
};
void jitCompileRegex(JSGlobalData* globalData, RegexCodeBlock& jitObject, const UString& patternString, unsigned& numSubpatterns, const char*& error, bool ignoreCase, bool multiline)
{
RegexPattern pattern(ignoreCase, multiline);
if ((error = compileRegex(patternString, pattern)))
return;
numSubpatterns = pattern.m_numSubpatterns;
RegexGenerator generator(pattern);
generator.compile(globalData, jitObject);
if (generator.generationFailed()) {
JSRegExpIgnoreCaseOption ignoreCaseOption = ignoreCase ? JSRegExpIgnoreCase : JSRegExpDoNotIgnoreCase;
JSRegExpMultilineOption multilineOption = multiline ? JSRegExpMultiline : JSRegExpSingleLine;
jitObject.setFallback(jsRegExpCompile(reinterpret_cast<const UChar*>(patternString.data()), patternString.size(), ignoreCaseOption, multilineOption, &numSubpatterns, &error));
}
}
}}
#endif
|