v8  3.14.5(node0.10.28)
V8 is Google's open source JavaScript engine
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
regexp-macro-assembler-x64.cc
Go to the documentation of this file.
1 // Copyright 2012 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
4 // met:
5 //
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.
15 //
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.
27 
28 #include "v8.h"
29 
30 #if defined(V8_TARGET_ARCH_X64)
31 
32 #include "serialize.h"
33 #include "unicode.h"
34 #include "log.h"
35 #include "regexp-stack.h"
36 #include "macro-assembler.h"
37 #include "regexp-macro-assembler.h"
39 
40 namespace v8 {
41 namespace internal {
42 
43 #ifndef V8_INTERPRETED_REGEXP
44 
45 /*
46  * This assembler uses the following register assignment convention
47  * - rdx : Currently loaded character(s) as ASCII or UC16. Must be loaded
48  * using LoadCurrentCharacter before using any of the dispatch methods.
49  * Temporarily stores the index of capture start after a matching pass
50  * for a global regexp.
51  * - rdi : Current position in input, as negative offset from end of string.
52  * Please notice that this is the byte offset, not the character
53  * offset! Is always a 32-bit signed (negative) offset, but must be
54  * maintained sign-extended to 64 bits, since it is used as index.
55  * - rsi : End of input (points to byte after last character in input),
56  * so that rsi+rdi points to the current character.
57  * - rbp : Frame pointer. Used to access arguments, local variables and
58  * RegExp registers.
59  * - rsp : Points to tip of C stack.
60  * - rcx : Points to tip of backtrack stack. The backtrack stack contains
61  * only 32-bit values. Most are offsets from some base (e.g., character
62  * positions from end of string or code location from Code* pointer).
63  * - r8 : Code object pointer. Used to convert between absolute and
64  * code-object-relative addresses.
65  *
66  * The registers rax, rbx, r9 and r11 are free to use for computations.
67  * If changed to use r12+, they should be saved as callee-save registers.
68  * The macro assembler special registers r12 and r13 (kSmiConstantRegister,
69  * kRootRegister) aren't special during execution of RegExp code (they don't
70  * hold the values assumed when creating JS code), so no Smi or Root related
71  * macro operations can be used.
72  *
73  * Each call to a C++ method should retain these registers.
74  *
75  * The stack will have the following content, in some order, indexable from the
76  * frame pointer (see, e.g., kStackHighEnd):
77  * - Isolate* isolate (address of the current isolate)
78  * - direct_call (if 1, direct call from JavaScript code, if 0 call
79  * through the runtime system)
80  * - stack_area_base (high end of the memory area to use as
81  * backtracking stack)
82  * - capture array size (may fit multiple sets of matches)
83  * - int* capture_array (int[num_saved_registers_], for output).
84  * - end of input (address of end of string)
85  * - start of input (address of first character in string)
86  * - start index (character index of start)
87  * - String* input_string (input string)
88  * - return address
89  * - backup of callee save registers (rbx, possibly rsi and rdi).
90  * - success counter (only useful for global regexp to count matches)
91  * - Offset of location before start of input (effectively character
92  * position -1). Used to initialize capture registers to a non-position.
93  * - At start of string (if 1, we are starting at the start of the
94  * string, otherwise 0)
95  * - register 0 rbp[-n] (Only positions must be stored in the first
96  * - register 1 rbp[-n-8] num_saved_registers_ registers)
97  * - ...
98  *
99  * The first num_saved_registers_ registers are initialized to point to
100  * "character -1" in the string (i.e., char_size() bytes before the first
101  * character of the string). The remaining registers starts out uninitialized.
102  *
103  * The first seven values must be provided by the calling code by
104  * calling the code's entry address cast to a function pointer with the
105  * following signature:
106  * int (*match)(String* input_string,
107  * int start_index,
108  * Address start,
109  * Address end,
110  * int* capture_output_array,
111  * bool at_start,
112  * byte* stack_area_base,
113  * bool direct_call)
114  */
115 
116 #define __ ACCESS_MASM((&masm_))
117 
119  Mode mode,
120  int registers_to_save,
121  Zone* zone)
122  : NativeRegExpMacroAssembler(zone),
123  masm_(Isolate::Current(), NULL, kRegExpCodeSize),
124  no_root_array_scope_(&masm_),
125  code_relative_fixup_positions_(4, zone),
126  mode_(mode),
127  num_registers_(registers_to_save),
128  num_saved_registers_(registers_to_save),
129  entry_label_(),
130  start_label_(),
131  success_label_(),
132  backtrack_label_(),
133  exit_label_() {
134  ASSERT_EQ(0, registers_to_save % 2);
135  __ jmp(&entry_label_); // We'll write the entry code when we know more.
136  __ bind(&start_label_); // And then continue from here.
137 }
138 
139 
140 RegExpMacroAssemblerX64::~RegExpMacroAssemblerX64() {
141  // Unuse labels in case we throw away the assembler without calling GetCode.
142  entry_label_.Unuse();
143  start_label_.Unuse();
144  success_label_.Unuse();
145  backtrack_label_.Unuse();
146  exit_label_.Unuse();
147  check_preempt_label_.Unuse();
148  stack_overflow_label_.Unuse();
149 }
150 
151 
152 int RegExpMacroAssemblerX64::stack_limit_slack() {
153  return RegExpStack::kStackLimitSlack;
154 }
155 
156 
157 void RegExpMacroAssemblerX64::AdvanceCurrentPosition(int by) {
158  if (by != 0) {
159  __ addq(rdi, Immediate(by * char_size()));
160  }
161 }
162 
163 
164 void RegExpMacroAssemblerX64::AdvanceRegister(int reg, int by) {
165  ASSERT(reg >= 0);
166  ASSERT(reg < num_registers_);
167  if (by != 0) {
168  __ addq(register_location(reg), Immediate(by));
169  }
170 }
171 
172 
173 void RegExpMacroAssemblerX64::Backtrack() {
174  CheckPreemption();
175  // Pop Code* offset from backtrack stack, add Code* and jump to location.
176  Pop(rbx);
177  __ addq(rbx, code_object_pointer());
178  __ jmp(rbx);
179 }
180 
181 
182 void RegExpMacroAssemblerX64::Bind(Label* label) {
183  __ bind(label);
184 }
185 
186 
187 void RegExpMacroAssemblerX64::CheckCharacter(uint32_t c, Label* on_equal) {
188  __ cmpl(current_character(), Immediate(c));
189  BranchOrBacktrack(equal, on_equal);
190 }
191 
192 
193 void RegExpMacroAssemblerX64::CheckCharacterGT(uc16 limit, Label* on_greater) {
194  __ cmpl(current_character(), Immediate(limit));
195  BranchOrBacktrack(greater, on_greater);
196 }
197 
198 
199 void RegExpMacroAssemblerX64::CheckAtStart(Label* on_at_start) {
200  Label not_at_start;
201  // Did we start the match at the start of the string at all?
202  __ cmpl(Operand(rbp, kStartIndex), Immediate(0));
203  BranchOrBacktrack(not_equal, &not_at_start);
204  // If we did, are we still at the start of the input?
205  __ lea(rax, Operand(rsi, rdi, times_1, 0));
206  __ cmpq(rax, Operand(rbp, kInputStart));
207  BranchOrBacktrack(equal, on_at_start);
208  __ bind(&not_at_start);
209 }
210 
211 
212 void RegExpMacroAssemblerX64::CheckNotAtStart(Label* on_not_at_start) {
213  // Did we start the match at the start of the string at all?
214  __ cmpl(Operand(rbp, kStartIndex), Immediate(0));
215  BranchOrBacktrack(not_equal, on_not_at_start);
216  // If we did, are we still at the start of the input?
217  __ lea(rax, Operand(rsi, rdi, times_1, 0));
218  __ cmpq(rax, Operand(rbp, kInputStart));
219  BranchOrBacktrack(not_equal, on_not_at_start);
220 }
221 
222 
223 void RegExpMacroAssemblerX64::CheckCharacterLT(uc16 limit, Label* on_less) {
224  __ cmpl(current_character(), Immediate(limit));
225  BranchOrBacktrack(less, on_less);
226 }
227 
228 
229 void RegExpMacroAssemblerX64::CheckCharacters(Vector<const uc16> str,
230  int cp_offset,
231  Label* on_failure,
232  bool check_end_of_string) {
233 #ifdef DEBUG
234  // If input is ASCII, don't even bother calling here if the string to
235  // match contains a non-ASCII character.
236  if (mode_ == ASCII) {
237  ASSERT(String::IsAscii(str.start(), str.length()));
238  }
239 #endif
240  int byte_length = str.length() * char_size();
241  int byte_offset = cp_offset * char_size();
242  if (check_end_of_string) {
243  // Check that there are at least str.length() characters left in the input.
244  __ cmpl(rdi, Immediate(-(byte_offset + byte_length)));
245  BranchOrBacktrack(greater, on_failure);
246  }
247 
248  if (on_failure == NULL) {
249  // Instead of inlining a backtrack, (re)use the global backtrack target.
250  on_failure = &backtrack_label_;
251  }
252 
253  // Do one character test first to minimize loading for the case that
254  // we don't match at all (loading more than one character introduces that
255  // chance of reading unaligned and reading across cache boundaries).
256  // If the first character matches, expect a larger chance of matching the
257  // string, and start loading more characters at a time.
258  if (mode_ == ASCII) {
259  __ cmpb(Operand(rsi, rdi, times_1, byte_offset),
260  Immediate(static_cast<int8_t>(str[0])));
261  } else {
262  // Don't use 16-bit immediate. The size changing prefix throws off
263  // pre-decoding.
264  __ movzxwl(rax,
265  Operand(rsi, rdi, times_1, byte_offset));
266  __ cmpl(rax, Immediate(static_cast<int32_t>(str[0])));
267  }
268  BranchOrBacktrack(not_equal, on_failure);
269 
270  __ lea(rbx, Operand(rsi, rdi, times_1, 0));
271  for (int i = 1, n = str.length(); i < n; ) {
272  if (mode_ == ASCII) {
273  if (i + 8 <= n) {
274  uint64_t combined_chars =
275  (static_cast<uint64_t>(str[i + 0]) << 0) ||
276  (static_cast<uint64_t>(str[i + 1]) << 8) ||
277  (static_cast<uint64_t>(str[i + 2]) << 16) ||
278  (static_cast<uint64_t>(str[i + 3]) << 24) ||
279  (static_cast<uint64_t>(str[i + 4]) << 32) ||
280  (static_cast<uint64_t>(str[i + 5]) << 40) ||
281  (static_cast<uint64_t>(str[i + 6]) << 48) ||
282  (static_cast<uint64_t>(str[i + 7]) << 56);
283  __ movq(rax, combined_chars, RelocInfo::NONE);
284  __ cmpq(rax, Operand(rbx, byte_offset + i));
285  i += 8;
286  } else if (i + 4 <= n) {
287  uint32_t combined_chars =
288  (static_cast<uint32_t>(str[i + 0]) << 0) ||
289  (static_cast<uint32_t>(str[i + 1]) << 8) ||
290  (static_cast<uint32_t>(str[i + 2]) << 16) ||
291  (static_cast<uint32_t>(str[i + 3]) << 24);
292  __ cmpl(Operand(rbx, byte_offset + i), Immediate(combined_chars));
293  i += 4;
294  } else {
295  __ cmpb(Operand(rbx, byte_offset + i),
296  Immediate(static_cast<int8_t>(str[i])));
297  i++;
298  }
299  } else {
300  ASSERT(mode_ == UC16);
301  if (i + 4 <= n) {
302  uint64_t combined_chars = *reinterpret_cast<const uint64_t*>(&str[i]);
303  __ movq(rax, combined_chars, RelocInfo::NONE);
304  __ cmpq(rax,
305  Operand(rsi, rdi, times_1, byte_offset + i * sizeof(uc16)));
306  i += 4;
307  } else if (i + 2 <= n) {
308  uint32_t combined_chars = *reinterpret_cast<const uint32_t*>(&str[i]);
309  __ cmpl(Operand(rsi, rdi, times_1, byte_offset + i * sizeof(uc16)),
310  Immediate(combined_chars));
311  i += 2;
312  } else {
313  __ movzxwl(rax,
314  Operand(rsi, rdi, times_1, byte_offset + i * sizeof(uc16)));
315  __ cmpl(rax, Immediate(str[i]));
316  i++;
317  }
318  }
319  BranchOrBacktrack(not_equal, on_failure);
320  }
321 }
322 
323 
324 void RegExpMacroAssemblerX64::CheckGreedyLoop(Label* on_equal) {
325  Label fallthrough;
326  __ cmpl(rdi, Operand(backtrack_stackpointer(), 0));
327  __ j(not_equal, &fallthrough);
328  Drop();
329  BranchOrBacktrack(no_condition, on_equal);
330  __ bind(&fallthrough);
331 }
332 
333 
334 void RegExpMacroAssemblerX64::CheckNotBackReferenceIgnoreCase(
335  int start_reg,
336  Label* on_no_match) {
337  Label fallthrough;
338  __ movq(rdx, register_location(start_reg)); // Offset of start of capture
339  __ movq(rbx, register_location(start_reg + 1)); // Offset of end of capture
340  __ subq(rbx, rdx); // Length of capture.
341 
342  // -----------------------
343  // rdx = Start offset of capture.
344  // rbx = Length of capture
345 
346  // If length is negative, this code will fail (it's a symptom of a partial or
347  // illegal capture where start of capture after end of capture).
348  // This must not happen (no back-reference can reference a capture that wasn't
349  // closed before in the reg-exp, and we must not generate code that can cause
350  // this condition).
351 
352  // If length is zero, either the capture is empty or it is nonparticipating.
353  // In either case succeed immediately.
354  __ j(equal, &fallthrough);
355 
356  // -----------------------
357  // rdx - Start of capture
358  // rbx - length of capture
359  // Check that there are sufficient characters left in the input.
360  __ movl(rax, rdi);
361  __ addl(rax, rbx);
362  BranchOrBacktrack(greater, on_no_match);
363 
364  if (mode_ == ASCII) {
365  Label loop_increment;
366  if (on_no_match == NULL) {
367  on_no_match = &backtrack_label_;
368  }
369 
370  __ lea(r9, Operand(rsi, rdx, times_1, 0));
371  __ lea(r11, Operand(rsi, rdi, times_1, 0));
372  __ addq(rbx, r9); // End of capture
373  // ---------------------
374  // r11 - current input character address
375  // r9 - current capture character address
376  // rbx - end of capture
377 
378  Label loop;
379  __ bind(&loop);
380  __ movzxbl(rdx, Operand(r9, 0));
381  __ movzxbl(rax, Operand(r11, 0));
382  // al - input character
383  // dl - capture character
384  __ cmpb(rax, rdx);
385  __ j(equal, &loop_increment);
386 
387  // Mismatch, try case-insensitive match (converting letters to lower-case).
388  // I.e., if or-ing with 0x20 makes values equal and in range 'a'-'z', it's
389  // a match.
390  __ or_(rax, Immediate(0x20)); // Convert match character to lower-case.
391  __ or_(rdx, Immediate(0x20)); // Convert capture character to lower-case.
392  __ cmpb(rax, rdx);
393  __ j(not_equal, on_no_match); // Definitely not equal.
394  __ subb(rax, Immediate('a'));
395  __ cmpb(rax, Immediate('z' - 'a'));
396  __ j(above, on_no_match); // Weren't letters anyway.
397 
398  __ bind(&loop_increment);
399  // Increment pointers into match and capture strings.
400  __ addq(r11, Immediate(1));
401  __ addq(r9, Immediate(1));
402  // Compare to end of capture, and loop if not done.
403  __ cmpq(r9, rbx);
404  __ j(below, &loop);
405 
406  // Compute new value of character position after the matched part.
407  __ movq(rdi, r11);
408  __ subq(rdi, rsi);
409  } else {
410  ASSERT(mode_ == UC16);
411  // Save important/volatile registers before calling C function.
412 #ifndef _WIN64
413  // Caller save on Linux and callee save in Windows.
414  __ push(rsi);
415  __ push(rdi);
416 #endif
417  __ push(backtrack_stackpointer());
418 
419  static const int num_arguments = 4;
420  __ PrepareCallCFunction(num_arguments);
421 
422  // Put arguments into parameter registers. Parameters are
423  // Address byte_offset1 - Address captured substring's start.
424  // Address byte_offset2 - Address of current character position.
425  // size_t byte_length - length of capture in bytes(!)
426  // Isolate* isolate
427 #ifdef _WIN64
428  // Compute and set byte_offset1 (start of capture).
429  __ lea(rcx, Operand(rsi, rdx, times_1, 0));
430  // Set byte_offset2.
431  __ lea(rdx, Operand(rsi, rdi, times_1, 0));
432  // Set byte_length.
433  __ movq(r8, rbx);
434  // Isolate.
435  __ LoadAddress(r9, ExternalReference::isolate_address());
436 #else // AMD64 calling convention
437  // Compute byte_offset2 (current position = rsi+rdi).
438  __ lea(rax, Operand(rsi, rdi, times_1, 0));
439  // Compute and set byte_offset1 (start of capture).
440  __ lea(rdi, Operand(rsi, rdx, times_1, 0));
441  // Set byte_offset2.
442  __ movq(rsi, rax);
443  // Set byte_length.
444  __ movq(rdx, rbx);
445  // Isolate.
446  __ LoadAddress(rcx, ExternalReference::isolate_address());
447 #endif
448 
449  { // NOLINT: Can't find a way to open this scope without confusing the
450  // linter.
451  AllowExternalCallThatCantCauseGC scope(&masm_);
452  ExternalReference compare =
453  ExternalReference::re_case_insensitive_compare_uc16(masm_.isolate());
454  __ CallCFunction(compare, num_arguments);
455  }
456 
457  // Restore original values before reacting on result value.
458  __ Move(code_object_pointer(), masm_.CodeObject());
459  __ pop(backtrack_stackpointer());
460 #ifndef _WIN64
461  __ pop(rdi);
462  __ pop(rsi);
463 #endif
464 
465  // Check if function returned non-zero for success or zero for failure.
466  __ testq(rax, rax);
467  BranchOrBacktrack(zero, on_no_match);
468  // On success, increment position by length of capture.
469  // Requires that rbx is callee save (true for both Win64 and AMD64 ABIs).
470  __ addq(rdi, rbx);
471  }
472  __ bind(&fallthrough);
473 }
474 
475 
476 void RegExpMacroAssemblerX64::CheckNotBackReference(
477  int start_reg,
478  Label* on_no_match) {
479  Label fallthrough;
480 
481  // Find length of back-referenced capture.
482  __ movq(rdx, register_location(start_reg));
483  __ movq(rax, register_location(start_reg + 1));
484  __ subq(rax, rdx); // Length to check.
485 
486  // Fail on partial or illegal capture (start of capture after end of capture).
487  // This must not happen (no back-reference can reference a capture that wasn't
488  // closed before in the reg-exp).
489  __ Check(greater_equal, "Invalid capture referenced");
490 
491  // Succeed on empty capture (including non-participating capture)
492  __ j(equal, &fallthrough);
493 
494  // -----------------------
495  // rdx - Start of capture
496  // rax - length of capture
497 
498  // Check that there are sufficient characters left in the input.
499  __ movl(rbx, rdi);
500  __ addl(rbx, rax);
501  BranchOrBacktrack(greater, on_no_match);
502 
503  // Compute pointers to match string and capture string
504  __ lea(rbx, Operand(rsi, rdi, times_1, 0)); // Start of match.
505  __ addq(rdx, rsi); // Start of capture.
506  __ lea(r9, Operand(rdx, rax, times_1, 0)); // End of capture
507 
508  // -----------------------
509  // rbx - current capture character address.
510  // rbx - current input character address .
511  // r9 - end of input to match (capture length after rbx).
512 
513  Label loop;
514  __ bind(&loop);
515  if (mode_ == ASCII) {
516  __ movzxbl(rax, Operand(rdx, 0));
517  __ cmpb(rax, Operand(rbx, 0));
518  } else {
519  ASSERT(mode_ == UC16);
520  __ movzxwl(rax, Operand(rdx, 0));
521  __ cmpw(rax, Operand(rbx, 0));
522  }
523  BranchOrBacktrack(not_equal, on_no_match);
524  // Increment pointers into capture and match string.
525  __ addq(rbx, Immediate(char_size()));
526  __ addq(rdx, Immediate(char_size()));
527  // Check if we have reached end of match area.
528  __ cmpq(rdx, r9);
529  __ j(below, &loop);
530 
531  // Success.
532  // Set current character position to position after match.
533  __ movq(rdi, rbx);
534  __ subq(rdi, rsi);
535 
536  __ bind(&fallthrough);
537 }
538 
539 
540 void RegExpMacroAssemblerX64::CheckNotCharacter(uint32_t c,
541  Label* on_not_equal) {
542  __ cmpl(current_character(), Immediate(c));
543  BranchOrBacktrack(not_equal, on_not_equal);
544 }
545 
546 
547 void RegExpMacroAssemblerX64::CheckCharacterAfterAnd(uint32_t c,
548  uint32_t mask,
549  Label* on_equal) {
550  if (c == 0) {
551  __ testl(current_character(), Immediate(mask));
552  } else {
553  __ movl(rax, Immediate(mask));
554  __ and_(rax, current_character());
555  __ cmpl(rax, Immediate(c));
556  }
557  BranchOrBacktrack(equal, on_equal);
558 }
559 
560 
561 void RegExpMacroAssemblerX64::CheckNotCharacterAfterAnd(uint32_t c,
562  uint32_t mask,
563  Label* on_not_equal) {
564  if (c == 0) {
565  __ testl(current_character(), Immediate(mask));
566  } else {
567  __ movl(rax, Immediate(mask));
568  __ and_(rax, current_character());
569  __ cmpl(rax, Immediate(c));
570  }
571  BranchOrBacktrack(not_equal, on_not_equal);
572 }
573 
574 
575 void RegExpMacroAssemblerX64::CheckNotCharacterAfterMinusAnd(
576  uc16 c,
577  uc16 minus,
578  uc16 mask,
579  Label* on_not_equal) {
580  ASSERT(minus < String::kMaxUtf16CodeUnit);
581  __ lea(rax, Operand(current_character(), -minus));
582  __ and_(rax, Immediate(mask));
583  __ cmpl(rax, Immediate(c));
584  BranchOrBacktrack(not_equal, on_not_equal);
585 }
586 
587 
588 void RegExpMacroAssemblerX64::CheckCharacterInRange(
589  uc16 from,
590  uc16 to,
591  Label* on_in_range) {
592  __ leal(rax, Operand(current_character(), -from));
593  __ cmpl(rax, Immediate(to - from));
594  BranchOrBacktrack(below_equal, on_in_range);
595 }
596 
597 
598 void RegExpMacroAssemblerX64::CheckCharacterNotInRange(
599  uc16 from,
600  uc16 to,
601  Label* on_not_in_range) {
602  __ leal(rax, Operand(current_character(), -from));
603  __ cmpl(rax, Immediate(to - from));
604  BranchOrBacktrack(above, on_not_in_range);
605 }
606 
607 
608 void RegExpMacroAssemblerX64::CheckBitInTable(
609  Handle<ByteArray> table,
610  Label* on_bit_set) {
611  __ Move(rax, table);
612  Register index = current_character();
613  if (mode_ != ASCII || kTableMask != String::kMaxAsciiCharCode) {
614  __ movq(rbx, current_character());
615  __ and_(rbx, Immediate(kTableMask));
616  index = rbx;
617  }
618  __ cmpb(FieldOperand(rax, index, times_1, ByteArray::kHeaderSize),
619  Immediate(0));
620  BranchOrBacktrack(not_equal, on_bit_set);
621 }
622 
623 
624 bool RegExpMacroAssemblerX64::CheckSpecialCharacterClass(uc16 type,
625  Label* on_no_match) {
626  // Range checks (c in min..max) are generally implemented by an unsigned
627  // (c - min) <= (max - min) check, using the sequence:
628  // lea(rax, Operand(current_character(), -min)) or sub(rax, Immediate(min))
629  // cmp(rax, Immediate(max - min))
630  switch (type) {
631  case 's':
632  // Match space-characters
633  if (mode_ == ASCII) {
634  // ASCII space characters are '\t'..'\r' and ' '.
635  Label success;
636  __ cmpl(current_character(), Immediate(' '));
637  __ j(equal, &success);
638  // Check range 0x09..0x0d
639  __ lea(rax, Operand(current_character(), -'\t'));
640  __ cmpl(rax, Immediate('\r' - '\t'));
641  BranchOrBacktrack(above, on_no_match);
642  __ bind(&success);
643  return true;
644  }
645  return false;
646  case 'S':
647  // Match non-space characters.
648  if (mode_ == ASCII) {
649  // ASCII space characters are '\t'..'\r' and ' '.
650  __ cmpl(current_character(), Immediate(' '));
651  BranchOrBacktrack(equal, on_no_match);
652  __ lea(rax, Operand(current_character(), -'\t'));
653  __ cmpl(rax, Immediate('\r' - '\t'));
654  BranchOrBacktrack(below_equal, on_no_match);
655  return true;
656  }
657  return false;
658  case 'd':
659  // Match ASCII digits ('0'..'9')
660  __ lea(rax, Operand(current_character(), -'0'));
661  __ cmpl(rax, Immediate('9' - '0'));
662  BranchOrBacktrack(above, on_no_match);
663  return true;
664  case 'D':
665  // Match non ASCII-digits
666  __ lea(rax, Operand(current_character(), -'0'));
667  __ cmpl(rax, Immediate('9' - '0'));
668  BranchOrBacktrack(below_equal, on_no_match);
669  return true;
670  case '.': {
671  // Match non-newlines (not 0x0a('\n'), 0x0d('\r'), 0x2028 and 0x2029)
672  __ movl(rax, current_character());
673  __ xor_(rax, Immediate(0x01));
674  // See if current character is '\n'^1 or '\r'^1, i.e., 0x0b or 0x0c
675  __ subl(rax, Immediate(0x0b));
676  __ cmpl(rax, Immediate(0x0c - 0x0b));
677  BranchOrBacktrack(below_equal, on_no_match);
678  if (mode_ == UC16) {
679  // Compare original value to 0x2028 and 0x2029, using the already
680  // computed (current_char ^ 0x01 - 0x0b). I.e., check for
681  // 0x201d (0x2028 - 0x0b) or 0x201e.
682  __ subl(rax, Immediate(0x2028 - 0x0b));
683  __ cmpl(rax, Immediate(0x2029 - 0x2028));
684  BranchOrBacktrack(below_equal, on_no_match);
685  }
686  return true;
687  }
688  case 'n': {
689  // Match newlines (0x0a('\n'), 0x0d('\r'), 0x2028 and 0x2029)
690  __ movl(rax, current_character());
691  __ xor_(rax, Immediate(0x01));
692  // See if current character is '\n'^1 or '\r'^1, i.e., 0x0b or 0x0c
693  __ subl(rax, Immediate(0x0b));
694  __ cmpl(rax, Immediate(0x0c - 0x0b));
695  if (mode_ == ASCII) {
696  BranchOrBacktrack(above, on_no_match);
697  } else {
698  Label done;
699  BranchOrBacktrack(below_equal, &done);
700  // Compare original value to 0x2028 and 0x2029, using the already
701  // computed (current_char ^ 0x01 - 0x0b). I.e., check for
702  // 0x201d (0x2028 - 0x0b) or 0x201e.
703  __ subl(rax, Immediate(0x2028 - 0x0b));
704  __ cmpl(rax, Immediate(0x2029 - 0x2028));
705  BranchOrBacktrack(above, on_no_match);
706  __ bind(&done);
707  }
708  return true;
709  }
710  case 'w': {
711  if (mode_ != ASCII) {
712  // Table is 128 entries, so all ASCII characters can be tested.
713  __ cmpl(current_character(), Immediate('z'));
714  BranchOrBacktrack(above, on_no_match);
715  }
716  __ movq(rbx, ExternalReference::re_word_character_map());
717  ASSERT_EQ(0, word_character_map[0]); // Character '\0' is not a word char.
718  __ testb(Operand(rbx, current_character(), times_1, 0),
719  current_character());
720  BranchOrBacktrack(zero, on_no_match);
721  return true;
722  }
723  case 'W': {
724  Label done;
725  if (mode_ != ASCII) {
726  // Table is 128 entries, so all ASCII characters can be tested.
727  __ cmpl(current_character(), Immediate('z'));
728  __ j(above, &done);
729  }
730  __ movq(rbx, ExternalReference::re_word_character_map());
731  ASSERT_EQ(0, word_character_map[0]); // Character '\0' is not a word char.
732  __ testb(Operand(rbx, current_character(), times_1, 0),
733  current_character());
734  BranchOrBacktrack(not_zero, on_no_match);
735  if (mode_ != ASCII) {
736  __ bind(&done);
737  }
738  return true;
739  }
740 
741  case '*':
742  // Match any character.
743  return true;
744  // No custom implementation (yet): s(UC16), S(UC16).
745  default:
746  return false;
747  }
748 }
749 
750 
752  STATIC_ASSERT(FAILURE == 0); // Return value for failure is zero.
753  if (!global()) {
754  __ Set(rax, FAILURE);
755  }
756  __ jmp(&exit_label_);
757 }
758 
759 
760 Handle<HeapObject> RegExpMacroAssemblerX64::GetCode(Handle<String> source) {
761  Label return_rax;
762  // Finalize code - write the entry point code now we know how many
763  // registers we need.
764  // Entry code:
765  __ bind(&entry_label_);
766 
767  // Tell the system that we have a stack frame. Because the type is MANUAL, no
768  // is generated.
769  FrameScope scope(&masm_, StackFrame::MANUAL);
770 
771  // Actually emit code to start a new stack frame.
772  __ push(rbp);
773  __ movq(rbp, rsp);
774  // Save parameters and callee-save registers. Order here should correspond
775  // to order of kBackup_ebx etc.
776 #ifdef _WIN64
777  // MSVC passes arguments in rcx, rdx, r8, r9, with backing stack slots.
778  // Store register parameters in pre-allocated stack slots,
779  __ movq(Operand(rbp, kInputString), rcx);
780  __ movq(Operand(rbp, kStartIndex), rdx); // Passed as int32 in edx.
781  __ movq(Operand(rbp, kInputStart), r8);
782  __ movq(Operand(rbp, kInputEnd), r9);
783  // Callee-save on Win64.
784  __ push(rsi);
785  __ push(rdi);
786  __ push(rbx);
787 #else
788  // GCC passes arguments in rdi, rsi, rdx, rcx, r8, r9 (and then on stack).
789  // Push register parameters on stack for reference.
790  ASSERT_EQ(kInputString, -1 * kPointerSize);
791  ASSERT_EQ(kStartIndex, -2 * kPointerSize);
792  ASSERT_EQ(kInputStart, -3 * kPointerSize);
793  ASSERT_EQ(kInputEnd, -4 * kPointerSize);
794  ASSERT_EQ(kRegisterOutput, -5 * kPointerSize);
795  ASSERT_EQ(kNumOutputRegisters, -6 * kPointerSize);
796  __ push(rdi);
797  __ push(rsi);
798  __ push(rdx);
799  __ push(rcx);
800  __ push(r8);
801  __ push(r9);
802 
803  __ push(rbx); // Callee-save
804 #endif
805 
806  __ push(Immediate(0)); // Number of successful matches in a global regexp.
807  __ push(Immediate(0)); // Make room for "input start - 1" constant.
808 
809  // Check if we have space on the stack for registers.
810  Label stack_limit_hit;
811  Label stack_ok;
812 
813  ExternalReference stack_limit =
814  ExternalReference::address_of_stack_limit(masm_.isolate());
815  __ movq(rcx, rsp);
816  __ movq(kScratchRegister, stack_limit);
817  __ subq(rcx, Operand(kScratchRegister, 0));
818  // Handle it if the stack pointer is already below the stack limit.
819  __ j(below_equal, &stack_limit_hit);
820  // Check if there is room for the variable number of registers above
821  // the stack limit.
822  __ cmpq(rcx, Immediate(num_registers_ * kPointerSize));
823  __ j(above_equal, &stack_ok);
824  // Exit with OutOfMemory exception. There is not enough space on the stack
825  // for our working registers.
826  __ Set(rax, EXCEPTION);
827  __ jmp(&return_rax);
828 
829  __ bind(&stack_limit_hit);
830  __ Move(code_object_pointer(), masm_.CodeObject());
831  CallCheckStackGuardState(); // Preserves no registers beside rbp and rsp.
832  __ testq(rax, rax);
833  // If returned value is non-zero, we exit with the returned value as result.
834  __ j(not_zero, &return_rax);
835 
836  __ bind(&stack_ok);
837 
838  // Allocate space on stack for registers.
839  __ subq(rsp, Immediate(num_registers_ * kPointerSize));
840  // Load string length.
841  __ movq(rsi, Operand(rbp, kInputEnd));
842  // Load input position.
843  __ movq(rdi, Operand(rbp, kInputStart));
844  // Set up rdi to be negative offset from string end.
845  __ subq(rdi, rsi);
846  // Set rax to address of char before start of the string
847  // (effectively string position -1).
848  __ movq(rbx, Operand(rbp, kStartIndex));
849  __ neg(rbx);
850  if (mode_ == UC16) {
851  __ lea(rax, Operand(rdi, rbx, times_2, -char_size()));
852  } else {
853  __ lea(rax, Operand(rdi, rbx, times_1, -char_size()));
854  }
855  // Store this value in a local variable, for use when clearing
856  // position registers.
857  __ movq(Operand(rbp, kInputStartMinusOne), rax);
858 
859 #ifdef WIN32
860  // Ensure that we have written to each stack page, in order. Skipping a page
861  // on Windows can cause segmentation faults. Assuming page size is 4k.
862  const int kPageSize = 4096;
863  const int kRegistersPerPage = kPageSize / kPointerSize;
864  for (int i = num_saved_registers_ + kRegistersPerPage - 1;
865  i < num_registers_;
866  i += kRegistersPerPage) {
867  __ movq(register_location(i), rax); // One write every page.
868  }
869 #endif // WIN32
870 
871  // Initialize code object pointer.
872  __ Move(code_object_pointer(), masm_.CodeObject());
873 
874  Label load_char_start_regexp, start_regexp;
875  // Load newline if index is at start, previous character otherwise.
876  __ cmpl(Operand(rbp, kStartIndex), Immediate(0));
877  __ j(not_equal, &load_char_start_regexp, Label::kNear);
878  __ Set(current_character(), '\n');
879  __ jmp(&start_regexp, Label::kNear);
880 
881  // Global regexp restarts matching here.
882  __ bind(&load_char_start_regexp);
883  // Load previous char as initial value of current character register.
884  LoadCurrentCharacterUnchecked(-1, 1);
885  __ bind(&start_regexp);
886 
887  // Initialize on-stack registers.
888  if (num_saved_registers_ > 0) {
889  // Fill saved registers with initial value = start offset - 1
890  // Fill in stack push order, to avoid accessing across an unwritten
891  // page (a problem on Windows).
892  if (num_saved_registers_ > 8) {
893  __ Set(rcx, kRegisterZero);
894  Label init_loop;
895  __ bind(&init_loop);
896  __ movq(Operand(rbp, rcx, times_1, 0), rax);
897  __ subq(rcx, Immediate(kPointerSize));
898  __ cmpq(rcx,
899  Immediate(kRegisterZero - num_saved_registers_ * kPointerSize));
900  __ j(greater, &init_loop);
901  } else { // Unroll the loop.
902  for (int i = 0; i < num_saved_registers_; i++) {
903  __ movq(register_location(i), rax);
904  }
905  }
906  }
907 
908  // Initialize backtrack stack pointer.
909  __ movq(backtrack_stackpointer(), Operand(rbp, kStackHighEnd));
910 
911  __ jmp(&start_label_);
912 
913  // Exit code:
914  if (success_label_.is_linked()) {
915  // Save captures when successful.
916  __ bind(&success_label_);
917  if (num_saved_registers_ > 0) {
918  // copy captures to output
919  __ movq(rdx, Operand(rbp, kStartIndex));
920  __ movq(rbx, Operand(rbp, kRegisterOutput));
921  __ movq(rcx, Operand(rbp, kInputEnd));
922  __ subq(rcx, Operand(rbp, kInputStart));
923  if (mode_ == UC16) {
924  __ lea(rcx, Operand(rcx, rdx, times_2, 0));
925  } else {
926  __ addq(rcx, rdx);
927  }
928  for (int i = 0; i < num_saved_registers_; i++) {
929  __ movq(rax, register_location(i));
930  if (i == 0 && global_with_zero_length_check()) {
931  // Keep capture start in rdx for the zero-length check later.
932  __ movq(rdx, rax);
933  }
934  __ addq(rax, rcx); // Convert to index from start, not end.
935  if (mode_ == UC16) {
936  __ sar(rax, Immediate(1)); // Convert byte index to character index.
937  }
938  __ movl(Operand(rbx, i * kIntSize), rax);
939  }
940  }
941 
942  if (global()) {
943  // Restart matching if the regular expression is flagged as global.
944  // Increment success counter.
945  __ incq(Operand(rbp, kSuccessfulCaptures));
946  // Capture results have been stored, so the number of remaining global
947  // output registers is reduced by the number of stored captures.
948  __ movsxlq(rcx, Operand(rbp, kNumOutputRegisters));
949  __ subq(rcx, Immediate(num_saved_registers_));
950  // Check whether we have enough room for another set of capture results.
951  __ cmpq(rcx, Immediate(num_saved_registers_));
952  __ j(less, &exit_label_);
953 
954  __ movq(Operand(rbp, kNumOutputRegisters), rcx);
955  // Advance the location for output.
956  __ addq(Operand(rbp, kRegisterOutput),
957  Immediate(num_saved_registers_ * kIntSize));
958 
959  // Prepare rax to initialize registers with its value in the next run.
960  __ movq(rax, Operand(rbp, kInputStartMinusOne));
961 
962  if (global_with_zero_length_check()) {
963  // Special case for zero-length matches.
964  // rdx: capture start index
965  __ cmpq(rdi, rdx);
966  // Not a zero-length match, restart.
967  __ j(not_equal, &load_char_start_regexp);
968  // rdi (offset from the end) is zero if we already reached the end.
969  __ testq(rdi, rdi);
970  __ j(zero, &exit_label_, Label::kNear);
971  // Advance current position after a zero-length match.
972  if (mode_ == UC16) {
973  __ addq(rdi, Immediate(2));
974  } else {
975  __ incq(rdi);
976  }
977  }
978 
979  __ jmp(&load_char_start_regexp);
980  } else {
981  __ movq(rax, Immediate(SUCCESS));
982  }
983  }
984 
985  __ bind(&exit_label_);
986  if (global()) {
987  // Return the number of successful captures.
988  __ movq(rax, Operand(rbp, kSuccessfulCaptures));
989  }
990 
991  __ bind(&return_rax);
992 #ifdef _WIN64
993  // Restore callee save registers.
994  __ lea(rsp, Operand(rbp, kLastCalleeSaveRegister));
995  __ pop(rbx);
996  __ pop(rdi);
997  __ pop(rsi);
998  // Stack now at rbp.
999 #else
1000  // Restore callee save register.
1001  __ movq(rbx, Operand(rbp, kBackup_rbx));
1002  // Skip rsp to rbp.
1003  __ movq(rsp, rbp);
1004 #endif
1005  // Exit function frame, restore previous one.
1006  __ pop(rbp);
1007  __ ret(0);
1008 
1009  // Backtrack code (branch target for conditional backtracks).
1010  if (backtrack_label_.is_linked()) {
1011  __ bind(&backtrack_label_);
1012  Backtrack();
1013  }
1014 
1015  Label exit_with_exception;
1016 
1017  // Preempt-code
1018  if (check_preempt_label_.is_linked()) {
1019  SafeCallTarget(&check_preempt_label_);
1020 
1021  __ push(backtrack_stackpointer());
1022  __ push(rdi);
1023 
1024  CallCheckStackGuardState();
1025  __ testq(rax, rax);
1026  // If returning non-zero, we should end execution with the given
1027  // result as return value.
1028  __ j(not_zero, &return_rax);
1029 
1030  // Restore registers.
1031  __ Move(code_object_pointer(), masm_.CodeObject());
1032  __ pop(rdi);
1033  __ pop(backtrack_stackpointer());
1034  // String might have moved: Reload esi from frame.
1035  __ movq(rsi, Operand(rbp, kInputEnd));
1036  SafeReturn();
1037  }
1038 
1039  // Backtrack stack overflow code.
1040  if (stack_overflow_label_.is_linked()) {
1041  SafeCallTarget(&stack_overflow_label_);
1042  // Reached if the backtrack-stack limit has been hit.
1043 
1044  Label grow_failed;
1045  // Save registers before calling C function
1046 #ifndef _WIN64
1047  // Callee-save in Microsoft 64-bit ABI, but not in AMD64 ABI.
1048  __ push(rsi);
1049  __ push(rdi);
1050 #endif
1051 
1052  // Call GrowStack(backtrack_stackpointer())
1053  static const int num_arguments = 3;
1054  __ PrepareCallCFunction(num_arguments);
1055 #ifdef _WIN64
1056  // Microsoft passes parameters in rcx, rdx, r8.
1057  // First argument, backtrack stackpointer, is already in rcx.
1058  __ lea(rdx, Operand(rbp, kStackHighEnd)); // Second argument
1059  __ LoadAddress(r8, ExternalReference::isolate_address());
1060 #else
1061  // AMD64 ABI passes parameters in rdi, rsi, rdx.
1062  __ movq(rdi, backtrack_stackpointer()); // First argument.
1063  __ lea(rsi, Operand(rbp, kStackHighEnd)); // Second argument.
1064  __ LoadAddress(rdx, ExternalReference::isolate_address());
1065 #endif
1066  ExternalReference grow_stack =
1067  ExternalReference::re_grow_stack(masm_.isolate());
1068  __ CallCFunction(grow_stack, num_arguments);
1069  // If return NULL, we have failed to grow the stack, and
1070  // must exit with a stack-overflow exception.
1071  __ testq(rax, rax);
1072  __ j(equal, &exit_with_exception);
1073  // Otherwise use return value as new stack pointer.
1074  __ movq(backtrack_stackpointer(), rax);
1075  // Restore saved registers and continue.
1076  __ Move(code_object_pointer(), masm_.CodeObject());
1077 #ifndef _WIN64
1078  __ pop(rdi);
1079  __ pop(rsi);
1080 #endif
1081  SafeReturn();
1082  }
1083 
1084  if (exit_with_exception.is_linked()) {
1085  // If any of the code above needed to exit with an exception.
1086  __ bind(&exit_with_exception);
1087  // Exit with Result EXCEPTION(-1) to signal thrown exception.
1088  __ Set(rax, EXCEPTION);
1089  __ jmp(&return_rax);
1090  }
1091 
1092  FixupCodeRelativePositions();
1093 
1094  CodeDesc code_desc;
1095  masm_.GetCode(&code_desc);
1096  Isolate* isolate = ISOLATE;
1097  Handle<Code> code = isolate->factory()->NewCode(
1098  code_desc, Code::ComputeFlags(Code::REGEXP),
1099  masm_.CodeObject());
1100  PROFILE(isolate, RegExpCodeCreateEvent(*code, *source));
1101  return Handle<HeapObject>::cast(code);
1102 }
1103 
1104 
1105 void RegExpMacroAssemblerX64::GoTo(Label* to) {
1106  BranchOrBacktrack(no_condition, to);
1107 }
1108 
1109 
1110 void RegExpMacroAssemblerX64::IfRegisterGE(int reg,
1111  int comparand,
1112  Label* if_ge) {
1113  __ cmpq(register_location(reg), Immediate(comparand));
1114  BranchOrBacktrack(greater_equal, if_ge);
1115 }
1116 
1117 
1118 void RegExpMacroAssemblerX64::IfRegisterLT(int reg,
1119  int comparand,
1120  Label* if_lt) {
1121  __ cmpq(register_location(reg), Immediate(comparand));
1122  BranchOrBacktrack(less, if_lt);
1123 }
1124 
1125 
1126 void RegExpMacroAssemblerX64::IfRegisterEqPos(int reg,
1127  Label* if_eq) {
1128  __ cmpq(rdi, register_location(reg));
1129  BranchOrBacktrack(equal, if_eq);
1130 }
1131 
1132 
1133 RegExpMacroAssembler::IrregexpImplementation
1134  RegExpMacroAssemblerX64::Implementation() {
1135  return kX64Implementation;
1136 }
1137 
1138 
1139 void RegExpMacroAssemblerX64::LoadCurrentCharacter(int cp_offset,
1140  Label* on_end_of_input,
1141  bool check_bounds,
1142  int characters) {
1143  ASSERT(cp_offset >= -1); // ^ and \b can look behind one character.
1144  ASSERT(cp_offset < (1<<30)); // Be sane! (And ensure negation works)
1145  if (check_bounds) {
1146  CheckPosition(cp_offset + characters - 1, on_end_of_input);
1147  }
1148  LoadCurrentCharacterUnchecked(cp_offset, characters);
1149 }
1150 
1151 
1152 void RegExpMacroAssemblerX64::PopCurrentPosition() {
1153  Pop(rdi);
1154 }
1155 
1156 
1157 void RegExpMacroAssemblerX64::PopRegister(int register_index) {
1158  Pop(rax);
1159  __ movq(register_location(register_index), rax);
1160 }
1161 
1162 
1163 void RegExpMacroAssemblerX64::PushBacktrack(Label* label) {
1164  Push(label);
1165  CheckStackLimit();
1166 }
1167 
1168 
1169 void RegExpMacroAssemblerX64::PushCurrentPosition() {
1170  Push(rdi);
1171 }
1172 
1173 
1174 void RegExpMacroAssemblerX64::PushRegister(int register_index,
1175  StackCheckFlag check_stack_limit) {
1176  __ movq(rax, register_location(register_index));
1177  Push(rax);
1178  if (check_stack_limit) CheckStackLimit();
1179 }
1180 
1181 
1182 void RegExpMacroAssemblerX64::ReadCurrentPositionFromRegister(int reg) {
1183  __ movq(rdi, register_location(reg));
1184 }
1185 
1186 
1187 void RegExpMacroAssemblerX64::ReadStackPointerFromRegister(int reg) {
1188  __ movq(backtrack_stackpointer(), register_location(reg));
1189  __ addq(backtrack_stackpointer(), Operand(rbp, kStackHighEnd));
1190 }
1191 
1192 
1193 void RegExpMacroAssemblerX64::SetCurrentPositionFromEnd(int by) {
1194  Label after_position;
1195  __ cmpq(rdi, Immediate(-by * char_size()));
1196  __ j(greater_equal, &after_position, Label::kNear);
1197  __ movq(rdi, Immediate(-by * char_size()));
1198  // On RegExp code entry (where this operation is used), the character before
1199  // the current position is expected to be already loaded.
1200  // We have advanced the position, so it's safe to read backwards.
1201  LoadCurrentCharacterUnchecked(-1, 1);
1202  __ bind(&after_position);
1203 }
1204 
1205 
1206 void RegExpMacroAssemblerX64::SetRegister(int register_index, int to) {
1207  ASSERT(register_index >= num_saved_registers_); // Reserved for positions!
1208  __ movq(register_location(register_index), Immediate(to));
1209 }
1210 
1211 
1212 bool RegExpMacroAssemblerX64::Succeed() {
1213  __ jmp(&success_label_);
1214  return global();
1215 }
1216 
1217 
1218 void RegExpMacroAssemblerX64::WriteCurrentPositionToRegister(int reg,
1219  int cp_offset) {
1220  if (cp_offset == 0) {
1221  __ movq(register_location(reg), rdi);
1222  } else {
1223  __ lea(rax, Operand(rdi, cp_offset * char_size()));
1224  __ movq(register_location(reg), rax);
1225  }
1226 }
1227 
1228 
1229 void RegExpMacroAssemblerX64::ClearRegisters(int reg_from, int reg_to) {
1230  ASSERT(reg_from <= reg_to);
1231  __ movq(rax, Operand(rbp, kInputStartMinusOne));
1232  for (int reg = reg_from; reg <= reg_to; reg++) {
1233  __ movq(register_location(reg), rax);
1234  }
1235 }
1236 
1237 
1238 void RegExpMacroAssemblerX64::WriteStackPointerToRegister(int reg) {
1239  __ movq(rax, backtrack_stackpointer());
1240  __ subq(rax, Operand(rbp, kStackHighEnd));
1241  __ movq(register_location(reg), rax);
1242 }
1243 
1244 
1245 // Private methods:
1246 
1247 void RegExpMacroAssemblerX64::CallCheckStackGuardState() {
1248  // This function call preserves no register values. Caller should
1249  // store anything volatile in a C call or overwritten by this function.
1250  static const int num_arguments = 3;
1251  __ PrepareCallCFunction(num_arguments);
1252 #ifdef _WIN64
1253  // Second argument: Code* of self. (Do this before overwriting r8).
1254  __ movq(rdx, code_object_pointer());
1255  // Third argument: RegExp code frame pointer.
1256  __ movq(r8, rbp);
1257  // First argument: Next address on the stack (will be address of
1258  // return address).
1259  __ lea(rcx, Operand(rsp, -kPointerSize));
1260 #else
1261  // Third argument: RegExp code frame pointer.
1262  __ movq(rdx, rbp);
1263  // Second argument: Code* of self.
1264  __ movq(rsi, code_object_pointer());
1265  // First argument: Next address on the stack (will be address of
1266  // return address).
1267  __ lea(rdi, Operand(rsp, -kPointerSize));
1268 #endif
1269  ExternalReference stack_check =
1270  ExternalReference::re_check_stack_guard_state(masm_.isolate());
1271  __ CallCFunction(stack_check, num_arguments);
1272 }
1273 
1274 
1275 // Helper function for reading a value out of a stack frame.
1276 template <typename T>
1277 static T& frame_entry(Address re_frame, int frame_offset) {
1278  return reinterpret_cast<T&>(Memory::int32_at(re_frame + frame_offset));
1279 }
1280 
1281 
1282 int RegExpMacroAssemblerX64::CheckStackGuardState(Address* return_address,
1283  Code* re_code,
1284  Address re_frame) {
1285  Isolate* isolate = frame_entry<Isolate*>(re_frame, kIsolate);
1286  ASSERT(isolate == Isolate::Current());
1287  if (isolate->stack_guard()->IsStackOverflow()) {
1288  isolate->StackOverflow();
1289  return EXCEPTION;
1290  }
1291 
1292  // If not real stack overflow the stack guard was used to interrupt
1293  // execution for another purpose.
1294 
1295  // If this is a direct call from JavaScript retry the RegExp forcing the call
1296  // through the runtime system. Currently the direct call cannot handle a GC.
1297  if (frame_entry<int>(re_frame, kDirectCall) == 1) {
1298  return RETRY;
1299  }
1300 
1301  // Prepare for possible GC.
1302  HandleScope handles(isolate);
1303  Handle<Code> code_handle(re_code);
1304 
1305  Handle<String> subject(frame_entry<String*>(re_frame, kInputString));
1306 
1307  // Current string.
1308  bool is_ascii = subject->IsAsciiRepresentationUnderneath();
1309 
1310  ASSERT(re_code->instruction_start() <= *return_address);
1311  ASSERT(*return_address <=
1312  re_code->instruction_start() + re_code->instruction_size());
1313 
1314  MaybeObject* result = Execution::HandleStackGuardInterrupt(isolate);
1315 
1316  if (*code_handle != re_code) { // Return address no longer valid
1317  intptr_t delta = code_handle->address() - re_code->address();
1318  // Overwrite the return address on the stack.
1319  *return_address += delta;
1320  }
1321 
1322  if (result->IsException()) {
1323  return EXCEPTION;
1324  }
1325 
1326  Handle<String> subject_tmp = subject;
1327  int slice_offset = 0;
1328 
1329  // Extract the underlying string and the slice offset.
1330  if (StringShape(*subject_tmp).IsCons()) {
1331  subject_tmp = Handle<String>(ConsString::cast(*subject_tmp)->first());
1332  } else if (StringShape(*subject_tmp).IsSliced()) {
1333  SlicedString* slice = SlicedString::cast(*subject_tmp);
1334  subject_tmp = Handle<String>(slice->parent());
1335  slice_offset = slice->offset();
1336  }
1337 
1338  // String might have changed.
1339  if (subject_tmp->IsAsciiRepresentation() != is_ascii) {
1340  // If we changed between an ASCII and an UC16 string, the specialized
1341  // code cannot be used, and we need to restart regexp matching from
1342  // scratch (including, potentially, compiling a new version of the code).
1343  return RETRY;
1344  }
1345 
1346  // Otherwise, the content of the string might have moved. It must still
1347  // be a sequential or external string with the same content.
1348  // Update the start and end pointers in the stack frame to the current
1349  // location (whether it has actually moved or not).
1350  ASSERT(StringShape(*subject_tmp).IsSequential() ||
1351  StringShape(*subject_tmp).IsExternal());
1352 
1353  // The original start address of the characters to match.
1354  const byte* start_address = frame_entry<const byte*>(re_frame, kInputStart);
1355 
1356  // Find the current start address of the same character at the current string
1357  // position.
1358  int start_index = frame_entry<int>(re_frame, kStartIndex);
1359  const byte* new_address = StringCharacterPosition(*subject_tmp,
1360  start_index + slice_offset);
1361 
1362  if (start_address != new_address) {
1363  // If there is a difference, update the object pointer and start and end
1364  // addresses in the RegExp stack frame to match the new value.
1365  const byte* end_address = frame_entry<const byte* >(re_frame, kInputEnd);
1366  int byte_length = static_cast<int>(end_address - start_address);
1367  frame_entry<const String*>(re_frame, kInputString) = *subject;
1368  frame_entry<const byte*>(re_frame, kInputStart) = new_address;
1369  frame_entry<const byte*>(re_frame, kInputEnd) = new_address + byte_length;
1370  } else if (frame_entry<const String*>(re_frame, kInputString) != *subject) {
1371  // Subject string might have been a ConsString that underwent
1372  // short-circuiting during GC. That will not change start_address but
1373  // will change pointer inside the subject handle.
1374  frame_entry<const String*>(re_frame, kInputString) = *subject;
1375  }
1376 
1377  return 0;
1378 }
1379 
1380 
1381 Operand RegExpMacroAssemblerX64::register_location(int register_index) {
1382  ASSERT(register_index < (1<<30));
1383  if (num_registers_ <= register_index) {
1384  num_registers_ = register_index + 1;
1385  }
1386  return Operand(rbp, kRegisterZero - register_index * kPointerSize);
1387 }
1388 
1389 
1390 void RegExpMacroAssemblerX64::CheckPosition(int cp_offset,
1391  Label* on_outside_input) {
1392  __ cmpl(rdi, Immediate(-cp_offset * char_size()));
1393  BranchOrBacktrack(greater_equal, on_outside_input);
1394 }
1395 
1396 
1397 void RegExpMacroAssemblerX64::BranchOrBacktrack(Condition condition,
1398  Label* to) {
1399  if (condition < 0) { // No condition
1400  if (to == NULL) {
1401  Backtrack();
1402  return;
1403  }
1404  __ jmp(to);
1405  return;
1406  }
1407  if (to == NULL) {
1408  __ j(condition, &backtrack_label_);
1409  return;
1410  }
1411  __ j(condition, to);
1412 }
1413 
1414 
1415 void RegExpMacroAssemblerX64::SafeCall(Label* to) {
1416  __ call(to);
1417 }
1418 
1419 
1420 void RegExpMacroAssemblerX64::SafeCallTarget(Label* label) {
1421  __ bind(label);
1422  __ subq(Operand(rsp, 0), code_object_pointer());
1423 }
1424 
1425 
1426 void RegExpMacroAssemblerX64::SafeReturn() {
1427  __ addq(Operand(rsp, 0), code_object_pointer());
1428  __ ret(0);
1429 }
1430 
1431 
1432 void RegExpMacroAssemblerX64::Push(Register source) {
1433  ASSERT(!source.is(backtrack_stackpointer()));
1434  // Notice: This updates flags, unlike normal Push.
1435  __ subq(backtrack_stackpointer(), Immediate(kIntSize));
1436  __ movl(Operand(backtrack_stackpointer(), 0), source);
1437 }
1438 
1439 
1440 void RegExpMacroAssemblerX64::Push(Immediate value) {
1441  // Notice: This updates flags, unlike normal Push.
1442  __ subq(backtrack_stackpointer(), Immediate(kIntSize));
1443  __ movl(Operand(backtrack_stackpointer(), 0), value);
1444 }
1445 
1446 
1447 void RegExpMacroAssemblerX64::FixupCodeRelativePositions() {
1448  for (int i = 0, n = code_relative_fixup_positions_.length(); i < n; i++) {
1449  int position = code_relative_fixup_positions_[i];
1450  // The position succeeds a relative label offset from position.
1451  // Patch the relative offset to be relative to the Code object pointer
1452  // instead.
1453  int patch_position = position - kIntSize;
1454  int offset = masm_.long_at(patch_position);
1455  masm_.long_at_put(patch_position,
1456  offset
1457  + position
1458  + Code::kHeaderSize
1459  - kHeapObjectTag);
1460  }
1461  code_relative_fixup_positions_.Clear();
1462 }
1463 
1464 
1465 void RegExpMacroAssemblerX64::Push(Label* backtrack_target) {
1466  __ subq(backtrack_stackpointer(), Immediate(kIntSize));
1467  __ movl(Operand(backtrack_stackpointer(), 0), backtrack_target);
1468  MarkPositionForCodeRelativeFixup();
1469 }
1470 
1471 
1472 void RegExpMacroAssemblerX64::Pop(Register target) {
1473  ASSERT(!target.is(backtrack_stackpointer()));
1474  __ movsxlq(target, Operand(backtrack_stackpointer(), 0));
1475  // Notice: This updates flags, unlike normal Pop.
1476  __ addq(backtrack_stackpointer(), Immediate(kIntSize));
1477 }
1478 
1479 
1480 void RegExpMacroAssemblerX64::Drop() {
1481  __ addq(backtrack_stackpointer(), Immediate(kIntSize));
1482 }
1483 
1484 
1485 void RegExpMacroAssemblerX64::CheckPreemption() {
1486  // Check for preemption.
1487  Label no_preempt;
1488  ExternalReference stack_limit =
1489  ExternalReference::address_of_stack_limit(masm_.isolate());
1490  __ load_rax(stack_limit);
1491  __ cmpq(rsp, rax);
1492  __ j(above, &no_preempt);
1493 
1494  SafeCall(&check_preempt_label_);
1495 
1496  __ bind(&no_preempt);
1497 }
1498 
1499 
1500 void RegExpMacroAssemblerX64::CheckStackLimit() {
1501  Label no_stack_overflow;
1502  ExternalReference stack_limit =
1503  ExternalReference::address_of_regexp_stack_limit(masm_.isolate());
1504  __ load_rax(stack_limit);
1505  __ cmpq(backtrack_stackpointer(), rax);
1506  __ j(above, &no_stack_overflow);
1507 
1508  SafeCall(&stack_overflow_label_);
1509 
1510  __ bind(&no_stack_overflow);
1511 }
1512 
1513 
1514 void RegExpMacroAssemblerX64::LoadCurrentCharacterUnchecked(int cp_offset,
1515  int characters) {
1516  if (mode_ == ASCII) {
1517  if (characters == 4) {
1518  __ movl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
1519  } else if (characters == 2) {
1520  __ movzxwl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
1521  } else {
1522  ASSERT(characters == 1);
1523  __ movzxbl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
1524  }
1525  } else {
1526  ASSERT(mode_ == UC16);
1527  if (characters == 2) {
1528  __ movl(current_character(),
1529  Operand(rsi, rdi, times_1, cp_offset * sizeof(uc16)));
1530  } else {
1531  ASSERT(characters == 1);
1532  __ movzxwl(current_character(),
1533  Operand(rsi, rdi, times_1, cp_offset * sizeof(uc16)));
1534  }
1535  }
1536 }
1537 
1538 #undef __
1539 
1540 #endif // V8_INTERPRETED_REGEXP
1541 
1542 }} // namespace v8::internal
1543 
1544 #endif // V8_TARGET_ARCH_X64
byte * Address
Definition: globals.h:157
const Register rdx
unsigned char byte
Definition: disasm.h:33
v8::Handle< v8::Value > Fail(const v8::Arguments &args)
const Register r11
const Register rbp
const Register rsi
#define ASSERT(condition)
Definition: checks.h:270
#define PROFILE(isolate, Call)
Definition: cpu-profiler.h:190
const int kIntSize
Definition: globals.h:217
RegExpMacroAssemblerX64(Mode mode, int registers_to_save, Zone *zone)
const Register r9
const int kPointerSize
Definition: globals.h:220
Operand FieldOperand(Register object, int offset)
const int kHeapObjectTag
Definition: v8.h:4009
const Register rbx
const Register rsp
#define __
const Register rax
const Register rdi
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra code(assertions) for debugging") DEFINE_bool(code_comments
#define T(name, string, precedence)
Definition: token.cc:48
#define ISOLATE
Definition: isolate.h:1435
const Register kScratchRegister
uint16_t uc16
Definition: globals.h:259
const Register r8
const Register rcx
#define ASSERT_EQ(v1, v2)
Definition: checks.h:271
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if NULL
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if NULL
Definition: flags.cc:301
#define STATIC_ASSERT(test)
Definition: checks.h:283
const uc32 kMaxAsciiCharCode
Definition: globals.h:263