1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #if defined(V8_TARGET_ARCH_X64)
32 #include "serialize.h"
35 #include "regexp-stack.h"
36 #include "macro-assembler.h"
37 #include "regexp-macro-assembler.h"
38 #include "x64/regexp-macro-assembler-x64.h"
43 #ifndef V8_INTERPRETED_REGEXP
46 * This assembler uses the following register assignment convention
47 * - rdx : currently loaded character(s) as ASCII or UC16. Must be loaded using
48 * LoadCurrentCharacter before using any of the dispatch methods.
49 * - rdi : current position in input, as negative offset from end of string.
50 * Please notice that this is the byte offset, not the character
51 * offset! Is always a 32-bit signed (negative) offset, but must be
52 * maintained sign-extended to 64 bits, since it is used as index.
53 * - rsi : end of input (points to byte after last character in input),
54 * so that rsi+rdi points to the current character.
55 * - rbp : frame pointer. Used to access arguments, local variables and
57 * - rsp : points to tip of C stack.
58 * - rcx : points to tip of backtrack stack. The backtrack stack contains
59 * only 32-bit values. Most are offsets from some base (e.g., character
60 * positions from end of string or code location from Code* pointer).
61 * - r8 : code object pointer. Used to convert between absolute and
62 * code-object-relative addresses.
64 * The registers rax, rbx, r9 and r11 are free to use for computations.
65 * If changed to use r12+, they should be saved as callee-save registers.
66 * The macro assembler special registers r12 and r13 (kSmiConstantRegister,
67 * kRootRegister) aren't special during execution of RegExp code (they don't
68 * hold the values assumed when creating JS code), so no Smi or Root related
69 * macro operations can be used.
71 * Each call to a C++ method should retain these registers.
73 * The stack will have the following content, in some order, indexable from the
74 * frame pointer (see, e.g., kStackHighEnd):
75 * - Isolate* isolate (Address of the current isolate)
76 * - direct_call (if 1, direct call from JavaScript code, if 0 call
77 * through the runtime system)
78 * - stack_area_base (High end of the memory area to use as
80 * - int* capture_array (int[num_saved_registers_], for output).
81 * - end of input (Address of end of string)
82 * - start of input (Address of first character in string)
83 * - start index (character index of start)
84 * - String* input_string (input string)
86 * - backup of callee save registers (rbx, possibly rsi and rdi).
87 * - Offset of location before start of input (effectively character
88 * position -1). Used to initialize capture registers to a non-position.
89 * - At start of string (if 1, we are starting at the start of the
90 * string, otherwise 0)
91 * - register 0 rbp[-n] (Only positions must be stored in the first
92 * - register 1 rbp[-n-8] num_saved_registers_ registers)
95 * The first num_saved_registers_ registers are initialized to point to
96 * "character -1" in the string (i.e., char_size() bytes before the first
97 * character of the string). The remaining registers starts out uninitialized.
99 * The first seven values must be provided by the calling code by
100 * calling the code's entry address cast to a function pointer with the
101 * following signature:
102 * int (*match)(String* input_string,
106 * int* capture_output_array,
108 * byte* stack_area_base,
112 #define __ ACCESS_MASM((&masm_))
114 RegExpMacroAssemblerX64::RegExpMacroAssemblerX64(
116 int registers_to_save)
117 : masm_(Isolate::Current(), NULL, kRegExpCodeSize),
118 no_root_array_scope_(&masm_),
119 code_relative_fixup_positions_(4),
121 num_registers_(registers_to_save),
122 num_saved_registers_(registers_to_save),
128 ASSERT_EQ(0, registers_to_save % 2);
129 __ jmp(&entry_label_); // We'll write the entry code when we know more.
130 __ bind(&start_label_); // And then continue from here.
134 RegExpMacroAssemblerX64::~RegExpMacroAssemblerX64() {
135 // Unuse labels in case we throw away the assembler without calling GetCode.
136 entry_label_.Unuse();
137 start_label_.Unuse();
138 success_label_.Unuse();
139 backtrack_label_.Unuse();
141 check_preempt_label_.Unuse();
142 stack_overflow_label_.Unuse();
146 int RegExpMacroAssemblerX64::stack_limit_slack() {
147 return RegExpStack::kStackLimitSlack;
151 void RegExpMacroAssemblerX64::AdvanceCurrentPosition(int by) {
153 __ addq(rdi, Immediate(by * char_size()));
158 void RegExpMacroAssemblerX64::AdvanceRegister(int reg, int by) {
160 ASSERT(reg < num_registers_);
162 __ addq(register_location(reg), Immediate(by));
167 void RegExpMacroAssemblerX64::Backtrack() {
169 // Pop Code* offset from backtrack stack, add Code* and jump to location.
171 __ addq(rbx, code_object_pointer());
176 void RegExpMacroAssemblerX64::Bind(Label* label) {
181 void RegExpMacroAssemblerX64::CheckCharacter(uint32_t c, Label* on_equal) {
182 __ cmpl(current_character(), Immediate(c));
183 BranchOrBacktrack(equal, on_equal);
187 void RegExpMacroAssemblerX64::CheckCharacterGT(uc16 limit, Label* on_greater) {
188 __ cmpl(current_character(), Immediate(limit));
189 BranchOrBacktrack(greater, on_greater);
193 void RegExpMacroAssemblerX64::CheckAtStart(Label* on_at_start) {
195 // Did we start the match at the start of the string at all?
196 __ cmpl(Operand(rbp, kStartIndex), Immediate(0));
197 BranchOrBacktrack(not_equal, ¬_at_start);
198 // If we did, are we still at the start of the input?
199 __ lea(rax, Operand(rsi, rdi, times_1, 0));
200 __ cmpq(rax, Operand(rbp, kInputStart));
201 BranchOrBacktrack(equal, on_at_start);
202 __ bind(¬_at_start);
206 void RegExpMacroAssemblerX64::CheckNotAtStart(Label* on_not_at_start) {
207 // Did we start the match at the start of the string at all?
208 __ cmpl(Operand(rbp, kStartIndex), Immediate(0));
209 BranchOrBacktrack(not_equal, on_not_at_start);
210 // If we did, are we still at the start of the input?
211 __ lea(rax, Operand(rsi, rdi, times_1, 0));
212 __ cmpq(rax, Operand(rbp, kInputStart));
213 BranchOrBacktrack(not_equal, on_not_at_start);
217 void RegExpMacroAssemblerX64::CheckCharacterLT(uc16 limit, Label* on_less) {
218 __ cmpl(current_character(), Immediate(limit));
219 BranchOrBacktrack(less, on_less);
223 void RegExpMacroAssemblerX64::CheckCharacters(Vector<const uc16> str,
226 bool check_end_of_string) {
228 // If input is ASCII, don't even bother calling here if the string to
229 // match contains a non-ASCII character.
230 if (mode_ == ASCII) {
231 ASSERT(String::IsAscii(str.start(), str.length()));
234 int byte_length = str.length() * char_size();
235 int byte_offset = cp_offset * char_size();
236 if (check_end_of_string) {
237 // Check that there are at least str.length() characters left in the input.
238 __ cmpl(rdi, Immediate(-(byte_offset + byte_length)));
239 BranchOrBacktrack(greater, on_failure);
242 if (on_failure == NULL) {
243 // Instead of inlining a backtrack, (re)use the global backtrack target.
244 on_failure = &backtrack_label_;
247 // Do one character test first to minimize loading for the case that
248 // we don't match at all (loading more than one character introduces that
249 // chance of reading unaligned and reading across cache boundaries).
250 // If the first character matches, expect a larger chance of matching the
251 // string, and start loading more characters at a time.
252 if (mode_ == ASCII) {
253 __ cmpb(Operand(rsi, rdi, times_1, byte_offset),
254 Immediate(static_cast<int8_t>(str[0])));
256 // Don't use 16-bit immediate. The size changing prefix throws off
259 Operand(rsi, rdi, times_1, byte_offset));
260 __ cmpl(rax, Immediate(static_cast<int32_t>(str[0])));
262 BranchOrBacktrack(not_equal, on_failure);
264 __ lea(rbx, Operand(rsi, rdi, times_1, 0));
265 for (int i = 1, n = str.length(); i < n; ) {
266 if (mode_ == ASCII) {
268 uint64_t combined_chars =
269 (static_cast<uint64_t>(str[i + 0]) << 0) ||
270 (static_cast<uint64_t>(str[i + 1]) << 8) ||
271 (static_cast<uint64_t>(str[i + 2]) << 16) ||
272 (static_cast<uint64_t>(str[i + 3]) << 24) ||
273 (static_cast<uint64_t>(str[i + 4]) << 32) ||
274 (static_cast<uint64_t>(str[i + 5]) << 40) ||
275 (static_cast<uint64_t>(str[i + 6]) << 48) ||
276 (static_cast<uint64_t>(str[i + 7]) << 56);
277 __ movq(rax, combined_chars, RelocInfo::NONE);
278 __ cmpq(rax, Operand(rbx, byte_offset + i));
280 } else if (i + 4 <= n) {
281 uint32_t combined_chars =
282 (static_cast<uint32_t>(str[i + 0]) << 0) ||
283 (static_cast<uint32_t>(str[i + 1]) << 8) ||
284 (static_cast<uint32_t>(str[i + 2]) << 16) ||
285 (static_cast<uint32_t>(str[i + 3]) << 24);
286 __ cmpl(Operand(rbx, byte_offset + i), Immediate(combined_chars));
289 __ cmpb(Operand(rbx, byte_offset + i),
290 Immediate(static_cast<int8_t>(str[i])));
294 ASSERT(mode_ == UC16);
296 uint64_t combined_chars = *reinterpret_cast<const uint64_t*>(&str[i]);
297 __ movq(rax, combined_chars, RelocInfo::NONE);
299 Operand(rsi, rdi, times_1, byte_offset + i * sizeof(uc16)));
301 } else if (i + 2 <= n) {
302 uint32_t combined_chars = *reinterpret_cast<const uint32_t*>(&str[i]);
303 __ cmpl(Operand(rsi, rdi, times_1, byte_offset + i * sizeof(uc16)),
304 Immediate(combined_chars));
308 Operand(rsi, rdi, times_1, byte_offset + i * sizeof(uc16)));
309 __ cmpl(rax, Immediate(str[i]));
313 BranchOrBacktrack(not_equal, on_failure);
318 void RegExpMacroAssemblerX64::CheckGreedyLoop(Label* on_equal) {
320 __ cmpl(rdi, Operand(backtrack_stackpointer(), 0));
321 __ j(not_equal, &fallthrough);
323 BranchOrBacktrack(no_condition, on_equal);
324 __ bind(&fallthrough);
328 void RegExpMacroAssemblerX64::CheckNotBackReferenceIgnoreCase(
330 Label* on_no_match) {
332 __ movq(rdx, register_location(start_reg)); // Offset of start of capture
333 __ movq(rbx, register_location(start_reg + 1)); // Offset of end of capture
334 __ subq(rbx, rdx); // Length of capture.
336 // -----------------------
337 // rdx = Start offset of capture.
338 // rbx = Length of capture
340 // If length is negative, this code will fail (it's a symptom of a partial or
341 // illegal capture where start of capture after end of capture).
342 // This must not happen (no back-reference can reference a capture that wasn't
343 // closed before in the reg-exp, and we must not generate code that can cause
346 // If length is zero, either the capture is empty or it is nonparticipating.
347 // In either case succeed immediately.
348 __ j(equal, &fallthrough);
350 if (mode_ == ASCII) {
351 Label loop_increment;
352 if (on_no_match == NULL) {
353 on_no_match = &backtrack_label_;
356 __ lea(r9, Operand(rsi, rdx, times_1, 0));
357 __ lea(r11, Operand(rsi, rdi, times_1, 0));
358 __ addq(rbx, r9); // End of capture
359 // ---------------------
360 // r11 - current input character address
361 // r9 - current capture character address
362 // rbx - end of capture
366 __ movzxbl(rdx, Operand(r9, 0));
367 __ movzxbl(rax, Operand(r11, 0));
368 // al - input character
369 // dl - capture character
371 __ j(equal, &loop_increment);
373 // Mismatch, try case-insensitive match (converting letters to lower-case).
374 // I.e., if or-ing with 0x20 makes values equal and in range 'a'-'z', it's
376 __ or_(rax, Immediate(0x20)); // Convert match character to lower-case.
377 __ or_(rdx, Immediate(0x20)); // Convert capture character to lower-case.
379 __ j(not_equal, on_no_match); // Definitely not equal.
380 __ subb(rax, Immediate('a'));
381 __ cmpb(rax, Immediate('z' - 'a'));
382 __ j(above, on_no_match); // Weren't letters anyway.
384 __ bind(&loop_increment);
385 // Increment pointers into match and capture strings.
386 __ addq(r11, Immediate(1));
387 __ addq(r9, Immediate(1));
388 // Compare to end of capture, and loop if not done.
392 // Compute new value of character position after the matched part.
396 ASSERT(mode_ == UC16);
397 // Save important/volatile registers before calling C function.
399 // Caller save on Linux and callee save in Windows.
403 __ push(backtrack_stackpointer());
405 static const int num_arguments = 4;
406 __ PrepareCallCFunction(num_arguments);
408 // Put arguments into parameter registers. Parameters are
409 // Address byte_offset1 - Address captured substring's start.
410 // Address byte_offset2 - Address of current character position.
411 // size_t byte_length - length of capture in bytes(!)
414 // Compute and set byte_offset1 (start of capture).
415 __ lea(rcx, Operand(rsi, rdx, times_1, 0));
417 __ lea(rdx, Operand(rsi, rdi, times_1, 0));
421 __ LoadAddress(r9, ExternalReference::isolate_address());
422 #else // AMD64 calling convention
423 // Compute byte_offset2 (current position = rsi+rdi).
424 __ lea(rax, Operand(rsi, rdi, times_1, 0));
425 // Compute and set byte_offset1 (start of capture).
426 __ lea(rdi, Operand(rsi, rdx, times_1, 0));
432 __ LoadAddress(rcx, ExternalReference::isolate_address());
435 { // NOLINT: Can't find a way to open this scope without confusing the
437 AllowExternalCallThatCantCauseGC scope(&masm_);
438 ExternalReference compare =
439 ExternalReference::re_case_insensitive_compare_uc16(masm_.isolate());
440 __ CallCFunction(compare, num_arguments);
443 // Restore original values before reacting on result value.
444 __ Move(code_object_pointer(), masm_.CodeObject());
445 __ pop(backtrack_stackpointer());
451 // Check if function returned non-zero for success or zero for failure.
453 BranchOrBacktrack(zero, on_no_match);
454 // On success, increment position by length of capture.
455 // Requires that rbx is callee save (true for both Win64 and AMD64 ABIs).
458 __ bind(&fallthrough);
462 void RegExpMacroAssemblerX64::CheckNotBackReference(
464 Label* on_no_match) {
467 // Find length of back-referenced capture.
468 __ movq(rdx, register_location(start_reg));
469 __ movq(rax, register_location(start_reg + 1));
470 __ subq(rax, rdx); // Length to check.
472 // Fail on partial or illegal capture (start of capture after end of capture).
473 // This must not happen (no back-reference can reference a capture that wasn't
474 // closed before in the reg-exp).
475 __ Check(greater_equal, "Invalid capture referenced");
477 // Succeed on empty capture (including non-participating capture)
478 __ j(equal, &fallthrough);
480 // -----------------------
481 // rdx - Start of capture
482 // rax - length of capture
484 // Check that there are sufficient characters left in the input.
487 BranchOrBacktrack(greater, on_no_match);
489 // Compute pointers to match string and capture string
490 __ lea(rbx, Operand(rsi, rdi, times_1, 0)); // Start of match.
491 __ addq(rdx, rsi); // Start of capture.
492 __ lea(r9, Operand(rdx, rax, times_1, 0)); // End of capture
494 // -----------------------
495 // rbx - current capture character address.
496 // rbx - current input character address .
497 // r9 - end of input to match (capture length after rbx).
501 if (mode_ == ASCII) {
502 __ movzxbl(rax, Operand(rdx, 0));
503 __ cmpb(rax, Operand(rbx, 0));
505 ASSERT(mode_ == UC16);
506 __ movzxwl(rax, Operand(rdx, 0));
507 __ cmpw(rax, Operand(rbx, 0));
509 BranchOrBacktrack(not_equal, on_no_match);
510 // Increment pointers into capture and match string.
511 __ addq(rbx, Immediate(char_size()));
512 __ addq(rdx, Immediate(char_size()));
513 // Check if we have reached end of match area.
518 // Set current character position to position after match.
522 __ bind(&fallthrough);
526 void RegExpMacroAssemblerX64::CheckNotRegistersEqual(int reg1,
528 Label* on_not_equal) {
529 __ movq(rax, register_location(reg1));
530 __ cmpq(rax, register_location(reg2));
531 BranchOrBacktrack(not_equal, on_not_equal);
535 void RegExpMacroAssemblerX64::CheckNotCharacter(uint32_t c,
536 Label* on_not_equal) {
537 __ cmpl(current_character(), Immediate(c));
538 BranchOrBacktrack(not_equal, on_not_equal);
542 void RegExpMacroAssemblerX64::CheckCharacterAfterAnd(uint32_t c,
546 __ testl(current_character(), Immediate(mask));
548 __ movl(rax, Immediate(mask));
549 __ and_(rax, current_character());
550 __ cmpl(rax, Immediate(c));
552 BranchOrBacktrack(equal, on_equal);
556 void RegExpMacroAssemblerX64::CheckNotCharacterAfterAnd(uint32_t c,
558 Label* on_not_equal) {
560 __ testl(current_character(), Immediate(mask));
562 __ movl(rax, Immediate(mask));
563 __ and_(rax, current_character());
564 __ cmpl(rax, Immediate(c));
566 BranchOrBacktrack(not_equal, on_not_equal);
570 void RegExpMacroAssemblerX64::CheckNotCharacterAfterMinusAnd(
574 Label* on_not_equal) {
575 ASSERT(minus < String::kMaxUtf16CodeUnit);
576 __ lea(rax, Operand(current_character(), -minus));
577 __ and_(rax, Immediate(mask));
578 __ cmpl(rax, Immediate(c));
579 BranchOrBacktrack(not_equal, on_not_equal);
583 void RegExpMacroAssemblerX64::CheckCharacterInRange(
586 Label* on_in_range) {
587 __ leal(rax, Operand(current_character(), -from));
588 __ cmpl(rax, Immediate(to - from));
589 BranchOrBacktrack(below_equal, on_in_range);
593 void RegExpMacroAssemblerX64::CheckCharacterNotInRange(
596 Label* on_not_in_range) {
597 __ leal(rax, Operand(current_character(), -from));
598 __ cmpl(rax, Immediate(to - from));
599 BranchOrBacktrack(above, on_not_in_range);
603 void RegExpMacroAssemblerX64::CheckBitInTable(
604 Handle<ByteArray> table,
607 Register index = current_character();
608 if (mode_ != ASCII || kTableMask != String::kMaxAsciiCharCode) {
609 __ movq(rbx, current_character());
610 __ and_(rbx, Immediate(kTableMask));
613 __ cmpb(FieldOperand(rax, index, times_1, ByteArray::kHeaderSize),
615 BranchOrBacktrack(not_equal, on_bit_set);
619 bool RegExpMacroAssemblerX64::CheckSpecialCharacterClass(uc16 type,
620 Label* on_no_match) {
621 // Range checks (c in min..max) are generally implemented by an unsigned
622 // (c - min) <= (max - min) check, using the sequence:
623 // lea(rax, Operand(current_character(), -min)) or sub(rax, Immediate(min))
624 // cmp(rax, Immediate(max - min))
627 // Match space-characters
628 if (mode_ == ASCII) {
629 // ASCII space characters are '\t'..'\r' and ' '.
631 __ cmpl(current_character(), Immediate(' '));
632 __ j(equal, &success);
633 // Check range 0x09..0x0d
634 __ lea(rax, Operand(current_character(), -'\t'));
635 __ cmpl(rax, Immediate('\r' - '\t'));
636 BranchOrBacktrack(above, on_no_match);
642 // Match non-space characters.
643 if (mode_ == ASCII) {
644 // ASCII space characters are '\t'..'\r' and ' '.
645 __ cmpl(current_character(), Immediate(' '));
646 BranchOrBacktrack(equal, on_no_match);
647 __ lea(rax, Operand(current_character(), -'\t'));
648 __ cmpl(rax, Immediate('\r' - '\t'));
649 BranchOrBacktrack(below_equal, on_no_match);
654 // Match ASCII digits ('0'..'9')
655 __ lea(rax, Operand(current_character(), -'0'));
656 __ cmpl(rax, Immediate('9' - '0'));
657 BranchOrBacktrack(above, on_no_match);
660 // Match non ASCII-digits
661 __ lea(rax, Operand(current_character(), -'0'));
662 __ cmpl(rax, Immediate('9' - '0'));
663 BranchOrBacktrack(below_equal, on_no_match);
666 // Match non-newlines (not 0x0a('\n'), 0x0d('\r'), 0x2028 and 0x2029)
667 __ movl(rax, current_character());
668 __ xor_(rax, Immediate(0x01));
669 // See if current character is '\n'^1 or '\r'^1, i.e., 0x0b or 0x0c
670 __ subl(rax, Immediate(0x0b));
671 __ cmpl(rax, Immediate(0x0c - 0x0b));
672 BranchOrBacktrack(below_equal, on_no_match);
674 // Compare original value to 0x2028 and 0x2029, using the already
675 // computed (current_char ^ 0x01 - 0x0b). I.e., check for
676 // 0x201d (0x2028 - 0x0b) or 0x201e.
677 __ subl(rax, Immediate(0x2028 - 0x0b));
678 __ cmpl(rax, Immediate(0x2029 - 0x2028));
679 BranchOrBacktrack(below_equal, on_no_match);
684 // Match newlines (0x0a('\n'), 0x0d('\r'), 0x2028 and 0x2029)
685 __ movl(rax, current_character());
686 __ xor_(rax, Immediate(0x01));
687 // See if current character is '\n'^1 or '\r'^1, i.e., 0x0b or 0x0c
688 __ subl(rax, Immediate(0x0b));
689 __ cmpl(rax, Immediate(0x0c - 0x0b));
690 if (mode_ == ASCII) {
691 BranchOrBacktrack(above, on_no_match);
694 BranchOrBacktrack(below_equal, &done);
695 // Compare original value to 0x2028 and 0x2029, using the already
696 // computed (current_char ^ 0x01 - 0x0b). I.e., check for
697 // 0x201d (0x2028 - 0x0b) or 0x201e.
698 __ subl(rax, Immediate(0x2028 - 0x0b));
699 __ cmpl(rax, Immediate(0x2029 - 0x2028));
700 BranchOrBacktrack(above, on_no_match);
706 if (mode_ != ASCII) {
707 // Table is 128 entries, so all ASCII characters can be tested.
708 __ cmpl(current_character(), Immediate('z'));
709 BranchOrBacktrack(above, on_no_match);
711 __ movq(rbx, ExternalReference::re_word_character_map());
712 ASSERT_EQ(0, word_character_map[0]); // Character '\0' is not a word char.
713 __ testb(Operand(rbx, current_character(), times_1, 0),
714 current_character());
715 BranchOrBacktrack(zero, on_no_match);
720 if (mode_ != ASCII) {
721 // Table is 128 entries, so all ASCII characters can be tested.
722 __ cmpl(current_character(), Immediate('z'));
725 __ movq(rbx, ExternalReference::re_word_character_map());
726 ASSERT_EQ(0, word_character_map[0]); // Character '\0' is not a word char.
727 __ testb(Operand(rbx, current_character(), times_1, 0),
728 current_character());
729 BranchOrBacktrack(not_zero, on_no_match);
730 if (mode_ != ASCII) {
737 // Match any character.
739 // No custom implementation (yet): s(UC16), S(UC16).
746 void RegExpMacroAssemblerX64::Fail() {
747 ASSERT(FAILURE == 0); // Return value for failure is zero.
749 __ jmp(&exit_label_);
753 Handle<HeapObject> RegExpMacroAssemblerX64::GetCode(Handle<String> source) {
754 // Finalize code - write the entry point code now we know how many
755 // registers we need.
757 __ bind(&entry_label_);
759 // Tell the system that we have a stack frame. Because the type is MANUAL, no
761 FrameScope scope(&masm_, StackFrame::MANUAL);
763 // Actually emit code to start a new stack frame.
766 // Save parameters and callee-save registers. Order here should correspond
767 // to order of kBackup_ebx etc.
769 // MSVC passes arguments in rcx, rdx, r8, r9, with backing stack slots.
770 // Store register parameters in pre-allocated stack slots,
771 __ movq(Operand(rbp, kInputString), rcx);
772 __ movq(Operand(rbp, kStartIndex), rdx); // Passed as int32 in edx.
773 __ movq(Operand(rbp, kInputStart), r8);
774 __ movq(Operand(rbp, kInputEnd), r9);
775 // Callee-save on Win64.
780 // GCC passes arguments in rdi, rsi, rdx, rcx, r8, r9 (and then on stack).
781 // Push register parameters on stack for reference.
782 ASSERT_EQ(kInputString, -1 * kPointerSize);
783 ASSERT_EQ(kStartIndex, -2 * kPointerSize);
784 ASSERT_EQ(kInputStart, -3 * kPointerSize);
785 ASSERT_EQ(kInputEnd, -4 * kPointerSize);
786 ASSERT_EQ(kRegisterOutput, -5 * kPointerSize);
787 ASSERT_EQ(kStackHighEnd, -6 * kPointerSize);
795 __ push(rbx); // Callee-save
798 __ push(Immediate(0)); // Make room for "at start" constant.
800 // Check if we have space on the stack for registers.
801 Label stack_limit_hit;
804 ExternalReference stack_limit =
805 ExternalReference::address_of_stack_limit(masm_.isolate());
807 __ movq(kScratchRegister, stack_limit);
808 __ subq(rcx, Operand(kScratchRegister, 0));
809 // Handle it if the stack pointer is already below the stack limit.
810 __ j(below_equal, &stack_limit_hit);
811 // Check if there is room for the variable number of registers above
813 __ cmpq(rcx, Immediate(num_registers_ * kPointerSize));
814 __ j(above_equal, &stack_ok);
815 // Exit with OutOfMemory exception. There is not enough space on the stack
816 // for our working registers.
817 __ Set(rax, EXCEPTION);
818 __ jmp(&exit_label_);
820 __ bind(&stack_limit_hit);
821 __ Move(code_object_pointer(), masm_.CodeObject());
822 CallCheckStackGuardState(); // Preserves no registers beside rbp and rsp.
824 // If returned value is non-zero, we exit with the returned value as result.
825 __ j(not_zero, &exit_label_);
829 // Allocate space on stack for registers.
830 __ subq(rsp, Immediate(num_registers_ * kPointerSize));
831 // Load string length.
832 __ movq(rsi, Operand(rbp, kInputEnd));
833 // Load input position.
834 __ movq(rdi, Operand(rbp, kInputStart));
835 // Set up rdi to be negative offset from string end.
837 // Set rax to address of char before start of the string
838 // (effectively string position -1).
839 __ movq(rbx, Operand(rbp, kStartIndex));
842 __ lea(rax, Operand(rdi, rbx, times_2, -char_size()));
844 __ lea(rax, Operand(rdi, rbx, times_1, -char_size()));
846 // Store this value in a local variable, for use when clearing
847 // position registers.
848 __ movq(Operand(rbp, kInputStartMinusOne), rax);
850 if (num_saved_registers_ > 0) {
851 // Fill saved registers with initial value = start offset - 1
852 // Fill in stack push order, to avoid accessing across an unwritten
853 // page (a problem on Windows).
854 __ Set(rcx, kRegisterZero);
857 __ movq(Operand(rbp, rcx, times_1, 0), rax);
858 __ subq(rcx, Immediate(kPointerSize));
860 Immediate(kRegisterZero - num_saved_registers_ * kPointerSize));
861 __ j(greater, &init_loop);
863 // Ensure that we have written to each stack page, in order. Skipping a page
864 // on Windows can cause segmentation faults. Assuming page size is 4k.
865 const int kPageSize = 4096;
866 const int kRegistersPerPage = kPageSize / kPointerSize;
867 for (int i = num_saved_registers_ + kRegistersPerPage - 1;
869 i += kRegistersPerPage) {
870 __ movq(register_location(i), rax); // One write every page.
873 // Initialize backtrack stack pointer.
874 __ movq(backtrack_stackpointer(), Operand(rbp, kStackHighEnd));
875 // Initialize code object pointer.
876 __ Move(code_object_pointer(), masm_.CodeObject());
877 // Load previous char as initial value of current-character.
879 __ cmpb(Operand(rbp, kStartIndex), Immediate(0));
880 __ j(equal, &at_start);
881 LoadCurrentCharacterUnchecked(-1, 1); // Load previous char.
882 __ jmp(&start_label_);
884 __ Set(current_character(), '\n');
885 __ jmp(&start_label_);
889 if (success_label_.is_linked()) {
890 // Save captures when successful.
891 __ bind(&success_label_);
892 if (num_saved_registers_ > 0) {
893 // copy captures to output
894 __ movq(rdx, Operand(rbp, kStartIndex));
895 __ movq(rbx, Operand(rbp, kRegisterOutput));
896 __ movq(rcx, Operand(rbp, kInputEnd));
897 __ subq(rcx, Operand(rbp, kInputStart));
899 __ lea(rcx, Operand(rcx, rdx, times_2, 0));
903 for (int i = 0; i < num_saved_registers_; i++) {
904 __ movq(rax, register_location(i));
905 __ addq(rax, rcx); // Convert to index from start, not end.
907 __ sar(rax, Immediate(1)); // Convert byte index to character index.
909 __ movl(Operand(rbx, i * kIntSize), rax);
912 __ Set(rax, SUCCESS);
915 // Exit and return rax
916 __ bind(&exit_label_);
919 // Restore callee save registers.
920 __ lea(rsp, Operand(rbp, kLastCalleeSaveRegister));
926 // Restore callee save register.
927 __ movq(rbx, Operand(rbp, kBackup_rbx));
931 // Exit function frame, restore previous one.
935 // Backtrack code (branch target for conditional backtracks).
936 if (backtrack_label_.is_linked()) {
937 __ bind(&backtrack_label_);
941 Label exit_with_exception;
944 if (check_preempt_label_.is_linked()) {
945 SafeCallTarget(&check_preempt_label_);
947 __ push(backtrack_stackpointer());
950 CallCheckStackGuardState();
952 // If returning non-zero, we should end execution with the given
953 // result as return value.
954 __ j(not_zero, &exit_label_);
956 // Restore registers.
957 __ Move(code_object_pointer(), masm_.CodeObject());
959 __ pop(backtrack_stackpointer());
960 // String might have moved: Reload esi from frame.
961 __ movq(rsi, Operand(rbp, kInputEnd));
965 // Backtrack stack overflow code.
966 if (stack_overflow_label_.is_linked()) {
967 SafeCallTarget(&stack_overflow_label_);
968 // Reached if the backtrack-stack limit has been hit.
971 // Save registers before calling C function
973 // Callee-save in Microsoft 64-bit ABI, but not in AMD64 ABI.
978 // Call GrowStack(backtrack_stackpointer())
979 static const int num_arguments = 3;
980 __ PrepareCallCFunction(num_arguments);
982 // Microsoft passes parameters in rcx, rdx, r8.
983 // First argument, backtrack stackpointer, is already in rcx.
984 __ lea(rdx, Operand(rbp, kStackHighEnd)); // Second argument
985 __ LoadAddress(r8, ExternalReference::isolate_address());
987 // AMD64 ABI passes parameters in rdi, rsi, rdx.
988 __ movq(rdi, backtrack_stackpointer()); // First argument.
989 __ lea(rsi, Operand(rbp, kStackHighEnd)); // Second argument.
990 __ LoadAddress(rdx, ExternalReference::isolate_address());
992 ExternalReference grow_stack =
993 ExternalReference::re_grow_stack(masm_.isolate());
994 __ CallCFunction(grow_stack, num_arguments);
995 // If return NULL, we have failed to grow the stack, and
996 // must exit with a stack-overflow exception.
998 __ j(equal, &exit_with_exception);
999 // Otherwise use return value as new stack pointer.
1000 __ movq(backtrack_stackpointer(), rax);
1001 // Restore saved registers and continue.
1002 __ Move(code_object_pointer(), masm_.CodeObject());
1010 if (exit_with_exception.is_linked()) {
1011 // If any of the code above needed to exit with an exception.
1012 __ bind(&exit_with_exception);
1013 // Exit with Result EXCEPTION(-1) to signal thrown exception.
1014 __ Set(rax, EXCEPTION);
1015 __ jmp(&exit_label_);
1018 FixupCodeRelativePositions();
1021 masm_.GetCode(&code_desc);
1022 Isolate* isolate = ISOLATE;
1023 Handle<Code> code = isolate->factory()->NewCode(
1024 code_desc, Code::ComputeFlags(Code::REGEXP),
1025 masm_.CodeObject());
1026 PROFILE(isolate, RegExpCodeCreateEvent(*code, *source));
1027 return Handle<HeapObject>::cast(code);
1031 void RegExpMacroAssemblerX64::GoTo(Label* to) {
1032 BranchOrBacktrack(no_condition, to);
1036 void RegExpMacroAssemblerX64::IfRegisterGE(int reg,
1039 __ cmpq(register_location(reg), Immediate(comparand));
1040 BranchOrBacktrack(greater_equal, if_ge);
1044 void RegExpMacroAssemblerX64::IfRegisterLT(int reg,
1047 __ cmpq(register_location(reg), Immediate(comparand));
1048 BranchOrBacktrack(less, if_lt);
1052 void RegExpMacroAssemblerX64::IfRegisterEqPos(int reg,
1054 __ cmpq(rdi, register_location(reg));
1055 BranchOrBacktrack(equal, if_eq);
1059 RegExpMacroAssembler::IrregexpImplementation
1060 RegExpMacroAssemblerX64::Implementation() {
1061 return kX64Implementation;
1065 void RegExpMacroAssemblerX64::LoadCurrentCharacter(int cp_offset,
1066 Label* on_end_of_input,
1069 ASSERT(cp_offset >= -1); // ^ and \b can look behind one character.
1070 ASSERT(cp_offset < (1<<30)); // Be sane! (And ensure negation works)
1072 CheckPosition(cp_offset + characters - 1, on_end_of_input);
1074 LoadCurrentCharacterUnchecked(cp_offset, characters);
1078 void RegExpMacroAssemblerX64::PopCurrentPosition() {
1083 void RegExpMacroAssemblerX64::PopRegister(int register_index) {
1085 __ movq(register_location(register_index), rax);
1089 void RegExpMacroAssemblerX64::PushBacktrack(Label* label) {
1095 void RegExpMacroAssemblerX64::PushCurrentPosition() {
1100 void RegExpMacroAssemblerX64::PushRegister(int register_index,
1101 StackCheckFlag check_stack_limit) {
1102 __ movq(rax, register_location(register_index));
1104 if (check_stack_limit) CheckStackLimit();
1108 void RegExpMacroAssemblerX64::ReadCurrentPositionFromRegister(int reg) {
1109 __ movq(rdi, register_location(reg));
1113 void RegExpMacroAssemblerX64::ReadStackPointerFromRegister(int reg) {
1114 __ movq(backtrack_stackpointer(), register_location(reg));
1115 __ addq(backtrack_stackpointer(), Operand(rbp, kStackHighEnd));
1119 void RegExpMacroAssemblerX64::SetCurrentPositionFromEnd(int by) {
1120 Label after_position;
1121 __ cmpq(rdi, Immediate(-by * char_size()));
1122 __ j(greater_equal, &after_position, Label::kNear);
1123 __ movq(rdi, Immediate(-by * char_size()));
1124 // On RegExp code entry (where this operation is used), the character before
1125 // the current position is expected to be already loaded.
1126 // We have advanced the position, so it's safe to read backwards.
1127 LoadCurrentCharacterUnchecked(-1, 1);
1128 __ bind(&after_position);
1132 void RegExpMacroAssemblerX64::SetRegister(int register_index, int to) {
1133 ASSERT(register_index >= num_saved_registers_); // Reserved for positions!
1134 __ movq(register_location(register_index), Immediate(to));
1138 void RegExpMacroAssemblerX64::Succeed() {
1139 __ jmp(&success_label_);
1143 void RegExpMacroAssemblerX64::WriteCurrentPositionToRegister(int reg,
1145 if (cp_offset == 0) {
1146 __ movq(register_location(reg), rdi);
1148 __ lea(rax, Operand(rdi, cp_offset * char_size()));
1149 __ movq(register_location(reg), rax);
1154 void RegExpMacroAssemblerX64::ClearRegisters(int reg_from, int reg_to) {
1155 ASSERT(reg_from <= reg_to);
1156 __ movq(rax, Operand(rbp, kInputStartMinusOne));
1157 for (int reg = reg_from; reg <= reg_to; reg++) {
1158 __ movq(register_location(reg), rax);
1163 void RegExpMacroAssemblerX64::WriteStackPointerToRegister(int reg) {
1164 __ movq(rax, backtrack_stackpointer());
1165 __ subq(rax, Operand(rbp, kStackHighEnd));
1166 __ movq(register_location(reg), rax);
1172 void RegExpMacroAssemblerX64::CallCheckStackGuardState() {
1173 // This function call preserves no register values. Caller should
1174 // store anything volatile in a C call or overwritten by this function.
1175 static const int num_arguments = 3;
1176 __ PrepareCallCFunction(num_arguments);
1178 // Second argument: Code* of self. (Do this before overwriting r8).
1179 __ movq(rdx, code_object_pointer());
1180 // Third argument: RegExp code frame pointer.
1182 // First argument: Next address on the stack (will be address of
1184 __ lea(rcx, Operand(rsp, -kPointerSize));
1186 // Third argument: RegExp code frame pointer.
1188 // Second argument: Code* of self.
1189 __ movq(rsi, code_object_pointer());
1190 // First argument: Next address on the stack (will be address of
1192 __ lea(rdi, Operand(rsp, -kPointerSize));
1194 ExternalReference stack_check =
1195 ExternalReference::re_check_stack_guard_state(masm_.isolate());
1196 __ CallCFunction(stack_check, num_arguments);
1200 // Helper function for reading a value out of a stack frame.
1201 template <typename T>
1202 static T& frame_entry(Address re_frame, int frame_offset) {
1203 return reinterpret_cast<T&>(Memory::int32_at(re_frame + frame_offset));
1207 int RegExpMacroAssemblerX64::CheckStackGuardState(Address* return_address,
1210 Isolate* isolate = frame_entry<Isolate*>(re_frame, kIsolate);
1211 ASSERT(isolate == Isolate::Current());
1212 if (isolate->stack_guard()->IsStackOverflow()) {
1213 isolate->StackOverflow();
1217 // If not real stack overflow the stack guard was used to interrupt
1218 // execution for another purpose.
1220 // If this is a direct call from JavaScript retry the RegExp forcing the call
1221 // through the runtime system. Currently the direct call cannot handle a GC.
1222 if (frame_entry<int>(re_frame, kDirectCall) == 1) {
1226 // Prepare for possible GC.
1227 HandleScope handles(isolate);
1228 Handle<Code> code_handle(re_code);
1230 Handle<String> subject(frame_entry<String*>(re_frame, kInputString));
1233 bool is_ascii = subject->IsAsciiRepresentationUnderneath();
1235 ASSERT(re_code->instruction_start() <= *return_address);
1236 ASSERT(*return_address <=
1237 re_code->instruction_start() + re_code->instruction_size());
1239 MaybeObject* result = Execution::HandleStackGuardInterrupt(isolate);
1241 if (*code_handle != re_code) { // Return address no longer valid
1242 intptr_t delta = code_handle->address() - re_code->address();
1243 // Overwrite the return address on the stack.
1244 *return_address += delta;
1247 if (result->IsException()) {
1251 Handle<String> subject_tmp = subject;
1252 int slice_offset = 0;
1254 // Extract the underlying string and the slice offset.
1255 if (StringShape(*subject_tmp).IsCons()) {
1256 subject_tmp = Handle<String>(ConsString::cast(*subject_tmp)->first());
1257 } else if (StringShape(*subject_tmp).IsSliced()) {
1258 SlicedString* slice = SlicedString::cast(*subject_tmp);
1259 subject_tmp = Handle<String>(slice->parent());
1260 slice_offset = slice->offset();
1263 // String might have changed.
1264 if (subject_tmp->IsAsciiRepresentation() != is_ascii) {
1265 // If we changed between an ASCII and an UC16 string, the specialized
1266 // code cannot be used, and we need to restart regexp matching from
1267 // scratch (including, potentially, compiling a new version of the code).
1271 // Otherwise, the content of the string might have moved. It must still
1272 // be a sequential or external string with the same content.
1273 // Update the start and end pointers in the stack frame to the current
1274 // location (whether it has actually moved or not).
1275 ASSERT(StringShape(*subject_tmp).IsSequential() ||
1276 StringShape(*subject_tmp).IsExternal());
1278 // The original start address of the characters to match.
1279 const byte* start_address = frame_entry<const byte*>(re_frame, kInputStart);
1281 // Find the current start address of the same character at the current string
1283 int start_index = frame_entry<int>(re_frame, kStartIndex);
1284 const byte* new_address = StringCharacterPosition(*subject_tmp,
1285 start_index + slice_offset);
1287 if (start_address != new_address) {
1288 // If there is a difference, update the object pointer and start and end
1289 // addresses in the RegExp stack frame to match the new value.
1290 const byte* end_address = frame_entry<const byte* >(re_frame, kInputEnd);
1291 int byte_length = static_cast<int>(end_address - start_address);
1292 frame_entry<const String*>(re_frame, kInputString) = *subject;
1293 frame_entry<const byte*>(re_frame, kInputStart) = new_address;
1294 frame_entry<const byte*>(re_frame, kInputEnd) = new_address + byte_length;
1295 } else if (frame_entry<const String*>(re_frame, kInputString) != *subject) {
1296 // Subject string might have been a ConsString that underwent
1297 // short-circuiting during GC. That will not change start_address but
1298 // will change pointer inside the subject handle.
1299 frame_entry<const String*>(re_frame, kInputString) = *subject;
1306 Operand RegExpMacroAssemblerX64::register_location(int register_index) {
1307 ASSERT(register_index < (1<<30));
1308 if (num_registers_ <= register_index) {
1309 num_registers_ = register_index + 1;
1311 return Operand(rbp, kRegisterZero - register_index * kPointerSize);
1315 void RegExpMacroAssemblerX64::CheckPosition(int cp_offset,
1316 Label* on_outside_input) {
1317 __ cmpl(rdi, Immediate(-cp_offset * char_size()));
1318 BranchOrBacktrack(greater_equal, on_outside_input);
1322 void RegExpMacroAssemblerX64::BranchOrBacktrack(Condition condition,
1324 if (condition < 0) { // No condition
1333 __ j(condition, &backtrack_label_);
1336 __ j(condition, to);
1340 void RegExpMacroAssemblerX64::SafeCall(Label* to) {
1345 void RegExpMacroAssemblerX64::SafeCallTarget(Label* label) {
1347 __ subq(Operand(rsp, 0), code_object_pointer());
1351 void RegExpMacroAssemblerX64::SafeReturn() {
1352 __ addq(Operand(rsp, 0), code_object_pointer());
1357 void RegExpMacroAssemblerX64::Push(Register source) {
1358 ASSERT(!source.is(backtrack_stackpointer()));
1359 // Notice: This updates flags, unlike normal Push.
1360 __ subq(backtrack_stackpointer(), Immediate(kIntSize));
1361 __ movl(Operand(backtrack_stackpointer(), 0), source);
1365 void RegExpMacroAssemblerX64::Push(Immediate value) {
1366 // Notice: This updates flags, unlike normal Push.
1367 __ subq(backtrack_stackpointer(), Immediate(kIntSize));
1368 __ movl(Operand(backtrack_stackpointer(), 0), value);
1372 void RegExpMacroAssemblerX64::FixupCodeRelativePositions() {
1373 for (int i = 0, n = code_relative_fixup_positions_.length(); i < n; i++) {
1374 int position = code_relative_fixup_positions_[i];
1375 // The position succeeds a relative label offset from position.
1376 // Patch the relative offset to be relative to the Code object pointer
1378 int patch_position = position - kIntSize;
1379 int offset = masm_.long_at(patch_position);
1380 masm_.long_at_put(patch_position,
1386 code_relative_fixup_positions_.Clear();
1390 void RegExpMacroAssemblerX64::Push(Label* backtrack_target) {
1391 __ subq(backtrack_stackpointer(), Immediate(kIntSize));
1392 __ movl(Operand(backtrack_stackpointer(), 0), backtrack_target);
1393 MarkPositionForCodeRelativeFixup();
1397 void RegExpMacroAssemblerX64::Pop(Register target) {
1398 ASSERT(!target.is(backtrack_stackpointer()));
1399 __ movsxlq(target, Operand(backtrack_stackpointer(), 0));
1400 // Notice: This updates flags, unlike normal Pop.
1401 __ addq(backtrack_stackpointer(), Immediate(kIntSize));
1405 void RegExpMacroAssemblerX64::Drop() {
1406 __ addq(backtrack_stackpointer(), Immediate(kIntSize));
1410 void RegExpMacroAssemblerX64::CheckPreemption() {
1411 // Check for preemption.
1413 ExternalReference stack_limit =
1414 ExternalReference::address_of_stack_limit(masm_.isolate());
1415 __ load_rax(stack_limit);
1417 __ j(above, &no_preempt);
1419 SafeCall(&check_preempt_label_);
1421 __ bind(&no_preempt);
1425 void RegExpMacroAssemblerX64::CheckStackLimit() {
1426 Label no_stack_overflow;
1427 ExternalReference stack_limit =
1428 ExternalReference::address_of_regexp_stack_limit(masm_.isolate());
1429 __ load_rax(stack_limit);
1430 __ cmpq(backtrack_stackpointer(), rax);
1431 __ j(above, &no_stack_overflow);
1433 SafeCall(&stack_overflow_label_);
1435 __ bind(&no_stack_overflow);
1439 void RegExpMacroAssemblerX64::LoadCurrentCharacterUnchecked(int cp_offset,
1441 if (mode_ == ASCII) {
1442 if (characters == 4) {
1443 __ movl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
1444 } else if (characters == 2) {
1445 __ movzxwl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
1447 ASSERT(characters == 1);
1448 __ movzxbl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
1451 ASSERT(mode_ == UC16);
1452 if (characters == 2) {
1453 __ movl(current_character(),
1454 Operand(rsi, rdi, times_1, cp_offset * sizeof(uc16)));
1456 ASSERT(characters == 1);
1457 __ movzxwl(current_character(),
1458 Operand(rsi, rdi, times_1, cp_offset * sizeof(uc16)));
1465 #endif // V8_INTERPRETED_REGEXP
1467 }} // namespace v8::internal
1469 #endif // V8_TARGET_ARCH_X64