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