27b8699cf21193adfdb461c241cf39212aafdc69
[platform/framework/web/crosswalk.git] / src / v8 / src / jsregexp.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/v8.h"
6
7 #include "src/ast.h"
8 #include "src/base/platform/platform.h"
9 #include "src/compilation-cache.h"
10 #include "src/compiler.h"
11 #include "src/execution.h"
12 #include "src/factory.h"
13 #include "src/jsregexp-inl.h"
14 #include "src/jsregexp.h"
15 #include "src/ostreams.h"
16 #include "src/parser.h"
17 #include "src/regexp-macro-assembler.h"
18 #include "src/regexp-macro-assembler-irregexp.h"
19 #include "src/regexp-macro-assembler-tracer.h"
20 #include "src/regexp-stack.h"
21 #include "src/runtime.h"
22 #include "src/string-search.h"
23
24 #ifndef V8_INTERPRETED_REGEXP
25 #if V8_TARGET_ARCH_IA32
26 #include "src/ia32/regexp-macro-assembler-ia32.h"  // NOLINT
27 #elif V8_TARGET_ARCH_X64
28 #include "src/x64/regexp-macro-assembler-x64.h"  // NOLINT
29 #elif V8_TARGET_ARCH_ARM64
30 #include "src/arm64/regexp-macro-assembler-arm64.h"  // NOLINT
31 #elif V8_TARGET_ARCH_ARM
32 #include "src/arm/regexp-macro-assembler-arm.h"  // NOLINT
33 #elif V8_TARGET_ARCH_MIPS
34 #include "src/mips/regexp-macro-assembler-mips.h"  // NOLINT
35 #elif V8_TARGET_ARCH_MIPS64
36 #include "src/mips64/regexp-macro-assembler-mips64.h"  // NOLINT
37 #elif V8_TARGET_ARCH_X87
38 #include "src/x87/regexp-macro-assembler-x87.h"  // NOLINT
39 #else
40 #error Unsupported target architecture.
41 #endif
42 #endif
43
44 #include "src/interpreter-irregexp.h"
45
46
47 namespace v8 {
48 namespace internal {
49
50 MaybeHandle<Object> RegExpImpl::CreateRegExpLiteral(
51     Handle<JSFunction> constructor,
52     Handle<String> pattern,
53     Handle<String> flags) {
54   // Call the construct code with 2 arguments.
55   Handle<Object> argv[] = { pattern, flags };
56   return Execution::New(constructor, ARRAY_SIZE(argv), argv);
57 }
58
59
60 static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
61   int flags = JSRegExp::NONE;
62   for (int i = 0; i < str->length(); i++) {
63     switch (str->Get(i)) {
64       case 'i':
65         flags |= JSRegExp::IGNORE_CASE;
66         break;
67       case 'g':
68         flags |= JSRegExp::GLOBAL;
69         break;
70       case 'm':
71         flags |= JSRegExp::MULTILINE;
72         break;
73     }
74   }
75   return JSRegExp::Flags(flags);
76 }
77
78
79 MUST_USE_RESULT
80 static inline MaybeHandle<Object> ThrowRegExpException(
81     Handle<JSRegExp> re,
82     Handle<String> pattern,
83     Handle<String> error_text,
84     const char* message) {
85   Isolate* isolate = re->GetIsolate();
86   Factory* factory = isolate->factory();
87   Handle<FixedArray> elements = factory->NewFixedArray(2);
88   elements->set(0, *pattern);
89   elements->set(1, *error_text);
90   Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
91   Handle<Object> regexp_err = factory->NewSyntaxError(message, array);
92   return isolate->Throw<Object>(regexp_err);
93 }
94
95
96 ContainedInLattice AddRange(ContainedInLattice containment,
97                             const int* ranges,
98                             int ranges_length,
99                             Interval new_range) {
100   DCHECK((ranges_length & 1) == 1);
101   DCHECK(ranges[ranges_length - 1] == String::kMaxUtf16CodeUnit + 1);
102   if (containment == kLatticeUnknown) return containment;
103   bool inside = false;
104   int last = 0;
105   for (int i = 0; i < ranges_length; inside = !inside, last = ranges[i], i++) {
106     // Consider the range from last to ranges[i].
107     // We haven't got to the new range yet.
108     if (ranges[i] <= new_range.from()) continue;
109     // New range is wholly inside last-ranges[i].  Note that new_range.to() is
110     // inclusive, but the values in ranges are not.
111     if (last <= new_range.from() && new_range.to() < ranges[i]) {
112       return Combine(containment, inside ? kLatticeIn : kLatticeOut);
113     }
114     return kLatticeUnknown;
115   }
116   return containment;
117 }
118
119
120 // More makes code generation slower, less makes V8 benchmark score lower.
121 const int kMaxLookaheadForBoyerMoore = 8;
122 // In a 3-character pattern you can maximally step forwards 3 characters
123 // at a time, which is not always enough to pay for the extra logic.
124 const int kPatternTooShortForBoyerMoore = 2;
125
126
127 // Identifies the sort of regexps where the regexp engine is faster
128 // than the code used for atom matches.
129 static bool HasFewDifferentCharacters(Handle<String> pattern) {
130   int length = Min(kMaxLookaheadForBoyerMoore, pattern->length());
131   if (length <= kPatternTooShortForBoyerMoore) return false;
132   const int kMod = 128;
133   bool character_found[kMod];
134   int different = 0;
135   memset(&character_found[0], 0, sizeof(character_found));
136   for (int i = 0; i < length; i++) {
137     int ch = (pattern->Get(i) & (kMod - 1));
138     if (!character_found[ch]) {
139       character_found[ch] = true;
140       different++;
141       // We declare a regexp low-alphabet if it has at least 3 times as many
142       // characters as it has different characters.
143       if (different * 3 > length) return false;
144     }
145   }
146   return true;
147 }
148
149
150 // Generic RegExp methods. Dispatches to implementation specific methods.
151
152
153 MaybeHandle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
154                                         Handle<String> pattern,
155                                         Handle<String> flag_str) {
156   Isolate* isolate = re->GetIsolate();
157   Zone zone(isolate);
158   JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
159   CompilationCache* compilation_cache = isolate->compilation_cache();
160   MaybeHandle<FixedArray> maybe_cached =
161       compilation_cache->LookupRegExp(pattern, flags);
162   Handle<FixedArray> cached;
163   bool in_cache = maybe_cached.ToHandle(&cached);
164   LOG(isolate, RegExpCompileEvent(re, in_cache));
165
166   Handle<Object> result;
167   if (in_cache) {
168     re->set_data(*cached);
169     return re;
170   }
171   pattern = String::Flatten(pattern);
172   PostponeInterruptsScope postpone(isolate);
173   RegExpCompileData parse_result;
174   FlatStringReader reader(isolate, pattern);
175   if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
176                                  &parse_result, &zone)) {
177     // Throw an exception if we fail to parse the pattern.
178     return ThrowRegExpException(re,
179                                 pattern,
180                                 parse_result.error,
181                                 "malformed_regexp");
182   }
183
184   bool has_been_compiled = false;
185
186   if (parse_result.simple &&
187       !flags.is_ignore_case() &&
188       !HasFewDifferentCharacters(pattern)) {
189     // Parse-tree is a single atom that is equal to the pattern.
190     AtomCompile(re, pattern, flags, pattern);
191     has_been_compiled = true;
192   } else if (parse_result.tree->IsAtom() &&
193       !flags.is_ignore_case() &&
194       parse_result.capture_count == 0) {
195     RegExpAtom* atom = parse_result.tree->AsAtom();
196     Vector<const uc16> atom_pattern = atom->data();
197     Handle<String> atom_string;
198     ASSIGN_RETURN_ON_EXCEPTION(
199         isolate, atom_string,
200         isolate->factory()->NewStringFromTwoByte(atom_pattern),
201         Object);
202     if (!HasFewDifferentCharacters(atom_string)) {
203       AtomCompile(re, pattern, flags, atom_string);
204       has_been_compiled = true;
205     }
206   }
207   if (!has_been_compiled) {
208     IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
209   }
210   DCHECK(re->data()->IsFixedArray());
211   // Compilation succeeded so the data is set on the regexp
212   // and we can store it in the cache.
213   Handle<FixedArray> data(FixedArray::cast(re->data()));
214   compilation_cache->PutRegExp(pattern, flags, data);
215
216   return re;
217 }
218
219
220 MaybeHandle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
221                                      Handle<String> subject,
222                                      int index,
223                                      Handle<JSArray> last_match_info) {
224   switch (regexp->TypeTag()) {
225     case JSRegExp::ATOM:
226       return AtomExec(regexp, subject, index, last_match_info);
227     case JSRegExp::IRREGEXP: {
228       return IrregexpExec(regexp, subject, index, last_match_info);
229     }
230     default:
231       UNREACHABLE();
232       return MaybeHandle<Object>();
233   }
234 }
235
236
237 // RegExp Atom implementation: Simple string search using indexOf.
238
239
240 void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
241                              Handle<String> pattern,
242                              JSRegExp::Flags flags,
243                              Handle<String> match_pattern) {
244   re->GetIsolate()->factory()->SetRegExpAtomData(re,
245                                                  JSRegExp::ATOM,
246                                                  pattern,
247                                                  flags,
248                                                  match_pattern);
249 }
250
251
252 static void SetAtomLastCapture(FixedArray* array,
253                                String* subject,
254                                int from,
255                                int to) {
256   SealHandleScope shs(array->GetIsolate());
257   RegExpImpl::SetLastCaptureCount(array, 2);
258   RegExpImpl::SetLastSubject(array, subject);
259   RegExpImpl::SetLastInput(array, subject);
260   RegExpImpl::SetCapture(array, 0, from);
261   RegExpImpl::SetCapture(array, 1, to);
262 }
263
264
265 int RegExpImpl::AtomExecRaw(Handle<JSRegExp> regexp,
266                             Handle<String> subject,
267                             int index,
268                             int32_t* output,
269                             int output_size) {
270   Isolate* isolate = regexp->GetIsolate();
271
272   DCHECK(0 <= index);
273   DCHECK(index <= subject->length());
274
275   subject = String::Flatten(subject);
276   DisallowHeapAllocation no_gc;  // ensure vectors stay valid
277
278   String* needle = String::cast(regexp->DataAt(JSRegExp::kAtomPatternIndex));
279   int needle_len = needle->length();
280   DCHECK(needle->IsFlat());
281   DCHECK_LT(0, needle_len);
282
283   if (index + needle_len > subject->length()) {
284     return RegExpImpl::RE_FAILURE;
285   }
286
287   for (int i = 0; i < output_size; i += 2) {
288     String::FlatContent needle_content = needle->GetFlatContent();
289     String::FlatContent subject_content = subject->GetFlatContent();
290     DCHECK(needle_content.IsFlat());
291     DCHECK(subject_content.IsFlat());
292     // dispatch on type of strings
293     index = (needle_content.IsAscii()
294              ? (subject_content.IsAscii()
295                 ? SearchString(isolate,
296                                subject_content.ToOneByteVector(),
297                                needle_content.ToOneByteVector(),
298                                index)
299                 : SearchString(isolate,
300                                subject_content.ToUC16Vector(),
301                                needle_content.ToOneByteVector(),
302                                index))
303              : (subject_content.IsAscii()
304                 ? SearchString(isolate,
305                                subject_content.ToOneByteVector(),
306                                needle_content.ToUC16Vector(),
307                                index)
308                 : SearchString(isolate,
309                                subject_content.ToUC16Vector(),
310                                needle_content.ToUC16Vector(),
311                                index)));
312     if (index == -1) {
313       return i / 2;  // Return number of matches.
314     } else {
315       output[i] = index;
316       output[i+1] = index + needle_len;
317       index += needle_len;
318     }
319   }
320   return output_size / 2;
321 }
322
323
324 Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
325                                     Handle<String> subject,
326                                     int index,
327                                     Handle<JSArray> last_match_info) {
328   Isolate* isolate = re->GetIsolate();
329
330   static const int kNumRegisters = 2;
331   STATIC_ASSERT(kNumRegisters <= Isolate::kJSRegexpStaticOffsetsVectorSize);
332   int32_t* output_registers = isolate->jsregexp_static_offsets_vector();
333
334   int res = AtomExecRaw(re, subject, index, output_registers, kNumRegisters);
335
336   if (res == RegExpImpl::RE_FAILURE) return isolate->factory()->null_value();
337
338   DCHECK_EQ(res, RegExpImpl::RE_SUCCESS);
339   SealHandleScope shs(isolate);
340   FixedArray* array = FixedArray::cast(last_match_info->elements());
341   SetAtomLastCapture(array, *subject, output_registers[0], output_registers[1]);
342   return last_match_info;
343 }
344
345
346 // Irregexp implementation.
347
348 // Ensures that the regexp object contains a compiled version of the
349 // source for either ASCII or non-ASCII strings.
350 // If the compiled version doesn't already exist, it is compiled
351 // from the source pattern.
352 // If compilation fails, an exception is thrown and this function
353 // returns false.
354 bool RegExpImpl::EnsureCompiledIrregexp(
355     Handle<JSRegExp> re, Handle<String> sample_subject, bool is_ascii) {
356   Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
357 #ifdef V8_INTERPRETED_REGEXP
358   if (compiled_code->IsByteArray()) return true;
359 #else  // V8_INTERPRETED_REGEXP (RegExp native code)
360   if (compiled_code->IsCode()) return true;
361 #endif
362   // We could potentially have marked this as flushable, but have kept
363   // a saved version if we did not flush it yet.
364   Object* saved_code = re->DataAt(JSRegExp::saved_code_index(is_ascii));
365   if (saved_code->IsCode()) {
366     // Reinstate the code in the original place.
367     re->SetDataAt(JSRegExp::code_index(is_ascii), saved_code);
368     DCHECK(compiled_code->IsSmi());
369     return true;
370   }
371   return CompileIrregexp(re, sample_subject, is_ascii);
372 }
373
374
375 static bool CreateRegExpErrorObjectAndThrow(Handle<JSRegExp> re,
376                                             bool is_ascii,
377                                             Handle<String> error_message,
378                                             Isolate* isolate) {
379   Factory* factory = isolate->factory();
380   Handle<FixedArray> elements = factory->NewFixedArray(2);
381   elements->set(0, re->Pattern());
382   elements->set(1, *error_message);
383   Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
384   Handle<Object> regexp_err =
385       factory->NewSyntaxError("malformed_regexp", array);
386   isolate->Throw(*regexp_err);
387   return false;
388 }
389
390
391 bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re,
392                                  Handle<String> sample_subject,
393                                  bool is_ascii) {
394   // Compile the RegExp.
395   Isolate* isolate = re->GetIsolate();
396   Zone zone(isolate);
397   PostponeInterruptsScope postpone(isolate);
398   // If we had a compilation error the last time this is saved at the
399   // saved code index.
400   Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
401   // When arriving here entry can only be a smi, either representing an
402   // uncompiled regexp, a previous compilation error, or code that has
403   // been flushed.
404   DCHECK(entry->IsSmi());
405   int entry_value = Smi::cast(entry)->value();
406   DCHECK(entry_value == JSRegExp::kUninitializedValue ||
407          entry_value == JSRegExp::kCompilationErrorValue ||
408          (entry_value < JSRegExp::kCodeAgeMask && entry_value >= 0));
409
410   if (entry_value == JSRegExp::kCompilationErrorValue) {
411     // A previous compilation failed and threw an error which we store in
412     // the saved code index (we store the error message, not the actual
413     // error). Recreate the error object and throw it.
414     Object* error_string = re->DataAt(JSRegExp::saved_code_index(is_ascii));
415     DCHECK(error_string->IsString());
416     Handle<String> error_message(String::cast(error_string));
417     CreateRegExpErrorObjectAndThrow(re, is_ascii, error_message, isolate);
418     return false;
419   }
420
421   JSRegExp::Flags flags = re->GetFlags();
422
423   Handle<String> pattern(re->Pattern());
424   pattern = String::Flatten(pattern);
425   RegExpCompileData compile_data;
426   FlatStringReader reader(isolate, pattern);
427   if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
428                                  &compile_data,
429                                  &zone)) {
430     // Throw an exception if we fail to parse the pattern.
431     // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
432     USE(ThrowRegExpException(re,
433                              pattern,
434                              compile_data.error,
435                              "malformed_regexp"));
436     return false;
437   }
438   RegExpEngine::CompilationResult result =
439       RegExpEngine::Compile(&compile_data,
440                             flags.is_ignore_case(),
441                             flags.is_global(),
442                             flags.is_multiline(),
443                             pattern,
444                             sample_subject,
445                             is_ascii,
446                             &zone);
447   if (result.error_message != NULL) {
448     // Unable to compile regexp.
449     Handle<String> error_message = isolate->factory()->NewStringFromUtf8(
450         CStrVector(result.error_message)).ToHandleChecked();
451     CreateRegExpErrorObjectAndThrow(re, is_ascii, error_message, isolate);
452     return false;
453   }
454
455   Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
456   data->set(JSRegExp::code_index(is_ascii), result.code);
457   int register_max = IrregexpMaxRegisterCount(*data);
458   if (result.num_registers > register_max) {
459     SetIrregexpMaxRegisterCount(*data, result.num_registers);
460   }
461
462   return true;
463 }
464
465
466 int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
467   return Smi::cast(
468       re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
469 }
470
471
472 void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
473   re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
474 }
475
476
477 int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
478   return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
479 }
480
481
482 int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
483   return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
484 }
485
486
487 ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
488   return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
489 }
490
491
492 Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
493   return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
494 }
495
496
497 void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
498                                     Handle<String> pattern,
499                                     JSRegExp::Flags flags,
500                                     int capture_count) {
501   // Initialize compiled code entries to null.
502   re->GetIsolate()->factory()->SetRegExpIrregexpData(re,
503                                                      JSRegExp::IRREGEXP,
504                                                      pattern,
505                                                      flags,
506                                                      capture_count);
507 }
508
509
510 int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
511                                 Handle<String> subject) {
512   subject = String::Flatten(subject);
513
514   // Check the asciiness of the underlying storage.
515   bool is_ascii = subject->IsOneByteRepresentationUnderneath();
516   if (!EnsureCompiledIrregexp(regexp, subject, is_ascii)) return -1;
517
518 #ifdef V8_INTERPRETED_REGEXP
519   // Byte-code regexp needs space allocated for all its registers.
520   // The result captures are copied to the start of the registers array
521   // if the match succeeds.  This way those registers are not clobbered
522   // when we set the last match info from last successful match.
523   return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data())) +
524          (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
525 #else  // V8_INTERPRETED_REGEXP
526   // Native regexp only needs room to output captures. Registers are handled
527   // internally.
528   return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
529 #endif  // V8_INTERPRETED_REGEXP
530 }
531
532
533 int RegExpImpl::IrregexpExecRaw(Handle<JSRegExp> regexp,
534                                 Handle<String> subject,
535                                 int index,
536                                 int32_t* output,
537                                 int output_size) {
538   Isolate* isolate = regexp->GetIsolate();
539
540   Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()), isolate);
541
542   DCHECK(index >= 0);
543   DCHECK(index <= subject->length());
544   DCHECK(subject->IsFlat());
545
546   bool is_ascii = subject->IsOneByteRepresentationUnderneath();
547
548 #ifndef V8_INTERPRETED_REGEXP
549   DCHECK(output_size >= (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
550   do {
551     EnsureCompiledIrregexp(regexp, subject, is_ascii);
552     Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii), isolate);
553     // The stack is used to allocate registers for the compiled regexp code.
554     // This means that in case of failure, the output registers array is left
555     // untouched and contains the capture results from the previous successful
556     // match.  We can use that to set the last match info lazily.
557     NativeRegExpMacroAssembler::Result res =
558         NativeRegExpMacroAssembler::Match(code,
559                                           subject,
560                                           output,
561                                           output_size,
562                                           index,
563                                           isolate);
564     if (res != NativeRegExpMacroAssembler::RETRY) {
565       DCHECK(res != NativeRegExpMacroAssembler::EXCEPTION ||
566              isolate->has_pending_exception());
567       STATIC_ASSERT(
568           static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
569       STATIC_ASSERT(
570           static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
571       STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
572                     == RE_EXCEPTION);
573       return static_cast<IrregexpResult>(res);
574     }
575     // If result is RETRY, the string has changed representation, and we
576     // must restart from scratch.
577     // In this case, it means we must make sure we are prepared to handle
578     // the, potentially, different subject (the string can switch between
579     // being internal and external, and even between being ASCII and UC16,
580     // but the characters are always the same).
581     IrregexpPrepare(regexp, subject);
582     is_ascii = subject->IsOneByteRepresentationUnderneath();
583   } while (true);
584   UNREACHABLE();
585   return RE_EXCEPTION;
586 #else  // V8_INTERPRETED_REGEXP
587
588   DCHECK(output_size >= IrregexpNumberOfRegisters(*irregexp));
589   // We must have done EnsureCompiledIrregexp, so we can get the number of
590   // registers.
591   int number_of_capture_registers =
592       (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
593   int32_t* raw_output = &output[number_of_capture_registers];
594   // We do not touch the actual capture result registers until we know there
595   // has been a match so that we can use those capture results to set the
596   // last match info.
597   for (int i = number_of_capture_registers - 1; i >= 0; i--) {
598     raw_output[i] = -1;
599   }
600   Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii), isolate);
601
602   IrregexpResult result = IrregexpInterpreter::Match(isolate,
603                                                      byte_codes,
604                                                      subject,
605                                                      raw_output,
606                                                      index);
607   if (result == RE_SUCCESS) {
608     // Copy capture results to the start of the registers array.
609     MemCopy(output, raw_output, number_of_capture_registers * sizeof(int32_t));
610   }
611   if (result == RE_EXCEPTION) {
612     DCHECK(!isolate->has_pending_exception());
613     isolate->StackOverflow();
614   }
615   return result;
616 #endif  // V8_INTERPRETED_REGEXP
617 }
618
619
620 MaybeHandle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> regexp,
621                                              Handle<String> subject,
622                                              int previous_index,
623                                              Handle<JSArray> last_match_info) {
624   Isolate* isolate = regexp->GetIsolate();
625   DCHECK_EQ(regexp->TypeTag(), JSRegExp::IRREGEXP);
626
627   // Prepare space for the return values.
628 #if defined(V8_INTERPRETED_REGEXP) && defined(DEBUG)
629   if (FLAG_trace_regexp_bytecodes) {
630     String* pattern = regexp->Pattern();
631     PrintF("\n\nRegexp match:   /%s/\n\n", pattern->ToCString().get());
632     PrintF("\n\nSubject string: '%s'\n\n", subject->ToCString().get());
633   }
634 #endif
635   int required_registers = RegExpImpl::IrregexpPrepare(regexp, subject);
636   if (required_registers < 0) {
637     // Compiling failed with an exception.
638     DCHECK(isolate->has_pending_exception());
639     return MaybeHandle<Object>();
640   }
641
642   int32_t* output_registers = NULL;
643   if (required_registers > Isolate::kJSRegexpStaticOffsetsVectorSize) {
644     output_registers = NewArray<int32_t>(required_registers);
645   }
646   SmartArrayPointer<int32_t> auto_release(output_registers);
647   if (output_registers == NULL) {
648     output_registers = isolate->jsregexp_static_offsets_vector();
649   }
650
651   int res = RegExpImpl::IrregexpExecRaw(
652       regexp, subject, previous_index, output_registers, required_registers);
653   if (res == RE_SUCCESS) {
654     int capture_count =
655         IrregexpNumberOfCaptures(FixedArray::cast(regexp->data()));
656     return SetLastMatchInfo(
657         last_match_info, subject, capture_count, output_registers);
658   }
659   if (res == RE_EXCEPTION) {
660     DCHECK(isolate->has_pending_exception());
661     return MaybeHandle<Object>();
662   }
663   DCHECK(res == RE_FAILURE);
664   return isolate->factory()->null_value();
665 }
666
667
668 Handle<JSArray> RegExpImpl::SetLastMatchInfo(Handle<JSArray> last_match_info,
669                                              Handle<String> subject,
670                                              int capture_count,
671                                              int32_t* match) {
672   DCHECK(last_match_info->HasFastObjectElements());
673   int capture_register_count = (capture_count + 1) * 2;
674   JSArray::EnsureSize(last_match_info,
675                       capture_register_count + kLastMatchOverhead);
676   DisallowHeapAllocation no_allocation;
677   FixedArray* array = FixedArray::cast(last_match_info->elements());
678   if (match != NULL) {
679     for (int i = 0; i < capture_register_count; i += 2) {
680       SetCapture(array, i, match[i]);
681       SetCapture(array, i + 1, match[i + 1]);
682     }
683   }
684   SetLastCaptureCount(array, capture_register_count);
685   SetLastSubject(array, *subject);
686   SetLastInput(array, *subject);
687   return last_match_info;
688 }
689
690
691 RegExpImpl::GlobalCache::GlobalCache(Handle<JSRegExp> regexp,
692                                      Handle<String> subject,
693                                      bool is_global,
694                                      Isolate* isolate)
695   : register_array_(NULL),
696     register_array_size_(0),
697     regexp_(regexp),
698     subject_(subject) {
699 #ifdef V8_INTERPRETED_REGEXP
700   bool interpreted = true;
701 #else
702   bool interpreted = false;
703 #endif  // V8_INTERPRETED_REGEXP
704
705   if (regexp_->TypeTag() == JSRegExp::ATOM) {
706     static const int kAtomRegistersPerMatch = 2;
707     registers_per_match_ = kAtomRegistersPerMatch;
708     // There is no distinction between interpreted and native for atom regexps.
709     interpreted = false;
710   } else {
711     registers_per_match_ = RegExpImpl::IrregexpPrepare(regexp_, subject_);
712     if (registers_per_match_ < 0) {
713       num_matches_ = -1;  // Signal exception.
714       return;
715     }
716   }
717
718   if (is_global && !interpreted) {
719     register_array_size_ =
720         Max(registers_per_match_, Isolate::kJSRegexpStaticOffsetsVectorSize);
721     max_matches_ = register_array_size_ / registers_per_match_;
722   } else {
723     // Global loop in interpreted regexp is not implemented.  We choose
724     // the size of the offsets vector so that it can only store one match.
725     register_array_size_ = registers_per_match_;
726     max_matches_ = 1;
727   }
728
729   if (register_array_size_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
730     register_array_ = NewArray<int32_t>(register_array_size_);
731   } else {
732     register_array_ = isolate->jsregexp_static_offsets_vector();
733   }
734
735   // Set state so that fetching the results the first time triggers a call
736   // to the compiled regexp.
737   current_match_index_ = max_matches_ - 1;
738   num_matches_ = max_matches_;
739   DCHECK(registers_per_match_ >= 2);  // Each match has at least one capture.
740   DCHECK_GE(register_array_size_, registers_per_match_);
741   int32_t* last_match =
742       &register_array_[current_match_index_ * registers_per_match_];
743   last_match[0] = -1;
744   last_match[1] = 0;
745 }
746
747
748 // -------------------------------------------------------------------
749 // Implementation of the Irregexp regular expression engine.
750 //
751 // The Irregexp regular expression engine is intended to be a complete
752 // implementation of ECMAScript regular expressions.  It generates either
753 // bytecodes or native code.
754
755 //   The Irregexp regexp engine is structured in three steps.
756 //   1) The parser generates an abstract syntax tree.  See ast.cc.
757 //   2) From the AST a node network is created.  The nodes are all
758 //      subclasses of RegExpNode.  The nodes represent states when
759 //      executing a regular expression.  Several optimizations are
760 //      performed on the node network.
761 //   3) From the nodes we generate either byte codes or native code
762 //      that can actually execute the regular expression (perform
763 //      the search).  The code generation step is described in more
764 //      detail below.
765
766 // Code generation.
767 //
768 //   The nodes are divided into four main categories.
769 //   * Choice nodes
770 //        These represent places where the regular expression can
771 //        match in more than one way.  For example on entry to an
772 //        alternation (foo|bar) or a repetition (*, +, ? or {}).
773 //   * Action nodes
774 //        These represent places where some action should be
775 //        performed.  Examples include recording the current position
776 //        in the input string to a register (in order to implement
777 //        captures) or other actions on register for example in order
778 //        to implement the counters needed for {} repetitions.
779 //   * Matching nodes
780 //        These attempt to match some element part of the input string.
781 //        Examples of elements include character classes, plain strings
782 //        or back references.
783 //   * End nodes
784 //        These are used to implement the actions required on finding
785 //        a successful match or failing to find a match.
786 //
787 //   The code generated (whether as byte codes or native code) maintains
788 //   some state as it runs.  This consists of the following elements:
789 //
790 //   * The capture registers.  Used for string captures.
791 //   * Other registers.  Used for counters etc.
792 //   * The current position.
793 //   * The stack of backtracking information.  Used when a matching node
794 //     fails to find a match and needs to try an alternative.
795 //
796 // Conceptual regular expression execution model:
797 //
798 //   There is a simple conceptual model of regular expression execution
799 //   which will be presented first.  The actual code generated is a more
800 //   efficient simulation of the simple conceptual model:
801 //
802 //   * Choice nodes are implemented as follows:
803 //     For each choice except the last {
804 //       push current position
805 //       push backtrack code location
806 //       <generate code to test for choice>
807 //       backtrack code location:
808 //       pop current position
809 //     }
810 //     <generate code to test for last choice>
811 //
812 //   * Actions nodes are generated as follows
813 //     <push affected registers on backtrack stack>
814 //     <generate code to perform action>
815 //     push backtrack code location
816 //     <generate code to test for following nodes>
817 //     backtrack code location:
818 //     <pop affected registers to restore their state>
819 //     <pop backtrack location from stack and go to it>
820 //
821 //   * Matching nodes are generated as follows:
822 //     if input string matches at current position
823 //       update current position
824 //       <generate code to test for following nodes>
825 //     else
826 //       <pop backtrack location from stack and go to it>
827 //
828 //   Thus it can be seen that the current position is saved and restored
829 //   by the choice nodes, whereas the registers are saved and restored by
830 //   by the action nodes that manipulate them.
831 //
832 //   The other interesting aspect of this model is that nodes are generated
833 //   at the point where they are needed by a recursive call to Emit().  If
834 //   the node has already been code generated then the Emit() call will
835 //   generate a jump to the previously generated code instead.  In order to
836 //   limit recursion it is possible for the Emit() function to put the node
837 //   on a work list for later generation and instead generate a jump.  The
838 //   destination of the jump is resolved later when the code is generated.
839 //
840 // Actual regular expression code generation.
841 //
842 //   Code generation is actually more complicated than the above.  In order
843 //   to improve the efficiency of the generated code some optimizations are
844 //   performed
845 //
846 //   * Choice nodes have 1-character lookahead.
847 //     A choice node looks at the following character and eliminates some of
848 //     the choices immediately based on that character.  This is not yet
849 //     implemented.
850 //   * Simple greedy loops store reduced backtracking information.
851 //     A quantifier like /.*foo/m will greedily match the whole input.  It will
852 //     then need to backtrack to a point where it can match "foo".  The naive
853 //     implementation of this would push each character position onto the
854 //     backtracking stack, then pop them off one by one.  This would use space
855 //     proportional to the length of the input string.  However since the "."
856 //     can only match in one way and always has a constant length (in this case
857 //     of 1) it suffices to store the current position on the top of the stack
858 //     once.  Matching now becomes merely incrementing the current position and
859 //     backtracking becomes decrementing the current position and checking the
860 //     result against the stored current position.  This is faster and saves
861 //     space.
862 //   * The current state is virtualized.
863 //     This is used to defer expensive operations until it is clear that they
864 //     are needed and to generate code for a node more than once, allowing
865 //     specialized an efficient versions of the code to be created. This is
866 //     explained in the section below.
867 //
868 // Execution state virtualization.
869 //
870 //   Instead of emitting code, nodes that manipulate the state can record their
871 //   manipulation in an object called the Trace.  The Trace object can record a
872 //   current position offset, an optional backtrack code location on the top of
873 //   the virtualized backtrack stack and some register changes.  When a node is
874 //   to be emitted it can flush the Trace or update it.  Flushing the Trace
875 //   will emit code to bring the actual state into line with the virtual state.
876 //   Avoiding flushing the state can postpone some work (e.g. updates of capture
877 //   registers).  Postponing work can save time when executing the regular
878 //   expression since it may be found that the work never has to be done as a
879 //   failure to match can occur.  In addition it is much faster to jump to a
880 //   known backtrack code location than it is to pop an unknown backtrack
881 //   location from the stack and jump there.
882 //
883 //   The virtual state found in the Trace affects code generation.  For example
884 //   the virtual state contains the difference between the actual current
885 //   position and the virtual current position, and matching code needs to use
886 //   this offset to attempt a match in the correct location of the input
887 //   string.  Therefore code generated for a non-trivial trace is specialized
888 //   to that trace.  The code generator therefore has the ability to generate
889 //   code for each node several times.  In order to limit the size of the
890 //   generated code there is an arbitrary limit on how many specialized sets of
891 //   code may be generated for a given node.  If the limit is reached, the
892 //   trace is flushed and a generic version of the code for a node is emitted.
893 //   This is subsequently used for that node.  The code emitted for non-generic
894 //   trace is not recorded in the node and so it cannot currently be reused in
895 //   the event that code generation is requested for an identical trace.
896
897
898 void RegExpTree::AppendToText(RegExpText* text, Zone* zone) {
899   UNREACHABLE();
900 }
901
902
903 void RegExpAtom::AppendToText(RegExpText* text, Zone* zone) {
904   text->AddElement(TextElement::Atom(this), zone);
905 }
906
907
908 void RegExpCharacterClass::AppendToText(RegExpText* text, Zone* zone) {
909   text->AddElement(TextElement::CharClass(this), zone);
910 }
911
912
913 void RegExpText::AppendToText(RegExpText* text, Zone* zone) {
914   for (int i = 0; i < elements()->length(); i++)
915     text->AddElement(elements()->at(i), zone);
916 }
917
918
919 TextElement TextElement::Atom(RegExpAtom* atom) {
920   return TextElement(ATOM, atom);
921 }
922
923
924 TextElement TextElement::CharClass(RegExpCharacterClass* char_class) {
925   return TextElement(CHAR_CLASS, char_class);
926 }
927
928
929 int TextElement::length() const {
930   switch (text_type()) {
931     case ATOM:
932       return atom()->length();
933
934     case CHAR_CLASS:
935       return 1;
936   }
937   UNREACHABLE();
938   return 0;
939 }
940
941
942 DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
943   if (table_ == NULL) {
944     table_ = new(zone()) DispatchTable(zone());
945     DispatchTableConstructor cons(table_, ignore_case, zone());
946     cons.BuildTable(this);
947   }
948   return table_;
949 }
950
951
952 class FrequencyCollator {
953  public:
954   FrequencyCollator() : total_samples_(0) {
955     for (int i = 0; i < RegExpMacroAssembler::kTableSize; i++) {
956       frequencies_[i] = CharacterFrequency(i);
957     }
958   }
959
960   void CountCharacter(int character) {
961     int index = (character & RegExpMacroAssembler::kTableMask);
962     frequencies_[index].Increment();
963     total_samples_++;
964   }
965
966   // Does not measure in percent, but rather per-128 (the table size from the
967   // regexp macro assembler).
968   int Frequency(int in_character) {
969     DCHECK((in_character & RegExpMacroAssembler::kTableMask) == in_character);
970     if (total_samples_ < 1) return 1;  // Division by zero.
971     int freq_in_per128 =
972         (frequencies_[in_character].counter() * 128) / total_samples_;
973     return freq_in_per128;
974   }
975
976  private:
977   class CharacterFrequency {
978    public:
979     CharacterFrequency() : counter_(0), character_(-1) { }
980     explicit CharacterFrequency(int character)
981         : counter_(0), character_(character) { }
982
983     void Increment() { counter_++; }
984     int counter() { return counter_; }
985     int character() { return character_; }
986
987    private:
988     int counter_;
989     int character_;
990   };
991
992
993  private:
994   CharacterFrequency frequencies_[RegExpMacroAssembler::kTableSize];
995   int total_samples_;
996 };
997
998
999 class RegExpCompiler {
1000  public:
1001   RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii,
1002                  Zone* zone);
1003
1004   int AllocateRegister() {
1005     if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
1006       reg_exp_too_big_ = true;
1007       return next_register_;
1008     }
1009     return next_register_++;
1010   }
1011
1012   RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
1013                                            RegExpNode* start,
1014                                            int capture_count,
1015                                            Handle<String> pattern);
1016
1017   inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
1018
1019   static const int kImplementationOffset = 0;
1020   static const int kNumberOfRegistersOffset = 0;
1021   static const int kCodeOffset = 1;
1022
1023   RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
1024   EndNode* accept() { return accept_; }
1025
1026   static const int kMaxRecursion = 100;
1027   inline int recursion_depth() { return recursion_depth_; }
1028   inline void IncrementRecursionDepth() { recursion_depth_++; }
1029   inline void DecrementRecursionDepth() { recursion_depth_--; }
1030
1031   void SetRegExpTooBig() { reg_exp_too_big_ = true; }
1032
1033   inline bool ignore_case() { return ignore_case_; }
1034   inline bool ascii() { return ascii_; }
1035   FrequencyCollator* frequency_collator() { return &frequency_collator_; }
1036
1037   int current_expansion_factor() { return current_expansion_factor_; }
1038   void set_current_expansion_factor(int value) {
1039     current_expansion_factor_ = value;
1040   }
1041
1042   Zone* zone() const { return zone_; }
1043
1044   static const int kNoRegister = -1;
1045
1046  private:
1047   EndNode* accept_;
1048   int next_register_;
1049   List<RegExpNode*>* work_list_;
1050   int recursion_depth_;
1051   RegExpMacroAssembler* macro_assembler_;
1052   bool ignore_case_;
1053   bool ascii_;
1054   bool reg_exp_too_big_;
1055   int current_expansion_factor_;
1056   FrequencyCollator frequency_collator_;
1057   Zone* zone_;
1058 };
1059
1060
1061 class RecursionCheck {
1062  public:
1063   explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
1064     compiler->IncrementRecursionDepth();
1065   }
1066   ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
1067  private:
1068   RegExpCompiler* compiler_;
1069 };
1070
1071
1072 static RegExpEngine::CompilationResult IrregexpRegExpTooBig(Isolate* isolate) {
1073   return RegExpEngine::CompilationResult(isolate, "RegExp too big");
1074 }
1075
1076
1077 // Attempts to compile the regexp using an Irregexp code generator.  Returns
1078 // a fixed array or a null handle depending on whether it succeeded.
1079 RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii,
1080                                Zone* zone)
1081     : next_register_(2 * (capture_count + 1)),
1082       work_list_(NULL),
1083       recursion_depth_(0),
1084       ignore_case_(ignore_case),
1085       ascii_(ascii),
1086       reg_exp_too_big_(false),
1087       current_expansion_factor_(1),
1088       frequency_collator_(),
1089       zone_(zone) {
1090   accept_ = new(zone) EndNode(EndNode::ACCEPT, zone);
1091   DCHECK(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
1092 }
1093
1094
1095 RegExpEngine::CompilationResult RegExpCompiler::Assemble(
1096     RegExpMacroAssembler* macro_assembler,
1097     RegExpNode* start,
1098     int capture_count,
1099     Handle<String> pattern) {
1100   Heap* heap = pattern->GetHeap();
1101
1102   bool use_slow_safe_regexp_compiler = false;
1103   if (heap->total_regexp_code_generated() >
1104           RegExpImpl::kRegWxpCompiledLimit &&
1105       heap->isolate()->memory_allocator()->SizeExecutable() >
1106           RegExpImpl::kRegExpExecutableMemoryLimit) {
1107     use_slow_safe_regexp_compiler = true;
1108   }
1109
1110   macro_assembler->set_slow_safe(use_slow_safe_regexp_compiler);
1111
1112 #ifdef DEBUG
1113   if (FLAG_trace_regexp_assembler)
1114     macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
1115   else
1116 #endif
1117     macro_assembler_ = macro_assembler;
1118
1119   List <RegExpNode*> work_list(0);
1120   work_list_ = &work_list;
1121   Label fail;
1122   macro_assembler_->PushBacktrack(&fail);
1123   Trace new_trace;
1124   start->Emit(this, &new_trace);
1125   macro_assembler_->Bind(&fail);
1126   macro_assembler_->Fail();
1127   while (!work_list.is_empty()) {
1128     work_list.RemoveLast()->Emit(this, &new_trace);
1129   }
1130   if (reg_exp_too_big_) return IrregexpRegExpTooBig(zone_->isolate());
1131
1132   Handle<HeapObject> code = macro_assembler_->GetCode(pattern);
1133   heap->IncreaseTotalRegexpCodeGenerated(code->Size());
1134   work_list_ = NULL;
1135 #ifdef DEBUG
1136   if (FLAG_print_code) {
1137     CodeTracer::Scope trace_scope(heap->isolate()->GetCodeTracer());
1138     OFStream os(trace_scope.file());
1139     Handle<Code>::cast(code)->Disassemble(pattern->ToCString().get(), os);
1140   }
1141   if (FLAG_trace_regexp_assembler) {
1142     delete macro_assembler_;
1143   }
1144 #endif
1145   return RegExpEngine::CompilationResult(*code, next_register_);
1146 }
1147
1148
1149 bool Trace::DeferredAction::Mentions(int that) {
1150   if (action_type() == ActionNode::CLEAR_CAPTURES) {
1151     Interval range = static_cast<DeferredClearCaptures*>(this)->range();
1152     return range.Contains(that);
1153   } else {
1154     return reg() == that;
1155   }
1156 }
1157
1158
1159 bool Trace::mentions_reg(int reg) {
1160   for (DeferredAction* action = actions_;
1161        action != NULL;
1162        action = action->next()) {
1163     if (action->Mentions(reg))
1164       return true;
1165   }
1166   return false;
1167 }
1168
1169
1170 bool Trace::GetStoredPosition(int reg, int* cp_offset) {
1171   DCHECK_EQ(0, *cp_offset);
1172   for (DeferredAction* action = actions_;
1173        action != NULL;
1174        action = action->next()) {
1175     if (action->Mentions(reg)) {
1176       if (action->action_type() == ActionNode::STORE_POSITION) {
1177         *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
1178         return true;
1179       } else {
1180         return false;
1181       }
1182     }
1183   }
1184   return false;
1185 }
1186
1187
1188 int Trace::FindAffectedRegisters(OutSet* affected_registers,
1189                                  Zone* zone) {
1190   int max_register = RegExpCompiler::kNoRegister;
1191   for (DeferredAction* action = actions_;
1192        action != NULL;
1193        action = action->next()) {
1194     if (action->action_type() == ActionNode::CLEAR_CAPTURES) {
1195       Interval range = static_cast<DeferredClearCaptures*>(action)->range();
1196       for (int i = range.from(); i <= range.to(); i++)
1197         affected_registers->Set(i, zone);
1198       if (range.to() > max_register) max_register = range.to();
1199     } else {
1200       affected_registers->Set(action->reg(), zone);
1201       if (action->reg() > max_register) max_register = action->reg();
1202     }
1203   }
1204   return max_register;
1205 }
1206
1207
1208 void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
1209                                      int max_register,
1210                                      const OutSet& registers_to_pop,
1211                                      const OutSet& registers_to_clear) {
1212   for (int reg = max_register; reg >= 0; reg--) {
1213     if (registers_to_pop.Get(reg)) {
1214       assembler->PopRegister(reg);
1215     } else if (registers_to_clear.Get(reg)) {
1216       int clear_to = reg;
1217       while (reg > 0 && registers_to_clear.Get(reg - 1)) {
1218         reg--;
1219       }
1220       assembler->ClearRegisters(reg, clear_to);
1221     }
1222   }
1223 }
1224
1225
1226 void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
1227                                    int max_register,
1228                                    const OutSet& affected_registers,
1229                                    OutSet* registers_to_pop,
1230                                    OutSet* registers_to_clear,
1231                                    Zone* zone) {
1232   // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
1233   const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
1234
1235   // Count pushes performed to force a stack limit check occasionally.
1236   int pushes = 0;
1237
1238   for (int reg = 0; reg <= max_register; reg++) {
1239     if (!affected_registers.Get(reg)) {
1240       continue;
1241     }
1242
1243     // The chronologically first deferred action in the trace
1244     // is used to infer the action needed to restore a register
1245     // to its previous state (or not, if it's safe to ignore it).
1246     enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
1247     DeferredActionUndoType undo_action = IGNORE;
1248
1249     int value = 0;
1250     bool absolute = false;
1251     bool clear = false;
1252     int store_position = -1;
1253     // This is a little tricky because we are scanning the actions in reverse
1254     // historical order (newest first).
1255     for (DeferredAction* action = actions_;
1256          action != NULL;
1257          action = action->next()) {
1258       if (action->Mentions(reg)) {
1259         switch (action->action_type()) {
1260           case ActionNode::SET_REGISTER: {
1261             Trace::DeferredSetRegister* psr =
1262                 static_cast<Trace::DeferredSetRegister*>(action);
1263             if (!absolute) {
1264               value += psr->value();
1265               absolute = true;
1266             }
1267             // SET_REGISTER is currently only used for newly introduced loop
1268             // counters. They can have a significant previous value if they
1269             // occour in a loop. TODO(lrn): Propagate this information, so
1270             // we can set undo_action to IGNORE if we know there is no value to
1271             // restore.
1272             undo_action = RESTORE;
1273             DCHECK_EQ(store_position, -1);
1274             DCHECK(!clear);
1275             break;
1276           }
1277           case ActionNode::INCREMENT_REGISTER:
1278             if (!absolute) {
1279               value++;
1280             }
1281             DCHECK_EQ(store_position, -1);
1282             DCHECK(!clear);
1283             undo_action = RESTORE;
1284             break;
1285           case ActionNode::STORE_POSITION: {
1286             Trace::DeferredCapture* pc =
1287                 static_cast<Trace::DeferredCapture*>(action);
1288             if (!clear && store_position == -1) {
1289               store_position = pc->cp_offset();
1290             }
1291
1292             // For captures we know that stores and clears alternate.
1293             // Other register, are never cleared, and if the occur
1294             // inside a loop, they might be assigned more than once.
1295             if (reg <= 1) {
1296               // Registers zero and one, aka "capture zero", is
1297               // always set correctly if we succeed. There is no
1298               // need to undo a setting on backtrack, because we
1299               // will set it again or fail.
1300               undo_action = IGNORE;
1301             } else {
1302               undo_action = pc->is_capture() ? CLEAR : RESTORE;
1303             }
1304             DCHECK(!absolute);
1305             DCHECK_EQ(value, 0);
1306             break;
1307           }
1308           case ActionNode::CLEAR_CAPTURES: {
1309             // Since we're scanning in reverse order, if we've already
1310             // set the position we have to ignore historically earlier
1311             // clearing operations.
1312             if (store_position == -1) {
1313               clear = true;
1314             }
1315             undo_action = RESTORE;
1316             DCHECK(!absolute);
1317             DCHECK_EQ(value, 0);
1318             break;
1319           }
1320           default:
1321             UNREACHABLE();
1322             break;
1323         }
1324       }
1325     }
1326     // Prepare for the undo-action (e.g., push if it's going to be popped).
1327     if (undo_action == RESTORE) {
1328       pushes++;
1329       RegExpMacroAssembler::StackCheckFlag stack_check =
1330           RegExpMacroAssembler::kNoStackLimitCheck;
1331       if (pushes == push_limit) {
1332         stack_check = RegExpMacroAssembler::kCheckStackLimit;
1333         pushes = 0;
1334       }
1335
1336       assembler->PushRegister(reg, stack_check);
1337       registers_to_pop->Set(reg, zone);
1338     } else if (undo_action == CLEAR) {
1339       registers_to_clear->Set(reg, zone);
1340     }
1341     // Perform the chronologically last action (or accumulated increment)
1342     // for the register.
1343     if (store_position != -1) {
1344       assembler->WriteCurrentPositionToRegister(reg, store_position);
1345     } else if (clear) {
1346       assembler->ClearRegisters(reg, reg);
1347     } else if (absolute) {
1348       assembler->SetRegister(reg, value);
1349     } else if (value != 0) {
1350       assembler->AdvanceRegister(reg, value);
1351     }
1352   }
1353 }
1354
1355
1356 // This is called as we come into a loop choice node and some other tricky
1357 // nodes.  It normalizes the state of the code generator to ensure we can
1358 // generate generic code.
1359 void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
1360   RegExpMacroAssembler* assembler = compiler->macro_assembler();
1361
1362   DCHECK(!is_trivial());
1363
1364   if (actions_ == NULL && backtrack() == NULL) {
1365     // Here we just have some deferred cp advances to fix and we are back to
1366     // a normal situation.  We may also have to forget some information gained
1367     // through a quick check that was already performed.
1368     if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
1369     // Create a new trivial state and generate the node with that.
1370     Trace new_state;
1371     successor->Emit(compiler, &new_state);
1372     return;
1373   }
1374
1375   // Generate deferred actions here along with code to undo them again.
1376   OutSet affected_registers;
1377
1378   if (backtrack() != NULL) {
1379     // Here we have a concrete backtrack location.  These are set up by choice
1380     // nodes and so they indicate that we have a deferred save of the current
1381     // position which we may need to emit here.
1382     assembler->PushCurrentPosition();
1383   }
1384
1385   int max_register = FindAffectedRegisters(&affected_registers,
1386                                            compiler->zone());
1387   OutSet registers_to_pop;
1388   OutSet registers_to_clear;
1389   PerformDeferredActions(assembler,
1390                          max_register,
1391                          affected_registers,
1392                          &registers_to_pop,
1393                          &registers_to_clear,
1394                          compiler->zone());
1395   if (cp_offset_ != 0) {
1396     assembler->AdvanceCurrentPosition(cp_offset_);
1397   }
1398
1399   // Create a new trivial state and generate the node with that.
1400   Label undo;
1401   assembler->PushBacktrack(&undo);
1402   Trace new_state;
1403   successor->Emit(compiler, &new_state);
1404
1405   // On backtrack we need to restore state.
1406   assembler->Bind(&undo);
1407   RestoreAffectedRegisters(assembler,
1408                            max_register,
1409                            registers_to_pop,
1410                            registers_to_clear);
1411   if (backtrack() == NULL) {
1412     assembler->Backtrack();
1413   } else {
1414     assembler->PopCurrentPosition();
1415     assembler->GoTo(backtrack());
1416   }
1417 }
1418
1419
1420 void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
1421   RegExpMacroAssembler* assembler = compiler->macro_assembler();
1422
1423   // Omit flushing the trace. We discard the entire stack frame anyway.
1424
1425   if (!label()->is_bound()) {
1426     // We are completely independent of the trace, since we ignore it,
1427     // so this code can be used as the generic version.
1428     assembler->Bind(label());
1429   }
1430
1431   // Throw away everything on the backtrack stack since the start
1432   // of the negative submatch and restore the character position.
1433   assembler->ReadCurrentPositionFromRegister(current_position_register_);
1434   assembler->ReadStackPointerFromRegister(stack_pointer_register_);
1435   if (clear_capture_count_ > 0) {
1436     // Clear any captures that might have been performed during the success
1437     // of the body of the negative look-ahead.
1438     int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1439     assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1440   }
1441   // Now that we have unwound the stack we find at the top of the stack the
1442   // backtrack that the BeginSubmatch node got.
1443   assembler->Backtrack();
1444 }
1445
1446
1447 void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
1448   if (!trace->is_trivial()) {
1449     trace->Flush(compiler, this);
1450     return;
1451   }
1452   RegExpMacroAssembler* assembler = compiler->macro_assembler();
1453   if (!label()->is_bound()) {
1454     assembler->Bind(label());
1455   }
1456   switch (action_) {
1457     case ACCEPT:
1458       assembler->Succeed();
1459       return;
1460     case BACKTRACK:
1461       assembler->GoTo(trace->backtrack());
1462       return;
1463     case NEGATIVE_SUBMATCH_SUCCESS:
1464       // This case is handled in a different virtual method.
1465       UNREACHABLE();
1466   }
1467   UNIMPLEMENTED();
1468 }
1469
1470
1471 void GuardedAlternative::AddGuard(Guard* guard, Zone* zone) {
1472   if (guards_ == NULL)
1473     guards_ = new(zone) ZoneList<Guard*>(1, zone);
1474   guards_->Add(guard, zone);
1475 }
1476
1477
1478 ActionNode* ActionNode::SetRegister(int reg,
1479                                     int val,
1480                                     RegExpNode* on_success) {
1481   ActionNode* result =
1482       new(on_success->zone()) ActionNode(SET_REGISTER, on_success);
1483   result->data_.u_store_register.reg = reg;
1484   result->data_.u_store_register.value = val;
1485   return result;
1486 }
1487
1488
1489 ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1490   ActionNode* result =
1491       new(on_success->zone()) ActionNode(INCREMENT_REGISTER, on_success);
1492   result->data_.u_increment_register.reg = reg;
1493   return result;
1494 }
1495
1496
1497 ActionNode* ActionNode::StorePosition(int reg,
1498                                       bool is_capture,
1499                                       RegExpNode* on_success) {
1500   ActionNode* result =
1501       new(on_success->zone()) ActionNode(STORE_POSITION, on_success);
1502   result->data_.u_position_register.reg = reg;
1503   result->data_.u_position_register.is_capture = is_capture;
1504   return result;
1505 }
1506
1507
1508 ActionNode* ActionNode::ClearCaptures(Interval range,
1509                                       RegExpNode* on_success) {
1510   ActionNode* result =
1511       new(on_success->zone()) ActionNode(CLEAR_CAPTURES, on_success);
1512   result->data_.u_clear_captures.range_from = range.from();
1513   result->data_.u_clear_captures.range_to = range.to();
1514   return result;
1515 }
1516
1517
1518 ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1519                                       int position_reg,
1520                                       RegExpNode* on_success) {
1521   ActionNode* result =
1522       new(on_success->zone()) ActionNode(BEGIN_SUBMATCH, on_success);
1523   result->data_.u_submatch.stack_pointer_register = stack_reg;
1524   result->data_.u_submatch.current_position_register = position_reg;
1525   return result;
1526 }
1527
1528
1529 ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1530                                                 int position_reg,
1531                                                 int clear_register_count,
1532                                                 int clear_register_from,
1533                                                 RegExpNode* on_success) {
1534   ActionNode* result =
1535       new(on_success->zone()) ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
1536   result->data_.u_submatch.stack_pointer_register = stack_reg;
1537   result->data_.u_submatch.current_position_register = position_reg;
1538   result->data_.u_submatch.clear_register_count = clear_register_count;
1539   result->data_.u_submatch.clear_register_from = clear_register_from;
1540   return result;
1541 }
1542
1543
1544 ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1545                                         int repetition_register,
1546                                         int repetition_limit,
1547                                         RegExpNode* on_success) {
1548   ActionNode* result =
1549       new(on_success->zone()) ActionNode(EMPTY_MATCH_CHECK, on_success);
1550   result->data_.u_empty_match_check.start_register = start_register;
1551   result->data_.u_empty_match_check.repetition_register = repetition_register;
1552   result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1553   return result;
1554 }
1555
1556
1557 #define DEFINE_ACCEPT(Type)                                          \
1558   void Type##Node::Accept(NodeVisitor* visitor) {                    \
1559     visitor->Visit##Type(this);                                      \
1560   }
1561 FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1562 #undef DEFINE_ACCEPT
1563
1564
1565 void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1566   visitor->VisitLoopChoice(this);
1567 }
1568
1569
1570 // -------------------------------------------------------------------
1571 // Emit code.
1572
1573
1574 void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1575                                Guard* guard,
1576                                Trace* trace) {
1577   switch (guard->op()) {
1578     case Guard::LT:
1579       DCHECK(!trace->mentions_reg(guard->reg()));
1580       macro_assembler->IfRegisterGE(guard->reg(),
1581                                     guard->value(),
1582                                     trace->backtrack());
1583       break;
1584     case Guard::GEQ:
1585       DCHECK(!trace->mentions_reg(guard->reg()));
1586       macro_assembler->IfRegisterLT(guard->reg(),
1587                                     guard->value(),
1588                                     trace->backtrack());
1589       break;
1590   }
1591 }
1592
1593
1594 // Returns the number of characters in the equivalence class, omitting those
1595 // that cannot occur in the source string because it is ASCII.
1596 static int GetCaseIndependentLetters(Isolate* isolate,
1597                                      uc16 character,
1598                                      bool ascii_subject,
1599                                      unibrow::uchar* letters) {
1600   int length =
1601       isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
1602   // Unibrow returns 0 or 1 for characters where case independence is
1603   // trivial.
1604   if (length == 0) {
1605     letters[0] = character;
1606     length = 1;
1607   }
1608   if (!ascii_subject || character <= String::kMaxOneByteCharCode) {
1609     return length;
1610   }
1611   // The standard requires that non-ASCII characters cannot have ASCII
1612   // character codes in their equivalence class.
1613   return 0;
1614 }
1615
1616
1617 static inline bool EmitSimpleCharacter(Isolate* isolate,
1618                                        RegExpCompiler* compiler,
1619                                        uc16 c,
1620                                        Label* on_failure,
1621                                        int cp_offset,
1622                                        bool check,
1623                                        bool preloaded) {
1624   RegExpMacroAssembler* assembler = compiler->macro_assembler();
1625   bool bound_checked = false;
1626   if (!preloaded) {
1627     assembler->LoadCurrentCharacter(
1628         cp_offset,
1629         on_failure,
1630         check);
1631     bound_checked = true;
1632   }
1633   assembler->CheckNotCharacter(c, on_failure);
1634   return bound_checked;
1635 }
1636
1637
1638 // Only emits non-letters (things that don't have case).  Only used for case
1639 // independent matches.
1640 static inline bool EmitAtomNonLetter(Isolate* isolate,
1641                                      RegExpCompiler* compiler,
1642                                      uc16 c,
1643                                      Label* on_failure,
1644                                      int cp_offset,
1645                                      bool check,
1646                                      bool preloaded) {
1647   RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1648   bool ascii = compiler->ascii();
1649   unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1650   int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
1651   if (length < 1) {
1652     // This can't match.  Must be an ASCII subject and a non-ASCII character.
1653     // We do not need to do anything since the ASCII pass already handled this.
1654     return false;  // Bounds not checked.
1655   }
1656   bool checked = false;
1657   // We handle the length > 1 case in a later pass.
1658   if (length == 1) {
1659     if (ascii && c > String::kMaxOneByteCharCodeU) {
1660       // Can't match - see above.
1661       return false;  // Bounds not checked.
1662     }
1663     if (!preloaded) {
1664       macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1665       checked = check;
1666     }
1667     macro_assembler->CheckNotCharacter(c, on_failure);
1668   }
1669   return checked;
1670 }
1671
1672
1673 static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
1674                                       bool ascii,
1675                                       uc16 c1,
1676                                       uc16 c2,
1677                                       Label* on_failure) {
1678   uc16 char_mask;
1679   if (ascii) {
1680     char_mask = String::kMaxOneByteCharCode;
1681   } else {
1682     char_mask = String::kMaxUtf16CodeUnit;
1683   }
1684   uc16 exor = c1 ^ c2;
1685   // Check whether exor has only one bit set.
1686   if (((exor - 1) & exor) == 0) {
1687     // If c1 and c2 differ only by one bit.
1688     // Ecma262UnCanonicalize always gives the highest number last.
1689     DCHECK(c2 > c1);
1690     uc16 mask = char_mask ^ exor;
1691     macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
1692     return true;
1693   }
1694   DCHECK(c2 > c1);
1695   uc16 diff = c2 - c1;
1696   if (((diff - 1) & diff) == 0 && c1 >= diff) {
1697     // If the characters differ by 2^n but don't differ by one bit then
1698     // subtract the difference from the found character, then do the or
1699     // trick.  We avoid the theoretical case where negative numbers are
1700     // involved in order to simplify code generation.
1701     uc16 mask = char_mask ^ diff;
1702     macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1703                                                     diff,
1704                                                     mask,
1705                                                     on_failure);
1706     return true;
1707   }
1708   return false;
1709 }
1710
1711
1712 typedef bool EmitCharacterFunction(Isolate* isolate,
1713                                    RegExpCompiler* compiler,
1714                                    uc16 c,
1715                                    Label* on_failure,
1716                                    int cp_offset,
1717                                    bool check,
1718                                    bool preloaded);
1719
1720 // Only emits letters (things that have case).  Only used for case independent
1721 // matches.
1722 static inline bool EmitAtomLetter(Isolate* isolate,
1723                                   RegExpCompiler* compiler,
1724                                   uc16 c,
1725                                   Label* on_failure,
1726                                   int cp_offset,
1727                                   bool check,
1728                                   bool preloaded) {
1729   RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1730   bool ascii = compiler->ascii();
1731   unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1732   int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
1733   if (length <= 1) return false;
1734   // We may not need to check against the end of the input string
1735   // if this character lies before a character that matched.
1736   if (!preloaded) {
1737     macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1738   }
1739   Label ok;
1740   DCHECK(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1741   switch (length) {
1742     case 2: {
1743       if (ShortCutEmitCharacterPair(macro_assembler,
1744                                     ascii,
1745                                     chars[0],
1746                                     chars[1],
1747                                     on_failure)) {
1748       } else {
1749         macro_assembler->CheckCharacter(chars[0], &ok);
1750         macro_assembler->CheckNotCharacter(chars[1], on_failure);
1751         macro_assembler->Bind(&ok);
1752       }
1753       break;
1754     }
1755     case 4:
1756       macro_assembler->CheckCharacter(chars[3], &ok);
1757       // Fall through!
1758     case 3:
1759       macro_assembler->CheckCharacter(chars[0], &ok);
1760       macro_assembler->CheckCharacter(chars[1], &ok);
1761       macro_assembler->CheckNotCharacter(chars[2], on_failure);
1762       macro_assembler->Bind(&ok);
1763       break;
1764     default:
1765       UNREACHABLE();
1766       break;
1767   }
1768   return true;
1769 }
1770
1771
1772 static void EmitBoundaryTest(RegExpMacroAssembler* masm,
1773                              int border,
1774                              Label* fall_through,
1775                              Label* above_or_equal,
1776                              Label* below) {
1777   if (below != fall_through) {
1778     masm->CheckCharacterLT(border, below);
1779     if (above_or_equal != fall_through) masm->GoTo(above_or_equal);
1780   } else {
1781     masm->CheckCharacterGT(border - 1, above_or_equal);
1782   }
1783 }
1784
1785
1786 static void EmitDoubleBoundaryTest(RegExpMacroAssembler* masm,
1787                                    int first,
1788                                    int last,
1789                                    Label* fall_through,
1790                                    Label* in_range,
1791                                    Label* out_of_range) {
1792   if (in_range == fall_through) {
1793     if (first == last) {
1794       masm->CheckNotCharacter(first, out_of_range);
1795     } else {
1796       masm->CheckCharacterNotInRange(first, last, out_of_range);
1797     }
1798   } else {
1799     if (first == last) {
1800       masm->CheckCharacter(first, in_range);
1801     } else {
1802       masm->CheckCharacterInRange(first, last, in_range);
1803     }
1804     if (out_of_range != fall_through) masm->GoTo(out_of_range);
1805   }
1806 }
1807
1808
1809 // even_label is for ranges[i] to ranges[i + 1] where i - start_index is even.
1810 // odd_label is for ranges[i] to ranges[i + 1] where i - start_index is odd.
1811 static void EmitUseLookupTable(
1812     RegExpMacroAssembler* masm,
1813     ZoneList<int>* ranges,
1814     int start_index,
1815     int end_index,
1816     int min_char,
1817     Label* fall_through,
1818     Label* even_label,
1819     Label* odd_label) {
1820   static const int kSize = RegExpMacroAssembler::kTableSize;
1821   static const int kMask = RegExpMacroAssembler::kTableMask;
1822
1823   int base = (min_char & ~kMask);
1824   USE(base);
1825
1826   // Assert that everything is on one kTableSize page.
1827   for (int i = start_index; i <= end_index; i++) {
1828     DCHECK_EQ(ranges->at(i) & ~kMask, base);
1829   }
1830   DCHECK(start_index == 0 || (ranges->at(start_index - 1) & ~kMask) <= base);
1831
1832   char templ[kSize];
1833   Label* on_bit_set;
1834   Label* on_bit_clear;
1835   int bit;
1836   if (even_label == fall_through) {
1837     on_bit_set = odd_label;
1838     on_bit_clear = even_label;
1839     bit = 1;
1840   } else {
1841     on_bit_set = even_label;
1842     on_bit_clear = odd_label;
1843     bit = 0;
1844   }
1845   for (int i = 0; i < (ranges->at(start_index) & kMask) && i < kSize; i++) {
1846     templ[i] = bit;
1847   }
1848   int j = 0;
1849   bit ^= 1;
1850   for (int i = start_index; i < end_index; i++) {
1851     for (j = (ranges->at(i) & kMask); j < (ranges->at(i + 1) & kMask); j++) {
1852       templ[j] = bit;
1853     }
1854     bit ^= 1;
1855   }
1856   for (int i = j; i < kSize; i++) {
1857     templ[i] = bit;
1858   }
1859   Factory* factory = masm->zone()->isolate()->factory();
1860   // TODO(erikcorry): Cache these.
1861   Handle<ByteArray> ba = factory->NewByteArray(kSize, TENURED);
1862   for (int i = 0; i < kSize; i++) {
1863     ba->set(i, templ[i]);
1864   }
1865   masm->CheckBitInTable(ba, on_bit_set);
1866   if (on_bit_clear != fall_through) masm->GoTo(on_bit_clear);
1867 }
1868
1869
1870 static void CutOutRange(RegExpMacroAssembler* masm,
1871                         ZoneList<int>* ranges,
1872                         int start_index,
1873                         int end_index,
1874                         int cut_index,
1875                         Label* even_label,
1876                         Label* odd_label) {
1877   bool odd = (((cut_index - start_index) & 1) == 1);
1878   Label* in_range_label = odd ? odd_label : even_label;
1879   Label dummy;
1880   EmitDoubleBoundaryTest(masm,
1881                          ranges->at(cut_index),
1882                          ranges->at(cut_index + 1) - 1,
1883                          &dummy,
1884                          in_range_label,
1885                          &dummy);
1886   DCHECK(!dummy.is_linked());
1887   // Cut out the single range by rewriting the array.  This creates a new
1888   // range that is a merger of the two ranges on either side of the one we
1889   // are cutting out.  The oddity of the labels is preserved.
1890   for (int j = cut_index; j > start_index; j--) {
1891     ranges->at(j) = ranges->at(j - 1);
1892   }
1893   for (int j = cut_index + 1; j < end_index; j++) {
1894     ranges->at(j) = ranges->at(j + 1);
1895   }
1896 }
1897
1898
1899 // Unicode case.  Split the search space into kSize spaces that are handled
1900 // with recursion.
1901 static void SplitSearchSpace(ZoneList<int>* ranges,
1902                              int start_index,
1903                              int end_index,
1904                              int* new_start_index,
1905                              int* new_end_index,
1906                              int* border) {
1907   static const int kSize = RegExpMacroAssembler::kTableSize;
1908   static const int kMask = RegExpMacroAssembler::kTableMask;
1909
1910   int first = ranges->at(start_index);
1911   int last = ranges->at(end_index) - 1;
1912
1913   *new_start_index = start_index;
1914   *border = (ranges->at(start_index) & ~kMask) + kSize;
1915   while (*new_start_index < end_index) {
1916     if (ranges->at(*new_start_index) > *border) break;
1917     (*new_start_index)++;
1918   }
1919   // new_start_index is the index of the first edge that is beyond the
1920   // current kSize space.
1921
1922   // For very large search spaces we do a binary chop search of the non-ASCII
1923   // space instead of just going to the end of the current kSize space.  The
1924   // heuristics are complicated a little by the fact that any 128-character
1925   // encoding space can be quickly tested with a table lookup, so we don't
1926   // wish to do binary chop search at a smaller granularity than that.  A
1927   // 128-character space can take up a lot of space in the ranges array if,
1928   // for example, we only want to match every second character (eg. the lower
1929   // case characters on some Unicode pages).
1930   int binary_chop_index = (end_index + start_index) / 2;
1931   // The first test ensures that we get to the code that handles the ASCII
1932   // range with a single not-taken branch, speeding up this important
1933   // character range (even non-ASCII charset-based text has spaces and
1934   // punctuation).
1935   if (*border - 1 > String::kMaxOneByteCharCode &&  // ASCII case.
1936       end_index - start_index > (*new_start_index - start_index) * 2 &&
1937       last - first > kSize * 2 &&
1938       binary_chop_index > *new_start_index &&
1939       ranges->at(binary_chop_index) >= first + 2 * kSize) {
1940     int scan_forward_for_section_border = binary_chop_index;;
1941     int new_border = (ranges->at(binary_chop_index) | kMask) + 1;
1942
1943     while (scan_forward_for_section_border < end_index) {
1944       if (ranges->at(scan_forward_for_section_border) > new_border) {
1945         *new_start_index = scan_forward_for_section_border;
1946         *border = new_border;
1947         break;
1948       }
1949       scan_forward_for_section_border++;
1950     }
1951   }
1952
1953   DCHECK(*new_start_index > start_index);
1954   *new_end_index = *new_start_index - 1;
1955   if (ranges->at(*new_end_index) == *border) {
1956     (*new_end_index)--;
1957   }
1958   if (*border >= ranges->at(end_index)) {
1959     *border = ranges->at(end_index);
1960     *new_start_index = end_index;  // Won't be used.
1961     *new_end_index = end_index - 1;
1962   }
1963 }
1964
1965
1966 // Gets a series of segment boundaries representing a character class.  If the
1967 // character is in the range between an even and an odd boundary (counting from
1968 // start_index) then go to even_label, otherwise go to odd_label.  We already
1969 // know that the character is in the range of min_char to max_char inclusive.
1970 // Either label can be NULL indicating backtracking.  Either label can also be
1971 // equal to the fall_through label.
1972 static void GenerateBranches(RegExpMacroAssembler* masm,
1973                              ZoneList<int>* ranges,
1974                              int start_index,
1975                              int end_index,
1976                              uc16 min_char,
1977                              uc16 max_char,
1978                              Label* fall_through,
1979                              Label* even_label,
1980                              Label* odd_label) {
1981   int first = ranges->at(start_index);
1982   int last = ranges->at(end_index) - 1;
1983
1984   DCHECK_LT(min_char, first);
1985
1986   // Just need to test if the character is before or on-or-after
1987   // a particular character.
1988   if (start_index == end_index) {
1989     EmitBoundaryTest(masm, first, fall_through, even_label, odd_label);
1990     return;
1991   }
1992
1993   // Another almost trivial case:  There is one interval in the middle that is
1994   // different from the end intervals.
1995   if (start_index + 1 == end_index) {
1996     EmitDoubleBoundaryTest(
1997         masm, first, last, fall_through, even_label, odd_label);
1998     return;
1999   }
2000
2001   // It's not worth using table lookup if there are very few intervals in the
2002   // character class.
2003   if (end_index - start_index <= 6) {
2004     // It is faster to test for individual characters, so we look for those
2005     // first, then try arbitrary ranges in the second round.
2006     static int kNoCutIndex = -1;
2007     int cut = kNoCutIndex;
2008     for (int i = start_index; i < end_index; i++) {
2009       if (ranges->at(i) == ranges->at(i + 1) - 1) {
2010         cut = i;
2011         break;
2012       }
2013     }
2014     if (cut == kNoCutIndex) cut = start_index;
2015     CutOutRange(
2016         masm, ranges, start_index, end_index, cut, even_label, odd_label);
2017     DCHECK_GE(end_index - start_index, 2);
2018     GenerateBranches(masm,
2019                      ranges,
2020                      start_index + 1,
2021                      end_index - 1,
2022                      min_char,
2023                      max_char,
2024                      fall_through,
2025                      even_label,
2026                      odd_label);
2027     return;
2028   }
2029
2030   // If there are a lot of intervals in the regexp, then we will use tables to
2031   // determine whether the character is inside or outside the character class.
2032   static const int kBits = RegExpMacroAssembler::kTableSizeBits;
2033
2034   if ((max_char >> kBits) == (min_char >> kBits)) {
2035     EmitUseLookupTable(masm,
2036                        ranges,
2037                        start_index,
2038                        end_index,
2039                        min_char,
2040                        fall_through,
2041                        even_label,
2042                        odd_label);
2043     return;
2044   }
2045
2046   if ((min_char >> kBits) != (first >> kBits)) {
2047     masm->CheckCharacterLT(first, odd_label);
2048     GenerateBranches(masm,
2049                      ranges,
2050                      start_index + 1,
2051                      end_index,
2052                      first,
2053                      max_char,
2054                      fall_through,
2055                      odd_label,
2056                      even_label);
2057     return;
2058   }
2059
2060   int new_start_index = 0;
2061   int new_end_index = 0;
2062   int border = 0;
2063
2064   SplitSearchSpace(ranges,
2065                    start_index,
2066                    end_index,
2067                    &new_start_index,
2068                    &new_end_index,
2069                    &border);
2070
2071   Label handle_rest;
2072   Label* above = &handle_rest;
2073   if (border == last + 1) {
2074     // We didn't find any section that started after the limit, so everything
2075     // above the border is one of the terminal labels.
2076     above = (end_index & 1) != (start_index & 1) ? odd_label : even_label;
2077     DCHECK(new_end_index == end_index - 1);
2078   }
2079
2080   DCHECK_LE(start_index, new_end_index);
2081   DCHECK_LE(new_start_index, end_index);
2082   DCHECK_LT(start_index, new_start_index);
2083   DCHECK_LT(new_end_index, end_index);
2084   DCHECK(new_end_index + 1 == new_start_index ||
2085          (new_end_index + 2 == new_start_index &&
2086           border == ranges->at(new_end_index + 1)));
2087   DCHECK_LT(min_char, border - 1);
2088   DCHECK_LT(border, max_char);
2089   DCHECK_LT(ranges->at(new_end_index), border);
2090   DCHECK(border < ranges->at(new_start_index) ||
2091          (border == ranges->at(new_start_index) &&
2092           new_start_index == end_index &&
2093           new_end_index == end_index - 1 &&
2094           border == last + 1));
2095   DCHECK(new_start_index == 0 || border >= ranges->at(new_start_index - 1));
2096
2097   masm->CheckCharacterGT(border - 1, above);
2098   Label dummy;
2099   GenerateBranches(masm,
2100                    ranges,
2101                    start_index,
2102                    new_end_index,
2103                    min_char,
2104                    border - 1,
2105                    &dummy,
2106                    even_label,
2107                    odd_label);
2108   if (handle_rest.is_linked()) {
2109     masm->Bind(&handle_rest);
2110     bool flip = (new_start_index & 1) != (start_index & 1);
2111     GenerateBranches(masm,
2112                      ranges,
2113                      new_start_index,
2114                      end_index,
2115                      border,
2116                      max_char,
2117                      &dummy,
2118                      flip ? odd_label : even_label,
2119                      flip ? even_label : odd_label);
2120   }
2121 }
2122
2123
2124 static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
2125                           RegExpCharacterClass* cc,
2126                           bool ascii,
2127                           Label* on_failure,
2128                           int cp_offset,
2129                           bool check_offset,
2130                           bool preloaded,
2131                           Zone* zone) {
2132   ZoneList<CharacterRange>* ranges = cc->ranges(zone);
2133   if (!CharacterRange::IsCanonical(ranges)) {
2134     CharacterRange::Canonicalize(ranges);
2135   }
2136
2137   int max_char;
2138   if (ascii) {
2139     max_char = String::kMaxOneByteCharCode;
2140   } else {
2141     max_char = String::kMaxUtf16CodeUnit;
2142   }
2143
2144   int range_count = ranges->length();
2145
2146   int last_valid_range = range_count - 1;
2147   while (last_valid_range >= 0) {
2148     CharacterRange& range = ranges->at(last_valid_range);
2149     if (range.from() <= max_char) {
2150       break;
2151     }
2152     last_valid_range--;
2153   }
2154
2155   if (last_valid_range < 0) {
2156     if (!cc->is_negated()) {
2157       macro_assembler->GoTo(on_failure);
2158     }
2159     if (check_offset) {
2160       macro_assembler->CheckPosition(cp_offset, on_failure);
2161     }
2162     return;
2163   }
2164
2165   if (last_valid_range == 0 &&
2166       ranges->at(0).IsEverything(max_char)) {
2167     if (cc->is_negated()) {
2168       macro_assembler->GoTo(on_failure);
2169     } else {
2170       // This is a common case hit by non-anchored expressions.
2171       if (check_offset) {
2172         macro_assembler->CheckPosition(cp_offset, on_failure);
2173       }
2174     }
2175     return;
2176   }
2177   if (last_valid_range == 0 &&
2178       !cc->is_negated() &&
2179       ranges->at(0).IsEverything(max_char)) {
2180     // This is a common case hit by non-anchored expressions.
2181     if (check_offset) {
2182       macro_assembler->CheckPosition(cp_offset, on_failure);
2183     }
2184     return;
2185   }
2186
2187   if (!preloaded) {
2188     macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
2189   }
2190
2191   if (cc->is_standard(zone) &&
2192         macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
2193                                                     on_failure)) {
2194       return;
2195   }
2196
2197
2198   // A new list with ascending entries.  Each entry is a code unit
2199   // where there is a boundary between code units that are part of
2200   // the class and code units that are not.  Normally we insert an
2201   // entry at zero which goes to the failure label, but if there
2202   // was already one there we fall through for success on that entry.
2203   // Subsequent entries have alternating meaning (success/failure).
2204   ZoneList<int>* range_boundaries =
2205       new(zone) ZoneList<int>(last_valid_range, zone);
2206
2207   bool zeroth_entry_is_failure = !cc->is_negated();
2208
2209   for (int i = 0; i <= last_valid_range; i++) {
2210     CharacterRange& range = ranges->at(i);
2211     if (range.from() == 0) {
2212       DCHECK_EQ(i, 0);
2213       zeroth_entry_is_failure = !zeroth_entry_is_failure;
2214     } else {
2215       range_boundaries->Add(range.from(), zone);
2216     }
2217     range_boundaries->Add(range.to() + 1, zone);
2218   }
2219   int end_index = range_boundaries->length() - 1;
2220   if (range_boundaries->at(end_index) > max_char) {
2221     end_index--;
2222   }
2223
2224   Label fall_through;
2225   GenerateBranches(macro_assembler,
2226                    range_boundaries,
2227                    0,  // start_index.
2228                    end_index,
2229                    0,  // min_char.
2230                    max_char,
2231                    &fall_through,
2232                    zeroth_entry_is_failure ? &fall_through : on_failure,
2233                    zeroth_entry_is_failure ? on_failure : &fall_through);
2234   macro_assembler->Bind(&fall_through);
2235 }
2236
2237
2238 RegExpNode::~RegExpNode() {
2239 }
2240
2241
2242 RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
2243                                                   Trace* trace) {
2244   // If we are generating a greedy loop then don't stop and don't reuse code.
2245   if (trace->stop_node() != NULL) {
2246     return CONTINUE;
2247   }
2248
2249   RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2250   if (trace->is_trivial()) {
2251     if (label_.is_bound()) {
2252       // We are being asked to generate a generic version, but that's already
2253       // been done so just go to it.
2254       macro_assembler->GoTo(&label_);
2255       return DONE;
2256     }
2257     if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
2258       // To avoid too deep recursion we push the node to the work queue and just
2259       // generate a goto here.
2260       compiler->AddWork(this);
2261       macro_assembler->GoTo(&label_);
2262       return DONE;
2263     }
2264     // Generate generic version of the node and bind the label for later use.
2265     macro_assembler->Bind(&label_);
2266     return CONTINUE;
2267   }
2268
2269   // We are being asked to make a non-generic version.  Keep track of how many
2270   // non-generic versions we generate so as not to overdo it.
2271   trace_count_++;
2272   if (FLAG_regexp_optimization &&
2273       trace_count_ < kMaxCopiesCodeGenerated &&
2274       compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
2275     return CONTINUE;
2276   }
2277
2278   // If we get here code has been generated for this node too many times or
2279   // recursion is too deep.  Time to switch to a generic version.  The code for
2280   // generic versions above can handle deep recursion properly.
2281   trace->Flush(compiler, this);
2282   return DONE;
2283 }
2284
2285
2286 int ActionNode::EatsAtLeast(int still_to_find,
2287                             int budget,
2288                             bool not_at_start) {
2289   if (budget <= 0) return 0;
2290   if (action_type_ == POSITIVE_SUBMATCH_SUCCESS) return 0;  // Rewinds input!
2291   return on_success()->EatsAtLeast(still_to_find,
2292                                    budget - 1,
2293                                    not_at_start);
2294 }
2295
2296
2297 void ActionNode::FillInBMInfo(int offset,
2298                               int budget,
2299                               BoyerMooreLookahead* bm,
2300                               bool not_at_start) {
2301   if (action_type_ == BEGIN_SUBMATCH) {
2302     bm->SetRest(offset);
2303   } else if (action_type_ != POSITIVE_SUBMATCH_SUCCESS) {
2304     on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
2305   }
2306   SaveBMInfo(bm, not_at_start, offset);
2307 }
2308
2309
2310 int AssertionNode::EatsAtLeast(int still_to_find,
2311                                int budget,
2312                                bool not_at_start) {
2313   if (budget <= 0) return 0;
2314   // If we know we are not at the start and we are asked "how many characters
2315   // will you match if you succeed?" then we can answer anything since false
2316   // implies false.  So lets just return the max answer (still_to_find) since
2317   // that won't prevent us from preloading a lot of characters for the other
2318   // branches in the node graph.
2319   if (assertion_type() == AT_START && not_at_start) return still_to_find;
2320   return on_success()->EatsAtLeast(still_to_find,
2321                                    budget - 1,
2322                                    not_at_start);
2323 }
2324
2325
2326 void AssertionNode::FillInBMInfo(int offset,
2327                                  int budget,
2328                                  BoyerMooreLookahead* bm,
2329                                  bool not_at_start) {
2330   // Match the behaviour of EatsAtLeast on this node.
2331   if (assertion_type() == AT_START && not_at_start) return;
2332   on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
2333   SaveBMInfo(bm, not_at_start, offset);
2334 }
2335
2336
2337 int BackReferenceNode::EatsAtLeast(int still_to_find,
2338                                    int budget,
2339                                    bool not_at_start) {
2340   if (budget <= 0) return 0;
2341   return on_success()->EatsAtLeast(still_to_find,
2342                                    budget - 1,
2343                                    not_at_start);
2344 }
2345
2346
2347 int TextNode::EatsAtLeast(int still_to_find,
2348                           int budget,
2349                           bool not_at_start) {
2350   int answer = Length();
2351   if (answer >= still_to_find) return answer;
2352   if (budget <= 0) return answer;
2353   // We are not at start after this node so we set the last argument to 'true'.
2354   return answer + on_success()->EatsAtLeast(still_to_find - answer,
2355                                             budget - 1,
2356                                             true);
2357 }
2358
2359
2360 int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
2361                                              int budget,
2362                                              bool not_at_start) {
2363   if (budget <= 0) return 0;
2364   // Alternative 0 is the negative lookahead, alternative 1 is what comes
2365   // afterwards.
2366   RegExpNode* node = alternatives_->at(1).node();
2367   return node->EatsAtLeast(still_to_find, budget - 1, not_at_start);
2368 }
2369
2370
2371 void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
2372     QuickCheckDetails* details,
2373     RegExpCompiler* compiler,
2374     int filled_in,
2375     bool not_at_start) {
2376   // Alternative 0 is the negative lookahead, alternative 1 is what comes
2377   // afterwards.
2378   RegExpNode* node = alternatives_->at(1).node();
2379   return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
2380 }
2381
2382
2383 int ChoiceNode::EatsAtLeastHelper(int still_to_find,
2384                                   int budget,
2385                                   RegExpNode* ignore_this_node,
2386                                   bool not_at_start) {
2387   if (budget <= 0) return 0;
2388   int min = 100;
2389   int choice_count = alternatives_->length();
2390   budget = (budget - 1) / choice_count;
2391   for (int i = 0; i < choice_count; i++) {
2392     RegExpNode* node = alternatives_->at(i).node();
2393     if (node == ignore_this_node) continue;
2394     int node_eats_at_least =
2395         node->EatsAtLeast(still_to_find, budget, not_at_start);
2396     if (node_eats_at_least < min) min = node_eats_at_least;
2397     if (min == 0) return 0;
2398   }
2399   return min;
2400 }
2401
2402
2403 int LoopChoiceNode::EatsAtLeast(int still_to_find,
2404                                 int budget,
2405                                 bool not_at_start) {
2406   return EatsAtLeastHelper(still_to_find,
2407                            budget - 1,
2408                            loop_node_,
2409                            not_at_start);
2410 }
2411
2412
2413 int ChoiceNode::EatsAtLeast(int still_to_find,
2414                             int budget,
2415                             bool not_at_start) {
2416   return EatsAtLeastHelper(still_to_find,
2417                            budget,
2418                            NULL,
2419                            not_at_start);
2420 }
2421
2422
2423 // Takes the left-most 1-bit and smears it out, setting all bits to its right.
2424 static inline uint32_t SmearBitsRight(uint32_t v) {
2425   v |= v >> 1;
2426   v |= v >> 2;
2427   v |= v >> 4;
2428   v |= v >> 8;
2429   v |= v >> 16;
2430   return v;
2431 }
2432
2433
2434 bool QuickCheckDetails::Rationalize(bool asc) {
2435   bool found_useful_op = false;
2436   uint32_t char_mask;
2437   if (asc) {
2438     char_mask = String::kMaxOneByteCharCode;
2439   } else {
2440     char_mask = String::kMaxUtf16CodeUnit;
2441   }
2442   mask_ = 0;
2443   value_ = 0;
2444   int char_shift = 0;
2445   for (int i = 0; i < characters_; i++) {
2446     Position* pos = &positions_[i];
2447     if ((pos->mask & String::kMaxOneByteCharCode) != 0) {
2448       found_useful_op = true;
2449     }
2450     mask_ |= (pos->mask & char_mask) << char_shift;
2451     value_ |= (pos->value & char_mask) << char_shift;
2452     char_shift += asc ? 8 : 16;
2453   }
2454   return found_useful_op;
2455 }
2456
2457
2458 bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
2459                                 Trace* trace,
2460                                 bool preload_has_checked_bounds,
2461                                 Label* on_possible_success,
2462                                 QuickCheckDetails* details,
2463                                 bool fall_through_on_failure) {
2464   if (details->characters() == 0) return false;
2465   GetQuickCheckDetails(
2466       details, compiler, 0, trace->at_start() == Trace::FALSE_VALUE);
2467   if (details->cannot_match()) return false;
2468   if (!details->Rationalize(compiler->ascii())) return false;
2469   DCHECK(details->characters() == 1 ||
2470          compiler->macro_assembler()->CanReadUnaligned());
2471   uint32_t mask = details->mask();
2472   uint32_t value = details->value();
2473
2474   RegExpMacroAssembler* assembler = compiler->macro_assembler();
2475
2476   if (trace->characters_preloaded() != details->characters()) {
2477     assembler->LoadCurrentCharacter(trace->cp_offset(),
2478                                     trace->backtrack(),
2479                                     !preload_has_checked_bounds,
2480                                     details->characters());
2481   }
2482
2483
2484   bool need_mask = true;
2485
2486   if (details->characters() == 1) {
2487     // If number of characters preloaded is 1 then we used a byte or 16 bit
2488     // load so the value is already masked down.
2489     uint32_t char_mask;
2490     if (compiler->ascii()) {
2491       char_mask = String::kMaxOneByteCharCode;
2492     } else {
2493       char_mask = String::kMaxUtf16CodeUnit;
2494     }
2495     if ((mask & char_mask) == char_mask) need_mask = false;
2496     mask &= char_mask;
2497   } else {
2498     // For 2-character preloads in ASCII mode or 1-character preloads in
2499     // TWO_BYTE mode we also use a 16 bit load with zero extend.
2500     if (details->characters() == 2 && compiler->ascii()) {
2501       if ((mask & 0xffff) == 0xffff) need_mask = false;
2502     } else if (details->characters() == 1 && !compiler->ascii()) {
2503       if ((mask & 0xffff) == 0xffff) need_mask = false;
2504     } else {
2505       if (mask == 0xffffffff) need_mask = false;
2506     }
2507   }
2508
2509   if (fall_through_on_failure) {
2510     if (need_mask) {
2511       assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
2512     } else {
2513       assembler->CheckCharacter(value, on_possible_success);
2514     }
2515   } else {
2516     if (need_mask) {
2517       assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
2518     } else {
2519       assembler->CheckNotCharacter(value, trace->backtrack());
2520     }
2521   }
2522   return true;
2523 }
2524
2525
2526 // Here is the meat of GetQuickCheckDetails (see also the comment on the
2527 // super-class in the .h file).
2528 //
2529 // We iterate along the text object, building up for each character a
2530 // mask and value that can be used to test for a quick failure to match.
2531 // The masks and values for the positions will be combined into a single
2532 // machine word for the current character width in order to be used in
2533 // generating a quick check.
2534 void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
2535                                     RegExpCompiler* compiler,
2536                                     int characters_filled_in,
2537                                     bool not_at_start) {
2538   Isolate* isolate = compiler->macro_assembler()->zone()->isolate();
2539   DCHECK(characters_filled_in < details->characters());
2540   int characters = details->characters();
2541   int char_mask;
2542   if (compiler->ascii()) {
2543     char_mask = String::kMaxOneByteCharCode;
2544   } else {
2545     char_mask = String::kMaxUtf16CodeUnit;
2546   }
2547   for (int k = 0; k < elms_->length(); k++) {
2548     TextElement elm = elms_->at(k);
2549     if (elm.text_type() == TextElement::ATOM) {
2550       Vector<const uc16> quarks = elm.atom()->data();
2551       for (int i = 0; i < characters && i < quarks.length(); i++) {
2552         QuickCheckDetails::Position* pos =
2553             details->positions(characters_filled_in);
2554         uc16 c = quarks[i];
2555         if (c > char_mask) {
2556           // If we expect a non-ASCII character from an ASCII string,
2557           // there is no way we can match. Not even case independent
2558           // matching can turn an ASCII character into non-ASCII or
2559           // vice versa.
2560           details->set_cannot_match();
2561           pos->determines_perfectly = false;
2562           return;
2563         }
2564         if (compiler->ignore_case()) {
2565           unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
2566           int length = GetCaseIndependentLetters(isolate, c, compiler->ascii(),
2567                                                  chars);
2568           DCHECK(length != 0);  // Can only happen if c > char_mask (see above).
2569           if (length == 1) {
2570             // This letter has no case equivalents, so it's nice and simple
2571             // and the mask-compare will determine definitely whether we have
2572             // a match at this character position.
2573             pos->mask = char_mask;
2574             pos->value = c;
2575             pos->determines_perfectly = true;
2576           } else {
2577             uint32_t common_bits = char_mask;
2578             uint32_t bits = chars[0];
2579             for (int j = 1; j < length; j++) {
2580               uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
2581               common_bits ^= differing_bits;
2582               bits &= common_bits;
2583             }
2584             // If length is 2 and common bits has only one zero in it then
2585             // our mask and compare instruction will determine definitely
2586             // whether we have a match at this character position.  Otherwise
2587             // it can only be an approximate check.
2588             uint32_t one_zero = (common_bits | ~char_mask);
2589             if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
2590               pos->determines_perfectly = true;
2591             }
2592             pos->mask = common_bits;
2593             pos->value = bits;
2594           }
2595         } else {
2596           // Don't ignore case.  Nice simple case where the mask-compare will
2597           // determine definitely whether we have a match at this character
2598           // position.
2599           pos->mask = char_mask;
2600           pos->value = c;
2601           pos->determines_perfectly = true;
2602         }
2603         characters_filled_in++;
2604         DCHECK(characters_filled_in <= details->characters());
2605         if (characters_filled_in == details->characters()) {
2606           return;
2607         }
2608       }
2609     } else {
2610       QuickCheckDetails::Position* pos =
2611           details->positions(characters_filled_in);
2612       RegExpCharacterClass* tree = elm.char_class();
2613       ZoneList<CharacterRange>* ranges = tree->ranges(zone());
2614       if (tree->is_negated()) {
2615         // A quick check uses multi-character mask and compare.  There is no
2616         // useful way to incorporate a negative char class into this scheme
2617         // so we just conservatively create a mask and value that will always
2618         // succeed.
2619         pos->mask = 0;
2620         pos->value = 0;
2621       } else {
2622         int first_range = 0;
2623         while (ranges->at(first_range).from() > char_mask) {
2624           first_range++;
2625           if (first_range == ranges->length()) {
2626             details->set_cannot_match();
2627             pos->determines_perfectly = false;
2628             return;
2629           }
2630         }
2631         CharacterRange range = ranges->at(first_range);
2632         uc16 from = range.from();
2633         uc16 to = range.to();
2634         if (to > char_mask) {
2635           to = char_mask;
2636         }
2637         uint32_t differing_bits = (from ^ to);
2638         // A mask and compare is only perfect if the differing bits form a
2639         // number like 00011111 with one single block of trailing 1s.
2640         if ((differing_bits & (differing_bits + 1)) == 0 &&
2641              from + differing_bits == to) {
2642           pos->determines_perfectly = true;
2643         }
2644         uint32_t common_bits = ~SmearBitsRight(differing_bits);
2645         uint32_t bits = (from & common_bits);
2646         for (int i = first_range + 1; i < ranges->length(); i++) {
2647           CharacterRange range = ranges->at(i);
2648           uc16 from = range.from();
2649           uc16 to = range.to();
2650           if (from > char_mask) continue;
2651           if (to > char_mask) to = char_mask;
2652           // Here we are combining more ranges into the mask and compare
2653           // value.  With each new range the mask becomes more sparse and
2654           // so the chances of a false positive rise.  A character class
2655           // with multiple ranges is assumed never to be equivalent to a
2656           // mask and compare operation.
2657           pos->determines_perfectly = false;
2658           uint32_t new_common_bits = (from ^ to);
2659           new_common_bits = ~SmearBitsRight(new_common_bits);
2660           common_bits &= new_common_bits;
2661           bits &= new_common_bits;
2662           uint32_t differing_bits = (from & common_bits) ^ bits;
2663           common_bits ^= differing_bits;
2664           bits &= common_bits;
2665         }
2666         pos->mask = common_bits;
2667         pos->value = bits;
2668       }
2669       characters_filled_in++;
2670       DCHECK(characters_filled_in <= details->characters());
2671       if (characters_filled_in == details->characters()) {
2672         return;
2673       }
2674     }
2675   }
2676   DCHECK(characters_filled_in != details->characters());
2677   if (!details->cannot_match()) {
2678     on_success()-> GetQuickCheckDetails(details,
2679                                         compiler,
2680                                         characters_filled_in,
2681                                         true);
2682   }
2683 }
2684
2685
2686 void QuickCheckDetails::Clear() {
2687   for (int i = 0; i < characters_; i++) {
2688     positions_[i].mask = 0;
2689     positions_[i].value = 0;
2690     positions_[i].determines_perfectly = false;
2691   }
2692   characters_ = 0;
2693 }
2694
2695
2696 void QuickCheckDetails::Advance(int by, bool ascii) {
2697   DCHECK(by >= 0);
2698   if (by >= characters_) {
2699     Clear();
2700     return;
2701   }
2702   for (int i = 0; i < characters_ - by; i++) {
2703     positions_[i] = positions_[by + i];
2704   }
2705   for (int i = characters_ - by; i < characters_; i++) {
2706     positions_[i].mask = 0;
2707     positions_[i].value = 0;
2708     positions_[i].determines_perfectly = false;
2709   }
2710   characters_ -= by;
2711   // We could change mask_ and value_ here but we would never advance unless
2712   // they had already been used in a check and they won't be used again because
2713   // it would gain us nothing.  So there's no point.
2714 }
2715
2716
2717 void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2718   DCHECK(characters_ == other->characters_);
2719   if (other->cannot_match_) {
2720     return;
2721   }
2722   if (cannot_match_) {
2723     *this = *other;
2724     return;
2725   }
2726   for (int i = from_index; i < characters_; i++) {
2727     QuickCheckDetails::Position* pos = positions(i);
2728     QuickCheckDetails::Position* other_pos = other->positions(i);
2729     if (pos->mask != other_pos->mask ||
2730         pos->value != other_pos->value ||
2731         !other_pos->determines_perfectly) {
2732       // Our mask-compare operation will be approximate unless we have the
2733       // exact same operation on both sides of the alternation.
2734       pos->determines_perfectly = false;
2735     }
2736     pos->mask &= other_pos->mask;
2737     pos->value &= pos->mask;
2738     other_pos->value &= pos->mask;
2739     uc16 differing_bits = (pos->value ^ other_pos->value);
2740     pos->mask &= ~differing_bits;
2741     pos->value &= pos->mask;
2742   }
2743 }
2744
2745
2746 class VisitMarker {
2747  public:
2748   explicit VisitMarker(NodeInfo* info) : info_(info) {
2749     DCHECK(!info->visited);
2750     info->visited = true;
2751   }
2752   ~VisitMarker() {
2753     info_->visited = false;
2754   }
2755  private:
2756   NodeInfo* info_;
2757 };
2758
2759
2760 RegExpNode* SeqRegExpNode::FilterASCII(int depth, bool ignore_case) {
2761   if (info()->replacement_calculated) return replacement();
2762   if (depth < 0) return this;
2763   DCHECK(!info()->visited);
2764   VisitMarker marker(info());
2765   return FilterSuccessor(depth - 1, ignore_case);
2766 }
2767
2768
2769 RegExpNode* SeqRegExpNode::FilterSuccessor(int depth, bool ignore_case) {
2770   RegExpNode* next = on_success_->FilterASCII(depth - 1, ignore_case);
2771   if (next == NULL) return set_replacement(NULL);
2772   on_success_ = next;
2773   return set_replacement(this);
2774 }
2775
2776
2777 // We need to check for the following characters: 0x39c 0x3bc 0x178.
2778 static inline bool RangeContainsLatin1Equivalents(CharacterRange range) {
2779   // TODO(dcarney): this could be a lot more efficient.
2780   return range.Contains(0x39c) ||
2781       range.Contains(0x3bc) || range.Contains(0x178);
2782 }
2783
2784
2785 static bool RangesContainLatin1Equivalents(ZoneList<CharacterRange>* ranges) {
2786   for (int i = 0; i < ranges->length(); i++) {
2787     // TODO(dcarney): this could be a lot more efficient.
2788     if (RangeContainsLatin1Equivalents(ranges->at(i))) return true;
2789   }
2790   return false;
2791 }
2792
2793
2794 RegExpNode* TextNode::FilterASCII(int depth, bool ignore_case) {
2795   if (info()->replacement_calculated) return replacement();
2796   if (depth < 0) return this;
2797   DCHECK(!info()->visited);
2798   VisitMarker marker(info());
2799   int element_count = elms_->length();
2800   for (int i = 0; i < element_count; i++) {
2801     TextElement elm = elms_->at(i);
2802     if (elm.text_type() == TextElement::ATOM) {
2803       Vector<const uc16> quarks = elm.atom()->data();
2804       for (int j = 0; j < quarks.length(); j++) {
2805         uint16_t c = quarks[j];
2806         if (c <= String::kMaxOneByteCharCode) continue;
2807         if (!ignore_case) return set_replacement(NULL);
2808         // Here, we need to check for characters whose upper and lower cases
2809         // are outside the Latin-1 range.
2810         uint16_t converted = unibrow::Latin1::ConvertNonLatin1ToLatin1(c);
2811         // Character is outside Latin-1 completely
2812         if (converted == 0) return set_replacement(NULL);
2813         // Convert quark to Latin-1 in place.
2814         uint16_t* copy = const_cast<uint16_t*>(quarks.start());
2815         copy[j] = converted;
2816       }
2817     } else {
2818       DCHECK(elm.text_type() == TextElement::CHAR_CLASS);
2819       RegExpCharacterClass* cc = elm.char_class();
2820       ZoneList<CharacterRange>* ranges = cc->ranges(zone());
2821       if (!CharacterRange::IsCanonical(ranges)) {
2822         CharacterRange::Canonicalize(ranges);
2823       }
2824       // Now they are in order so we only need to look at the first.
2825       int range_count = ranges->length();
2826       if (cc->is_negated()) {
2827         if (range_count != 0 &&
2828             ranges->at(0).from() == 0 &&
2829             ranges->at(0).to() >= String::kMaxOneByteCharCode) {
2830           // This will be handled in a later filter.
2831           if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
2832           return set_replacement(NULL);
2833         }
2834       } else {
2835         if (range_count == 0 ||
2836             ranges->at(0).from() > String::kMaxOneByteCharCode) {
2837           // This will be handled in a later filter.
2838           if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
2839           return set_replacement(NULL);
2840         }
2841       }
2842     }
2843   }
2844   return FilterSuccessor(depth - 1, ignore_case);
2845 }
2846
2847
2848 RegExpNode* LoopChoiceNode::FilterASCII(int depth, bool ignore_case) {
2849   if (info()->replacement_calculated) return replacement();
2850   if (depth < 0) return this;
2851   if (info()->visited) return this;
2852   {
2853     VisitMarker marker(info());
2854
2855     RegExpNode* continue_replacement =
2856         continue_node_->FilterASCII(depth - 1, ignore_case);
2857     // If we can't continue after the loop then there is no sense in doing the
2858     // loop.
2859     if (continue_replacement == NULL) return set_replacement(NULL);
2860   }
2861
2862   return ChoiceNode::FilterASCII(depth - 1, ignore_case);
2863 }
2864
2865
2866 RegExpNode* ChoiceNode::FilterASCII(int depth, bool ignore_case) {
2867   if (info()->replacement_calculated) return replacement();
2868   if (depth < 0) return this;
2869   if (info()->visited) return this;
2870   VisitMarker marker(info());
2871   int choice_count = alternatives_->length();
2872
2873   for (int i = 0; i < choice_count; i++) {
2874     GuardedAlternative alternative = alternatives_->at(i);
2875     if (alternative.guards() != NULL && alternative.guards()->length() != 0) {
2876       set_replacement(this);
2877       return this;
2878     }
2879   }
2880
2881   int surviving = 0;
2882   RegExpNode* survivor = NULL;
2883   for (int i = 0; i < choice_count; i++) {
2884     GuardedAlternative alternative = alternatives_->at(i);
2885     RegExpNode* replacement =
2886         alternative.node()->FilterASCII(depth - 1, ignore_case);
2887     DCHECK(replacement != this);  // No missing EMPTY_MATCH_CHECK.
2888     if (replacement != NULL) {
2889       alternatives_->at(i).set_node(replacement);
2890       surviving++;
2891       survivor = replacement;
2892     }
2893   }
2894   if (surviving < 2) return set_replacement(survivor);
2895
2896   set_replacement(this);
2897   if (surviving == choice_count) {
2898     return this;
2899   }
2900   // Only some of the nodes survived the filtering.  We need to rebuild the
2901   // alternatives list.
2902   ZoneList<GuardedAlternative>* new_alternatives =
2903       new(zone()) ZoneList<GuardedAlternative>(surviving, zone());
2904   for (int i = 0; i < choice_count; i++) {
2905     RegExpNode* replacement =
2906         alternatives_->at(i).node()->FilterASCII(depth - 1, ignore_case);
2907     if (replacement != NULL) {
2908       alternatives_->at(i).set_node(replacement);
2909       new_alternatives->Add(alternatives_->at(i), zone());
2910     }
2911   }
2912   alternatives_ = new_alternatives;
2913   return this;
2914 }
2915
2916
2917 RegExpNode* NegativeLookaheadChoiceNode::FilterASCII(int depth,
2918                                                      bool ignore_case) {
2919   if (info()->replacement_calculated) return replacement();
2920   if (depth < 0) return this;
2921   if (info()->visited) return this;
2922   VisitMarker marker(info());
2923   // Alternative 0 is the negative lookahead, alternative 1 is what comes
2924   // afterwards.
2925   RegExpNode* node = alternatives_->at(1).node();
2926   RegExpNode* replacement = node->FilterASCII(depth - 1, ignore_case);
2927   if (replacement == NULL) return set_replacement(NULL);
2928   alternatives_->at(1).set_node(replacement);
2929
2930   RegExpNode* neg_node = alternatives_->at(0).node();
2931   RegExpNode* neg_replacement = neg_node->FilterASCII(depth - 1, ignore_case);
2932   // If the negative lookahead is always going to fail then
2933   // we don't need to check it.
2934   if (neg_replacement == NULL) return set_replacement(replacement);
2935   alternatives_->at(0).set_node(neg_replacement);
2936   return set_replacement(this);
2937 }
2938
2939
2940 void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2941                                           RegExpCompiler* compiler,
2942                                           int characters_filled_in,
2943                                           bool not_at_start) {
2944   if (body_can_be_zero_length_ || info()->visited) return;
2945   VisitMarker marker(info());
2946   return ChoiceNode::GetQuickCheckDetails(details,
2947                                           compiler,
2948                                           characters_filled_in,
2949                                           not_at_start);
2950 }
2951
2952
2953 void LoopChoiceNode::FillInBMInfo(int offset,
2954                                   int budget,
2955                                   BoyerMooreLookahead* bm,
2956                                   bool not_at_start) {
2957   if (body_can_be_zero_length_ || budget <= 0) {
2958     bm->SetRest(offset);
2959     SaveBMInfo(bm, not_at_start, offset);
2960     return;
2961   }
2962   ChoiceNode::FillInBMInfo(offset, budget - 1, bm, not_at_start);
2963   SaveBMInfo(bm, not_at_start, offset);
2964 }
2965
2966
2967 void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2968                                       RegExpCompiler* compiler,
2969                                       int characters_filled_in,
2970                                       bool not_at_start) {
2971   not_at_start = (not_at_start || not_at_start_);
2972   int choice_count = alternatives_->length();
2973   DCHECK(choice_count > 0);
2974   alternatives_->at(0).node()->GetQuickCheckDetails(details,
2975                                                     compiler,
2976                                                     characters_filled_in,
2977                                                     not_at_start);
2978   for (int i = 1; i < choice_count; i++) {
2979     QuickCheckDetails new_details(details->characters());
2980     RegExpNode* node = alternatives_->at(i).node();
2981     node->GetQuickCheckDetails(&new_details, compiler,
2982                                characters_filled_in,
2983                                not_at_start);
2984     // Here we merge the quick match details of the two branches.
2985     details->Merge(&new_details, characters_filled_in);
2986   }
2987 }
2988
2989
2990 // Check for [0-9A-Z_a-z].
2991 static void EmitWordCheck(RegExpMacroAssembler* assembler,
2992                           Label* word,
2993                           Label* non_word,
2994                           bool fall_through_on_word) {
2995   if (assembler->CheckSpecialCharacterClass(
2996           fall_through_on_word ? 'w' : 'W',
2997           fall_through_on_word ? non_word : word)) {
2998     // Optimized implementation available.
2999     return;
3000   }
3001   assembler->CheckCharacterGT('z', non_word);
3002   assembler->CheckCharacterLT('0', non_word);
3003   assembler->CheckCharacterGT('a' - 1, word);
3004   assembler->CheckCharacterLT('9' + 1, word);
3005   assembler->CheckCharacterLT('A', non_word);
3006   assembler->CheckCharacterLT('Z' + 1, word);
3007   if (fall_through_on_word) {
3008     assembler->CheckNotCharacter('_', non_word);
3009   } else {
3010     assembler->CheckCharacter('_', word);
3011   }
3012 }
3013
3014
3015 // Emit the code to check for a ^ in multiline mode (1-character lookbehind
3016 // that matches newline or the start of input).
3017 static void EmitHat(RegExpCompiler* compiler,
3018                     RegExpNode* on_success,
3019                     Trace* trace) {
3020   RegExpMacroAssembler* assembler = compiler->macro_assembler();
3021   // We will be loading the previous character into the current character
3022   // register.
3023   Trace new_trace(*trace);
3024   new_trace.InvalidateCurrentCharacter();
3025
3026   Label ok;
3027   if (new_trace.cp_offset() == 0) {
3028     // The start of input counts as a newline in this context, so skip to
3029     // ok if we are at the start.
3030     assembler->CheckAtStart(&ok);
3031   }
3032   // We already checked that we are not at the start of input so it must be
3033   // OK to load the previous character.
3034   assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
3035                                   new_trace.backtrack(),
3036                                   false);
3037   if (!assembler->CheckSpecialCharacterClass('n',
3038                                              new_trace.backtrack())) {
3039     // Newline means \n, \r, 0x2028 or 0x2029.
3040     if (!compiler->ascii()) {
3041       assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
3042     }
3043     assembler->CheckCharacter('\n', &ok);
3044     assembler->CheckNotCharacter('\r', new_trace.backtrack());
3045   }
3046   assembler->Bind(&ok);
3047   on_success->Emit(compiler, &new_trace);
3048 }
3049
3050
3051 // Emit the code to handle \b and \B (word-boundary or non-word-boundary).
3052 void AssertionNode::EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace) {
3053   RegExpMacroAssembler* assembler = compiler->macro_assembler();
3054   Trace::TriBool next_is_word_character = Trace::UNKNOWN;
3055   bool not_at_start = (trace->at_start() == Trace::FALSE_VALUE);
3056   BoyerMooreLookahead* lookahead = bm_info(not_at_start);
3057   if (lookahead == NULL) {
3058     int eats_at_least =
3059         Min(kMaxLookaheadForBoyerMoore, EatsAtLeast(kMaxLookaheadForBoyerMoore,
3060                                                     kRecursionBudget,
3061                                                     not_at_start));
3062     if (eats_at_least >= 1) {
3063       BoyerMooreLookahead* bm =
3064           new(zone()) BoyerMooreLookahead(eats_at_least, compiler, zone());
3065       FillInBMInfo(0, kRecursionBudget, bm, not_at_start);
3066       if (bm->at(0)->is_non_word())
3067         next_is_word_character = Trace::FALSE_VALUE;
3068       if (bm->at(0)->is_word()) next_is_word_character = Trace::TRUE_VALUE;
3069     }
3070   } else {
3071     if (lookahead->at(0)->is_non_word())
3072       next_is_word_character = Trace::FALSE_VALUE;
3073     if (lookahead->at(0)->is_word())
3074       next_is_word_character = Trace::TRUE_VALUE;
3075   }
3076   bool at_boundary = (assertion_type_ == AssertionNode::AT_BOUNDARY);
3077   if (next_is_word_character == Trace::UNKNOWN) {
3078     Label before_non_word;
3079     Label before_word;
3080     if (trace->characters_preloaded() != 1) {
3081       assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
3082     }
3083     // Fall through on non-word.
3084     EmitWordCheck(assembler, &before_word, &before_non_word, false);
3085     // Next character is not a word character.
3086     assembler->Bind(&before_non_word);
3087     Label ok;
3088     BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
3089     assembler->GoTo(&ok);
3090
3091     assembler->Bind(&before_word);
3092     BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
3093     assembler->Bind(&ok);
3094   } else if (next_is_word_character == Trace::TRUE_VALUE) {
3095     BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
3096   } else {
3097     DCHECK(next_is_word_character == Trace::FALSE_VALUE);
3098     BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
3099   }
3100 }
3101
3102
3103 void AssertionNode::BacktrackIfPrevious(
3104     RegExpCompiler* compiler,
3105     Trace* trace,
3106     AssertionNode::IfPrevious backtrack_if_previous) {
3107   RegExpMacroAssembler* assembler = compiler->macro_assembler();
3108   Trace new_trace(*trace);
3109   new_trace.InvalidateCurrentCharacter();
3110
3111   Label fall_through, dummy;
3112
3113   Label* non_word = backtrack_if_previous == kIsNonWord ?
3114                     new_trace.backtrack() :
3115                     &fall_through;
3116   Label* word = backtrack_if_previous == kIsNonWord ?
3117                 &fall_through :
3118                 new_trace.backtrack();
3119
3120   if (new_trace.cp_offset() == 0) {
3121     // The start of input counts as a non-word character, so the question is
3122     // decided if we are at the start.
3123     assembler->CheckAtStart(non_word);
3124   }
3125   // We already checked that we are not at the start of input so it must be
3126   // OK to load the previous character.
3127   assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1, &dummy, false);
3128   EmitWordCheck(assembler, word, non_word, backtrack_if_previous == kIsNonWord);
3129
3130   assembler->Bind(&fall_through);
3131   on_success()->Emit(compiler, &new_trace);
3132 }
3133
3134
3135 void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
3136                                          RegExpCompiler* compiler,
3137                                          int filled_in,
3138                                          bool not_at_start) {
3139   if (assertion_type_ == AT_START && not_at_start) {
3140     details->set_cannot_match();
3141     return;
3142   }
3143   return on_success()->GetQuickCheckDetails(details,
3144                                             compiler,
3145                                             filled_in,
3146                                             not_at_start);
3147 }
3148
3149
3150 void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3151   RegExpMacroAssembler* assembler = compiler->macro_assembler();
3152   switch (assertion_type_) {
3153     case AT_END: {
3154       Label ok;
3155       assembler->CheckPosition(trace->cp_offset(), &ok);
3156       assembler->GoTo(trace->backtrack());
3157       assembler->Bind(&ok);
3158       break;
3159     }
3160     case AT_START: {
3161       if (trace->at_start() == Trace::FALSE_VALUE) {
3162         assembler->GoTo(trace->backtrack());
3163         return;
3164       }
3165       if (trace->at_start() == Trace::UNKNOWN) {
3166         assembler->CheckNotAtStart(trace->backtrack());
3167         Trace at_start_trace = *trace;
3168         at_start_trace.set_at_start(true);
3169         on_success()->Emit(compiler, &at_start_trace);
3170         return;
3171       }
3172     }
3173     break;
3174     case AFTER_NEWLINE:
3175       EmitHat(compiler, on_success(), trace);
3176       return;
3177     case AT_BOUNDARY:
3178     case AT_NON_BOUNDARY: {
3179       EmitBoundaryCheck(compiler, trace);
3180       return;
3181     }
3182   }
3183   on_success()->Emit(compiler, trace);
3184 }
3185
3186
3187 static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
3188   if (quick_check == NULL) return false;
3189   if (offset >= quick_check->characters()) return false;
3190   return quick_check->positions(offset)->determines_perfectly;
3191 }
3192
3193
3194 static void UpdateBoundsCheck(int index, int* checked_up_to) {
3195   if (index > *checked_up_to) {
3196     *checked_up_to = index;
3197   }
3198 }
3199
3200
3201 // We call this repeatedly to generate code for each pass over the text node.
3202 // The passes are in increasing order of difficulty because we hope one
3203 // of the first passes will fail in which case we are saved the work of the
3204 // later passes.  for example for the case independent regexp /%[asdfghjkl]a/
3205 // we will check the '%' in the first pass, the case independent 'a' in the
3206 // second pass and the character class in the last pass.
3207 //
3208 // The passes are done from right to left, so for example to test for /bar/
3209 // we will first test for an 'r' with offset 2, then an 'a' with offset 1
3210 // and then a 'b' with offset 0.  This means we can avoid the end-of-input
3211 // bounds check most of the time.  In the example we only need to check for
3212 // end-of-input when loading the putative 'r'.
3213 //
3214 // A slight complication involves the fact that the first character may already
3215 // be fetched into a register by the previous node.  In this case we want to
3216 // do the test for that character first.  We do this in separate passes.  The
3217 // 'preloaded' argument indicates that we are doing such a 'pass'.  If such a
3218 // pass has been performed then subsequent passes will have true in
3219 // first_element_checked to indicate that that character does not need to be
3220 // checked again.
3221 //
3222 // In addition to all this we are passed a Trace, which can
3223 // contain an AlternativeGeneration object.  In this AlternativeGeneration
3224 // object we can see details of any quick check that was already passed in
3225 // order to get to the code we are now generating.  The quick check can involve
3226 // loading characters, which means we do not need to recheck the bounds
3227 // up to the limit the quick check already checked.  In addition the quick
3228 // check can have involved a mask and compare operation which may simplify
3229 // or obviate the need for further checks at some character positions.
3230 void TextNode::TextEmitPass(RegExpCompiler* compiler,
3231                             TextEmitPassType pass,
3232                             bool preloaded,
3233                             Trace* trace,
3234                             bool first_element_checked,
3235                             int* checked_up_to) {
3236   RegExpMacroAssembler* assembler = compiler->macro_assembler();
3237   Isolate* isolate = assembler->zone()->isolate();
3238   bool ascii = compiler->ascii();
3239   Label* backtrack = trace->backtrack();
3240   QuickCheckDetails* quick_check = trace->quick_check_performed();
3241   int element_count = elms_->length();
3242   for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
3243     TextElement elm = elms_->at(i);
3244     int cp_offset = trace->cp_offset() + elm.cp_offset();
3245     if (elm.text_type() == TextElement::ATOM) {
3246       Vector<const uc16> quarks = elm.atom()->data();
3247       for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
3248         if (first_element_checked && i == 0 && j == 0) continue;
3249         if (DeterminedAlready(quick_check, elm.cp_offset() + j)) continue;
3250         EmitCharacterFunction* emit_function = NULL;
3251         switch (pass) {
3252           case NON_ASCII_MATCH:
3253             DCHECK(ascii);
3254             if (quarks[j] > String::kMaxOneByteCharCode) {
3255               assembler->GoTo(backtrack);
3256               return;
3257             }
3258             break;
3259           case NON_LETTER_CHARACTER_MATCH:
3260             emit_function = &EmitAtomNonLetter;
3261             break;
3262           case SIMPLE_CHARACTER_MATCH:
3263             emit_function = &EmitSimpleCharacter;
3264             break;
3265           case CASE_CHARACTER_MATCH:
3266             emit_function = &EmitAtomLetter;
3267             break;
3268           default:
3269             break;
3270         }
3271         if (emit_function != NULL) {
3272           bool bound_checked = emit_function(isolate,
3273                                              compiler,
3274                                              quarks[j],
3275                                              backtrack,
3276                                              cp_offset + j,
3277                                              *checked_up_to < cp_offset + j,
3278                                              preloaded);
3279           if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
3280         }
3281       }
3282     } else {
3283       DCHECK_EQ(TextElement::CHAR_CLASS, elm.text_type());
3284       if (pass == CHARACTER_CLASS_MATCH) {
3285         if (first_element_checked && i == 0) continue;
3286         if (DeterminedAlready(quick_check, elm.cp_offset())) continue;
3287         RegExpCharacterClass* cc = elm.char_class();
3288         EmitCharClass(assembler,
3289                       cc,
3290                       ascii,
3291                       backtrack,
3292                       cp_offset,
3293                       *checked_up_to < cp_offset,
3294                       preloaded,
3295                       zone());
3296         UpdateBoundsCheck(cp_offset, checked_up_to);
3297       }
3298     }
3299   }
3300 }
3301
3302
3303 int TextNode::Length() {
3304   TextElement elm = elms_->last();
3305   DCHECK(elm.cp_offset() >= 0);
3306   return elm.cp_offset() + elm.length();
3307 }
3308
3309
3310 bool TextNode::SkipPass(int int_pass, bool ignore_case) {
3311   TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
3312   if (ignore_case) {
3313     return pass == SIMPLE_CHARACTER_MATCH;
3314   } else {
3315     return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
3316   }
3317 }
3318
3319
3320 // This generates the code to match a text node.  A text node can contain
3321 // straight character sequences (possibly to be matched in a case-independent
3322 // way) and character classes.  For efficiency we do not do this in a single
3323 // pass from left to right.  Instead we pass over the text node several times,
3324 // emitting code for some character positions every time.  See the comment on
3325 // TextEmitPass for details.
3326 void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3327   LimitResult limit_result = LimitVersions(compiler, trace);
3328   if (limit_result == DONE) return;
3329   DCHECK(limit_result == CONTINUE);
3330
3331   if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
3332     compiler->SetRegExpTooBig();
3333     return;
3334   }
3335
3336   if (compiler->ascii()) {
3337     int dummy = 0;
3338     TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
3339   }
3340
3341   bool first_elt_done = false;
3342   int bound_checked_to = trace->cp_offset() - 1;
3343   bound_checked_to += trace->bound_checked_up_to();
3344
3345   // If a character is preloaded into the current character register then
3346   // check that now.
3347   if (trace->characters_preloaded() == 1) {
3348     for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3349       if (!SkipPass(pass, compiler->ignore_case())) {
3350         TextEmitPass(compiler,
3351                      static_cast<TextEmitPassType>(pass),
3352                      true,
3353                      trace,
3354                      false,
3355                      &bound_checked_to);
3356       }
3357     }
3358     first_elt_done = true;
3359   }
3360
3361   for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3362     if (!SkipPass(pass, compiler->ignore_case())) {
3363       TextEmitPass(compiler,
3364                    static_cast<TextEmitPassType>(pass),
3365                    false,
3366                    trace,
3367                    first_elt_done,
3368                    &bound_checked_to);
3369     }
3370   }
3371
3372   Trace successor_trace(*trace);
3373   successor_trace.set_at_start(false);
3374   successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
3375   RecursionCheck rc(compiler);
3376   on_success()->Emit(compiler, &successor_trace);
3377 }
3378
3379
3380 void Trace::InvalidateCurrentCharacter() {
3381   characters_preloaded_ = 0;
3382 }
3383
3384
3385 void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
3386   DCHECK(by > 0);
3387   // We don't have an instruction for shifting the current character register
3388   // down or for using a shifted value for anything so lets just forget that
3389   // we preloaded any characters into it.
3390   characters_preloaded_ = 0;
3391   // Adjust the offsets of the quick check performed information.  This
3392   // information is used to find out what we already determined about the
3393   // characters by means of mask and compare.
3394   quick_check_performed_.Advance(by, compiler->ascii());
3395   cp_offset_ += by;
3396   if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
3397     compiler->SetRegExpTooBig();
3398     cp_offset_ = 0;
3399   }
3400   bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
3401 }
3402
3403
3404 void TextNode::MakeCaseIndependent(bool is_ascii) {
3405   int element_count = elms_->length();
3406   for (int i = 0; i < element_count; i++) {
3407     TextElement elm = elms_->at(i);
3408     if (elm.text_type() == TextElement::CHAR_CLASS) {
3409       RegExpCharacterClass* cc = elm.char_class();
3410       // None of the standard character classes is different in the case
3411       // independent case and it slows us down if we don't know that.
3412       if (cc->is_standard(zone())) continue;
3413       ZoneList<CharacterRange>* ranges = cc->ranges(zone());
3414       int range_count = ranges->length();
3415       for (int j = 0; j < range_count; j++) {
3416         ranges->at(j).AddCaseEquivalents(ranges, is_ascii, zone());
3417       }
3418     }
3419   }
3420 }
3421
3422
3423 int TextNode::GreedyLoopTextLength() {
3424   TextElement elm = elms_->at(elms_->length() - 1);
3425   return elm.cp_offset() + elm.length();
3426 }
3427
3428
3429 RegExpNode* TextNode::GetSuccessorOfOmnivorousTextNode(
3430     RegExpCompiler* compiler) {
3431   if (elms_->length() != 1) return NULL;
3432   TextElement elm = elms_->at(0);
3433   if (elm.text_type() != TextElement::CHAR_CLASS) return NULL;
3434   RegExpCharacterClass* node = elm.char_class();
3435   ZoneList<CharacterRange>* ranges = node->ranges(zone());
3436   if (!CharacterRange::IsCanonical(ranges)) {
3437     CharacterRange::Canonicalize(ranges);
3438   }
3439   if (node->is_negated()) {
3440     return ranges->length() == 0 ? on_success() : NULL;
3441   }
3442   if (ranges->length() != 1) return NULL;
3443   uint32_t max_char;
3444   if (compiler->ascii()) {
3445     max_char = String::kMaxOneByteCharCode;
3446   } else {
3447     max_char = String::kMaxUtf16CodeUnit;
3448   }
3449   return ranges->at(0).IsEverything(max_char) ? on_success() : NULL;
3450 }
3451
3452
3453 // Finds the fixed match length of a sequence of nodes that goes from
3454 // this alternative and back to this choice node.  If there are variable
3455 // length nodes or other complications in the way then return a sentinel
3456 // value indicating that a greedy loop cannot be constructed.
3457 int ChoiceNode::GreedyLoopTextLengthForAlternative(
3458     GuardedAlternative* alternative) {
3459   int length = 0;
3460   RegExpNode* node = alternative->node();
3461   // Later we will generate code for all these text nodes using recursion
3462   // so we have to limit the max number.
3463   int recursion_depth = 0;
3464   while (node != this) {
3465     if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
3466       return kNodeIsTooComplexForGreedyLoops;
3467     }
3468     int node_length = node->GreedyLoopTextLength();
3469     if (node_length == kNodeIsTooComplexForGreedyLoops) {
3470       return kNodeIsTooComplexForGreedyLoops;
3471     }
3472     length += node_length;
3473     SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
3474     node = seq_node->on_success();
3475   }
3476   return length;
3477 }
3478
3479
3480 void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
3481   DCHECK_EQ(loop_node_, NULL);
3482   AddAlternative(alt);
3483   loop_node_ = alt.node();
3484 }
3485
3486
3487 void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
3488   DCHECK_EQ(continue_node_, NULL);
3489   AddAlternative(alt);
3490   continue_node_ = alt.node();
3491 }
3492
3493
3494 void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3495   RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3496   if (trace->stop_node() == this) {
3497     int text_length =
3498         GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
3499     DCHECK(text_length != kNodeIsTooComplexForGreedyLoops);
3500     // Update the counter-based backtracking info on the stack.  This is an
3501     // optimization for greedy loops (see below).
3502     DCHECK(trace->cp_offset() == text_length);
3503     macro_assembler->AdvanceCurrentPosition(text_length);
3504     macro_assembler->GoTo(trace->loop_label());
3505     return;
3506   }
3507   DCHECK(trace->stop_node() == NULL);
3508   if (!trace->is_trivial()) {
3509     trace->Flush(compiler, this);
3510     return;
3511   }
3512   ChoiceNode::Emit(compiler, trace);
3513 }
3514
3515
3516 int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
3517                                            int eats_at_least) {
3518   int preload_characters = Min(4, eats_at_least);
3519   if (compiler->macro_assembler()->CanReadUnaligned()) {
3520     bool ascii = compiler->ascii();
3521     if (ascii) {
3522       if (preload_characters > 4) preload_characters = 4;
3523       // We can't preload 3 characters because there is no machine instruction
3524       // to do that.  We can't just load 4 because we could be reading
3525       // beyond the end of the string, which could cause a memory fault.
3526       if (preload_characters == 3) preload_characters = 2;
3527     } else {
3528       if (preload_characters > 2) preload_characters = 2;
3529     }
3530   } else {
3531     if (preload_characters > 1) preload_characters = 1;
3532   }
3533   return preload_characters;
3534 }
3535
3536
3537 // This class is used when generating the alternatives in a choice node.  It
3538 // records the way the alternative is being code generated.
3539 class AlternativeGeneration: public Malloced {
3540  public:
3541   AlternativeGeneration()
3542       : possible_success(),
3543         expects_preload(false),
3544         after(),
3545         quick_check_details() { }
3546   Label possible_success;
3547   bool expects_preload;
3548   Label after;
3549   QuickCheckDetails quick_check_details;
3550 };
3551
3552
3553 // Creates a list of AlternativeGenerations.  If the list has a reasonable
3554 // size then it is on the stack, otherwise the excess is on the heap.
3555 class AlternativeGenerationList {
3556  public:
3557   AlternativeGenerationList(int count, Zone* zone)
3558       : alt_gens_(count, zone) {
3559     for (int i = 0; i < count && i < kAFew; i++) {
3560       alt_gens_.Add(a_few_alt_gens_ + i, zone);
3561     }
3562     for (int i = kAFew; i < count; i++) {
3563       alt_gens_.Add(new AlternativeGeneration(), zone);
3564     }
3565   }
3566   ~AlternativeGenerationList() {
3567     for (int i = kAFew; i < alt_gens_.length(); i++) {
3568       delete alt_gens_[i];
3569       alt_gens_[i] = NULL;
3570     }
3571   }
3572
3573   AlternativeGeneration* at(int i) {
3574     return alt_gens_[i];
3575   }
3576
3577  private:
3578   static const int kAFew = 10;
3579   ZoneList<AlternativeGeneration*> alt_gens_;
3580   AlternativeGeneration a_few_alt_gens_[kAFew];
3581 };
3582
3583
3584 // The '2' variant is has inclusive from and exclusive to.
3585 // This covers \s as defined in ECMA-262 5.1, 15.10.2.12,
3586 // which include WhiteSpace (7.2) or LineTerminator (7.3) values.
3587 static const int kSpaceRanges[] = { '\t', '\r' + 1, ' ', ' ' + 1,
3588     0x00A0, 0x00A1, 0x1680, 0x1681, 0x180E, 0x180F, 0x2000, 0x200B,
3589     0x2028, 0x202A, 0x202F, 0x2030, 0x205F, 0x2060, 0x3000, 0x3001,
3590     0xFEFF, 0xFF00, 0x10000 };
3591 static const int kSpaceRangeCount = ARRAY_SIZE(kSpaceRanges);
3592
3593 static const int kWordRanges[] = {
3594     '0', '9' + 1, 'A', 'Z' + 1, '_', '_' + 1, 'a', 'z' + 1, 0x10000 };
3595 static const int kWordRangeCount = ARRAY_SIZE(kWordRanges);
3596 static const int kDigitRanges[] = { '0', '9' + 1, 0x10000 };
3597 static const int kDigitRangeCount = ARRAY_SIZE(kDigitRanges);
3598 static const int kSurrogateRanges[] = { 0xd800, 0xe000, 0x10000 };
3599 static const int kSurrogateRangeCount = ARRAY_SIZE(kSurrogateRanges);
3600 static const int kLineTerminatorRanges[] = { 0x000A, 0x000B, 0x000D, 0x000E,
3601     0x2028, 0x202A, 0x10000 };
3602 static const int kLineTerminatorRangeCount = ARRAY_SIZE(kLineTerminatorRanges);
3603
3604
3605 void BoyerMoorePositionInfo::Set(int character) {
3606   SetInterval(Interval(character, character));
3607 }
3608
3609
3610 void BoyerMoorePositionInfo::SetInterval(const Interval& interval) {
3611   s_ = AddRange(s_, kSpaceRanges, kSpaceRangeCount, interval);
3612   w_ = AddRange(w_, kWordRanges, kWordRangeCount, interval);
3613   d_ = AddRange(d_, kDigitRanges, kDigitRangeCount, interval);
3614   surrogate_ =
3615       AddRange(surrogate_, kSurrogateRanges, kSurrogateRangeCount, interval);
3616   if (interval.to() - interval.from() >= kMapSize - 1) {
3617     if (map_count_ != kMapSize) {
3618       map_count_ = kMapSize;
3619       for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3620     }
3621     return;
3622   }
3623   for (int i = interval.from(); i <= interval.to(); i++) {
3624     int mod_character = (i & kMask);
3625     if (!map_->at(mod_character)) {
3626       map_count_++;
3627       map_->at(mod_character) = true;
3628     }
3629     if (map_count_ == kMapSize) return;
3630   }
3631 }
3632
3633
3634 void BoyerMoorePositionInfo::SetAll() {
3635   s_ = w_ = d_ = kLatticeUnknown;
3636   if (map_count_ != kMapSize) {
3637     map_count_ = kMapSize;
3638     for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3639   }
3640 }
3641
3642
3643 BoyerMooreLookahead::BoyerMooreLookahead(
3644     int length, RegExpCompiler* compiler, Zone* zone)
3645     : length_(length),
3646       compiler_(compiler) {
3647   if (compiler->ascii()) {
3648     max_char_ = String::kMaxOneByteCharCode;
3649   } else {
3650     max_char_ = String::kMaxUtf16CodeUnit;
3651   }
3652   bitmaps_ = new(zone) ZoneList<BoyerMoorePositionInfo*>(length, zone);
3653   for (int i = 0; i < length; i++) {
3654     bitmaps_->Add(new(zone) BoyerMoorePositionInfo(zone), zone);
3655   }
3656 }
3657
3658
3659 // Find the longest range of lookahead that has the fewest number of different
3660 // characters that can occur at a given position.  Since we are optimizing two
3661 // different parameters at once this is a tradeoff.
3662 bool BoyerMooreLookahead::FindWorthwhileInterval(int* from, int* to) {
3663   int biggest_points = 0;
3664   // If more than 32 characters out of 128 can occur it is unlikely that we can
3665   // be lucky enough to step forwards much of the time.
3666   const int kMaxMax = 32;
3667   for (int max_number_of_chars = 4;
3668        max_number_of_chars < kMaxMax;
3669        max_number_of_chars *= 2) {
3670     biggest_points =
3671         FindBestInterval(max_number_of_chars, biggest_points, from, to);
3672   }
3673   if (biggest_points == 0) return false;
3674   return true;
3675 }
3676
3677
3678 // Find the highest-points range between 0 and length_ where the character
3679 // information is not too vague.  'Too vague' means that there are more than
3680 // max_number_of_chars that can occur at this position.  Calculates the number
3681 // of points as the product of width-of-the-range and
3682 // probability-of-finding-one-of-the-characters, where the probability is
3683 // calculated using the frequency distribution of the sample subject string.
3684 int BoyerMooreLookahead::FindBestInterval(
3685     int max_number_of_chars, int old_biggest_points, int* from, int* to) {
3686   int biggest_points = old_biggest_points;
3687   static const int kSize = RegExpMacroAssembler::kTableSize;
3688   for (int i = 0; i < length_; ) {
3689     while (i < length_ && Count(i) > max_number_of_chars) i++;
3690     if (i == length_) break;
3691     int remembered_from = i;
3692     bool union_map[kSize];
3693     for (int j = 0; j < kSize; j++) union_map[j] = false;
3694     while (i < length_ && Count(i) <= max_number_of_chars) {
3695       BoyerMoorePositionInfo* map = bitmaps_->at(i);
3696       for (int j = 0; j < kSize; j++) union_map[j] |= map->at(j);
3697       i++;
3698     }
3699     int frequency = 0;
3700     for (int j = 0; j < kSize; j++) {
3701       if (union_map[j]) {
3702         // Add 1 to the frequency to give a small per-character boost for
3703         // the cases where our sampling is not good enough and many
3704         // characters have a frequency of zero.  This means the frequency
3705         // can theoretically be up to 2*kSize though we treat it mostly as
3706         // a fraction of kSize.
3707         frequency += compiler_->frequency_collator()->Frequency(j) + 1;
3708       }
3709     }
3710     // We use the probability of skipping times the distance we are skipping to
3711     // judge the effectiveness of this.  Actually we have a cut-off:  By
3712     // dividing by 2 we switch off the skipping if the probability of skipping
3713     // is less than 50%.  This is because the multibyte mask-and-compare
3714     // skipping in quickcheck is more likely to do well on this case.
3715     bool in_quickcheck_range = ((i - remembered_from < 4) ||
3716         (compiler_->ascii() ? remembered_from <= 4 : remembered_from <= 2));
3717     // Called 'probability' but it is only a rough estimate and can actually
3718     // be outside the 0-kSize range.
3719     int probability = (in_quickcheck_range ? kSize / 2 : kSize) - frequency;
3720     int points = (i - remembered_from) * probability;
3721     if (points > biggest_points) {
3722       *from = remembered_from;
3723       *to = i - 1;
3724       biggest_points = points;
3725     }
3726   }
3727   return biggest_points;
3728 }
3729
3730
3731 // Take all the characters that will not prevent a successful match if they
3732 // occur in the subject string in the range between min_lookahead and
3733 // max_lookahead (inclusive) measured from the current position.  If the
3734 // character at max_lookahead offset is not one of these characters, then we
3735 // can safely skip forwards by the number of characters in the range.
3736 int BoyerMooreLookahead::GetSkipTable(int min_lookahead,
3737                                       int max_lookahead,
3738                                       Handle<ByteArray> boolean_skip_table) {
3739   const int kSize = RegExpMacroAssembler::kTableSize;
3740
3741   const int kSkipArrayEntry = 0;
3742   const int kDontSkipArrayEntry = 1;
3743
3744   for (int i = 0; i < kSize; i++) {
3745     boolean_skip_table->set(i, kSkipArrayEntry);
3746   }
3747   int skip = max_lookahead + 1 - min_lookahead;
3748
3749   for (int i = max_lookahead; i >= min_lookahead; i--) {
3750     BoyerMoorePositionInfo* map = bitmaps_->at(i);
3751     for (int j = 0; j < kSize; j++) {
3752       if (map->at(j)) {
3753         boolean_skip_table->set(j, kDontSkipArrayEntry);
3754       }
3755     }
3756   }
3757
3758   return skip;
3759 }
3760
3761
3762 // See comment above on the implementation of GetSkipTable.
3763 bool BoyerMooreLookahead::EmitSkipInstructions(RegExpMacroAssembler* masm) {
3764   const int kSize = RegExpMacroAssembler::kTableSize;
3765
3766   int min_lookahead = 0;
3767   int max_lookahead = 0;
3768
3769   if (!FindWorthwhileInterval(&min_lookahead, &max_lookahead)) return false;
3770
3771   bool found_single_character = false;
3772   int single_character = 0;
3773   for (int i = max_lookahead; i >= min_lookahead; i--) {
3774     BoyerMoorePositionInfo* map = bitmaps_->at(i);
3775     if (map->map_count() > 1 ||
3776         (found_single_character && map->map_count() != 0)) {
3777       found_single_character = false;
3778       break;
3779     }
3780     for (int j = 0; j < kSize; j++) {
3781       if (map->at(j)) {
3782         found_single_character = true;
3783         single_character = j;
3784         break;
3785       }
3786     }
3787   }
3788
3789   int lookahead_width = max_lookahead + 1 - min_lookahead;
3790
3791   if (found_single_character && lookahead_width == 1 && max_lookahead < 3) {
3792     // The mask-compare can probably handle this better.
3793     return false;
3794   }
3795
3796   if (found_single_character) {
3797     Label cont, again;
3798     masm->Bind(&again);
3799     masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3800     if (max_char_ > kSize) {
3801       masm->CheckCharacterAfterAnd(single_character,
3802                                    RegExpMacroAssembler::kTableMask,
3803                                    &cont);
3804     } else {
3805       masm->CheckCharacter(single_character, &cont);
3806     }
3807     masm->AdvanceCurrentPosition(lookahead_width);
3808     masm->GoTo(&again);
3809     masm->Bind(&cont);
3810     return true;
3811   }
3812
3813   Factory* factory = masm->zone()->isolate()->factory();
3814   Handle<ByteArray> boolean_skip_table = factory->NewByteArray(kSize, TENURED);
3815   int skip_distance = GetSkipTable(
3816       min_lookahead, max_lookahead, boolean_skip_table);
3817   DCHECK(skip_distance != 0);
3818
3819   Label cont, again;
3820   masm->Bind(&again);
3821   masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3822   masm->CheckBitInTable(boolean_skip_table, &cont);
3823   masm->AdvanceCurrentPosition(skip_distance);
3824   masm->GoTo(&again);
3825   masm->Bind(&cont);
3826
3827   return true;
3828 }
3829
3830
3831 /* Code generation for choice nodes.
3832  *
3833  * We generate quick checks that do a mask and compare to eliminate a
3834  * choice.  If the quick check succeeds then it jumps to the continuation to
3835  * do slow checks and check subsequent nodes.  If it fails (the common case)
3836  * it falls through to the next choice.
3837  *
3838  * Here is the desired flow graph.  Nodes directly below each other imply
3839  * fallthrough.  Alternatives 1 and 2 have quick checks.  Alternative
3840  * 3 doesn't have a quick check so we have to call the slow check.
3841  * Nodes are marked Qn for quick checks and Sn for slow checks.  The entire
3842  * regexp continuation is generated directly after the Sn node, up to the
3843  * next GoTo if we decide to reuse some already generated code.  Some
3844  * nodes expect preload_characters to be preloaded into the current
3845  * character register.  R nodes do this preloading.  Vertices are marked
3846  * F for failures and S for success (possible success in the case of quick
3847  * nodes).  L, V, < and > are used as arrow heads.
3848  *
3849  * ----------> R
3850  *             |
3851  *             V
3852  *            Q1 -----> S1
3853  *             |   S   /
3854  *            F|      /
3855  *             |    F/
3856  *             |    /
3857  *             |   R
3858  *             |  /
3859  *             V L
3860  *            Q2 -----> S2
3861  *             |   S   /
3862  *            F|      /
3863  *             |    F/
3864  *             |    /
3865  *             |   R
3866  *             |  /
3867  *             V L
3868  *            S3
3869  *             |
3870  *            F|
3871  *             |
3872  *             R
3873  *             |
3874  * backtrack   V
3875  * <----------Q4
3876  *   \    F    |
3877  *    \        |S
3878  *     \   F   V
3879  *      \-----S4
3880  *
3881  * For greedy loops we reverse our expectation and expect to match rather
3882  * than fail. Therefore we want the loop code to look like this (U is the
3883  * unwind code that steps back in the greedy loop).  The following alternatives
3884  * look the same as above.
3885  *              _____
3886  *             /     \
3887  *             V     |
3888  * ----------> S1    |
3889  *            /|     |
3890  *           / |S    |
3891  *         F/  \_____/
3892  *         /
3893  *        |<-----------
3894  *        |            \
3895  *        V             \
3896  *        Q2 ---> S2     \
3897  *        |  S   /       |
3898  *       F|     /        |
3899  *        |   F/         |
3900  *        |   /          |
3901  *        |  R           |
3902  *        | /            |
3903  *   F    VL             |
3904  * <------U              |
3905  * back   |S             |
3906  *        \______________/
3907  */
3908
3909 void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3910   RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3911   int choice_count = alternatives_->length();
3912 #ifdef DEBUG
3913   for (int i = 0; i < choice_count - 1; i++) {
3914     GuardedAlternative alternative = alternatives_->at(i);
3915     ZoneList<Guard*>* guards = alternative.guards();
3916     int guard_count = (guards == NULL) ? 0 : guards->length();
3917     for (int j = 0; j < guard_count; j++) {
3918       DCHECK(!trace->mentions_reg(guards->at(j)->reg()));
3919     }
3920   }
3921 #endif
3922
3923   LimitResult limit_result = LimitVersions(compiler, trace);
3924   if (limit_result == DONE) return;
3925   DCHECK(limit_result == CONTINUE);
3926
3927   int new_flush_budget = trace->flush_budget() / choice_count;
3928   if (trace->flush_budget() == 0 && trace->actions() != NULL) {
3929     trace->Flush(compiler, this);
3930     return;
3931   }
3932
3933   RecursionCheck rc(compiler);
3934
3935   Trace* current_trace = trace;
3936
3937   int text_length = GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
3938   bool greedy_loop = false;
3939   Label greedy_loop_label;
3940   Trace counter_backtrack_trace;
3941   counter_backtrack_trace.set_backtrack(&greedy_loop_label);
3942   if (not_at_start()) counter_backtrack_trace.set_at_start(false);
3943
3944   if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
3945     // Here we have special handling for greedy loops containing only text nodes
3946     // and other simple nodes.  These are handled by pushing the current
3947     // position on the stack and then incrementing the current position each
3948     // time around the switch.  On backtrack we decrement the current position
3949     // and check it against the pushed value.  This avoids pushing backtrack
3950     // information for each iteration of the loop, which could take up a lot of
3951     // space.
3952     greedy_loop = true;
3953     DCHECK(trace->stop_node() == NULL);
3954     macro_assembler->PushCurrentPosition();
3955     current_trace = &counter_backtrack_trace;
3956     Label greedy_match_failed;
3957     Trace greedy_match_trace;
3958     if (not_at_start()) greedy_match_trace.set_at_start(false);
3959     greedy_match_trace.set_backtrack(&greedy_match_failed);
3960     Label loop_label;
3961     macro_assembler->Bind(&loop_label);
3962     greedy_match_trace.set_stop_node(this);
3963     greedy_match_trace.set_loop_label(&loop_label);
3964     alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
3965     macro_assembler->Bind(&greedy_match_failed);
3966   }
3967
3968   Label second_choice;  // For use in greedy matches.
3969   macro_assembler->Bind(&second_choice);
3970
3971   int first_normal_choice = greedy_loop ? 1 : 0;
3972
3973   bool not_at_start = current_trace->at_start() == Trace::FALSE_VALUE;
3974   const int kEatsAtLeastNotYetInitialized = -1;
3975   int eats_at_least = kEatsAtLeastNotYetInitialized;
3976
3977   bool skip_was_emitted = false;
3978
3979   if (!greedy_loop && choice_count == 2) {
3980     GuardedAlternative alt1 = alternatives_->at(1);
3981     if (alt1.guards() == NULL || alt1.guards()->length() == 0) {
3982       RegExpNode* eats_anything_node = alt1.node();
3983       if (eats_anything_node->GetSuccessorOfOmnivorousTextNode(compiler) ==
3984           this) {
3985         // At this point we know that we are at a non-greedy loop that will eat
3986         // any character one at a time.  Any non-anchored regexp has such a
3987         // loop prepended to it in order to find where it starts.  We look for
3988         // a pattern of the form ...abc... where we can look 6 characters ahead
3989         // and step forwards 3 if the character is not one of abc.  Abc need
3990         // not be atoms, they can be any reasonably limited character class or
3991         // small alternation.
3992         DCHECK(trace->is_trivial());  // This is the case on LoopChoiceNodes.
3993         BoyerMooreLookahead* lookahead = bm_info(not_at_start);
3994         if (lookahead == NULL) {
3995           eats_at_least = Min(kMaxLookaheadForBoyerMoore,
3996                               EatsAtLeast(kMaxLookaheadForBoyerMoore,
3997                                           kRecursionBudget,
3998                                           not_at_start));
3999           if (eats_at_least >= 1) {
4000             BoyerMooreLookahead* bm =
4001                 new(zone()) BoyerMooreLookahead(eats_at_least,
4002                                                 compiler,
4003                                                 zone());
4004             GuardedAlternative alt0 = alternatives_->at(0);
4005             alt0.node()->FillInBMInfo(0, kRecursionBudget, bm, not_at_start);
4006             skip_was_emitted = bm->EmitSkipInstructions(macro_assembler);
4007           }
4008         } else {
4009           skip_was_emitted = lookahead->EmitSkipInstructions(macro_assembler);
4010         }
4011       }
4012     }
4013   }
4014
4015   if (eats_at_least == kEatsAtLeastNotYetInitialized) {
4016     // Save some time by looking at most one machine word ahead.
4017     eats_at_least =
4018         EatsAtLeast(compiler->ascii() ? 4 : 2, kRecursionBudget, not_at_start);
4019   }
4020   int preload_characters = CalculatePreloadCharacters(compiler, eats_at_least);
4021
4022   bool preload_is_current = !skip_was_emitted &&
4023       (current_trace->characters_preloaded() == preload_characters);
4024   bool preload_has_checked_bounds = preload_is_current;
4025
4026   AlternativeGenerationList alt_gens(choice_count, zone());
4027
4028   // For now we just call all choices one after the other.  The idea ultimately
4029   // is to use the Dispatch table to try only the relevant ones.
4030   for (int i = first_normal_choice; i < choice_count; i++) {
4031     GuardedAlternative alternative = alternatives_->at(i);
4032     AlternativeGeneration* alt_gen = alt_gens.at(i);
4033     alt_gen->quick_check_details.set_characters(preload_characters);
4034     ZoneList<Guard*>* guards = alternative.guards();
4035     int guard_count = (guards == NULL) ? 0 : guards->length();
4036     Trace new_trace(*current_trace);
4037     new_trace.set_characters_preloaded(preload_is_current ?
4038                                          preload_characters :
4039                                          0);
4040     if (preload_has_checked_bounds) {
4041       new_trace.set_bound_checked_up_to(preload_characters);
4042     }
4043     new_trace.quick_check_performed()->Clear();
4044     if (not_at_start_) new_trace.set_at_start(Trace::FALSE_VALUE);
4045     alt_gen->expects_preload = preload_is_current;
4046     bool generate_full_check_inline = false;
4047     if (FLAG_regexp_optimization &&
4048         try_to_emit_quick_check_for_alternative(i) &&
4049         alternative.node()->EmitQuickCheck(compiler,
4050                                            &new_trace,
4051                                            preload_has_checked_bounds,
4052                                            &alt_gen->possible_success,
4053                                            &alt_gen->quick_check_details,
4054                                            i < choice_count - 1)) {
4055       // Quick check was generated for this choice.
4056       preload_is_current = true;
4057       preload_has_checked_bounds = true;
4058       // On the last choice in the ChoiceNode we generated the quick
4059       // check to fall through on possible success.  So now we need to
4060       // generate the full check inline.
4061       if (i == choice_count - 1) {
4062         macro_assembler->Bind(&alt_gen->possible_success);
4063         new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
4064         new_trace.set_characters_preloaded(preload_characters);
4065         new_trace.set_bound_checked_up_to(preload_characters);
4066         generate_full_check_inline = true;
4067       }
4068     } else if (alt_gen->quick_check_details.cannot_match()) {
4069       if (i == choice_count - 1 && !greedy_loop) {
4070         macro_assembler->GoTo(trace->backtrack());
4071       }
4072       continue;
4073     } else {
4074       // No quick check was generated.  Put the full code here.
4075       // If this is not the first choice then there could be slow checks from
4076       // previous cases that go here when they fail.  There's no reason to
4077       // insist that they preload characters since the slow check we are about
4078       // to generate probably can't use it.
4079       if (i != first_normal_choice) {
4080         alt_gen->expects_preload = false;
4081         new_trace.InvalidateCurrentCharacter();
4082       }
4083       if (i < choice_count - 1) {
4084         new_trace.set_backtrack(&alt_gen->after);
4085       }
4086       generate_full_check_inline = true;
4087     }
4088     if (generate_full_check_inline) {
4089       if (new_trace.actions() != NULL) {
4090         new_trace.set_flush_budget(new_flush_budget);
4091       }
4092       for (int j = 0; j < guard_count; j++) {
4093         GenerateGuard(macro_assembler, guards->at(j), &new_trace);
4094       }
4095       alternative.node()->Emit(compiler, &new_trace);
4096       preload_is_current = false;
4097     }
4098     macro_assembler->Bind(&alt_gen->after);
4099   }
4100   if (greedy_loop) {
4101     macro_assembler->Bind(&greedy_loop_label);
4102     // If we have unwound to the bottom then backtrack.
4103     macro_assembler->CheckGreedyLoop(trace->backtrack());
4104     // Otherwise try the second priority at an earlier position.
4105     macro_assembler->AdvanceCurrentPosition(-text_length);
4106     macro_assembler->GoTo(&second_choice);
4107   }
4108
4109   // At this point we need to generate slow checks for the alternatives where
4110   // the quick check was inlined.  We can recognize these because the associated
4111   // label was bound.
4112   for (int i = first_normal_choice; i < choice_count - 1; i++) {
4113     AlternativeGeneration* alt_gen = alt_gens.at(i);
4114     Trace new_trace(*current_trace);
4115     // If there are actions to be flushed we have to limit how many times
4116     // they are flushed.  Take the budget of the parent trace and distribute
4117     // it fairly amongst the children.
4118     if (new_trace.actions() != NULL) {
4119       new_trace.set_flush_budget(new_flush_budget);
4120     }
4121     EmitOutOfLineContinuation(compiler,
4122                               &new_trace,
4123                               alternatives_->at(i),
4124                               alt_gen,
4125                               preload_characters,
4126                               alt_gens.at(i + 1)->expects_preload);
4127   }
4128 }
4129
4130
4131 void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
4132                                            Trace* trace,
4133                                            GuardedAlternative alternative,
4134                                            AlternativeGeneration* alt_gen,
4135                                            int preload_characters,
4136                                            bool next_expects_preload) {
4137   if (!alt_gen->possible_success.is_linked()) return;
4138
4139   RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4140   macro_assembler->Bind(&alt_gen->possible_success);
4141   Trace out_of_line_trace(*trace);
4142   out_of_line_trace.set_characters_preloaded(preload_characters);
4143   out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
4144   if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE_VALUE);
4145   ZoneList<Guard*>* guards = alternative.guards();
4146   int guard_count = (guards == NULL) ? 0 : guards->length();
4147   if (next_expects_preload) {
4148     Label reload_current_char;
4149     out_of_line_trace.set_backtrack(&reload_current_char);
4150     for (int j = 0; j < guard_count; j++) {
4151       GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
4152     }
4153     alternative.node()->Emit(compiler, &out_of_line_trace);
4154     macro_assembler->Bind(&reload_current_char);
4155     // Reload the current character, since the next quick check expects that.
4156     // We don't need to check bounds here because we only get into this
4157     // code through a quick check which already did the checked load.
4158     macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
4159                                           NULL,
4160                                           false,
4161                                           preload_characters);
4162     macro_assembler->GoTo(&(alt_gen->after));
4163   } else {
4164     out_of_line_trace.set_backtrack(&(alt_gen->after));
4165     for (int j = 0; j < guard_count; j++) {
4166       GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
4167     }
4168     alternative.node()->Emit(compiler, &out_of_line_trace);
4169   }
4170 }
4171
4172
4173 void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4174   RegExpMacroAssembler* assembler = compiler->macro_assembler();
4175   LimitResult limit_result = LimitVersions(compiler, trace);
4176   if (limit_result == DONE) return;
4177   DCHECK(limit_result == CONTINUE);
4178
4179   RecursionCheck rc(compiler);
4180
4181   switch (action_type_) {
4182     case STORE_POSITION: {
4183       Trace::DeferredCapture
4184           new_capture(data_.u_position_register.reg,
4185                       data_.u_position_register.is_capture,
4186                       trace);
4187       Trace new_trace = *trace;
4188       new_trace.add_action(&new_capture);
4189       on_success()->Emit(compiler, &new_trace);
4190       break;
4191     }
4192     case INCREMENT_REGISTER: {
4193       Trace::DeferredIncrementRegister
4194           new_increment(data_.u_increment_register.reg);
4195       Trace new_trace = *trace;
4196       new_trace.add_action(&new_increment);
4197       on_success()->Emit(compiler, &new_trace);
4198       break;
4199     }
4200     case SET_REGISTER: {
4201       Trace::DeferredSetRegister
4202           new_set(data_.u_store_register.reg, data_.u_store_register.value);
4203       Trace new_trace = *trace;
4204       new_trace.add_action(&new_set);
4205       on_success()->Emit(compiler, &new_trace);
4206       break;
4207     }
4208     case CLEAR_CAPTURES: {
4209       Trace::DeferredClearCaptures
4210         new_capture(Interval(data_.u_clear_captures.range_from,
4211                              data_.u_clear_captures.range_to));
4212       Trace new_trace = *trace;
4213       new_trace.add_action(&new_capture);
4214       on_success()->Emit(compiler, &new_trace);
4215       break;
4216     }
4217     case BEGIN_SUBMATCH:
4218       if (!trace->is_trivial()) {
4219         trace->Flush(compiler, this);
4220       } else {
4221         assembler->WriteCurrentPositionToRegister(
4222             data_.u_submatch.current_position_register, 0);
4223         assembler->WriteStackPointerToRegister(
4224             data_.u_submatch.stack_pointer_register);
4225         on_success()->Emit(compiler, trace);
4226       }
4227       break;
4228     case EMPTY_MATCH_CHECK: {
4229       int start_pos_reg = data_.u_empty_match_check.start_register;
4230       int stored_pos = 0;
4231       int rep_reg = data_.u_empty_match_check.repetition_register;
4232       bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
4233       bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
4234       if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
4235         // If we know we haven't advanced and there is no minimum we
4236         // can just backtrack immediately.
4237         assembler->GoTo(trace->backtrack());
4238       } else if (know_dist && stored_pos < trace->cp_offset()) {
4239         // If we know we've advanced we can generate the continuation
4240         // immediately.
4241         on_success()->Emit(compiler, trace);
4242       } else if (!trace->is_trivial()) {
4243         trace->Flush(compiler, this);
4244       } else {
4245         Label skip_empty_check;
4246         // If we have a minimum number of repetitions we check the current
4247         // number first and skip the empty check if it's not enough.
4248         if (has_minimum) {
4249           int limit = data_.u_empty_match_check.repetition_limit;
4250           assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
4251         }
4252         // If the match is empty we bail out, otherwise we fall through
4253         // to the on-success continuation.
4254         assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
4255                                    trace->backtrack());
4256         assembler->Bind(&skip_empty_check);
4257         on_success()->Emit(compiler, trace);
4258       }
4259       break;
4260     }
4261     case POSITIVE_SUBMATCH_SUCCESS: {
4262       if (!trace->is_trivial()) {
4263         trace->Flush(compiler, this);
4264         return;
4265       }
4266       assembler->ReadCurrentPositionFromRegister(
4267           data_.u_submatch.current_position_register);
4268       assembler->ReadStackPointerFromRegister(
4269           data_.u_submatch.stack_pointer_register);
4270       int clear_register_count = data_.u_submatch.clear_register_count;
4271       if (clear_register_count == 0) {
4272         on_success()->Emit(compiler, trace);
4273         return;
4274       }
4275       int clear_registers_from = data_.u_submatch.clear_register_from;
4276       Label clear_registers_backtrack;
4277       Trace new_trace = *trace;
4278       new_trace.set_backtrack(&clear_registers_backtrack);
4279       on_success()->Emit(compiler, &new_trace);
4280
4281       assembler->Bind(&clear_registers_backtrack);
4282       int clear_registers_to = clear_registers_from + clear_register_count - 1;
4283       assembler->ClearRegisters(clear_registers_from, clear_registers_to);
4284
4285       DCHECK(trace->backtrack() == NULL);
4286       assembler->Backtrack();
4287       return;
4288     }
4289     default:
4290       UNREACHABLE();
4291   }
4292 }
4293
4294
4295 void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4296   RegExpMacroAssembler* assembler = compiler->macro_assembler();
4297   if (!trace->is_trivial()) {
4298     trace->Flush(compiler, this);
4299     return;
4300   }
4301
4302   LimitResult limit_result = LimitVersions(compiler, trace);
4303   if (limit_result == DONE) return;
4304   DCHECK(limit_result == CONTINUE);
4305
4306   RecursionCheck rc(compiler);
4307
4308   DCHECK_EQ(start_reg_ + 1, end_reg_);
4309   if (compiler->ignore_case()) {
4310     assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
4311                                                trace->backtrack());
4312   } else {
4313     assembler->CheckNotBackReference(start_reg_, trace->backtrack());
4314   }
4315   on_success()->Emit(compiler, trace);
4316 }
4317
4318
4319 // -------------------------------------------------------------------
4320 // Dot/dotty output
4321
4322
4323 #ifdef DEBUG
4324
4325
4326 class DotPrinter: public NodeVisitor {
4327  public:
4328   DotPrinter(OStream& os, bool ignore_case)  // NOLINT
4329       : os_(os),
4330         ignore_case_(ignore_case) {}
4331   void PrintNode(const char* label, RegExpNode* node);
4332   void Visit(RegExpNode* node);
4333   void PrintAttributes(RegExpNode* from);
4334   void PrintOnFailure(RegExpNode* from, RegExpNode* to);
4335 #define DECLARE_VISIT(Type)                                          \
4336   virtual void Visit##Type(Type##Node* that);
4337 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
4338 #undef DECLARE_VISIT
4339  private:
4340   OStream& os_;
4341   bool ignore_case_;
4342 };
4343
4344
4345 void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
4346   os_ << "digraph G {\n  graph [label=\"";
4347   for (int i = 0; label[i]; i++) {
4348     switch (label[i]) {
4349       case '\\':
4350         os_ << "\\\\";
4351         break;
4352       case '"':
4353         os_ << "\"";
4354         break;
4355       default:
4356         os_ << label[i];
4357         break;
4358     }
4359   }
4360   os_ << "\"];\n";
4361   Visit(node);
4362   os_ << "}" << endl;
4363 }
4364
4365
4366 void DotPrinter::Visit(RegExpNode* node) {
4367   if (node->info()->visited) return;
4368   node->info()->visited = true;
4369   node->Accept(this);
4370 }
4371
4372
4373 void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
4374   os_ << "  n" << from << " -> n" << on_failure << " [style=dotted];\n";
4375   Visit(on_failure);
4376 }
4377
4378
4379 class TableEntryBodyPrinter {
4380  public:
4381   TableEntryBodyPrinter(OStream& os, ChoiceNode* choice)  // NOLINT
4382       : os_(os),
4383         choice_(choice) {}
4384   void Call(uc16 from, DispatchTable::Entry entry) {
4385     OutSet* out_set = entry.out_set();
4386     for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4387       if (out_set->Get(i)) {
4388         os_ << "    n" << choice() << ":s" << from << "o" << i << " -> n"
4389             << choice()->alternatives()->at(i).node() << ";\n";
4390       }
4391     }
4392   }
4393  private:
4394   ChoiceNode* choice() { return choice_; }
4395   OStream& os_;
4396   ChoiceNode* choice_;
4397 };
4398
4399
4400 class TableEntryHeaderPrinter {
4401  public:
4402   explicit TableEntryHeaderPrinter(OStream& os)  // NOLINT
4403       : first_(true),
4404         os_(os) {}
4405   void Call(uc16 from, DispatchTable::Entry entry) {
4406     if (first_) {
4407       first_ = false;
4408     } else {
4409       os_ << "|";
4410     }
4411     os_ << "{\\" << AsUC16(from) << "-\\" << AsUC16(entry.to()) << "|{";
4412     OutSet* out_set = entry.out_set();
4413     int priority = 0;
4414     for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4415       if (out_set->Get(i)) {
4416         if (priority > 0) os_ << "|";
4417         os_ << "<s" << from << "o" << i << "> " << priority;
4418         priority++;
4419       }
4420     }
4421     os_ << "}}";
4422   }
4423
4424  private:
4425   bool first_;
4426   OStream& os_;
4427 };
4428
4429
4430 class AttributePrinter {
4431  public:
4432   explicit AttributePrinter(OStream& os)  // NOLINT
4433       : os_(os),
4434         first_(true) {}
4435   void PrintSeparator() {
4436     if (first_) {
4437       first_ = false;
4438     } else {
4439       os_ << "|";
4440     }
4441   }
4442   void PrintBit(const char* name, bool value) {
4443     if (!value) return;
4444     PrintSeparator();
4445     os_ << "{" << name << "}";
4446   }
4447   void PrintPositive(const char* name, int value) {
4448     if (value < 0) return;
4449     PrintSeparator();
4450     os_ << "{" << name << "|" << value << "}";
4451   }
4452
4453  private:
4454   OStream& os_;
4455   bool first_;
4456 };
4457
4458
4459 void DotPrinter::PrintAttributes(RegExpNode* that) {
4460   os_ << "  a" << that << " [shape=Mrecord, color=grey, fontcolor=grey, "
4461       << "margin=0.1, fontsize=10, label=\"{";
4462   AttributePrinter printer(os_);
4463   NodeInfo* info = that->info();
4464   printer.PrintBit("NI", info->follows_newline_interest);
4465   printer.PrintBit("WI", info->follows_word_interest);
4466   printer.PrintBit("SI", info->follows_start_interest);
4467   Label* label = that->label();
4468   if (label->is_bound())
4469     printer.PrintPositive("@", label->pos());
4470   os_ << "}\"];\n"
4471       << "  a" << that << " -> n" << that
4472       << " [style=dashed, color=grey, arrowhead=none];\n";
4473 }
4474
4475
4476 static const bool kPrintDispatchTable = false;
4477 void DotPrinter::VisitChoice(ChoiceNode* that) {
4478   if (kPrintDispatchTable) {
4479     os_ << "  n" << that << " [shape=Mrecord, label=\"";
4480     TableEntryHeaderPrinter header_printer(os_);
4481     that->GetTable(ignore_case_)->ForEach(&header_printer);
4482     os_ << "\"]\n";
4483     PrintAttributes(that);
4484     TableEntryBodyPrinter body_printer(os_, that);
4485     that->GetTable(ignore_case_)->ForEach(&body_printer);
4486   } else {
4487     os_ << "  n" << that << " [shape=Mrecord, label=\"?\"];\n";
4488     for (int i = 0; i < that->alternatives()->length(); i++) {
4489       GuardedAlternative alt = that->alternatives()->at(i);
4490       os_ << "  n" << that << " -> n" << alt.node();
4491     }
4492   }
4493   for (int i = 0; i < that->alternatives()->length(); i++) {
4494     GuardedAlternative alt = that->alternatives()->at(i);
4495     alt.node()->Accept(this);
4496   }
4497 }
4498
4499
4500 void DotPrinter::VisitText(TextNode* that) {
4501   Zone* zone = that->zone();
4502   os_ << "  n" << that << " [label=\"";
4503   for (int i = 0; i < that->elements()->length(); i++) {
4504     if (i > 0) os_ << " ";
4505     TextElement elm = that->elements()->at(i);
4506     switch (elm.text_type()) {
4507       case TextElement::ATOM: {
4508         Vector<const uc16> data = elm.atom()->data();
4509         for (int i = 0; i < data.length(); i++) {
4510           os_ << static_cast<char>(data[i]);
4511         }
4512         break;
4513       }
4514       case TextElement::CHAR_CLASS: {
4515         RegExpCharacterClass* node = elm.char_class();
4516         os_ << "[";
4517         if (node->is_negated()) os_ << "^";
4518         for (int j = 0; j < node->ranges(zone)->length(); j++) {
4519           CharacterRange range = node->ranges(zone)->at(j);
4520           os_ << AsUC16(range.from()) << "-" << AsUC16(range.to());
4521         }
4522         os_ << "]";
4523         break;
4524       }
4525       default:
4526         UNREACHABLE();
4527     }
4528   }
4529   os_ << "\", shape=box, peripheries=2];\n";
4530   PrintAttributes(that);
4531   os_ << "  n" << that << " -> n" << that->on_success() << ";\n";
4532   Visit(that->on_success());
4533 }
4534
4535
4536 void DotPrinter::VisitBackReference(BackReferenceNode* that) {
4537   os_ << "  n" << that << " [label=\"$" << that->start_register() << "..$"
4538       << that->end_register() << "\", shape=doubleoctagon];\n";
4539   PrintAttributes(that);
4540   os_ << "  n" << that << " -> n" << that->on_success() << ";\n";
4541   Visit(that->on_success());
4542 }
4543
4544
4545 void DotPrinter::VisitEnd(EndNode* that) {
4546   os_ << "  n" << that << " [style=bold, shape=point];\n";
4547   PrintAttributes(that);
4548 }
4549
4550
4551 void DotPrinter::VisitAssertion(AssertionNode* that) {
4552   os_ << "  n" << that << " [";
4553   switch (that->assertion_type()) {
4554     case AssertionNode::AT_END:
4555       os_ << "label=\"$\", shape=septagon";
4556       break;
4557     case AssertionNode::AT_START:
4558       os_ << "label=\"^\", shape=septagon";
4559       break;
4560     case AssertionNode::AT_BOUNDARY:
4561       os_ << "label=\"\\b\", shape=septagon";
4562       break;
4563     case AssertionNode::AT_NON_BOUNDARY:
4564       os_ << "label=\"\\B\", shape=septagon";
4565       break;
4566     case AssertionNode::AFTER_NEWLINE:
4567       os_ << "label=\"(?<=\\n)\", shape=septagon";
4568       break;
4569   }
4570   os_ << "];\n";
4571   PrintAttributes(that);
4572   RegExpNode* successor = that->on_success();
4573   os_ << "  n" << that << " -> n" << successor << ";\n";
4574   Visit(successor);
4575 }
4576
4577
4578 void DotPrinter::VisitAction(ActionNode* that) {
4579   os_ << "  n" << that << " [";
4580   switch (that->action_type_) {
4581     case ActionNode::SET_REGISTER:
4582       os_ << "label=\"$" << that->data_.u_store_register.reg
4583           << ":=" << that->data_.u_store_register.value << "\", shape=octagon";
4584       break;
4585     case ActionNode::INCREMENT_REGISTER:
4586       os_ << "label=\"$" << that->data_.u_increment_register.reg
4587           << "++\", shape=octagon";
4588       break;
4589     case ActionNode::STORE_POSITION:
4590       os_ << "label=\"$" << that->data_.u_position_register.reg
4591           << ":=$pos\", shape=octagon";
4592       break;
4593     case ActionNode::BEGIN_SUBMATCH:
4594       os_ << "label=\"$" << that->data_.u_submatch.current_position_register
4595           << ":=$pos,begin\", shape=septagon";
4596       break;
4597     case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
4598       os_ << "label=\"escape\", shape=septagon";
4599       break;
4600     case ActionNode::EMPTY_MATCH_CHECK:
4601       os_ << "label=\"$" << that->data_.u_empty_match_check.start_register
4602           << "=$pos?,$" << that->data_.u_empty_match_check.repetition_register
4603           << "<" << that->data_.u_empty_match_check.repetition_limit
4604           << "?\", shape=septagon";
4605       break;
4606     case ActionNode::CLEAR_CAPTURES: {
4607       os_ << "label=\"clear $" << that->data_.u_clear_captures.range_from
4608           << " to $" << that->data_.u_clear_captures.range_to
4609           << "\", shape=septagon";
4610       break;
4611     }
4612   }
4613   os_ << "];\n";
4614   PrintAttributes(that);
4615   RegExpNode* successor = that->on_success();
4616   os_ << "  n" << that << " -> n" << successor << ";\n";
4617   Visit(successor);
4618 }
4619
4620
4621 class DispatchTableDumper {
4622  public:
4623   explicit DispatchTableDumper(OStream& os) : os_(os) {}
4624   void Call(uc16 key, DispatchTable::Entry entry);
4625  private:
4626   OStream& os_;
4627 };
4628
4629
4630 void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
4631   os_ << "[" << AsUC16(key) << "-" << AsUC16(entry.to()) << "]: {";
4632   OutSet* set = entry.out_set();
4633   bool first = true;
4634   for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4635     if (set->Get(i)) {
4636       if (first) {
4637         first = false;
4638       } else {
4639         os_ << ", ";
4640       }
4641       os_ << i;
4642     }
4643   }
4644   os_ << "}\n";
4645 }
4646
4647
4648 void DispatchTable::Dump() {
4649   OFStream os(stderr);
4650   DispatchTableDumper dumper(os);
4651   tree()->ForEach(&dumper);
4652 }
4653
4654
4655 void RegExpEngine::DotPrint(const char* label,
4656                             RegExpNode* node,
4657                             bool ignore_case) {
4658   OFStream os(stdout);
4659   DotPrinter printer(os, ignore_case);
4660   printer.PrintNode(label, node);
4661 }
4662
4663
4664 #endif  // DEBUG
4665
4666
4667 // -------------------------------------------------------------------
4668 // Tree to graph conversion
4669
4670 RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
4671                                RegExpNode* on_success) {
4672   ZoneList<TextElement>* elms =
4673       new(compiler->zone()) ZoneList<TextElement>(1, compiler->zone());
4674   elms->Add(TextElement::Atom(this), compiler->zone());
4675   return new(compiler->zone()) TextNode(elms, on_success);
4676 }
4677
4678
4679 RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
4680                                RegExpNode* on_success) {
4681   return new(compiler->zone()) TextNode(elements(), on_success);
4682 }
4683
4684
4685 static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
4686                                  const int* special_class,
4687                                  int length) {
4688   length--;  // Remove final 0x10000.
4689   DCHECK(special_class[length] == 0x10000);
4690   DCHECK(ranges->length() != 0);
4691   DCHECK(length != 0);
4692   DCHECK(special_class[0] != 0);
4693   if (ranges->length() != (length >> 1) + 1) {
4694     return false;
4695   }
4696   CharacterRange range = ranges->at(0);
4697   if (range.from() != 0) {
4698     return false;
4699   }
4700   for (int i = 0; i < length; i += 2) {
4701     if (special_class[i] != (range.to() + 1)) {
4702       return false;
4703     }
4704     range = ranges->at((i >> 1) + 1);
4705     if (special_class[i+1] != range.from()) {
4706       return false;
4707     }
4708   }
4709   if (range.to() != 0xffff) {
4710     return false;
4711   }
4712   return true;
4713 }
4714
4715
4716 static bool CompareRanges(ZoneList<CharacterRange>* ranges,
4717                           const int* special_class,
4718                           int length) {
4719   length--;  // Remove final 0x10000.
4720   DCHECK(special_class[length] == 0x10000);
4721   if (ranges->length() * 2 != length) {
4722     return false;
4723   }
4724   for (int i = 0; i < length; i += 2) {
4725     CharacterRange range = ranges->at(i >> 1);
4726     if (range.from() != special_class[i] ||
4727         range.to() != special_class[i + 1] - 1) {
4728       return false;
4729     }
4730   }
4731   return true;
4732 }
4733
4734
4735 bool RegExpCharacterClass::is_standard(Zone* zone) {
4736   // TODO(lrn): Remove need for this function, by not throwing away information
4737   // along the way.
4738   if (is_negated_) {
4739     return false;
4740   }
4741   if (set_.is_standard()) {
4742     return true;
4743   }
4744   if (CompareRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
4745     set_.set_standard_set_type('s');
4746     return true;
4747   }
4748   if (CompareInverseRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
4749     set_.set_standard_set_type('S');
4750     return true;
4751   }
4752   if (CompareInverseRanges(set_.ranges(zone),
4753                            kLineTerminatorRanges,
4754                            kLineTerminatorRangeCount)) {
4755     set_.set_standard_set_type('.');
4756     return true;
4757   }
4758   if (CompareRanges(set_.ranges(zone),
4759                     kLineTerminatorRanges,
4760                     kLineTerminatorRangeCount)) {
4761     set_.set_standard_set_type('n');
4762     return true;
4763   }
4764   if (CompareRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
4765     set_.set_standard_set_type('w');
4766     return true;
4767   }
4768   if (CompareInverseRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
4769     set_.set_standard_set_type('W');
4770     return true;
4771   }
4772   return false;
4773 }
4774
4775
4776 RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
4777                                          RegExpNode* on_success) {
4778   return new(compiler->zone()) TextNode(this, on_success);
4779 }
4780
4781
4782 RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
4783                                       RegExpNode* on_success) {
4784   ZoneList<RegExpTree*>* alternatives = this->alternatives();
4785   int length = alternatives->length();
4786   ChoiceNode* result =
4787       new(compiler->zone()) ChoiceNode(length, compiler->zone());
4788   for (int i = 0; i < length; i++) {
4789     GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
4790                                                                on_success));
4791     result->AddAlternative(alternative);
4792   }
4793   return result;
4794 }
4795
4796
4797 RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
4798                                      RegExpNode* on_success) {
4799   return ToNode(min(),
4800                 max(),
4801                 is_greedy(),
4802                 body(),
4803                 compiler,
4804                 on_success);
4805 }
4806
4807
4808 // Scoped object to keep track of how much we unroll quantifier loops in the
4809 // regexp graph generator.
4810 class RegExpExpansionLimiter {
4811  public:
4812   static const int kMaxExpansionFactor = 6;
4813   RegExpExpansionLimiter(RegExpCompiler* compiler, int factor)
4814       : compiler_(compiler),
4815         saved_expansion_factor_(compiler->current_expansion_factor()),
4816         ok_to_expand_(saved_expansion_factor_ <= kMaxExpansionFactor) {
4817     DCHECK(factor > 0);
4818     if (ok_to_expand_) {
4819       if (factor > kMaxExpansionFactor) {
4820         // Avoid integer overflow of the current expansion factor.
4821         ok_to_expand_ = false;
4822         compiler->set_current_expansion_factor(kMaxExpansionFactor + 1);
4823       } else {
4824         int new_factor = saved_expansion_factor_ * factor;
4825         ok_to_expand_ = (new_factor <= kMaxExpansionFactor);
4826         compiler->set_current_expansion_factor(new_factor);
4827       }
4828     }
4829   }
4830
4831   ~RegExpExpansionLimiter() {
4832     compiler_->set_current_expansion_factor(saved_expansion_factor_);
4833   }
4834
4835   bool ok_to_expand() { return ok_to_expand_; }
4836
4837  private:
4838   RegExpCompiler* compiler_;
4839   int saved_expansion_factor_;
4840   bool ok_to_expand_;
4841
4842   DISALLOW_IMPLICIT_CONSTRUCTORS(RegExpExpansionLimiter);
4843 };
4844
4845
4846 RegExpNode* RegExpQuantifier::ToNode(int min,
4847                                      int max,
4848                                      bool is_greedy,
4849                                      RegExpTree* body,
4850                                      RegExpCompiler* compiler,
4851                                      RegExpNode* on_success,
4852                                      bool not_at_start) {
4853   // x{f, t} becomes this:
4854   //
4855   //             (r++)<-.
4856   //               |     `
4857   //               |     (x)
4858   //               v     ^
4859   //      (r=0)-->(?)---/ [if r < t]
4860   //               |
4861   //   [if r >= f] \----> ...
4862   //
4863
4864   // 15.10.2.5 RepeatMatcher algorithm.
4865   // The parser has already eliminated the case where max is 0.  In the case
4866   // where max_match is zero the parser has removed the quantifier if min was
4867   // > 0 and removed the atom if min was 0.  See AddQuantifierToAtom.
4868
4869   // If we know that we cannot match zero length then things are a little
4870   // simpler since we don't need to make the special zero length match check
4871   // from step 2.1.  If the min and max are small we can unroll a little in
4872   // this case.
4873   static const int kMaxUnrolledMinMatches = 3;  // Unroll (foo)+ and (foo){3,}
4874   static const int kMaxUnrolledMaxMatches = 3;  // Unroll (foo)? and (foo){x,3}
4875   if (max == 0) return on_success;  // This can happen due to recursion.
4876   bool body_can_be_empty = (body->min_match() == 0);
4877   int body_start_reg = RegExpCompiler::kNoRegister;
4878   Interval capture_registers = body->CaptureRegisters();
4879   bool needs_capture_clearing = !capture_registers.is_empty();
4880   Zone* zone = compiler->zone();
4881
4882   if (body_can_be_empty) {
4883     body_start_reg = compiler->AllocateRegister();
4884   } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
4885     // Only unroll if there are no captures and the body can't be
4886     // empty.
4887     {
4888       RegExpExpansionLimiter limiter(
4889           compiler, min + ((max != min) ? 1 : 0));
4890       if (min > 0 && min <= kMaxUnrolledMinMatches && limiter.ok_to_expand()) {
4891         int new_max = (max == kInfinity) ? max : max - min;
4892         // Recurse once to get the loop or optional matches after the fixed
4893         // ones.
4894         RegExpNode* answer = ToNode(
4895             0, new_max, is_greedy, body, compiler, on_success, true);
4896         // Unroll the forced matches from 0 to min.  This can cause chains of
4897         // TextNodes (which the parser does not generate).  These should be
4898         // combined if it turns out they hinder good code generation.
4899         for (int i = 0; i < min; i++) {
4900           answer = body->ToNode(compiler, answer);
4901         }
4902         return answer;
4903       }
4904     }
4905     if (max <= kMaxUnrolledMaxMatches && min == 0) {
4906       DCHECK(max > 0);  // Due to the 'if' above.
4907       RegExpExpansionLimiter limiter(compiler, max);
4908       if (limiter.ok_to_expand()) {
4909         // Unroll the optional matches up to max.
4910         RegExpNode* answer = on_success;
4911         for (int i = 0; i < max; i++) {
4912           ChoiceNode* alternation = new(zone) ChoiceNode(2, zone);
4913           if (is_greedy) {
4914             alternation->AddAlternative(
4915                 GuardedAlternative(body->ToNode(compiler, answer)));
4916             alternation->AddAlternative(GuardedAlternative(on_success));
4917           } else {
4918             alternation->AddAlternative(GuardedAlternative(on_success));
4919             alternation->AddAlternative(
4920                 GuardedAlternative(body->ToNode(compiler, answer)));
4921           }
4922           answer = alternation;
4923           if (not_at_start) alternation->set_not_at_start();
4924         }
4925         return answer;
4926       }
4927     }
4928   }
4929   bool has_min = min > 0;
4930   bool has_max = max < RegExpTree::kInfinity;
4931   bool needs_counter = has_min || has_max;
4932   int reg_ctr = needs_counter
4933       ? compiler->AllocateRegister()
4934       : RegExpCompiler::kNoRegister;
4935   LoopChoiceNode* center = new(zone) LoopChoiceNode(body->min_match() == 0,
4936                                                     zone);
4937   if (not_at_start) center->set_not_at_start();
4938   RegExpNode* loop_return = needs_counter
4939       ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
4940       : static_cast<RegExpNode*>(center);
4941   if (body_can_be_empty) {
4942     // If the body can be empty we need to check if it was and then
4943     // backtrack.
4944     loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
4945                                               reg_ctr,
4946                                               min,
4947                                               loop_return);
4948   }
4949   RegExpNode* body_node = body->ToNode(compiler, loop_return);
4950   if (body_can_be_empty) {
4951     // If the body can be empty we need to store the start position
4952     // so we can bail out if it was empty.
4953     body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
4954   }
4955   if (needs_capture_clearing) {
4956     // Before entering the body of this loop we need to clear captures.
4957     body_node = ActionNode::ClearCaptures(capture_registers, body_node);
4958   }
4959   GuardedAlternative body_alt(body_node);
4960   if (has_max) {
4961     Guard* body_guard =
4962         new(zone) Guard(reg_ctr, Guard::LT, max);
4963     body_alt.AddGuard(body_guard, zone);
4964   }
4965   GuardedAlternative rest_alt(on_success);
4966   if (has_min) {
4967     Guard* rest_guard = new(compiler->zone()) Guard(reg_ctr, Guard::GEQ, min);
4968     rest_alt.AddGuard(rest_guard, zone);
4969   }
4970   if (is_greedy) {
4971     center->AddLoopAlternative(body_alt);
4972     center->AddContinueAlternative(rest_alt);
4973   } else {
4974     center->AddContinueAlternative(rest_alt);
4975     center->AddLoopAlternative(body_alt);
4976   }
4977   if (needs_counter) {
4978     return ActionNode::SetRegister(reg_ctr, 0, center);
4979   } else {
4980     return center;
4981   }
4982 }
4983
4984
4985 RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
4986                                     RegExpNode* on_success) {
4987   NodeInfo info;
4988   Zone* zone = compiler->zone();
4989
4990   switch (assertion_type()) {
4991     case START_OF_LINE:
4992       return AssertionNode::AfterNewline(on_success);
4993     case START_OF_INPUT:
4994       return AssertionNode::AtStart(on_success);
4995     case BOUNDARY:
4996       return AssertionNode::AtBoundary(on_success);
4997     case NON_BOUNDARY:
4998       return AssertionNode::AtNonBoundary(on_success);
4999     case END_OF_INPUT:
5000       return AssertionNode::AtEnd(on_success);
5001     case END_OF_LINE: {
5002       // Compile $ in multiline regexps as an alternation with a positive
5003       // lookahead in one side and an end-of-input on the other side.
5004       // We need two registers for the lookahead.
5005       int stack_pointer_register = compiler->AllocateRegister();
5006       int position_register = compiler->AllocateRegister();
5007       // The ChoiceNode to distinguish between a newline and end-of-input.
5008       ChoiceNode* result = new(zone) ChoiceNode(2, zone);
5009       // Create a newline atom.
5010       ZoneList<CharacterRange>* newline_ranges =
5011           new(zone) ZoneList<CharacterRange>(3, zone);
5012       CharacterRange::AddClassEscape('n', newline_ranges, zone);
5013       RegExpCharacterClass* newline_atom = new(zone) RegExpCharacterClass('n');
5014       TextNode* newline_matcher = new(zone) TextNode(
5015          newline_atom,
5016          ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
5017                                              position_register,
5018                                              0,  // No captures inside.
5019                                              -1,  // Ignored if no captures.
5020                                              on_success));
5021       // Create an end-of-input matcher.
5022       RegExpNode* end_of_line = ActionNode::BeginSubmatch(
5023           stack_pointer_register,
5024           position_register,
5025           newline_matcher);
5026       // Add the two alternatives to the ChoiceNode.
5027       GuardedAlternative eol_alternative(end_of_line);
5028       result->AddAlternative(eol_alternative);
5029       GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
5030       result->AddAlternative(end_alternative);
5031       return result;
5032     }
5033     default:
5034       UNREACHABLE();
5035   }
5036   return on_success;
5037 }
5038
5039
5040 RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
5041                                         RegExpNode* on_success) {
5042   return new(compiler->zone())
5043       BackReferenceNode(RegExpCapture::StartRegister(index()),
5044                         RegExpCapture::EndRegister(index()),
5045                         on_success);
5046 }
5047
5048
5049 RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
5050                                 RegExpNode* on_success) {
5051   return on_success;
5052 }
5053
5054
5055 RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
5056                                     RegExpNode* on_success) {
5057   int stack_pointer_register = compiler->AllocateRegister();
5058   int position_register = compiler->AllocateRegister();
5059
5060   const int registers_per_capture = 2;
5061   const int register_of_first_capture = 2;
5062   int register_count = capture_count_ * registers_per_capture;
5063   int register_start =
5064     register_of_first_capture + capture_from_ * registers_per_capture;
5065
5066   RegExpNode* success;
5067   if (is_positive()) {
5068     RegExpNode* node = ActionNode::BeginSubmatch(
5069         stack_pointer_register,
5070         position_register,
5071         body()->ToNode(
5072             compiler,
5073             ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
5074                                                 position_register,
5075                                                 register_count,
5076                                                 register_start,
5077                                                 on_success)));
5078     return node;
5079   } else {
5080     // We use a ChoiceNode for a negative lookahead because it has most of
5081     // the characteristics we need.  It has the body of the lookahead as its
5082     // first alternative and the expression after the lookahead of the second
5083     // alternative.  If the first alternative succeeds then the
5084     // NegativeSubmatchSuccess will unwind the stack including everything the
5085     // choice node set up and backtrack.  If the first alternative fails then
5086     // the second alternative is tried, which is exactly the desired result
5087     // for a negative lookahead.  The NegativeLookaheadChoiceNode is a special
5088     // ChoiceNode that knows to ignore the first exit when calculating quick
5089     // checks.
5090     Zone* zone = compiler->zone();
5091
5092     GuardedAlternative body_alt(
5093         body()->ToNode(
5094             compiler,
5095             success = new(zone) NegativeSubmatchSuccess(stack_pointer_register,
5096                                                         position_register,
5097                                                         register_count,
5098                                                         register_start,
5099                                                         zone)));
5100     ChoiceNode* choice_node =
5101         new(zone) NegativeLookaheadChoiceNode(body_alt,
5102                                               GuardedAlternative(on_success),
5103                                               zone);
5104     return ActionNode::BeginSubmatch(stack_pointer_register,
5105                                      position_register,
5106                                      choice_node);
5107   }
5108 }
5109
5110
5111 RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
5112                                   RegExpNode* on_success) {
5113   return ToNode(body(), index(), compiler, on_success);
5114 }
5115
5116
5117 RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
5118                                   int index,
5119                                   RegExpCompiler* compiler,
5120                                   RegExpNode* on_success) {
5121   int start_reg = RegExpCapture::StartRegister(index);
5122   int end_reg = RegExpCapture::EndRegister(index);
5123   RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
5124   RegExpNode* body_node = body->ToNode(compiler, store_end);
5125   return ActionNode::StorePosition(start_reg, true, body_node);
5126 }
5127
5128
5129 RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
5130                                       RegExpNode* on_success) {
5131   ZoneList<RegExpTree*>* children = nodes();
5132   RegExpNode* current = on_success;
5133   for (int i = children->length() - 1; i >= 0; i--) {
5134     current = children->at(i)->ToNode(compiler, current);
5135   }
5136   return current;
5137 }
5138
5139
5140 static void AddClass(const int* elmv,
5141                      int elmc,
5142                      ZoneList<CharacterRange>* ranges,
5143                      Zone* zone) {
5144   elmc--;
5145   DCHECK(elmv[elmc] == 0x10000);
5146   for (int i = 0; i < elmc; i += 2) {
5147     DCHECK(elmv[i] < elmv[i + 1]);
5148     ranges->Add(CharacterRange(elmv[i], elmv[i + 1] - 1), zone);
5149   }
5150 }
5151
5152
5153 static void AddClassNegated(const int *elmv,
5154                             int elmc,
5155                             ZoneList<CharacterRange>* ranges,
5156                             Zone* zone) {
5157   elmc--;
5158   DCHECK(elmv[elmc] == 0x10000);
5159   DCHECK(elmv[0] != 0x0000);
5160   DCHECK(elmv[elmc-1] != String::kMaxUtf16CodeUnit);
5161   uc16 last = 0x0000;
5162   for (int i = 0; i < elmc; i += 2) {
5163     DCHECK(last <= elmv[i] - 1);
5164     DCHECK(elmv[i] < elmv[i + 1]);
5165     ranges->Add(CharacterRange(last, elmv[i] - 1), zone);
5166     last = elmv[i + 1];
5167   }
5168   ranges->Add(CharacterRange(last, String::kMaxUtf16CodeUnit), zone);
5169 }
5170
5171
5172 void CharacterRange::AddClassEscape(uc16 type,
5173                                     ZoneList<CharacterRange>* ranges,
5174                                     Zone* zone) {
5175   switch (type) {
5176     case 's':
5177       AddClass(kSpaceRanges, kSpaceRangeCount, ranges, zone);
5178       break;
5179     case 'S':
5180       AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges, zone);
5181       break;
5182     case 'w':
5183       AddClass(kWordRanges, kWordRangeCount, ranges, zone);
5184       break;
5185     case 'W':
5186       AddClassNegated(kWordRanges, kWordRangeCount, ranges, zone);
5187       break;
5188     case 'd':
5189       AddClass(kDigitRanges, kDigitRangeCount, ranges, zone);
5190       break;
5191     case 'D':
5192       AddClassNegated(kDigitRanges, kDigitRangeCount, ranges, zone);
5193       break;
5194     case '.':
5195       AddClassNegated(kLineTerminatorRanges,
5196                       kLineTerminatorRangeCount,
5197                       ranges,
5198                       zone);
5199       break;
5200     // This is not a character range as defined by the spec but a
5201     // convenient shorthand for a character class that matches any
5202     // character.
5203     case '*':
5204       ranges->Add(CharacterRange::Everything(), zone);
5205       break;
5206     // This is the set of characters matched by the $ and ^ symbols
5207     // in multiline mode.
5208     case 'n':
5209       AddClass(kLineTerminatorRanges,
5210                kLineTerminatorRangeCount,
5211                ranges,
5212                zone);
5213       break;
5214     default:
5215       UNREACHABLE();
5216   }
5217 }
5218
5219
5220 Vector<const int> CharacterRange::GetWordBounds() {
5221   return Vector<const int>(kWordRanges, kWordRangeCount - 1);
5222 }
5223
5224
5225 class CharacterRangeSplitter {
5226  public:
5227   CharacterRangeSplitter(ZoneList<CharacterRange>** included,
5228                          ZoneList<CharacterRange>** excluded,
5229                          Zone* zone)
5230       : included_(included),
5231         excluded_(excluded),
5232         zone_(zone) { }
5233   void Call(uc16 from, DispatchTable::Entry entry);
5234
5235   static const int kInBase = 0;
5236   static const int kInOverlay = 1;
5237
5238  private:
5239   ZoneList<CharacterRange>** included_;
5240   ZoneList<CharacterRange>** excluded_;
5241   Zone* zone_;
5242 };
5243
5244
5245 void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
5246   if (!entry.out_set()->Get(kInBase)) return;
5247   ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
5248     ? included_
5249     : excluded_;
5250   if (*target == NULL) *target = new(zone_) ZoneList<CharacterRange>(2, zone_);
5251   (*target)->Add(CharacterRange(entry.from(), entry.to()), zone_);
5252 }
5253
5254
5255 void CharacterRange::Split(ZoneList<CharacterRange>* base,
5256                            Vector<const int> overlay,
5257                            ZoneList<CharacterRange>** included,
5258                            ZoneList<CharacterRange>** excluded,
5259                            Zone* zone) {
5260   DCHECK_EQ(NULL, *included);
5261   DCHECK_EQ(NULL, *excluded);
5262   DispatchTable table(zone);
5263   for (int i = 0; i < base->length(); i++)
5264     table.AddRange(base->at(i), CharacterRangeSplitter::kInBase, zone);
5265   for (int i = 0; i < overlay.length(); i += 2) {
5266     table.AddRange(CharacterRange(overlay[i], overlay[i + 1] - 1),
5267                    CharacterRangeSplitter::kInOverlay, zone);
5268   }
5269   CharacterRangeSplitter callback(included, excluded, zone);
5270   table.ForEach(&callback);
5271 }
5272
5273
5274 void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
5275                                         bool is_ascii,
5276                                         Zone* zone) {
5277   Isolate* isolate = zone->isolate();
5278   uc16 bottom = from();
5279   uc16 top = to();
5280   if (is_ascii && !RangeContainsLatin1Equivalents(*this)) {
5281     if (bottom > String::kMaxOneByteCharCode) return;
5282     if (top > String::kMaxOneByteCharCode) top = String::kMaxOneByteCharCode;
5283   }
5284   unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5285   if (top == bottom) {
5286     // If this is a singleton we just expand the one character.
5287     int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
5288     for (int i = 0; i < length; i++) {
5289       uc32 chr = chars[i];
5290       if (chr != bottom) {
5291         ranges->Add(CharacterRange::Singleton(chars[i]), zone);
5292       }
5293     }
5294   } else {
5295     // If this is a range we expand the characters block by block,
5296     // expanding contiguous subranges (blocks) one at a time.
5297     // The approach is as follows.  For a given start character we
5298     // look up the remainder of the block that contains it (represented
5299     // by the end point), for instance we find 'z' if the character
5300     // is 'c'.  A block is characterized by the property
5301     // that all characters uncanonicalize in the same way, except that
5302     // each entry in the result is incremented by the distance from the first
5303     // element.  So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
5304     // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
5305     // Once we've found the end point we look up its uncanonicalization
5306     // and produce a range for each element.  For instance for [c-f]
5307     // we look up ['z', 'Z'] and produce [c-f] and [C-F].  We then only
5308     // add a range if it is not already contained in the input, so [c-f]
5309     // will be skipped but [C-F] will be added.  If this range is not
5310     // completely contained in a block we do this for all the blocks
5311     // covered by the range (handling characters that is not in a block
5312     // as a "singleton block").
5313     unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5314     int pos = bottom;
5315     while (pos <= top) {
5316       int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
5317       uc16 block_end;
5318       if (length == 0) {
5319         block_end = pos;
5320       } else {
5321         DCHECK_EQ(1, length);
5322         block_end = range[0];
5323       }
5324       int end = (block_end > top) ? top : block_end;
5325       length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
5326       for (int i = 0; i < length; i++) {
5327         uc32 c = range[i];
5328         uc16 range_from = c - (block_end - pos);
5329         uc16 range_to = c - (block_end - end);
5330         if (!(bottom <= range_from && range_to <= top)) {
5331           ranges->Add(CharacterRange(range_from, range_to), zone);
5332         }
5333       }
5334       pos = end + 1;
5335     }
5336   }
5337 }
5338
5339
5340 bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
5341   DCHECK_NOT_NULL(ranges);
5342   int n = ranges->length();
5343   if (n <= 1) return true;
5344   int max = ranges->at(0).to();
5345   for (int i = 1; i < n; i++) {
5346     CharacterRange next_range = ranges->at(i);
5347     if (next_range.from() <= max + 1) return false;
5348     max = next_range.to();
5349   }
5350   return true;
5351 }
5352
5353
5354 ZoneList<CharacterRange>* CharacterSet::ranges(Zone* zone) {
5355   if (ranges_ == NULL) {
5356     ranges_ = new(zone) ZoneList<CharacterRange>(2, zone);
5357     CharacterRange::AddClassEscape(standard_set_type_, ranges_, zone);
5358   }
5359   return ranges_;
5360 }
5361
5362
5363 // Move a number of elements in a zonelist to another position
5364 // in the same list. Handles overlapping source and target areas.
5365 static void MoveRanges(ZoneList<CharacterRange>* list,
5366                        int from,
5367                        int to,
5368                        int count) {
5369   // Ranges are potentially overlapping.
5370   if (from < to) {
5371     for (int i = count - 1; i >= 0; i--) {
5372       list->at(to + i) = list->at(from + i);
5373     }
5374   } else {
5375     for (int i = 0; i < count; i++) {
5376       list->at(to + i) = list->at(from + i);
5377     }
5378   }
5379 }
5380
5381
5382 static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
5383                                       int count,
5384                                       CharacterRange insert) {
5385   // Inserts a range into list[0..count[, which must be sorted
5386   // by from value and non-overlapping and non-adjacent, using at most
5387   // list[0..count] for the result. Returns the number of resulting
5388   // canonicalized ranges. Inserting a range may collapse existing ranges into
5389   // fewer ranges, so the return value can be anything in the range 1..count+1.
5390   uc16 from = insert.from();
5391   uc16 to = insert.to();
5392   int start_pos = 0;
5393   int end_pos = count;
5394   for (int i = count - 1; i >= 0; i--) {
5395     CharacterRange current = list->at(i);
5396     if (current.from() > to + 1) {
5397       end_pos = i;
5398     } else if (current.to() + 1 < from) {
5399       start_pos = i + 1;
5400       break;
5401     }
5402   }
5403
5404   // Inserted range overlaps, or is adjacent to, ranges at positions
5405   // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
5406   // not affected by the insertion.
5407   // If start_pos == end_pos, the range must be inserted before start_pos.
5408   // if start_pos < end_pos, the entire range from start_pos to end_pos
5409   // must be merged with the insert range.
5410
5411   if (start_pos == end_pos) {
5412     // Insert between existing ranges at position start_pos.
5413     if (start_pos < count) {
5414       MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
5415     }
5416     list->at(start_pos) = insert;
5417     return count + 1;
5418   }
5419   if (start_pos + 1 == end_pos) {
5420     // Replace single existing range at position start_pos.
5421     CharacterRange to_replace = list->at(start_pos);
5422     int new_from = Min(to_replace.from(), from);
5423     int new_to = Max(to_replace.to(), to);
5424     list->at(start_pos) = CharacterRange(new_from, new_to);
5425     return count;
5426   }
5427   // Replace a number of existing ranges from start_pos to end_pos - 1.
5428   // Move the remaining ranges down.
5429
5430   int new_from = Min(list->at(start_pos).from(), from);
5431   int new_to = Max(list->at(end_pos - 1).to(), to);
5432   if (end_pos < count) {
5433     MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
5434   }
5435   list->at(start_pos) = CharacterRange(new_from, new_to);
5436   return count - (end_pos - start_pos) + 1;
5437 }
5438
5439
5440 void CharacterSet::Canonicalize() {
5441   // Special/default classes are always considered canonical. The result
5442   // of calling ranges() will be sorted.
5443   if (ranges_ == NULL) return;
5444   CharacterRange::Canonicalize(ranges_);
5445 }
5446
5447
5448 void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
5449   if (character_ranges->length() <= 1) return;
5450   // Check whether ranges are already canonical (increasing, non-overlapping,
5451   // non-adjacent).
5452   int n = character_ranges->length();
5453   int max = character_ranges->at(0).to();
5454   int i = 1;
5455   while (i < n) {
5456     CharacterRange current = character_ranges->at(i);
5457     if (current.from() <= max + 1) {
5458       break;
5459     }
5460     max = current.to();
5461     i++;
5462   }
5463   // Canonical until the i'th range. If that's all of them, we are done.
5464   if (i == n) return;
5465
5466   // The ranges at index i and forward are not canonicalized. Make them so by
5467   // doing the equivalent of insertion sort (inserting each into the previous
5468   // list, in order).
5469   // Notice that inserting a range can reduce the number of ranges in the
5470   // result due to combining of adjacent and overlapping ranges.
5471   int read = i;  // Range to insert.
5472   int num_canonical = i;  // Length of canonicalized part of list.
5473   do {
5474     num_canonical = InsertRangeInCanonicalList(character_ranges,
5475                                                num_canonical,
5476                                                character_ranges->at(read));
5477     read++;
5478   } while (read < n);
5479   character_ranges->Rewind(num_canonical);
5480
5481   DCHECK(CharacterRange::IsCanonical(character_ranges));
5482 }
5483
5484
5485 void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
5486                             ZoneList<CharacterRange>* negated_ranges,
5487                             Zone* zone) {
5488   DCHECK(CharacterRange::IsCanonical(ranges));
5489   DCHECK_EQ(0, negated_ranges->length());
5490   int range_count = ranges->length();
5491   uc16 from = 0;
5492   int i = 0;
5493   if (range_count > 0 && ranges->at(0).from() == 0) {
5494     from = ranges->at(0).to();
5495     i = 1;
5496   }
5497   while (i < range_count) {
5498     CharacterRange range = ranges->at(i);
5499     negated_ranges->Add(CharacterRange(from + 1, range.from() - 1), zone);
5500     from = range.to();
5501     i++;
5502   }
5503   if (from < String::kMaxUtf16CodeUnit) {
5504     negated_ranges->Add(CharacterRange(from + 1, String::kMaxUtf16CodeUnit),
5505                         zone);
5506   }
5507 }
5508
5509
5510 // -------------------------------------------------------------------
5511 // Splay tree
5512
5513
5514 OutSet* OutSet::Extend(unsigned value, Zone* zone) {
5515   if (Get(value))
5516     return this;
5517   if (successors(zone) != NULL) {
5518     for (int i = 0; i < successors(zone)->length(); i++) {
5519       OutSet* successor = successors(zone)->at(i);
5520       if (successor->Get(value))
5521         return successor;
5522     }
5523   } else {
5524     successors_ = new(zone) ZoneList<OutSet*>(2, zone);
5525   }
5526   OutSet* result = new(zone) OutSet(first_, remaining_);
5527   result->Set(value, zone);
5528   successors(zone)->Add(result, zone);
5529   return result;
5530 }
5531
5532
5533 void OutSet::Set(unsigned value, Zone *zone) {
5534   if (value < kFirstLimit) {
5535     first_ |= (1 << value);
5536   } else {
5537     if (remaining_ == NULL)
5538       remaining_ = new(zone) ZoneList<unsigned>(1, zone);
5539     if (remaining_->is_empty() || !remaining_->Contains(value))
5540       remaining_->Add(value, zone);
5541   }
5542 }
5543
5544
5545 bool OutSet::Get(unsigned value) const {
5546   if (value < kFirstLimit) {
5547     return (first_ & (1 << value)) != 0;
5548   } else if (remaining_ == NULL) {
5549     return false;
5550   } else {
5551     return remaining_->Contains(value);
5552   }
5553 }
5554
5555
5556 const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
5557
5558
5559 void DispatchTable::AddRange(CharacterRange full_range, int value,
5560                              Zone* zone) {
5561   CharacterRange current = full_range;
5562   if (tree()->is_empty()) {
5563     // If this is the first range we just insert into the table.
5564     ZoneSplayTree<Config>::Locator loc;
5565     DCHECK_RESULT(tree()->Insert(current.from(), &loc));
5566     loc.set_value(Entry(current.from(), current.to(),
5567                         empty()->Extend(value, zone)));
5568     return;
5569   }
5570   // First see if there is a range to the left of this one that
5571   // overlaps.
5572   ZoneSplayTree<Config>::Locator loc;
5573   if (tree()->FindGreatestLessThan(current.from(), &loc)) {
5574     Entry* entry = &loc.value();
5575     // If we've found a range that overlaps with this one, and it
5576     // starts strictly to the left of this one, we have to fix it
5577     // because the following code only handles ranges that start on
5578     // or after the start point of the range we're adding.
5579     if (entry->from() < current.from() && entry->to() >= current.from()) {
5580       // Snap the overlapping range in half around the start point of
5581       // the range we're adding.
5582       CharacterRange left(entry->from(), current.from() - 1);
5583       CharacterRange right(current.from(), entry->to());
5584       // The left part of the overlapping range doesn't overlap.
5585       // Truncate the whole entry to be just the left part.
5586       entry->set_to(left.to());
5587       // The right part is the one that overlaps.  We add this part
5588       // to the map and let the next step deal with merging it with
5589       // the range we're adding.
5590       ZoneSplayTree<Config>::Locator loc;
5591       DCHECK_RESULT(tree()->Insert(right.from(), &loc));
5592       loc.set_value(Entry(right.from(),
5593                           right.to(),
5594                           entry->out_set()));
5595     }
5596   }
5597   while (current.is_valid()) {
5598     if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
5599         (loc.value().from() <= current.to()) &&
5600         (loc.value().to() >= current.from())) {
5601       Entry* entry = &loc.value();
5602       // We have overlap.  If there is space between the start point of
5603       // the range we're adding and where the overlapping range starts
5604       // then we have to add a range covering just that space.
5605       if (current.from() < entry->from()) {
5606         ZoneSplayTree<Config>::Locator ins;
5607         DCHECK_RESULT(tree()->Insert(current.from(), &ins));
5608         ins.set_value(Entry(current.from(),
5609                             entry->from() - 1,
5610                             empty()->Extend(value, zone)));
5611         current.set_from(entry->from());
5612       }
5613       DCHECK_EQ(current.from(), entry->from());
5614       // If the overlapping range extends beyond the one we want to add
5615       // we have to snap the right part off and add it separately.
5616       if (entry->to() > current.to()) {
5617         ZoneSplayTree<Config>::Locator ins;
5618         DCHECK_RESULT(tree()->Insert(current.to() + 1, &ins));
5619         ins.set_value(Entry(current.to() + 1,
5620                             entry->to(),
5621                             entry->out_set()));
5622         entry->set_to(current.to());
5623       }
5624       DCHECK(entry->to() <= current.to());
5625       // The overlapping range is now completely contained by the range
5626       // we're adding so we can just update it and move the start point
5627       // of the range we're adding just past it.
5628       entry->AddValue(value, zone);
5629       // Bail out if the last interval ended at 0xFFFF since otherwise
5630       // adding 1 will wrap around to 0.
5631       if (entry->to() == String::kMaxUtf16CodeUnit)
5632         break;
5633       DCHECK(entry->to() + 1 > current.from());
5634       current.set_from(entry->to() + 1);
5635     } else {
5636       // There is no overlap so we can just add the range
5637       ZoneSplayTree<Config>::Locator ins;
5638       DCHECK_RESULT(tree()->Insert(current.from(), &ins));
5639       ins.set_value(Entry(current.from(),
5640                           current.to(),
5641                           empty()->Extend(value, zone)));
5642       break;
5643     }
5644   }
5645 }
5646
5647
5648 OutSet* DispatchTable::Get(uc16 value) {
5649   ZoneSplayTree<Config>::Locator loc;
5650   if (!tree()->FindGreatestLessThan(value, &loc))
5651     return empty();
5652   Entry* entry = &loc.value();
5653   if (value <= entry->to())
5654     return entry->out_set();
5655   else
5656     return empty();
5657 }
5658
5659
5660 // -------------------------------------------------------------------
5661 // Analysis
5662
5663
5664 void Analysis::EnsureAnalyzed(RegExpNode* that) {
5665   StackLimitCheck check(that->zone()->isolate());
5666   if (check.HasOverflowed()) {
5667     fail("Stack overflow");
5668     return;
5669   }
5670   if (that->info()->been_analyzed || that->info()->being_analyzed)
5671     return;
5672   that->info()->being_analyzed = true;
5673   that->Accept(this);
5674   that->info()->being_analyzed = false;
5675   that->info()->been_analyzed = true;
5676 }
5677
5678
5679 void Analysis::VisitEnd(EndNode* that) {
5680   // nothing to do
5681 }
5682
5683
5684 void TextNode::CalculateOffsets() {
5685   int element_count = elements()->length();
5686   // Set up the offsets of the elements relative to the start.  This is a fixed
5687   // quantity since a TextNode can only contain fixed-width things.
5688   int cp_offset = 0;
5689   for (int i = 0; i < element_count; i++) {
5690     TextElement& elm = elements()->at(i);
5691     elm.set_cp_offset(cp_offset);
5692     cp_offset += elm.length();
5693   }
5694 }
5695
5696
5697 void Analysis::VisitText(TextNode* that) {
5698   if (ignore_case_) {
5699     that->MakeCaseIndependent(is_ascii_);
5700   }
5701   EnsureAnalyzed(that->on_success());
5702   if (!has_failed()) {
5703     that->CalculateOffsets();
5704   }
5705 }
5706
5707
5708 void Analysis::VisitAction(ActionNode* that) {
5709   RegExpNode* target = that->on_success();
5710   EnsureAnalyzed(target);
5711   if (!has_failed()) {
5712     // If the next node is interested in what it follows then this node
5713     // has to be interested too so it can pass the information on.
5714     that->info()->AddFromFollowing(target->info());
5715   }
5716 }
5717
5718
5719 void Analysis::VisitChoice(ChoiceNode* that) {
5720   NodeInfo* info = that->info();
5721   for (int i = 0; i < that->alternatives()->length(); i++) {
5722     RegExpNode* node = that->alternatives()->at(i).node();
5723     EnsureAnalyzed(node);
5724     if (has_failed()) return;
5725     // Anything the following nodes need to know has to be known by
5726     // this node also, so it can pass it on.
5727     info->AddFromFollowing(node->info());
5728   }
5729 }
5730
5731
5732 void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
5733   NodeInfo* info = that->info();
5734   for (int i = 0; i < that->alternatives()->length(); i++) {
5735     RegExpNode* node = that->alternatives()->at(i).node();
5736     if (node != that->loop_node()) {
5737       EnsureAnalyzed(node);
5738       if (has_failed()) return;
5739       info->AddFromFollowing(node->info());
5740     }
5741   }
5742   // Check the loop last since it may need the value of this node
5743   // to get a correct result.
5744   EnsureAnalyzed(that->loop_node());
5745   if (!has_failed()) {
5746     info->AddFromFollowing(that->loop_node()->info());
5747   }
5748 }
5749
5750
5751 void Analysis::VisitBackReference(BackReferenceNode* that) {
5752   EnsureAnalyzed(that->on_success());
5753 }
5754
5755
5756 void Analysis::VisitAssertion(AssertionNode* that) {
5757   EnsureAnalyzed(that->on_success());
5758 }
5759
5760
5761 void BackReferenceNode::FillInBMInfo(int offset,
5762                                      int budget,
5763                                      BoyerMooreLookahead* bm,
5764                                      bool not_at_start) {
5765   // Working out the set of characters that a backreference can match is too
5766   // hard, so we just say that any character can match.
5767   bm->SetRest(offset);
5768   SaveBMInfo(bm, not_at_start, offset);
5769 }
5770
5771
5772 STATIC_ASSERT(BoyerMoorePositionInfo::kMapSize ==
5773               RegExpMacroAssembler::kTableSize);
5774
5775
5776 void ChoiceNode::FillInBMInfo(int offset,
5777                               int budget,
5778                               BoyerMooreLookahead* bm,
5779                               bool not_at_start) {
5780   ZoneList<GuardedAlternative>* alts = alternatives();
5781   budget = (budget - 1) / alts->length();
5782   for (int i = 0; i < alts->length(); i++) {
5783     GuardedAlternative& alt = alts->at(i);
5784     if (alt.guards() != NULL && alt.guards()->length() != 0) {
5785       bm->SetRest(offset);  // Give up trying to fill in info.
5786       SaveBMInfo(bm, not_at_start, offset);
5787       return;
5788     }
5789     alt.node()->FillInBMInfo(offset, budget, bm, not_at_start);
5790   }
5791   SaveBMInfo(bm, not_at_start, offset);
5792 }
5793
5794
5795 void TextNode::FillInBMInfo(int initial_offset,
5796                             int budget,
5797                             BoyerMooreLookahead* bm,
5798                             bool not_at_start) {
5799   if (initial_offset >= bm->length()) return;
5800   int offset = initial_offset;
5801   int max_char = bm->max_char();
5802   for (int i = 0; i < elements()->length(); i++) {
5803     if (offset >= bm->length()) {
5804       if (initial_offset == 0) set_bm_info(not_at_start, bm);
5805       return;
5806     }
5807     TextElement text = elements()->at(i);
5808     if (text.text_type() == TextElement::ATOM) {
5809       RegExpAtom* atom = text.atom();
5810       for (int j = 0; j < atom->length(); j++, offset++) {
5811         if (offset >= bm->length()) {
5812           if (initial_offset == 0) set_bm_info(not_at_start, bm);
5813           return;
5814         }
5815         uc16 character = atom->data()[j];
5816         if (bm->compiler()->ignore_case()) {
5817           unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5818           int length = GetCaseIndependentLetters(
5819               Isolate::Current(),
5820               character,
5821               bm->max_char() == String::kMaxOneByteCharCode,
5822               chars);
5823           for (int j = 0; j < length; j++) {
5824             bm->Set(offset, chars[j]);
5825           }
5826         } else {
5827           if (character <= max_char) bm->Set(offset, character);
5828         }
5829       }
5830     } else {
5831       DCHECK_EQ(TextElement::CHAR_CLASS, text.text_type());
5832       RegExpCharacterClass* char_class = text.char_class();
5833       ZoneList<CharacterRange>* ranges = char_class->ranges(zone());
5834       if (char_class->is_negated()) {
5835         bm->SetAll(offset);
5836       } else {
5837         for (int k = 0; k < ranges->length(); k++) {
5838           CharacterRange& range = ranges->at(k);
5839           if (range.from() > max_char) continue;
5840           int to = Min(max_char, static_cast<int>(range.to()));
5841           bm->SetInterval(offset, Interval(range.from(), to));
5842         }
5843       }
5844       offset++;
5845     }
5846   }
5847   if (offset >= bm->length()) {
5848     if (initial_offset == 0) set_bm_info(not_at_start, bm);
5849     return;
5850   }
5851   on_success()->FillInBMInfo(offset,
5852                              budget - 1,
5853                              bm,
5854                              true);  // Not at start after a text node.
5855   if (initial_offset == 0) set_bm_info(not_at_start, bm);
5856 }
5857
5858
5859 // -------------------------------------------------------------------
5860 // Dispatch table construction
5861
5862
5863 void DispatchTableConstructor::VisitEnd(EndNode* that) {
5864   AddRange(CharacterRange::Everything());
5865 }
5866
5867
5868 void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5869   node->set_being_calculated(true);
5870   ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5871   for (int i = 0; i < alternatives->length(); i++) {
5872     set_choice_index(i);
5873     alternatives->at(i).node()->Accept(this);
5874   }
5875   node->set_being_calculated(false);
5876 }
5877
5878
5879 class AddDispatchRange {
5880  public:
5881   explicit AddDispatchRange(DispatchTableConstructor* constructor)
5882     : constructor_(constructor) { }
5883   void Call(uc32 from, DispatchTable::Entry entry);
5884  private:
5885   DispatchTableConstructor* constructor_;
5886 };
5887
5888
5889 void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5890   CharacterRange range(from, entry.to());
5891   constructor_->AddRange(range);
5892 }
5893
5894
5895 void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5896   if (node->being_calculated())
5897     return;
5898   DispatchTable* table = node->GetTable(ignore_case_);
5899   AddDispatchRange adder(this);
5900   table->ForEach(&adder);
5901 }
5902
5903
5904 void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5905   // TODO(160): Find the node that we refer back to and propagate its start
5906   // set back to here.  For now we just accept anything.
5907   AddRange(CharacterRange::Everything());
5908 }
5909
5910
5911 void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5912   RegExpNode* target = that->on_success();
5913   target->Accept(this);
5914 }
5915
5916
5917 static int CompareRangeByFrom(const CharacterRange* a,
5918                               const CharacterRange* b) {
5919   return Compare<uc16>(a->from(), b->from());
5920 }
5921
5922
5923 void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5924   ranges->Sort(CompareRangeByFrom);
5925   uc16 last = 0;
5926   for (int i = 0; i < ranges->length(); i++) {
5927     CharacterRange range = ranges->at(i);
5928     if (last < range.from())
5929       AddRange(CharacterRange(last, range.from() - 1));
5930     if (range.to() >= last) {
5931       if (range.to() == String::kMaxUtf16CodeUnit) {
5932         return;
5933       } else {
5934         last = range.to() + 1;
5935       }
5936     }
5937   }
5938   AddRange(CharacterRange(last, String::kMaxUtf16CodeUnit));
5939 }
5940
5941
5942 void DispatchTableConstructor::VisitText(TextNode* that) {
5943   TextElement elm = that->elements()->at(0);
5944   switch (elm.text_type()) {
5945     case TextElement::ATOM: {
5946       uc16 c = elm.atom()->data()[0];
5947       AddRange(CharacterRange(c, c));
5948       break;
5949     }
5950     case TextElement::CHAR_CLASS: {
5951       RegExpCharacterClass* tree = elm.char_class();
5952       ZoneList<CharacterRange>* ranges = tree->ranges(that->zone());
5953       if (tree->is_negated()) {
5954         AddInverse(ranges);
5955       } else {
5956         for (int i = 0; i < ranges->length(); i++)
5957           AddRange(ranges->at(i));
5958       }
5959       break;
5960     }
5961     default: {
5962       UNIMPLEMENTED();
5963     }
5964   }
5965 }
5966
5967
5968 void DispatchTableConstructor::VisitAction(ActionNode* that) {
5969   RegExpNode* target = that->on_success();
5970   target->Accept(this);
5971 }
5972
5973
5974 RegExpEngine::CompilationResult RegExpEngine::Compile(
5975     RegExpCompileData* data,
5976     bool ignore_case,
5977     bool is_global,
5978     bool is_multiline,
5979     Handle<String> pattern,
5980     Handle<String> sample_subject,
5981     bool is_ascii,
5982     Zone* zone) {
5983   if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
5984     return IrregexpRegExpTooBig(zone->isolate());
5985   }
5986   RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii, zone);
5987
5988   // Sample some characters from the middle of the string.
5989   static const int kSampleSize = 128;
5990
5991   sample_subject = String::Flatten(sample_subject);
5992   int chars_sampled = 0;
5993   int half_way = (sample_subject->length() - kSampleSize) / 2;
5994   for (int i = Max(0, half_way);
5995        i < sample_subject->length() && chars_sampled < kSampleSize;
5996        i++, chars_sampled++) {
5997     compiler.frequency_collator()->CountCharacter(sample_subject->Get(i));
5998   }
5999
6000   // Wrap the body of the regexp in capture #0.
6001   RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
6002                                                     0,
6003                                                     &compiler,
6004                                                     compiler.accept());
6005   RegExpNode* node = captured_body;
6006   bool is_end_anchored = data->tree->IsAnchoredAtEnd();
6007   bool is_start_anchored = data->tree->IsAnchoredAtStart();
6008   int max_length = data->tree->max_match();
6009   if (!is_start_anchored) {
6010     // Add a .*? at the beginning, outside the body capture, unless
6011     // this expression is anchored at the beginning.
6012     RegExpNode* loop_node =
6013         RegExpQuantifier::ToNode(0,
6014                                  RegExpTree::kInfinity,
6015                                  false,
6016                                  new(zone) RegExpCharacterClass('*'),
6017                                  &compiler,
6018                                  captured_body,
6019                                  data->contains_anchor);
6020
6021     if (data->contains_anchor) {
6022       // Unroll loop once, to take care of the case that might start
6023       // at the start of input.
6024       ChoiceNode* first_step_node = new(zone) ChoiceNode(2, zone);
6025       first_step_node->AddAlternative(GuardedAlternative(captured_body));
6026       first_step_node->AddAlternative(GuardedAlternative(
6027           new(zone) TextNode(new(zone) RegExpCharacterClass('*'), loop_node)));
6028       node = first_step_node;
6029     } else {
6030       node = loop_node;
6031     }
6032   }
6033   if (is_ascii) {
6034     node = node->FilterASCII(RegExpCompiler::kMaxRecursion, ignore_case);
6035     // Do it again to propagate the new nodes to places where they were not
6036     // put because they had not been calculated yet.
6037     if (node != NULL) {
6038       node = node->FilterASCII(RegExpCompiler::kMaxRecursion, ignore_case);
6039     }
6040   }
6041
6042   if (node == NULL) node = new(zone) EndNode(EndNode::BACKTRACK, zone);
6043   data->node = node;
6044   Analysis analysis(ignore_case, is_ascii);
6045   analysis.EnsureAnalyzed(node);
6046   if (analysis.has_failed()) {
6047     const char* error_message = analysis.error_message();
6048     return CompilationResult(zone->isolate(), error_message);
6049   }
6050
6051   // Create the correct assembler for the architecture.
6052 #ifndef V8_INTERPRETED_REGEXP
6053   // Native regexp implementation.
6054
6055   NativeRegExpMacroAssembler::Mode mode =
6056       is_ascii ? NativeRegExpMacroAssembler::ASCII
6057                : NativeRegExpMacroAssembler::UC16;
6058
6059 #if V8_TARGET_ARCH_IA32
6060   RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2,
6061                                            zone);
6062 #elif V8_TARGET_ARCH_X64
6063   RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2,
6064                                           zone);
6065 #elif V8_TARGET_ARCH_ARM
6066   RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2,
6067                                           zone);
6068 #elif V8_TARGET_ARCH_ARM64
6069   RegExpMacroAssemblerARM64 macro_assembler(mode, (data->capture_count + 1) * 2,
6070                                             zone);
6071 #elif V8_TARGET_ARCH_MIPS
6072   RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2,
6073                                            zone);
6074 #elif V8_TARGET_ARCH_MIPS64
6075   RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2,
6076                                            zone);
6077 #elif V8_TARGET_ARCH_X87
6078   RegExpMacroAssemblerX87 macro_assembler(mode, (data->capture_count + 1) * 2,
6079                                           zone);
6080 #else
6081 #error "Unsupported architecture"
6082 #endif
6083
6084 #else  // V8_INTERPRETED_REGEXP
6085   // Interpreted regexp implementation.
6086   EmbeddedVector<byte, 1024> codes;
6087   RegExpMacroAssemblerIrregexp macro_assembler(codes, zone);
6088 #endif  // V8_INTERPRETED_REGEXP
6089
6090   // Inserted here, instead of in Assembler, because it depends on information
6091   // in the AST that isn't replicated in the Node structure.
6092   static const int kMaxBacksearchLimit = 1024;
6093   if (is_end_anchored &&
6094       !is_start_anchored &&
6095       max_length < kMaxBacksearchLimit) {
6096     macro_assembler.SetCurrentPositionFromEnd(max_length);
6097   }
6098
6099   if (is_global) {
6100     macro_assembler.set_global_mode(
6101         (data->tree->min_match() > 0)
6102             ? RegExpMacroAssembler::GLOBAL_NO_ZERO_LENGTH_CHECK
6103             : RegExpMacroAssembler::GLOBAL);
6104   }
6105
6106   return compiler.Assemble(&macro_assembler,
6107                            node,
6108                            data->capture_count,
6109                            pattern);
6110 }
6111
6112
6113 }}  // namespace v8::internal