Chromium Code Reviews| Index: runtime/vm/regexp.cc |
| diff --git a/runtime/vm/regexp.cc b/runtime/vm/regexp.cc |
| index db1015f908432eb417ffd841eea6edbdac7e996d..fc4b06ffddba7dbd46b552c8369d264c6a6754f5 100644 |
| --- a/runtime/vm/regexp.cc |
| +++ b/runtime/vm/regexp.cc |
| @@ -4,7 +4,10 @@ |
| #include "vm/regexp.h" |
| +#include "vm/dart_entry.h" |
| +#include "vm/regexp_assembler.h" |
| #include "vm/regexp_ast.h" |
| +#include "vm/unibrow-inl.h" |
| #include "vm/unicode.h" |
| #include "vm/symbols.h" |
| @@ -13,6 +16,7 @@ |
| namespace dart { |
| +DECLARE_FLAG(bool, trace_irregexp); |
| #define DEFINE_ACCEPT(Type) \ |
| void Type##Node::Accept(NodeVisitor* visitor) { \ |
| @@ -45,6 +49,8 @@ static const intptr_t kWordRanges[] = { |
| static const intptr_t kWordRangeCount = ARRAY_SIZE(kWordRanges); |
| static const intptr_t kDigitRanges[] = { '0', '9' + 1, 0x10000 }; |
| static const intptr_t kDigitRangeCount = ARRAY_SIZE(kDigitRanges); |
| +static const intptr_t kSurrogateRanges[] = { 0xd800, 0xe000, 0x10000 }; |
| +static const intptr_t kSurrogateRangeCount = ARRAY_SIZE(kSurrogateRanges); |
| static const intptr_t kLineTerminatorRanges[] = { |
| 0x000A, 0x000B, 0x000D, 0x000E, 0x2028, 0x202A, 0x10000 }; |
| static const intptr_t kLineTerminatorRangeCount = |
| @@ -105,24 +111,75 @@ class VisitMarker { |
| }; |
| +class FrequencyCollator : public ValueObject { |
| + public: |
| + FrequencyCollator() : total_samples_(0) { |
| + for (intptr_t i = 0; i < RegExpMacroAssembler::kTableSize; i++) { |
| + frequencies_[i] = CharacterFrequency(i); |
| + } |
| + } |
| + |
| + void CountCharacter(intptr_t character) { |
| + intptr_t index = (character & RegExpMacroAssembler::kTableMask); |
| + frequencies_[index].Increment(); |
| + total_samples_++; |
| + } |
| + |
| + // Does not measure in percent, but rather per-128 (the table size from the |
| + // regexp macro assembler). |
| + intptr_t Frequency(intptr_t in_character) { |
| + ASSERT((in_character & RegExpMacroAssembler::kTableMask) == in_character); |
| + if (total_samples_ < 1) return 1; // Division by zero. |
| + intptr_t freq_in_per128 = |
| + (frequencies_[in_character].counter() * 128) / total_samples_; |
| + return freq_in_per128; |
| + } |
| + |
| + private: |
| + class CharacterFrequency { |
| + public: |
| + CharacterFrequency() : counter_(0), character_(-1) { } |
| + explicit CharacterFrequency(intptr_t character) |
| + : counter_(0), character_(character) { } |
| + |
| + void Increment() { counter_++; } |
| + intptr_t counter() { return counter_; } |
| + intptr_t character() { return character_; } |
| + |
| + private: |
| + intptr_t counter_; |
| + intptr_t character_; |
| + }; |
| + |
| + |
| + private: |
| + CharacterFrequency frequencies_[RegExpMacroAssembler::kTableSize]; |
| + intptr_t total_samples_; |
| +}; |
| + |
| + |
| class RegExpCompiler { |
| public: |
| - RegExpCompiler(intptr_t capture_count, bool ignore_case, bool is_ascii); |
| + RegExpCompiler(intptr_t capture_count, |
| + bool ignore_case, |
| + intptr_t specialization_cid); |
| intptr_t AllocateRegister() { |
| return next_register_++; |
| } |
| - RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler, |
| + RegExpEngine::CompilationResult Assemble(IRRegExpMacroAssembler* assembler, |
| RegExpNode* start, |
| intptr_t capture_count, |
| const String& pattern); |
| + inline void AddWork(RegExpNode* node) { work_list_->Add(node); } |
| + |
| static const intptr_t kImplementationOffset = 0; |
| static const intptr_t kNumberOfRegistersOffset = 0; |
| static const intptr_t kCodeOffset = 1; |
| - RegExpMacroAssembler* macro_assembler() { return macro_assembler_; } |
| + IRRegExpMacroAssembler* macro_assembler() { return macro_assembler_; } |
| EndNode* accept() { return accept_; } |
| static const intptr_t kMaxRecursion = 100; |
| @@ -133,7 +190,12 @@ class RegExpCompiler { |
| void SetRegExpTooBig() { reg_exp_too_big_ = true; } |
| inline bool ignore_case() { return ignore_case_; } |
| - inline bool ascii() { return ascii_; } |
| + inline bool ascii() const { |
| + return (specialization_cid_ == kOneByteStringCid || |
| + specialization_cid_ == kExternalOneByteStringCid); |
| + } |
| + inline intptr_t specialization_cid() { return specialization_cid_; } |
| + FrequencyCollator* frequency_collator() { return &frequency_collator_; } |
| intptr_t current_expansion_factor() { return current_expansion_factor_; } |
| void set_current_expansion_factor(intptr_t value) { |
| @@ -147,19 +209,32 @@ class RegExpCompiler { |
| private: |
| EndNode* accept_; |
| intptr_t next_register_; |
| + ZoneGrowableArray<RegExpNode*>* work_list_; |
| intptr_t recursion_depth_; |
| - RegExpMacroAssembler* macro_assembler_; |
| + IRRegExpMacroAssembler* macro_assembler_; |
| bool ignore_case_; |
| - bool ascii_; |
| + intptr_t specialization_cid_; |
| bool reg_exp_too_big_; |
| intptr_t current_expansion_factor_; |
| + FrequencyCollator frequency_collator_; |
| Isolate* isolate_; |
| }; |
| +class RecursionCheck : public ValueObject { |
| + public: |
| + explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) { |
| + compiler->IncrementRecursionDepth(); |
| + } |
| + ~RecursionCheck() { compiler_->DecrementRecursionDepth(); } |
| + private: |
| + RegExpCompiler* compiler_; |
| +}; |
| + |
| + |
| // Scoped object to keep track of how much we unroll quantifier loops in the |
| // regexp graph generator. |
| -class RegExpExpansionLimiter { |
| +class RegExpExpansionLimiter : public ValueObject { |
| public: |
| static const intptr_t kMaxExpansionFactor = 6; |
| RegExpExpansionLimiter(RegExpCompiler* compiler, intptr_t factor) |
| @@ -708,45 +783,2039 @@ RegExpNode* NegativeLookaheadChoiceNode::FilterASCII(intptr_t depth, |
| } |
| -// Code emission --------------------------------------------------------------- |
| +// Code emission --------------------------------------------------------------- |
| + |
| + |
| +void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler, |
| + Guard* guard, |
| + Trace* trace) { |
| + switch (guard->op()) { |
| + case Guard::LT: |
| + ASSERT(!trace->mentions_reg(guard->reg())); |
| + macro_assembler->IfRegisterGE(guard->reg(), |
| + guard->value(), |
| + trace->backtrack()); |
| + break; |
| + case Guard::GEQ: |
| + ASSERT(!trace->mentions_reg(guard->reg())); |
| + macro_assembler->IfRegisterLT(guard->reg(), |
| + guard->value(), |
| + trace->backtrack()); |
| + break; |
| + } |
| +} |
| + |
| + |
| +void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) { |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + |
| + // Omit flushing the trace. We discard the entire stack frame anyway. |
| + |
| + if (!label()->IsBound()) { |
| + // We are completely independent of the trace, since we ignore it, |
| + // so this code can be used as the generic version. |
| + assembler->BindBlock(label()); |
| + } |
| + |
| + // Throw away everything on the backtrack stack since the start |
| + // of the negative submatch and restore the character position. |
| + assembler->ReadCurrentPositionFromRegister(current_position_register_); |
| + assembler->ReadStackPointerFromRegister(stack_pointer_register_); |
| + if (clear_capture_count_ > 0) { |
| + // Clear any captures that might have been performed during the success |
| + // of the body of the negative look-ahead. |
| + intptr_t clear_capture_end = |
| + clear_capture_start_ + clear_capture_count_ - 1; |
| + assembler->ClearRegisters(clear_capture_start_, clear_capture_end); |
| + } |
| + // Now that we have unwound the stack we find at the top of the stack the |
| + // backtrack that the BeginSubmatch node got. |
| + assembler->Backtrack(); |
| +} |
| + |
| + |
| +bool Trace::GetStoredPosition(intptr_t reg, intptr_t* cp_offset) { |
| + ASSERT(*cp_offset == 0); |
| + for (DeferredAction* action = actions_; |
| + action != NULL; |
| + action = action->next()) { |
| + if (action->Mentions(reg)) { |
| + if (action->action_type() == ActionNode::STORE_POSITION) { |
| + *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset(); |
| + return true; |
| + } else { |
| + return false; |
| + } |
| + } |
| + } |
| + return false; |
| +} |
| + |
| + |
| +// This is called as we come into a loop choice node and some other tricky |
| +// nodes. It normalizes the state of the code generator to ensure we can |
| +// generate generic code. |
| +intptr_t Trace::FindAffectedRegisters(OutSet* affected_registers, |
| + Isolate* isolate) { |
| + intptr_t max_register = RegExpCompiler::kNoRegister; |
| + for (DeferredAction* action = actions_; |
| + action != NULL; |
| + action = action->next()) { |
| + if (action->action_type() == ActionNode::CLEAR_CAPTURES) { |
| + Interval range = static_cast<DeferredClearCaptures*>(action)->range(); |
| + for (intptr_t i = range.from(); i <= range.to(); i++) |
| + affected_registers->Set(i, isolate); |
| + if (range.to() > max_register) max_register = range.to(); |
| + } else { |
| + affected_registers->Set(action->reg(), isolate); |
| + if (action->reg() > max_register) max_register = action->reg(); |
| + } |
| + } |
| + return max_register; |
| +} |
| + |
| + |
| +bool Trace::DeferredAction::Mentions(intptr_t that) { |
| + if (action_type() == ActionNode::CLEAR_CAPTURES) { |
| + Interval range = static_cast<DeferredClearCaptures*>(this)->range(); |
| + return range.Contains(that); |
| + } else { |
| + return reg() == that; |
| + } |
| +} |
| + |
| + |
| +bool Trace::mentions_reg(intptr_t reg) { |
| + for (DeferredAction* action = actions_; |
| + action != NULL; |
| + action = action->next()) { |
| + if (action->Mentions(reg)) |
| + return true; |
| + } |
| + return false; |
| +} |
| + |
| + |
| +void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler, |
| + intptr_t max_register, |
| + const OutSet& registers_to_pop, |
| + const OutSet& registers_to_clear) { |
| + for (intptr_t reg = max_register; reg >= 0; reg--) { |
| + if (registers_to_pop.Get(reg)) { |
| + assembler->PopRegister(reg); |
| + } else if (registers_to_clear.Get(reg)) { |
| + intptr_t clear_to = reg; |
| + while (reg > 0 && registers_to_clear.Get(reg - 1)) { |
| + reg--; |
| + } |
| + assembler->ClearRegisters(reg, clear_to); |
| + } |
| + } |
| +} |
| + |
| + |
| +void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler, |
| + intptr_t max_register, |
| + const OutSet& affected_registers, |
| + OutSet* registers_to_pop, |
| + OutSet* registers_to_clear, |
| + Isolate* isolate) { |
| + // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1. |
| + const intptr_t push_limit = (assembler->stack_limit_slack() + 1) / 2; |
| + |
| + // Count pushes performed to force a stack limit check occasionally. |
| + intptr_t pushes = 0; |
| + |
| + for (intptr_t reg = 0; reg <= max_register; reg++) { |
| + if (!affected_registers.Get(reg)) { |
| + continue; |
| + } |
| + |
| + // The chronologically first deferred action in the trace |
| + // is used to infer the action needed to restore a register |
| + // to its previous state (or not, if it's safe to ignore it). |
| + enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR }; |
| + DeferredActionUndoType undo_action = IGNORE; |
| + |
| + intptr_t value = 0; |
| + bool absolute = false; |
| + bool clear = false; |
| + intptr_t store_position = -1; |
| + // This is a little tricky because we are scanning the actions in reverse |
| + // historical order (newest first). |
| + for (DeferredAction* action = actions_; |
| + action != NULL; |
| + action = action->next()) { |
| + if (action->Mentions(reg)) { |
| + switch (action->action_type()) { |
| + case ActionNode::SET_REGISTER: { |
| + Trace::DeferredSetRegister* psr = |
| + static_cast<Trace::DeferredSetRegister*>(action); |
| + if (!absolute) { |
| + value += psr->value(); |
| + absolute = true; |
| + } |
| + // SET_REGISTER is currently only used for newly introduced loop |
| + // counters. They can have a significant previous value if they |
| + // occour in a loop. TODO(lrn): Propagate this information, so |
| + // we can set undo_action to IGNORE if we know there is no value to |
| + // restore. |
| + undo_action = RESTORE; |
| + ASSERT(store_position == -1); |
| + ASSERT(!clear); |
| + break; |
| + } |
| + case ActionNode::INCREMENT_REGISTER: |
| + if (!absolute) { |
| + value++; |
| + } |
| + ASSERT(store_position == -1); |
| + ASSERT(!clear); |
| + undo_action = RESTORE; |
| + break; |
| + case ActionNode::STORE_POSITION: { |
| + Trace::DeferredCapture* pc = |
| + static_cast<Trace::DeferredCapture*>(action); |
| + if (!clear && store_position == -1) { |
| + store_position = pc->cp_offset(); |
| + } |
| + |
| + // For captures we know that stores and clears alternate. |
| + // Other register, are never cleared, and if the occur |
| + // inside a loop, they might be assigned more than once. |
| + if (reg <= 1) { |
| + // Registers zero and one, aka "capture zero", is |
| + // always set correctly if we succeed. There is no |
| + // need to undo a setting on backtrack, because we |
| + // will set it again or fail. |
| + undo_action = IGNORE; |
| + } else { |
| + undo_action = pc->is_capture() ? CLEAR : RESTORE; |
| + } |
| + ASSERT(!absolute); |
| + ASSERT(value == 0); |
| + break; |
| + } |
| + case ActionNode::CLEAR_CAPTURES: { |
| + // Since we're scanning in reverse order, if we've already |
| + // set the position we have to ignore historically earlier |
| + // clearing operations. |
| + if (store_position == -1) { |
| + clear = true; |
| + } |
| + undo_action = RESTORE; |
| + ASSERT(!absolute); |
| + ASSERT(value == 0); |
| + break; |
| + } |
| + default: |
| + UNREACHABLE(); |
| + break; |
| + } |
| + } |
| + } |
| + // Prepare for the undo-action (e.g., push if it's going to be popped). |
| + if (undo_action == RESTORE) { |
| + pushes++; |
| + RegExpMacroAssembler::StackCheckFlag stack_check = |
| + RegExpMacroAssembler::kNoStackLimitCheck; |
| + if (pushes == push_limit) { |
| + stack_check = RegExpMacroAssembler::kCheckStackLimit; |
| + pushes = 0; |
| + } |
| + |
| + assembler->PushRegister(reg, stack_check); |
| + registers_to_pop->Set(reg, isolate); |
| + } else if (undo_action == CLEAR) { |
| + registers_to_clear->Set(reg, isolate); |
| + } |
| + // Perform the chronologically last action (or accumulated increment) |
| + // for the register. |
| + if (store_position != -1) { |
| + assembler->WriteCurrentPositionToRegister(reg, store_position); |
| + } else if (clear) { |
| + assembler->ClearRegisters(reg, reg); |
| + } else if (absolute) { |
| + assembler->SetRegister(reg, value); |
| + } else if (value != 0) { |
| + assembler->AdvanceRegister(reg, value); |
| + } |
| + } |
| +} |
| + |
| + |
| +void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) { |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + |
| + ASSERT(!is_trivial()); |
| + |
| + if (actions_ == NULL && backtrack() == NULL) { |
| + // Here we just have some deferred cp advances to fix and we are back to |
| + // a normal situation. We may also have to forget some information gained |
| + // through a quick check that was already performed. |
| + if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_); |
| + // Create a new trivial state and generate the node with that. |
| + Trace new_state; |
| + successor->Emit(compiler, &new_state); |
| + return; |
| + } |
| + |
| + // Generate deferred actions here along with code to undo them again. |
| + OutSet affected_registers; |
| + |
| + if (backtrack() != NULL) { |
| + // Here we have a concrete backtrack location. These are set up by choice |
| + // nodes and so they indicate that we have a deferred save of the current |
| + // position which we may need to emit here. |
| + assembler->PushCurrentPosition(); |
| + } |
| + |
| + intptr_t max_register = FindAffectedRegisters(&affected_registers, CI); |
| + OutSet registers_to_pop; |
| + OutSet registers_to_clear; |
| + PerformDeferredActions(assembler, |
| + max_register, |
| + affected_registers, |
| + ®isters_to_pop, |
| + ®isters_to_clear, |
| + CI); |
| + if (cp_offset_ != 0) { |
| + assembler->AdvanceCurrentPosition(cp_offset_); |
| + } |
| + |
| + // Create a new trivial state and generate the node with that. |
| + BlockLabel undo; |
| + assembler->PushBacktrack(&undo); |
| + Trace new_state; |
| + successor->Emit(compiler, &new_state); |
| + |
| + // On backtrack we need to restore state. |
| + assembler->BindBlock(&undo); |
| + RestoreAffectedRegisters(assembler, |
| + max_register, |
| + registers_to_pop, |
| + registers_to_clear); |
| + if (backtrack() == NULL) { |
| + assembler->Backtrack(); |
| + } else { |
| + assembler->PopCurrentPosition(); |
| + assembler->GoTo(backtrack()); |
| + } |
| +} |
| + |
| + |
| +void Trace::InvalidateCurrentCharacter() { |
| + characters_preloaded_ = 0; |
| +} |
| + |
| + |
| +void Trace::AdvanceCurrentPositionInTrace(intptr_t by, |
| + RegExpCompiler* compiler) { |
| + ASSERT(by > 0); |
| + // We don't have an instruction for shifting the current character register |
| + // down or for using a shifted value for anything so lets just forget that |
| + // we preloaded any characters into it. |
| + characters_preloaded_ = 0; |
| + // Adjust the offsets of the quick check performed information. This |
| + // information is used to find out what we already determined about the |
| + // characters by means of mask and compare. |
| + quick_check_performed_.Advance(by, compiler->ascii()); |
| + cp_offset_ += by; |
| + if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) { |
| + compiler->SetRegExpTooBig(); |
| + cp_offset_ = 0; |
| + } |
| + bound_checked_up_to_ = Utils::Maximum(static_cast<intptr_t>(0), |
| + bound_checked_up_to_ - by); |
| +} |
| + |
| + |
| +void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| + if (!trace->is_trivial()) { |
| + trace->Flush(compiler, this); |
| + return; |
| + } |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + if (!label()->IsBound()) { |
| + assembler->BindBlock(label()); |
| + } |
| + switch (action_) { |
| + case ACCEPT: |
| + assembler->Succeed(); |
| + return; |
| + case BACKTRACK: |
| + assembler->GoTo(trace->backtrack()); |
| + return; |
| + case NEGATIVE_SUBMATCH_SUCCESS: |
| + // This case is handled in a different virtual method. |
| + UNREACHABLE(); |
| + } |
| + UNIMPLEMENTED(); |
| +} |
| + |
| + |
| +bool QuickCheckDetails::Rationalize(bool asc) { |
| + bool found_useful_op = false; |
| + uint32_t char_mask; |
| + if (asc) { |
| + char_mask = Symbols::kMaxOneCharCodeSymbol; |
| + } else { |
| + char_mask = Utf16::kMaxCodeUnit; |
| + } |
| + mask_ = 0; |
| + value_ = 0; |
| + intptr_t char_shift = 0; |
| + for (intptr_t i = 0; i < characters_; i++) { |
| + Position* pos = &positions_[i]; |
| + if ((pos->mask & Symbols::kMaxOneCharCodeSymbol) != 0) { |
| + found_useful_op = true; |
| + } |
| + mask_ |= (pos->mask & char_mask) << char_shift; |
| + value_ |= (pos->value & char_mask) << char_shift; |
| + char_shift += asc ? 8 : 16; |
| + } |
| + return found_useful_op; |
| +} |
| + |
| + |
| +bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler, |
| + Trace* trace, |
| + bool preload_has_checked_bounds, |
| + BlockLabel* on_possible_success, |
| + QuickCheckDetails* details, |
| + bool fall_through_on_failure) { |
| + if (details->characters() == 0) return false; |
| + GetQuickCheckDetails( |
| + details, compiler, 0, trace->at_start() == Trace::FALSE_VALUE); |
| + if (details->cannot_match()) return false; |
| + if (!details->Rationalize(compiler->ascii())) return false; |
| + ASSERT(details->characters() == 1 || |
| + compiler->macro_assembler()->CanReadUnaligned()); |
| + uint32_t mask = details->mask(); |
| + uint32_t value = details->value(); |
| + |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + |
| + if (trace->characters_preloaded() != details->characters()) { |
| + assembler->LoadCurrentCharacter(trace->cp_offset(), |
| + trace->backtrack(), |
| + !preload_has_checked_bounds, |
| + details->characters()); |
| + } |
| + |
| + |
| + bool need_mask = true; |
| + |
| + if (details->characters() == 1) { |
| + // If number of characters preloaded is 1 then we used a byte or 16 bit |
| + // load so the value is already masked down. |
| + uint32_t char_mask; |
| + if (compiler->ascii()) { |
| + char_mask = Symbols::kMaxOneCharCodeSymbol; |
| + } else { |
| + char_mask = Utf16::kMaxCodeUnit; |
| + } |
| + if ((mask & char_mask) == char_mask) need_mask = false; |
| + mask &= char_mask; |
| + } else { |
| + // For 2-character preloads in ASCII mode or 1-character preloads in |
| + // TWO_BYTE mode we also use a 16 bit load with zero extend. |
| + if (details->characters() == 2 && compiler->ascii()) { |
| + if ((mask & 0xffff) == 0xffff) need_mask = false; |
| + } else if (details->characters() == 1 && !compiler->ascii()) { |
| + if ((mask & 0xffff) == 0xffff) need_mask = false; |
| + } else { |
| + if (mask == 0xffffffff) need_mask = false; |
| + } |
| + } |
| + |
| + if (fall_through_on_failure) { |
| + if (need_mask) { |
| + assembler->CheckCharacterAfterAnd(value, mask, on_possible_success); |
| + } else { |
| + assembler->CheckCharacter(value, on_possible_success); |
| + } |
| + } else { |
| + if (need_mask) { |
| + assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack()); |
| + } else { |
| + assembler->CheckNotCharacter(value, trace->backtrack()); |
| + } |
| + } |
| + return true; |
| +} |
| + |
| + |
| +// Emit the code to check for a ^ in multiline mode (1-character lookbehind |
| +// that matches newline or the start of input). |
| +static void EmitHat(RegExpCompiler* compiler, |
| + RegExpNode* on_success, |
| + Trace* trace) { |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + // We will be loading the previous character into the current character |
| + // register. |
| + Trace new_trace(*trace); |
| + new_trace.InvalidateCurrentCharacter(); |
| + |
| + BlockLabel ok; |
| + if (new_trace.cp_offset() == 0) { |
| + // The start of input counts as a newline in this context, so skip to |
| + // ok if we are at the start. |
| + assembler->CheckAtStart(&ok); |
| + } |
| + // We already checked that we are not at the start of input so it must be |
| + // OK to load the previous character. |
| + assembler->LoadCurrentCharacter(new_trace.cp_offset() -1, |
| + new_trace.backtrack(), |
| + false); |
| + if (!assembler->CheckSpecialCharacterClass('n', |
| + new_trace.backtrack())) { |
| + // Newline means \n, \r, 0x2028 or 0x2029. |
| + if (!compiler->ascii()) { |
| + assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok); |
| + } |
| + assembler->CheckCharacter('\n', &ok); |
| + assembler->CheckNotCharacter('\r', new_trace.backtrack()); |
| + } |
| + assembler->BindBlock(&ok); |
| + on_success->Emit(compiler, &new_trace); |
| +} |
| + |
| + |
| +void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + switch (assertion_type_) { |
| + case AT_END: { |
| + BlockLabel ok; |
| + assembler->CheckPosition(trace->cp_offset(), &ok); |
| + assembler->GoTo(trace->backtrack()); |
| + assembler->BindBlock(&ok); |
| + break; |
| + } |
| + case AT_START: { |
| + if (trace->at_start() == Trace::FALSE_VALUE) { |
| + assembler->GoTo(trace->backtrack()); |
| + return; |
| + } |
| + if (trace->at_start() == Trace::UNKNOWN) { |
| + assembler->CheckNotAtStart(trace->backtrack()); |
| + Trace at_start_trace = *trace; |
| + at_start_trace.set_at_start(true); |
| + on_success()->Emit(compiler, &at_start_trace); |
| + return; |
| + } |
| + } |
| + break; |
| + case AFTER_NEWLINE: |
| + EmitHat(compiler, on_success(), trace); |
| + return; |
| + case AT_BOUNDARY: |
| + case AT_NON_BOUNDARY: { |
| + EmitBoundaryCheck(compiler, trace); |
| + return; |
| + } |
| + } |
| + on_success()->Emit(compiler, trace); |
| +} |
| + |
| + |
| +RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler, |
| + Trace* trace) { |
| + // If we are generating a greedy loop then don't stop and don't reuse code. |
| + if (trace->stop_node() != NULL) { |
| + return CONTINUE; |
| + } |
| + |
| + RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| + if (trace->is_trivial()) { |
| + if (label_.IsBound()) { |
| + // We are being asked to generate a generic version, but that's already |
| + // been done so just go to it. |
| + macro_assembler->GoTo(&label_); |
| + return DONE; |
| + } |
| + if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) { |
| + // To avoid too deep recursion we push the node to the work queue and just |
| + // generate a goto here. |
| + compiler->AddWork(this); |
| + macro_assembler->GoTo(&label_); |
| + return DONE; |
| + } |
| + // Generate generic version of the node and bind the label for later use. |
| + macro_assembler->BindBlock(&label_); |
| + return CONTINUE; |
| + } |
| + |
| + // We are being asked to make a non-generic version. Keep track of how many |
| + // non-generic versions we generate so as not to overdo it. |
| + trace_count_++; |
| + if (kRegexpOptimization && |
| + trace_count_ < kMaxCopiesCodeGenerated && |
| + compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) { |
| + return CONTINUE; |
| + } |
| + |
| + // If we get here code has been generated for this node too many times or |
| + // recursion is too deep. Time to switch to a generic version. The code for |
| + // generic versions above can handle deep recursion properly. |
| + trace->Flush(compiler, this); |
| + return DONE; |
| +} |
| + |
| + |
| +// This generates the code to match a text node. A text node can contain |
| +// straight character sequences (possibly to be matched in a case-independent |
| +// way) and character classes. For efficiency we do not do this in a single |
| +// pass from left to right. Instead we pass over the text node several times, |
| +// emitting code for some character positions every time. See the comment on |
| +// TextEmitPass for details. |
| +void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| + LimitResult limit_result = LimitVersions(compiler, trace); |
| + if (limit_result == DONE) return; |
| + ASSERT(limit_result == CONTINUE); |
| + |
| + if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) { |
| + compiler->SetRegExpTooBig(); |
| + return; |
| + } |
| + |
| + if (compiler->ascii()) { |
| + intptr_t dummy = 0; |
| + TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy); |
| + } |
| + |
| + bool first_elt_done = false; |
| + intptr_t bound_checked_to = trace->cp_offset() - 1; |
| + bound_checked_to += trace->bound_checked_up_to(); |
| + |
| + // If a character is preloaded into the current character register then |
| + // check that now. |
| + if (trace->characters_preloaded() == 1) { |
| + for (intptr_t pass = kFirstRealPass; pass <= kLastPass; pass++) { |
| + if (!SkipPass(pass, compiler->ignore_case())) { |
| + TextEmitPass(compiler, |
| + static_cast<TextEmitPassType>(pass), |
| + true, |
| + trace, |
| + false, |
| + &bound_checked_to); |
| + } |
| + } |
| + first_elt_done = true; |
| + } |
| + |
| + for (intptr_t pass = kFirstRealPass; pass <= kLastPass; pass++) { |
| + if (!SkipPass(pass, compiler->ignore_case())) { |
| + TextEmitPass(compiler, |
| + static_cast<TextEmitPassType>(pass), |
| + false, |
| + trace, |
| + first_elt_done, |
| + &bound_checked_to); |
| + } |
| + } |
| + |
| + Trace successor_trace(*trace); |
| + successor_trace.set_at_start(false); |
| + successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler); |
| + RecursionCheck rc(compiler); |
| + on_success()->Emit(compiler, &successor_trace); |
| +} |
| + |
| + |
| +void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| + RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| + if (trace->stop_node() == this) { |
| + intptr_t text_length = |
| + GreedyLoopTextLengthForAlternative(&((*alternatives_)[0])); |
| + ASSERT(text_length != kNodeIsTooComplexForGreedyLoops); |
| + // Update the counter-based backtracking info on the stack. This is an |
| + // optimization for greedy loops (see below). |
| + ASSERT(trace->cp_offset() == text_length); |
| + macro_assembler->AdvanceCurrentPosition(text_length); |
| + macro_assembler->GoTo(trace->loop_label()); |
| + return; |
| + } |
| + ASSERT(trace->stop_node() == NULL); |
| + if (!trace->is_trivial()) { |
| + trace->Flush(compiler, this); |
| + return; |
| + } |
| + ChoiceNode::Emit(compiler, trace); |
| +} |
| + |
| + |
| +// This class is used when generating the alternatives in a choice node. It |
| +// records the way the alternative is being code generated. |
| +class AlternativeGeneration { |
| + public: |
| + AlternativeGeneration() |
| + : possible_success(), |
| + expects_preload(false), |
| + after(), |
| + quick_check_details() { } |
| + BlockLabel possible_success; |
| + bool expects_preload; |
| + BlockLabel after; |
| + QuickCheckDetails quick_check_details; |
| +}; |
| + |
| + |
| +// Creates a list of AlternativeGenerations. If the list has a reasonable |
| +// size then it is on the stack, otherwise the excess is on the heap. |
| +class AlternativeGenerationList { |
| + public: |
| + explicit AlternativeGenerationList(intptr_t count) |
| + : alt_gens_(count) { |
| + for (intptr_t i = 0; i < count && i < kAFew; i++) { |
| + alt_gens_.Add(a_few_alt_gens_ + i); |
| + } |
| + for (intptr_t i = kAFew; i < count; i++) { |
| + alt_gens_.Add(new AlternativeGeneration()); |
| + } |
| + } |
| + ~AlternativeGenerationList() { |
| + for (intptr_t i = kAFew; i < alt_gens_.length(); i++) { |
| + delete alt_gens_[i]; |
| + alt_gens_[i] = NULL; |
| + } |
| + } |
| + |
| + AlternativeGeneration* at(intptr_t i) { |
| + return alt_gens_[i]; |
| + } |
| + |
| + private: |
| + static const intptr_t kAFew = 10; |
| + GrowableArray<AlternativeGeneration*> alt_gens_; |
| + AlternativeGeneration a_few_alt_gens_[kAFew]; |
| +}; |
| + |
| + |
| +void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| + RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| + intptr_t choice_count = alternatives_->length(); |
| + |
| +#ifdef DEBUG |
| + for (intptr_t i = 0; i < choice_count - 1; i++) { |
| + GuardedAlternative alternative = alternatives_->At(i); |
| + ZoneGrowableArray<Guard*>* guards = alternative.guards(); |
| + intptr_t guard_count = (guards == NULL) ? 0 : guards->length(); |
| + for (intptr_t j = 0; j < guard_count; j++) { |
| + ASSERT(!trace->mentions_reg(guards->At(j)->reg())); |
| + } |
| + } |
| +#endif |
| + |
| + LimitResult limit_result = LimitVersions(compiler, trace); |
| + if (limit_result == DONE) return; |
| + ASSERT(limit_result == CONTINUE); |
| + |
| + intptr_t new_flush_budget = trace->flush_budget() / choice_count; |
| + if (trace->flush_budget() == 0 && trace->actions() != NULL) { |
| + trace->Flush(compiler, this); |
| + return; |
| + } |
| + |
| + RecursionCheck rc(compiler); |
| + |
| + Trace* current_trace = trace; |
| + |
| + intptr_t text_length = |
| + GreedyLoopTextLengthForAlternative(&((*alternatives_)[0])); |
| + bool greedy_loop = false; |
| + BlockLabel greedy_loop_label; |
| + Trace counter_backtrack_trace; |
| + counter_backtrack_trace.set_backtrack(&greedy_loop_label); |
| + if (not_at_start()) counter_backtrack_trace.set_at_start(false); |
| + |
| + if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) { |
| + // Here we have special handling for greedy loops containing only text nodes |
| + // and other simple nodes. These are handled by pushing the current |
| + // position on the stack and then incrementing the current position each |
| + // time around the switch. On backtrack we decrement the current position |
| + // and check it against the pushed value. This avoids pushing backtrack |
| + // information for each iteration of the loop, which could take up a lot of |
| + // space. |
| + greedy_loop = true; |
| + ASSERT(trace->stop_node() == NULL); |
| + macro_assembler->PushCurrentPosition(); |
| + current_trace = &counter_backtrack_trace; |
| + BlockLabel greedy_match_failed; |
| + Trace greedy_match_trace; |
| + if (not_at_start()) greedy_match_trace.set_at_start(false); |
| + greedy_match_trace.set_backtrack(&greedy_match_failed); |
| + BlockLabel loop_label; |
| + macro_assembler->BindBlock(&loop_label); |
| + greedy_match_trace.set_stop_node(this); |
| + greedy_match_trace.set_loop_label(&loop_label); |
| + (*alternatives_)[0].node()->Emit(compiler, &greedy_match_trace); |
| + macro_assembler->BindBlock(&greedy_match_failed); |
| + } |
| + |
| + BlockLabel second_choice; // For use in greedy matches. |
| + macro_assembler->BindBlock(&second_choice); |
| + |
| + intptr_t first_normal_choice = greedy_loop ? 1 : 0; |
| + |
| + bool not_at_start = current_trace->at_start() == Trace::FALSE_VALUE; |
| + const intptr_t kEatsAtLeastNotYetInitialized = -1; |
| + intptr_t eats_at_least = kEatsAtLeastNotYetInitialized; |
| + |
| + bool skip_was_emitted = false; |
| + |
| + if (!greedy_loop && choice_count == 2) { |
| + GuardedAlternative alt1 = (*alternatives_)[1]; |
| + if (alt1.guards() == NULL || alt1.guards()->length() == 0) { |
| + RegExpNode* eats_anything_node = alt1.node(); |
| + if (eats_anything_node->GetSuccessorOfOmnivorousTextNode(compiler) == |
| + this) { |
| + // At this point we know that we are at a non-greedy loop that will eat |
| + // any character one at a time. Any non-anchored regexp has such a |
| + // loop prepended to it in order to find where it starts. We look for |
| + // a pattern of the form ...abc... where we can look 6 characters ahead |
| + // and step forwards 3 if the character is not one of abc. Abc need |
| + // not be atoms, they can be any reasonably limited character class or |
| + // small alternation. |
| + ASSERT(trace->is_trivial()); // This is the case on LoopChoiceNodes. |
| + BoyerMooreLookahead* lookahead = bm_info(not_at_start); |
| + if (lookahead == NULL) { |
| + eats_at_least = Utils::Minimum(kMaxLookaheadForBoyerMoore, |
| + EatsAtLeast(kMaxLookaheadForBoyerMoore, |
| + kRecursionBudget, |
| + not_at_start)); |
| + if (eats_at_least >= 1) { |
| + BoyerMooreLookahead* bm = |
| + new(I) BoyerMooreLookahead(eats_at_least, compiler, I); |
| + GuardedAlternative alt0 = alternatives_->At(0); |
| + alt0.node()->FillInBMInfo(0, kRecursionBudget, bm, not_at_start); |
| + skip_was_emitted = bm->EmitSkipInstructions(macro_assembler); |
| + } |
| + } else { |
| + skip_was_emitted = lookahead->EmitSkipInstructions(macro_assembler); |
| + } |
| + } |
| + } |
| + } |
| + |
| + if (eats_at_least == kEatsAtLeastNotYetInitialized) { |
| + // Save some time by looking at most one machine word ahead. |
| + eats_at_least = |
| + EatsAtLeast(compiler->ascii() ? 4 : 2, kRecursionBudget, not_at_start); |
| + } |
| + intptr_t preload_characters = |
| + CalculatePreloadCharacters(compiler, eats_at_least); |
| + |
| + bool preload_is_current = !skip_was_emitted && |
| + (current_trace->characters_preloaded() == preload_characters); |
| + bool preload_has_checked_bounds = preload_is_current; |
| + |
| + AlternativeGenerationList alt_gens(choice_count); |
| + |
| + // For now we just call all choices one after the other. The idea ultimately |
| + // is to use the Dispatch table to try only the relevant ones. |
| + for (intptr_t i = first_normal_choice; i < choice_count; i++) { |
| + GuardedAlternative alternative = alternatives_->At(i); |
| + AlternativeGeneration* alt_gen = alt_gens.at(i); |
| + alt_gen->quick_check_details.set_characters(preload_characters); |
| + ZoneGrowableArray<Guard*>* guards = alternative.guards(); |
| + intptr_t guard_count = (guards == NULL) ? 0 : guards->length(); |
| + Trace new_trace(*current_trace); |
| + new_trace.set_characters_preloaded(preload_is_current ? |
| + preload_characters : |
| + 0); |
| + if (preload_has_checked_bounds) { |
| + new_trace.set_bound_checked_up_to(preload_characters); |
| + } |
| + new_trace.quick_check_performed()->Clear(); |
| + if (not_at_start_) new_trace.set_at_start(Trace::FALSE_VALUE); |
| + alt_gen->expects_preload = preload_is_current; |
| + bool generate_full_check_inline = false; |
| + if (kRegexpOptimization && |
| + try_to_emit_quick_check_for_alternative(i) && |
| + alternative.node()->EmitQuickCheck(compiler, |
| + &new_trace, |
| + preload_has_checked_bounds, |
| + &alt_gen->possible_success, |
| + &alt_gen->quick_check_details, |
| + i < choice_count - 1)) { |
| + // Quick check was generated for this choice. |
| + preload_is_current = true; |
| + preload_has_checked_bounds = true; |
| + // On the last choice in the ChoiceNode we generated the quick |
| + // check to fall through on possible success. So now we need to |
| + // generate the full check inline. |
| + if (i == choice_count - 1) { |
| + macro_assembler->BindBlock(&alt_gen->possible_success); |
| + new_trace.set_quick_check_performed(&alt_gen->quick_check_details); |
| + new_trace.set_characters_preloaded(preload_characters); |
| + new_trace.set_bound_checked_up_to(preload_characters); |
| + generate_full_check_inline = true; |
| + } |
| + } else if (alt_gen->quick_check_details.cannot_match()) { |
| + if (i == choice_count - 1 && !greedy_loop) { |
| + macro_assembler->GoTo(trace->backtrack()); |
| + } |
| + continue; |
| + } else { |
| + // No quick check was generated. Put the full code here. |
| + // If this is not the first choice then there could be slow checks from |
| + // previous cases that go here when they fail. There's no reason to |
| + // insist that they preload characters since the slow check we are about |
| + // to generate probably can't use it. |
| + if (i != first_normal_choice) { |
| + alt_gen->expects_preload = false; |
| + new_trace.InvalidateCurrentCharacter(); |
| + } |
| + if (i < choice_count - 1) { |
| + new_trace.set_backtrack(&alt_gen->after); |
| + } |
| + generate_full_check_inline = true; |
| + } |
| + if (generate_full_check_inline) { |
| + if (new_trace.actions() != NULL) { |
| + new_trace.set_flush_budget(new_flush_budget); |
| + } |
| + for (intptr_t j = 0; j < guard_count; j++) { |
| + GenerateGuard(macro_assembler, guards->At(j), &new_trace); |
| + } |
| + alternative.node()->Emit(compiler, &new_trace); |
| + preload_is_current = false; |
| + } |
| + macro_assembler->BindBlock(&alt_gen->after); |
| + } |
| + if (greedy_loop) { |
| + macro_assembler->BindBlock(&greedy_loop_label); |
| + // If we have unwound to the bottom then backtrack. |
| + macro_assembler->CheckGreedyLoop(trace->backtrack()); |
| + // Otherwise try the second priority at an earlier position. |
| + macro_assembler->AdvanceCurrentPosition(-text_length); |
| + macro_assembler->GoTo(&second_choice); |
| + } |
| + |
| + // At this point we need to generate slow checks for the alternatives where |
| + // the quick check was inlined. We can recognize these because the associated |
| + // label was bound. |
| + for (intptr_t i = first_normal_choice; i < choice_count - 1; i++) { |
| + AlternativeGeneration* alt_gen = alt_gens.at(i); |
| + Trace new_trace(*current_trace); |
| + // If there are actions to be flushed we have to limit how many times |
| + // they are flushed. Take the budget of the parent trace and distribute |
| + // it fairly amongst the children. |
| + if (new_trace.actions() != NULL) { |
| + new_trace.set_flush_budget(new_flush_budget); |
| + } |
| + EmitOutOfLineContinuation(compiler, |
| + &new_trace, |
| + alternatives_->At(i), |
| + alt_gen, |
| + preload_characters, |
| + alt_gens.at(i + 1)->expects_preload); |
| + } |
| +} |
| + |
| + |
| +void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler, |
| + Trace* trace, |
| + GuardedAlternative alternative, |
| + AlternativeGeneration* alt_gen, |
| + intptr_t preload_characters, |
| + bool next_expects_preload) { |
| + if (!alt_gen->possible_success.IsLinked()) return; |
| + |
| + RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| + macro_assembler->BindBlock(&alt_gen->possible_success); |
| + Trace out_of_line_trace(*trace); |
| + out_of_line_trace.set_characters_preloaded(preload_characters); |
| + out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details); |
| + if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE_VALUE); |
| + ZoneGrowableArray<Guard*>* guards = alternative.guards(); |
| + intptr_t guard_count = (guards == NULL) ? 0 : guards->length(); |
| + if (next_expects_preload) { |
| + BlockLabel reload_current_char; |
| + out_of_line_trace.set_backtrack(&reload_current_char); |
| + for (intptr_t j = 0; j < guard_count; j++) { |
| + GenerateGuard(macro_assembler, guards->At(j), &out_of_line_trace); |
| + } |
| + alternative.node()->Emit(compiler, &out_of_line_trace); |
| + macro_assembler->BindBlock(&reload_current_char); |
| + // Reload the current character, since the next quick check expects that. |
| + // We don't need to check bounds here because we only get into this |
| + // code through a quick check which already did the checked load. |
| + macro_assembler->LoadCurrentCharacter(trace->cp_offset(), |
| + NULL, |
| + false, |
| + preload_characters); |
| + macro_assembler->GoTo(&(alt_gen->after)); |
| + } else { |
| + out_of_line_trace.set_backtrack(&(alt_gen->after)); |
| + for (intptr_t j = 0; j < guard_count; j++) { |
| + GenerateGuard(macro_assembler, guards->At(j), &out_of_line_trace); |
| + } |
| + alternative.node()->Emit(compiler, &out_of_line_trace); |
| + } |
| +} |
| + |
| + |
| +void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + LimitResult limit_result = LimitVersions(compiler, trace); |
| + if (limit_result == DONE) return; |
| + ASSERT(limit_result == CONTINUE); |
| + |
| + RecursionCheck rc(compiler); |
| + |
| + switch (action_type_) { |
| + case STORE_POSITION: { |
| + Trace::DeferredCapture |
| + new_capture(data_.u_position_register.reg, |
| + data_.u_position_register.is_capture, |
| + trace); |
| + Trace new_trace = *trace; |
| + new_trace.add_action(&new_capture); |
| + on_success()->Emit(compiler, &new_trace); |
| + break; |
| + } |
| + case INCREMENT_REGISTER: { |
| + Trace::DeferredIncrementRegister |
| + new_increment(data_.u_increment_register.reg); |
| + Trace new_trace = *trace; |
| + new_trace.add_action(&new_increment); |
| + on_success()->Emit(compiler, &new_trace); |
| + break; |
| + } |
| + case SET_REGISTER: { |
| + Trace::DeferredSetRegister |
| + new_set(data_.u_store_register.reg, data_.u_store_register.value); |
| + Trace new_trace = *trace; |
| + new_trace.add_action(&new_set); |
| + on_success()->Emit(compiler, &new_trace); |
| + break; |
| + } |
| + case CLEAR_CAPTURES: { |
| + Trace::DeferredClearCaptures |
| + new_capture(Interval(data_.u_clear_captures.range_from, |
| + data_.u_clear_captures.range_to)); |
| + Trace new_trace = *trace; |
| + new_trace.add_action(&new_capture); |
| + on_success()->Emit(compiler, &new_trace); |
| + break; |
| + } |
| + case BEGIN_SUBMATCH: |
| + if (!trace->is_trivial()) { |
| + trace->Flush(compiler, this); |
| + } else { |
| + assembler->WriteCurrentPositionToRegister( |
| + data_.u_submatch.current_position_register, 0); |
| + assembler->WriteStackPointerToRegister( |
| + data_.u_submatch.stack_pointer_register); |
| + on_success()->Emit(compiler, trace); |
| + } |
| + break; |
| + case EMPTY_MATCH_CHECK: { |
| + intptr_t start_pos_reg = data_.u_empty_match_check.start_register; |
| + intptr_t stored_pos = 0; |
| + intptr_t rep_reg = data_.u_empty_match_check.repetition_register; |
| + bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister); |
| + bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos); |
| + if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) { |
| + // If we know we haven't advanced and there is no minimum we |
| + // can just backtrack immediately. |
| + assembler->GoTo(trace->backtrack()); |
| + } else if (know_dist && stored_pos < trace->cp_offset()) { |
| + // If we know we've advanced we can generate the continuation |
| + // immediately. |
| + on_success()->Emit(compiler, trace); |
| + } else if (!trace->is_trivial()) { |
| + trace->Flush(compiler, this); |
| + } else { |
| + BlockLabel skip_empty_check; |
| + // If we have a minimum number of repetitions we check the current |
| + // number first and skip the empty check if it's not enough. |
| + if (has_minimum) { |
| + intptr_t limit = data_.u_empty_match_check.repetition_limit; |
| + assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check); |
| + } |
| + // If the match is empty we bail out, otherwise we fall through |
| + // to the on-success continuation. |
| + assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register, |
| + trace->backtrack()); |
| + assembler->BindBlock(&skip_empty_check); |
| + on_success()->Emit(compiler, trace); |
| + } |
| + break; |
| + } |
| + case POSITIVE_SUBMATCH_SUCCESS: { |
| + if (!trace->is_trivial()) { |
| + trace->Flush(compiler, this); |
| + return; |
| + } |
| + assembler->ReadCurrentPositionFromRegister( |
| + data_.u_submatch.current_position_register); |
| + assembler->ReadStackPointerFromRegister( |
| + data_.u_submatch.stack_pointer_register); |
| + intptr_t clear_register_count = data_.u_submatch.clear_register_count; |
| + if (clear_register_count == 0) { |
| + on_success()->Emit(compiler, trace); |
| + return; |
| + } |
| + intptr_t clear_registers_from = data_.u_submatch.clear_register_from; |
| + BlockLabel clear_registers_backtrack; |
| + Trace new_trace = *trace; |
| + new_trace.set_backtrack(&clear_registers_backtrack); |
| + on_success()->Emit(compiler, &new_trace); |
| + |
| + assembler->BindBlock(&clear_registers_backtrack); |
| + intptr_t clear_registers_to = |
| + clear_registers_from + clear_register_count - 1; |
| + assembler->ClearRegisters(clear_registers_from, clear_registers_to); |
| + |
| + ASSERT(trace->backtrack() == NULL); |
| + assembler->Backtrack(); |
| + return; |
| + } |
| + default: |
| + UNREACHABLE(); |
| + } |
| +} |
| + |
| + |
| +void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + if (!trace->is_trivial()) { |
| + trace->Flush(compiler, this); |
| + return; |
| + } |
| + |
| + LimitResult limit_result = LimitVersions(compiler, trace); |
| + if (limit_result == DONE) return; |
| + ASSERT(limit_result == CONTINUE); |
| + |
| + RecursionCheck rc(compiler); |
| + |
| + ASSERT(start_reg_ + 1 == end_reg_); |
| + if (compiler->ignore_case()) { |
| + assembler->CheckNotBackReferenceIgnoreCase(start_reg_, |
| + trace->backtrack()); |
| + } else { |
| + assembler->CheckNotBackReference(start_reg_, trace->backtrack()); |
| + } |
| + on_success()->Emit(compiler, trace); |
| +} |
| + |
| + |
| +void ActionNode::FillInBMInfo(intptr_t offset, |
| + intptr_t budget, |
| + BoyerMooreLookahead* bm, |
| + bool not_at_start) { |
| + if (action_type_ == BEGIN_SUBMATCH) { |
| + bm->SetRest(offset); |
| + } else if (action_type_ != POSITIVE_SUBMATCH_SUCCESS) { |
| + on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start); |
| + } |
| + SaveBMInfo(bm, not_at_start, offset); |
| +} |
| + |
| + |
| +void AssertionNode::FillInBMInfo(intptr_t offset, |
| + intptr_t budget, |
| + BoyerMooreLookahead* bm, |
| + bool not_at_start) { |
| + // Match the behaviour of EatsAtLeast on this node. |
| + if (assertion_type() == AT_START && not_at_start) return; |
| + on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start); |
| + SaveBMInfo(bm, not_at_start, offset); |
| +} |
| + |
| + |
| +void BackReferenceNode::FillInBMInfo(intptr_t offset, |
| + intptr_t budget, |
| + BoyerMooreLookahead* bm, |
| + bool not_at_start) { |
| + // Working out the set of characters that a backreference can match is too |
| + // hard, so we just say that any character can match. |
| + bm->SetRest(offset); |
| + SaveBMInfo(bm, not_at_start, offset); |
| +} |
| + |
| + |
| +// Returns the number of characters in the equivalence class, omitting those |
| +// that cannot occur in the source string because it is ASCII. |
| +static intptr_t GetCaseIndependentLetters(uint16_t character, |
| + bool ascii_subject, |
| + int32_t* letters) { |
| + unibrow::Mapping<unibrow::Ecma262UnCanonicalize> jsregexp_uncanonicalize; |
| + intptr_t length = jsregexp_uncanonicalize.get(character, '\0', letters); |
| + // Unibrow returns 0 or 1 for characters where case independence is |
| + // trivial. |
| + if (length == 0) { |
| + letters[0] = character; |
| + length = 1; |
| + } |
| + if (!ascii_subject || character <= Symbols::kMaxOneCharCodeSymbol) { |
| + return length; |
| + } |
| + // The standard requires that non-ASCII characters cannot have ASCII |
| + // character codes in their equivalence class. |
| + return 0; |
| +} |
| + |
| + |
| +void ChoiceNode::FillInBMInfo(intptr_t offset, |
| + intptr_t budget, |
| + BoyerMooreLookahead* bm, |
| + bool not_at_start) { |
| + ZoneGrowableArray<GuardedAlternative>* alts = alternatives(); |
| + budget = (budget - 1) / alts->length(); |
| + for (intptr_t i = 0; i < alts->length(); i++) { |
| + GuardedAlternative& alt = (*alts)[i]; |
| + if (alt.guards() != NULL && alt.guards()->length() != 0) { |
| + bm->SetRest(offset); // Give up trying to fill in info. |
| + SaveBMInfo(bm, not_at_start, offset); |
| + return; |
| + } |
| + alt.node()->FillInBMInfo(offset, budget, bm, not_at_start); |
| + } |
| + SaveBMInfo(bm, not_at_start, offset); |
| +} |
| + |
| + |
| +void EndNode::FillInBMInfo(intptr_t offset, |
| + intptr_t budget, |
| + BoyerMooreLookahead* bm, |
| + bool not_at_start) { |
| + // Returning 0 from EatsAtLeast should ensure we never get here. |
| + UNREACHABLE(); |
| +} |
| + |
| + |
| +void LoopChoiceNode::FillInBMInfo(intptr_t offset, |
| + intptr_t budget, |
| + BoyerMooreLookahead* bm, |
| + bool not_at_start) { |
| + if (body_can_be_zero_length_ || budget <= 0) { |
| + bm->SetRest(offset); |
| + SaveBMInfo(bm, not_at_start, offset); |
| + return; |
| + } |
| + ChoiceNode::FillInBMInfo(offset, budget - 1, bm, not_at_start); |
| + SaveBMInfo(bm, not_at_start, offset); |
| +} |
| + |
| + |
| +void TextNode::FillInBMInfo(intptr_t initial_offset, |
| + intptr_t budget, |
| + BoyerMooreLookahead* bm, |
| + bool not_at_start) { |
| + if (initial_offset >= bm->length()) return; |
| + intptr_t offset = initial_offset; |
| + intptr_t max_char = bm->max_char(); |
| + for (intptr_t i = 0; i < elements()->length(); i++) { |
| + if (offset >= bm->length()) { |
| + if (initial_offset == 0) set_bm_info(not_at_start, bm); |
| + return; |
| + } |
| + TextElement text = elements()->At(i); |
| + if (text.text_type() == TextElement::ATOM) { |
| + RegExpAtom* atom = text.atom(); |
| + for (intptr_t j = 0; j < atom->length(); j++, offset++) { |
| + if (offset >= bm->length()) { |
| + if (initial_offset == 0) set_bm_info(not_at_start, bm); |
| + return; |
| + } |
| + uint16_t character = atom->data()->At(j); |
| + if (bm->compiler()->ignore_case()) { |
| + int32_t chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| + intptr_t length = GetCaseIndependentLetters( |
| + character, |
| + bm->max_char() == Symbols::kMaxOneCharCodeSymbol, |
| + chars); |
| + for (intptr_t j = 0; j < length; j++) { |
| + bm->Set(offset, chars[j]); |
| + } |
| + } else { |
| + if (character <= max_char) bm->Set(offset, character); |
| + } |
| + } |
| + } else { |
| + ASSERT(text.text_type() == TextElement::CHAR_CLASS); |
| + RegExpCharacterClass* char_class = text.char_class(); |
| + ZoneGrowableArray<CharacterRange>* ranges = char_class->ranges(); |
| + if (char_class->is_negated()) { |
| + bm->SetAll(offset); |
| + } else { |
| + for (intptr_t k = 0; k < ranges->length(); k++) { |
| + CharacterRange& range = (*ranges)[k]; |
| + if (range.from() > max_char) continue; |
| + intptr_t to = Utils::Minimum(max_char, |
| + static_cast<intptr_t>(range.to())); |
| + bm->SetInterval(offset, Interval(range.from(), to)); |
| + } |
| + } |
| + offset++; |
| + } |
| + } |
| + if (offset >= bm->length()) { |
| + if (initial_offset == 0) set_bm_info(not_at_start, bm); |
| + return; |
| + } |
| + on_success()->FillInBMInfo(offset, |
| + budget - 1, |
| + bm, |
| + true); // Not at start after a text node. |
| + if (initial_offset == 0) set_bm_info(not_at_start, bm); |
| +} |
| + |
| + |
| +// Check for [0-9A-Z_a-z]. |
| +static void EmitWordCheck(RegExpMacroAssembler* assembler, |
| + BlockLabel* word, |
| + BlockLabel* non_word, |
| + bool fall_through_on_word) { |
| + if (assembler->CheckSpecialCharacterClass( |
| + fall_through_on_word ? 'w' : 'W', |
| + fall_through_on_word ? non_word : word)) { |
| + // Optimized implementation available. |
| + return; |
| + } |
| + assembler->CheckCharacterGT('z', non_word); |
| + assembler->CheckCharacterLT('0', non_word); |
| + assembler->CheckCharacterGT('a' - 1, word); |
| + assembler->CheckCharacterLT('9' + 1, word); |
| + assembler->CheckCharacterLT('A', non_word); |
| + assembler->CheckCharacterLT('Z' + 1, word); |
| + if (fall_through_on_word) { |
| + assembler->CheckNotCharacter('_', non_word); |
| + } else { |
| + assembler->CheckCharacter('_', word); |
| + } |
| +} |
| + |
| + |
| +// Emit the code to handle \b and \B (word-boundary or non-word-boundary). |
| +void AssertionNode::EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace) { |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + Trace::TriBool next_is_word_character = Trace::UNKNOWN; |
| + bool not_at_start = (trace->at_start() == Trace::FALSE_VALUE); |
| + BoyerMooreLookahead* lookahead = bm_info(not_at_start); |
| + if (lookahead == NULL) { |
| + intptr_t eats_at_least = |
| + Utils::Minimum(kMaxLookaheadForBoyerMoore, |
| + EatsAtLeast(kMaxLookaheadForBoyerMoore, |
| + kRecursionBudget, |
| + not_at_start)); |
| + if (eats_at_least >= 1) { |
| + BoyerMooreLookahead* bm = |
| + new(I) BoyerMooreLookahead(eats_at_least, compiler, I); |
| + FillInBMInfo(0, kRecursionBudget, bm, not_at_start); |
| + if (bm->at(0)->is_non_word()) |
| + next_is_word_character = Trace::FALSE_VALUE; |
| + if (bm->at(0)->is_word()) next_is_word_character = Trace::TRUE_VALUE; |
| + } |
| + } else { |
| + if (lookahead->at(0)->is_non_word()) |
| + next_is_word_character = Trace::FALSE_VALUE; |
| + if (lookahead->at(0)->is_word()) |
| + next_is_word_character = Trace::TRUE_VALUE; |
| + } |
| + bool at_boundary = (assertion_type_ == AssertionNode::AT_BOUNDARY); |
| + if (next_is_word_character == Trace::UNKNOWN) { |
| + BlockLabel before_non_word; |
| + BlockLabel before_word; |
| + if (trace->characters_preloaded() != 1) { |
| + assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word); |
| + } |
| + // Fall through on non-word. |
| + EmitWordCheck(assembler, &before_word, &before_non_word, false); |
| + // Next character is not a word character. |
| + assembler->BindBlock(&before_non_word); |
| + BlockLabel ok; |
| + // Backtrack on \B (non-boundary check) if previous is a word, |
| + // since we know next *is not* a word and this would be a boundary. |
| + BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord); |
| + |
| + if (!assembler->IsClosed()) { |
| + assembler->GoTo(&ok); |
| + } |
| + |
| + assembler->BindBlock(&before_word); |
| + BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord); |
| + assembler->BindBlock(&ok); |
| + } else if (next_is_word_character == Trace::TRUE_VALUE) { |
| + BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord); |
| + } else { |
| + ASSERT(next_is_word_character == Trace::FALSE_VALUE); |
| + BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord); |
| + } |
| +} |
| + |
| + |
| +void AssertionNode::BacktrackIfPrevious( |
| + RegExpCompiler* compiler, |
| + Trace* trace, |
| + AssertionNode::IfPrevious backtrack_if_previous) { |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + Trace new_trace(*trace); |
| + new_trace.InvalidateCurrentCharacter(); |
| + |
| + BlockLabel fall_through, dummy; |
| + |
| + BlockLabel* non_word = backtrack_if_previous == kIsNonWord ? |
| + new_trace.backtrack() : |
| + &fall_through; |
| + BlockLabel* word = backtrack_if_previous == kIsNonWord ? |
| + &fall_through : |
| + new_trace.backtrack(); |
| + |
| + if (new_trace.cp_offset() == 0) { |
| + // The start of input counts as a non-word character, so the question is |
| + // decided if we are at the start. |
| + assembler->CheckAtStart(non_word); |
| + } |
| + // We already checked that we are not at the start of input so it must be |
| + // OK to load the previous character. |
| + assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1, &dummy, false); |
| + EmitWordCheck(assembler, word, non_word, backtrack_if_previous == kIsNonWord); |
| + |
| + assembler->BindBlock(&fall_through); |
| + on_success()->Emit(compiler, &new_trace); |
| +} |
| + |
| + |
| +static bool DeterminedAlready(QuickCheckDetails* quick_check, intptr_t offset) { |
| + if (quick_check == NULL) return false; |
| + if (offset >= quick_check->characters()) return false; |
| + return quick_check->positions(offset)->determines_perfectly; |
| +} |
| + |
| + |
| +static void UpdateBoundsCheck(intptr_t index, intptr_t* checked_up_to) { |
| + if (index > *checked_up_to) { |
| + *checked_up_to = index; |
| + } |
| +} |
| + |
| + |
| +typedef bool EmitCharacterFunction(Isolate* isolate, |
| + RegExpCompiler* compiler, |
| + uint16_t c, |
| + BlockLabel* on_failure, |
| + intptr_t cp_offset, |
| + bool check, |
| + bool preloaded); |
| + |
| + |
| +static inline bool EmitSimpleCharacter(Isolate* isolate, |
| + RegExpCompiler* compiler, |
| + uint16_t c, |
| + BlockLabel* on_failure, |
| + intptr_t cp_offset, |
| + bool check, |
| + bool preloaded) { |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + bool bound_checked = false; |
| + if (!preloaded) { |
| + assembler->LoadCurrentCharacter( |
| + cp_offset, |
| + on_failure, |
| + check); |
| + bound_checked = true; |
| + } |
| + assembler->CheckNotCharacter(c, on_failure); |
| + return bound_checked; |
| +} |
| + |
| + |
| +static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler, |
| + bool ascii, |
| + uint16_t c1, |
| + uint16_t c2, |
| + BlockLabel* on_failure) { |
| + uint16_t char_mask; |
| + if (ascii) { |
| + char_mask = Symbols::kMaxOneCharCodeSymbol; |
| + } else { |
| + char_mask = Utf16::kMaxCodeUnit; |
| + } |
| + uint16_t exor = c1 ^ c2; |
| + // Check whether exor has only one bit set. |
| + if (((exor - 1) & exor) == 0) { |
| + // If c1 and c2 differ only by one bit. |
| + // Ecma262UnCanonicalize always gives the highest number last. |
| + ASSERT(c2 > c1); |
| + uint16_t mask = char_mask ^ exor; |
| + macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure); |
| + return true; |
| + } |
| + ASSERT(c2 > c1); |
| + uint16_t diff = c2 - c1; |
| + if (((diff - 1) & diff) == 0 && c1 >= diff) { |
| + // If the characters differ by 2^n but don't differ by one bit then |
| + // subtract the difference from the found character, then do the or |
| + // trick. We avoid the theoretical case where negative numbers are |
| + // involved in order to simplify code generation. |
| + uint16_t mask = char_mask ^ diff; |
| + macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff, |
| + diff, |
| + mask, |
| + on_failure); |
| + return true; |
| + } |
| + return false; |
| +} |
| + |
| +// Only emits letters (things that have case). Only used for case independent |
| +// matches. |
| +static inline bool EmitAtomLetter(Isolate* isolate, |
| + RegExpCompiler* compiler, |
| + uint16_t c, |
| + BlockLabel* on_failure, |
| + intptr_t cp_offset, |
| + bool check, |
| + bool preloaded) { |
| + RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| + bool ascii = compiler->ascii(); |
| + int32_t chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| + intptr_t length = GetCaseIndependentLetters(c, ascii, chars); |
| + if (length <= 1) return false; |
| + // We may not need to check against the end of the input string |
| + // if this character lies before a character that matched. |
| + if (!preloaded) { |
| + macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check); |
| + } |
| + BlockLabel ok; |
| + ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4); |
| + switch (length) { |
| + case 2: { |
| + if (ShortCutEmitCharacterPair(macro_assembler, |
| + ascii, |
| + chars[0], |
| + chars[1], |
| + on_failure)) { |
| + } else { |
| + macro_assembler->CheckCharacter(chars[0], &ok); |
| + macro_assembler->CheckNotCharacter(chars[1], on_failure); |
| + macro_assembler->BindBlock(&ok); |
| + } |
| + break; |
| + } |
| + case 4: |
| + macro_assembler->CheckCharacter(chars[3], &ok); |
| + // Fall through! |
| + case 3: |
| + macro_assembler->CheckCharacter(chars[0], &ok); |
| + macro_assembler->CheckCharacter(chars[1], &ok); |
| + macro_assembler->CheckNotCharacter(chars[2], on_failure); |
| + macro_assembler->BindBlock(&ok); |
| + break; |
| + default: |
| + UNREACHABLE(); |
| + break; |
| + } |
| + return true; |
| +} |
| + |
| + |
| +// Only emits non-letters (things that don't have case). Only used for case |
| +// independent matches. |
| +static inline bool EmitAtomNonLetter(Isolate* isolate, |
| + RegExpCompiler* compiler, |
| + uint16_t c, |
| + BlockLabel* on_failure, |
| + intptr_t cp_offset, |
| + bool check, |
| + bool preloaded) { |
| + RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| + bool ascii = compiler->ascii(); |
| + int32_t chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| + intptr_t length = GetCaseIndependentLetters(c, ascii, chars); |
| + if (length < 1) { |
| + // This can't match. Must be an ASCII subject and a non-ASCII character. |
| + // We do not need to do anything since the ASCII pass already handled this. |
| + return false; // Bounds not checked. |
| + } |
| + bool checked = false; |
| + // We handle the length > 1 case in a later pass. |
| + if (length == 1) { |
| + if (ascii && c > Symbols::kMaxOneCharCodeSymbol) { |
| + // Can't match - see above. |
| + return false; // Bounds not checked. |
| + } |
| + if (!preloaded) { |
| + macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check); |
| + checked = check; |
| + } |
| + macro_assembler->CheckNotCharacter(c, on_failure); |
| + } |
| + return checked; |
| +} |
| + |
| + |
| +static void EmitBoundaryTest(RegExpMacroAssembler* masm, |
| + intptr_t border, |
| + BlockLabel* fall_through, |
| + BlockLabel* above_or_equal, |
| + BlockLabel* below) { |
| + if (below != fall_through) { |
| + masm->CheckCharacterLT(border, below); |
| + if (above_or_equal != fall_through) masm->GoTo(above_or_equal); |
| + } else { |
| + masm->CheckCharacterGT(border - 1, above_or_equal); |
| + } |
| +} |
| + |
| + |
| +static void EmitDoubleBoundaryTest(RegExpMacroAssembler* masm, |
| + intptr_t first, |
| + intptr_t last, |
| + BlockLabel* fall_through, |
| + BlockLabel* in_range, |
| + BlockLabel* out_of_range) { |
| + if (in_range == fall_through) { |
| + if (first == last) { |
| + masm->CheckNotCharacter(first, out_of_range); |
| + } else { |
| + masm->CheckCharacterNotInRange(first, last, out_of_range); |
| + } |
| + } else { |
| + if (first == last) { |
| + masm->CheckCharacter(first, in_range); |
| + } else { |
| + masm->CheckCharacterInRange(first, last, in_range); |
| + } |
| + if (out_of_range != fall_through) masm->GoTo(out_of_range); |
| + } |
| +} |
| + |
| + |
| +static void CutOutRange(RegExpMacroAssembler* masm, |
| + ZoneGrowableArray<int>* ranges, |
| + intptr_t start_index, |
| + intptr_t end_index, |
| + intptr_t cut_index, |
| + BlockLabel* even_label, |
| + BlockLabel* odd_label) { |
| + bool odd = (((cut_index - start_index) & 1) == 1); |
| + BlockLabel* in_range_label = odd ? odd_label : even_label; |
| + BlockLabel dummy; |
| + EmitDoubleBoundaryTest(masm, |
| + ranges->At(cut_index), |
| + ranges->At(cut_index + 1) - 1, |
| + &dummy, |
| + in_range_label, |
| + &dummy); |
| + ASSERT(!dummy.IsLinked()); |
| + // Cut out the single range by rewriting the array. This creates a new |
| + // range that is a merger of the two ranges on either side of the one we |
| + // are cutting out. The oddity of the labels is preserved. |
| + for (intptr_t j = cut_index; j > start_index; j--) { |
| + (*ranges)[j] = ranges->At(j - 1); |
| + } |
| + for (intptr_t j = cut_index + 1; j < end_index; j++) { |
| + (*ranges)[j] = ranges->At(j + 1); |
| + } |
| +} |
| + |
| + |
| +// even_label is for ranges[i] to ranges[i + 1] where i - start_index is even. |
| +// odd_label is for ranges[i] to ranges[i + 1] where i - start_index is odd. |
| +static void EmitUseLookupTable( |
| + RegExpMacroAssembler* masm, |
| + ZoneGrowableArray<int>* ranges, |
| + intptr_t start_index, |
| + intptr_t end_index, |
| + intptr_t min_char, |
| + BlockLabel* fall_through, |
| + BlockLabel* even_label, |
| + BlockLabel* odd_label) { |
| + static const intptr_t kSize = RegExpMacroAssembler::kTableSize; |
| + static const intptr_t kMask = RegExpMacroAssembler::kTableMask; |
| + |
| + intptr_t base = (min_char & ~kMask); |
| + |
| + // Assert that everything is on one kTableSize page. |
| + for (intptr_t i = start_index; i <= end_index; i++) { |
| + ASSERT((ranges->At(i) & ~kMask) == base); |
| + } |
| + ASSERT(start_index == 0 || (ranges->At(start_index - 1) & ~kMask) <= base); |
| + |
| + char templ[kSize]; |
| + BlockLabel* on_bit_set; |
| + BlockLabel* on_bit_clear; |
| + intptr_t bit; |
| + if (even_label == fall_through) { |
| + on_bit_set = odd_label; |
| + on_bit_clear = even_label; |
| + bit = 1; |
| + } else { |
| + on_bit_set = even_label; |
| + on_bit_clear = odd_label; |
| + bit = 0; |
| + } |
| + for (intptr_t i = 0; i < (ranges->At(start_index) & kMask) && i < kSize; |
| + i++) { |
| + templ[i] = bit; |
| + } |
| + intptr_t j = 0; |
| + bit ^= 1; |
| + for (intptr_t i = start_index; i < end_index; i++) { |
| + for (j = (ranges->At(i) & kMask); j < (ranges->At(i + 1) & kMask); j++) { |
| + templ[j] = bit; |
| + } |
| + bit ^= 1; |
| + } |
| + for (intptr_t i = j; i < kSize; i++) { |
| + templ[i] = bit; |
| + } |
| + // TODO(erikcorry): Cache these. |
| + TypedData& ba = TypedData::ZoneHandle( |
|
Florian Schneider
2014/10/01 17:04:14
const TypedData&
jgruber1
2014/10/03 18:59:52
Done.
|
| + masm->isolate(), |
| + TypedData::New(kTypedDataUint8ArrayCid, kSize, Heap::kOld)); |
| + for (intptr_t i = 0; i < kSize; i++) { |
| + ba.SetUint8(i, templ[i]); |
| + } |
| + masm->CheckBitInTable(ba, on_bit_set); |
| + if (on_bit_clear != fall_through) masm->GoTo(on_bit_clear); |
| +} |
| + |
| + |
| +// Unicode case. Split the search space into kSize spaces that are handled |
| +// with recursion. |
| +static void SplitSearchSpace(ZoneGrowableArray<int>* ranges, |
| + intptr_t start_index, |
| + intptr_t end_index, |
| + intptr_t* new_start_index, |
| + intptr_t* new_end_index, |
| + intptr_t* border) { |
| + static const intptr_t kSize = RegExpMacroAssembler::kTableSize; |
| + static const intptr_t kMask = RegExpMacroAssembler::kTableMask; |
| + |
| + intptr_t first = ranges->At(start_index); |
| + intptr_t last = ranges->At(end_index) - 1; |
| + |
| + *new_start_index = start_index; |
| + *border = (ranges->At(start_index) & ~kMask) + kSize; |
| + while (*new_start_index < end_index) { |
| + if (ranges->At(*new_start_index) > *border) break; |
| + (*new_start_index)++; |
| + } |
| + // new_start_index is the index of the first edge that is beyond the |
| + // current kSize space. |
| + |
| + // For very large search spaces we do a binary chop search of the non-ASCII |
| + // space instead of just going to the end of the current kSize space. The |
| + // heuristics are complicated a little by the fact that any 128-character |
| + // encoding space can be quickly tested with a table lookup, so we don't |
| + // wish to do binary chop search at a smaller granularity than that. A |
| + // 128-character space can take up a lot of space in the ranges array if, |
| + // for example, we only want to match every second character (eg. the lower |
| + // case characters on some Unicode pages). |
| + intptr_t binary_chop_index = (end_index + start_index) / 2; |
| + // The first test ensures that we get to the code that handles the ASCII |
| + // range with a single not-taken branch, speeding up this important |
| + // character range (even non-ASCII charset-based text has spaces and |
| + // punctuation). |
| + if (*border - 1 > Symbols::kMaxOneCharCodeSymbol && // ASCII case. |
| + end_index - start_index > (*new_start_index - start_index) * 2 && |
| + last - first > kSize * 2 && |
| + binary_chop_index > *new_start_index && |
| + ranges->At(binary_chop_index) >= first + 2 * kSize) { |
| + intptr_t scan_forward_for_section_border = binary_chop_index;; |
| + intptr_t new_border = (ranges->At(binary_chop_index) | kMask) + 1; |
| + |
| + while (scan_forward_for_section_border < end_index) { |
| + if (ranges->At(scan_forward_for_section_border) > new_border) { |
| + *new_start_index = scan_forward_for_section_border; |
| + *border = new_border; |
| + break; |
| + } |
| + scan_forward_for_section_border++; |
| + } |
| + } |
| + |
| + ASSERT(*new_start_index > start_index); |
| + *new_end_index = *new_start_index - 1; |
| + if (ranges->At(*new_end_index) == *border) { |
| + (*new_end_index)--; |
| + } |
| + if (*border >= ranges->At(end_index)) { |
| + *border = ranges->At(end_index); |
| + *new_start_index = end_index; // Won't be used. |
| + *new_end_index = end_index - 1; |
| + } |
| +} |
| + |
| + |
| +// Gets a series of segment boundaries representing a character class. If the |
| +// character is in the range between an even and an odd boundary (counting from |
| +// start_index) then go to even_label, otherwise go to odd_label. We already |
| +// know that the character is in the range of min_char to max_char inclusive. |
| +// Either label can be NULL indicating backtracking. Either label can also be |
| +// equal to the fall_through label. |
| +static void GenerateBranches(RegExpMacroAssembler* masm, |
| + ZoneGrowableArray<int>* ranges, |
| + intptr_t start_index, |
| + intptr_t end_index, |
| + uint16_t min_char, |
| + uint16_t max_char, |
| + BlockLabel* fall_through, |
| + BlockLabel* even_label, |
| + BlockLabel* odd_label) { |
| + intptr_t first = ranges->At(start_index); |
| + intptr_t last = ranges->At(end_index) - 1; |
| + |
| + ASSERT(min_char < first); |
| + |
| + // Just need to test if the character is before or on-or-after |
| + // a particular character. |
| + if (start_index == end_index) { |
| + EmitBoundaryTest(masm, first, fall_through, even_label, odd_label); |
| + return; |
| + } |
| + |
| + // Another almost trivial case: There is one interval in the middle that is |
| + // different from the end intervals. |
| + if (start_index + 1 == end_index) { |
| + EmitDoubleBoundaryTest( |
| + masm, first, last, fall_through, even_label, odd_label); |
| + return; |
| + } |
| + |
| + // It's not worth using table lookup if there are very few intervals in the |
| + // character class. |
| + if (end_index - start_index <= 6) { |
| + // It is faster to test for individual characters, so we look for those |
| + // first, then try arbitrary ranges in the second round. |
| + static intptr_t kNoCutIndex = -1; |
| + intptr_t cut = kNoCutIndex; |
| + for (intptr_t i = start_index; i < end_index; i++) { |
| + if (ranges->At(i) == ranges->At(i + 1) - 1) { |
| + cut = i; |
| + break; |
| + } |
| + } |
| + if (cut == kNoCutIndex) cut = start_index; |
| + CutOutRange( |
| + masm, ranges, start_index, end_index, cut, even_label, odd_label); |
| + ASSERT(end_index - start_index >= 2); |
| + GenerateBranches(masm, |
| + ranges, |
| + start_index + 1, |
| + end_index - 1, |
| + min_char, |
| + max_char, |
| + fall_through, |
| + even_label, |
| + odd_label); |
| + return; |
| + } |
| + |
| + // If there are a lot of intervals in the regexp, then we will use tables to |
| + // determine whether the character is inside or outside the character class. |
| + static const intptr_t kBits = RegExpMacroAssembler::kTableSizeBits; |
| + |
| + if ((max_char >> kBits) == (min_char >> kBits)) { |
| + EmitUseLookupTable(masm, |
| + ranges, |
| + start_index, |
| + end_index, |
| + min_char, |
| + fall_through, |
| + even_label, |
| + odd_label); |
| + return; |
| + } |
| + |
| + if ((min_char >> kBits) != (first >> kBits)) { |
| + masm->CheckCharacterLT(first, odd_label); |
| + GenerateBranches(masm, |
| + ranges, |
| + start_index + 1, |
| + end_index, |
| + first, |
| + max_char, |
| + fall_through, |
| + odd_label, |
| + even_label); |
| + return; |
| + } |
| + |
| + intptr_t new_start_index = 0; |
| + intptr_t new_end_index = 0; |
| + intptr_t border = 0; |
| + |
| + SplitSearchSpace(ranges, |
| + start_index, |
| + end_index, |
| + &new_start_index, |
| + &new_end_index, |
| + &border); |
| + |
| + BlockLabel handle_rest; |
| + BlockLabel* above = &handle_rest; |
| + if (border == last + 1) { |
| + // We didn't find any section that started after the limit, so everything |
| + // above the border is one of the terminal labels. |
| + above = (end_index & 1) != (start_index & 1) ? odd_label : even_label; |
| + ASSERT(new_end_index == end_index - 1); |
| + } |
| + |
| + ASSERT(start_index <= new_end_index); |
| + ASSERT(new_start_index <= end_index); |
| + ASSERT(start_index < new_start_index); |
| + ASSERT(new_end_index < end_index); |
| + ASSERT(new_end_index + 1 == new_start_index || |
| + (new_end_index + 2 == new_start_index && |
| + border == ranges->At(new_end_index + 1))); |
| + ASSERT(min_char < border - 1); |
| + ASSERT(border < max_char); |
| + ASSERT(ranges->At(new_end_index) < border); |
| + ASSERT(border < ranges->At(new_start_index) || |
| + (border == ranges->At(new_start_index) && |
| + new_start_index == end_index && |
| + new_end_index == end_index - 1 && |
| + border == last + 1)); |
| + ASSERT(new_start_index == 0 || border >= ranges->At(new_start_index - 1)); |
| + |
| + masm->CheckCharacterGT(border - 1, above); |
| + BlockLabel dummy; |
| + GenerateBranches(masm, |
| + ranges, |
| + start_index, |
| + new_end_index, |
| + min_char, |
| + border - 1, |
| + &dummy, |
| + even_label, |
| + odd_label); |
| + |
| + if (handle_rest.IsLinked()) { |
| + masm->BindBlock(&handle_rest); |
| + bool flip = (new_start_index & 1) != (start_index & 1); |
| + GenerateBranches(masm, |
| + ranges, |
| + new_start_index, |
| + end_index, |
| + border, |
| + max_char, |
| + &dummy, |
| + flip ? odd_label : even_label, |
| + flip ? even_label : odd_label); |
| + } |
| +} |
| + |
| + |
| +static void EmitCharClass(RegExpMacroAssembler* macro_assembler, |
| + RegExpCharacterClass* cc, |
| + bool ascii, |
| + BlockLabel* on_failure, |
| + intptr_t cp_offset, |
| + bool check_offset, |
| + bool preloaded, |
| + Isolate* isolate) { |
| + ZoneGrowableArray<CharacterRange>* ranges = cc->ranges(); |
| + if (!CharacterRange::IsCanonical(ranges)) { |
| + CharacterRange::Canonicalize(ranges); |
| + } |
| + |
| + intptr_t max_char; |
| + if (ascii) { |
| + max_char = Symbols::kMaxOneCharCodeSymbol; |
| + } else { |
| + max_char = Utf16::kMaxCodeUnit; |
| + } |
| + intptr_t range_count = ranges->length(); |
| -#define DEFINE_EMIT(Type) \ |
| - void Type##Node::Emit(RegExpCompiler* compiler, Trace* trace) { \ |
| - UNIMPLEMENTED(); \ |
| + intptr_t last_valid_range = range_count - 1; |
| + while (last_valid_range >= 0) { |
| + CharacterRange& range = (*ranges)[last_valid_range]; |
| + if (range.from() <= max_char) { |
| + break; |
| + } |
| + last_valid_range--; |
| } |
| -FOR_EACH_NODE_TYPE(DEFINE_EMIT) |
| -DEFINE_EMIT(LoopChoice) |
| -void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, |
| - Trace* trace) { |
| - UNIMPLEMENTED(); |
| -} |
| -#undef DEFINE_EMIT |
| + if (last_valid_range < 0) { |
| + if (!cc->is_negated()) { |
| + macro_assembler->GoTo(on_failure); |
| + } |
| + if (check_offset) { |
| + macro_assembler->CheckPosition(cp_offset, on_failure); |
| + } |
| + return; |
| + } |
| -#define DEFINE_BMINFO(Type) \ |
| - void Type##Node::FillInBMInfo(intptr_t initial_offset, \ |
| - intptr_t budget, \ |
| - BoyerMooreLookahead* bm, \ |
| - bool not_at_start) { \ |
| - UNIMPLEMENTED(); \ |
| + if (last_valid_range == 0 && |
| + ranges->At(0).IsEverything(max_char)) { |
| + if (cc->is_negated()) { |
| + macro_assembler->GoTo(on_failure); |
| + } else { |
| + // This is a common case hit by non-anchored expressions. |
| + if (check_offset) { |
| + macro_assembler->CheckPosition(cp_offset, on_failure); |
| + } |
| + } |
| + return; |
| + } |
| + if (last_valid_range == 0 && |
| + !cc->is_negated() && |
| + ranges->At(0).IsEverything(max_char)) { |
| + // This is a common case hit by non-anchored expressions. |
| + if (check_offset) { |
| + macro_assembler->CheckPosition(cp_offset, on_failure); |
| + } |
| + return; |
| } |
| -FOR_EACH_NODE_TYPE(DEFINE_BMINFO) |
| -DEFINE_BMINFO(LoopChoice) |
| -#undef DEFINE_BMINFO |
| + if (!preloaded) { |
| + macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset); |
| + } |
| -// Emit the code to handle \b and \B (word-boundary or non-word-boundary). |
| -void AssertionNode::EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace) { |
| - UNIMPLEMENTED(); |
| -} |
| + if (cc->is_standard() && |
| + macro_assembler->CheckSpecialCharacterClass(cc->standard_type(), |
| + on_failure)) { |
| + return; |
| + } |
| -void AssertionNode::BacktrackIfPrevious( |
| - RegExpCompiler* compiler, |
| - Trace* trace, |
| - AssertionNode::IfPrevious backtrack_if_previous) { |
| - UNIMPLEMENTED(); |
| + // A new list with ascending entries. Each entry is a code unit |
| + // where there is a boundary between code units that are part of |
| + // the class and code units that are not. Normally we insert an |
| + // entry at zero which goes to the failure label, but if there |
| + // was already one there we fall through for success on that entry. |
| + // Subsequent entries have alternating meaning (success/failure). |
| + ZoneGrowableArray<int>* range_boundaries = |
| + new(isolate) ZoneGrowableArray<int>(last_valid_range); |
| + |
| + bool zeroth_entry_is_failure = !cc->is_negated(); |
| + |
| + for (intptr_t i = 0; i <= last_valid_range; i++) { |
| + CharacterRange& range = (*ranges)[i]; |
| + if (range.from() == 0) { |
| + ASSERT(i == 0); |
| + zeroth_entry_is_failure = !zeroth_entry_is_failure; |
| + } else { |
| + range_boundaries->Add(range.from()); |
| + } |
| + range_boundaries->Add(range.to() + 1); |
| + } |
| + intptr_t end_index = range_boundaries->length() - 1; |
| + if (range_boundaries->At(end_index) > max_char) { |
| + end_index--; |
| + } |
| + |
| + BlockLabel fall_through; |
| + GenerateBranches(macro_assembler, |
| + range_boundaries, |
| + 0, // start_index. |
| + end_index, |
| + 0, // min_char. |
| + max_char, |
| + &fall_through, |
| + zeroth_entry_is_failure ? &fall_through : on_failure, |
| + zeroth_entry_is_failure ? on_failure : &fall_through); |
| + macro_assembler->BindBlock(&fall_through); |
| } |
| @@ -785,24 +2854,91 @@ void TextNode::TextEmitPass(RegExpCompiler* compiler, |
| Trace* trace, |
| bool first_element_checked, |
| intptr_t* checked_up_to) { |
| - UNIMPLEMENTED(); |
| + RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| + bool ascii = compiler->ascii(); |
| + BlockLabel* backtrack = trace->backtrack(); |
| + QuickCheckDetails* quick_check = trace->quick_check_performed(); |
| + intptr_t element_count = elms_->length(); |
| + for (intptr_t i = preloaded ? 0 : element_count - 1; i >= 0; i--) { |
| + TextElement elm = elms_->At(i); |
| + intptr_t cp_offset = trace->cp_offset() + elm.cp_offset(); |
| + if (elm.text_type() == TextElement::ATOM) { |
| + ZoneGrowableArray<uint16_t>* quarks = elm.atom()->data(); |
| + for (intptr_t j = preloaded ? 0 : quarks->length() - 1; j >= 0; j--) { |
| + if (first_element_checked && i == 0 && j == 0) continue; |
| + if (DeterminedAlready(quick_check, elm.cp_offset() + j)) continue; |
| + EmitCharacterFunction* emit_function = NULL; |
| + switch (pass) { |
| + case NON_ASCII_MATCH: |
| + ASSERT(ascii); |
| + if (quarks->At(j) > Symbols::kMaxOneCharCodeSymbol) { |
| + assembler->GoTo(backtrack); |
| + return; |
| + } |
| + break; |
| + case NON_LETTER_CHARACTER_MATCH: |
| + emit_function = &EmitAtomNonLetter; |
| + break; |
| + case SIMPLE_CHARACTER_MATCH: |
| + emit_function = &EmitSimpleCharacter; |
| + break; |
| + case CASE_CHARACTER_MATCH: |
| + emit_function = &EmitAtomLetter; |
| + break; |
| + default: |
| + break; |
| + } |
| + if (emit_function != NULL) { |
| + bool bound_checked = emit_function(I, |
| + compiler, |
| + quarks->At(j), |
| + backtrack, |
| + cp_offset + j, |
| + *checked_up_to < cp_offset + j, |
| + preloaded); |
| + if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to); |
| + } |
| + } |
| + } else { |
| + ASSERT(elm.text_type() == TextElement::CHAR_CLASS); |
| + if (pass == CHARACTER_CLASS_MATCH) { |
| + if (first_element_checked && i == 0) continue; |
| + if (DeterminedAlready(quick_check, elm.cp_offset())) continue; |
| + RegExpCharacterClass* cc = elm.char_class(); |
| + EmitCharClass(assembler, |
| + cc, |
| + ascii, |
| + backtrack, |
| + cp_offset, |
| + *checked_up_to < cp_offset, |
| + preloaded, |
| + I); |
| + UpdateBoundsCheck(cp_offset, checked_up_to); |
| + } |
| + } |
| + } |
| } |
| intptr_t ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler, |
| - intptr_t eats_at_least) { |
| - UNIMPLEMENTED(); |
| - return NULL; |
| -} |
| - |
| - |
| -void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler, |
| - Trace* trace, |
| - GuardedAlternative alternative, |
| - AlternativeGeneration* alt_gen, |
| - intptr_t preload_characters, |
| - bool next_expects_preload) { |
| - UNIMPLEMENTED(); |
| + intptr_t eats_at_least) { |
| + intptr_t preload_characters = Utils::Minimum(static_cast<intptr_t>(4), |
| + eats_at_least); |
| + if (compiler->macro_assembler()->CanReadUnaligned()) { |
| + bool ascii = compiler->ascii(); |
| + if (ascii) { |
| + if (preload_characters > 4) preload_characters = 4; |
| + // We can't preload 3 characters because there is no machine instruction |
| + // to do that. We can't just load 4 because we could be reading |
| + // beyond the end of the string, which could cause a memory fault. |
| + if (preload_characters == 3) preload_characters = 2; |
| + } else { |
| + if (preload_characters > 2) preload_characters = 2; |
| + } |
| + } else { |
| + if (preload_characters > 1) preload_characters = 1; |
| + } |
| + return preload_characters; |
| } |
| @@ -897,6 +3033,17 @@ intptr_t NegativeLookaheadChoiceNode::EatsAtLeast(intptr_t still_to_find, |
| } |
| +// Takes the left-most 1-bit and smears it out, setting all bits to its right. |
| +static inline uint32_t SmearBitsRight(uint32_t v) { |
| + v |= v >> 1; |
| + v |= v >> 2; |
| + v |= v >> 4; |
| + v |= v >> 8; |
| + v |= v >> 16; |
| + return v; |
| +} |
| + |
| + |
| // Here is the meat of GetQuickCheckDetails (see also the comment on the |
| // super-class in the .h file). |
| // |
| @@ -909,7 +3056,150 @@ void TextNode::GetQuickCheckDetails(QuickCheckDetails* details, |
| RegExpCompiler* compiler, |
| intptr_t characters_filled_in, |
| bool not_at_start) { |
| - UNIMPLEMENTED(); |
| + ASSERT(characters_filled_in < details->characters()); |
| + intptr_t characters = details->characters(); |
| + intptr_t char_mask; |
| + if (compiler->ascii()) { |
| + char_mask = Symbols::kMaxOneCharCodeSymbol; |
| + } else { |
| + char_mask = Utf16::kMaxCodeUnit; |
| + } |
| + for (intptr_t k = 0; k < elms_->length(); k++) { |
| + TextElement elm = elms_->At(k); |
| + if (elm.text_type() == TextElement::ATOM) { |
| + ZoneGrowableArray<uint16_t>* quarks = elm.atom()->data(); |
| + for (intptr_t i = 0; i < characters && i < quarks->length(); i++) { |
| + QuickCheckDetails::Position* pos = |
| + details->positions(characters_filled_in); |
| + uint16_t c = quarks->At(i); |
| + if (c > char_mask) { |
| + // If we expect a non-ASCII character from an ASCII string, |
| + // there is no way we can match. Not even case independent |
| + // matching can turn an ASCII character into non-ASCII or |
| + // vice versa. |
| + details->set_cannot_match(); |
| + pos->determines_perfectly = false; |
| + return; |
| + } |
| + if (compiler->ignore_case()) { |
| + int32_t chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| + intptr_t length = |
| + GetCaseIndependentLetters(c, compiler->ascii(), chars); |
| + ASSERT(length != 0); // Can only happen if c > char_mask (see above). |
| + if (length == 1) { |
| + // This letter has no case equivalents, so it's nice and simple |
| + // and the mask-compare will determine definitely whether we have |
| + // a match at this character position. |
| + pos->mask = char_mask; |
| + pos->value = c; |
| + pos->determines_perfectly = true; |
| + } else { |
| + uint32_t common_bits = char_mask; |
| + uint32_t bits = chars[0]; |
| + for (intptr_t j = 1; j < length; j++) { |
| + uint32_t differing_bits = ((chars[j] & common_bits) ^ bits); |
| + common_bits ^= differing_bits; |
| + bits &= common_bits; |
| + } |
| + // If length is 2 and common bits has only one zero in it then |
| + // our mask and compare instruction will determine definitely |
| + // whether we have a match at this character position. Otherwise |
| + // it can only be an approximate check. |
| + uint32_t one_zero = (common_bits | ~char_mask); |
| + if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) { |
| + pos->determines_perfectly = true; |
| + } |
| + pos->mask = common_bits; |
| + pos->value = bits; |
| + } |
| + } else { |
| + // Don't ignore case. Nice simple case where the mask-compare will |
| + // determine definitely whether we have a match at this character |
| + // position. |
| + pos->mask = char_mask; |
| + pos->value = c; |
| + pos->determines_perfectly = true; |
| + } |
| + characters_filled_in++; |
| + ASSERT(characters_filled_in <= details->characters()); |
| + if (characters_filled_in == details->characters()) { |
| + return; |
| + } |
| + } |
| + } else { |
| + QuickCheckDetails::Position* pos = |
| + details->positions(characters_filled_in); |
| + RegExpCharacterClass* tree = elm.char_class(); |
| + ZoneGrowableArray<CharacterRange>* ranges = tree->ranges(); |
| + if (tree->is_negated()) { |
| + // A quick check uses multi-character mask and compare. There is no |
| + // useful way to incorporate a negative char class into this scheme |
| + // so we just conservatively create a mask and value that will always |
| + // succeed. |
| + pos->mask = 0; |
| + pos->value = 0; |
| + } else { |
| + intptr_t first_range = 0; |
| + while (ranges->At(first_range).from() > char_mask) { |
| + first_range++; |
| + if (first_range == ranges->length()) { |
| + details->set_cannot_match(); |
| + pos->determines_perfectly = false; |
| + return; |
| + } |
| + } |
| + CharacterRange range = ranges->At(first_range); |
| + uint16_t from = range.from(); |
| + uint16_t to = range.to(); |
| + if (to > char_mask) { |
| + to = char_mask; |
| + } |
| + uint32_t differing_bits = (from ^ to); |
| + // A mask and compare is only perfect if the differing bits form a |
| + // number like 00011111 with one single block of trailing 1s. |
| + if ((differing_bits & (differing_bits + 1)) == 0 && |
| + from + differing_bits == to) { |
| + pos->determines_perfectly = true; |
| + } |
| + uint32_t common_bits = ~SmearBitsRight(differing_bits); |
| + uint32_t bits = (from & common_bits); |
| + for (intptr_t i = first_range + 1; i < ranges->length(); i++) { |
| + CharacterRange range = ranges->At(i); |
| + uint16_t from = range.from(); |
| + uint16_t to = range.to(); |
| + if (from > char_mask) continue; |
| + if (to > char_mask) to = char_mask; |
| + // Here we are combining more ranges into the mask and compare |
| + // value. With each new range the mask becomes more sparse and |
| + // so the chances of a false positive rise. A character class |
| + // with multiple ranges is assumed never to be equivalent to a |
| + // mask and compare operation. |
| + pos->determines_perfectly = false; |
| + uint32_t new_common_bits = (from ^ to); |
| + new_common_bits = ~SmearBitsRight(new_common_bits); |
| + common_bits &= new_common_bits; |
| + bits &= new_common_bits; |
| + uint32_t differing_bits = (from & common_bits) ^ bits; |
| + common_bits ^= differing_bits; |
| + bits &= common_bits; |
| + } |
| + pos->mask = common_bits; |
| + pos->value = bits; |
| + } |
| + characters_filled_in++; |
| + ASSERT(characters_filled_in <= details->characters()); |
| + if (characters_filled_in == details->characters()) { |
| + return; |
| + } |
| + } |
| + } |
| + ASSERT(characters_filled_in != details->characters()); |
| + if (!details->cannot_match()) { |
| + on_success()-> GetQuickCheckDetails(details, |
| + compiler, |
| + characters_filled_in, |
| + true); |
| + } |
| } |
| @@ -917,7 +3207,12 @@ void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details, |
| RegExpCompiler* compiler, |
| intptr_t characters_filled_in, |
| bool not_at_start) { |
| - UNIMPLEMENTED(); |
| + if (body_can_be_zero_length_ || info()->visited) return; |
| + VisitMarker marker(info()); |
| + return ChoiceNode::GetQuickCheckDetails(details, |
| + compiler, |
| + characters_filled_in, |
| + not_at_start); |
| } |
| @@ -1456,61 +3751,103 @@ void CharacterRange::AddCaseEquivalents( |
| } |
| } |
| - UNIMPLEMENTED(); |
| + unibrow::Mapping<unibrow::Ecma262UnCanonicalize> jsregexp_uncanonicalize; |
| + unibrow::Mapping<unibrow::CanonicalizationRange> jsregexp_canonrange; |
| + int32_t chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| + if (top == bottom) { |
| + // If this is a singleton we just expand the one character. |
| + intptr_t length = jsregexp_uncanonicalize.get(bottom, '\0', chars); // NOLINT |
| + for (intptr_t i = 0; i < length; i++) { |
| + uint32_t chr = chars[i]; |
| + if (chr != bottom) { |
| + ranges->Add(CharacterRange::Singleton(chars[i])); |
| + } |
| + } |
| + } else { |
| + // If this is a range we expand the characters block by block, |
| + // expanding contiguous subranges (blocks) one at a time. |
| + // The approach is as follows. For a given start character we |
| + // look up the remainder of the block that contains it (represented |
| + // by the end point), for instance we find 'z' if the character |
| + // is 'c'. A block is characterized by the property |
| + // that all characters uncanonicalize in the same way, except that |
| + // each entry in the result is incremented by the distance from the first |
| + // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and // NOLINT |
| + // the k'th letter uncanonicalizes to ['a' + k, 'A' + k]. |
| + // Once we've found the end point we look up its uncanonicalization |
| + // and produce a range for each element. For instance for [c-f] |
| + // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only |
| + // add a range if it is not already contained in the input, so [c-f] |
| + // will be skipped but [C-F] will be added. If this range is not |
| + // completely contained in a block we do this for all the blocks |
| + // covered by the range (handling characters that is not in a block |
| + // as a "singleton block"). |
| + int32_t range[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| + intptr_t pos = bottom; |
| + while (pos <= top) { |
| + intptr_t length = jsregexp_canonrange.get(pos, '\0', range); |
| + uint16_t block_end; |
| + if (length == 0) { |
| + block_end = pos; |
| + } else { |
| + ASSERT(length == 1); |
| + block_end = range[0]; |
| + } |
| + intptr_t end = (block_end > top) ? top : block_end; |
| + length = jsregexp_uncanonicalize.get(block_end, '\0', range); // NOLINT |
| + for (intptr_t i = 0; i < length; i++) { |
| + uint32_t c = range[i]; |
| + uint16_t range_from = c - (block_end - pos); |
| + uint16_t range_to = c - (block_end - end); |
| + if (!(bottom <= range_from && range_to <= top)) { |
| + ranges->Add(CharacterRange(range_from, range_to)); |
| + } |
| + } |
| + pos = end + 1; |
| + } |
| + } |
| +} |
| + |
| + |
| +// ------------------------------------------------------------------- |
| +// Splay tree |
| + |
| + |
| +// Workaround for the fact that ZoneGrowableArray does not have contains(). |
| +static bool ArrayContains(ZoneGrowableArray<unsigned>* array, |
| + unsigned value) { |
| + for (intptr_t i = 0; i < array->length(); i++) { |
| + if (array->At(i) == value) { |
| + return true; |
| + } |
| + } |
| + return false; |
| +} |
| + |
| + |
| +void OutSet::Set(unsigned value, Isolate* isolate) { |
| + if (value < kFirstLimit) { |
| + first_ |= (1 << value); |
| + } else { |
| + if (remaining_ == NULL) |
| + remaining_ = new(isolate) ZoneGrowableArray<unsigned>(1); |
| -// unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| -// if (top == bottom) { |
| -// // If this is a singleton we just expand the one character. |
| -// intptr_t length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars); // NOLINT |
| -// for (intptr_t i = 0; i < length; i++) { |
| -// uint32_t chr = chars[i]; |
| -// if (chr != bottom) { |
| -// ranges->Add(CharacterRange::Singleton(chars[i]), zone); |
| -// } |
| -// } |
| -// } else { |
| -// // If this is a range we expand the characters block by block, |
| -// // expanding contiguous subranges (blocks) one at a time. |
| -// // The approach is as follows. For a given start character we |
| -// // look up the remainder of the block that contains it (represented |
| -// // by the end point), for instance we find 'z' if the character |
| -// // is 'c'. A block is characterized by the property |
| -// // that all characters uncanonicalize in the same way, except that |
| -// // each entry in the result is incremented by the distance from the first |
| -// // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and // NOLINT |
| -// // the k'th letter uncanonicalizes to ['a' + k, 'A' + k]. |
| -// // Once we've found the end point we look up its uncanonicalization |
| -// // and produce a range for each element. For instance for [c-f] |
| -// // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only |
| -// // add a range if it is not already contained in the input, so [c-f] |
| -// // will be skipped but [C-F] will be added. If this range is not |
| -// // completely contained in a block we do this for all the blocks |
| -// // covered by the range (handling characters that is not in a block |
| -// // as a "singleton block"). |
| -// unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| -// intptr_t pos = bottom; |
| -// while (pos <= top) { |
| -// intptr_t length = isolate->jsregexp_canonrange()->get(pos, '\0', range); |
| -// uint16_t block_end; |
| -// if (length == 0) { |
| -// block_end = pos; |
| -// } else { |
| -// ASSERT(length == 1); |
| -// block_end = range[0]; |
| -// } |
| -// intptr_t end = (block_end > top) ? top : block_end; |
| -// length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range); // NOLINT |
| -// for (intptr_t i = 0; i < length; i++) { |
| -// uint32_t c = range[i]; |
| -// uint16_t range_from = c - (block_end - pos); |
| -// uint16_t range_to = c - (block_end - end); |
| -// if (!(bottom <= range_from && range_to <= top)) { |
| -// ranges->Add(CharacterRange(range_from, range_to)); |
| -// } |
| -// } |
| -// pos = end + 1; |
| -// } |
| -// } |
| + bool remaining_contains_value = ArrayContains(remaining_, value); |
| + if (remaining_->is_empty() || !remaining_contains_value) { |
| + remaining_->Add(value); |
| + } |
| + } |
| +} |
| + |
| + |
| +bool OutSet::Get(unsigned value) const { |
| + if (value < kFirstLimit) { |
| + return (first_ & (1 << value)) != 0; |
| + } else if (remaining_ == NULL) { |
| + return false; |
| + } else { |
| + return ArrayContains(remaining_, value); |
| + } |
| } |
| void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details, |
| @@ -1564,23 +3901,6 @@ intptr_t LoopChoiceNode::EatsAtLeast(intptr_t still_to_find, |
| } |
| -class RecursionCheck { |
| - public: |
| - explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) { |
| - compiler->IncrementRecursionDepth(); |
| - } |
| - ~RecursionCheck() { compiler_->DecrementRecursionDepth(); } |
| - private: |
| - RegExpCompiler* compiler_; |
| -}; |
| - |
| - |
| -DispatchTable* ChoiceNode::GetTable(bool ignore_case) { |
| - UNIMPLEMENTED(); |
| - return NULL; |
| -} |
| - |
| - |
| void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details, |
| RegExpCompiler* compiler, |
| intptr_t characters_filled_in, |
| @@ -1703,14 +4023,20 @@ void NegativeLookaheadChoiceNode::GetQuickCheckDetails( |
| } |
| +static RegExpEngine::CompilationResult IrregexpRegExpTooBig() { |
| + return RegExpEngine::CompilationResult("RegExp too big"); |
| +} |
| + |
| + |
| // Attempts to compile the regexp using an Irregexp code generator. Returns |
| // a fixed array or a null handle depending on whether it succeeded. |
| RegExpCompiler::RegExpCompiler(intptr_t capture_count, bool ignore_case, |
| - bool ascii) |
| + intptr_t specialization_cid) |
| : next_register_(2 * (capture_count + 1)), |
| + work_list_(NULL), |
| recursion_depth_(0), |
| ignore_case_(ignore_case), |
| - ascii_(ascii), |
| + specialization_cid_(specialization_cid), |
| reg_exp_too_big_(false), |
| current_expansion_factor_(1), |
| isolate_(Isolate::Current()) { |
| @@ -1719,28 +4045,71 @@ RegExpCompiler::RegExpCompiler(intptr_t capture_count, bool ignore_case, |
| RegExpEngine::CompilationResult RegExpCompiler::Assemble( |
| - RegExpMacroAssembler* macro_assembler, |
| + IRRegExpMacroAssembler* macro_assembler, |
| RegExpNode* start, |
| intptr_t capture_count, |
| const String& pattern) { |
| - UNIMPLEMENTED(); |
| - return RegExpEngine::CompilationResult(""); |
| + static const bool use_slow_safe_regexp_compiler = false; |
| + |
| + macro_assembler->set_slow_safe(use_slow_safe_regexp_compiler); |
| + macro_assembler_ = macro_assembler; |
| + |
| + ZoneGrowableArray<RegExpNode*> work_list(0); |
| + work_list_ = &work_list; |
| + BlockLabel fail; |
| + macro_assembler_->PushBacktrack(&fail); |
| + Trace new_trace; |
| + start->Emit(this, &new_trace); |
| + macro_assembler_->BindBlock(&fail); |
| + macro_assembler_->Fail(); |
| + while (!work_list.is_empty()) { |
| + work_list.RemoveLast()->Emit(this, &new_trace); |
| + } |
| + if (reg_exp_too_big_) return IrregexpRegExpTooBig(); |
| + |
| + macro_assembler->FinalizeIndirectGotos(); |
| + |
| + return RegExpEngine::CompilationResult(macro_assembler, |
| + macro_assembler->graph_entry(), |
| + macro_assembler->num_blocks(), |
| + macro_assembler->num_stack_locals()); |
| } |
| RegExpEngine::CompilationResult RegExpEngine::Compile( |
| RegExpCompileData* data, |
| - bool ignore_case, |
| - bool is_global, |
| - bool is_multiline, |
| - const String& pattern, |
| - const String& sample_subject, |
| - bool is_ascii) { |
| + const ParsedFunction* parsed_function, |
| + ZoneGrowableArray<const ICData*>* ic_data_array) { |
| Isolate* isolate = Isolate::Current(); |
| - RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii); |
| - |
| - // TODO(jgruber): Character frequency sampling. |
| + const Function& function = parsed_function->function(); |
| + const intptr_t specialization_cid = function.regexp_specialization(); |
| + const bool is_ascii = (specialization_cid == kOneByteStringCid || |
| + specialization_cid == kExternalOneByteStringCid); |
| + JSRegExp& regexp = JSRegExp::Handle(isolate, function.regexp()); |
| + const String& pattern = String::Handle(isolate, regexp.pattern()); |
| + const String& sample_subject = |
| + String::Handle(isolate, regexp.sample_subject(specialization_cid)); |
| + |
| + ASSERT(!regexp.IsNull()); |
| + ASSERT(!pattern.IsNull()); |
| + ASSERT(!sample_subject.IsNull()); |
| + |
| + const bool ignore_case = regexp.is_ignore_case(); |
| + const bool is_global = regexp.is_global(); |
| + |
| + RegExpCompiler compiler(data->capture_count, ignore_case, specialization_cid); |
| + |
| + // Sample some characters from the middle of the string. |
| + static const intptr_t kSampleSize = 128; |
| + |
| + intptr_t chars_sampled = 0; |
| + intptr_t half_way = (sample_subject.Length() - kSampleSize) / 2; |
| + for (intptr_t i = Utils::Maximum(static_cast<intptr_t>(0), half_way); |
| + i < sample_subject.Length() && chars_sampled < kSampleSize; |
| + i++, chars_sampled++) { |
| + compiler.frequency_collator()->CountCharacter(sample_subject.CharAt(i)); |
| + } |
| // Wrap the body of the regexp in capture #0. |
| RegExpNode* captured_body = RegExpCapture::ToNode(data->tree, |
| @@ -1750,6 +4119,8 @@ RegExpEngine::CompilationResult RegExpEngine::Compile( |
| RegExpNode* node = captured_body; |
| bool is_start_anchored = data->tree->IsAnchoredAtStart(); |
| + bool is_end_anchored = data->tree->IsAnchoredAtEnd(); |
| + intptr_t max_length = data->tree->max_match(); |
| if (!is_start_anchored) { |
| // Add a .*? at the beginning, outside the body capture, unless |
| // this expression is anchored at the beginning. |
| @@ -1793,9 +4164,366 @@ RegExpEngine::CompilationResult RegExpEngine::Compile( |
| return CompilationResult(error_message); |
| } |
| - // TODO(jgruber): Assemble native code. |
| + // Native regexp implementation. |
| + |
| + IRRegExpMacroAssembler* macro_assembler = |
| + new(isolate) IRRegExpMacroAssembler(specialization_cid, |
| + data->capture_count, |
| + parsed_function, |
| + ic_data_array, |
| + isolate); |
| + |
| + // Inserted here, instead of in Assembler, because it depends on information |
| + // in the AST that isn't replicated in the Node structure. |
| + static const intptr_t kMaxBacksearchLimit = 1024; |
| + if (is_end_anchored && |
| + !is_start_anchored && |
| + max_length < kMaxBacksearchLimit) { |
| + macro_assembler->SetCurrentPositionFromEnd(max_length); |
| + } |
| + |
| + if (is_global) { |
| + macro_assembler->set_global_mode( |
| + (data->tree->min_match() > 0) |
| + ? RegExpMacroAssembler::GLOBAL_NO_ZERO_LENGTH_CHECK |
| + : RegExpMacroAssembler::GLOBAL); |
| + } |
| + |
| + RegExpEngine::CompilationResult result = |
| + compiler.Assemble(macro_assembler, |
| + node, |
| + data->capture_count, |
| + pattern); |
| + |
| + if (FLAG_trace_irregexp) { |
| + macro_assembler->PrintBlocks(); |
| + } |
| + |
| + return result; |
| +} |
| + |
| + |
| +static void CreateSpecializedFunction(Isolate* isolate, |
| + JSRegExp* regexp, |
| + intptr_t specialization_cid, |
| + const Object& owner) { |
| + const intptr_t kParamCount = RegExpMacroAssembler::kParamCount; |
| + |
| + Function& fn = Function::Handle(isolate, |
| + Function::New(String::Handle(isolate, Symbols::New("RegExp")), |
| + RawFunction::kIrregexpFunction, |
| + true, // Static. |
| + false, // Not const. |
| + false, // Not abstract. |
| + false, // Not external. |
| + false, // Not native. |
| + owner, |
| + 0)); // Requires a non-negative token position. |
| + |
| + fn.set_num_fixed_parameters(kParamCount); |
| + fn.set_parameter_types( |
| + Array::Handle(isolate, Array::New(kParamCount, Heap::kOld))); |
| + fn.set_parameter_names( |
| + Array::Handle(isolate, Array::New(kParamCount, Heap::kOld))); |
| + fn.SetParameterTypeAt(0, Type::Handle(isolate, Type::DynamicType())); |
| + fn.SetParameterNameAt(0, Symbols::string_param_()); |
| + fn.SetParameterTypeAt(1, Type::Handle(isolate, Type::DynamicType())); |
| + fn.SetParameterNameAt(1, Symbols::start_index_param_()); |
| + fn.set_result_type(Type::Handle(isolate, Type::ArrayType())); |
| + |
| + // Cache the result. |
| + regexp->set_function(specialization_cid, fn); |
| + |
| + fn.set_regexp(*regexp); |
| + fn.set_regexp_specialization(specialization_cid); |
| + |
| + // The function is compiled lazily during the first call. |
| +} |
| + |
| + |
| +RawJSRegExp* RegExpEngine::New(Isolate* isolate, |
| + const String& pattern, |
| + bool multi_line, |
| + bool ignore_case) { |
| + JSRegExp& regexp = JSRegExp::Handle(JSRegExp::New(0)); |
| + |
| + regexp.set_pattern(pattern); |
| + |
| + if (multi_line) regexp.set_is_multi_line(); |
| + if (ignore_case) regexp.set_is_ignore_case(); |
| + |
| + // TODO(jgruber): We might want to use normal string searching algorithms |
| + // for simple patterns. |
| + regexp.set_is_complex(); |
| + regexp.set_is_global(); // All dart regexps are global. |
| + |
| + const Library& lib = Library::Handle(isolate, Library::CoreLibrary()); |
| + const Class& owner = Class::Handle(isolate, |
| + lib.LookupClass(String::Handle(isolate, Symbols::New("RegExp")))); |
| + |
| + CreateSpecializedFunction(isolate, ®exp, kOneByteStringCid, owner); |
| + CreateSpecializedFunction(isolate, ®exp, kTwoByteStringCid, owner); |
| + CreateSpecializedFunction(isolate, ®exp, kExternalOneByteStringCid, owner); |
| + CreateSpecializedFunction(isolate, ®exp, kExternalTwoByteStringCid, owner); |
| + |
| + return regexp.raw(); |
| +} |
| + |
| + |
| +void BoyerMoorePositionInfo::Set(intptr_t character) { |
| + SetInterval(Interval(character, character)); |
| +} |
| + |
| + |
| +ContainedInLattice AddRange(ContainedInLattice containment, |
| + const intptr_t* ranges, |
| + intptr_t ranges_length, |
| + Interval new_range) { |
| + ASSERT((ranges_length & 1) == 1); |
| + ASSERT(ranges[ranges_length - 1] == Utf16::kMaxCodeUnit + 1); |
| + if (containment == kLatticeUnknown) return containment; |
| + bool inside = false; |
| + intptr_t last = 0; |
| + for (intptr_t i = 0; i < ranges_length; |
| + inside = !inside, last = ranges[i], i++) { |
| + // Consider the range from last to ranges[i]. |
| + // We haven't got to the new range yet. |
| + if (ranges[i] <= new_range.from()) continue; |
| + // New range is wholly inside last-ranges[i]. Note that new_range.to() is |
| + // inclusive, but the values in ranges are not. |
| + if (last <= new_range.from() && new_range.to() < ranges[i]) { |
| + return Combine(containment, inside ? kLatticeIn : kLatticeOut); |
| + } |
| + return kLatticeUnknown; |
| + } |
| + return containment; |
| +} |
| + |
| + |
| +void BoyerMoorePositionInfo::SetInterval(const Interval& interval) { |
| + s_ = AddRange(s_, kSpaceRanges, kSpaceRangeCount, interval); |
| + w_ = AddRange(w_, kWordRanges, kWordRangeCount, interval); |
| + d_ = AddRange(d_, kDigitRanges, kDigitRangeCount, interval); |
| + surrogate_ = |
| + AddRange(surrogate_, kSurrogateRanges, kSurrogateRangeCount, interval); |
| + if (interval.to() - interval.from() >= kMapSize - 1) { |
| + if (map_count_ != kMapSize) { |
| + map_count_ = kMapSize; |
| + for (intptr_t i = 0; i < kMapSize; i++) (*map_)[i] = true; |
| + } |
| + return; |
| + } |
| + for (intptr_t i = interval.from(); i <= interval.to(); i++) { |
| + intptr_t mod_character = (i & kMask); |
| + if (!map_->At(mod_character)) { |
| + map_count_++; |
| + (*map_)[mod_character] = true; |
| + } |
| + if (map_count_ == kMapSize) return; |
| + } |
| +} |
| + |
| + |
| +void BoyerMoorePositionInfo::SetAll() { |
| + s_ = w_ = d_ = kLatticeUnknown; |
| + if (map_count_ != kMapSize) { |
| + map_count_ = kMapSize; |
| + for (intptr_t i = 0; i < kMapSize; i++) (*map_)[i] = true; |
| + } |
| +} |
| + |
| + |
| +BoyerMooreLookahead::BoyerMooreLookahead( |
| + intptr_t length, RegExpCompiler* compiler, Isolate* isolate) |
| + : length_(length), |
| + compiler_(compiler) { |
| + if (compiler->ascii()) { |
| + max_char_ = Symbols::kMaxOneCharCodeSymbol; |
| + } else { |
| + max_char_ = Utf16::kMaxCodeUnit; |
| + } |
| + bitmaps_ = new(isolate) ZoneGrowableArray<BoyerMoorePositionInfo*>(length); |
| + for (intptr_t i = 0; i < length; i++) { |
| + bitmaps_->Add(new(isolate) BoyerMoorePositionInfo(isolate)); |
| + } |
| +} |
| + |
| + |
| +// Take all the characters that will not prevent a successful match if they |
| +// occur in the subject string in the range between min_lookahead and |
| +// max_lookahead (inclusive) measured from the current position. If the |
| +// character at max_lookahead offset is not one of these characters, then we |
| +// can safely skip forwards by the number of characters in the range. |
| +intptr_t BoyerMooreLookahead::GetSkipTable(intptr_t min_lookahead, |
| + intptr_t max_lookahead, |
| + TypedData* boolean_skip_table) { |
|
Florian Schneider
2014/10/01 17:04:14
const TypedData& since this will never be NULL.
jgruber1
2014/10/03 18:59:52
Done.
|
| + const intptr_t kSize = RegExpMacroAssembler::kTableSize; |
| + |
| + const intptr_t kSkipArrayEntry = 0; |
| + const intptr_t kDontSkipArrayEntry = 1; |
| + |
| + for (intptr_t i = 0; i < kSize; i++) { |
| + boolean_skip_table->SetUint8(i, kSkipArrayEntry); |
| + } |
| + intptr_t skip = max_lookahead + 1 - min_lookahead; |
| + |
| + for (intptr_t i = max_lookahead; i >= min_lookahead; i--) { |
| + BoyerMoorePositionInfo* map = bitmaps_->At(i); |
| + for (intptr_t j = 0; j < kSize; j++) { |
| + if (map->at(j)) { |
| + boolean_skip_table->SetUint8(j, kDontSkipArrayEntry); |
| + } |
| + } |
| + } |
| + |
| + return skip; |
| +} |
| + |
| + |
| +// Find the longest range of lookahead that has the fewest number of different |
| +// characters that can occur at a given position. Since we are optimizing two |
| +// different parameters at once this is a tradeoff. |
| +bool BoyerMooreLookahead::FindWorthwhileInterval(intptr_t* from, intptr_t* to) { |
| + intptr_t biggest_points = 0; |
| + // If more than 32 characters out of 128 can occur it is unlikely that we can |
| + // be lucky enough to step forwards much of the time. |
| + const intptr_t kMaxMax = 32; |
| + for (intptr_t max_number_of_chars = 4; |
| + max_number_of_chars < kMaxMax; |
| + max_number_of_chars *= 2) { |
| + biggest_points = |
| + FindBestInterval(max_number_of_chars, biggest_points, from, to); |
| + } |
| + if (biggest_points == 0) return false; |
| + return true; |
| +} |
| + |
| + |
| +// Find the highest-points range between 0 and length_ where the character |
| +// information is not too vague. 'Too vague' means that there are more than |
| +// max_number_of_chars that can occur at this position. Calculates the number |
| +// of points as the product of width-of-the-range and |
| +// probability-of-finding-one-of-the-characters, where the probability is |
| +// calculated using the frequency distribution of the sample subject string. |
| +intptr_t BoyerMooreLookahead::FindBestInterval( |
| + intptr_t max_number_of_chars, |
| + intptr_t old_biggest_points, |
| + intptr_t* from, |
| + intptr_t* to) { |
| + intptr_t biggest_points = old_biggest_points; |
| + static const intptr_t kSize = RegExpMacroAssembler::kTableSize; |
| + for (intptr_t i = 0; i < length_; ) { |
| + while (i < length_ && Count(i) > max_number_of_chars) i++; |
| + if (i == length_) break; |
| + intptr_t remembered_from = i; |
| + bool union_map[kSize]; |
| + for (intptr_t j = 0; j < kSize; j++) union_map[j] = false; |
| + while (i < length_ && Count(i) <= max_number_of_chars) { |
| + BoyerMoorePositionInfo* map = bitmaps_->At(i); |
| + for (intptr_t j = 0; j < kSize; j++) union_map[j] |= map->at(j); |
| + i++; |
| + } |
| + intptr_t frequency = 0; |
| + for (intptr_t j = 0; j < kSize; j++) { |
| + if (union_map[j]) { |
| + // Add 1 to the frequency to give a small per-character boost for |
| + // the cases where our sampling is not good enough and many |
| + // characters have a frequency of zero. This means the frequency |
| + // can theoretically be up to 2*kSize though we treat it mostly as |
| + // a fraction of kSize. |
| + frequency += compiler_->frequency_collator()->Frequency(j) + 1; |
| + } |
| + } |
| + // We use the probability of skipping times the distance we are skipping to |
| + // judge the effectiveness of this. Actually we have a cut-off: By |
| + // dividing by 2 we switch off the skipping if the probability of skipping |
| + // is less than 50%. This is because the multibyte mask-and-compare |
| + // skipping in quickcheck is more likely to do well on this case. |
| + bool in_quickcheck_range = ((i - remembered_from < 4) || |
| + (compiler_->ascii() ? remembered_from <= 4 : remembered_from <= 2)); |
| + // Called 'probability' but it is only a rough estimate and can actually |
| + // be outside the 0-kSize range. |
| + intptr_t probability = |
| + (in_quickcheck_range ? kSize / 2 : kSize) - frequency; |
| + intptr_t points = (i - remembered_from) * probability; |
| + if (points > biggest_points) { |
| + *from = remembered_from; |
| + *to = i - 1; |
| + biggest_points = points; |
| + } |
| + } |
| + return biggest_points; |
| +} |
| + |
| + |
| +// See comment above on the implementation of GetSkipTable. |
| +bool BoyerMooreLookahead::EmitSkipInstructions(RegExpMacroAssembler* masm) { |
| + const intptr_t kSize = RegExpMacroAssembler::kTableSize; |
| + |
| + intptr_t min_lookahead = 0; |
| + intptr_t max_lookahead = 0; |
| + |
| + if (!FindWorthwhileInterval(&min_lookahead, &max_lookahead)) return false; |
| + |
| + bool found_single_character = false; |
| + intptr_t single_character = 0; |
| + for (intptr_t i = max_lookahead; i >= min_lookahead; i--) { |
| + BoyerMoorePositionInfo* map = bitmaps_->At(i); |
| + if (map->map_count() > 1 || |
| + (found_single_character && map->map_count() != 0)) { |
| + found_single_character = false; |
| + break; |
| + } |
| + for (intptr_t j = 0; j < kSize; j++) { |
| + if (map->at(j)) { |
| + found_single_character = true; |
| + single_character = j; |
| + break; |
| + } |
| + } |
| + } |
| + |
| + intptr_t lookahead_width = max_lookahead + 1 - min_lookahead; |
| + |
| + if (found_single_character && lookahead_width == 1 && max_lookahead < 3) { |
| + // The mask-compare can probably handle this better. |
| + return false; |
| + } |
| + |
| + if (found_single_character) { |
| + BlockLabel cont, again; |
| + masm->BindBlock(&again); |
| + masm->LoadCurrentCharacter(max_lookahead, &cont, true); |
| + if (max_char_ > kSize) { |
| + masm->CheckCharacterAfterAnd(single_character, |
| + RegExpMacroAssembler::kTableMask, |
| + &cont); |
| + } else { |
| + masm->CheckCharacter(single_character, &cont); |
| + } |
| + masm->AdvanceCurrentPosition(lookahead_width); |
| + masm->GoTo(&again); |
| + masm->BindBlock(&cont); |
| + return true; |
| + } |
| - return RegExpEngine::CompilationResult(""); |
| + TypedData& boolean_skip_table = TypedData::ZoneHandle( |
|
Florian Schneider
2014/10/01 17:04:14
const TypedData&
jgruber1
2014/10/03 18:59:52
Done.
|
| + compiler_->isolate(), |
| + TypedData::New(kTypedDataUint8ArrayCid, kSize, Heap::kOld)); |
| + intptr_t skip_distance = GetSkipTable( |
| + min_lookahead, max_lookahead, &boolean_skip_table); |
| + ASSERT(skip_distance != 0); |
| + |
| + BlockLabel cont, again; |
| + |
| + masm->BindBlock(&again); |
| + masm->LoadCurrentCharacter(max_lookahead, &cont, true); |
| + masm->CheckBitInTable(boolean_skip_table, &cont); |
| + masm->AdvanceCurrentPosition(skip_distance); |
| + masm->GoTo(&again); |
| + masm->BindBlock(&cont); |
| + |
| + return true; |
| } |
| @@ -1987,7 +4715,7 @@ void DotPrinter::PrintAttributes(RegExpNode* that) { |
| printer.PrintBit("NI", info->follows_newline_interest); |
| printer.PrintBit("WI", info->follows_word_interest); |
| printer.PrintBit("SI", info->follows_start_interest); |
| - Label* label = that->label(); |
| + BlockLabel* label = that->label(); |
| if (label->IsBound()) |
| printer.PrintPositive("@", label->Position()); |
| OS::Print("}\"];\n" |