2011-01-21 Michael Saboff <msaboff@apple.com>
[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 "JSGlobalData.h"
31 #include "LinkBuffer.h"
32 #include "MacroAssembler.h"
33 #include "Yarr.h"
34
35 #if ENABLE(YARR_JIT)
36
37 using namespace WTF;
38
39 namespace JSC { namespace Yarr {
40
41 class YarrGenerator : private MacroAssembler {
42     friend void jitCompile(JSGlobalData*, YarrCodeBlock& jitObject, const UString& pattern, unsigned& numSubpatterns, const char*& error, bool ignoreCase, bool multiline);
43
44 #if CPU(ARM)
45     static const RegisterID input = ARMRegisters::r0;
46     static const RegisterID index = ARMRegisters::r1;
47     static const RegisterID length = ARMRegisters::r2;
48     static const RegisterID output = ARMRegisters::r4;
49
50     static const RegisterID regT0 = ARMRegisters::r5;
51     static const RegisterID regT1 = ARMRegisters::r6;
52
53     static const RegisterID returnRegister = ARMRegisters::r0;
54 #elif CPU(MIPS)
55     static const RegisterID input = MIPSRegisters::a0;
56     static const RegisterID index = MIPSRegisters::a1;
57     static const RegisterID length = MIPSRegisters::a2;
58     static const RegisterID output = MIPSRegisters::a3;
59
60     static const RegisterID regT0 = MIPSRegisters::t4;
61     static const RegisterID regT1 = MIPSRegisters::t5;
62
63     static const RegisterID returnRegister = MIPSRegisters::v0;
64 #elif CPU(X86)
65     static const RegisterID input = X86Registers::eax;
66     static const RegisterID index = X86Registers::edx;
67     static const RegisterID length = X86Registers::ecx;
68     static const RegisterID output = X86Registers::edi;
69
70     static const RegisterID regT0 = X86Registers::ebx;
71     static const RegisterID regT1 = X86Registers::esi;
72
73     static const RegisterID returnRegister = X86Registers::eax;
74 #elif CPU(X86_64)
75     static const RegisterID input = X86Registers::edi;
76     static const RegisterID index = X86Registers::esi;
77     static const RegisterID length = X86Registers::edx;
78     static const RegisterID output = X86Registers::ecx;
79
80     static const RegisterID regT0 = X86Registers::eax;
81     static const RegisterID regT1 = X86Registers::ebx;
82
83     static const RegisterID returnRegister = X86Registers::eax;
84 #endif
85
86     void optimizeAlternative(PatternAlternative* alternative)
87     {
88         if (!alternative->m_terms.size())
89             return;
90
91         for (unsigned i = 0; i < alternative->m_terms.size() - 1; ++i) {
92             PatternTerm& term = alternative->m_terms[i];
93             PatternTerm& nextTerm = alternative->m_terms[i + 1];
94
95             if ((term.type == PatternTerm::TypeCharacterClass)
96                 && (term.quantityType == QuantifierFixedCount)
97                 && (nextTerm.type == PatternTerm::TypePatternCharacter)
98                 && (nextTerm.quantityType == QuantifierFixedCount)) {
99                 PatternTerm termCopy = term;
100                 alternative->m_terms[i] = nextTerm;
101                 alternative->m_terms[i + 1] = termCopy;
102             }
103         }
104     }
105
106     void matchCharacterClassRange(RegisterID character, JumpList& failures, JumpList& matchDest, const CharacterRange* ranges, unsigned count, unsigned* matchIndex, const UChar* matches, unsigned matchCount)
107     {
108         do {
109             // pick which range we're going to generate
110             int which = count >> 1;
111             char lo = ranges[which].begin;
112             char hi = ranges[which].end;
113
114             // check if there are any ranges or matches below lo.  If not, just jl to failure -
115             // if there is anything else to check, check that first, if it falls through jmp to failure.
116             if ((*matchIndex < matchCount) && (matches[*matchIndex] < lo)) {
117                 Jump loOrAbove = branch32(GreaterThanOrEqual, character, Imm32((unsigned short)lo));
118
119                 // generate code for all ranges before this one
120                 if (which)
121                     matchCharacterClassRange(character, failures, matchDest, ranges, which, matchIndex, matches, matchCount);
122
123                 while ((*matchIndex < matchCount) && (matches[*matchIndex] < lo)) {
124                     matchDest.append(branch32(Equal, character, Imm32((unsigned short)matches[*matchIndex])));
125                     ++*matchIndex;
126                 }
127                 failures.append(jump());
128
129                 loOrAbove.link(this);
130             } else if (which) {
131                 Jump loOrAbove = branch32(GreaterThanOrEqual, character, Imm32((unsigned short)lo));
132
133                 matchCharacterClassRange(character, failures, matchDest, ranges, which, matchIndex, matches, matchCount);
134                 failures.append(jump());
135
136                 loOrAbove.link(this);
137             } else
138                 failures.append(branch32(LessThan, character, Imm32((unsigned short)lo)));
139
140             while ((*matchIndex < matchCount) && (matches[*matchIndex] <= hi))
141                 ++*matchIndex;
142
143             matchDest.append(branch32(LessThanOrEqual, character, Imm32((unsigned short)hi)));
144             // fall through to here, the value is above hi.
145
146             // shuffle along & loop around if there are any more matches to handle.
147             unsigned next = which + 1;
148             ranges += next;
149             count -= next;
150         } while (count);
151     }
152
153     void matchCharacterClass(RegisterID character, JumpList& matchDest, const CharacterClass* charClass)
154     {
155         if (charClass->m_table) {
156             ExtendedAddress tableEntry(character, reinterpret_cast<intptr_t>(charClass->m_table->m_table));
157             matchDest.append(branchTest8(charClass->m_table->m_inverted ? Zero : NonZero, tableEntry));
158             return;
159         }
160         Jump unicodeFail;
161         if (charClass->m_matchesUnicode.size() || charClass->m_rangesUnicode.size()) {
162             Jump isAscii = branch32(LessThanOrEqual, character, Imm32(0x7f));
163
164             if (charClass->m_matchesUnicode.size()) {
165                 for (unsigned i = 0; i < charClass->m_matchesUnicode.size(); ++i) {
166                     UChar ch = charClass->m_matchesUnicode[i];
167                     matchDest.append(branch32(Equal, character, Imm32(ch)));
168                 }
169             }
170
171             if (charClass->m_rangesUnicode.size()) {
172                 for (unsigned i = 0; i < charClass->m_rangesUnicode.size(); ++i) {
173                     UChar lo = charClass->m_rangesUnicode[i].begin;
174                     UChar hi = charClass->m_rangesUnicode[i].end;
175
176                     Jump below = branch32(LessThan, character, Imm32(lo));
177                     matchDest.append(branch32(LessThanOrEqual, character, Imm32(hi)));
178                     below.link(this);
179                 }
180             }
181
182             unicodeFail = jump();
183             isAscii.link(this);
184         }
185
186         if (charClass->m_ranges.size()) {
187             unsigned matchIndex = 0;
188             JumpList failures;
189             matchCharacterClassRange(character, failures, matchDest, charClass->m_ranges.begin(), charClass->m_ranges.size(), &matchIndex, charClass->m_matches.begin(), charClass->m_matches.size());
190             while (matchIndex < charClass->m_matches.size())
191                 matchDest.append(branch32(Equal, character, Imm32((unsigned short)charClass->m_matches[matchIndex++])));
192
193             failures.link(this);
194         } else if (charClass->m_matches.size()) {
195             // optimization: gather 'a','A' etc back together, can mask & test once.
196             Vector<char> matchesAZaz;
197
198             for (unsigned i = 0; i < charClass->m_matches.size(); ++i) {
199                 char ch = charClass->m_matches[i];
200                 if (m_pattern.m_ignoreCase) {
201                     if (isASCIILower(ch)) {
202                         matchesAZaz.append(ch);
203                         continue;
204                     }
205                     if (isASCIIUpper(ch))
206                         continue;
207                 }
208                 matchDest.append(branch32(Equal, character, Imm32((unsigned short)ch)));
209             }
210
211             if (unsigned countAZaz = matchesAZaz.size()) {
212                 or32(Imm32(32), character);
213                 for (unsigned i = 0; i < countAZaz; ++i)
214                     matchDest.append(branch32(Equal, character, Imm32(matchesAZaz[i])));
215             }
216         }
217
218         if (charClass->m_matchesUnicode.size() || charClass->m_rangesUnicode.size())
219             unicodeFail.link(this);
220     }
221
222     // Jumps if input not available; will have (incorrectly) incremented already!
223     Jump jumpIfNoAvailableInput(unsigned countToCheck)
224     {
225         add32(Imm32(countToCheck), index);
226         return branch32(Above, index, length);
227     }
228
229     Jump jumpIfAvailableInput(unsigned countToCheck)
230     {
231         add32(Imm32(countToCheck), index);
232         return branch32(BelowOrEqual, index, length);
233     }
234
235     Jump checkInput()
236     {
237         return branch32(BelowOrEqual, index, length);
238     }
239
240     Jump atEndOfInput()
241     {
242         return branch32(Equal, index, length);
243     }
244
245     Jump notAtEndOfInput()
246     {
247         return branch32(NotEqual, index, length);
248     }
249
250     Jump jumpIfCharEquals(UChar ch, int inputPosition)
251     {
252         return branch16(Equal, BaseIndex(input, index, TimesTwo, inputPosition * sizeof(UChar)), Imm32(ch));
253     }
254
255     Jump jumpIfCharNotEquals(UChar ch, int inputPosition)
256     {
257         return branch16(NotEqual, BaseIndex(input, index, TimesTwo, inputPosition * sizeof(UChar)), Imm32(ch));
258     }
259
260     void readCharacter(int inputPosition, RegisterID reg)
261     {
262         load16(BaseIndex(input, index, TimesTwo, inputPosition * sizeof(UChar)), reg);
263     }
264
265     void storeToFrame(RegisterID reg, unsigned frameLocation)
266     {
267         poke(reg, frameLocation);
268     }
269
270     void storeToFrame(Imm32 imm, unsigned frameLocation)
271     {
272         poke(imm, frameLocation);
273     }
274
275     DataLabelPtr storeToFrameWithPatch(unsigned frameLocation)
276     {
277         return storePtrWithPatch(ImmPtr(0), Address(stackPointerRegister, frameLocation * sizeof(void*)));
278     }
279
280     void loadFromFrame(unsigned frameLocation, RegisterID reg)
281     {
282         peek(reg, frameLocation);
283     }
284
285     void loadFromFrameAndJump(unsigned frameLocation)
286     {
287         jump(Address(stackPointerRegister, frameLocation * sizeof(void*)));
288     }
289
290     struct IndirectJumpEntry {
291         IndirectJumpEntry(int32_t stackOffset)
292             : m_stackOffset(stackOffset)
293         {
294         }
295
296         IndirectJumpEntry(int32_t stackOffset, Jump jump)
297             : m_stackOffset(stackOffset)
298         {
299             addJump(jump);
300         }
301
302         IndirectJumpEntry(int32_t stackOffset, DataLabelPtr dataLabel)
303         : m_stackOffset(stackOffset)
304         {
305             addDataLabel(dataLabel);
306         }
307
308         void addJump(Jump jump)
309         {
310             m_relJumps.append(jump);
311         }
312         
313         void addDataLabel(DataLabelPtr dataLabel)
314         {
315             m_dataLabelPtrVector.append(dataLabel);
316         }
317
318         int32_t m_stackOffset;
319         JumpList m_relJumps;
320         Vector<DataLabelPtr, 16> m_dataLabelPtrVector;
321     };
322
323     struct AlternativeBacktrackRecord {
324         DataLabelPtr dataLabel;
325         Label backtrackLocation;
326
327         AlternativeBacktrackRecord(DataLabelPtr dataLabel, Label backtrackLocation)
328             : dataLabel(dataLabel)
329             , backtrackLocation(backtrackLocation)
330         {
331         }
332     };
333
334     struct ParenthesesTail;
335     struct TermGenerationState;
336
337     struct GenerationState {
338         typedef HashMap<int, IndirectJumpEntry*, WTF::IntHash<uint32_t>, UnsignedWithZeroKeyHashTraits<uint32_t> > IndirectJumpHashMap;
339
340         GenerationState()
341             : m_parenNestingLevel(0)
342         {
343         }
344
345         void addIndirectJumpEntry(int32_t stackOffset, Jump jump)
346         {
347             IndirectJumpHashMap::iterator result = m_indirectJumpMap.find(stackOffset);
348
349             ASSERT(stackOffset >= 0);
350
351             uint32_t offset = static_cast<uint32_t>(stackOffset);
352
353             if (result == m_indirectJumpMap.end())
354                 m_indirectJumpMap.add(offset, new IndirectJumpEntry(stackOffset, jump));
355             else
356                 result->second->addJump(jump);
357         }
358
359         void addIndirectJumpEntry(int32_t stackOffset, JumpList jumps)
360         {
361             JumpList::JumpVector jumpVector = jumps.jumps();
362             size_t size = jumpVector.size();
363             for (size_t i = 0; i < size; ++i)
364                 addIndirectJumpEntry(stackOffset, jumpVector[i]);
365
366             jumps.empty();
367         }
368
369         void addIndirectJumpEntry(int32_t stackOffset, DataLabelPtr dataLabel)
370         {
371             IndirectJumpHashMap::iterator result = m_indirectJumpMap.find(stackOffset);
372
373             ASSERT(stackOffset >= 0);
374
375             uint32_t offset = static_cast<uint32_t>(stackOffset);
376
377             if (result == m_indirectJumpMap.end())
378                 m_indirectJumpMap.add(offset, new IndirectJumpEntry(stackOffset, dataLabel));
379             else
380                 result->second->addDataLabel(dataLabel);
381         }
382
383         void emitIndirectJumpTable(MacroAssembler* masm)
384         {
385             for (IndirectJumpHashMap::iterator iter = m_indirectJumpMap.begin(); iter != m_indirectJumpMap.end(); ++iter) {
386                 IndirectJumpEntry* indJumpEntry = iter->second;
387                 size_t size = indJumpEntry->m_dataLabelPtrVector.size();
388                 if (size) {
389                     // Link any associated DataLabelPtr's with indirect jump via label
390                     Label hereLabel = masm->label();
391                     for (size_t i = 0; i < size; ++i)
392                         m_backtrackRecords.append(AlternativeBacktrackRecord(indJumpEntry->m_dataLabelPtrVector[i], hereLabel));
393                 }
394                 indJumpEntry->m_relJumps.link(masm);
395                 masm->jump(Address(stackPointerRegister, indJumpEntry->m_stackOffset));
396                 delete indJumpEntry;
397             }
398         }
399
400         void incrementParenNestingLevel()
401         {
402             ++m_parenNestingLevel;
403         }
404
405         void decrementParenNestingLevel()
406         {
407             --m_parenNestingLevel;
408         }
409
410         ParenthesesTail* addParenthesesTail(PatternTerm& term, ParenthesesTail* nextOuterParenTail)
411         {
412             ParenthesesTail* parenthesesTail = new ParenthesesTail(term, m_parenNestingLevel, nextOuterParenTail);
413             m_parenTails.append(parenthesesTail);
414             m_parenTailsForIteration.append(parenthesesTail);
415
416             return parenthesesTail;
417         }
418
419         void emitParenthesesTail(YarrGenerator* generator)
420         {
421             unsigned vectorSize = m_parenTails.size();
422             bool priorBacktrackFallThrough = false;
423
424             // Emit in reverse order so parentTail N can fall through to N-1
425             for (unsigned index = vectorSize; index > 0; --index) {
426                 JumpList jumpsToNext;
427                 priorBacktrackFallThrough = m_parenTails[index-1].get()->generateCode(generator, jumpsToNext, priorBacktrackFallThrough, index > 1);
428                 if (index > 1)
429                     jumpsToNext.linkTo(generator->label(), generator);
430                 else
431                     addJumpsToNextInteration(jumpsToNext);
432             }
433             m_parenTails.clear();
434         }
435
436         void addJumpToNextInteration(Jump jump)
437         {
438             m_jumpsToNextInteration.append(jump);
439         }
440
441         void addJumpsToNextInteration(JumpList jumps)
442         {
443             m_jumpsToNextInteration.append(jumps);
444         }
445
446         void addDataLabelToNextIteration(DataLabelPtr dataLabel)
447         {
448             m_dataPtrsToNextIteration.append(dataLabel);
449         }
450
451         void linkToNextIteration(Label label)
452         {
453             m_nextIteration = label;
454
455             for (unsigned i = 0; i < m_dataPtrsToNextIteration.size(); ++i)
456                 m_backtrackRecords.append(AlternativeBacktrackRecord(m_dataPtrsToNextIteration[i], m_nextIteration));
457
458             m_dataPtrsToNextIteration.clear();
459
460             for (unsigned i = 0; i < m_parenTailsForIteration.size(); ++i)
461                 m_parenTailsForIteration[i]->setNextIteration(m_nextIteration);
462
463             m_parenTailsForIteration.clear();
464         }
465
466         void linkToNextIteration(YarrGenerator* generator)
467         {
468             m_jumpsToNextInteration.linkTo(m_nextIteration, generator);
469         }
470
471         int m_parenNestingLevel;
472         Vector<AlternativeBacktrackRecord> m_backtrackRecords;
473         IndirectJumpHashMap m_indirectJumpMap;
474         Label m_nextIteration;
475         Vector<OwnPtr<ParenthesesTail> > m_parenTails;
476         JumpList m_jumpsToNextInteration;
477         Vector<DataLabelPtr> m_dataPtrsToNextIteration;
478         Vector<ParenthesesTail*> m_parenTailsForIteration;
479     };
480
481     struct BacktrackDestination {
482         typedef enum {
483             NoBacktrack,
484             BacktrackLabel,
485             BacktrackStackOffset,
486             BacktrackJumpList,
487             BacktrackLinked
488         } BacktrackType;
489
490         BacktrackDestination()
491             : m_backtrackType(NoBacktrack)
492             , m_backtrackToLabel(0)
493             , m_subDataLabelPtr(0)
494             , m_nextBacktrack(0)
495             , m_backtrackSourceLabel(0)
496             , m_backtrackSourceJumps(0)
497         {
498         }
499
500         BacktrackDestination(int32_t stackOffset)
501             : m_backtrackType(BacktrackStackOffset)
502             , m_backtrackStackOffset(stackOffset)
503             , m_backtrackToLabel(0)
504             , m_subDataLabelPtr(0)
505             , m_nextBacktrack(0)
506             , m_backtrackSourceLabel(0)
507             , m_backtrackSourceJumps(0)
508         {
509         }
510
511         BacktrackDestination(Label label)
512             : m_backtrackType(BacktrackLabel)
513             , m_backtrackLabel(label)
514             , m_backtrackToLabel(0)
515             , m_subDataLabelPtr(0)
516             , m_nextBacktrack(0)
517             , m_backtrackSourceLabel(0)
518             , m_backtrackSourceJumps(0)
519         {
520         }
521
522         void clear(bool doDataLabelClear = true)
523         {
524             m_backtrackType = NoBacktrack;
525             if (doDataLabelClear)
526                 clearDataLabel();
527             m_nextBacktrack = 0;
528         }
529
530         void clearDataLabel()
531         {
532             m_dataLabelPtr = DataLabelPtr();
533         }
534
535         bool hasDestination()
536         {
537             return (m_backtrackType != NoBacktrack);
538         }
539
540         bool isStackOffset()
541         {
542             return (m_backtrackType == BacktrackStackOffset);
543         }
544
545         bool isLabel()
546         {
547             return (m_backtrackType == BacktrackLabel);
548         }
549
550         bool isJumpList()
551         {
552             return (m_backtrackType == BacktrackJumpList);
553         }
554
555         bool hasDataLabel()
556         {
557             return m_dataLabelPtr.isSet();
558         }
559
560         void copyTarget(BacktrackDestination& rhs, bool copyDataLabel = true)
561         {
562             m_backtrackType = rhs.m_backtrackType;
563             if (m_backtrackType == BacktrackStackOffset)
564                 m_backtrackStackOffset = rhs.m_backtrackStackOffset;
565             else if (m_backtrackType == BacktrackLabel)
566                 m_backtrackLabel = rhs.m_backtrackLabel;
567             if (copyDataLabel)
568                 m_dataLabelPtr = rhs.m_dataLabelPtr;
569             m_backtrackSourceJumps = rhs.m_backtrackSourceJumps;
570             m_backtrackSourceLabel = rhs.m_backtrackSourceLabel;
571         }
572
573         void copyTo(BacktrackDestination& lhs)
574         {
575             lhs.m_backtrackType = m_backtrackType;
576             if (m_backtrackType == BacktrackStackOffset)
577                 lhs.m_backtrackStackOffset = m_backtrackStackOffset;
578             else if (m_backtrackType == BacktrackLabel)
579                 lhs.m_backtrackLabel = m_backtrackLabel;
580             lhs.m_backtrackSourceJumps = m_backtrackSourceJumps;
581             lhs.m_backtrackSourceLabel = m_backtrackSourceLabel;
582             lhs.m_dataLabelPtr = m_dataLabelPtr;
583             lhs.m_backTrackJumps = m_backTrackJumps;
584         }
585
586         void addBacktrackJump(Jump jump)
587         {
588             m_backTrackJumps.append(jump);
589         }
590
591         void setStackOffset(int32_t stackOffset)
592         {
593             m_backtrackType = BacktrackStackOffset;
594             m_backtrackStackOffset = stackOffset;
595         }
596
597         void setLabel(Label label)
598         {
599             m_backtrackType = BacktrackLabel;
600             m_backtrackLabel = label;
601         }
602
603         void setNextBacktrackLabel(Label label)
604         {
605             if (m_nextBacktrack)
606                 m_nextBacktrack->setLabel(label);
607         }
608
609         void propagateBacktrackToLabel(const BacktrackDestination& rhs)
610         {
611             if (!m_backtrackToLabel && rhs.m_backtrackToLabel)
612                 m_backtrackToLabel = rhs.m_backtrackToLabel;
613         }
614
615         void setBacktrackToLabel(Label* backtrackToLabel)
616         {
617             if (!m_backtrackToLabel)
618                 m_backtrackToLabel = backtrackToLabel;
619         }
620
621         bool hasBacktrackToLabel()
622         {
623             return m_backtrackToLabel;
624         }
625
626         void setBacktrackJumpList(JumpList* jumpList)
627         {
628             m_backtrackType = BacktrackJumpList;
629             m_backtrackSourceJumps = jumpList;
630         }
631
632         void setBacktrackSourceLabel(Label* backtrackSourceLabel)
633         {
634             m_backtrackSourceLabel = backtrackSourceLabel;
635         }
636
637         void setDataLabel(DataLabelPtr dp)
638         {
639             if (m_subDataLabelPtr) {
640                 *m_subDataLabelPtr = dp;
641                 m_subDataLabelPtr = 0;
642             } else {
643                 ASSERT(!hasDataLabel());
644                 m_dataLabelPtr = dp;
645             }
646         }
647
648         void clearSubDataLabelPtr()
649         {
650             m_subDataLabelPtr = 0;
651         }
652
653         void setSubDataLabelPtr(DataLabelPtr* subDataLabelPtr)
654         {
655             m_subDataLabelPtr = subDataLabelPtr;
656         }
657
658         void linkToNextBacktrack(BacktrackDestination* nextBacktrack)
659         {
660             m_nextBacktrack = nextBacktrack;
661         }
662
663         int32_t getStackOffset()
664         {
665             ASSERT(m_backtrackType == BacktrackStackOffset);
666             return m_backtrackStackOffset;
667         }
668
669         Label getLabel()
670         {
671             ASSERT(m_backtrackType == BacktrackLabel);
672             return m_backtrackLabel;
673         }
674
675         JumpList& getBacktrackJumps()
676         {
677             return m_backTrackJumps;
678         }
679
680         DataLabelPtr& getDataLabel()
681         {
682             return m_dataLabelPtr;
683         }
684
685         void jumpToBacktrack(MacroAssembler* masm)
686         {
687             if (isJumpList()) {
688                 if (m_backtrackSourceLabel && (m_backtrackSourceLabel->isSet()))
689                     masm->jump().linkTo(*m_backtrackSourceLabel, masm);
690                 else
691                     m_backtrackSourceJumps->append(masm->jump());
692             } else if (isStackOffset())
693                 masm->jump(Address(stackPointerRegister, m_backtrackStackOffset));
694             else if (isLabel())
695                 masm->jump().linkTo(m_backtrackLabel, masm);
696             else
697                 m_backTrackJumps.append(masm->jump());
698         }
699
700         void jumpToBacktrack(YarrGenerator* generator, Jump jump)
701         {
702             if (isJumpList()) {
703                 if (m_backtrackSourceLabel && (m_backtrackSourceLabel->isSet()))
704                     jump.linkTo(*m_backtrackSourceLabel, generator);
705                 else
706                     m_backtrackSourceJumps->append(jump);
707             } else if (isStackOffset())
708                 generator->m_expressionState.addIndirectJumpEntry(getStackOffset(), jump);
709             else if (isLabel())
710                 jump.linkTo(getLabel(), generator);
711             else
712                 m_backTrackJumps.append(jump);
713         }
714
715         void jumpToBacktrack(YarrGenerator* generator, JumpList& jumps)
716         {
717             if (isJumpList()) {
718                 if (m_backtrackSourceLabel && (m_backtrackSourceLabel->isSet()))
719                     jumps.linkTo(*m_backtrackSourceLabel, generator);
720                 else
721                     m_backtrackSourceJumps->append(jumps);
722             } else if (isStackOffset())
723                 generator->m_expressionState.addIndirectJumpEntry(getStackOffset(), jumps);
724             else if (isLabel())
725                 jumps.linkTo(getLabel(), generator);
726             else
727                 m_backTrackJumps.append(jumps);
728         }
729
730         bool plantJumpToBacktrackIfExists(YarrGenerator* generator)
731         {
732             if (isJumpList()) {
733                 if (m_backtrackSourceLabel && (m_backtrackSourceLabel->isSet()))
734                     generator->jump(*m_backtrackSourceLabel);
735                 else
736                     m_backtrackSourceJumps->append(generator->jump());
737
738                 return true;
739             }
740
741             if (isStackOffset()) {
742                 generator->jump(Address(stackPointerRegister, getStackOffset()));
743                 return true;
744             }
745
746             if (isLabel()) {
747                 generator->jump(getLabel());
748                 if (hasDataLabel()) {
749                     generator->m_expressionState.m_backtrackRecords.append(AlternativeBacktrackRecord(getDataLabel(), getLabel()));
750                     clearDataLabel();
751                 }
752                 return true;
753             }
754
755             return false;
756         }
757
758         void linkBacktrackToLabel(Label backtrackLabel)
759         {
760             if (m_backtrackToLabel)
761                 *m_backtrackToLabel = backtrackLabel;
762         }
763
764         void linkAlternativeBacktracks(YarrGenerator* generator, bool nextIteration = false)
765         {
766             Label hereLabel = generator->label();
767
768             if (m_backtrackToLabel) {
769                 *m_backtrackToLabel = hereLabel;
770                 m_backtrackToLabel = 0;
771             }
772
773             m_backTrackJumps.link(generator);
774
775             if (nextIteration)
776                 generator->m_expressionState.linkToNextIteration(hereLabel);
777
778             if (hasDataLabel()) {
779                 generator->m_expressionState.m_backtrackRecords.append(AlternativeBacktrackRecord(getDataLabel(), hereLabel));
780                 // data label cleared as a result of the clear() below
781             }
782
783             clear();
784         }
785
786         void linkAlternativeBacktracksTo(YarrGenerator* generator, Label label, bool nextIteration = false)
787         {
788             m_backTrackJumps.linkTo(label, generator);
789
790             if (nextIteration)
791                 generator->m_expressionState.linkToNextIteration(label);
792
793             if (hasDataLabel()) {
794                 generator->m_expressionState.m_backtrackRecords.append(AlternativeBacktrackRecord(getDataLabel(), label));
795                 clearDataLabel();
796             }
797         }
798
799     private:
800         BacktrackType m_backtrackType;
801         int32_t m_backtrackStackOffset;
802         Label m_backtrackLabel;
803         DataLabelPtr m_dataLabelPtr;
804         Label* m_backtrackToLabel;
805         DataLabelPtr* m_subDataLabelPtr;
806         BacktrackDestination* m_nextBacktrack;
807         Label* m_backtrackSourceLabel;
808         JumpList* m_backtrackSourceJumps;
809         JumpList m_backTrackJumps;
810     };
811
812     struct TermGenerationState {
813         TermGenerationState(PatternDisjunction* disjunction, unsigned checkedTotal)
814             : disjunction(disjunction)
815             , checkedTotal(checkedTotal)
816             , m_subParenNum(0)
817             , m_linkedBacktrack(0)
818             , m_parenthesesTail(0)
819         {
820         }
821
822         void resetAlternative()
823         {
824             m_backtrack.clear();
825             alt = 0;
826         }
827         bool alternativeValid()
828         {
829             return alt < disjunction->m_alternatives.size();
830         }
831         void nextAlternative()
832         {
833             ++alt;
834         }
835         PatternAlternative* alternative()
836         {
837             return disjunction->m_alternatives[alt];
838         }
839         bool isLastAlternative()
840         {
841             return (alt + 1) == disjunction->m_alternatives.size();
842         }
843
844         void resetTerm()
845         {
846             ASSERT(alternativeValid());
847             t = 0;
848             m_subParenNum = 0;
849         }
850         bool termValid()
851         {
852             ASSERT(alternativeValid());
853             return t < alternative()->m_terms.size();
854         }
855         void nextTerm()
856         {
857             ASSERT(alternativeValid());
858             ++t;
859         }
860         PatternTerm& term()
861         {
862             ASSERT(alternativeValid());
863             return alternative()->m_terms[t];
864         }
865         bool isLastTerm()
866         {
867             ASSERT(alternativeValid());
868             return (t + 1) == alternative()->m_terms.size();
869         }
870         unsigned getSubParenNum()
871         {
872             return m_subParenNum++;
873         }
874         bool isMainDisjunction()
875         {
876             return !disjunction->m_parent;
877         }
878
879         void setParenthesesTail(ParenthesesTail* parenthesesTail)
880         {
881             m_parenthesesTail = parenthesesTail;
882         }
883
884         ParenthesesTail* getParenthesesTail()
885         {
886             return m_parenthesesTail;
887         }
888
889         PatternTerm& lookaheadTerm()
890         {
891             ASSERT(alternativeValid());
892             ASSERT((t + 1) < alternative()->m_terms.size());
893             return alternative()->m_terms[t + 1];
894         }
895         bool isSinglePatternCharacterLookaheadTerm()
896         {
897             ASSERT(alternativeValid());
898             return ((t + 1) < alternative()->m_terms.size())
899                 && (lookaheadTerm().type == PatternTerm::TypePatternCharacter)
900                 && (lookaheadTerm().quantityType == QuantifierFixedCount)
901                 && (lookaheadTerm().quantityCount == 1);
902         }
903
904         int inputOffset()
905         {
906             return term().inputPosition - checkedTotal;
907         }
908
909         void clearBacktrack()
910         {
911             m_backtrack.clear(false);
912             m_linkedBacktrack = 0;
913         }
914
915         void jumpToBacktrack(MacroAssembler* masm)
916         {
917             m_backtrack.jumpToBacktrack(masm);
918         }
919
920         void jumpToBacktrack(YarrGenerator* generator, Jump jump)
921         {
922             m_backtrack.jumpToBacktrack(generator, jump);
923         }
924
925         void jumpToBacktrack(YarrGenerator* generator, JumpList& jumps)
926         {
927             m_backtrack.jumpToBacktrack(generator, jumps);
928         }
929
930         bool plantJumpToBacktrackIfExists(YarrGenerator* generator)
931         {
932             return m_backtrack.plantJumpToBacktrackIfExists(generator);
933         }
934
935         void linkDataLabelToBacktrackIfExists(YarrGenerator* generator, DataLabelPtr dataLabel)
936         {
937             // If we have a stack offset backtrack destination, use it directly
938             if (m_backtrack.isStackOffset()) {
939                 generator->m_expressionState.addIndirectJumpEntry(m_backtrack.getStackOffset(), dataLabel);
940                 m_backtrack.clearSubDataLabelPtr();
941             } else {
942                 // If we have a backtrack label, connect the datalabel to it directly.
943                 if (m_backtrack.isLabel())
944                     generator->m_expressionState.m_backtrackRecords.append(AlternativeBacktrackRecord(dataLabel, m_backtrack.getLabel()));
945                 else
946                     setBacktrackDataLabel(dataLabel);
947             }
948         }
949
950         void addBacktrackJump(Jump jump)
951         {
952             m_backtrack.addBacktrackJump(jump);
953         }
954
955         void setBacktrackDataLabel(DataLabelPtr dp)
956         {
957             m_backtrack.setDataLabel(dp);
958         }
959
960         void setBackTrackStackOffset(int32_t stackOffset)
961         {
962             m_backtrack.setStackOffset(stackOffset);
963         }
964
965         void setBacktrackLabel(Label label)
966         {
967             m_backtrack.setLabel(label);
968         }
969
970         void linkAlternativeBacktracks(YarrGenerator* generator, bool nextIteration = false)
971         {
972             m_backtrack.linkAlternativeBacktracks(generator, nextIteration);
973             m_linkedBacktrack = 0;
974         }
975
976         void linkAlternativeBacktracksTo(YarrGenerator* generator, Label label, bool nextIteration = false)
977         {
978             m_backtrack.linkAlternativeBacktracksTo(generator, label, nextIteration);
979         }
980
981         void setBacktrackLink(BacktrackDestination* linkedBacktrack)
982         {
983             m_linkedBacktrack = linkedBacktrack;
984         }
985
986         void chainBacktracks(BacktrackDestination* followonBacktrack)
987         {
988             if (m_linkedBacktrack)
989                 m_linkedBacktrack->linkToNextBacktrack(followonBacktrack);
990         }
991
992         BacktrackDestination& getBacktrackDestination()
993         {
994             return m_backtrack;
995         }
996
997         void propagateBacktrackingFrom(YarrGenerator* generator, BacktrackDestination& backtrack, bool doJump = true)
998         {
999             if (doJump)
1000                 m_backtrack.jumpToBacktrack(generator, backtrack.getBacktrackJumps());
1001
1002             if (m_backtrack.isLabel() && backtrack.hasBacktrackToLabel())
1003                 backtrack.linkBacktrackToLabel(m_backtrack.getLabel());
1004
1005             if (backtrack.hasDestination()) {
1006                 if (m_backtrack.hasDataLabel())
1007                     generator->m_expressionState.addDataLabelToNextIteration(m_backtrack.getDataLabel());
1008
1009                 m_backtrack.copyTarget(backtrack, doJump);
1010             }
1011         }
1012
1013         PatternDisjunction* disjunction;
1014         int checkedTotal;
1015     private:
1016         unsigned alt;
1017         unsigned t;
1018         unsigned m_subParenNum;
1019         BacktrackDestination m_backtrack;
1020         BacktrackDestination* m_linkedBacktrack;
1021         ParenthesesTail* m_parenthesesTail;
1022     };
1023
1024     struct ParenthesesTail {
1025         ParenthesesTail(PatternTerm& term, int nestingLevel, ParenthesesTail* nextOuterParenTail)
1026             : m_term(term)
1027             , m_nestingLevel(nestingLevel)
1028             , m_subParenIndex(0)
1029             , m_nextOuterParenTail(nextOuterParenTail)
1030         {
1031         }
1032
1033         void processBacktracks(YarrGenerator* generator, TermGenerationState& state, TermGenerationState& parenthesesState, Label nonGreedyTryParentheses, Label fallThrough)
1034         {
1035             m_nonGreedyTryParentheses = nonGreedyTryParentheses;
1036             m_fallThrough = fallThrough;
1037
1038             m_subParenIndex = state.getSubParenNum();
1039             parenthesesState.getBacktrackDestination().copyTo(m_parenBacktrack);
1040             state.chainBacktracks(&m_backtrack);
1041             BacktrackDestination& stateBacktrack = state.getBacktrackDestination();
1042             stateBacktrack.copyTo(m_backtrack);
1043             stateBacktrack.setBacktrackToLabel(&m_backtrackToLabel);
1044             state.setBacktrackLink(&m_backtrack);
1045             stateBacktrack.setSubDataLabelPtr(&m_dataAfterLabelPtr);
1046
1047             m_doDirectBacktrack = m_parenBacktrack.hasDestination();
1048
1049             if ((m_term.quantityType == QuantifierGreedy) || (m_term.quantityType == QuantifierNonGreedy))
1050                 m_doDirectBacktrack = false;
1051
1052             if (m_doDirectBacktrack)
1053                 state.propagateBacktrackingFrom(generator, m_parenBacktrack, false);
1054             else {
1055                 stateBacktrack.setBacktrackJumpList(&m_pattBacktrackJumps);
1056                 stateBacktrack.setBacktrackSourceLabel(&m_backtrackFromAfterParens);
1057             }
1058         }
1059
1060         void setNextIteration(Label nextIteration)
1061         {
1062             if (!m_nestingLevel && !m_backtrackToLabel.isSet())
1063                 m_backtrackToLabel = nextIteration;
1064         }
1065
1066         void addAfterParenJump(Jump jump)
1067         {
1068             m_pattBacktrackJumps.append(jump);
1069         }
1070
1071         bool generateCode(YarrGenerator* generator, JumpList& jumpsToNext, bool priorBackTrackFallThrough, bool nextBacktrackFallThrough)
1072         {
1073             const RegisterID indexTemporary = regT0;
1074             unsigned parenthesesFrameLocation = m_term.frameLocation;
1075             Jump fromPriorBacktrack;
1076             bool needJumpForPriorParenTail = false;
1077
1078             if (priorBackTrackFallThrough
1079                 && ((m_term.quantityType == QuantifierGreedy)
1080                  || (m_term.quantityType == QuantifierNonGreedy)
1081                  || (!m_doDirectBacktrack && m_parenBacktrack.hasDestination()))) {
1082                 // If the prior paren tail code assumed that it could fall through,
1083                 // but we need to generate after paren backtrack code, then provide
1084                 // a jump around that code for the prior paren tail code.
1085                 // A regular expressing like ((xxx)...)? needs this.
1086                 fromPriorBacktrack = generator->jump();
1087                 needJumpForPriorParenTail = true;
1088             }
1089
1090             if (!m_backtrack.hasDestination()) {
1091                 if (m_backtrackToLabel.isSet()) {
1092                     m_backtrack.setLabel(m_backtrackToLabel);
1093                     nextBacktrackFallThrough = false;
1094                 } else if (!m_subParenIndex && m_nextOuterParenTail) {
1095                     // If we don't have a destination and we are the first term of a nested paren, go
1096                     // back to the outer paren.
1097                     // There is an optimization if the next outer paren is the next paren to be emitted.
1098                     // In that case we really want the else clause.
1099                     m_backtrack.setBacktrackJumpList(&m_nextOuterParenTail->m_withinBacktrackJumps);
1100                     nextBacktrackFallThrough = false;
1101                 } else
1102                     m_backtrack.setBacktrackJumpList(&jumpsToNext);
1103             } else
1104                 nextBacktrackFallThrough = false;
1105
1106             // A failure AFTER the parens jumps here - Backtrack to this paren
1107             m_backtrackFromAfterParens = generator->label();
1108
1109             if (m_dataAfterLabelPtr.isSet())
1110                 generator->m_expressionState.m_backtrackRecords.append(AlternativeBacktrackRecord(m_dataAfterLabelPtr, m_backtrackFromAfterParens));
1111
1112             m_pattBacktrackJumps.link(generator);
1113
1114             if (m_term.quantityType == QuantifierGreedy) {
1115                 // If this is -1 we have now tested with both with and without the parens.
1116                 generator->loadFromFrame(parenthesesFrameLocation, indexTemporary);
1117                 m_backtrack.jumpToBacktrack(generator, generator->branch32(Equal, indexTemporary, Imm32(-1)));
1118             } else if (m_term.quantityType == QuantifierNonGreedy) {
1119                 // If this is -1 we have now tested with both with and without the parens.
1120                 generator->loadFromFrame(parenthesesFrameLocation, indexTemporary);
1121                 generator->branch32(Equal, indexTemporary, Imm32(-1)).linkTo(m_nonGreedyTryParentheses, generator);
1122             }
1123
1124             if (!m_doDirectBacktrack)
1125                 m_parenBacktrack.plantJumpToBacktrackIfExists(generator);
1126
1127             // A failure WITHIN the parens jumps here
1128             if (needJumpForPriorParenTail)
1129                 fromPriorBacktrack.link(generator);
1130             m_parenBacktrack.linkAlternativeBacktracks(generator);
1131             m_withinBacktrackJumps.link(generator);
1132
1133             if (m_term.capture())
1134                 generator->store32(Imm32(-1), Address(output, (m_term.parentheses.subpatternId << 1) * sizeof(int)));
1135
1136             if (m_term.quantityType == QuantifierGreedy) {
1137                 generator->storeToFrame(Imm32(-1), parenthesesFrameLocation);
1138                 generator->jump().linkTo(m_fallThrough, generator);
1139                 nextBacktrackFallThrough = false;
1140             } else if (!nextBacktrackFallThrough)
1141                 m_backtrack.jumpToBacktrack(generator);
1142
1143             if (!m_doDirectBacktrack)
1144                 m_backtrack.setNextBacktrackLabel(m_backtrackFromAfterParens);
1145
1146             return nextBacktrackFallThrough;
1147         }
1148
1149         PatternTerm& m_term;
1150         int m_nestingLevel;
1151         unsigned m_subParenIndex;
1152         ParenthesesTail* m_nextOuterParenTail;
1153         Label m_nonGreedyTryParentheses;
1154         Label m_fallThrough;
1155         Label m_backtrackToLabel;
1156         Label m_backtrackFromAfterParens;
1157         DataLabelPtr m_dataAfterLabelPtr;
1158         JumpList m_pattBacktrackJumps;
1159         JumpList m_withinBacktrackJumps;
1160         BacktrackDestination m_parenBacktrack;
1161         BacktrackDestination m_backtrack;
1162         bool m_doDirectBacktrack;
1163     };
1164
1165     void generateAssertionBOL(TermGenerationState& state)
1166     {
1167         PatternTerm& term = state.term();
1168
1169         if (m_pattern.m_multiline) {
1170             const RegisterID character = regT0;
1171
1172             JumpList matchDest;
1173             if (!term.inputPosition)
1174                 matchDest.append(branch32(Equal, index, Imm32(state.checkedTotal)));
1175
1176             readCharacter(state.inputOffset() - 1, character);
1177             matchCharacterClass(character, matchDest, m_pattern.newlineCharacterClass());
1178             state.jumpToBacktrack(this);
1179
1180             matchDest.link(this);
1181         } else {
1182             // Erk, really should poison out these alternatives early. :-/
1183             if (term.inputPosition)
1184                 state.jumpToBacktrack(this);
1185             else
1186                 state.jumpToBacktrack(this, branch32(NotEqual, index, Imm32(state.checkedTotal)));
1187         }
1188     }
1189
1190     void generateAssertionEOL(TermGenerationState& state)
1191     {
1192         PatternTerm& term = state.term();
1193
1194         if (m_pattern.m_multiline) {
1195             const RegisterID character = regT0;
1196
1197             JumpList matchDest;
1198             if (term.inputPosition == state.checkedTotal)
1199                 matchDest.append(atEndOfInput());
1200
1201             readCharacter(state.inputOffset(), character);
1202             matchCharacterClass(character, matchDest, m_pattern.newlineCharacterClass());
1203             state.jumpToBacktrack(this);
1204
1205             matchDest.link(this);
1206         } else {
1207             if (term.inputPosition == state.checkedTotal)
1208                 state.jumpToBacktrack(this, notAtEndOfInput());
1209             // Erk, really should poison out these alternatives early. :-/
1210             else
1211                 state.jumpToBacktrack(this);
1212         }
1213     }
1214
1215     // Also falls though on nextIsNotWordChar.
1216     void matchAssertionWordchar(TermGenerationState& state, JumpList& nextIsWordChar, JumpList& nextIsNotWordChar)
1217     {
1218         const RegisterID character = regT0;
1219         PatternTerm& term = state.term();
1220
1221         if (term.inputPosition == state.checkedTotal)
1222             nextIsNotWordChar.append(atEndOfInput());
1223
1224         readCharacter(state.inputOffset(), character);
1225         matchCharacterClass(character, nextIsWordChar, m_pattern.wordcharCharacterClass());
1226     }
1227
1228     void generateAssertionWordBoundary(TermGenerationState& state)
1229     {
1230         const RegisterID character = regT0;
1231         PatternTerm& term = state.term();
1232
1233         Jump atBegin;
1234         JumpList matchDest;
1235         if (!term.inputPosition)
1236             atBegin = branch32(Equal, index, Imm32(state.checkedTotal));
1237         readCharacter(state.inputOffset() - 1, character);
1238         matchCharacterClass(character, matchDest, m_pattern.wordcharCharacterClass());
1239         if (!term.inputPosition)
1240             atBegin.link(this);
1241
1242         // We fall through to here if the last character was not a wordchar.
1243         JumpList nonWordCharThenWordChar;
1244         JumpList nonWordCharThenNonWordChar;
1245         if (term.invert()) {
1246             matchAssertionWordchar(state, nonWordCharThenNonWordChar, nonWordCharThenWordChar);
1247             nonWordCharThenWordChar.append(jump());
1248         } else {
1249             matchAssertionWordchar(state, nonWordCharThenWordChar, nonWordCharThenNonWordChar);
1250             nonWordCharThenNonWordChar.append(jump());
1251         }
1252         state.jumpToBacktrack(this, nonWordCharThenNonWordChar);
1253
1254         // We jump here if the last character was a wordchar.
1255         matchDest.link(this);
1256         JumpList wordCharThenWordChar;
1257         JumpList wordCharThenNonWordChar;
1258         if (term.invert()) {
1259             matchAssertionWordchar(state, wordCharThenNonWordChar, wordCharThenWordChar);
1260             wordCharThenWordChar.append(jump());
1261         } else {
1262             matchAssertionWordchar(state, wordCharThenWordChar, wordCharThenNonWordChar);
1263             // This can fall-though!
1264         }
1265
1266         state.jumpToBacktrack(this, wordCharThenWordChar);
1267
1268         nonWordCharThenWordChar.link(this);
1269         wordCharThenNonWordChar.link(this);
1270     }
1271
1272     void generatePatternCharacterSingle(TermGenerationState& state)
1273     {
1274         const RegisterID character = regT0;
1275         UChar ch = state.term().patternCharacter;
1276
1277         if (m_pattern.m_ignoreCase && isASCIIAlpha(ch)) {
1278             readCharacter(state.inputOffset(), character);
1279             or32(Imm32(32), character);
1280             state.jumpToBacktrack(this, branch32(NotEqual, character, Imm32(Unicode::toLower(ch))));
1281         } else {
1282             ASSERT(!m_pattern.m_ignoreCase || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
1283             state.jumpToBacktrack(this, jumpIfCharNotEquals(ch, state.inputOffset()));
1284         }
1285     }
1286
1287     void generatePatternCharacterPair(TermGenerationState& state)
1288     {
1289         const RegisterID character = regT0;
1290         UChar ch1 = state.term().patternCharacter;
1291         UChar ch2 = state.lookaheadTerm().patternCharacter;
1292
1293         int mask = 0;
1294         int chPair = ch1 | (ch2 << 16);
1295
1296         if (m_pattern.m_ignoreCase) {
1297             if (isASCIIAlpha(ch1))
1298                 mask |= 32;
1299             if (isASCIIAlpha(ch2))
1300                 mask |= 32 << 16;
1301         }
1302
1303         if (mask) {
1304             load32WithUnalignedHalfWords(BaseIndex(input, index, TimesTwo, state.inputOffset() * sizeof(UChar)), character);
1305             or32(Imm32(mask), character);
1306             state.jumpToBacktrack(this, branch32(NotEqual, character, Imm32(chPair | mask)));
1307         } else
1308             state.jumpToBacktrack(this, branch32WithUnalignedHalfWords(NotEqual, BaseIndex(input, index, TimesTwo, state.inputOffset() * sizeof(UChar)), Imm32(chPair)));
1309     }
1310
1311     void generatePatternCharacterFixed(TermGenerationState& state)
1312     {
1313         const RegisterID character = regT0;
1314         const RegisterID countRegister = regT1;
1315         PatternTerm& term = state.term();
1316         UChar ch = term.patternCharacter;
1317
1318         move(index, countRegister);
1319         sub32(Imm32(term.quantityCount), countRegister);
1320
1321         Label loop(this);
1322         if (m_pattern.m_ignoreCase && isASCIIAlpha(ch)) {
1323             load16(BaseIndex(input, countRegister, TimesTwo, (state.inputOffset() + term.quantityCount) * sizeof(UChar)), character);
1324             or32(Imm32(32), character);
1325             state.jumpToBacktrack(this, branch32(NotEqual, character, Imm32(Unicode::toLower(ch))));
1326         } else {
1327             ASSERT(!m_pattern.m_ignoreCase || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
1328             state.jumpToBacktrack(this, branch16(NotEqual, BaseIndex(input, countRegister, TimesTwo, (state.inputOffset() + term.quantityCount) * sizeof(UChar)), Imm32(ch)));
1329         }
1330         add32(Imm32(1), countRegister);
1331         branch32(NotEqual, countRegister, index).linkTo(loop, this);
1332     }
1333
1334     void generatePatternCharacterGreedy(TermGenerationState& state)
1335     {
1336         const RegisterID character = regT0;
1337         const RegisterID countRegister = regT1;
1338         PatternTerm& term = state.term();
1339         UChar ch = term.patternCharacter;
1340
1341         move(Imm32(0), countRegister);
1342
1343         JumpList failures;
1344         Label loop(this);
1345         failures.append(atEndOfInput());
1346         if (m_pattern.m_ignoreCase && isASCIIAlpha(ch)) {
1347             readCharacter(state.inputOffset(), character);
1348             or32(Imm32(32), character);
1349             failures.append(branch32(NotEqual, character, Imm32(Unicode::toLower(ch))));
1350         } else {
1351             ASSERT(!m_pattern.m_ignoreCase || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
1352             failures.append(jumpIfCharNotEquals(ch, state.inputOffset()));
1353         }
1354
1355         add32(Imm32(1), countRegister);
1356         add32(Imm32(1), index);
1357         if (term.quantityCount != quantifyInfinite) {
1358             branch32(NotEqual, countRegister, Imm32(term.quantityCount)).linkTo(loop, this);
1359             failures.append(jump());
1360         } else
1361             jump(loop);
1362
1363         Label backtrackBegin(this);
1364         loadFromFrame(term.frameLocation, countRegister);
1365         state.jumpToBacktrack(this, branchTest32(Zero, countRegister));
1366         sub32(Imm32(1), countRegister);
1367         sub32(Imm32(1), index);
1368
1369         failures.link(this);
1370
1371         storeToFrame(countRegister, term.frameLocation);
1372
1373         state.setBacktrackLabel(backtrackBegin);
1374     }
1375
1376     void generatePatternCharacterNonGreedy(TermGenerationState& state)
1377     {
1378         const RegisterID character = regT0;
1379         const RegisterID countRegister = regT1;
1380         PatternTerm& term = state.term();
1381         UChar ch = term.patternCharacter;
1382
1383         move(Imm32(0), countRegister);
1384
1385         Jump firstTimeDoNothing = jump();
1386
1387         Label hardFail(this);
1388         sub32(countRegister, index);
1389         state.jumpToBacktrack(this);
1390
1391         Label backtrackBegin(this);
1392         loadFromFrame(term.frameLocation, countRegister);
1393
1394         atEndOfInput().linkTo(hardFail, this);
1395         if (term.quantityCount != quantifyInfinite)
1396             branch32(Equal, countRegister, Imm32(term.quantityCount), hardFail);
1397         if (m_pattern.m_ignoreCase && isASCIIAlpha(ch)) {
1398             readCharacter(state.inputOffset(), character);
1399             or32(Imm32(32), character);
1400             branch32(NotEqual, character, Imm32(Unicode::toLower(ch))).linkTo(hardFail, this);
1401         } else {
1402             ASSERT(!m_pattern.m_ignoreCase || (Unicode::toLower(ch) == Unicode::toUpper(ch)));
1403             jumpIfCharNotEquals(ch, state.inputOffset()).linkTo(hardFail, this);
1404         }
1405
1406         add32(Imm32(1), countRegister);
1407         add32(Imm32(1), index);
1408
1409         firstTimeDoNothing.link(this);
1410         storeToFrame(countRegister, term.frameLocation);
1411
1412         state.setBacktrackLabel(backtrackBegin);
1413     }
1414
1415     void generateCharacterClassSingle(TermGenerationState& state)
1416     {
1417         const RegisterID character = regT0;
1418         PatternTerm& term = state.term();
1419
1420         JumpList matchDest;
1421         readCharacter(state.inputOffset(), character);
1422         matchCharacterClass(character, matchDest, term.characterClass);
1423
1424         if (term.invert())
1425             state.jumpToBacktrack(this, matchDest);
1426         else {
1427             state.jumpToBacktrack(this);
1428             matchDest.link(this);
1429         }
1430     }
1431
1432     void generateCharacterClassFixed(TermGenerationState& state)
1433     {
1434         const RegisterID character = regT0;
1435         const RegisterID countRegister = regT1;
1436         PatternTerm& term = state.term();
1437
1438         move(index, countRegister);
1439         sub32(Imm32(term.quantityCount), countRegister);
1440
1441         Label loop(this);
1442         JumpList matchDest;
1443         load16(BaseIndex(input, countRegister, TimesTwo, (state.inputOffset() + term.quantityCount) * sizeof(UChar)), character);
1444         matchCharacterClass(character, matchDest, term.characterClass);
1445
1446         if (term.invert())
1447             state.jumpToBacktrack(this, matchDest);
1448         else {
1449             state.jumpToBacktrack(this);
1450             matchDest.link(this);
1451         }
1452
1453         add32(Imm32(1), countRegister);
1454         branch32(NotEqual, countRegister, index).linkTo(loop, this);
1455     }
1456
1457     void generateCharacterClassGreedy(TermGenerationState& state)
1458     {
1459         const RegisterID character = regT0;
1460         const RegisterID countRegister = regT1;
1461         PatternTerm& term = state.term();
1462
1463         move(Imm32(0), countRegister);
1464
1465         JumpList failures;
1466         Label loop(this);
1467         failures.append(atEndOfInput());
1468
1469         if (term.invert()) {
1470             readCharacter(state.inputOffset(), character);
1471             matchCharacterClass(character, failures, term.characterClass);
1472         } else {
1473             JumpList matchDest;
1474             readCharacter(state.inputOffset(), character);
1475             matchCharacterClass(character, matchDest, term.characterClass);
1476             failures.append(jump());
1477             matchDest.link(this);
1478         }
1479
1480         add32(Imm32(1), countRegister);
1481         add32(Imm32(1), index);
1482         if (term.quantityCount != quantifyInfinite) {
1483             branch32(NotEqual, countRegister, Imm32(term.quantityCount)).linkTo(loop, this);
1484             failures.append(jump());
1485         } else
1486             jump(loop);
1487
1488         Label backtrackBegin(this);
1489         loadFromFrame(term.frameLocation, countRegister);
1490         state.jumpToBacktrack(this, branchTest32(Zero, countRegister));
1491         sub32(Imm32(1), countRegister);
1492         sub32(Imm32(1), index);
1493
1494         failures.link(this);
1495
1496         storeToFrame(countRegister, term.frameLocation);
1497
1498         state.setBacktrackLabel(backtrackBegin);
1499     }
1500
1501     void generateCharacterClassNonGreedy(TermGenerationState& state)
1502     {
1503         const RegisterID character = regT0;
1504         const RegisterID countRegister = regT1;
1505         PatternTerm& term = state.term();
1506
1507         move(Imm32(0), countRegister);
1508
1509         Jump firstTimeDoNothing = jump();
1510
1511         Label hardFail(this);
1512         sub32(countRegister, index);
1513         state.jumpToBacktrack(this);
1514
1515         Label backtrackBegin(this);
1516         loadFromFrame(term.frameLocation, countRegister);
1517
1518         atEndOfInput().linkTo(hardFail, this);
1519         branch32(Equal, countRegister, Imm32(term.quantityCount), hardFail);
1520
1521         JumpList matchDest;
1522         readCharacter(state.inputOffset(), character);
1523         matchCharacterClass(character, matchDest, term.characterClass);
1524
1525         if (term.invert())
1526             matchDest.linkTo(hardFail, this);
1527         else {
1528             jump(hardFail);
1529             matchDest.link(this);
1530         }
1531
1532         add32(Imm32(1), countRegister);
1533         add32(Imm32(1), index);
1534
1535         firstTimeDoNothing.link(this);
1536         storeToFrame(countRegister, term.frameLocation);
1537
1538         state.setBacktrackLabel(backtrackBegin);
1539     }
1540
1541     void generateParenthesesDisjunction(PatternTerm& parenthesesTerm, TermGenerationState& state, unsigned alternativeFrameLocation)
1542     {
1543         ASSERT((parenthesesTerm.type == PatternTerm::TypeParenthesesSubpattern) || (parenthesesTerm.type == PatternTerm::TypeParentheticalAssertion));
1544         ASSERT(parenthesesTerm.quantityCount == 1);
1545
1546         PatternDisjunction* disjunction = parenthesesTerm.parentheses.disjunction;
1547         unsigned preCheckedCount = ((parenthesesTerm.quantityType == QuantifierFixedCount) && (parenthesesTerm.type != PatternTerm::TypeParentheticalAssertion)) ? disjunction->m_minimumSize : 0;
1548
1549         if (disjunction->m_alternatives.size() == 1) {
1550             state.resetAlternative();
1551             ASSERT(state.alternativeValid());
1552             PatternAlternative* alternative = state.alternative();
1553             optimizeAlternative(alternative);
1554
1555             int countToCheck = alternative->m_minimumSize - preCheckedCount;
1556             if (countToCheck) {
1557                 ASSERT((parenthesesTerm.type == PatternTerm::TypeParentheticalAssertion) || (parenthesesTerm.quantityType != QuantifierFixedCount));
1558
1559                 // FIXME: This is quite horrible.  The call to 'plantJumpToBacktrackIfExists'
1560                 // will be forced to always trampoline into here, just to decrement the index.
1561                 // Ick. 
1562                 Jump skip = jump();
1563
1564                 Label backtrackBegin(this);
1565                 sub32(Imm32(countToCheck), index);
1566                 state.addBacktrackJump(jump());
1567
1568                 skip.link(this);
1569
1570                 state.setBacktrackLabel(backtrackBegin);
1571
1572                 state.jumpToBacktrack(this, jumpIfNoAvailableInput(countToCheck));
1573                 state.checkedTotal += countToCheck;
1574             }
1575
1576             for (state.resetTerm(); state.termValid(); state.nextTerm())
1577                 generateTerm(state);
1578
1579             state.checkedTotal -= countToCheck;
1580         } else {
1581             JumpList successes;
1582             bool propogateBacktrack = false;
1583
1584             for (state.resetAlternative(); state.alternativeValid(); state.nextAlternative()) {
1585
1586                 PatternAlternative* alternative = state.alternative();
1587                 optimizeAlternative(alternative);
1588
1589                 ASSERT(alternative->m_minimumSize >= preCheckedCount);
1590                 int countToCheck = alternative->m_minimumSize - preCheckedCount;
1591                 if (countToCheck) {
1592                     state.addBacktrackJump(jumpIfNoAvailableInput(countToCheck));
1593                     state.checkedTotal += countToCheck;
1594                 }
1595
1596                 for (state.resetTerm(); state.termValid(); state.nextTerm())
1597                     generateTerm(state);
1598
1599                 // Matched an alternative.
1600                 DataLabelPtr dataLabel = storeToFrameWithPatch(alternativeFrameLocation);
1601
1602                 if (!state.isLastAlternative() || countToCheck)
1603                     successes.append(jump());
1604
1605                 // Alternative did not match.
1606
1607                 // Do we have a backtrack destination?
1608                 //    if so, link the data label to it.
1609                 state.linkDataLabelToBacktrackIfExists(this, dataLabel);
1610
1611                 if (!state.isLastAlternative() || countToCheck)
1612                     state.linkAlternativeBacktracks(this);
1613
1614                 if (countToCheck) {
1615                     sub32(Imm32(countToCheck), index);
1616                     state.checkedTotal -= countToCheck;
1617                 } else if (state.isLastAlternative())
1618                     propogateBacktrack = true;
1619             }
1620             // We fall through to here when the last alternative fails.
1621             // Add a backtrack out of here for the parenthese handling code to link up.
1622             if (!propogateBacktrack)
1623                 state.addBacktrackJump(jump());
1624
1625             // Save address on stack for the parens code to backtrack to, to retry the
1626             // next alternative.
1627             state.setBackTrackStackOffset(alternativeFrameLocation * sizeof(void*));
1628
1629             successes.link(this);
1630         }
1631     }
1632
1633     void generateParenthesesSingle(TermGenerationState& state)
1634     {
1635         const RegisterID indexTemporary = regT0;
1636         PatternTerm& term = state.term();
1637         PatternDisjunction* disjunction = term.parentheses.disjunction;
1638         ASSERT(term.quantityCount == 1);
1639
1640         unsigned preCheckedCount = (term.quantityType == QuantifierFixedCount) ? disjunction->m_minimumSize : 0;
1641
1642         unsigned parenthesesFrameLocation = term.frameLocation;
1643         unsigned alternativeFrameLocation = parenthesesFrameLocation;
1644         if (term.quantityType != QuantifierFixedCount)
1645             alternativeFrameLocation += YarrStackSpaceForBackTrackInfoParenthesesOnce;
1646
1647         // optimized case - no capture & no quantifier can be handled in a light-weight manner.
1648         if (!term.capture() && (term.quantityType == QuantifierFixedCount)) {
1649             m_expressionState.incrementParenNestingLevel();
1650
1651             TermGenerationState parenthesesState(disjunction, state.checkedTotal);
1652             
1653             // Use the current paren Tail to connect the nested parentheses.
1654             parenthesesState.setParenthesesTail(state.getParenthesesTail());
1655
1656             generateParenthesesDisjunction(state.term(), parenthesesState, alternativeFrameLocation);
1657             // this expects that any backtracks back out of the parentheses will be in the
1658             // parenthesesState's m_backTrackJumps vector, and that if they need backtracking
1659             // they will have set an entry point on the parenthesesState's m_backtrackLabel.
1660             BacktrackDestination& parenthesesBacktrack = parenthesesState.getBacktrackDestination();
1661             BacktrackDestination& stateBacktrack = state.getBacktrackDestination();
1662
1663             state.propagateBacktrackingFrom(this, parenthesesBacktrack);
1664             stateBacktrack.propagateBacktrackToLabel(parenthesesBacktrack);
1665
1666             m_expressionState.decrementParenNestingLevel();
1667         } else {
1668             Jump nonGreedySkipParentheses;
1669             Label nonGreedyTryParentheses;
1670             if (term.quantityType == QuantifierGreedy)
1671                 storeToFrame(index, parenthesesFrameLocation);
1672             else if (term.quantityType == QuantifierNonGreedy) {
1673                 storeToFrame(Imm32(-1), parenthesesFrameLocation);
1674                 nonGreedySkipParentheses = jump();
1675                 nonGreedyTryParentheses = label();
1676                 storeToFrame(index, parenthesesFrameLocation);
1677             }
1678
1679             // store the match start index
1680             if (term.capture()) {
1681                 int inputOffset = state.inputOffset() - preCheckedCount;
1682                 if (inputOffset) {
1683                     move(index, indexTemporary);
1684                     add32(Imm32(inputOffset), indexTemporary);
1685                     store32(indexTemporary, Address(output, (term.parentheses.subpatternId << 1) * sizeof(int)));
1686                 } else
1687                     store32(index, Address(output, (term.parentheses.subpatternId << 1) * sizeof(int)));
1688             }
1689
1690             ParenthesesTail* parenthesesTail = m_expressionState.addParenthesesTail(term, state.getParenthesesTail());
1691
1692             m_expressionState.incrementParenNestingLevel();
1693
1694             TermGenerationState parenthesesState(disjunction, state.checkedTotal);
1695
1696             // Save the parenthesesTail for backtracking from nested parens to this one.
1697             parenthesesState.setParenthesesTail(parenthesesTail);
1698
1699             // generate the body of the parentheses
1700             generateParenthesesDisjunction(state.term(), parenthesesState, alternativeFrameLocation);
1701
1702             // For non-fixed counts, backtrack if we didn't match anything.
1703             if (term.quantityType != QuantifierFixedCount)
1704                 parenthesesTail->addAfterParenJump(branch32(Equal, index, Address(stackPointerRegister, (parenthesesFrameLocation * sizeof(void*)))));
1705
1706             // store the match end index
1707             if (term.capture()) {
1708                 int inputOffset = state.inputOffset();
1709                 if (inputOffset) {
1710                     move(index, indexTemporary);
1711                     add32(Imm32(state.inputOffset()), indexTemporary);
1712                     store32(indexTemporary, Address(output, ((term.parentheses.subpatternId << 1) + 1) * sizeof(int)));
1713                 } else
1714                     store32(index, Address(output, ((term.parentheses.subpatternId << 1) + 1) * sizeof(int)));
1715             }
1716
1717             m_expressionState.decrementParenNestingLevel();
1718
1719             parenthesesTail->processBacktracks(this, state, parenthesesState, nonGreedyTryParentheses, label());
1720
1721             parenthesesState.getBacktrackDestination().clear();
1722
1723             if (term.quantityType == QuantifierNonGreedy)
1724                 nonGreedySkipParentheses.link(this);
1725         }
1726     }
1727
1728     void generateParenthesesGreedyNoBacktrack(TermGenerationState& state)
1729     {
1730         PatternTerm& parenthesesTerm = state.term();
1731         PatternDisjunction* disjunction = parenthesesTerm.parentheses.disjunction;
1732         ASSERT(parenthesesTerm.type == PatternTerm::TypeParenthesesSubpattern);
1733         ASSERT(parenthesesTerm.quantityCount != 1); // Handled by generateParenthesesSingle.
1734
1735         TermGenerationState parenthesesState(disjunction, state.checkedTotal);
1736
1737         Label matchAgain(this);
1738
1739         storeToFrame(index, parenthesesTerm.frameLocation); // Save the current index to check for zero len matches later.
1740
1741         for (parenthesesState.resetAlternative(); parenthesesState.alternativeValid(); parenthesesState.nextAlternative()) {
1742
1743             PatternAlternative* alternative = parenthesesState.alternative();
1744             optimizeAlternative(alternative);
1745
1746             int countToCheck = alternative->m_minimumSize;
1747             if (countToCheck) {
1748                 parenthesesState.addBacktrackJump(jumpIfNoAvailableInput(countToCheck));
1749                 parenthesesState.checkedTotal += countToCheck;
1750             }
1751
1752             for (parenthesesState.resetTerm(); parenthesesState.termValid(); parenthesesState.nextTerm())
1753                 generateTerm(parenthesesState);
1754
1755             // If we get here, we matched! If the index advanced then try to match more since limit isn't supported yet.
1756             branch32(NotEqual, index, Address(stackPointerRegister, (parenthesesTerm.frameLocation * sizeof(void*))), matchAgain);
1757
1758             // If we get here we matched, but we matched "" - cannot accept this alternative as is, so either backtrack,
1759             // or fall through to try the next alternative if no backtrack is available.
1760             parenthesesState.plantJumpToBacktrackIfExists(this);
1761
1762             parenthesesState.linkAlternativeBacktracks(this);
1763
1764             // We get here if the alternative fails to match - fall through to the next iteration, or out of the loop.
1765
1766             if (countToCheck) {
1767                 sub32(Imm32(countToCheck), index);
1768                 parenthesesState.checkedTotal -= countToCheck;
1769             }
1770         }
1771
1772         // If the last alternative falls through to here, we have a failed match...
1773         // Which means that we match whatever we have matched up to this point (even if nothing).
1774     }
1775
1776     void generateParentheticalAssertion(TermGenerationState& state)
1777     {
1778         PatternTerm& term = state.term();
1779         PatternDisjunction* disjunction = term.parentheses.disjunction;
1780         ASSERT(term.quantityCount == 1);
1781         ASSERT(term.quantityType == QuantifierFixedCount);
1782
1783         unsigned parenthesesFrameLocation = term.frameLocation;
1784         unsigned alternativeFrameLocation = parenthesesFrameLocation + YarrStackSpaceForBackTrackInfoParentheticalAssertion;
1785
1786         int countCheckedAfterAssertion = state.checkedTotal - term.inputPosition;
1787
1788         if (term.invert()) {
1789             // Inverted case
1790             storeToFrame(index, parenthesesFrameLocation);
1791
1792             state.checkedTotal -= countCheckedAfterAssertion;
1793             if (countCheckedAfterAssertion)
1794                 sub32(Imm32(countCheckedAfterAssertion), index);
1795
1796             TermGenerationState parenthesesState(disjunction, state.checkedTotal);
1797             generateParenthesesDisjunction(state.term(), parenthesesState, alternativeFrameLocation);
1798             // Success! - which means - Fail!
1799             loadFromFrame(parenthesesFrameLocation, index);
1800             state.jumpToBacktrack(this);
1801
1802             // And fail means success.
1803             parenthesesState.linkAlternativeBacktracks(this);
1804
1805             loadFromFrame(parenthesesFrameLocation, index);
1806
1807             state.checkedTotal += countCheckedAfterAssertion;
1808         } else {
1809             // Normal case
1810             storeToFrame(index, parenthesesFrameLocation);
1811
1812             state.checkedTotal -= countCheckedAfterAssertion;
1813             if (countCheckedAfterAssertion)
1814                 sub32(Imm32(countCheckedAfterAssertion), index);
1815
1816             TermGenerationState parenthesesState(disjunction, state.checkedTotal);
1817             generateParenthesesDisjunction(state.term(), parenthesesState, alternativeFrameLocation);
1818             // Success! - which means - Success!
1819             loadFromFrame(parenthesesFrameLocation, index);
1820             Jump success = jump();
1821
1822             parenthesesState.linkAlternativeBacktracks(this);
1823
1824             loadFromFrame(parenthesesFrameLocation, index);
1825             state.jumpToBacktrack(this);
1826
1827             success.link(this);
1828
1829             state.checkedTotal += countCheckedAfterAssertion;
1830         }
1831     }
1832
1833     void generateTerm(TermGenerationState& state)
1834     {
1835         PatternTerm& term = state.term();
1836
1837         switch (term.type) {
1838         case PatternTerm::TypeAssertionBOL:
1839             generateAssertionBOL(state);
1840             break;
1841
1842         case PatternTerm::TypeAssertionEOL:
1843             generateAssertionEOL(state);
1844             break;
1845
1846         case PatternTerm::TypeAssertionWordBoundary:
1847             generateAssertionWordBoundary(state);
1848             break;
1849
1850         case PatternTerm::TypePatternCharacter:
1851             switch (term.quantityType) {
1852             case QuantifierFixedCount:
1853                 if (term.quantityCount == 1) {
1854                     if (state.isSinglePatternCharacterLookaheadTerm() && (state.lookaheadTerm().inputPosition == (term.inputPosition + 1))) {
1855                         generatePatternCharacterPair(state);
1856                         state.nextTerm();
1857                     } else
1858                         generatePatternCharacterSingle(state);
1859                 } else
1860                     generatePatternCharacterFixed(state);
1861                 break;
1862             case QuantifierGreedy:
1863                 generatePatternCharacterGreedy(state);
1864                 break;
1865             case QuantifierNonGreedy:
1866                 generatePatternCharacterNonGreedy(state);
1867                 break;
1868             }
1869             break;
1870
1871         case PatternTerm::TypeCharacterClass:
1872             switch (term.quantityType) {
1873             case QuantifierFixedCount:
1874                 if (term.quantityCount == 1)
1875                     generateCharacterClassSingle(state);
1876                 else
1877                     generateCharacterClassFixed(state);
1878                 break;
1879             case QuantifierGreedy:
1880                 generateCharacterClassGreedy(state);
1881                 break;
1882             case QuantifierNonGreedy:
1883                 generateCharacterClassNonGreedy(state);
1884                 break;
1885             }
1886             break;
1887
1888         case PatternTerm::TypeBackReference:
1889             m_shouldFallBack = true;
1890             break;
1891
1892         case PatternTerm::TypeForwardReference:
1893             break;
1894
1895         case PatternTerm::TypeParenthesesSubpattern:
1896             if (term.quantityCount == 1 && !term.parentheses.isCopy)
1897                 generateParenthesesSingle(state);
1898             else if (term.parentheses.isTerminal)
1899                 generateParenthesesGreedyNoBacktrack(state);
1900             else
1901                 m_shouldFallBack = true;
1902             break;
1903
1904         case PatternTerm::TypeParentheticalAssertion:
1905             generateParentheticalAssertion(state);
1906             break;
1907         }
1908     }
1909
1910     void generateDisjunction(PatternDisjunction* disjunction)
1911     {
1912         TermGenerationState state(disjunction, 0);
1913         state.resetAlternative();
1914
1915         // check availability for the next alternative
1916         int countCheckedForCurrentAlternative = 0;
1917         int countToCheckForFirstAlternative = 0;
1918         bool hasShorterAlternatives = false;
1919         bool setRepeatAlternativeLabels = false;
1920         JumpList notEnoughInputForPreviousAlternative;
1921         Label firstAlternative;
1922         Label firstAlternativeInputChecked;
1923
1924         // The label 'firstAlternative' is used to plant a check to see if there is 
1925         // sufficient input available to run the first repeating alternative.
1926         // The label 'firstAlternativeInputChecked' will jump directly to matching 
1927         // the first repeating alternative having skipped this check.
1928
1929         if (state.alternativeValid()) {
1930             PatternAlternative* alternative = state.alternative();
1931             if (!alternative->onceThrough()) {
1932                 firstAlternative = Label(this);
1933                 setRepeatAlternativeLabels = true;
1934             }
1935             countToCheckForFirstAlternative = alternative->m_minimumSize;
1936             state.checkedTotal += countToCheckForFirstAlternative;
1937             if (countToCheckForFirstAlternative)
1938                 notEnoughInputForPreviousAlternative.append(jumpIfNoAvailableInput(countToCheckForFirstAlternative));
1939             countCheckedForCurrentAlternative = countToCheckForFirstAlternative;
1940         }
1941
1942         if (setRepeatAlternativeLabels)
1943             firstAlternativeInputChecked = Label(this);
1944
1945         while (state.alternativeValid()) {
1946             PatternAlternative* alternative = state.alternative();
1947             optimizeAlternative(alternative);
1948
1949             // Track whether any alternatives are shorter than the first one.
1950             if (!alternative->onceThrough())
1951                 hasShorterAlternatives = hasShorterAlternatives || (countCheckedForCurrentAlternative < countToCheckForFirstAlternative);
1952
1953             for (state.resetTerm(); state.termValid(); state.nextTerm())
1954                 generateTerm(state);
1955
1956             // If we get here, the alternative matched.
1957             if (m_pattern.m_body->m_callFrameSize)
1958                 addPtr(Imm32(m_pattern.m_body->m_callFrameSize * sizeof(void*)), stackPointerRegister);
1959
1960             ASSERT(index != returnRegister);
1961             if (m_pattern.m_body->m_hasFixedSize) {
1962                 move(index, returnRegister);
1963                 if (alternative->m_minimumSize)
1964                     sub32(Imm32(alternative->m_minimumSize), returnRegister);
1965
1966                 store32(returnRegister, output);
1967             } else
1968                 load32(Address(output), returnRegister);
1969
1970             store32(index, Address(output, 4));
1971
1972             generateReturn();
1973
1974             state.nextAlternative();
1975             if (alternative->onceThrough() && state.alternativeValid())
1976                 state.clearBacktrack();
1977
1978             // if there are any more alternatives, plant the check for input before looping.
1979             if (state.alternativeValid()) {
1980                 PatternAlternative* nextAlternative = state.alternative();
1981                 if (!setRepeatAlternativeLabels && !nextAlternative->onceThrough()) {
1982                     // We have handled non-repeating alternatives, jump to next iteration 
1983                     // and loop over repeating alternatives.
1984                     state.jumpToBacktrack(this);
1985
1986                     countToCheckForFirstAlternative = nextAlternative->m_minimumSize;
1987
1988                     // If we get here, there the last input checked failed.
1989                     notEnoughInputForPreviousAlternative.link(this);
1990
1991                     state.linkAlternativeBacktracks(this);
1992
1993                     // Back up to start the looping alternatives.
1994                     if (countCheckedForCurrentAlternative)
1995                         sub32(Imm32(countCheckedForCurrentAlternative), index);
1996
1997                     firstAlternative = Label(this);
1998
1999                     state.checkedTotal = countToCheckForFirstAlternative;
2000                     if (countToCheckForFirstAlternative)
2001                         notEnoughInputForPreviousAlternative.append(jumpIfNoAvailableInput(countToCheckForFirstAlternative));
2002
2003                     countCheckedForCurrentAlternative = countToCheckForFirstAlternative;
2004
2005                     firstAlternativeInputChecked = Label(this);
2006
2007                     setRepeatAlternativeLabels = true;
2008                 } else {
2009                     int countToCheckForNextAlternative = nextAlternative->m_minimumSize;
2010
2011                     if (countCheckedForCurrentAlternative > countToCheckForNextAlternative) { // CASE 1: current alternative was longer than the next one.
2012                         // If we get here, then the last input checked failed.
2013                         notEnoughInputForPreviousAlternative.link(this);
2014
2015                         // Check if sufficent input available to run the next alternative 
2016                         notEnoughInputForPreviousAlternative.append(jumpIfNoAvailableInput(countToCheckForNextAlternative - countCheckedForCurrentAlternative));
2017                         // We are now in the correct state to enter the next alternative; this add is only required
2018                         // to mirror and revert operation of the sub32, just below.
2019                         add32(Imm32(countCheckedForCurrentAlternative - countToCheckForNextAlternative), index);
2020
2021                         // If we get here, then the last input checked passed.
2022                         state.linkAlternativeBacktracks(this);
2023
2024                         // No need to check if we can run the next alternative, since it is shorter -
2025                         // just update index.
2026                         sub32(Imm32(countCheckedForCurrentAlternative - countToCheckForNextAlternative), index);
2027                     } else if (countCheckedForCurrentAlternative < countToCheckForNextAlternative) { // CASE 2: next alternative is longer than the current one.
2028                         // If we get here, then the last input checked failed.
2029                         // If there is insufficient input to run the current alternative, and the next alternative is longer,
2030                         // then there is definitely not enough input to run it - don't even check. Just adjust index, as if
2031                         // we had checked.
2032                         notEnoughInputForPreviousAlternative.link(this);
2033                         add32(Imm32(countToCheckForNextAlternative - countCheckedForCurrentAlternative), index);
2034                         notEnoughInputForPreviousAlternative.append(jump());
2035
2036                         // The next alternative is longer than the current one; check the difference.
2037                         state.linkAlternativeBacktracks(this);
2038
2039                         notEnoughInputForPreviousAlternative.append(jumpIfNoAvailableInput(countToCheckForNextAlternative - countCheckedForCurrentAlternative));
2040                     } else { // CASE 3: Both alternatives are the same length.
2041                         ASSERT(countCheckedForCurrentAlternative == countToCheckForNextAlternative);
2042
2043                         // If the next alterative is the same length as this one, then no need to check the input -
2044                         // if there was sufficent input to run the current alternative then there is sufficient
2045                         // input to run the next one; if not, there isn't.
2046                         state.linkAlternativeBacktracks(this);
2047                     }
2048                     state.checkedTotal -= countCheckedForCurrentAlternative;
2049                     countCheckedForCurrentAlternative = countToCheckForNextAlternative;
2050                     state.checkedTotal += countCheckedForCurrentAlternative;
2051                 }
2052             }
2053         }
2054
2055         // If we get here, all Alternatives failed...
2056
2057         state.checkedTotal -= countCheckedForCurrentAlternative;
2058
2059         if (!setRepeatAlternativeLabels) {
2060             // If there are no alternatives that need repeating (all are marked 'onceThrough') then just link
2061             // the match failures to this point, and fall through to the return below.
2062             state.linkAlternativeBacktracks(this, true);
2063
2064             notEnoughInputForPreviousAlternative.link(this);
2065         } else {
2066             // How much more input need there be to be able to retry from the first alternative?
2067             // examples:
2068             //   /yarr_jit/ or /wrec|pcre/
2069             //     In these examples we need check for one more input before looping.
2070             //   /yarr_jit|pcre/
2071             //     In this case we need check for 5 more input to loop (+4 to allow for the first alterative
2072             //     being four longer than the last alternative checked, and another +1 to effectively move
2073             //     the start position along by one).
2074             //   /yarr|rules/ or /wrec|notsomuch/
2075             //     In these examples, provided that there was sufficient input to have just been matching for
2076             //     the second alternative we can loop without checking for available input (since the second
2077             //     alternative is longer than the first).  In the latter example we need to decrement index
2078             //     (by 4) so the start position is only progressed by 1 from the last iteration.
2079             int incrementForNextIter = (countToCheckForFirstAlternative - countCheckedForCurrentAlternative) + 1;
2080
2081             // First, deal with the cases where there was sufficient input to try the last alternative.
2082             if (incrementForNextIter > 0) // We need to check for more input anyway, fall through to the checking below.
2083                 state.linkAlternativeBacktracks(this, true);
2084             else if (m_pattern.m_body->m_hasFixedSize && !incrementForNextIter) // No need to update anything, link these backtracks straight to the to pof the loop!
2085                 state.linkAlternativeBacktracksTo(this, firstAlternativeInputChecked, true);
2086             else { // no need to check the input, but we do have some bookkeeping to do first.
2087                 state.linkAlternativeBacktracks(this, true);
2088
2089                 // Where necessary update our preserved start position.
2090                 if (!m_pattern.m_body->m_hasFixedSize) {
2091                     move(index, regT0);
2092                     sub32(Imm32(countCheckedForCurrentAlternative - 1), regT0);
2093                     store32(regT0, Address(output));
2094                 }
2095
2096                 // Update index if necessary, and loop (without checking).
2097                 if (incrementForNextIter)
2098                     add32(Imm32(incrementForNextIter), index);
2099                 jump().linkTo(firstAlternativeInputChecked, this);
2100             }
2101
2102             notEnoughInputForPreviousAlternative.link(this);
2103             // Update our idea of the start position, if we're tracking this.
2104             if (!m_pattern.m_body->m_hasFixedSize) {
2105                 if (countCheckedForCurrentAlternative - 1) {
2106                     move(index, regT0);
2107                     sub32(Imm32(countCheckedForCurrentAlternative - 1), regT0);
2108                     store32(regT0, Address(output));
2109                 } else
2110                     store32(index, Address(output));
2111             }
2112
2113             // Check if there is sufficent input to run the first alternative again.
2114             jumpIfAvailableInput(incrementForNextIter).linkTo(firstAlternativeInputChecked, this);
2115             // No - insufficent input to run the first alteranative, are there any other alternatives we
2116             // might need to check?  If so, the last check will have left the index incremented by
2117             // (countToCheckForFirstAlternative + 1), so we need test whether countToCheckForFirstAlternative
2118             // LESS input is available, to have the effect of just progressing the start position by 1
2119             // from the last iteration.  If this check passes we can just jump up to the check associated
2120             // with the first alternative in the loop.  This is a bit sad, since we'll end up trying the
2121             // first alternative again, and this check will fail (otherwise the check planted just above
2122             // here would have passed).  This is a bit sad, however it saves trying to do something more
2123             // complex here in compilation, and in the common case we should end up coallescing the checks.
2124             //
2125             // FIXME: a nice improvement here may be to stop trying to match sooner, based on the least
2126             // of the minimum-alternative-lengths.  E.g. if I have two alternatives of length 200 and 150,
2127             // and a string of length 100, we'll end up looping index from 0 to 100, checking whether there
2128             // is sufficient input to run either alternative (constantly failing).  If there had been only
2129             // one alternative, or if the shorter alternative had come first, we would have terminated
2130             // immediately. :-/
2131             if (hasShorterAlternatives)
2132                 jumpIfAvailableInput(-countToCheckForFirstAlternative).linkTo(firstAlternative, this);
2133             // index will now be a bit garbled (depending on whether 'hasShorterAlternatives' is true,
2134             // it has either been incremented by 1 or by (countToCheckForFirstAlternative + 1) ... 
2135             // but since we're about to return a failure this doesn't really matter!)
2136         }
2137
2138         if (m_pattern.m_body->m_callFrameSize)
2139             addPtr(Imm32(m_pattern.m_body->m_callFrameSize * sizeof(void*)), stackPointerRegister);
2140
2141         move(Imm32(-1), returnRegister);
2142
2143         generateReturn();
2144
2145         m_expressionState.emitParenthesesTail(this);
2146         m_expressionState.emitIndirectJumpTable(this);
2147         m_expressionState.linkToNextIteration(this);
2148     }
2149
2150     void generateEnter()
2151     {
2152 #if CPU(X86_64)
2153         push(X86Registers::ebp);
2154         move(stackPointerRegister, X86Registers::ebp);
2155         push(X86Registers::ebx);
2156 #elif CPU(X86)
2157         push(X86Registers::ebp);
2158         move(stackPointerRegister, X86Registers::ebp);
2159         // TODO: do we need spill registers to fill the output pointer if there are no sub captures?
2160         push(X86Registers::ebx);
2161         push(X86Registers::edi);
2162         push(X86Registers::esi);
2163         // load output into edi (2 = saved ebp + return address).
2164     #if COMPILER(MSVC)
2165         loadPtr(Address(X86Registers::ebp, 2 * sizeof(void*)), input);
2166         loadPtr(Address(X86Registers::ebp, 3 * sizeof(void*)), index);
2167         loadPtr(Address(X86Registers::ebp, 4 * sizeof(void*)), length);
2168         loadPtr(Address(X86Registers::ebp, 5 * sizeof(void*)), output);
2169     #else
2170         loadPtr(Address(X86Registers::ebp, 2 * sizeof(void*)), output);
2171     #endif
2172 #elif CPU(ARM)
2173         push(ARMRegisters::r4);
2174         push(ARMRegisters::r5);
2175         push(ARMRegisters::r6);
2176 #if CPU(ARM_TRADITIONAL)
2177         push(ARMRegisters::r8); // scratch register
2178 #endif
2179         move(ARMRegisters::r3, output);
2180 #elif CPU(MIPS)
2181         // Do nothing.
2182 #endif
2183     }
2184
2185     void generateReturn()
2186     {
2187 #if CPU(X86_64)
2188         pop(X86Registers::ebx);
2189         pop(X86Registers::ebp);
2190 #elif CPU(X86)
2191         pop(X86Registers::esi);
2192         pop(X86Registers::edi);
2193         pop(X86Registers::ebx);
2194         pop(X86Registers::ebp);
2195 #elif CPU(ARM)
2196 #if CPU(ARM_TRADITIONAL)
2197         pop(ARMRegisters::r8); // scratch register
2198 #endif
2199         pop(ARMRegisters::r6);
2200         pop(ARMRegisters::r5);
2201         pop(ARMRegisters::r4);
2202 #elif CPU(MIPS)
2203         // Do nothing
2204 #endif
2205         ret();
2206     }
2207
2208 public:
2209     YarrGenerator(YarrPattern& pattern)
2210         : m_pattern(pattern)
2211         , m_shouldFallBack(false)
2212     {
2213     }
2214
2215     void generate()
2216     {
2217         generateEnter();
2218
2219         if (!m_pattern.m_body->m_hasFixedSize)
2220             store32(index, Address(output));
2221
2222         if (m_pattern.m_body->m_callFrameSize)
2223             subPtr(Imm32(m_pattern.m_body->m_callFrameSize * sizeof(void*)), stackPointerRegister);
2224
2225         generateDisjunction(m_pattern.m_body);
2226     }
2227
2228     void compile(JSGlobalData* globalData, YarrCodeBlock& jitObject)
2229     {
2230         generate();
2231
2232         LinkBuffer patchBuffer(this, globalData->regexAllocator.poolForSize(size()), 0);
2233
2234         for (unsigned i = 0; i < m_expressionState.m_backtrackRecords.size(); ++i)
2235             patchBuffer.patch(m_expressionState.m_backtrackRecords[i].dataLabel, patchBuffer.locationOf(m_expressionState.m_backtrackRecords[i].backtrackLocation));
2236
2237         jitObject.set(patchBuffer.finalizeCode());
2238         jitObject.setFallBack(m_shouldFallBack);
2239     }
2240
2241 private:
2242     YarrPattern& m_pattern;
2243     bool m_shouldFallBack;
2244     GenerationState m_expressionState;
2245 };
2246
2247 void jitCompile(YarrPattern& pattern, JSGlobalData* globalData, YarrCodeBlock& jitObject)
2248 {
2249     YarrGenerator(pattern).compile(globalData, jitObject);
2250 }
2251
2252 int execute(YarrCodeBlock& jitObject, const UChar* input, unsigned start, unsigned length, int* output)
2253 {
2254     return jitObject.execute(input, start, length, output);
2255 }
2256
2257 }}
2258
2259 #endif