/
regexp-compiler.cc
3887 lines (3539 loc) Β· 148 KB
/
regexp-compiler.cc
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 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/regexp/regexp-compiler.h"
#include "src/base/safe_conversions.h"
#include "src/execution/isolate.h"
#include "src/objects/objects-inl.h"
#include "src/regexp/regexp-macro-assembler-arch.h"
#ifdef V8_INTL_SUPPORT
#include "src/regexp/special-case.h"
#endif // V8_INTL_SUPPORT
#include "src/strings/unicode-inl.h"
#include "src/zone/zone-list-inl.h"
#ifdef V8_INTL_SUPPORT
#include "unicode/locid.h"
#include "unicode/uniset.h"
#include "unicode/utypes.h"
#endif // V8_INTL_SUPPORT
namespace v8 {
namespace internal {
using namespace regexp_compiler_constants; // NOLINT(build/namespaces)
// -------------------------------------------------------------------
// Implementation of the Irregexp regular expression engine.
//
// The Irregexp regular expression engine is intended to be a complete
// implementation of ECMAScript regular expressions. It generates either
// bytecodes or native code.
// The Irregexp regexp engine is structured in three steps.
// 1) The parser generates an abstract syntax tree. See ast.cc.
// 2) From the AST a node network is created. The nodes are all
// subclasses of RegExpNode. The nodes represent states when
// executing a regular expression. Several optimizations are
// performed on the node network.
// 3) From the nodes we generate either byte codes or native code
// that can actually execute the regular expression (perform
// the search). The code generation step is described in more
// detail below.
// Code generation.
//
// The nodes are divided into four main categories.
// * Choice nodes
// These represent places where the regular expression can
// match in more than one way. For example on entry to an
// alternation (foo|bar) or a repetition (*, +, ? or {}).
// * Action nodes
// These represent places where some action should be
// performed. Examples include recording the current position
// in the input string to a register (in order to implement
// captures) or other actions on register for example in order
// to implement the counters needed for {} repetitions.
// * Matching nodes
// These attempt to match some element part of the input string.
// Examples of elements include character classes, plain strings
// or back references.
// * End nodes
// These are used to implement the actions required on finding
// a successful match or failing to find a match.
//
// The code generated (whether as byte codes or native code) maintains
// some state as it runs. This consists of the following elements:
//
// * The capture registers. Used for string captures.
// * Other registers. Used for counters etc.
// * The current position.
// * The stack of backtracking information. Used when a matching node
// fails to find a match and needs to try an alternative.
//
// Conceptual regular expression execution model:
//
// There is a simple conceptual model of regular expression execution
// which will be presented first. The actual code generated is a more
// efficient simulation of the simple conceptual model:
//
// * Choice nodes are implemented as follows:
// For each choice except the last {
// push current position
// push backtrack code location
// <generate code to test for choice>
// backtrack code location:
// pop current position
// }
// <generate code to test for last choice>
//
// * Actions nodes are generated as follows
// <push affected registers on backtrack stack>
// <generate code to perform action>
// push backtrack code location
// <generate code to test for following nodes>
// backtrack code location:
// <pop affected registers to restore their state>
// <pop backtrack location from stack and go to it>
//
// * Matching nodes are generated as follows:
// if input string matches at current position
// update current position
// <generate code to test for following nodes>
// else
// <pop backtrack location from stack and go to it>
//
// Thus it can be seen that the current position is saved and restored
// by the choice nodes, whereas the registers are saved and restored by
// by the action nodes that manipulate them.
//
// The other interesting aspect of this model is that nodes are generated
// at the point where they are needed by a recursive call to Emit(). If
// the node has already been code generated then the Emit() call will
// generate a jump to the previously generated code instead. In order to
// limit recursion it is possible for the Emit() function to put the node
// on a work list for later generation and instead generate a jump. The
// destination of the jump is resolved later when the code is generated.
//
// Actual regular expression code generation.
//
// Code generation is actually more complicated than the above. In order
// to improve the efficiency of the generated code some optimizations are
// performed
//
// * Choice nodes have 1-character lookahead.
// A choice node looks at the following character and eliminates some of
// the choices immediately based on that character. This is not yet
// implemented.
// * Simple greedy loops store reduced backtracking information.
// A quantifier like /.*foo/m will greedily match the whole input. It will
// then need to backtrack to a point where it can match "foo". The naive
// implementation of this would push each character position onto the
// backtracking stack, then pop them off one by one. This would use space
// proportional to the length of the input string. However since the "."
// can only match in one way and always has a constant length (in this case
// of 1) it suffices to store the current position on the top of the stack
// once. Matching now becomes merely incrementing the current position and
// backtracking becomes decrementing the current position and checking the
// result against the stored current position. This is faster and saves
// space.
// * The current state is virtualized.
// This is used to defer expensive operations until it is clear that they
// are needed and to generate code for a node more than once, allowing
// specialized an efficient versions of the code to be created. This is
// explained in the section below.
//
// Execution state virtualization.
//
// Instead of emitting code, nodes that manipulate the state can record their
// manipulation in an object called the Trace. The Trace object can record a
// current position offset, an optional backtrack code location on the top of
// the virtualized backtrack stack and some register changes. When a node is
// to be emitted it can flush the Trace or update it. Flushing the Trace
// will emit code to bring the actual state into line with the virtual state.
// Avoiding flushing the state can postpone some work (e.g. updates of capture
// registers). Postponing work can save time when executing the regular
// expression since it may be found that the work never has to be done as a
// failure to match can occur. In addition it is much faster to jump to a
// known backtrack code location than it is to pop an unknown backtrack
// location from the stack and jump there.
//
// The virtual state found in the Trace affects code generation. For example
// the virtual state contains the difference between the actual current
// position and the virtual current position, and matching code needs to use
// this offset to attempt a match in the correct location of the input
// string. Therefore code generated for a non-trivial trace is specialized
// to that trace. The code generator therefore has the ability to generate
// code for each node several times. In order to limit the size of the
// generated code there is an arbitrary limit on how many specialized sets of
// code may be generated for a given node. If the limit is reached, the
// trace is flushed and a generic version of the code for a node is emitted.
// This is subsequently used for that node. The code emitted for non-generic
// trace is not recorded in the node and so it cannot currently be reused in
// the event that code generation is requested for an identical trace.
void RegExpTree::AppendToText(RegExpText* text, Zone* zone) { UNREACHABLE(); }
void RegExpAtom::AppendToText(RegExpText* text, Zone* zone) {
text->AddElement(TextElement::Atom(this), zone);
}
void RegExpCharacterClass::AppendToText(RegExpText* text, Zone* zone) {
text->AddElement(TextElement::CharClass(this), zone);
}
void RegExpText::AppendToText(RegExpText* text, Zone* zone) {
for (int i = 0; i < elements()->length(); i++)
text->AddElement(elements()->at(i), zone);
}
TextElement TextElement::Atom(RegExpAtom* atom) {
return TextElement(ATOM, atom);
}
TextElement TextElement::CharClass(RegExpCharacterClass* char_class) {
return TextElement(CHAR_CLASS, char_class);
}
int TextElement::length() const {
switch (text_type()) {
case ATOM:
return atom()->length();
case CHAR_CLASS:
return 1;
}
UNREACHABLE();
}
class RecursionCheck {
public:
explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
compiler->IncrementRecursionDepth();
}
~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
private:
RegExpCompiler* compiler_;
};
// Attempts to compile the regexp using an Irregexp code generator. Returns
// a fixed array or a null handle depending on whether it succeeded.
RegExpCompiler::RegExpCompiler(Isolate* isolate, Zone* zone, int capture_count,
bool one_byte)
: next_register_(JSRegExp::RegistersForCaptureCount(capture_count)),
unicode_lookaround_stack_register_(kNoRegister),
unicode_lookaround_position_register_(kNoRegister),
work_list_(nullptr),
recursion_depth_(0),
one_byte_(one_byte),
reg_exp_too_big_(false),
limiting_recursion_(false),
optimize_(FLAG_regexp_optimization),
read_backward_(false),
current_expansion_factor_(1),
frequency_collator_(),
isolate_(isolate),
zone_(zone) {
accept_ = new (zone) EndNode(EndNode::ACCEPT, zone);
DCHECK_GE(RegExpMacroAssembler::kMaxRegister, next_register_ - 1);
}
RegExpCompiler::CompilationResult RegExpCompiler::Assemble(
Isolate* isolate, RegExpMacroAssembler* macro_assembler, RegExpNode* start,
int capture_count, Handle<String> pattern) {
macro_assembler_ = macro_assembler;
ZoneVector<RegExpNode*> work_list(zone());
work_list_ = &work_list;
Label fail;
macro_assembler_->PushBacktrack(&fail);
Trace new_trace;
start->Emit(this, &new_trace);
macro_assembler_->BindJumpTarget(&fail);
macro_assembler_->Fail();
while (!work_list.empty()) {
RegExpNode* node = work_list.back();
work_list.pop_back();
node->set_on_work_list(false);
if (!node->label()->is_bound()) node->Emit(this, &new_trace);
}
if (reg_exp_too_big_) {
macro_assembler_->AbortedCodeGeneration();
return CompilationResult::RegExpTooBig();
}
Handle<HeapObject> code = macro_assembler_->GetCode(pattern);
isolate->IncreaseTotalRegexpCodeGenerated(code);
work_list_ = nullptr;
return {code, next_register_};
}
bool Trace::DeferredAction::Mentions(int that) {
if (action_type() == ActionNode::CLEAR_CAPTURES) {
Interval range = static_cast<DeferredClearCaptures*>(this)->range();
return range.Contains(that);
} else {
return reg() == that;
}
}
bool Trace::mentions_reg(int reg) {
for (DeferredAction* action = actions_; action != nullptr;
action = action->next()) {
if (action->Mentions(reg)) return true;
}
return false;
}
bool Trace::GetStoredPosition(int reg, int* cp_offset) {
DCHECK_EQ(0, *cp_offset);
for (DeferredAction* action = actions_; action != nullptr;
action = action->next()) {
if (action->Mentions(reg)) {
if (action->action_type() == ActionNode::STORE_POSITION) {
*cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
return true;
} else {
return false;
}
}
}
return false;
}
// A (dynamically-sized) set of unsigned integers that behaves especially well
// on small integers (< kFirstLimit). May do zone-allocation.
class DynamicBitSet : public ZoneObject {
public:
V8_EXPORT_PRIVATE bool Get(unsigned value) const {
if (value < kFirstLimit) {
return (first_ & (1 << value)) != 0;
} else if (remaining_ == nullptr) {
return false;
} else {
return remaining_->Contains(value);
}
}
// Destructively set a value in this set.
void Set(unsigned value, Zone* zone) {
if (value < kFirstLimit) {
first_ |= (1 << value);
} else {
if (remaining_ == nullptr)
remaining_ = new (zone) ZoneList<unsigned>(1, zone);
if (remaining_->is_empty() || !remaining_->Contains(value))
remaining_->Add(value, zone);
}
}
private:
static constexpr unsigned kFirstLimit = 32;
uint32_t first_ = 0;
ZoneList<unsigned>* remaining_ = nullptr;
};
int Trace::FindAffectedRegisters(DynamicBitSet* affected_registers,
Zone* zone) {
int max_register = RegExpCompiler::kNoRegister;
for (DeferredAction* action = actions_; action != nullptr;
action = action->next()) {
if (action->action_type() == ActionNode::CLEAR_CAPTURES) {
Interval range = static_cast<DeferredClearCaptures*>(action)->range();
for (int i = range.from(); i <= range.to(); i++)
affected_registers->Set(i, zone);
if (range.to() > max_register) max_register = range.to();
} else {
affected_registers->Set(action->reg(), zone);
if (action->reg() > max_register) max_register = action->reg();
}
}
return max_register;
}
void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
int max_register,
const DynamicBitSet& registers_to_pop,
const DynamicBitSet& registers_to_clear) {
for (int reg = max_register; reg >= 0; reg--) {
if (registers_to_pop.Get(reg)) {
assembler->PopRegister(reg);
} else if (registers_to_clear.Get(reg)) {
int clear_to = reg;
while (reg > 0 && registers_to_clear.Get(reg - 1)) {
reg--;
}
assembler->ClearRegisters(reg, clear_to);
}
}
}
void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
int max_register,
const DynamicBitSet& affected_registers,
DynamicBitSet* registers_to_pop,
DynamicBitSet* registers_to_clear,
Zone* zone) {
// The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
// Count pushes performed to force a stack limit check occasionally.
int pushes = 0;
for (int reg = 0; reg <= max_register; reg++) {
if (!affected_registers.Get(reg)) {
continue;
}
// The chronologically first deferred action in the trace
// is used to infer the action needed to restore a register
// to its previous state (or not, if it's safe to ignore it).
enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
DeferredActionUndoType undo_action = IGNORE;
int value = 0;
bool absolute = false;
bool clear = false;
static const int kNoStore = kMinInt;
int store_position = kNoStore;
// This is a little tricky because we are scanning the actions in reverse
// historical order (newest first).
for (DeferredAction* action = actions_; action != nullptr;
action = action->next()) {
if (action->Mentions(reg)) {
switch (action->action_type()) {
case ActionNode::SET_REGISTER_FOR_LOOP: {
Trace::DeferredSetRegisterForLoop* psr =
static_cast<Trace::DeferredSetRegisterForLoop*>(action);
if (!absolute) {
value += psr->value();
absolute = true;
}
// SET_REGISTER_FOR_LOOP is only used for newly introduced loop
// counters. They can have a significant previous value if they
// occur in a loop. TODO(lrn): Propagate this information, so
// we can set undo_action to IGNORE if we know there is no value to
// restore.
undo_action = RESTORE;
DCHECK_EQ(store_position, kNoStore);
DCHECK(!clear);
break;
}
case ActionNode::INCREMENT_REGISTER:
if (!absolute) {
value++;
}
DCHECK_EQ(store_position, kNoStore);
DCHECK(!clear);
undo_action = RESTORE;
break;
case ActionNode::STORE_POSITION: {
Trace::DeferredCapture* pc =
static_cast<Trace::DeferredCapture*>(action);
if (!clear && store_position == kNoStore) {
store_position = pc->cp_offset();
}
// For captures we know that stores and clears alternate.
// Other register, are never cleared, and if the occur
// inside a loop, they might be assigned more than once.
if (reg <= 1) {
// Registers zero and one, aka "capture zero", is
// always set correctly if we succeed. There is no
// need to undo a setting on backtrack, because we
// will set it again or fail.
undo_action = IGNORE;
} else {
undo_action = pc->is_capture() ? CLEAR : RESTORE;
}
DCHECK(!absolute);
DCHECK_EQ(value, 0);
break;
}
case ActionNode::CLEAR_CAPTURES: {
// Since we're scanning in reverse order, if we've already
// set the position we have to ignore historically earlier
// clearing operations.
if (store_position == kNoStore) {
clear = true;
}
undo_action = RESTORE;
DCHECK(!absolute);
DCHECK_EQ(value, 0);
break;
}
default:
UNREACHABLE();
break;
}
}
}
// Prepare for the undo-action (e.g., push if it's going to be popped).
if (undo_action == RESTORE) {
pushes++;
RegExpMacroAssembler::StackCheckFlag stack_check =
RegExpMacroAssembler::kNoStackLimitCheck;
if (pushes == push_limit) {
stack_check = RegExpMacroAssembler::kCheckStackLimit;
pushes = 0;
}
assembler->PushRegister(reg, stack_check);
registers_to_pop->Set(reg, zone);
} else if (undo_action == CLEAR) {
registers_to_clear->Set(reg, zone);
}
// Perform the chronologically last action (or accumulated increment)
// for the register.
if (store_position != kNoStore) {
assembler->WriteCurrentPositionToRegister(reg, store_position);
} else if (clear) {
assembler->ClearRegisters(reg, reg);
} else if (absolute) {
assembler->SetRegister(reg, value);
} else if (value != 0) {
assembler->AdvanceRegister(reg, value);
}
}
}
// This is called as we come into a loop choice node and some other tricky
// nodes. It normalizes the state of the code generator to ensure we can
// generate generic code.
void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
RegExpMacroAssembler* assembler = compiler->macro_assembler();
DCHECK(!is_trivial());
if (actions_ == nullptr && backtrack() == nullptr) {
// Here we just have some deferred cp advances to fix and we are back to
// a normal situation. We may also have to forget some information gained
// through a quick check that was already performed.
if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
// Create a new trivial state and generate the node with that.
Trace new_state;
successor->Emit(compiler, &new_state);
return;
}
// Generate deferred actions here along with code to undo them again.
DynamicBitSet affected_registers;
if (backtrack() != nullptr) {
// Here we have a concrete backtrack location. These are set up by choice
// nodes and so they indicate that we have a deferred save of the current
// position which we may need to emit here.
assembler->PushCurrentPosition();
}
int max_register =
FindAffectedRegisters(&affected_registers, compiler->zone());
DynamicBitSet registers_to_pop;
DynamicBitSet registers_to_clear;
PerformDeferredActions(assembler, max_register, affected_registers,
®isters_to_pop, ®isters_to_clear,
compiler->zone());
if (cp_offset_ != 0) {
assembler->AdvanceCurrentPosition(cp_offset_);
}
// Create a new trivial state and generate the node with that.
Label undo;
assembler->PushBacktrack(&undo);
if (successor->KeepRecursing(compiler)) {
Trace new_state;
successor->Emit(compiler, &new_state);
} else {
compiler->AddWork(successor);
assembler->GoTo(successor->label());
}
// On backtrack we need to restore state.
assembler->BindJumpTarget(&undo);
RestoreAffectedRegisters(assembler, max_register, registers_to_pop,
registers_to_clear);
if (backtrack() == nullptr) {
assembler->Backtrack();
} else {
assembler->PopCurrentPosition();
assembler->GoTo(backtrack());
}
}
void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
RegExpMacroAssembler* assembler = compiler->macro_assembler();
// Omit flushing the trace. We discard the entire stack frame anyway.
if (!label()->is_bound()) {
// We are completely independent of the trace, since we ignore it,
// so this code can be used as the generic version.
assembler->Bind(label());
}
// Throw away everything on the backtrack stack since the start
// of the negative submatch and restore the character position.
assembler->ReadCurrentPositionFromRegister(current_position_register_);
assembler->ReadStackPointerFromRegister(stack_pointer_register_);
if (clear_capture_count_ > 0) {
// Clear any captures that might have been performed during the success
// of the body of the negative look-ahead.
int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
}
// Now that we have unwound the stack we find at the top of the stack the
// backtrack that the BeginSubmatch node got.
assembler->Backtrack();
}
void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
if (!trace->is_trivial()) {
trace->Flush(compiler, this);
return;
}
RegExpMacroAssembler* assembler = compiler->macro_assembler();
if (!label()->is_bound()) {
assembler->Bind(label());
}
switch (action_) {
case ACCEPT:
assembler->Succeed();
return;
case BACKTRACK:
assembler->GoTo(trace->backtrack());
return;
case NEGATIVE_SUBMATCH_SUCCESS:
// This case is handled in a different virtual method.
UNREACHABLE();
}
UNIMPLEMENTED();
}
void GuardedAlternative::AddGuard(Guard* guard, Zone* zone) {
if (guards_ == nullptr) guards_ = new (zone) ZoneList<Guard*>(1, zone);
guards_->Add(guard, zone);
}
ActionNode* ActionNode::SetRegisterForLoop(int reg, int val,
RegExpNode* on_success) {
ActionNode* result =
new (on_success->zone()) ActionNode(SET_REGISTER_FOR_LOOP, on_success);
result->data_.u_store_register.reg = reg;
result->data_.u_store_register.value = val;
return result;
}
ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
ActionNode* result =
new (on_success->zone()) ActionNode(INCREMENT_REGISTER, on_success);
result->data_.u_increment_register.reg = reg;
return result;
}
ActionNode* ActionNode::StorePosition(int reg, bool is_capture,
RegExpNode* on_success) {
ActionNode* result =
new (on_success->zone()) ActionNode(STORE_POSITION, on_success);
result->data_.u_position_register.reg = reg;
result->data_.u_position_register.is_capture = is_capture;
return result;
}
ActionNode* ActionNode::ClearCaptures(Interval range, RegExpNode* on_success) {
ActionNode* result =
new (on_success->zone()) ActionNode(CLEAR_CAPTURES, on_success);
result->data_.u_clear_captures.range_from = range.from();
result->data_.u_clear_captures.range_to = range.to();
return result;
}
ActionNode* ActionNode::BeginSubmatch(int stack_reg, int position_reg,
RegExpNode* on_success) {
ActionNode* result =
new (on_success->zone()) ActionNode(BEGIN_SUBMATCH, on_success);
result->data_.u_submatch.stack_pointer_register = stack_reg;
result->data_.u_submatch.current_position_register = position_reg;
return result;
}
ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg, int position_reg,
int clear_register_count,
int clear_register_from,
RegExpNode* on_success) {
ActionNode* result = new (on_success->zone())
ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
result->data_.u_submatch.stack_pointer_register = stack_reg;
result->data_.u_submatch.current_position_register = position_reg;
result->data_.u_submatch.clear_register_count = clear_register_count;
result->data_.u_submatch.clear_register_from = clear_register_from;
return result;
}
ActionNode* ActionNode::EmptyMatchCheck(int start_register,
int repetition_register,
int repetition_limit,
RegExpNode* on_success) {
ActionNode* result =
new (on_success->zone()) ActionNode(EMPTY_MATCH_CHECK, on_success);
result->data_.u_empty_match_check.start_register = start_register;
result->data_.u_empty_match_check.repetition_register = repetition_register;
result->data_.u_empty_match_check.repetition_limit = repetition_limit;
return result;
}
#define DEFINE_ACCEPT(Type) \
void Type##Node::Accept(NodeVisitor* visitor) { visitor->Visit##Type(this); }
FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
#undef DEFINE_ACCEPT
// -------------------------------------------------------------------
// Emit code.
void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
Guard* guard, Trace* trace) {
switch (guard->op()) {
case Guard::LT:
DCHECK(!trace->mentions_reg(guard->reg()));
macro_assembler->IfRegisterGE(guard->reg(), guard->value(),
trace->backtrack());
break;
case Guard::GEQ:
DCHECK(!trace->mentions_reg(guard->reg()));
macro_assembler->IfRegisterLT(guard->reg(), guard->value(),
trace->backtrack());
break;
}
}
// Returns the number of characters in the equivalence class, omitting those
// that cannot occur in the source string because it is Latin1.
static int GetCaseIndependentLetters(Isolate* isolate, uc16 character,
bool one_byte_subject,
unibrow::uchar* letters,
int letter_length) {
#ifdef V8_INTL_SUPPORT
if (RegExpCaseFolding::IgnoreSet().contains(character)) {
letters[0] = character;
return 1;
}
bool in_special_add_set =
RegExpCaseFolding::SpecialAddSet().contains(character);
icu::UnicodeSet set;
set.add(character);
set = set.closeOver(USET_CASE_INSENSITIVE);
UChar32 canon = 0;
if (in_special_add_set) {
canon = RegExpCaseFolding::Canonicalize(character);
}
int32_t range_count = set.getRangeCount();
int items = 0;
for (int32_t i = 0; i < range_count; i++) {
UChar32 start = set.getRangeStart(i);
UChar32 end = set.getRangeEnd(i);
CHECK(end - start + items <= letter_length);
for (UChar32 cu = start; cu <= end; cu++) {
if (one_byte_subject && cu > String::kMaxOneByteCharCode) break;
if (in_special_add_set && RegExpCaseFolding::Canonicalize(cu) != canon) {
continue;
}
letters[items++] = (unibrow::uchar)(cu);
}
}
return items;
#else
int length =
isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
// Unibrow returns 0 or 1 for characters where case independence is
// trivial.
if (length == 0) {
letters[0] = character;
length = 1;
}
if (one_byte_subject) {
int new_length = 0;
for (int i = 0; i < length; i++) {
if (letters[i] <= String::kMaxOneByteCharCode) {
letters[new_length++] = letters[i];
}
}
length = new_length;
}
return length;
#endif // V8_INTL_SUPPORT
}
static inline bool EmitSimpleCharacter(Isolate* isolate,
RegExpCompiler* compiler, uc16 c,
Label* on_failure, int cp_offset,
bool check, bool preloaded) {
RegExpMacroAssembler* assembler = compiler->macro_assembler();
bool bound_checked = false;
if (!preloaded) {
assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
bound_checked = true;
}
assembler->CheckNotCharacter(c, on_failure);
return bound_checked;
}
// Only emits non-letters (things that don't have case). Only used for case
// independent matches.
static inline bool EmitAtomNonLetter(Isolate* isolate, RegExpCompiler* compiler,
uc16 c, Label* on_failure, int cp_offset,
bool check, bool preloaded) {
RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
bool one_byte = compiler->one_byte();
unibrow::uchar chars[4];
int length = GetCaseIndependentLetters(isolate, c, one_byte, chars, 4);
if (length < 1) {
// This can't match. Must be an one-byte subject and a non-one-byte
// character. We do not need to do anything since the one-byte pass
// already handled this.
return false; // Bounds not checked.
}
bool checked = false;
// We handle the length > 1 case in a later pass.
if (length == 1) {
if (one_byte && c > String::kMaxOneByteCharCodeU) {
// Can't match - see above.
return false; // Bounds not checked.
}
if (!preloaded) {
macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
checked = check;
}
macro_assembler->CheckNotCharacter(c, on_failure);
}
return checked;
}
static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
bool one_byte, uc16 c1, uc16 c2,
Label* on_failure) {
uc16 char_mask;
if (one_byte) {
char_mask = String::kMaxOneByteCharCode;
} else {
char_mask = String::kMaxUtf16CodeUnit;
}
uc16 exor = c1 ^ c2;
// Check whether exor has only one bit set.
if (((exor - 1) & exor) == 0) {
// If c1 and c2 differ only by one bit.
// Ecma262UnCanonicalize always gives the highest number last.
DCHECK(c2 > c1);
uc16 mask = char_mask ^ exor;
macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
return true;
}
DCHECK(c2 > c1);
uc16 diff = c2 - c1;
if (((diff - 1) & diff) == 0 && c1 >= diff) {
// If the characters differ by 2^n but don't differ by one bit then
// subtract the difference from the found character, then do the or
// trick. We avoid the theoretical case where negative numbers are
// involved in order to simplify code generation.
uc16 mask = char_mask ^ diff;
macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff, diff, mask,
on_failure);
return true;
}
return false;
}
// Only emits letters (things that have case). Only used for case independent
// matches.
static inline bool EmitAtomLetter(Isolate* isolate, RegExpCompiler* compiler,
uc16 c, Label* on_failure, int cp_offset,
bool check, bool preloaded) {
RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
bool one_byte = compiler->one_byte();
unibrow::uchar chars[4];
int length = GetCaseIndependentLetters(isolate, c, one_byte, chars, 4);
if (length <= 1) return false;
// We may not need to check against the end of the input string
// if this character lies before a character that matched.
if (!preloaded) {
macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
}
Label ok;
switch (length) {
case 2: {
if (ShortCutEmitCharacterPair(macro_assembler, one_byte, chars[0],
chars[1], on_failure)) {
} else {
macro_assembler->CheckCharacter(chars[0], &ok);
macro_assembler->CheckNotCharacter(chars[1], on_failure);
macro_assembler->Bind(&ok);
}
break;
}
case 4:
macro_assembler->CheckCharacter(chars[3], &ok);
V8_FALLTHROUGH;
case 3:
macro_assembler->CheckCharacter(chars[0], &ok);
macro_assembler->CheckCharacter(chars[1], &ok);
macro_assembler->CheckNotCharacter(chars[2], on_failure);
macro_assembler->Bind(&ok);
break;
default:
UNREACHABLE();
}
return true;
}
static void EmitBoundaryTest(RegExpMacroAssembler* masm, int border,
Label* fall_through, Label* above_or_equal,
Label* below) {
if (below != fall_through) {
masm->CheckCharacterLT(border, below);
if (above_or_equal != fall_through) masm->GoTo(above_or_equal);
} else {
masm->CheckCharacterGT(border - 1, above_or_equal);
}
}
static void EmitDoubleBoundaryTest(RegExpMacroAssembler* masm, int first,
int last, Label* fall_through,
Label* in_range, Label* out_of_range) {
if (in_range == fall_through) {
if (first == last) {
masm->CheckNotCharacter(first, out_of_range);
} else {
masm->CheckCharacterNotInRange(first, last, out_of_range);
}
} else {
if (first == last) {
masm->CheckCharacter(first, in_range);
} else {
masm->CheckCharacterInRange(first, last, in_range);
}
if (out_of_range != fall_through) masm->GoTo(out_of_range);
}
}
// even_label is for ranges[i] to ranges[i + 1] where i - start_index is even.
// odd_label is for ranges[i] to ranges[i + 1] where i - start_index is odd.
static void EmitUseLookupTable(RegExpMacroAssembler* masm,
ZoneList<int>* ranges, int start_index,
int end_index, int min_char, Label* fall_through,
Label* even_label, Label* odd_label) {
static const int kSize = RegExpMacroAssembler::kTableSize;
static const int kMask = RegExpMacroAssembler::kTableMask;
int base = (min_char & ~kMask);
USE(base);
// Assert that everything is on one kTableSize page.
for (int i = start_index; i <= end_index; i++) {
DCHECK_EQ(ranges->at(i) & ~kMask, base);
}
DCHECK(start_index == 0 || (ranges->at(start_index - 1) & ~kMask) <= base);
char templ[kSize];
Label* on_bit_set;
Label* on_bit_clear;
int bit;
if (even_label == fall_through) {
on_bit_set = odd_label;
on_bit_clear = even_label;
bit = 1;
} else {
on_bit_set = even_label;
on_bit_clear = odd_label;
bit = 0;
}
for (int i = 0; i < (ranges->at(start_index) & kMask) && i < kSize; i++) {
templ[i] = bit;
}
int j = 0;
bit ^= 1;
for (int i = start_index; i < end_index; i++) {
for (j = (ranges->at(i) & kMask); j < (ranges->at(i + 1) & kMask); j++) {
templ[j] = bit;
}
bit ^= 1;
}
for (int i = j; i < kSize; i++) {
templ[i] = bit;
}
Factory* factory = masm->isolate()->factory();
// TODO(erikcorry): Cache these.
Handle<ByteArray> ba = factory->NewByteArray(kSize, AllocationType::kOld);
for (int i = 0; i < kSize; i++) {
ba->set(i, templ[i]);
}
masm->CheckBitInTable(ba, on_bit_set);
if (on_bit_clear != fall_through) masm->GoTo(on_bit_clear);
}
static void CutOutRange(RegExpMacroAssembler* masm, ZoneList<int>* ranges,
int start_index, int end_index, int cut_index,
Label* even_label, Label* odd_label) {
bool odd = (((cut_index - start_index) & 1) == 1);
Label* in_range_label = odd ? odd_label : even_label;
Label dummy;
EmitDoubleBoundaryTest(masm, ranges->at(cut_index),
ranges->at(cut_index + 1) - 1, &dummy, in_range_label,
&dummy);
DCHECK(!dummy.is_linked());
// Cut out the single range by rewriting the array. This creates a new
// range that is a merger of the two ranges on either side of the one we
// are cutting out. The oddity of the labels is preserved.
for (int j = cut_index; j > start_index; j--) {
ranges->at(j) = ranges->at(j - 1);
}
for (int j = cut_index + 1; j < end_index; j++) {
ranges->at(j) = ranges->at(j + 1);
}
}