Unused variable in YarrJIT.cpp.
[WebKit-https.git] / Source / JavaScriptCore / yarr / YarrJIT.cpp
1 /*
2  * Copyright (C) 2009 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "YarrJIT.h"
28
29 #include "ASCIICType.h"
30 #include "LinkBuffer.h"
31 #include "Yarr.h"
32
33 #if ENABLE(YARR_JIT)
34
35 using namespace WTF;
36
37 namespace JSC { namespace Yarr {
38
39 class YarrGenerator : private MacroAssembler {
40     friend void jitCompile(JSGlobalData*, YarrCodeBlock& jitObject, const UString& pattern, unsigned& numSubpatterns, const char*& error, bool ignoreCase, bool multiline);
41
42 #if CPU(ARM)
43     static const RegisterID input = ARMRegisters::r0;
44     static const RegisterID index = ARMRegisters::r1;
45     static const RegisterID length = ARMRegisters::r2;
46     static const RegisterID output = ARMRegisters::r4;
47
48     static const RegisterID regT0 = ARMRegisters::r5;
49     static const RegisterID regT1 = ARMRegisters::r6;
50
51     static const RegisterID returnRegister = ARMRegisters::r0;
52 #elif CPU(MIPS)
53     static const RegisterID input = MIPSRegisters::a0;
54     static const RegisterID index = MIPSRegisters::a1;
55     static const RegisterID length = MIPSRegisters::a2;
56     static const RegisterID output = MIPSRegisters::a3;
57
58     static const RegisterID regT0 = MIPSRegisters::t4;
59     static const RegisterID regT1 = MIPSRegisters::t5;
60
61     static const RegisterID returnRegister = MIPSRegisters::v0;
62 #elif CPU(SH4)
63     static const RegisterID input = SH4Registers::r4;
64     static const RegisterID index = SH4Registers::r5;
65     static const RegisterID length = SH4Registers::r6;
66     static const RegisterID output = SH4Registers::r7;
67
68     static const RegisterID regT0 = SH4Registers::r0;
69     static const RegisterID regT1 = SH4Registers::r1;
70
71     static const RegisterID returnRegister = SH4Registers::r0;
72 #elif CPU(X86)
73     static const RegisterID input = X86Registers::eax;
74     static const RegisterID index = X86Registers::edx;
75     static const RegisterID length = X86Registers::ecx;
76     static const RegisterID output = X86Registers::edi;
77
78     static const RegisterID regT0 = X86Registers::ebx;
79     static const RegisterID regT1 = X86Registers::esi;
80
81     static const RegisterID returnRegister = X86Registers::eax;
82 #elif CPU(X86_64)
83     static const RegisterID input = X86Registers::edi;
84     static const RegisterID index = X86Registers::esi;
85     static const RegisterID length = X86Registers::edx;
86     static const RegisterID output = X86Registers::ecx;
87
88     static const RegisterID regT0 = X86Registers::eax;
89     static const RegisterID regT1 = X86Registers::ebx;
90
91     static const RegisterID returnRegister = X86Registers::eax;
92 #endif
93
94     void optimizeAlternative(PatternAlternative* alternative)
95     {
96         if (!alternative->m_terms.size())
97             return;
98
99         for (unsigned i = 0; i < alternative->m_terms.size() - 1; ++i) {
100             PatternTerm& term = alternative->m_terms[i];
101             PatternTerm& nextTerm = alternative->m_terms[i + 1];
102
103             if ((term.type == PatternTerm::TypeCharacterClass)
104                 && (term.quantityType == QuantifierFixedCount)
105                 && (nextTerm.type == PatternTerm::TypePatternCharacter)
106                 && (nextTerm.quantityType == QuantifierFixedCount)) {
107                 PatternTerm termCopy = term;
108                 alternative->m_terms[i] = nextTerm;
109                 alternative->m_terms[i + 1] = termCopy;
110             }
111         }
112     }
113
114     void matchCharacterClassRange(RegisterID character, JumpList& failures, JumpList& matchDest, const CharacterRange* ranges, unsigned count, unsigned* matchIndex, const UChar* matches, unsigned matchCount)
115     {
116         do {
117             // pick which range we're going to generate
118             int which = count >> 1;
119             char lo = ranges[which].begin;
120             char hi = ranges[which].end;
121
122             // check if there are any ranges or matches below lo.  If not, just jl to failure -
123             // if there is anything else to check, check that first, if it falls through jmp to failure.
124             if ((*matchIndex < matchCount) && (matches[*matchIndex] < lo)) {
125                 Jump loOrAbove = branch32(GreaterThanOrEqual, character, Imm32((unsigned short)lo));
126
127                 // generate code for all ranges before this one
128                 if (which)
129                     matchCharacterClassRange(character, failures, matchDest, ranges, which, matchIndex, matches, matchCount);
130
131                 while ((*matchIndex < matchCount) && (matches[*matchIndex] < lo)) {
132                     matchDest.append(branch32(Equal, character, Imm32((unsigned short)matches[*matchIndex])));
133                     ++*matchIndex;
134                 }
135                 failures.append(jump());
136
137                 loOrAbove.link(this);
138             } else if (which) {
139                 Jump loOrAbove = branch32(GreaterThanOrEqual, character, Imm32((unsigned short)lo));
140
141                 matchCharacterClassRange(character, failures, matchDest, ranges, which, matchIndex, matches, matchCount);
142                 failures.append(jump());
143
144                 loOrAbove.link(this);
145             } else
146                 failures.append(branch32(LessThan, character, Imm32((unsigned short)lo)));
147
148             while ((*matchIndex < matchCount) && (matches[*matchIndex] <= hi))
149                 ++*matchIndex;
150
151             matchDest.append(branch32(LessThanOrEqual, character, Imm32((unsigned short)hi)));
152             // fall through to here, the value is above hi.
153
154             // shuffle along & loop around if there are any more matches to handle.
155             unsigned next = which + 1;
156             ranges += next;
157             count -= next;
158         } while (count);
159     }
160
161     void matchCharacterClass(RegisterID character, JumpList& matchDest, const CharacterClass* charClass)
162     {
163         if (charClass->m_table) {
164             ExtendedAddress tableEntry(character, reinterpret_cast<intptr_t>(charClass->m_table->m_table));
165             matchDest.append(branchTest8(charClass->m_table->m_inverted ? Zero : NonZero, tableEntry));
166             return;
167         }
168         Jump unicodeFail;
169         if (charClass->m_matchesUnicode.size() || charClass->m_rangesUnicode.size()) {
170             Jump isAscii = branch32(LessThanOrEqual, character, TrustedImm32(0x7f));
171
172             if (charClass->m_matchesUnicode.size()) {
173                 for (unsigned i = 0; i < charClass->m_matchesUnicode.size(); ++i) {
174                     UChar ch = charClass->m_matchesUnicode[i];
175                     matchDest.append(branch32(Equal, character, Imm32(ch)));
176                 }
177             }
178
179             if (charClass->m_rangesUnicode.size()) {
180                 for (unsigned i = 0; i < charClass->m_rangesUnicode.size(); ++i) {
181                     UChar lo = charClass->m_rangesUnicode[i].begin;
182                     UChar hi = charClass->m_rangesUnicode[i].end;
183
184                     Jump below = branch32(LessThan, character, Imm32(lo));
185                     matchDest.append(branch32(LessThanOrEqual, character, Imm32(hi)));
186                     below.link(this);
187                 }
188             }
189
190             unicodeFail = jump();
191             isAscii.link(this);
192         }
193
194         if (charClass->m_ranges.size()) {
195             unsigned matchIndex = 0;
196             JumpList failures;
197             matchCharacterClassRange(character, failures, matchDest, charClass->m_ranges.begin(), charClass->m_ranges.size(), &matchIndex, charClass->m_matches.begin(), charClass->m_matches.size());
198             while (matchIndex < charClass->m_matches.size())
199                 matchDest.append(branch32(Equal, character, Imm32((unsigned short)charClass->m_matches[matchIndex++])));
200
201             failures.link(this);
202         } else if (charClass->m_matches.size()) {
203             // optimization: gather 'a','A' etc back together, can mask & test once.
204             Vector<char> matchesAZaz;
205
206             for (unsigned i = 0; i < charClass->m_matches.size(); ++i) {
207                 char ch = charClass->m_matches[i];
208                 if (m_pattern.m_ignoreCase) {
209                     if (isASCIILower(ch)) {
210                         matchesAZaz.append(ch);
211                         continue;
212                     }
213                     if (isASCIIUpper(ch))
214                         continue;
215                 }
216                 matchDest.append(branch32(Equal, character, Imm32((unsigned short)ch)));
217             }
218
219             if (unsigned countAZaz = matchesAZaz.size()) {
220                 or32(TrustedImm32(32), character);
221                 for (unsigned i = 0; i < countAZaz; ++i)
222                     matchDest.append(branch32(Equal, character, TrustedImm32(matchesAZaz[i])));
223             }
224         }
225
226         if (charClass->m_matchesUnicode.size() || charClass->m_rangesUnicode.size())
227             unicodeFail.link(this);
228     }
229
230     // Jumps if input not available; will have (incorrectly) incremented already!
231     Jump jumpIfNoAvailableInput(unsigned countToCheck = 0)
232     {
233         if (countToCheck)
234             add32(Imm32(countToCheck), index);
235         return branch32(Above, index, length);
236     }
237
238     Jump jumpIfAvailableInput(unsigned countToCheck)
239     {
240         add32(Imm32(countToCheck), index);
241         return branch32(BelowOrEqual, index, length);
242     }
243
244     Jump checkInput()
245     {
246         return branch32(BelowOrEqual, index, length);
247     }
248
249     Jump atEndOfInput()
250     {
251         return branch32(Equal, index, length);
252     }
253
254     Jump notAtEndOfInput()
255     {
256         return branch32(NotEqual, index, length);
257     }
258
259     Jump jumpIfCharNotEquals(UChar ch, int inputPosition, RegisterID character)
260     {
261         readCharacter(inputPosition, character);
262
263         // For case-insesitive compares, non-ascii characters that have different
264         // upper & lower case representations are converted to a character class.
265         ASSERT(!m_pattern.m_ignoreCase || isASCIIAlpha(ch) || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
266         if (m_pattern.m_ignoreCase && isASCIIAlpha(ch)) {
267             or32(TrustedImm32(32), character);
268             ch = Unicode::toLower(ch);
269         }
270
271         return branch32(NotEqual, character, Imm32(ch));
272     }
273
274     void readCharacter(int inputPosition, RegisterID reg)
275     {
276         if (m_charSize == Char8)
277             load8(BaseIndex(input, index, TimesOne, inputPosition * sizeof(char)), reg);
278         else
279             load16(BaseIndex(input, index, TimesTwo, inputPosition * sizeof(UChar)), reg);
280     }
281
282     void storeToFrame(RegisterID reg, unsigned frameLocation)
283     {
284         poke(reg, frameLocation);
285     }
286
287     void storeToFrame(TrustedImm32 imm, unsigned frameLocation)
288     {
289         poke(imm, frameLocation);
290     }
291
292     DataLabelPtr storeToFrameWithPatch(unsigned frameLocation)
293     {
294         return storePtrWithPatch(TrustedImmPtr(0), Address(stackPointerRegister, frameLocation * sizeof(void*)));
295     }
296
297     void loadFromFrame(unsigned frameLocation, RegisterID reg)
298     {
299         peek(reg, frameLocation);
300     }
301
302     void loadFromFrameAndJump(unsigned frameLocation)
303     {
304         jump(Address(stackPointerRegister, frameLocation * sizeof(void*)));
305     }
306
307     enum YarrOpCode {
308         // These nodes wrap body alternatives - those in the main disjunction,
309         // rather than subpatterns or assertions. These are chained together in
310         // a doubly linked list, with a 'begin' node for the first alternative,
311         // a 'next' node for each subsequent alternative, and an 'end' node at
312         // the end. In the case of repeating alternatives, the 'end' node also
313         // has a reference back to 'begin'.
314         OpBodyAlternativeBegin,
315         OpBodyAlternativeNext,
316         OpBodyAlternativeEnd,
317         // Similar to the body alternatives, but used for subpatterns with two
318         // or more alternatives.
319         OpNestedAlternativeBegin,
320         OpNestedAlternativeNext,
321         OpNestedAlternativeEnd,
322         // Used for alternatives in subpatterns where there is only a single
323         // alternative (backtrackingis easier in these cases), or for alternatives
324         // which never need to be backtracked (those in parenthetical assertions,
325         // terminal subpatterns).
326         OpSimpleNestedAlternativeBegin,
327         OpSimpleNestedAlternativeNext,
328         OpSimpleNestedAlternativeEnd,
329         // Used to wrap 'Once' subpattern matches (quantityCount == 1).
330         OpParenthesesSubpatternOnceBegin,
331         OpParenthesesSubpatternOnceEnd,
332         // Used to wrap 'Terminal' subpattern matches (at the end of the regexp).
333         OpParenthesesSubpatternTerminalBegin,
334         OpParenthesesSubpatternTerminalEnd,
335         // Used to wrap parenthetical assertions.
336         OpParentheticalAssertionBegin,
337         OpParentheticalAssertionEnd,
338         // Wraps all simple terms (pattern characters, character classes).
339         OpTerm,
340         // Where an expression contains only 'once through' body alternatives
341         // and no repeating ones, this op is used to return match failure.
342         OpMatchFailed
343     };
344
345     // This structure is used to hold the compiled opcode information,
346     // including reference back to the original PatternTerm/PatternAlternatives,
347     // and JIT compilation data structures.
348     struct YarrOp {
349         explicit YarrOp(PatternTerm* term)
350             : m_op(OpTerm)
351             , m_term(term)
352             , m_isDeadCode(false)
353         {
354         }
355
356         explicit YarrOp(YarrOpCode op)
357             : m_op(op)
358             , m_isDeadCode(false)
359         {
360         }
361
362         // The operation, as a YarrOpCode, and also a reference to the PatternTerm.
363         YarrOpCode m_op;
364         PatternTerm* m_term;
365
366         // For alternatives, this holds the PatternAlternative and doubly linked
367         // references to this alternative's siblings. In the case of the
368         // OpBodyAlternativeEnd node at the end of a section of repeating nodes,
369         // m_nextOp will reference the OpBodyAlternativeBegin node of the first
370         // repeating alternative.
371         PatternAlternative* m_alternative;
372         size_t m_previousOp;
373         size_t m_nextOp;
374
375         // Used to record a set of Jumps out of the generated code, typically
376         // used for jumps out to backtracking code, and a single reentry back
377         // into the code for a node (likely where a backtrack will trigger
378         // rematching).
379         Label m_reentry;
380         JumpList m_jumps;
381
382         // This flag is used to null out the second pattern character, when
383         // two are fused to match a pair together.
384         bool m_isDeadCode;
385
386         // Currently used in the case of some of the more complex management of
387         // 'm_checked', to cache the offset used in this alternative, to avoid
388         // recalculating it.
389         int m_checkAdjust;
390
391         // Used by OpNestedAlternativeNext/End to hold the pointer to the
392         // value that will be pushed into the pattern's frame to return to,
393         // upon backtracking back into the disjunction.
394         DataLabelPtr m_returnAddress;
395     };
396
397     // BacktrackingState
398     // This class encapsulates information about the state of code generation
399     // whilst generating the code for backtracking, when a term fails to match.
400     // Upon entry to code generation of the backtracking code for a given node,
401     // the Backtracking state will hold references to all control flow sources
402     // that are outputs in need of further backtracking from the prior node
403     // generated (which is the subsequent operation in the regular expression,
404     // and in the m_ops Vector, since we generated backtracking backwards).
405     // These references to control flow take the form of:
406     //  - A jump list of jumps, to be linked to code that will backtrack them
407     //    further.
408     //  - A set of DataLabelPtr values, to be populated with values to be
409     //    treated effectively as return addresses backtracking into complex
410     //    subpatterns.
411     //  - A flag indicating that the current sequence of generated code up to
412     //    this point requires backtracking.
413     class BacktrackingState {
414     public:
415         BacktrackingState()
416             : m_pendingFallthrough(false)
417         {
418         }
419
420         // Add a jump or jumps, a return address, or set the flag indicating
421         // that the current 'fallthrough' control flow requires backtracking.
422         void append(const Jump& jump)
423         {
424             m_laterFailures.append(jump);
425         }
426         void append(JumpList& jumpList)
427         {
428             m_laterFailures.append(jumpList);
429         }
430         void append(const DataLabelPtr& returnAddress)
431         {
432             m_pendingReturns.append(returnAddress);
433         }
434         void fallthrough()
435         {
436             ASSERT(!m_pendingFallthrough);
437             m_pendingFallthrough = true;
438         }
439
440         // These methods clear the backtracking state, either linking to the
441         // current location, a provided label, or copying the backtracking out
442         // to a JumpList. All actions may require code generation to take place,
443         // and as such are passed a pointer to the assembler.
444         void link(MacroAssembler* assembler)
445         {
446             if (m_pendingReturns.size()) {
447                 Label here(assembler);
448                 for (unsigned i = 0; i < m_pendingReturns.size(); ++i)
449                     m_backtrackRecords.append(ReturnAddressRecord(m_pendingReturns[i], here));
450                 m_pendingReturns.clear();
451             }
452             m_laterFailures.link(assembler);
453             m_laterFailures.clear();
454             m_pendingFallthrough = false;
455         }
456         void linkTo(Label label, MacroAssembler* assembler)
457         {
458             if (m_pendingReturns.size()) {
459                 for (unsigned i = 0; i < m_pendingReturns.size(); ++i)
460                     m_backtrackRecords.append(ReturnAddressRecord(m_pendingReturns[i], label));
461                 m_pendingReturns.clear();
462             }
463             if (m_pendingFallthrough)
464                 assembler->jump(label);
465             m_laterFailures.linkTo(label, assembler);
466             m_laterFailures.clear();
467             m_pendingFallthrough = false;
468         }
469         void takeBacktracksToJumpList(JumpList& jumpList, MacroAssembler* assembler)
470         {
471             if (m_pendingReturns.size()) {
472                 Label here(assembler);
473                 for (unsigned i = 0; i < m_pendingReturns.size(); ++i)
474                     m_backtrackRecords.append(ReturnAddressRecord(m_pendingReturns[i], here));
475                 m_pendingReturns.clear();
476                 m_pendingFallthrough = true;
477             }
478             if (m_pendingFallthrough)
479                 jumpList.append(assembler->jump());
480             jumpList.append(m_laterFailures);
481             m_laterFailures.clear();
482             m_pendingFallthrough = false;
483         }
484
485         bool isEmpty()
486         {
487             return m_laterFailures.empty() && m_pendingReturns.isEmpty() && !m_pendingFallthrough;
488         }
489
490         // Called at the end of code generation to link all return addresses.
491         void linkDataLabels(LinkBuffer& linkBuffer)
492         {
493             ASSERT(isEmpty());
494             for (unsigned i = 0; i < m_backtrackRecords.size(); ++i)
495                 linkBuffer.patch(m_backtrackRecords[i].m_dataLabel, linkBuffer.locationOf(m_backtrackRecords[i].m_backtrackLocation));
496         }
497
498     private:
499         struct ReturnAddressRecord {
500             ReturnAddressRecord(DataLabelPtr dataLabel, Label backtrackLocation)
501                 : m_dataLabel(dataLabel)
502                 , m_backtrackLocation(backtrackLocation)
503             {
504             }
505
506             DataLabelPtr m_dataLabel;
507             Label m_backtrackLocation;
508         };
509
510         JumpList m_laterFailures;
511         bool m_pendingFallthrough;
512         Vector<DataLabelPtr, 4> m_pendingReturns;
513         Vector<ReturnAddressRecord, 4> m_backtrackRecords;
514     };
515
516     // Generation methods:
517     // ===================
518
519     // This method provides a default implementation of backtracking common
520     // to many terms; terms commonly jump out of the forwards  matching path
521     // on any failed conditions, and add these jumps to the m_jumps list. If
522     // no special handling is required we can often just backtrack to m_jumps.
523     void backtrackTermDefault(size_t opIndex)
524     {
525         YarrOp& op = m_ops[opIndex];
526         m_backtrackingState.append(op.m_jumps);
527     }
528
529     void generateAssertionBOL(size_t opIndex)
530     {
531         YarrOp& op = m_ops[opIndex];
532         PatternTerm* term = op.m_term;
533
534         if (m_pattern.m_multiline) {
535             const RegisterID character = regT0;
536
537             JumpList matchDest;
538             if (!term->inputPosition)
539                 matchDest.append(branch32(Equal, index, Imm32(m_checked)));
540
541             readCharacter((term->inputPosition - m_checked) - 1, character);
542             matchCharacterClass(character, matchDest, m_pattern.newlineCharacterClass());
543             op.m_jumps.append(jump());
544
545             matchDest.link(this);
546         } else {
547             // Erk, really should poison out these alternatives early. :-/
548             if (term->inputPosition)
549                 op.m_jumps.append(jump());
550             else
551                 op.m_jumps.append(branch32(NotEqual, index, Imm32(m_checked)));
552         }
553     }
554     void backtrackAssertionBOL(size_t opIndex)
555     {
556         backtrackTermDefault(opIndex);
557     }
558
559     void generateAssertionEOL(size_t opIndex)
560     {
561         YarrOp& op = m_ops[opIndex];
562         PatternTerm* term = op.m_term;
563
564         if (m_pattern.m_multiline) {
565             const RegisterID character = regT0;
566
567             JumpList matchDest;
568             if (term->inputPosition == m_checked)
569                 matchDest.append(atEndOfInput());
570
571             readCharacter(term->inputPosition - m_checked, character);
572             matchCharacterClass(character, matchDest, m_pattern.newlineCharacterClass());
573             op.m_jumps.append(jump());
574
575             matchDest.link(this);
576         } else {
577             if (term->inputPosition == m_checked)
578                 op.m_jumps.append(notAtEndOfInput());
579             // Erk, really should poison out these alternatives early. :-/
580             else
581                 op.m_jumps.append(jump());
582         }
583     }
584     void backtrackAssertionEOL(size_t opIndex)
585     {
586         backtrackTermDefault(opIndex);
587     }
588
589     // Also falls though on nextIsNotWordChar.
590     void matchAssertionWordchar(size_t opIndex, JumpList& nextIsWordChar, JumpList& nextIsNotWordChar)
591     {
592         YarrOp& op = m_ops[opIndex];
593         PatternTerm* term = op.m_term;
594
595         const RegisterID character = regT0;
596
597         if (term->inputPosition == m_checked)
598             nextIsNotWordChar.append(atEndOfInput());
599
600         readCharacter((term->inputPosition - m_checked), character);
601         matchCharacterClass(character, nextIsWordChar, m_pattern.wordcharCharacterClass());
602     }
603
604     void generateAssertionWordBoundary(size_t opIndex)
605     {
606         YarrOp& op = m_ops[opIndex];
607         PatternTerm* term = op.m_term;
608
609         const RegisterID character = regT0;
610
611         Jump atBegin;
612         JumpList matchDest;
613         if (!term->inputPosition)
614             atBegin = branch32(Equal, index, Imm32(m_checked));
615         readCharacter((term->inputPosition - m_checked) - 1, character);
616         matchCharacterClass(character, matchDest, m_pattern.wordcharCharacterClass());
617         if (!term->inputPosition)
618             atBegin.link(this);
619
620         // We fall through to here if the last character was not a wordchar.
621         JumpList nonWordCharThenWordChar;
622         JumpList nonWordCharThenNonWordChar;
623         if (term->invert()) {
624             matchAssertionWordchar(opIndex, nonWordCharThenNonWordChar, nonWordCharThenWordChar);
625             nonWordCharThenWordChar.append(jump());
626         } else {
627             matchAssertionWordchar(opIndex, nonWordCharThenWordChar, nonWordCharThenNonWordChar);
628             nonWordCharThenNonWordChar.append(jump());
629         }
630         op.m_jumps.append(nonWordCharThenNonWordChar);
631
632         // We jump here if the last character was a wordchar.
633         matchDest.link(this);
634         JumpList wordCharThenWordChar;
635         JumpList wordCharThenNonWordChar;
636         if (term->invert()) {
637             matchAssertionWordchar(opIndex, wordCharThenNonWordChar, wordCharThenWordChar);
638             wordCharThenWordChar.append(jump());
639         } else {
640             matchAssertionWordchar(opIndex, wordCharThenWordChar, wordCharThenNonWordChar);
641             // This can fall-though!
642         }
643
644         op.m_jumps.append(wordCharThenWordChar);
645
646         nonWordCharThenWordChar.link(this);
647         wordCharThenNonWordChar.link(this);
648     }
649     void backtrackAssertionWordBoundary(size_t opIndex)
650     {
651         backtrackTermDefault(opIndex);
652     }
653
654     void generatePatternCharacterOnce(size_t opIndex)
655     {
656         YarrOp& op = m_ops[opIndex];
657
658         if (op.m_isDeadCode)
659             return;
660         
661         // m_ops always ends with a OpBodyAlternativeEnd or OpMatchFailed
662         // node, so there must always be at least one more node.
663         ASSERT(opIndex + 1 < m_ops.size());
664         YarrOp* nextOp = &m_ops[opIndex + 1];
665
666         PatternTerm* term = op.m_term;
667         UChar ch = term->patternCharacter;
668
669         if ((ch > 0xff) && (m_charSize == Char8)) {
670             // Have a 16 bit pattern character and an 8 bit string - short circuit
671             op.m_jumps.append(jump());
672             return;
673         }
674
675         const RegisterID character = regT0;
676         int maxCharactersAtOnce = m_charSize == Char8 ? 4 : 2;
677         unsigned ignoreCaseMask = 0;
678         int allCharacters = ch;
679         int numberCharacters;
680         int startTermPosition = term->inputPosition;
681
682         // For case-insesitive compares, non-ascii characters that have different
683         // upper & lower case representations are converted to a character class.
684         ASSERT(!m_pattern.m_ignoreCase || isASCIIAlpha(ch) || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
685
686         if ((m_pattern.m_ignoreCase) && (isASCIIAlpha(ch)))
687             ignoreCaseMask |= 32;
688
689         for (numberCharacters = 1; numberCharacters < maxCharactersAtOnce && nextOp->m_op == OpTerm; ++numberCharacters, nextOp = &m_ops[opIndex + numberCharacters]) {
690             PatternTerm* nextTerm = nextOp->m_term;
691             
692             if (nextTerm->type != PatternTerm::TypePatternCharacter
693                 || nextTerm->quantityType != QuantifierFixedCount
694                 || nextTerm->quantityCount != 1
695                 || nextTerm->inputPosition != (startTermPosition + numberCharacters))
696                 break;
697
698             nextOp->m_isDeadCode = true;
699
700             int shiftAmount = (m_charSize == Char8 ? 8 : 16) * numberCharacters;
701
702             UChar currentCharacter = nextTerm->patternCharacter;
703
704             if ((currentCharacter > 0xff) && (m_charSize == Char8)) {
705                 // Have a 16 bit pattern character and an 8 bit string - short circuit
706                 op.m_jumps.append(jump());
707                 return;
708             }
709
710             // For case-insesitive compares, non-ascii characters that have different
711             // upper & lower case representations are converted to a character class.
712             ASSERT(!m_pattern.m_ignoreCase || isASCIIAlpha(currentCharacter) || (Unicode::toLower(currentCharacter) == Unicode::toUpper(currentCharacter)));
713
714             allCharacters |= (currentCharacter << shiftAmount);
715
716             if ((m_pattern.m_ignoreCase) && (isASCIIAlpha(currentCharacter)))
717                 ignoreCaseMask |= 32 << shiftAmount;                    
718         }
719
720         if (m_charSize == Char8) {
721             switch (numberCharacters) {
722             case 1:
723                 op.m_jumps.append(jumpIfCharNotEquals(ch, startTermPosition - m_checked, character));
724                 return;
725             case 2: {
726                 BaseIndex address(input, index, TimesOne, (startTermPosition - m_checked) * sizeof(LChar));
727                 load16(address, character);
728                 break;
729             }
730             case 3: {
731                 BaseIndex address(input, index, TimesOne, (startTermPosition - m_checked) * sizeof(LChar));
732                 load32WithUnalignedHalfWords(address, character);
733                 and32(Imm32(0xffffff), character);
734                 break;
735             }
736             case 4: {
737                 BaseIndex address(input, index, TimesOne, (startTermPosition - m_checked) * sizeof(LChar));
738                 load32WithUnalignedHalfWords(address, character);
739                 break;
740             }
741             }
742         } else {
743             switch (numberCharacters) {
744             case 1:
745                 op.m_jumps.append(jumpIfCharNotEquals(ch, term->inputPosition - m_checked, character));
746                 return;
747             case 2:
748                 BaseIndex address(input, index, TimesTwo, (term->inputPosition - m_checked) * sizeof(UChar));
749                 load32WithUnalignedHalfWords(address, character);
750                 break;
751             }
752         }
753
754         if (ignoreCaseMask)
755             or32(Imm32(ignoreCaseMask), character);
756         op.m_jumps.append(branch32(NotEqual, character, Imm32(allCharacters | ignoreCaseMask)));
757         return;
758     }
759     void backtrackPatternCharacterOnce(size_t opIndex)
760     {
761         backtrackTermDefault(opIndex);
762     }
763
764     void generatePatternCharacterFixed(size_t opIndex)
765     {
766         YarrOp& op = m_ops[opIndex];
767         PatternTerm* term = op.m_term;
768         UChar ch = term->patternCharacter;
769
770         const RegisterID character = regT0;
771         const RegisterID countRegister = regT1;
772
773         move(index, countRegister);
774         sub32(Imm32(term->quantityCount.unsafeGet()), countRegister);
775
776         Label loop(this);
777         BaseIndex address(input, countRegister, m_charScale, (Checked<int>(term->inputPosition - m_checked + Checked<int64_t>(term->quantityCount)) * static_cast<int>(m_charSize == Char8 ? sizeof(char) : sizeof(UChar))).unsafeGet());
778
779         if (m_charSize == Char8)
780             load8(address, character);
781         else
782             load16(address, character);
783
784         // For case-insesitive compares, non-ascii characters that have different
785         // upper & lower case representations are converted to a character class.
786         ASSERT(!m_pattern.m_ignoreCase || isASCIIAlpha(ch) || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
787         if (m_pattern.m_ignoreCase && isASCIIAlpha(ch)) {
788             or32(TrustedImm32(32), character);
789             ch = Unicode::toLower(ch);
790         }
791
792         op.m_jumps.append(branch32(NotEqual, character, Imm32(ch)));
793         add32(TrustedImm32(1), countRegister);
794         branch32(NotEqual, countRegister, index).linkTo(loop, this);
795     }
796     void backtrackPatternCharacterFixed(size_t opIndex)
797     {
798         backtrackTermDefault(opIndex);
799     }
800
801     void generatePatternCharacterGreedy(size_t opIndex)
802     {
803         YarrOp& op = m_ops[opIndex];
804         PatternTerm* term = op.m_term;
805         UChar ch = term->patternCharacter;
806
807         const RegisterID character = regT0;
808         const RegisterID countRegister = regT1;
809
810         move(TrustedImm32(0), countRegister);
811
812         if ((ch > 0xff) && (m_charSize == Char8)) {
813             // Have a 16 bit pattern character and an 8 bit string - short circuit
814             op.m_jumps.append(jump());
815         } else {
816             JumpList failures;
817             Label loop(this);
818             failures.append(atEndOfInput());
819             failures.append(jumpIfCharNotEquals(ch, term->inputPosition - m_checked, character));
820
821             add32(TrustedImm32(1), countRegister);
822             add32(TrustedImm32(1), index);
823             if (term->quantityCount == quantifyInfinite)
824                 jump(loop);
825             else
826                 branch32(NotEqual, countRegister, Imm32(term->quantityCount.unsafeGet())).linkTo(loop, this);
827
828             failures.link(this);
829         }
830         op.m_reentry = label();
831
832         storeToFrame(countRegister, term->frameLocation);
833
834     }
835     void backtrackPatternCharacterGreedy(size_t opIndex)
836     {
837         YarrOp& op = m_ops[opIndex];
838         PatternTerm* term = op.m_term;
839
840         const RegisterID countRegister = regT1;
841
842         m_backtrackingState.link(this);
843
844         loadFromFrame(term->frameLocation, countRegister);
845         m_backtrackingState.append(branchTest32(Zero, countRegister));
846         sub32(TrustedImm32(1), countRegister);
847         sub32(TrustedImm32(1), index);
848         jump(op.m_reentry);
849     }
850
851     void generatePatternCharacterNonGreedy(size_t opIndex)
852     {
853         YarrOp& op = m_ops[opIndex];
854         PatternTerm* term = op.m_term;
855
856         const RegisterID countRegister = regT1;
857
858         move(TrustedImm32(0), countRegister);
859         op.m_reentry = label();
860         storeToFrame(countRegister, term->frameLocation);
861     }
862     void backtrackPatternCharacterNonGreedy(size_t opIndex)
863     {
864         YarrOp& op = m_ops[opIndex];
865         PatternTerm* term = op.m_term;
866         UChar ch = term->patternCharacter;
867
868         const RegisterID character = regT0;
869         const RegisterID countRegister = regT1;
870
871         JumpList nonGreedyFailures;
872
873         m_backtrackingState.link(this);
874
875         loadFromFrame(term->frameLocation, countRegister);
876
877         if ((ch > 0xff) && (m_charSize == Char8)) {
878             // Have a 16 bit pattern character and an 8 bit string - short circuit
879             nonGreedyFailures.append(jump());
880         } else {
881             nonGreedyFailures.append(atEndOfInput());
882             if (term->quantityCount != quantifyInfinite)
883                 nonGreedyFailures.append(branch32(Equal, countRegister, Imm32(term->quantityCount.unsafeGet())));
884             nonGreedyFailures.append(jumpIfCharNotEquals(ch, term->inputPosition - m_checked, character));
885
886             add32(TrustedImm32(1), countRegister);
887             add32(TrustedImm32(1), index);
888
889             jump(op.m_reentry);
890         }
891         nonGreedyFailures.link(this);
892
893         sub32(countRegister, index);
894         m_backtrackingState.fallthrough();
895     }
896
897     void generateCharacterClassOnce(size_t opIndex)
898     {
899         YarrOp& op = m_ops[opIndex];
900         PatternTerm* term = op.m_term;
901
902         const RegisterID character = regT0;
903
904         JumpList matchDest;
905         readCharacter(term->inputPosition - m_checked, character);
906         matchCharacterClass(character, matchDest, term->characterClass);
907
908         if (term->invert())
909             op.m_jumps.append(matchDest);
910         else {
911             op.m_jumps.append(jump());
912             matchDest.link(this);
913         }
914     }
915     void backtrackCharacterClassOnce(size_t opIndex)
916     {
917         backtrackTermDefault(opIndex);
918     }
919
920     void generateCharacterClassFixed(size_t opIndex)
921     {
922         YarrOp& op = m_ops[opIndex];
923         PatternTerm* term = op.m_term;
924
925         const RegisterID character = regT0;
926         const RegisterID countRegister = regT1;
927
928         move(index, countRegister);
929         sub32(Imm32(term->quantityCount.unsafeGet()), countRegister);
930
931         Label loop(this);
932         JumpList matchDest;
933         if (m_charSize == Char8)
934             load8(BaseIndex(input, countRegister, TimesOne, (Checked<int>(term->inputPosition - m_checked + Checked<int64_t>(term->quantityCount)) * static_cast<int>(sizeof(char))).unsafeGet()), character);
935         else
936             load16(BaseIndex(input, countRegister, TimesTwo, (Checked<int>(term->inputPosition - m_checked + Checked<int64_t>(term->quantityCount)) * static_cast<int>(sizeof(UChar))).unsafeGet()), character);
937         matchCharacterClass(character, matchDest, term->characterClass);
938
939         if (term->invert())
940             op.m_jumps.append(matchDest);
941         else {
942             op.m_jumps.append(jump());
943             matchDest.link(this);
944         }
945
946         add32(TrustedImm32(1), countRegister);
947         branch32(NotEqual, countRegister, index).linkTo(loop, this);
948     }
949     void backtrackCharacterClassFixed(size_t opIndex)
950     {
951         backtrackTermDefault(opIndex);
952     }
953
954     void generateCharacterClassGreedy(size_t opIndex)
955     {
956         YarrOp& op = m_ops[opIndex];
957         PatternTerm* term = op.m_term;
958
959         const RegisterID character = regT0;
960         const RegisterID countRegister = regT1;
961
962         move(TrustedImm32(0), countRegister);
963
964         JumpList failures;
965         Label loop(this);
966         failures.append(atEndOfInput());
967
968         if (term->invert()) {
969             readCharacter(term->inputPosition - m_checked, character);
970             matchCharacterClass(character, failures, term->characterClass);
971         } else {
972             JumpList matchDest;
973             readCharacter(term->inputPosition - m_checked, character);
974             matchCharacterClass(character, matchDest, term->characterClass);
975             failures.append(jump());
976             matchDest.link(this);
977         }
978
979         add32(TrustedImm32(1), countRegister);
980         add32(TrustedImm32(1), index);
981         if (term->quantityCount != quantifyInfinite) {
982             branch32(NotEqual, countRegister, Imm32(term->quantityCount.unsafeGet())).linkTo(loop, this);
983             failures.append(jump());
984         } else
985             jump(loop);
986
987         failures.link(this);
988         op.m_reentry = label();
989
990         storeToFrame(countRegister, term->frameLocation);
991     }
992     void backtrackCharacterClassGreedy(size_t opIndex)
993     {
994         YarrOp& op = m_ops[opIndex];
995         PatternTerm* term = op.m_term;
996
997         const RegisterID countRegister = regT1;
998
999         m_backtrackingState.link(this);
1000
1001         loadFromFrame(term->frameLocation, countRegister);
1002         m_backtrackingState.append(branchTest32(Zero, countRegister));
1003         sub32(TrustedImm32(1), countRegister);
1004         sub32(TrustedImm32(1), index);
1005         jump(op.m_reentry);
1006     }
1007
1008     void generateCharacterClassNonGreedy(size_t opIndex)
1009     {
1010         YarrOp& op = m_ops[opIndex];
1011         PatternTerm* term = op.m_term;
1012
1013         const RegisterID countRegister = regT1;
1014
1015         move(TrustedImm32(0), countRegister);
1016         op.m_reentry = label();
1017         storeToFrame(countRegister, term->frameLocation);
1018     }
1019     void backtrackCharacterClassNonGreedy(size_t opIndex)
1020     {
1021         YarrOp& op = m_ops[opIndex];
1022         PatternTerm* term = op.m_term;
1023
1024         const RegisterID character = regT0;
1025         const RegisterID countRegister = regT1;
1026
1027         JumpList nonGreedyFailures;
1028
1029         m_backtrackingState.link(this);
1030
1031         Label backtrackBegin(this);
1032         loadFromFrame(term->frameLocation, countRegister);
1033
1034         nonGreedyFailures.append(atEndOfInput());
1035         nonGreedyFailures.append(branch32(Equal, countRegister, Imm32(term->quantityCount.unsafeGet())));
1036
1037         JumpList matchDest;
1038         readCharacter(term->inputPosition - m_checked, character);
1039         matchCharacterClass(character, matchDest, term->characterClass);
1040
1041         if (term->invert())
1042             nonGreedyFailures.append(matchDest);
1043         else {
1044             nonGreedyFailures.append(jump());
1045             matchDest.link(this);
1046         }
1047
1048         add32(TrustedImm32(1), countRegister);
1049         add32(TrustedImm32(1), index);
1050
1051         jump(op.m_reentry);
1052
1053         nonGreedyFailures.link(this);
1054         sub32(countRegister, index);
1055         m_backtrackingState.fallthrough();
1056     }
1057
1058     void generateDotStarEnclosure(size_t opIndex)
1059     {
1060         YarrOp& op = m_ops[opIndex];
1061         PatternTerm* term = op.m_term;
1062
1063         const RegisterID character = regT0;
1064         const RegisterID matchPos = regT1;
1065
1066         JumpList foundBeginningNewLine;
1067         JumpList saveStartIndex;
1068         JumpList foundEndingNewLine;
1069
1070         if (m_pattern.m_body->m_hasFixedSize) {
1071             move(index, matchPos);
1072             sub32(Imm32(m_checked), matchPos);
1073         } else
1074             load32(Address(output), matchPos);
1075
1076         saveStartIndex.append(branchTest32(Zero, matchPos));
1077         Label findBOLLoop(this);
1078         sub32(TrustedImm32(1), matchPos);
1079         if (m_charSize == Char8)
1080             load8(BaseIndex(input, matchPos, TimesOne, 0), character);
1081         else
1082             load16(BaseIndex(input, matchPos, TimesTwo, 0), character);
1083         matchCharacterClass(character, foundBeginningNewLine, m_pattern.newlineCharacterClass());
1084         branchTest32(NonZero, matchPos).linkTo(findBOLLoop, this);
1085         saveStartIndex.append(jump());
1086
1087         foundBeginningNewLine.link(this);
1088         add32(TrustedImm32(1), matchPos); // Advance past newline
1089         saveStartIndex.link(this);
1090
1091         if (!m_pattern.m_multiline && term->anchors.bolAnchor)
1092             op.m_jumps.append(branchTest32(NonZero, matchPos));
1093
1094         store32(matchPos, Address(output));
1095
1096         move(index, matchPos);
1097
1098         Label findEOLLoop(this);        
1099         foundEndingNewLine.append(branch32(Equal, matchPos, length));
1100         if (m_charSize == Char8)
1101             load8(BaseIndex(input, matchPos, TimesOne, 0), character);
1102         else
1103             load16(BaseIndex(input, matchPos, TimesTwo, 0), character);
1104         matchCharacterClass(character, foundEndingNewLine, m_pattern.newlineCharacterClass());
1105         add32(TrustedImm32(1), matchPos);
1106         jump(findEOLLoop);
1107
1108         foundEndingNewLine.link(this);
1109
1110         if (!m_pattern.m_multiline && term->anchors.eolAnchor)
1111             op.m_jumps.append(branch32(NotEqual, matchPos, length));
1112
1113         move(matchPos, index);
1114     }
1115
1116     void backtrackDotStarEnclosure(size_t opIndex)
1117     {
1118         backtrackTermDefault(opIndex);
1119     }
1120     
1121     // Code generation/backtracking for simple terms
1122     // (pattern characters, character classes, and assertions).
1123     // These methods farm out work to the set of functions above.
1124     void generateTerm(size_t opIndex)
1125     {
1126         YarrOp& op = m_ops[opIndex];
1127         PatternTerm* term = op.m_term;
1128
1129         switch (term->type) {
1130         case PatternTerm::TypePatternCharacter:
1131             switch (term->quantityType) {
1132             case QuantifierFixedCount:
1133                 if (term->quantityCount == 1)
1134                     generatePatternCharacterOnce(opIndex);
1135                 else
1136                     generatePatternCharacterFixed(opIndex);
1137                 break;
1138             case QuantifierGreedy:
1139                 generatePatternCharacterGreedy(opIndex);
1140                 break;
1141             case QuantifierNonGreedy:
1142                 generatePatternCharacterNonGreedy(opIndex);
1143                 break;
1144             }
1145             break;
1146
1147         case PatternTerm::TypeCharacterClass:
1148             switch (term->quantityType) {
1149             case QuantifierFixedCount:
1150                 if (term->quantityCount == 1)
1151                     generateCharacterClassOnce(opIndex);
1152                 else
1153                     generateCharacterClassFixed(opIndex);
1154                 break;
1155             case QuantifierGreedy:
1156                 generateCharacterClassGreedy(opIndex);
1157                 break;
1158             case QuantifierNonGreedy:
1159                 generateCharacterClassNonGreedy(opIndex);
1160                 break;
1161             }
1162             break;
1163
1164         case PatternTerm::TypeAssertionBOL:
1165             generateAssertionBOL(opIndex);
1166             break;
1167
1168         case PatternTerm::TypeAssertionEOL:
1169             generateAssertionEOL(opIndex);
1170             break;
1171
1172         case PatternTerm::TypeAssertionWordBoundary:
1173             generateAssertionWordBoundary(opIndex);
1174             break;
1175
1176         case PatternTerm::TypeForwardReference:
1177             break;
1178
1179         case PatternTerm::TypeParenthesesSubpattern:
1180         case PatternTerm::TypeParentheticalAssertion:
1181             ASSERT_NOT_REACHED();
1182         case PatternTerm::TypeBackReference:
1183             m_shouldFallBack = true;
1184             break;
1185         case PatternTerm::TypeDotStarEnclosure:
1186             generateDotStarEnclosure(opIndex);
1187             break;
1188         }
1189     }
1190     void backtrackTerm(size_t opIndex)
1191     {
1192         YarrOp& op = m_ops[opIndex];
1193         PatternTerm* term = op.m_term;
1194
1195         switch (term->type) {
1196         case PatternTerm::TypePatternCharacter:
1197             switch (term->quantityType) {
1198             case QuantifierFixedCount:
1199                 if (term->quantityCount == 1)
1200                     backtrackPatternCharacterOnce(opIndex);
1201                 else
1202                     backtrackPatternCharacterFixed(opIndex);
1203                 break;
1204             case QuantifierGreedy:
1205                 backtrackPatternCharacterGreedy(opIndex);
1206                 break;
1207             case QuantifierNonGreedy:
1208                 backtrackPatternCharacterNonGreedy(opIndex);
1209                 break;
1210             }
1211             break;
1212
1213         case PatternTerm::TypeCharacterClass:
1214             switch (term->quantityType) {
1215             case QuantifierFixedCount:
1216                 if (term->quantityCount == 1)
1217                     backtrackCharacterClassOnce(opIndex);
1218                 else
1219                     backtrackCharacterClassFixed(opIndex);
1220                 break;
1221             case QuantifierGreedy:
1222                 backtrackCharacterClassGreedy(opIndex);
1223                 break;
1224             case QuantifierNonGreedy:
1225                 backtrackCharacterClassNonGreedy(opIndex);
1226                 break;
1227             }
1228             break;
1229
1230         case PatternTerm::TypeAssertionBOL:
1231             backtrackAssertionBOL(opIndex);
1232             break;
1233
1234         case PatternTerm::TypeAssertionEOL:
1235             backtrackAssertionEOL(opIndex);
1236             break;
1237
1238         case PatternTerm::TypeAssertionWordBoundary:
1239             backtrackAssertionWordBoundary(opIndex);
1240             break;
1241
1242         case PatternTerm::TypeForwardReference:
1243             break;
1244
1245         case PatternTerm::TypeParenthesesSubpattern:
1246         case PatternTerm::TypeParentheticalAssertion:
1247             ASSERT_NOT_REACHED();
1248
1249         case PatternTerm::TypeDotStarEnclosure:
1250             backtrackDotStarEnclosure(opIndex);
1251             break;
1252
1253         case PatternTerm::TypeBackReference:
1254             m_shouldFallBack = true;
1255             break;
1256         }
1257     }
1258
1259     void generate()
1260     {
1261         // Forwards generate the matching code.
1262         ASSERT(m_ops.size());
1263         size_t opIndex = 0;
1264
1265         do {
1266             YarrOp& op = m_ops[opIndex];
1267             switch (op.m_op) {
1268
1269             case OpTerm:
1270                 generateTerm(opIndex);
1271                 break;
1272
1273             // OpBodyAlternativeBegin/Next/End
1274             //
1275             // These nodes wrap the set of alternatives in the body of the regular expression.
1276             // There may be either one or two chains of OpBodyAlternative nodes, one representing
1277             // the 'once through' sequence of alternatives (if any exist), and one representing
1278             // the repeating alternatives (again, if any exist).
1279             //
1280             // Upon normal entry to the Begin alternative, we will check that input is available.
1281             // Reentry to the Begin alternative will take place after the check has taken place,
1282             // and will assume that the input position has already been progressed as appropriate.
1283             //
1284             // Entry to subsequent Next/End alternatives occurs when the prior alternative has
1285             // successfully completed a match - return a success state from JIT code.
1286             //
1287             // Next alternatives allow for reentry optimized to suit backtracking from its
1288             // preceding alternative. It expects the input position to still be set to a position
1289             // appropriate to its predecessor, and it will only perform an input check if the
1290             // predecessor had a minimum size less than its own.
1291             //
1292             // In the case 'once through' expressions, the End node will also have a reentry
1293             // point to jump to when the last alternative fails. Again, this expects the input
1294             // position to still reflect that expected by the prior alternative.
1295             case OpBodyAlternativeBegin: {
1296                 PatternAlternative* alternative = op.m_alternative;
1297
1298                 // Upon entry at the head of the set of alternatives, check if input is available
1299                 // to run the first alternative. (This progresses the input position).
1300                 op.m_jumps.append(jumpIfNoAvailableInput(alternative->m_minimumSize));
1301                 // We will reenter after the check, and assume the input position to have been
1302                 // set as appropriate to this alternative.
1303                 op.m_reentry = label();
1304
1305                 m_checked += alternative->m_minimumSize;
1306                 break;
1307             }
1308             case OpBodyAlternativeNext:
1309             case OpBodyAlternativeEnd: {
1310                 PatternAlternative* priorAlternative = m_ops[op.m_previousOp].m_alternative;
1311                 PatternAlternative* alternative = op.m_alternative;
1312
1313                 // If we get here, the prior alternative matched - return success.
1314                 
1315                 // Adjust the stack pointer to remove the pattern's frame.
1316                 if (m_pattern.m_body->m_callFrameSize)
1317                     addPtr(Imm32(m_pattern.m_body->m_callFrameSize * sizeof(void*)), stackPointerRegister);
1318
1319                 // Load appropriate values into the return register and the first output
1320                 // slot, and return. In the case of pattern with a fixed size, we will
1321                 // not have yet set the value in the first 
1322                 ASSERT(index != returnRegister);
1323                 if (m_pattern.m_body->m_hasFixedSize) {
1324                     move(index, returnRegister);
1325                     if (priorAlternative->m_minimumSize)
1326                         sub32(Imm32(priorAlternative->m_minimumSize), returnRegister);
1327                     store32(returnRegister, output);
1328                 } else
1329                     load32(Address(output), returnRegister);
1330                 store32(index, Address(output, 4));
1331                 generateReturn();
1332
1333                 // This is the divide between the tail of the prior alternative, above, and
1334                 // the head of the subsequent alternative, below.
1335
1336                 if (op.m_op == OpBodyAlternativeNext) {
1337                     // This is the reentry point for the Next alternative. We expect any code
1338                     // that jumps here to do so with the input position matching that of the
1339                     // PRIOR alteranative, and we will only check input availability if we
1340                     // need to progress it forwards.
1341                     op.m_reentry = label();
1342                     if (alternative->m_minimumSize > priorAlternative->m_minimumSize) {
1343                         add32(Imm32(alternative->m_minimumSize - priorAlternative->m_minimumSize), index);
1344                         op.m_jumps.append(jumpIfNoAvailableInput());
1345                     } else if (priorAlternative->m_minimumSize > alternative->m_minimumSize)
1346                         sub32(Imm32(priorAlternative->m_minimumSize - alternative->m_minimumSize), index);
1347                 } else if (op.m_nextOp == notFound) {
1348                     // This is the reentry point for the End of 'once through' alternatives,
1349                     // jumped to when the last alternative fails to match.
1350                     op.m_reentry = label();
1351                     sub32(Imm32(priorAlternative->m_minimumSize), index);
1352                 }
1353
1354                 if (op.m_op == OpBodyAlternativeNext)
1355                     m_checked += alternative->m_minimumSize;
1356                 m_checked -= priorAlternative->m_minimumSize;
1357                 break;
1358             }
1359
1360             // OpSimpleNestedAlternativeBegin/Next/End
1361             // OpNestedAlternativeBegin/Next/End
1362             //
1363             // These nodes are used to handle sets of alternatives that are nested within
1364             // subpatterns and parenthetical assertions. The 'simple' forms are used where
1365             // we do not need to be able to backtrack back into any alternative other than
1366             // the last, the normal forms allow backtracking into any alternative.
1367             //
1368             // Each Begin/Next node is responsible for planting an input check to ensure
1369             // sufficient input is available on entry. Next nodes additionally need to
1370             // jump to the end - Next nodes use the End node's m_jumps list to hold this
1371             // set of jumps.
1372             //
1373             // In the non-simple forms, successful alternative matches must store a
1374             // 'return address' using a DataLabelPtr, used to store the address to jump
1375             // to when backtracking, to get to the code for the appropriate alternative.
1376             case OpSimpleNestedAlternativeBegin:
1377             case OpNestedAlternativeBegin: {
1378                 PatternTerm* term = op.m_term;
1379                 PatternAlternative* alternative = op.m_alternative;
1380                 PatternDisjunction* disjunction = term->parentheses.disjunction;
1381
1382                 // Calculate how much input we need to check for, and if non-zero check.
1383                 op.m_checkAdjust = alternative->m_minimumSize;
1384                 if ((term->quantityType == QuantifierFixedCount) && (term->type != PatternTerm::TypeParentheticalAssertion))
1385                     op.m_checkAdjust -= disjunction->m_minimumSize;
1386                 if (op.m_checkAdjust)
1387                     op.m_jumps.append(jumpIfNoAvailableInput(op.m_checkAdjust));
1388  
1389                 m_checked += op.m_checkAdjust;
1390                 break;
1391             }
1392             case OpSimpleNestedAlternativeNext:
1393             case OpNestedAlternativeNext: {
1394                 PatternTerm* term = op.m_term;
1395                 PatternAlternative* alternative = op.m_alternative;
1396                 PatternDisjunction* disjunction = term->parentheses.disjunction;
1397
1398                 // In the non-simple case, store a 'return address' so we can backtrack correctly.
1399                 if (op.m_op == OpNestedAlternativeNext) {
1400                     unsigned parenthesesFrameLocation = term->frameLocation;
1401                     unsigned alternativeFrameLocation = parenthesesFrameLocation;
1402                     if (term->quantityType != QuantifierFixedCount)
1403                         alternativeFrameLocation += YarrStackSpaceForBackTrackInfoParenthesesOnce;
1404                     op.m_returnAddress = storeToFrameWithPatch(alternativeFrameLocation);
1405                 }
1406
1407                 // If we reach here then the last alternative has matched - jump to the
1408                 // End node, to skip over any further alternatives.
1409                 //
1410                 // FIXME: this is logically O(N^2) (though N can be expected to be very
1411                 // small). We could avoid this either by adding an extra jump to the JIT
1412                 // data structures, or by making backtracking code that jumps to Next
1413                 // alternatives are responsible for checking that input is available (if
1414                 // we didn't need to plant the input checks, then m_jumps would be free).
1415                 YarrOp* endOp = &m_ops[op.m_nextOp];
1416                 while (endOp->m_nextOp != notFound) {
1417                     ASSERT(endOp->m_op == OpSimpleNestedAlternativeNext || endOp->m_op == OpNestedAlternativeNext);
1418                     endOp = &m_ops[endOp->m_nextOp];
1419                 }
1420                 ASSERT(endOp->m_op == OpSimpleNestedAlternativeEnd || endOp->m_op == OpNestedAlternativeEnd);
1421                 endOp->m_jumps.append(jump());
1422
1423                 // This is the entry point for the next alternative.
1424                 op.m_reentry = label();
1425
1426                 // Calculate how much input we need to check for, and if non-zero check.
1427                 op.m_checkAdjust = alternative->m_minimumSize;
1428                 if ((term->quantityType == QuantifierFixedCount) && (term->type != PatternTerm::TypeParentheticalAssertion))
1429                     op.m_checkAdjust -= disjunction->m_minimumSize;
1430                 if (op.m_checkAdjust)
1431                     op.m_jumps.append(jumpIfNoAvailableInput(op.m_checkAdjust));
1432
1433                 YarrOp& lastOp = m_ops[op.m_previousOp];
1434                 m_checked -= lastOp.m_checkAdjust;
1435                 m_checked += op.m_checkAdjust;
1436                 break;
1437             }
1438             case OpSimpleNestedAlternativeEnd:
1439             case OpNestedAlternativeEnd: {
1440                 PatternTerm* term = op.m_term;
1441
1442                 // In the non-simple case, store a 'return address' so we can backtrack correctly.
1443                 if (op.m_op == OpNestedAlternativeEnd) {
1444                     unsigned parenthesesFrameLocation = term->frameLocation;
1445                     unsigned alternativeFrameLocation = parenthesesFrameLocation;
1446                     if (term->quantityType != QuantifierFixedCount)
1447                         alternativeFrameLocation += YarrStackSpaceForBackTrackInfoParenthesesOnce;
1448                     op.m_returnAddress = storeToFrameWithPatch(alternativeFrameLocation);
1449                 }
1450
1451                 // If this set of alternatives contains more than one alternative,
1452                 // then the Next nodes will have planted jumps to the End, and added
1453                 // them to this node's m_jumps list.
1454                 op.m_jumps.link(this);
1455                 op.m_jumps.clear();
1456
1457                 YarrOp& lastOp = m_ops[op.m_previousOp];
1458                 m_checked -= lastOp.m_checkAdjust;
1459                 break;
1460             }
1461
1462             // OpParenthesesSubpatternOnceBegin/End
1463             //
1464             // These nodes support (optionally) capturing subpatterns, that have a
1465             // quantity count of 1 (this covers fixed once, and ?/?? quantifiers). 
1466             case OpParenthesesSubpatternOnceBegin: {
1467                 PatternTerm* term = op.m_term;
1468                 unsigned parenthesesFrameLocation = term->frameLocation;
1469                 const RegisterID indexTemporary = regT0;
1470                 ASSERT(term->quantityCount == 1);
1471
1472                 // Upon entry to a Greedy quantified set of parenthese store the index.
1473                 // We'll use this for two purposes:
1474                 //  - To indicate which iteration we are on of mathing the remainder of
1475                 //    the expression after the parentheses - the first, including the
1476                 //    match within the parentheses, or the second having skipped over them.
1477                 //  - To check for empty matches, which must be rejected.
1478                 //
1479                 // At the head of a NonGreedy set of parentheses we'll immediately set the
1480                 // value on the stack to -1 (indicating a match skipping the subpattern),
1481                 // and plant a jump to the end. We'll also plant a label to backtrack to
1482                 // to reenter the subpattern later, with a store to set up index on the
1483                 // second iteration.
1484                 //
1485                 // FIXME: for capturing parens, could use the index in the capture array?
1486                 if (term->quantityType == QuantifierGreedy)
1487                     storeToFrame(index, parenthesesFrameLocation);
1488                 else if (term->quantityType == QuantifierNonGreedy) {
1489                     storeToFrame(TrustedImm32(-1), parenthesesFrameLocation);
1490                     op.m_jumps.append(jump());
1491                     op.m_reentry = label();
1492                     storeToFrame(index, parenthesesFrameLocation);
1493                 }
1494
1495                 // If the parenthese are capturing, store the starting index value to the
1496                 // captures array, offsetting as necessary.
1497                 //
1498                 // FIXME: could avoid offsetting this value in JIT code, apply
1499                 // offsets only afterwards, at the point the results array is
1500                 // being accessed.
1501                 if (term->capture()) {
1502                     int offsetId = term->parentheses.subpatternId << 1;
1503                     int inputOffset = term->inputPosition - m_checked;
1504                     if (term->quantityType == QuantifierFixedCount)
1505                         inputOffset -= term->parentheses.disjunction->m_minimumSize;
1506                     if (inputOffset) {
1507                         move(index, indexTemporary);
1508                         add32(Imm32(inputOffset), indexTemporary);
1509                         store32(indexTemporary, Address(output, offsetId * sizeof(int)));
1510                     } else
1511                         store32(index, Address(output, offsetId * sizeof(int)));
1512                 }
1513                 break;
1514             }
1515             case OpParenthesesSubpatternOnceEnd: {
1516                 PatternTerm* term = op.m_term;
1517                 unsigned parenthesesFrameLocation = term->frameLocation;
1518                 const RegisterID indexTemporary = regT0;
1519                 ASSERT(term->quantityCount == 1);
1520
1521                 // For Greedy/NonGreedy quantified parentheses, we must reject zero length
1522                 // matches. If the minimum size is know to be non-zero we need not check.
1523                 if (term->quantityType != QuantifierFixedCount && !term->parentheses.disjunction->m_minimumSize)
1524                     op.m_jumps.append(branch32(Equal, index, Address(stackPointerRegister, parenthesesFrameLocation * sizeof(void*))));
1525
1526                 // If the parenthese are capturing, store the ending index value to the
1527                 // captures array, offsetting as necessary.
1528                 //
1529                 // FIXME: could avoid offsetting this value in JIT code, apply
1530                 // offsets only afterwards, at the point the results array is
1531                 // being accessed.
1532                 if (term->capture()) {
1533                     int offsetId = (term->parentheses.subpatternId << 1) + 1;
1534                     int inputOffset = term->inputPosition - m_checked;
1535                     if (inputOffset) {
1536                         move(index, indexTemporary);
1537                         add32(Imm32(inputOffset), indexTemporary);
1538                         store32(indexTemporary, Address(output, offsetId * sizeof(int)));
1539                     } else
1540                         store32(index, Address(output, offsetId * sizeof(int)));
1541                 }
1542
1543                 // If the parentheses are quantified Greedy then add a label to jump back
1544                 // to if get a failed match from after the parentheses. For NonGreedy
1545                 // parentheses, link the jump from before the subpattern to here.
1546                 if (term->quantityType == QuantifierGreedy)
1547                     op.m_reentry = label();
1548                 else if (term->quantityType == QuantifierNonGreedy) {
1549                     YarrOp& beginOp = m_ops[op.m_previousOp];
1550                     beginOp.m_jumps.link(this);
1551                 }
1552                 break;
1553             }
1554
1555             // OpParenthesesSubpatternTerminalBegin/End
1556             case OpParenthesesSubpatternTerminalBegin: {
1557                 PatternTerm* term = op.m_term;
1558                 ASSERT(term->quantityType == QuantifierGreedy);
1559                 ASSERT(term->quantityCount == quantifyInfinite);
1560                 ASSERT(!term->capture());
1561
1562                 // Upon entry set a label to loop back to.
1563                 op.m_reentry = label();
1564
1565                 // Store the start index of the current match; we need to reject zero
1566                 // length matches.
1567                 storeToFrame(index, term->frameLocation);
1568                 break;
1569             }
1570             case OpParenthesesSubpatternTerminalEnd: {
1571                 PatternTerm* term = op.m_term;
1572
1573                 // Check for zero length matches - if the match is non-zero, then we
1574                 // can accept it & loop back up to the head of the subpattern.
1575                 YarrOp& beginOp = m_ops[op.m_previousOp];
1576                 branch32(NotEqual, index, Address(stackPointerRegister, term->frameLocation * sizeof(void*)), beginOp.m_reentry);
1577
1578                 // Reject the match - backtrack back into the subpattern.
1579                 op.m_jumps.append(jump());
1580
1581                 // This is the entry point to jump to when we stop matching - we will
1582                 // do so once the subpattern cannot match any more.
1583                 op.m_reentry = label();
1584                 break;
1585             }
1586
1587             // OpParentheticalAssertionBegin/End
1588             case OpParentheticalAssertionBegin: {
1589                 PatternTerm* term = op.m_term;
1590
1591                 // Store the current index - assertions should not update index, so
1592                 // we will need to restore it upon a successful match.
1593                 unsigned parenthesesFrameLocation = term->frameLocation;
1594                 storeToFrame(index, parenthesesFrameLocation);
1595
1596                 // Check 
1597                 op.m_checkAdjust = m_checked - term->inputPosition;
1598                 if (op.m_checkAdjust)
1599                     sub32(Imm32(op.m_checkAdjust), index);
1600
1601                 m_checked -= op.m_checkAdjust;
1602                 break;
1603             }
1604             case OpParentheticalAssertionEnd: {
1605                 PatternTerm* term = op.m_term;
1606
1607                 // Restore the input index value.
1608                 unsigned parenthesesFrameLocation = term->frameLocation;
1609                 loadFromFrame(parenthesesFrameLocation, index);
1610
1611                 // If inverted, a successful match of the assertion must be treated
1612                 // as a failure, so jump to backtracking.
1613                 if (term->invert()) {
1614                     op.m_jumps.append(jump());
1615                     op.m_reentry = label();
1616                 }
1617
1618                 YarrOp& lastOp = m_ops[op.m_previousOp];
1619                 m_checked += lastOp.m_checkAdjust;
1620                 break;
1621             }
1622
1623             case OpMatchFailed:
1624                 if (m_pattern.m_body->m_callFrameSize)
1625                     addPtr(Imm32(m_pattern.m_body->m_callFrameSize * sizeof(void*)), stackPointerRegister);
1626                 move(TrustedImm32(-1), returnRegister);
1627                 generateReturn();
1628                 break;
1629             }
1630
1631             ++opIndex;
1632         } while (opIndex < m_ops.size());
1633     }
1634
1635     void backtrack()
1636     {
1637         // Backwards generate the backtracking code.
1638         size_t opIndex = m_ops.size();
1639         ASSERT(opIndex);
1640
1641         do {
1642             --opIndex;
1643             YarrOp& op = m_ops[opIndex];
1644             switch (op.m_op) {
1645
1646             case OpTerm:
1647                 backtrackTerm(opIndex);
1648                 break;
1649
1650             // OpBodyAlternativeBegin/Next/End
1651             //
1652             // For each Begin/Next node representing an alternative, we need to decide what to do
1653             // in two circumstances:
1654             //  - If we backtrack back into this node, from within the alternative.
1655             //  - If the input check at the head of the alternative fails (if this exists).
1656             //
1657             // We treat these two cases differently since in the former case we have slightly
1658             // more information - since we are backtracking out of a prior alternative we know
1659             // that at least enough input was available to run it. For example, given the regular
1660             // expression /a|b/, if we backtrack out of the first alternative (a failed pattern
1661             // character match of 'a'), then we need not perform an additional input availability
1662             // check before running the second alternative.
1663             //
1664             // Backtracking required differs for the last alternative, which in the case of the
1665             // repeating set of alternatives must loop. The code generated for the last alternative
1666             // will also be used to handle all input check failures from any prior alternatives -
1667             // these require similar functionality, in seeking the next available alternative for
1668             // which there is sufficient input.
1669             //
1670             // Since backtracking of all other alternatives simply requires us to link backtracks
1671             // to the reentry point for the subsequent alternative, we will only be generating any
1672             // code when backtracking the last alternative.
1673             case OpBodyAlternativeBegin:
1674             case OpBodyAlternativeNext: {
1675                 PatternAlternative* alternative = op.m_alternative;
1676
1677                 if (op.m_op == OpBodyAlternativeNext) {
1678                     PatternAlternative* priorAlternative = m_ops[op.m_previousOp].m_alternative;
1679                     m_checked += priorAlternative->m_minimumSize;
1680                 }
1681                 m_checked -= alternative->m_minimumSize;
1682
1683                 // Is this the last alternative? If not, then if we backtrack to this point we just
1684                 // need to jump to try to match the next alternative.
1685                 if (m_ops[op.m_nextOp].m_op != OpBodyAlternativeEnd) {
1686                     m_backtrackingState.linkTo(m_ops[op.m_nextOp].m_reentry, this);
1687                     break;
1688                 }
1689                 YarrOp& endOp = m_ops[op.m_nextOp];
1690
1691                 YarrOp* beginOp = &op;
1692                 while (beginOp->m_op != OpBodyAlternativeBegin) {
1693                     ASSERT(beginOp->m_op == OpBodyAlternativeNext);
1694                     beginOp = &m_ops[beginOp->m_previousOp];
1695                 }
1696
1697                 bool onceThrough = endOp.m_nextOp == notFound;
1698
1699                 // First, generate code to handle cases where we backtrack out of an attempted match
1700                 // of the last alternative. If this is a 'once through' set of alternatives then we
1701                 // have nothing to do - link this straight through to the End.
1702                 if (onceThrough)
1703                     m_backtrackingState.linkTo(endOp.m_reentry, this);
1704                 else {
1705                     // If we don't need to move the input poistion, and the pattern has a fixed size
1706                     // (in which case we omit the store of the start index until the pattern has matched)
1707                     // then we can just link the backtrack out of the last alternative straight to the
1708                     // head of the first alternative.
1709                     if (m_pattern.m_body->m_hasFixedSize
1710                         && (alternative->m_minimumSize > beginOp->m_alternative->m_minimumSize)
1711                         && (alternative->m_minimumSize - beginOp->m_alternative->m_minimumSize == 1))
1712                         m_backtrackingState.linkTo(beginOp->m_reentry, this);
1713                     else {
1714                         // We need to generate a trampoline of code to execute before looping back
1715                         // around to the first alternative.
1716                         m_backtrackingState.link(this);
1717
1718                         // If the pattern size is not fixed, then store the start index, for use if we match.
1719                         if (!m_pattern.m_body->m_hasFixedSize) {
1720                             if (alternative->m_minimumSize == 1)
1721                                 store32(index, Address(output));
1722                             else {
1723                                 move(index, regT0);
1724                                 if (alternative->m_minimumSize)
1725                                     sub32(Imm32(alternative->m_minimumSize - 1), regT0);
1726                                 else
1727                                     add32(Imm32(1), regT0);
1728                                 store32(regT0, Address(output));
1729                             }
1730                         }
1731
1732                         // Generate code to loop. Check whether the last alternative is longer than the
1733                         // first (e.g. /a|xy/ or /a|xyz/).
1734                         if (alternative->m_minimumSize > beginOp->m_alternative->m_minimumSize) {
1735                             // We want to loop, and increment input position. If the delta is 1, it is
1736                             // already correctly incremented, if more than one then decrement as appropriate.
1737                             unsigned delta = alternative->m_minimumSize - beginOp->m_alternative->m_minimumSize;
1738                             ASSERT(delta);
1739                             if (delta != 1)
1740                                 sub32(Imm32(delta - 1), index);
1741                             jump(beginOp->m_reentry);
1742                         } else {
1743                             // If the first alternative has minimum size 0xFFFFFFFFu, then there cannot
1744                             // be sufficent input available to handle this, so just fall through.
1745                             unsigned delta = beginOp->m_alternative->m_minimumSize - alternative->m_minimumSize;
1746                             if (delta != 0xFFFFFFFFu) {
1747                                 // We need to check input because we are incrementing the input.
1748                                 add32(Imm32(delta + 1), index);
1749                                 checkInput().linkTo(beginOp->m_reentry, this);
1750                             }
1751                         }
1752                     }
1753                 }
1754
1755                 // We can reach this point in the code in two ways:
1756                 //  - Fallthrough from the code above (a repeating alternative backtracked out of its
1757                 //    last alternative, and did not have sufficent input to run the first).
1758                 //  - We will loop back up to the following label when a releating alternative loops,
1759                 //    following a failed input check.
1760                 //
1761                 // Either way, we have just failed the input check for the first alternative.
1762                 Label firstInputCheckFailed(this);
1763
1764                 // Generate code to handle input check failures from alternatives except the last.
1765                 // prevOp is the alternative we're handling a bail out from (initially Begin), and
1766                 // nextOp is the alternative we will be attempting to reenter into.
1767                 // 
1768                 // We will link input check failures from the forwards matching path back to the code
1769                 // that can handle them.
1770                 YarrOp* prevOp = beginOp;
1771                 YarrOp* nextOp = &m_ops[beginOp->m_nextOp];
1772                 while (nextOp->m_op != OpBodyAlternativeEnd) {
1773                     prevOp->m_jumps.link(this);
1774
1775                     // We only get here if an input check fails, it is only worth checking again
1776                     // if the next alternative has a minimum size less than the last.
1777                     if (prevOp->m_alternative->m_minimumSize > nextOp->m_alternative->m_minimumSize) {
1778                         // FIXME: if we added an extra label to YarrOp, we could avoid needing to
1779                         // subtract delta back out, and reduce this code. Should performance test
1780                         // the benefit of this.
1781                         unsigned delta = prevOp->m_alternative->m_minimumSize - nextOp->m_alternative->m_minimumSize;
1782                         sub32(Imm32(delta), index);
1783                         Jump fail = jumpIfNoAvailableInput();
1784                         add32(Imm32(delta), index);
1785                         jump(nextOp->m_reentry);
1786                         fail.link(this);
1787                     } else if (prevOp->m_alternative->m_minimumSize < nextOp->m_alternative->m_minimumSize)
1788                         add32(Imm32(nextOp->m_alternative->m_minimumSize - prevOp->m_alternative->m_minimumSize), index);
1789                     prevOp = nextOp;
1790                     nextOp = &m_ops[nextOp->m_nextOp];
1791                 }
1792
1793                 // We fall through to here if there is insufficient input to run the last alternative.
1794
1795                 // If there is insufficient input to run the last alternative, then for 'once through'
1796                 // alternatives we are done - just jump back up into the forwards matching path at the End.
1797                 if (onceThrough) {
1798                     op.m_jumps.linkTo(endOp.m_reentry, this);
1799                     jump(endOp.m_reentry);
1800                     break;
1801                 }
1802
1803                 // For repeating alternatives, link any input check failure from the last alternative to
1804                 // this point.
1805                 op.m_jumps.link(this);
1806
1807                 bool needsToUpdateMatchStart = !m_pattern.m_body->m_hasFixedSize;
1808
1809                 // Check for cases where input position is already incremented by 1 for the last
1810                 // alternative (this is particularly useful where the minimum size of the body
1811                 // disjunction is 0, e.g. /a*|b/).
1812                 if (needsToUpdateMatchStart && alternative->m_minimumSize == 1) {
1813                     // index is already incremented by 1, so just store it now!
1814                     store32(index, Address(output));
1815                     needsToUpdateMatchStart = false;
1816                 }
1817
1818                 // Check whether there is sufficient input to loop. Increment the input position by
1819                 // one, and check. Also add in the minimum disjunction size before checking - there
1820                 // is no point in looping if we're just going to fail all the input checks around
1821                 // the next iteration.
1822                 ASSERT(alternative->m_minimumSize >= m_pattern.m_body->m_minimumSize);
1823                 if (alternative->m_minimumSize == m_pattern.m_body->m_minimumSize) {
1824                     // If the last alternative had the same minimum size as the disjunction,
1825                     // just simply increment input pos by 1, no adjustment based on minimum size.
1826                     add32(Imm32(1), index);
1827                 } else {
1828                     // If the minumum for the last alternative was one greater than than that
1829                     // for the disjunction, we're already progressed by 1, nothing to do!
1830                     unsigned delta = (alternative->m_minimumSize - m_pattern.m_body->m_minimumSize) - 1;
1831                     if (delta)
1832                         sub32(Imm32(delta), index);
1833                 }
1834                 Jump matchFailed = jumpIfNoAvailableInput();
1835
1836                 if (needsToUpdateMatchStart) {
1837                     if (!m_pattern.m_body->m_minimumSize)
1838                         store32(index, Address(output));
1839                     else {
1840                         move(index, regT0);
1841                         sub32(Imm32(m_pattern.m_body->m_minimumSize), regT0);
1842                         store32(regT0, Address(output));
1843                     }
1844                 }
1845
1846                 // Calculate how much more input the first alternative requires than the minimum
1847                 // for the body as a whole. If no more is needed then we dont need an additional
1848                 // input check here - jump straight back up to the start of the first alternative.
1849                 if (beginOp->m_alternative->m_minimumSize == m_pattern.m_body->m_minimumSize)
1850                     jump(beginOp->m_reentry);
1851                 else {
1852                     if (beginOp->m_alternative->m_minimumSize > m_pattern.m_body->m_minimumSize)
1853                         add32(Imm32(beginOp->m_alternative->m_minimumSize - m_pattern.m_body->m_minimumSize), index);
1854                     else
1855                         sub32(Imm32(m_pattern.m_body->m_minimumSize - beginOp->m_alternative->m_minimumSize), index);
1856                     checkInput().linkTo(beginOp->m_reentry, this);
1857                     jump(firstInputCheckFailed);
1858                 }
1859
1860                 // We jump to here if we iterate to the point that there is insufficient input to
1861                 // run any matches, and need to return a failure state from JIT code.
1862                 matchFailed.link(this);
1863
1864                 if (m_pattern.m_body->m_callFrameSize)
1865                     addPtr(Imm32(m_pattern.m_body->m_callFrameSize * sizeof(void*)), stackPointerRegister);
1866                 move(TrustedImm32(-1), returnRegister);
1867                 generateReturn();
1868                 break;
1869             }
1870             case OpBodyAlternativeEnd: {
1871                 // We should never backtrack back into a body disjunction.
1872                 ASSERT(m_backtrackingState.isEmpty());
1873
1874                 PatternAlternative* priorAlternative = m_ops[op.m_previousOp].m_alternative;
1875                 m_checked += priorAlternative->m_minimumSize;
1876                 break;
1877             }
1878
1879             // OpSimpleNestedAlternativeBegin/Next/End
1880             // OpNestedAlternativeBegin/Next/End
1881             //
1882             // Generate code for when we backtrack back out of an alternative into
1883             // a Begin or Next node, or when the entry input count check fails. If
1884             // there are more alternatives we need to jump to the next alternative,
1885             // if not we backtrack back out of the current set of parentheses.
1886             //
1887             // In the case of non-simple nested assertions we need to also link the
1888             // 'return address' appropriately to backtrack back out into the correct
1889             // alternative.
1890             case OpSimpleNestedAlternativeBegin:
1891             case OpSimpleNestedAlternativeNext:
1892             case OpNestedAlternativeBegin:
1893             case OpNestedAlternativeNext: {
1894                 YarrOp& nextOp = m_ops[op.m_nextOp];
1895                 bool isBegin = op.m_previousOp == notFound;
1896                 bool isLastAlternative = nextOp.m_nextOp == notFound;
1897                 ASSERT(isBegin == (op.m_op == OpSimpleNestedAlternativeBegin || op.m_op == OpNestedAlternativeBegin));
1898                 ASSERT(isLastAlternative == (nextOp.m_op == OpSimpleNestedAlternativeEnd || nextOp.m_op == OpNestedAlternativeEnd));
1899
1900                 // Treat an input check failure the same as a failed match.
1901                 m_backtrackingState.append(op.m_jumps);
1902
1903                 // Set the backtracks to jump to the appropriate place. We may need
1904                 // to link the backtracks in one of three different way depending on
1905                 // the type of alternative we are dealing with:
1906                 //  - A single alternative, with no simplings.
1907                 //  - The last alternative of a set of two or more.
1908                 //  - An alternative other than the last of a set of two or more.
1909                 //
1910                 // In the case of a single alternative on its own, we don't need to
1911                 // jump anywhere - if the alternative fails to match we can just
1912                 // continue to backtrack out of the parentheses without jumping.
1913                 //
1914                 // In the case of the last alternative in a set of more than one, we
1915                 // need to jump to return back out to the beginning. We'll do so by
1916                 // adding a jump to the End node's m_jumps list, and linking this
1917                 // when we come to generate the Begin node. For alternatives other
1918                 // than the last, we need to jump to the next alternative.
1919                 //
1920                 // If the alternative had adjusted the input position we must link
1921                 // backtracking to here, correct, and then jump on. If not we can
1922                 // link the backtracks directly to their destination.
1923                 if (op.m_checkAdjust) {
1924                     // Handle the cases where we need to link the backtracks here.
1925                     m_backtrackingState.link(this);
1926                     sub32(Imm32(op.m_checkAdjust), index);
1927                     if (!isLastAlternative) {
1928                         // An alternative that is not the last should jump to its successor.
1929                         jump(nextOp.m_reentry);
1930                     } else if (!isBegin) {
1931                         // The last of more than one alternatives must jump back to the begnning.
1932                         nextOp.m_jumps.append(jump());
1933                     } else {
1934                         // A single alternative on its own can fall through.
1935                         m_backtrackingState.fallthrough();
1936                     }
1937                 } else {
1938                     // Handle the cases where we can link the backtracks directly to their destinations.
1939                     if (!isLastAlternative) {
1940                         // An alternative that is not the last should jump to its successor.
1941                         m_backtrackingState.linkTo(nextOp.m_reentry, this);
1942                     } else if (!isBegin) {
1943                         // The last of more than one alternatives must jump back to the begnning.
1944                         m_backtrackingState.takeBacktracksToJumpList(nextOp.m_jumps, this);
1945                     }
1946                     // In the case of a single alternative on its own do nothing - it can fall through.
1947                 }
1948
1949                 // At this point we've handled the backtracking back into this node.
1950                 // Now link any backtracks that need to jump to here.
1951
1952                 // For non-simple alternatives, link the alternative's 'return address'
1953                 // so that we backtrack back out into the previous alternative.
1954                 if (op.m_op == OpNestedAlternativeNext)
1955                     m_backtrackingState.append(op.m_returnAddress);
1956
1957                 // If there is more than one alternative, then the last alternative will
1958                 // have planted a jump to be linked to the end. This jump was added to the
1959                 // End node's m_jumps list. If we are back at the beginning, link it here.
1960                 if (isBegin) {
1961                     YarrOp* endOp = &m_ops[op.m_nextOp];
1962                     while (endOp->m_nextOp != notFound) {
1963                         ASSERT(endOp->m_op == OpSimpleNestedAlternativeNext || endOp->m_op == OpNestedAlternativeNext);
1964                         endOp = &m_ops[endOp->m_nextOp];
1965                     }
1966                     ASSERT(endOp->m_op == OpSimpleNestedAlternativeEnd || endOp->m_op == OpNestedAlternativeEnd);
1967                     m_backtrackingState.append(endOp->m_jumps);
1968                 }
1969
1970                 if (!isBegin) {
1971                     YarrOp& lastOp = m_ops[op.m_previousOp];
1972                     m_checked += lastOp.m_checkAdjust;
1973                 }
1974                 m_checked -= op.m_checkAdjust;
1975                 break;
1976             }
1977             case OpSimpleNestedAlternativeEnd:
1978             case OpNestedAlternativeEnd: {
1979                 PatternTerm* term = op.m_term;
1980
1981                 // If we backtrack into the end of a simple subpattern do nothing;
1982                 // just continue through into the last alternative. If we backtrack
1983                 // into the end of a non-simple set of alterntives we need to jump
1984                 // to the backtracking return address set up during generation.
1985                 if (op.m_op == OpNestedAlternativeEnd) {
1986                     m_backtrackingState.link(this);
1987
1988                     // Plant a jump to the return address.
1989                     unsigned parenthesesFrameLocation = term->frameLocation;
1990                     unsigned alternativeFrameLocation = parenthesesFrameLocation;
1991                     if (term->quantityType != QuantifierFixedCount)
1992                         alternativeFrameLocation += YarrStackSpaceForBackTrackInfoParenthesesOnce;
1993                     loadFromFrameAndJump(alternativeFrameLocation);
1994
1995                     // Link the DataLabelPtr associated with the end of the last
1996                     // alternative to this point.
1997                     m_backtrackingState.append(op.m_returnAddress);
1998                 }
1999
2000                 YarrOp& lastOp = m_ops[op.m_previousOp];
2001                 m_checked += lastOp.m_checkAdjust;
2002                 break;
2003             }
2004
2005             // OpParenthesesSubpatternOnceBegin/End
2006             //
2007             // When we are backtracking back out of a capturing subpattern we need
2008             // to clear the start index in the matches output array, to record that
2009             // this subpattern has not been captured.
2010             //
2011             // When backtracking back out of a Greedy quantified subpattern we need
2012             // to catch this, and try running the remainder of the alternative after
2013             // the subpattern again, skipping the parentheses.
2014             //
2015             // Upon backtracking back into a quantified set of parentheses we need to
2016             // check whether we were currently skipping the subpattern. If not, we
2017             // can backtrack into them, if we were we need to either backtrack back
2018             // out of the start of the parentheses, or jump back to the forwards
2019             // matching start, depending of whether the match is Greedy or NonGreedy.
2020             case OpParenthesesSubpatternOnceBegin: {
2021                 PatternTerm* term = op.m_term;
2022                 ASSERT(term->quantityCount == 1);
2023
2024                 // We only need to backtrack to thispoint if capturing or greedy.
2025                 if (term->capture() || term->quantityType == QuantifierGreedy) {
2026                     m_backtrackingState.link(this);
2027
2028                     // If capturing, clear the capture (we only need to reset start).
2029                     if (term->capture())
2030                         store32(TrustedImm32(-1), Address(output, (term->parentheses.subpatternId << 1) * sizeof(int)));
2031
2032                     // If Greedy, jump to the end.
2033                     if (term->quantityType == QuantifierGreedy) {
2034                         // Clear the flag in the stackframe indicating we ran through the subpattern.
2035                         unsigned parenthesesFrameLocation = term->frameLocation;
2036                         storeToFrame(TrustedImm32(-1), parenthesesFrameLocation);
2037                         // Jump to after the parentheses, skipping the subpattern.
2038                         jump(m_ops[op.m_nextOp].m_reentry);
2039                         // A backtrack from after the parentheses, when skipping the subpattern,
2040                         // will jump back to here.
2041                         op.m_jumps.link(this);
2042                     }
2043
2044                     m_backtrackingState.fallthrough();
2045                 }
2046                 break;
2047             }
2048             case OpParenthesesSubpatternOnceEnd: {
2049                 PatternTerm* term = op.m_term;
2050
2051                 if (term->quantityType != QuantifierFixedCount) {
2052                     m_backtrackingState.link(this);
2053
2054                     // Check whether we should backtrack back into the parentheses, or if we
2055                     // are currently in a state where we had skipped over the subpattern
2056                     // (in which case the flag value on the stack will be -1).
2057                     unsigned parenthesesFrameLocation = term->frameLocation;
2058                     Jump hadSkipped = branch32(Equal, Address(stackPointerRegister, parenthesesFrameLocation * sizeof(void*)), TrustedImm32(-1));
2059
2060                     if (term->quantityType == QuantifierGreedy) {
2061                         // For Greedy parentheses, we skip after having already tried going
2062                         // through the subpattern, so if we get here we're done.
2063                         YarrOp& beginOp = m_ops[op.m_previousOp];
2064                         beginOp.m_jumps.append(hadSkipped);
2065                     } else {
2066                         // For NonGreedy parentheses, we try skipping the subpattern first,
2067                         // so if we get here we need to try running through the subpattern
2068                         // next. Jump back to the start of the parentheses in the forwards
2069                         // matching path.
2070                         ASSERT(term->quantityType == QuantifierNonGreedy);
2071                         YarrOp& beginOp = m_ops[op.m_previousOp];
2072                         hadSkipped.linkTo(beginOp.m_reentry, this);
2073                     }
2074
2075                     m_backtrackingState.fallthrough();
2076                 }
2077
2078                 m_backtrackingState.append(op.m_jumps);
2079                 break;
2080             }
2081
2082             // OpParenthesesSubpatternTerminalBegin/End
2083             //
2084             // Terminal subpatterns will always match - there is nothing after them to
2085             // force a backtrack, and they have a minimum count of 0, and as such will
2086             // always produce an acceptable result.
2087             case OpParenthesesSubpatternTerminalBegin: {
2088                 // We will backtrack to this point once the subpattern cannot match any
2089                 // more. Since no match is accepted as a successful match (we are Greedy
2090                 // quantified with a minimum of zero) jump back to the forwards matching
2091                 // path at the end.
2092                 YarrOp& endOp = m_ops[op.m_nextOp];
2093                 m_backtrackingState.linkTo(endOp.m_reentry, this);
2094                 break;
2095             }
2096             case OpParenthesesSubpatternTerminalEnd:
2097                 // We should never be backtracking to here (hence the 'terminal' in the name).
2098                 ASSERT(m_backtrackingState.isEmpty());
2099                 m_backtrackingState.append(op.m_jumps);
2100                 break;
2101
2102             // OpParentheticalAssertionBegin/End
2103             case OpParentheticalAssertionBegin: {
2104                 PatternTerm* term = op.m_term;
2105                 YarrOp& endOp = m_ops[op.m_nextOp];
2106
2107                 // We need to handle the backtracks upon backtracking back out
2108                 // of a parenthetical assertion if either we need to correct
2109                 // the input index, or the assertion was inverted.
2110                 if (op.m_checkAdjust || term->invert()) {
2111                      m_backtrackingState.link(this);
2112
2113                     if (op.m_checkAdjust)
2114                         add32(Imm32(op.m_checkAdjust), index);
2115
2116                     // In an inverted assertion failure to match the subpattern
2117                     // is treated as a successful match - jump to the end of the
2118                     // subpattern. We already have adjusted the input position
2119                     // back to that before the assertion, which is correct.
2120                     if (term->invert())
2121                         jump(endOp.m_reentry);
2122
2123                     m_backtrackingState.fallthrough();
2124                 }
2125
2126                 // The End node's jump list will contain any backtracks into
2127                 // the end of the assertion. Also, if inverted, we will have
2128                 // added the failure caused by a successful match to this.
2129                 m_backtrackingState.append(endOp.m_jumps);
2130
2131                 m_checked += op.m_checkAdjust;
2132                 break;
2133             }
2134             case OpParentheticalAssertionEnd: {
2135                 // FIXME: We should really be clearing any nested subpattern
2136                 // matches on bailing out from after the pattern. Firefox has
2137                 // this bug too (presumably because they use YARR!)
2138
2139                 // Never backtrack into an assertion; later failures bail to before the begin.
2140                 m_backtrackingState.takeBacktracksToJumpList(op.m_jumps, this);
2141
2142                 YarrOp& lastOp = m_ops[op.m_previousOp];
2143                 m_checked -= lastOp.m_checkAdjust;
2144                 break;
2145             }
2146
2147             case OpMatchFailed:
2148                 break;
2149             }
2150
2151         } while (opIndex);
2152     }
2153
2154     // Compilation methods:
2155     // ====================
2156
2157     // opCompileParenthesesSubpattern
2158     // Emits ops for a subpattern (set of parentheses). These consist
2159     // of a set of alternatives wrapped in an outer set of nodes for
2160     // the parentheses.
2161     // Supported types of parentheses are 'Once' (quantityCount == 1)
2162     // and 'Terminal' (non-capturing parentheses quantified as greedy
2163     // and infinite).
2164     // Alternatives will use the 'Simple' set of ops if either the
2165     // subpattern is terminal (in which case we will never need to
2166     // backtrack), or if the subpattern only contains one alternative.
2167     void opCompileParenthesesSubpattern(PatternTerm* term)
2168     {
2169         YarrOpCode parenthesesBeginOpCode;
2170         YarrOpCode parenthesesEndOpCode;
2171         YarrOpCode alternativeBeginOpCode = OpSimpleNestedAlternativeBegin;
2172         YarrOpCode alternativeNextOpCode = OpSimpleNestedAlternativeNext;
2173         YarrOpCode alternativeEndOpCode = OpSimpleNestedAlternativeEnd;
2174
2175         // We can currently only compile quantity 1 subpatterns that are
2176         // not copies. We generate a copy in the case of a range quantifier,
2177         // e.g. /(?:x){3,9}/, or /(?:x)+/ (These are effectively expanded to
2178         // /(?:x){3,3}(?:x){0,6}/ and /(?:x)(?:x)*/ repectively). The problem
2179         // comes where the subpattern is capturing, in which case we would
2180         // need to restore the capture from the first subpattern upon a
2181         // failure in the second.
2182         if (term->quantityCount == 1 && !term->parentheses.isCopy) {
2183             // Select the 'Once' nodes.
2184             parenthesesBeginOpCode = OpParenthesesSubpatternOnceBegin;
2185             parenthesesEndOpCode = OpParenthesesSubpatternOnceEnd;
2186
2187             // If there is more than one alternative we cannot use the 'simple' nodes.
2188             if (term->parentheses.disjunction->m_alternatives.size() != 1) {
2189                 alternativeBeginOpCode = OpNestedAlternativeBegin;
2190                 alternativeNextOpCode = OpNestedAlternativeNext;
2191                 alternativeEndOpCode = OpNestedAlternativeEnd;
2192             }
2193         } else if (term->parentheses.isTerminal) {
2194             // Select the 'Terminal' nodes.
2195             parenthesesBeginOpCode = OpParenthesesSubpatternTerminalBegin;
2196             parenthesesEndOpCode = OpParenthesesSubpatternTerminalEnd;
2197         } else {
2198             // This subpattern is not supported by the JIT.
2199             m_shouldFallBack = true;
2200             return;
2201         }
2202
2203         size_t parenBegin = m_ops.size();
2204         m_ops.append(parenthesesBeginOpCode);
2205
2206         m_ops.append(alternativeBeginOpCode);
2207         m_ops.last().m_previousOp = notFound;
2208         m_ops.last().m_term = term;
2209         Vector<PatternAlternative*>& alternatives =  term->parentheses.disjunction->m_alternatives;
2210         for (unsigned i = 0; i < alternatives.size(); ++i) {
2211             size_t lastOpIndex = m_ops.size() - 1;
2212
2213             PatternAlternative* nestedAlternative = alternatives[i];
2214             opCompileAlternative(nestedAlternative);
2215
2216             size_t thisOpIndex = m_ops.size();
2217             m_ops.append(YarrOp(alternativeNextOpCode));
2218
2219             YarrOp& lastOp = m_ops[lastOpIndex];
2220             YarrOp& thisOp = m_ops[thisOpIndex];
2221
2222             lastOp.m_alternative = nestedAlternative;
2223             lastOp.m_nextOp = thisOpIndex;
2224             thisOp.m_previousOp = lastOpIndex;
2225             thisOp.m_term = term;
2226         }
2227         YarrOp& lastOp = m_ops.last();
2228         ASSERT(lastOp.m_op == alternativeNextOpCode);
2229         lastOp.m_op = alternativeEndOpCode;
2230         lastOp.m_alternative = 0;
2231         lastOp.m_nextOp = notFound;
2232
2233         size_t parenEnd = m_ops.size();
2234         m_ops.append(parenthesesEndOpCode);
2235
2236         m_ops[parenBegin].m_term = term;
2237         m_ops[parenBegin].m_previousOp = notFound;
2238         m_ops[parenBegin].m_nextOp = parenEnd;
2239         m_ops[parenEnd].m_term = term;
2240         m_ops[parenEnd].m_previousOp = parenBegin;
2241         m_ops[parenEnd].m_nextOp = notFound;
2242     }
2243
2244     // opCompileParentheticalAssertion
2245     // Emits ops for a parenthetical assertion. These consist of an
2246     // OpSimpleNestedAlternativeBegin/Next/End set of nodes wrapping
2247     // the alternatives, with these wrapped by an outer pair of
2248     // OpParentheticalAssertionBegin/End nodes.
2249     // We can always use the OpSimpleNestedAlternative nodes in the
2250     // case of parenthetical assertions since these only ever match
2251     // once, and will never backtrack back into the assertion.
2252     void opCompileParentheticalAssertion(PatternTerm* term)
2253     {
2254         size_t parenBegin = m_ops.size();
2255         m_ops.append(OpParentheticalAssertionBegin);
2256
2257         m_ops.append(OpSimpleNestedAlternativeBegin);
2258         m_ops.last().m_previousOp = notFound;
2259         m_ops.last().m_term = term;
2260         Vector<PatternAlternative*>& alternatives =  term->parentheses.disjunction->m_alternatives;
2261         for (unsigned i = 0; i < alternatives.size(); ++i) {
2262             size_t lastOpIndex = m_ops.size() - 1;
2263
2264             PatternAlternative* nestedAlternative = alternatives[i];
2265             opCompileAlternative(nestedAlternative);
2266
2267             size_t thisOpIndex = m_ops.size();
2268             m_ops.append(YarrOp(OpSimpleNestedAlternativeNext));
2269
2270             YarrOp& lastOp = m_ops[lastOpIndex];
2271             YarrOp& thisOp = m_ops[thisOpIndex];
2272
2273             lastOp.m_alternative = nestedAlternative;
2274             lastOp.m_nextOp = thisOpIndex;
2275             thisOp.m_previousOp = lastOpIndex;
2276             thisOp.m_term = term;
2277         }
2278         YarrOp& lastOp = m_ops.last();
2279         ASSERT(lastOp.m_op == OpSimpleNestedAlternativeNext);
2280         lastOp.m_op = OpSimpleNestedAlternativeEnd;
2281         lastOp.m_alternative = 0;
2282         lastOp.m_nextOp = notFound;
2283
2284         size_t parenEnd = m_ops.size();
2285         m_ops.append(OpParentheticalAssertionEnd);
2286
2287         m_ops[parenBegin].m_term = term;
2288         m_ops[parenBegin].m_previousOp = notFound;
2289         m_ops[parenBegin].m_nextOp = parenEnd;
2290         m_ops[parenEnd].m_term = term;
2291         m_ops[parenEnd].m_previousOp = parenBegin;
2292         m_ops[parenEnd].m_nextOp = notFound;
2293     }
2294
2295     // opCompileAlternative
2296     // Called to emit nodes for all terms in an alternative.
2297     void opCompileAlternative(PatternAlternative* alternative)
2298     {
2299         optimizeAlternative(alternative);
2300
2301         for (unsigned i = 0; i < alternative->m_terms.size(); ++i) {
2302             PatternTerm* term = &alternative->m_terms[i];
2303
2304             switch (term->type) {
2305             case PatternTerm::TypeParenthesesSubpattern:
2306                 opCompileParenthesesSubpattern(term);
2307                 break;
2308
2309             case PatternTerm::TypeParentheticalAssertion:
2310                 opCompileParentheticalAssertion(term);
2311                 break;
2312
2313             default:
2314                 m_ops.append(term);
2315             }
2316         }
2317     }
2318
2319     // opCompileBody
2320     // This method compiles the body disjunction of the regular expression.
2321     // The body consists of two sets of alternatives - zero or more 'once
2322     // through' (BOL anchored) alternatives, followed by zero or more
2323     // repeated alternatives.
2324     // For each of these two sets of alteratives, if not empty they will be
2325     // wrapped in a set of OpBodyAlternativeBegin/Next/End nodes (with the
2326     // 'begin' node referencing the first alternative, and 'next' nodes
2327     // referencing any further alternatives. The begin/next/end nodes are
2328     // linked together in a doubly linked list. In the case of repeating
2329     // alternatives, the end node is also linked back to the beginning.
2330     // If no repeating alternatives exist, then a OpMatchFailed node exists
2331     // to return the failing result.
2332     void opCompileBody(PatternDisjunction* disjunction)
2333     {
2334         Vector<PatternAlternative*>& alternatives =  disjunction->m_alternatives;
2335         size_t currentAlternativeIndex = 0;
2336
2337         // Emit the 'once through' alternatives.
2338         if (alternatives.size() && alternatives[0]->onceThrough()) {
2339             m_ops.append(YarrOp(OpBodyAlternativeBegin));
2340             m_ops.last().m_previousOp = notFound;
2341
2342             do {
2343                 size_t lastOpIndex = m_ops.size() - 1;
2344                 PatternAlternative* alternative = alternatives[currentAlternativeIndex];
2345                 opCompileAlternative(alternative);
2346
2347                 size_t thisOpIndex = m_ops.size();
2348                 m_ops.append(YarrOp(OpBodyAlternativeNext));
2349
2350                 YarrOp& lastOp = m_ops[lastOpIndex];
2351                 YarrOp& thisOp = m_ops[thisOpIndex];
2352
2353                 lastOp.m_alternative = alternative;
2354                 lastOp.m_nextOp = thisOpIndex;
2355                 thisOp.m_previousOp = lastOpIndex;
2356                 
2357                 ++currentAlternativeIndex;
2358             } while (currentAlternativeIndex < alternatives.size() && alternatives[currentAlternativeIndex]->onceThrough());
2359
2360             YarrOp& lastOp = m_ops.last();
2361
2362             ASSERT(lastOp.m_op == OpBodyAlternativeNext);
2363             lastOp.m_op = OpBodyAlternativeEnd;
2364             lastOp.m_alternative = 0;
2365             lastOp.m_nextOp = notFound;
2366         }
2367
2368         if (currentAlternativeIndex == alternatives.size()) {
2369             m_ops.append(YarrOp(OpMatchFailed));
2370             return;
2371         }
2372
2373         // Emit the repeated alternatives.
2374         size_t repeatLoop = m_ops.size();
2375         m_ops.append(YarrOp(OpBodyAlternativeBegin));
2376         m_ops.last().m_previousOp = notFound;
2377         do {
2378             size_t lastOpIndex = m_ops.size() - 1;
2379             PatternAlternative* alternative = alternatives[currentAlternativeIndex];
2380             ASSERT(!alternative->onceThrough());
2381             opCompileAlternative(alternative);
2382
2383             size_t thisOpIndex = m_ops.size();
2384             m_ops.append(YarrOp(OpBodyAlternativeNext));
2385
2386             YarrOp& lastOp = m_ops[lastOpIndex];
2387             YarrOp& thisOp = m_ops[thisOpIndex];
2388
2389             lastOp.m_alternative = alternative;
2390             lastOp.m_nextOp = thisOpIndex;
2391             thisOp.m_previousOp = lastOpIndex;
2392             
2393             ++currentAlternativeIndex;
2394         } while (currentAlternativeIndex < alternatives.size());
2395         YarrOp& lastOp = m_ops.last();
2396         ASSERT(lastOp.m_op == OpBodyAlternativeNext);
2397         lastOp.m_op = OpBodyAlternativeEnd;
2398         lastOp.m_alternative = 0;
2399         lastOp.m_nextOp = repeatLoop;
2400     }
2401
2402     void generateEnter()
2403     {
2404 #if CPU(X86_64)
2405         push(X86Registers::ebp);
2406         move(stackPointerRegister, X86Registers::ebp);
2407         push(X86Registers::ebx);
2408 #elif CPU(X86)
2409         push(X86Registers::ebp);
2410         move(stackPointerRegister, X86Registers::ebp);
2411         // TODO: do we need spill registers to fill the output pointer if there are no sub captures?
2412         push(X86Registers::ebx);
2413         push(X86Registers::edi);
2414         push(X86Registers::esi);
2415         // load output into edi (2 = saved ebp + return address).
2416     #if COMPILER(MSVC)
2417         loadPtr(Address(X86Registers::ebp, 2 * sizeof(void*)), input);
2418         loadPtr(Address(X86Registers::ebp, 3 * sizeof(void*)), index);
2419         loadPtr(Address(X86Registers::ebp, 4 * sizeof(void*)), length);
2420         loadPtr(Address(X86Registers::ebp, 5 * sizeof(void*)), output);
2421     #else
2422         loadPtr(Address(X86Registers::ebp, 2 * sizeof(void*)), output);
2423     #endif
2424 #elif CPU(ARM)
2425         push(ARMRegisters::r4);
2426         push(ARMRegisters::r5);
2427         push(ARMRegisters::r6);
2428 #if CPU(ARM_TRADITIONAL)
2429         push(ARMRegisters::r8); // scratch register
2430 #endif
2431         move(ARMRegisters::r3, output);
2432 #elif CPU(SH4)
2433         push(SH4Registers::r11);
2434         push(SH4Registers::r13);
2435 #elif CPU(MIPS)
2436         // Do nothing.
2437 #endif
2438     }
2439
2440     void generateReturn()
2441     {
2442 #if CPU(X86_64)
2443         pop(X86Registers::ebx);
2444         pop(X86Registers::ebp);
2445 #elif CPU(X86)
2446         pop(X86Registers::esi);
2447         pop(X86Registers::edi);
2448         pop(X86Registers::ebx);
2449         pop(X86Registers::ebp);
2450 #elif CPU(ARM)
2451 #if CPU(ARM_TRADITIONAL)
2452         pop(ARMRegisters::r8); // scratch register
2453 #endif
2454         pop(ARMRegisters::r6);
2455         pop(ARMRegisters::r5);
2456         pop(ARMRegisters::r4);
2457 #elif CPU(SH4)
2458         pop(SH4Registers::r13);
2459         pop(SH4Registers::r11);
2460 #elif CPU(MIPS)
2461         // Do nothing
2462 #endif
2463         ret();
2464     }
2465
2466 public:
2467     YarrGenerator(YarrPattern& pattern, YarrCharSize charSize)
2468         : m_pattern(pattern)
2469         , m_charSize(charSize)
2470         , m_charScale(m_charSize == Char8 ? TimesOne: TimesTwo)
2471         , m_shouldFallBack(false)
2472         , m_checked(0)
2473     {
2474     }
2475
2476     void compile(JSGlobalData* globalData, YarrCodeBlock& jitObject)
2477     {
2478         generateEnter();
2479
2480         if (!m_pattern.m_body->m_hasFixedSize)
2481             store32(index, Address(output));
2482
2483         if (m_pattern.m_body->m_callFrameSize)
2484             subPtr(Imm32(m_pattern.m_body->m_callFrameSize * sizeof(void*)), stackPointerRegister);
2485
2486         // Compile the pattern to the internal 'YarrOp' representation.
2487         opCompileBody(m_pattern.m_body);
2488
2489         // If we encountered anything we can't handle in the JIT code
2490         // (e.g. backreferences) then return early.
2491         if (m_shouldFallBack) {
2492             jitObject.setFallBack(true);
2493             return;
2494         }
2495
2496         generate();
2497         backtrack();
2498
2499         // Link & finalize the code.
2500         LinkBuffer linkBuffer(*globalData, this);
2501         m_backtrackingState.linkDataLabels(linkBuffer);
2502         if (m_charSize == Char8)
2503             jitObject.set8BitCode(linkBuffer.finalizeCode());
2504         else
2505             jitObject.set16BitCode(linkBuffer.finalizeCode());
2506         jitObject.setFallBack(m_shouldFallBack);
2507     }
2508
2509 private:
2510     YarrPattern& m_pattern;
2511
2512     YarrCharSize m_charSize;
2513
2514     Scale m_charScale;
2515
2516     // Used to detect regular expression constructs that are not currently
2517     // supported in the JIT; fall back to the interpreter when this is detected.
2518     bool m_shouldFallBack;
2519
2520     // The regular expression expressed as a linear sequence of operations.
2521     Vector<YarrOp, 128> m_ops;
2522
2523     // This records the current input offset being applied due to the current
2524     // set of alternatives we are nested within. E.g. when matching the
2525     // character 'b' within the regular expression /abc/, we will know that
2526     // the minimum size for the alternative is 3, checked upon entry to the
2527     // alternative, and that 'b' is at offset 1 from the start, and as such
2528     // when matching 'b' we need to apply an offset of -2 to the load.
2529     //
2530     // FIXME: This should go away. Rather than tracking this value throughout
2531     // code generation, we should gather this information up front & store it
2532     // on the YarrOp structure.
2533     int m_checked;
2534
2535     // This class records state whilst generating the backtracking path of code.
2536     BacktrackingState m_backtrackingState;
2537 };
2538
2539 void jitCompile(YarrPattern& pattern, YarrCharSize charSize, JSGlobalData* globalData, YarrCodeBlock& jitObject)
2540 {
2541     YarrGenerator(pattern, charSize).compile(globalData, jitObject);
2542 }
2543
2544 int execute(YarrCodeBlock& jitObject, const LChar* input, unsigned start, unsigned length, int* output)
2545 {
2546     return jitObject.execute(input, start, length, output);
2547 }
2548
2549 int execute(YarrCodeBlock& jitObject, const UChar* input, unsigned start, unsigned length, int* output)
2550 {
2551     return jitObject.execute(input, start, length, output);
2552 }
2553
2554 }}
2555
2556 #endif