regexp-macro-assembler-mips.cc 46.4 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#if V8_TARGET_ARCH_MIPS
6

7 8
#include "src/regexp/mips/regexp-macro-assembler-mips.h"

9 10
#include "src/codegen/assembler-inl.h"
#include "src/codegen/macro-assembler.h"
11
#include "src/logging/log.h"
12
#include "src/objects/objects-inl.h"
13 14
#include "src/regexp/regexp-macro-assembler.h"
#include "src/regexp/regexp-stack.h"
15
#include "src/snapshot/embedded/embedded-data.h"
16
#include "src/strings/unicode.h"
17

18 19 20 21 22
namespace v8 {
namespace internal {

/*
 * This assembler uses the following register assignment convention
23 24
 * - t7 : Temporarily stores the index of capture start after a matching pass
 *        for a global regexp.
25
 * - t1 : Pointer to current Code object including heap object tag.
26 27 28 29
 * - t2 : Current position in input, as negative offset from end of string.
 *        Please notice that this is the byte offset, not the character offset!
 * - t3 : Currently loaded character. Must be loaded using
 *        LoadCurrentCharacter before using any of the dispatch methods.
30
 * - t4 : Points to tip of backtrack stack
31 32 33 34
 * - t5 : Unused.
 * - t6 : End of input (points to byte after last character in input).
 * - fp : Frame pointer. Used to access arguments, local variables and
 *         RegExp registers.
35
 * - sp : Points to tip of C stack.
36 37 38
 *
 * The remaining registers are free for computations.
 * Each call to a public method should retain this convention.
39
 *
40
 * The stack will have the following structure:
41
 *
42 43
 *  - fp[60]  Isolate* isolate   (address of the current isolate)
 *  - fp[56]  direct_call  (if 1, direct call from JavaScript code,
44
 *                          if 0, call through the runtime system).
45
 *  - fp[52]  stack_area_base (High end of the memory area to use as
46
 *                             backtracking stack).
47 48
 *  - fp[48]  capture array size (may fit multiple sets of matches)
 *  - fp[44]  int* capture_array (int[num_saved_registers_], for output).
49
 *  --- sp when called ---
50 51
 *  - fp[40]  return address      (lr).
 *  - fp[36]  old frame pointer   (r11).
52 53
 *  - fp[0..32]  backup of registers s0..s7.
 *  --- frame pointer ----
54 55
 *  - fp[-4]  end of input       (address of end of string).
 *  - fp[-8]  start of input     (address of first character in string).
56 57
 *  - fp[-12] start index        (character index of start).
 *  - fp[-16] void* input_string (location of a handle containing the string).
58 59
 *  - fp[-20] success counter    (only for global regexps to count matches).
 *  - fp[-24] Offset of location before start of input (effectively character
60 61
 *            position -1). Used to initialize capture registers to a
 *            non-position.
62
 *  - fp[-28] At start (if 1, we are starting at the start of the
63
 *    string, otherwise 0)
64
 *  - fp[-32] register 0         (Only positions must be stored in the first
65 66 67 68
 *  -         register 1          num_saved_registers_ registers)
 *  -         ...
 *  -         register num_registers-1
 *  --- sp ---
69 70 71 72 73 74
 *
 * The first num_saved_registers_ registers are initialized to point to
 * "character -1" in the string (i.e., char_size() bytes before the first
 * character of the string). The remaining registers start out as garbage.
 *
 * The data up to the return address must be placed there by the calling
75 76
 * code and the remaining arguments are passed in registers, e.g. by calling the
 * code entry as cast to a function with the signature:
77
 * int (*match)(String input_string,
78 79 80 81
 *              int start_index,
 *              Address start,
 *              Address end,
 *              int* capture_output_array,
82
 *              int num_capture_registers,
83
 *              byte* stack_area_base,
84 85
 *              bool direct_call = false,
 *              Isolate* isolate);
86
 * The call is performed by NativeRegExpMacroAssembler::Execute()
87
 * (in regexp-macro-assembler.cc) via the GeneratedCode wrapper.
88 89 90 91
 */

#define __ ACCESS_MASM(masm_)

92 93
const int RegExpMacroAssemblerMIPS::kRegExpCodeSize;

94 95 96 97
RegExpMacroAssemblerMIPS::RegExpMacroAssemblerMIPS(Isolate* isolate, Zone* zone,
                                                   Mode mode,
                                                   int registers_to_save)
    : NativeRegExpMacroAssembler(isolate, zone),
98 99
      masm_(new MacroAssembler(isolate, CodeObjectRequired::kYes,
                               NewAssemblerBuffer(kRegExpCodeSize))),
100 101 102 103 104 105 106
      mode_(mode),
      num_registers_(registers_to_save),
      num_saved_registers_(registers_to_save),
      entry_label_(),
      start_label_(),
      success_label_(),
      backtrack_label_(),
107 108
      exit_label_(),
      internal_failure_label_() {
109 110
  masm_->set_root_array_available(false);

111
  DCHECK_EQ(0, registers_to_save % 2);
112
  __ jmp(&entry_label_);   // We'll write the entry code later.
113 114 115 116 117
  // If the code gets too big or corrupted, an internal exception will be
  // raised, and we will exit right away.
  __ bind(&internal_failure_label_);
  __ li(v0, Operand(FAILURE));
  __ Ret();
118 119 120 121 122 123 124 125 126 127 128 129 130
  __ bind(&start_label_);  // And then continue from here.
}

RegExpMacroAssemblerMIPS::~RegExpMacroAssemblerMIPS() {
  delete masm_;
  // Unuse labels in case we throw away the assembler without calling GetCode.
  entry_label_.Unuse();
  start_label_.Unuse();
  success_label_.Unuse();
  backtrack_label_.Unuse();
  exit_label_.Unuse();
  check_preempt_label_.Unuse();
  stack_overflow_label_.Unuse();
131
  internal_failure_label_.Unuse();
132 133 134 135 136 137 138 139 140
}


int RegExpMacroAssemblerMIPS::stack_limit_slack()  {
  return RegExpStack::kStackLimitSlack;
}


void RegExpMacroAssemblerMIPS::AdvanceCurrentPosition(int by) {
141 142
  if (by != 0) {
    __ Addu(current_input_offset(),
143
            current_input_offset(), Operand(by * char_size()));
144
  }
145 146 147 148
}


void RegExpMacroAssemblerMIPS::AdvanceRegister(int reg, int by) {
149 150
  DCHECK_LE(0, reg);
  DCHECK_GT(num_registers_, reg);
151 152 153 154 155
  if (by != 0) {
    __ lw(a0, register_location(reg));
    __ Addu(a0, a0, Operand(by));
    __ sw(a0, register_location(reg));
  }
156 157 158 159
}


void RegExpMacroAssemblerMIPS::Backtrack() {
160
  CheckPreemption();
161 162 163 164 165 166 167 168 169 170 171 172
  if (has_backtrack_limit()) {
    Label next;
    __ Lw(a0, MemOperand(frame_pointer(), kBacktrackCount));
    __ Addu(a0, a0, Operand(1));
    __ Sw(a0, MemOperand(frame_pointer(), kBacktrackCount));
    __ Branch(&next, ne, a0, Operand(backtrack_limit()));

    // Exceeded limits are treated as a failed match.
    Fail();

    __ bind(&next);
  }
173
  // Pop Code offset from backtrack stack, add Code and jump to location.
174 175
  Pop(a0);
  __ Addu(a0, a0, code_pointer());
176
  __ Jump(a0);
177 178 179 180
}


void RegExpMacroAssemblerMIPS::Bind(Label* label) {
181
  __ bind(label);
182 183 184 185
}


void RegExpMacroAssemblerMIPS::CheckCharacter(uint32_t c, Label* on_equal) {
186
  BranchOrBacktrack(on_equal, eq, current_character(), Operand(c));
187 188 189 190
}


void RegExpMacroAssemblerMIPS::CheckCharacterGT(uc16 limit, Label* on_greater) {
191
  BranchOrBacktrack(on_greater, gt, current_character(), Operand(limit));
192 193 194
}


195
void RegExpMacroAssemblerMIPS::CheckAtStart(int cp_offset, Label* on_at_start) {
196
  __ lw(a1, MemOperand(frame_pointer(), kStringStartMinusOne));
197 198
  __ Addu(a0, current_input_offset(),
          Operand(-char_size() + cp_offset * char_size()));
199
  BranchOrBacktrack(on_at_start, eq, a0, Operand(a1));
200 201 202
}


203 204 205 206 207
void RegExpMacroAssemblerMIPS::CheckNotAtStart(int cp_offset,
                                               Label* on_not_at_start) {
  __ lw(a1, MemOperand(frame_pointer(), kStringStartMinusOne));
  __ Addu(a0, current_input_offset(),
          Operand(-char_size() + cp_offset * char_size()));
208
  BranchOrBacktrack(on_not_at_start, ne, a0, Operand(a1));
209 210 211 212
}


void RegExpMacroAssemblerMIPS::CheckCharacterLT(uc16 limit, Label* on_less) {
213
  BranchOrBacktrack(on_less, lt, current_character(), Operand(limit));
214 215 216 217
}


void RegExpMacroAssemblerMIPS::CheckGreedyLoop(Label* on_equal) {
218 219 220 221 222 223 224 225
  Label backtrack_non_equal;
  __ lw(a0, MemOperand(backtrack_stackpointer(), 0));
  __ Branch(&backtrack_non_equal, ne, current_input_offset(), Operand(a0));
  __ Addu(backtrack_stackpointer(),
          backtrack_stackpointer(),
          Operand(kPointerSize));
  __ bind(&backtrack_non_equal);
  BranchOrBacktrack(on_equal, eq, current_input_offset(), Operand(a0));
226 227 228
}

void RegExpMacroAssemblerMIPS::CheckNotBackReferenceIgnoreCase(
229
    int start_reg, bool read_backward, Label* on_no_match) {
230 231 232 233 234
  Label fallthrough;
  __ lw(a0, register_location(start_reg));  // Index of start of capture.
  __ lw(a1, register_location(start_reg + 1));  // Index of end of capture.
  __ Subu(a1, a1, a0);  // Length of capture.

235 236 237
  // At this point, the capture registers are either both set or both cleared.
  // If the capture length is zero, then the capture is either empty or cleared.
  // Fall through in both cases.
238 239
  __ Branch(&fallthrough, eq, a1, Operand(zero_reg));

240 241 242 243 244 245 246 247 248
  if (read_backward) {
    __ lw(t0, MemOperand(frame_pointer(), kStringStartMinusOne));
    __ Addu(t0, t0, a1);
    BranchOrBacktrack(on_no_match, le, current_input_offset(), Operand(t0));
  } else {
    __ Addu(t5, a1, current_input_offset());
    // Check that there are enough characters left in the input.
    BranchOrBacktrack(on_no_match, gt, t5, Operand(zero_reg));
  }
249

250
  if (mode_ == LATIN1) {
251 252 253 254 255 256 257 258
    Label success;
    Label fail;
    Label loop_check;

    // a0 - offset of start of capture.
    // a1 - length of capture.
    __ Addu(a0, a0, Operand(end_of_input_address()));
    __ Addu(a2, end_of_input_address(), Operand(current_input_offset()));
259 260 261
    if (read_backward) {
      __ Subu(a2, a2, Operand(a1));
    }
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    __ Addu(a1, a0, Operand(a1));

    // a0 - Address of start of capture.
    // a1 - Address of end of capture.
    // a2 - Address of current input position.

    Label loop;
    __ bind(&loop);
    __ lbu(a3, MemOperand(a0, 0));
    __ addiu(a0, a0, char_size());
    __ lbu(t0, MemOperand(a2, 0));
    __ addiu(a2, a2, char_size());

    __ Branch(&loop_check, eq, t0, Operand(a3));

    // Mismatch, try case-insensitive match (converting letters to lower-case).
    __ Or(a3, a3, Operand(0x20));  // Convert capture character to lower-case.
    __ Or(t0, t0, Operand(0x20));  // Also convert input character.
    __ Branch(&fail, ne, t0, Operand(a3));
    __ Subu(a3, a3, Operand('a'));
282 283 284 285 286 287 288
    __ Branch(&loop_check, ls, a3, Operand('z' - 'a'));
    // Latin-1: Check for values in range [224,254] but not 247.
    __ Subu(a3, a3, Operand(224 - 'a'));
    // Weren't Latin-1 letters.
    __ Branch(&fail, hi, a3, Operand(254 - 224));
    // Check for 247.
    __ Branch(&fail, eq, a3, Operand(247 - 224));
289 290 291 292 293 294 295 296 297 298 299

    __ bind(&loop_check);
    __ Branch(&loop, lt, a0, Operand(a1));
    __ jmp(&success);

    __ bind(&fail);
    GoTo(on_no_match);

    __ bind(&success);
    // Compute new value of character position after the matched part.
    __ Subu(current_input_offset(), a2, end_of_input_address());
300 301 302 303 304 305
    if (read_backward) {
      __ lw(t0, register_location(start_reg));  // Index of start of capture.
      __ lw(t5, register_location(start_reg + 1));  // Index of end of capture.
      __ Addu(current_input_offset(), current_input_offset(), Operand(t0));
      __ Subu(current_input_offset(), current_input_offset(), Operand(t5));
    }
306
  } else {
307
    DCHECK_EQ(UC16, mode_);
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    // Put regexp engine registers on stack.
    RegList regexp_registers_to_retain = current_input_offset().bit() |
        current_character().bit() | backtrack_stackpointer().bit();
    __ MultiPush(regexp_registers_to_retain);

    int argument_count = 4;
    __ PrepareCallCFunction(argument_count, a2);

    // a0 - offset of start of capture.
    // a1 - length of capture.

    // Put arguments into arguments registers.
    // Parameters are
    //   a0: Address byte_offset1 - Address captured substring's start.
    //   a1: Address byte_offset2 - Address of current character position.
    //   a2: size_t byte_length - length of capture in bytes(!).
324
    //   a3: Isolate* isolate.
325 326 327 328 329 330 331 332 333

    // Address of start of capture.
    __ Addu(a0, a0, Operand(end_of_input_address()));
    // Length of capture.
    __ mov(a2, a1);
    // Save length in callee-save register for use on return.
    __ mov(s3, a1);
    // Address of current input position.
    __ Addu(a1, current_input_offset(), Operand(end_of_input_address()));
334 335 336
    if (read_backward) {
      __ Subu(a1, a1, Operand(s3));
    }
337
    // Isolate.
338
    __ li(a3, Operand(ExternalReference::isolate_address(masm_->isolate())));
339

340 341 342 343 344 345
    {
      AllowExternalCallThatCantCauseGC scope(masm_);
      ExternalReference function =
          ExternalReference::re_case_insensitive_compare_uc16(masm_->isolate());
      __ CallCFunction(function, argument_count);
    }
346 347 348

    // Restore regexp engine registers.
    __ MultiPop(regexp_registers_to_retain);
349
    __ li(code_pointer(), Operand(masm_->CodeObject()), CONSTANT_SIZE);
350 351 352 353
    __ lw(end_of_input_address(), MemOperand(frame_pointer(), kInputEnd));

    // Check if function returned non-zero for success or zero for failure.
    BranchOrBacktrack(on_no_match, eq, v0, Operand(zero_reg));
354 355 356 357 358 359
    // On success, advance position by length of capture.
    if (read_backward) {
      __ Subu(current_input_offset(), current_input_offset(), Operand(s3));
    } else {
      __ Addu(current_input_offset(), current_input_offset(), Operand(s3));
    }
360 361 362
  }

  __ bind(&fallthrough);
363 364
}

365 366 367
void RegExpMacroAssemblerMIPS::CheckNotBackReference(int start_reg,
                                                     bool read_backward,
                                                     Label* on_no_match) {
368 369 370 371 372 373 374
  Label fallthrough;

  // Find length of back-referenced capture.
  __ lw(a0, register_location(start_reg));
  __ lw(a1, register_location(start_reg + 1));
  __ Subu(a1, a1, a0);  // Length to check.

375 376 377 378 379 380 381 382 383 384 385 386 387 388
  // At this point, the capture registers are either both set or both cleared.
  // If the capture length is zero, then the capture is either empty or cleared.
  // Fall through in both cases.
  __ Branch(&fallthrough, le, a1, Operand(zero_reg));

  if (read_backward) {
    __ lw(t0, MemOperand(frame_pointer(), kStringStartMinusOne));
    __ Addu(t0, t0, a1);
    BranchOrBacktrack(on_no_match, le, current_input_offset(), Operand(t0));
  } else {
    __ Addu(t5, a1, current_input_offset());
    // Check that there are enough characters left in the input.
    BranchOrBacktrack(on_no_match, gt, t5, Operand(zero_reg));
  }
389

390 391
  // a0 - offset of start of capture.
  // a1 - length of capture.
392 393
  __ Addu(a0, a0, Operand(end_of_input_address()));
  __ Addu(a2, end_of_input_address(), Operand(current_input_offset()));
394 395 396 397 398 399 400 401 402
  if (read_backward) {
    __ Subu(a2, a2, Operand(a1));
  }
  __ Addu(a1, a0, Operand(a1));

  // a0 - Address of start of capture.
  // a1 - Address of end of capture.
  // a2 - Address of current input position.

403 404 405

  Label loop;
  __ bind(&loop);
406
  if (mode_ == LATIN1) {
407 408 409 410 411
    __ lbu(a3, MemOperand(a0, 0));
    __ addiu(a0, a0, char_size());
    __ lbu(t0, MemOperand(a2, 0));
    __ addiu(a2, a2, char_size());
  } else {
412
    DCHECK(mode_ == UC16);
413 414 415 416 417 418 419 420 421 422
    __ lhu(a3, MemOperand(a0, 0));
    __ addiu(a0, a0, char_size());
    __ lhu(t0, MemOperand(a2, 0));
    __ addiu(a2, a2, char_size());
  }
  BranchOrBacktrack(on_no_match, ne, a3, Operand(t0));
  __ Branch(&loop, lt, a0, Operand(a1));

  // Move current character position to position after match.
  __ Subu(current_input_offset(), a2, end_of_input_address());
423 424 425 426 427 428
  if (read_backward) {
    __ lw(t0, register_location(start_reg));      // Index of start of capture.
    __ lw(t5, register_location(start_reg + 1));  // Index of end of capture.
    __ Addu(current_input_offset(), current_input_offset(), Operand(t0));
    __ Subu(current_input_offset(), current_input_offset(), Operand(t5));
  }
429
  __ bind(&fallthrough);
430 431 432 433
}


void RegExpMacroAssemblerMIPS::CheckNotCharacter(uint32_t c,
434
                                                 Label* on_not_equal) {
435
  BranchOrBacktrack(on_not_equal, ne, current_character(), Operand(c));
436 437 438 439
}


void RegExpMacroAssemblerMIPS::CheckCharacterAfterAnd(uint32_t c,
440 441
                                                      uint32_t mask,
                                                      Label* on_equal) {
442
  __ And(a0, current_character(), Operand(mask));
443 444
  Operand rhs = (c == 0) ? Operand(zero_reg) : Operand(c);
  BranchOrBacktrack(on_equal, eq, a0, rhs);
445 446 447 448
}


void RegExpMacroAssemblerMIPS::CheckNotCharacterAfterAnd(uint32_t c,
449 450
                                                         uint32_t mask,
                                                         Label* on_not_equal) {
451
  __ And(a0, current_character(), Operand(mask));
452 453
  Operand rhs = (c == 0) ? Operand(zero_reg) : Operand(c);
  BranchOrBacktrack(on_not_equal, ne, a0, rhs);
454 455 456 457 458 459 460 461
}


void RegExpMacroAssemblerMIPS::CheckNotCharacterAfterMinusAnd(
    uc16 c,
    uc16 minus,
    uc16 mask,
    Label* on_not_equal) {
462
  DCHECK_GT(String::kMaxUtf16CodeUnit, minus);
463 464 465
  __ Subu(a0, current_character(), Operand(minus));
  __ And(a0, a0, Operand(mask));
  BranchOrBacktrack(on_not_equal, ne, a0, Operand(c));
466 467 468
}


469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
void RegExpMacroAssemblerMIPS::CheckCharacterInRange(
    uc16 from,
    uc16 to,
    Label* on_in_range) {
  __ Subu(a0, current_character(), Operand(from));
  // Unsigned lower-or-same condition.
  BranchOrBacktrack(on_in_range, ls, a0, Operand(to - from));
}


void RegExpMacroAssemblerMIPS::CheckCharacterNotInRange(
    uc16 from,
    uc16 to,
    Label* on_not_in_range) {
  __ Subu(a0, current_character(), Operand(from));
  // Unsigned higher condition.
  BranchOrBacktrack(on_not_in_range, hi, a0, Operand(to - from));
}


void RegExpMacroAssemblerMIPS::CheckBitInTable(
    Handle<ByteArray> table,
    Label* on_bit_set) {
  __ li(a0, Operand(table));
493
  if (mode_ != LATIN1 || kTableMask != String::kMaxOneByteCharCode) {
494 495 496 497 498 499
    __ And(a1, current_character(), Operand(kTableSize - 1));
    __ Addu(a0, a0, a1);
  } else {
    __ Addu(a0, a0, current_character());
  }

500
  __ lbu(a0, FieldMemOperand(a0, ByteArray::kHeaderSize));
501 502 503 504
  BranchOrBacktrack(on_bit_set, ne, a0, Operand(zero_reg));
}


505
bool RegExpMacroAssemblerMIPS::CheckSpecialCharacterClass(uc16 type,
506
                                                          Label* on_no_match) {
507 508 509 510 511
  // Range checks (c in min..max) are generally implemented by an unsigned
  // (c - min) <= (max - min) check.
  switch (type) {
  case 's':
    // Match space-characters.
512
    if (mode_ == LATIN1) {
513
      // One byte space characters are '\t'..'\r', ' ' and \u00a0.
514 515
      Label success;
      __ Branch(&success, eq, current_character(), Operand(' '));
516
      // Check range 0x09..0x0D.
517
      __ Subu(a0, current_character(), Operand('\t'));
518 519
      __ Branch(&success, ls, a0, Operand('\r' - '\t'));
      // \u00a0 (NBSP).
520
      BranchOrBacktrack(on_no_match, ne, a0, Operand(0x00A0 - '\t'));
521 522 523 524 525
      __ bind(&success);
      return true;
    }
    return false;
  case 'S':
526
    // The emitted code for generic character classes is good enough.
527 528
    return false;
  case 'd':
529
    // Match Latin1 digits ('0'..'9').
530 531 532 533
    __ Subu(a0, current_character(), Operand('0'));
    BranchOrBacktrack(on_no_match, hi, a0, Operand('9' - '0'));
    return true;
  case 'D':
534
    // Match non Latin1-digits.
535 536 537 538
    __ Subu(a0, current_character(), Operand('0'));
    BranchOrBacktrack(on_no_match, ls, a0, Operand('9' - '0'));
    return true;
  case '.': {
539
    // Match non-newlines (not 0x0A('\n'), 0x0D('\r'), 0x2028 and 0x2029).
540
    __ Xor(a0, current_character(), Operand(0x01));
541 542 543
    // See if current character is '\n'^1 or '\r'^1, i.e., 0x0B or 0x0C.
    __ Subu(a0, a0, Operand(0x0B));
    BranchOrBacktrack(on_no_match, ls, a0, Operand(0x0C - 0x0B));
544 545
    if (mode_ == UC16) {
      // Compare original value to 0x2028 and 0x2029, using the already
546 547 548
      // computed (current_char ^ 0x01 - 0x0B). I.e., check for
      // 0x201D (0x2028 - 0x0B) or 0x201E.
      __ Subu(a0, a0, Operand(0x2028 - 0x0B));
549 550 551 552 553
      BranchOrBacktrack(on_no_match, ls, a0, Operand(1));
    }
    return true;
  }
  case 'n': {
554
    // Match newlines (0x0A('\n'), 0x0D('\r'), 0x2028 and 0x2029).
555
    __ Xor(a0, current_character(), Operand(0x01));
556 557
    // See if current character is '\n'^1 or '\r'^1, i.e., 0x0B or 0x0C.
    __ Subu(a0, a0, Operand(0x0B));
558
    if (mode_ == LATIN1) {
559
      BranchOrBacktrack(on_no_match, hi, a0, Operand(0x0C - 0x0B));
560 561
    } else {
      Label done;
562
      BranchOrBacktrack(&done, ls, a0, Operand(0x0C - 0x0B));
563
      // Compare original value to 0x2028 and 0x2029, using the already
564 565 566
      // computed (current_char ^ 0x01 - 0x0B). I.e., check for
      // 0x201D (0x2028 - 0x0B) or 0x201E.
      __ Subu(a0, a0, Operand(0x2028 - 0x0B));
567 568 569 570 571 572
      BranchOrBacktrack(on_no_match, hi, a0, Operand(1));
      __ bind(&done);
    }
    return true;
  }
  case 'w': {
573 574
    if (mode_ != LATIN1) {
      // Table is 256 entries, so all Latin1 characters can be tested.
575 576
      BranchOrBacktrack(on_no_match, hi, current_character(), Operand('z'));
    }
577
    ExternalReference map = ExternalReference::re_word_character_map(isolate());
578 579 580 581 582 583 584 585
    __ li(a0, Operand(map));
    __ Addu(a0, a0, current_character());
    __ lbu(a0, MemOperand(a0, 0));
    BranchOrBacktrack(on_no_match, eq, a0, Operand(zero_reg));
    return true;
  }
  case 'W': {
    Label done;
586 587
    if (mode_ != LATIN1) {
      // Table is 256 entries, so all Latin1 characters can be tested.
588 589
      __ Branch(&done, hi, current_character(), Operand('z'));
    }
590
    ExternalReference map = ExternalReference::re_word_character_map(isolate());
591 592 593 594
    __ li(a0, Operand(map));
    __ Addu(a0, a0, current_character());
    __ lbu(a0, MemOperand(a0, 0));
    BranchOrBacktrack(on_no_match, ne, a0, Operand(zero_reg));
595
    if (mode_ != LATIN1) {
596 597 598 599 600 601 602 603 604 605 606
      __ bind(&done);
    }
    return true;
  }
  case '*':
    // Match any character.
    return true;
  // No custom implementation (yet): s(UC16), S(UC16).
  default:
    return false;
  }
607 608 609 610
}


void RegExpMacroAssemblerMIPS::Fail() {
611 612
  __ li(v0, Operand(FAILURE));
  __ jmp(&exit_label_);
613 614 615
}


616
Handle<HeapObject> RegExpMacroAssemblerMIPS::GetCode(Handle<String> source) {
617
  Label return_v0;
618 619 620 621 622 623 624 625 626 627 628
  if (masm_->has_exception()) {
    // If the code gets corrupted due to long regular expressions and lack of
    // space on trampolines, an internal exception flag is set. If this case
    // is detected, we will jump into exit sequence right away.
    __ bind_to(&entry_label_, internal_failure_label_.pos());
  } else {
    // Finalize code - write the entry point code now we know how many
    // registers we need.

    // Entry code:
    __ bind(&entry_label_);
629 630 631 632 633 634

    // Tell the system that we have a stack frame.  Because the type is MANUAL,
    // no is generated.
    FrameScope scope(masm_, StackFrame::MANUAL);

    // Actually emit code to start a new stack frame.
635 636 637 638 639 640 641 642 643 644 645 646
    // Push arguments
    // Save callee-save registers.
    // Start new stack frame.
    // Store link register in existing stack-cell.
    // Order here should correspond to order of offset constants in header file.
    RegList registers_to_retain = s0.bit() | s1.bit() | s2.bit() |
        s3.bit() | s4.bit() | s5.bit() | s6.bit() | s7.bit() | fp.bit();
    RegList argument_registers = a0.bit() | a1.bit() | a2.bit() | a3.bit();
    __ MultiPush(argument_registers | registers_to_retain | ra.bit());
    // Set frame pointer in space for it if this is not a direct call
    // from generated code.
    __ Addu(frame_pointer(), sp, Operand(4 * kPointerSize));
647 648

    STATIC_ASSERT(kSuccessfulCaptures == kInputString - kSystemPointerSize);
649 650
    __ mov(a0, zero_reg);
    __ push(a0);  // Make room for success counter and initialize it to 0.
651 652
    STATIC_ASSERT(kStringStartMinusOne ==
                  kSuccessfulCaptures - kSystemPointerSize);
653
    __ push(a0);  // Make room for "string start - 1" constant.
654 655
    STATIC_ASSERT(kBacktrackCount == kStringStartMinusOne - kSystemPointerSize);
    __ push(a0);
656 657 658 659 660 661

    // Check if we have space on the stack for registers.
    Label stack_limit_hit;
    Label stack_ok;

    ExternalReference stack_limit =
662
        ExternalReference::address_of_jslimit(masm_->isolate());
663 664 665 666 667 668 669 670 671 672 673
    __ li(a0, Operand(stack_limit));
    __ lw(a0, MemOperand(a0));
    __ Subu(a0, sp, a0);
    // Handle it if the stack pointer is already below the stack limit.
    __ Branch(&stack_limit_hit, le, a0, Operand(zero_reg));
    // Check if there is room for the variable number of registers above
    // the stack limit.
    __ Branch(&stack_ok, hs, a0, Operand(num_registers_ * kPointerSize));
    // Exit with OutOfMemory exception. There is not enough space on the stack
    // for our working registers.
    __ li(v0, Operand(EXCEPTION));
674
    __ jmp(&return_v0);
675 676 677 678

    __ bind(&stack_limit_hit);
    CallCheckStackGuardState(a0);
    // If returned value is non-zero, we exit with the returned value as result.
679
    __ Branch(&return_v0, ne, v0, Operand(zero_reg));
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697

    __ bind(&stack_ok);
    // Allocate space on stack for registers.
    __ Subu(sp, sp, Operand(num_registers_ * kPointerSize));
    // Load string end.
    __ lw(end_of_input_address(), MemOperand(frame_pointer(), kInputEnd));
    // Load input start.
    __ lw(a0, MemOperand(frame_pointer(), kInputStart));
    // Find negative length (offset of start relative to end).
    __ Subu(current_input_offset(), a0, end_of_input_address());
    // Set a0 to address of char before start of the input string
    // (effectively string position -1).
    __ lw(a1, MemOperand(frame_pointer(), kStartIndex));
    __ Subu(a0, current_input_offset(), Operand(char_size()));
    __ sll(t5, a1, (mode_ == UC16) ? 1 : 0);
    __ Subu(a0, a0, t5);
    // Store this value in a local variable, for use when clearing
    // position registers.
698
    __ sw(a0, MemOperand(frame_pointer(), kStringStartMinusOne));
699

700 701 702 703 704 705 706 707 708 709 710 711 712 713
    // Initialize code pointer register
    __ li(code_pointer(), Operand(masm_->CodeObject()), CONSTANT_SIZE);

    Label load_char_start_regexp, start_regexp;
    // Load newline if index is at start, previous character otherwise.
    __ Branch(&load_char_start_regexp, ne, a1, Operand(zero_reg));
    __ li(current_character(), Operand('\n'));
    __ jmp(&start_regexp);

    // Global regexp restarts matching here.
    __ bind(&load_char_start_regexp);
    // Load previous char as initial value of current character register.
    LoadCurrentCharacterUnchecked(-1, 1);
    __ bind(&start_regexp);
714

715
    // Initialize on-stack registers.
716 717
    if (num_saved_registers_ > 0) {  // Always is, if generated from a regexp.
      // Fill saved registers with initial value = start offset - 1.
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
      if (num_saved_registers_ > 8) {
        // Address of register 0.
        __ Addu(a1, frame_pointer(), Operand(kRegisterZero));
        __ li(a2, Operand(num_saved_registers_));
        Label init_loop;
        __ bind(&init_loop);
        __ sw(a0, MemOperand(a1));
        __ Addu(a1, a1, Operand(-kPointerSize));
        __ Subu(a2, a2, Operand(1));
        __ Branch(&init_loop, ne, a2, Operand(zero_reg));
      } else {
        for (int i = 0; i < num_saved_registers_; i++) {
          __ sw(a0, register_location(i));
        }
      }
733 734 735 736
    }

    // Initialize backtrack stack pointer.
    __ lw(backtrack_stackpointer(), MemOperand(frame_pointer(), kStackHighEnd));
737

738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
    __ jmp(&start_label_);


    // Exit code:
    if (success_label_.is_linked()) {
      // Save captures when successful.
      __ bind(&success_label_);
      if (num_saved_registers_ > 0) {
        // Copy captures to output.
        __ lw(a1, MemOperand(frame_pointer(), kInputStart));
        __ lw(a0, MemOperand(frame_pointer(), kRegisterOutput));
        __ lw(a2, MemOperand(frame_pointer(), kStartIndex));
        __ Subu(a1, end_of_input_address(), a1);
        // a1 is length of input in bytes.
        if (mode_ == UC16) {
          __ srl(a1, a1, 1);
        }
        // a1 is length of input in characters.
        __ Addu(a1, a1, Operand(a2));
        // a1 is length of string in characters.

759
        DCHECK_EQ(0, num_saved_registers_ % 2);
760 761 762 763 764 765
        // Always an even number of capture registers. This allows us to
        // unroll the loop once to add an operation between a load of a register
        // and the following use of that register.
        for (int i = 0; i < num_saved_registers_; i += 2) {
          __ lw(a2, register_location(i));
          __ lw(a3, register_location(i + 1));
766
          if (i == 0 && global_with_zero_length_check()) {
767 768 769
            // Keep capture start in a4 for the zero-length check later.
            __ mov(t7, a2);
          }
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
          if (mode_ == UC16) {
            __ sra(a2, a2, 1);
            __ Addu(a2, a2, a1);
            __ sra(a3, a3, 1);
            __ Addu(a3, a3, a1);
          } else {
            __ Addu(a2, a1, Operand(a2));
            __ Addu(a3, a1, Operand(a3));
          }
          __ sw(a2, MemOperand(a0));
          __ Addu(a0, a0, kPointerSize);
          __ sw(a3, MemOperand(a0));
          __ Addu(a0, a0, kPointerSize);
        }
      }
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806

      if (global()) {
        // Restart matching if the regular expression is flagged as global.
        __ lw(a0, MemOperand(frame_pointer(), kSuccessfulCaptures));
        __ lw(a1, MemOperand(frame_pointer(), kNumOutputRegisters));
        __ lw(a2, MemOperand(frame_pointer(), kRegisterOutput));
        // Increment success counter.
        __ Addu(a0, a0, 1);
        __ sw(a0, MemOperand(frame_pointer(), kSuccessfulCaptures));
        // Capture results have been stored, so the number of remaining global
        // output registers is reduced by the number of stored captures.
        __ Subu(a1, a1, num_saved_registers_);
        // Check whether we have enough room for another set of capture results.
        __ mov(v0, a0);
        __ Branch(&return_v0, lt, a1, Operand(num_saved_registers_));

        __ sw(a1, MemOperand(frame_pointer(), kNumOutputRegisters));
        // Advance the location for output.
        __ Addu(a2, a2, num_saved_registers_ * kPointerSize);
        __ sw(a2, MemOperand(frame_pointer(), kRegisterOutput));

        // Prepare a0 to initialize registers with its value in the next run.
807
        __ lw(a0, MemOperand(frame_pointer(), kStringStartMinusOne));
808 809 810 811 812 813 814 815

        if (global_with_zero_length_check()) {
          // Special case for zero-length matches.
          // t7: capture start index
          // Not a zero-length match, restart.
          __ Branch(
              &load_char_start_regexp, ne, current_input_offset(), Operand(t7));
          // Offset from the end is zero if we already reached the end.
svenpanne@chromium.org's avatar
svenpanne@chromium.org committed
816 817
          __ Branch(&exit_label_, eq, current_input_offset(),
                    Operand(zero_reg));
818
          // Advance current position after a zero-length match.
819 820
          Label advance;
          __ bind(&advance);
821 822 823
          __ Addu(current_input_offset(),
                  current_input_offset(),
                  Operand((mode_ == UC16) ? 2 : 1));
824
          if (global_unicode()) CheckNotInSurrogatePair(0, &advance);
825 826
        }

827 828 829 830
        __ Branch(&load_char_start_regexp);
      } else {
        __ li(v0, Operand(SUCCESS));
      }
831 832 833
    }
    // Exit and return v0.
    __ bind(&exit_label_);
834 835 836 837 838
    if (global()) {
      __ lw(v0, MemOperand(frame_pointer(), kSuccessfulCaptures));
    }

    __ bind(&return_v0);
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    // Skip sp past regexp registers and local variables..
    __ mov(sp, frame_pointer());
    // Restore registers s0..s7 and return (restoring ra to pc).
    __ MultiPop(registers_to_retain | ra.bit());
    __ Ret();

    // Backtrack code (branch target for conditional backtracks).
    if (backtrack_label_.is_linked()) {
      __ bind(&backtrack_label_);
      Backtrack();
    }

    Label exit_with_exception;

    // Preempt-code.
    if (check_preempt_label_.is_linked()) {
      SafeCallTarget(&check_preempt_label_);
      // Put regexp engine registers on stack.
      RegList regexp_registers_to_retain = current_input_offset().bit() |
          current_character().bit() | backtrack_stackpointer().bit();
      __ MultiPush(regexp_registers_to_retain);
      CallCheckStackGuardState(a0);
      __ MultiPop(regexp_registers_to_retain);
      // If returning non-zero, we should end execution with the given
      // result as return value.
864
      __ Branch(&return_v0, ne, v0, Operand(zero_reg));
865 866 867

      // String might have moved: Reload end of string from frame.
      __ lw(end_of_input_address(), MemOperand(frame_pointer(), kInputEnd));
868
      __ li(code_pointer(), Operand(masm_->CodeObject()), CONSTANT_SIZE);
869 870 871 872 873 874 875 876 877 878 879
      SafeReturn();
    }

    // Backtrack stack overflow code.
    if (stack_overflow_label_.is_linked()) {
      SafeCallTarget(&stack_overflow_label_);
      // Reached if the backtrack-stack limit has been hit.
      // Put regexp engine registers on stack first.
      RegList regexp_registers = current_input_offset().bit() |
          current_character().bit();
      __ MultiPush(regexp_registers);
880

881 882 883 884 885
      // Call GrowStack(backtrack_stackpointer(), &stack_base)
      static const int num_arguments = 3;
      __ PrepareCallCFunction(num_arguments, a0);
      __ mov(a0, backtrack_stackpointer());
      __ Addu(a1, frame_pointer(), Operand(kStackHighEnd));
886
      __ li(a2, Operand(ExternalReference::isolate_address(masm_->isolate())));
887 888 889 890 891
      ExternalReference grow_stack =
          ExternalReference::re_grow_stack(masm_->isolate());
      __ CallCFunction(grow_stack, num_arguments);
      // Restore regexp registers.
      __ MultiPop(regexp_registers);
892
      // If return nullptr, we have failed to grow the stack, and
893 894 895 896 897
      // must exit with a stack-overflow exception.
      __ Branch(&exit_with_exception, eq, v0, Operand(zero_reg));
      // Otherwise use return value as new stack pointer.
      __ mov(backtrack_stackpointer(), v0);
      // Restore saved registers and continue.
898
      __ li(code_pointer(), Operand(masm_->CodeObject()), CONSTANT_SIZE);
899 900 901 902 903 904 905 906 907
      __ lw(end_of_input_address(), MemOperand(frame_pointer(), kInputEnd));
      SafeReturn();
    }

    if (exit_with_exception.is_linked()) {
      // If any of the code above needed to exit with an exception.
      __ bind(&exit_with_exception);
      // Exit with Result EXCEPTION(-1) to signal thrown exception.
      __ li(v0, Operand(EXCEPTION));
908
      __ jmp(&return_v0);
909 910 911 912
    }
  }

  CodeDesc code_desc;
913
  masm_->GetCode(isolate(), &code_desc);
914 915 916
  Handle<Code> code = Factory::CodeBuilder(isolate(), code_desc, Code::REGEXP)
                          .set_self_reference(masm_->CodeObject())
                          .Build();
917
  LOG(masm_->isolate(),
918
      RegExpCodeCreateEvent(Handle<AbstractCode>::cast(code), source));
919
  return Handle<HeapObject>::cast(code);
920 921 922 923
}


void RegExpMacroAssemblerMIPS::GoTo(Label* to) {
924
  if (to == nullptr) {
925 926 927 928 929
    Backtrack();
    return;
  }
  __ jmp(to);
  return;
930 931 932 933
}


void RegExpMacroAssemblerMIPS::IfRegisterGE(int reg,
934 935
                                            int comparand,
                                            Label* if_ge) {
936 937 938 939 940 941
  __ lw(a0, register_location(reg));
    BranchOrBacktrack(if_ge, ge, a0, Operand(comparand));
}


void RegExpMacroAssemblerMIPS::IfRegisterLT(int reg,
942 943
                                            int comparand,
                                            Label* if_lt) {
944 945
  __ lw(a0, register_location(reg));
  BranchOrBacktrack(if_lt, lt, a0, Operand(comparand));
946 947 948 949
}


void RegExpMacroAssemblerMIPS::IfRegisterEqPos(int reg,
950
                                               Label* if_eq) {
951 952
  __ lw(a0, register_location(reg));
  BranchOrBacktrack(if_eq, eq, a0, Operand(current_input_offset()));
953 954 955 956 957 958 959 960
}


RegExpMacroAssembler::IrregexpImplementation
    RegExpMacroAssemblerMIPS::Implementation() {
  return kMIPSImplementation;
}

961 962 963 964 965 966 967 968
void RegExpMacroAssemblerMIPS::LoadCurrentCharacterImpl(int cp_offset,
                                                        Label* on_end_of_input,
                                                        bool check_bounds,
                                                        int characters,
                                                        int eats_at_least) {
  // It's possible to preload a small number of characters when each success
  // path requires a large number of characters, but not the reverse.
  DCHECK_GE(eats_at_least, characters);
969

970
  DCHECK(cp_offset < (1<<30));  // Be sane! (And ensure negation works).
971
  if (check_bounds) {
972
    if (cp_offset >= 0) {
973
      CheckPosition(cp_offset + eats_at_least - 1, on_end_of_input);
974 975 976
    } else {
      CheckPosition(cp_offset, on_end_of_input);
    }
977 978
  }
  LoadCurrentCharacterUnchecked(cp_offset, characters);
979 980 981
}

void RegExpMacroAssemblerMIPS::PopCurrentPosition() {
982
  Pop(current_input_offset());
983 984 985 986
}


void RegExpMacroAssemblerMIPS::PopRegister(int register_index) {
987 988
  Pop(a0);
  __ sw(a0, register_location(register_index));
989 990 991 992
}


void RegExpMacroAssemblerMIPS::PushBacktrack(Label* label) {
993 994 995 996
  if (label->is_bound()) {
    int target = label->pos();
    __ li(a0, Operand(target + Code::kHeaderSize - kHeapObjectTag));
  } else {
997
    Assembler::BlockTrampolinePoolScope block_trampoline_pool(masm_);
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    Label after_constant;
    __ Branch(&after_constant);
    int offset = masm_->pc_offset();
    int cp_offset = offset + Code::kHeaderSize - kHeapObjectTag;
    __ emit(0);
    masm_->label_at_put(label, offset);
    __ bind(&after_constant);
    if (is_int16(cp_offset)) {
      __ lw(a0, MemOperand(code_pointer(), cp_offset));
    } else {
      __ Addu(a0, code_pointer(), cp_offset);
      __ lw(a0, MemOperand(a0, 0));
    }
  }
  Push(a0);
  CheckStackLimit();
1014 1015 1016 1017 1018 1019 1020 1021 1022
}


void RegExpMacroAssemblerMIPS::PushCurrentPosition() {
  Push(current_input_offset());
}


void RegExpMacroAssemblerMIPS::PushRegister(int register_index,
1023
                                            StackCheckFlag check_stack_limit) {
1024 1025 1026
  __ lw(a0, register_location(register_index));
  Push(a0);
  if (check_stack_limit) CheckStackLimit();
1027 1028 1029 1030
}


void RegExpMacroAssemblerMIPS::ReadCurrentPositionFromRegister(int reg) {
1031
  __ lw(current_input_offset(), register_location(reg));
1032 1033 1034 1035
}


void RegExpMacroAssemblerMIPS::ReadStackPointerFromRegister(int reg) {
1036 1037 1038
  __ lw(backtrack_stackpointer(), register_location(reg));
  __ lw(a0, MemOperand(frame_pointer(), kStackHighEnd));
  __ Addu(backtrack_stackpointer(), backtrack_stackpointer(), Operand(a0));
1039 1040 1041 1042
}


void RegExpMacroAssemblerMIPS::SetCurrentPositionFromEnd(int by) {
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
  Label after_position;
  __ Branch(&after_position,
            ge,
            current_input_offset(),
            Operand(-by * char_size()));
  __ li(current_input_offset(), -by * char_size());
  // On RegExp code entry (where this operation is used), the character before
  // the current position is expected to be already loaded.
  // We have advanced the position, so it's safe to read backwards.
  LoadCurrentCharacterUnchecked(-1, 1);
  __ bind(&after_position);
1054 1055 1056 1057
}


void RegExpMacroAssemblerMIPS::SetRegister(int register_index, int to) {
1058
  DCHECK(register_index >= num_saved_registers_);  // Reserved for positions!
1059 1060
  __ li(a0, Operand(to));
  __ sw(a0, register_location(register_index));
1061 1062 1063
}


1064
bool RegExpMacroAssemblerMIPS::Succeed() {
1065
  __ jmp(&success_label_);
1066
  return global();
1067 1068 1069 1070
}


void RegExpMacroAssemblerMIPS::WriteCurrentPositionToRegister(int reg,
1071
                                                              int cp_offset) {
1072 1073 1074 1075 1076 1077
  if (cp_offset == 0) {
    __ sw(current_input_offset(), register_location(reg));
  } else {
    __ Addu(a0, current_input_offset(), Operand(cp_offset * char_size()));
    __ sw(a0, register_location(reg));
  }
1078 1079 1080 1081
}


void RegExpMacroAssemblerMIPS::ClearRegisters(int reg_from, int reg_to) {
1082
  DCHECK(reg_from <= reg_to);
1083
  __ lw(a0, MemOperand(frame_pointer(), kStringStartMinusOne));
1084 1085 1086
  for (int reg = reg_from; reg <= reg_to; reg++) {
    __ sw(a0, register_location(reg));
  }
1087 1088 1089 1090
}


void RegExpMacroAssemblerMIPS::WriteStackPointerToRegister(int reg) {
1091 1092 1093
  __ lw(a1, MemOperand(frame_pointer(), kStackHighEnd));
  __ Subu(a0, backtrack_stackpointer(), a1);
  __ sw(a0, register_location(reg));
1094 1095 1096
}


1097 1098 1099 1100 1101
bool RegExpMacroAssemblerMIPS::CanReadUnaligned() {
  return false;
}


1102 1103 1104
// Private methods:

void RegExpMacroAssemblerMIPS::CallCheckStackGuardState(Register scratch) {
1105
  DCHECK(!isolate()->IsGeneratingEmbeddedBuiltins());
1106 1107
  DCHECK(!masm_->options().isolate_independent_code);

1108
  int stack_alignment = base::OS::ActivationFrameAlignment();
1109 1110 1111 1112

  // Align the stack pointer and save the original sp value on the stack.
  __ mov(scratch, sp);
  __ Subu(sp, sp, Operand(kPointerSize));
1113
  DCHECK(base::bits::IsPowerOfTwo(stack_alignment));
1114 1115 1116
  __ And(sp, sp, Operand(-stack_alignment));
  __ sw(scratch, MemOperand(sp));

1117
  __ mov(a2, frame_pointer());
1118
  // Code of self.
1119
  __ li(a1, Operand(masm_->CodeObject()), CONSTANT_SIZE);
1120 1121

  // We need to make room for the return address on the stack.
1122
  DCHECK(IsAligned(stack_alignment, kPointerSize));
1123 1124
  __ Subu(sp, sp, Operand(stack_alignment));

1125 1126 1127
  // The stack pointer now points to cell where the return address will be
  // written. Arguments are in registers, meaning we treat the return address as
  // argument 5. Since DirectCEntry will handle allocating space for the C
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
  // argument slots, we don't need to care about that here. This is how the
  // stack will look (sp meaning the value of sp at this moment):
  // [sp + 3] - empty slot if needed for alignment.
  // [sp + 2] - saved sp.
  // [sp + 1] - second word reserved for return value.
  // [sp + 0] - first word reserved for return value.

  // a0 will point to the return address, placed by DirectCEntry.
  __ mov(a0, sp);

1138 1139
  ExternalReference stack_guard_check =
      ExternalReference::re_check_stack_guard_state(masm_->isolate());
1140 1141
  __ li(t9, Operand(stack_guard_check));

1142 1143 1144 1145 1146
  EmbeddedData d = EmbeddedData::FromBlob();
  CHECK(Builtins::IsIsolateIndependent(Builtins::kDirectCEntry));
  Address entry = d.InstructionStartOfBuiltin(Builtins::kDirectCEntry);
  __ li(kScratchReg, Operand(entry, RelocInfo::OFF_HEAP_TARGET));
  __ Call(kScratchReg);
1147 1148

  // DirectCEntry allocated space for the C argument slots so we have to
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
  // drop them with the return address from the stack with loading saved sp.
  // At this point stack must look:
  // [sp + 7] - empty slot if needed for alignment.
  // [sp + 6] - saved sp.
  // [sp + 5] - second word reserved for return value.
  // [sp + 4] - first word reserved for return value.
  // [sp + 3] - C argument slot.
  // [sp + 2] - C argument slot.
  // [sp + 1] - C argument slot.
  // [sp + 0] - C argument slot.
  __ lw(sp, MemOperand(sp, stack_alignment + kCArgsSlotsSize));

  __ li(code_pointer(), Operand(masm_->CodeObject()));
1162 1163 1164 1165 1166 1167
}


// Helper function for reading a value out of a stack frame.
template <typename T>
static T& frame_entry(Address re_frame, int frame_offset) {
1168
  return reinterpret_cast<T&>(Memory<int32_t>(re_frame + frame_offset));
1169 1170 1171
}


1172 1173 1174 1175 1176
template <typename T>
static T* frame_entry_address(Address re_frame, int frame_offset) {
  return reinterpret_cast<T*>(re_frame + frame_offset);
}

1177
int RegExpMacroAssemblerMIPS::CheckStackGuardState(Address* return_address,
1178
                                                   Address raw_code,
1179
                                                   Address re_frame) {
1180
  Code re_code = Code::cast(Object(raw_code));
1181 1182 1183
  return NativeRegExpMacroAssembler::CheckStackGuardState(
      frame_entry<Isolate*>(re_frame, kIsolate),
      frame_entry<int>(re_frame, kStartIndex),
1184 1185
      static_cast<RegExp::CallOrigin>(frame_entry<int>(re_frame, kDirectCall)),
      return_address, re_code,
1186
      frame_entry_address<Address>(re_frame, kInputString),
1187 1188
      frame_entry_address<const byte*>(re_frame, kInputStart),
      frame_entry_address<const byte*>(re_frame, kInputEnd));
1189 1190 1191 1192
}


MemOperand RegExpMacroAssemblerMIPS::register_location(int register_index) {
1193
  DCHECK(register_index < (1<<30));
1194 1195 1196 1197 1198
  if (num_registers_ <= register_index) {
    num_registers_ = register_index + 1;
  }
  return MemOperand(frame_pointer(),
                    kRegisterZero - register_index * kPointerSize);
1199 1200 1201 1202
}


void RegExpMacroAssemblerMIPS::CheckPosition(int cp_offset,
1203
                                             Label* on_outside_input) {
1204 1205 1206 1207 1208 1209 1210 1211
  if (cp_offset >= 0) {
    BranchOrBacktrack(on_outside_input, ge, current_input_offset(),
                      Operand(-cp_offset * char_size()));
  } else {
    __ lw(a1, MemOperand(frame_pointer(), kStringStartMinusOne));
    __ Addu(a0, current_input_offset(), Operand(cp_offset * char_size()));
    BranchOrBacktrack(on_outside_input, le, a0, Operand(a1));
  }
1212 1213 1214 1215 1216 1217 1218
}


void RegExpMacroAssemblerMIPS::BranchOrBacktrack(Label* to,
                                                 Condition condition,
                                                 Register rs,
                                                 const Operand& rt) {
1219
  if (condition == al) {  // Unconditional.
1220
    if (to == nullptr) {
1221 1222 1223 1224 1225 1226
      Backtrack();
      return;
    }
    __ jmp(to);
    return;
  }
1227
  if (to == nullptr) {
1228 1229 1230 1231
    __ Branch(&backtrack_label_, condition, rs, rt);
    return;
  }
  __ Branch(to, condition, rs, rt);
1232 1233 1234
}


1235 1236 1237 1238
void RegExpMacroAssemblerMIPS::SafeCall(Label* to,
                                        Condition cond,
                                        Register rs,
                                        const Operand& rt) {
1239
  __ BranchAndLink(to, cond, rs, rt);
1240 1241 1242 1243
}


void RegExpMacroAssemblerMIPS::SafeReturn() {
1244 1245 1246
  __ pop(ra);
  __ Addu(t5, ra, Operand(masm_->CodeObject()));
  __ Jump(t5);
1247 1248 1249 1250
}


void RegExpMacroAssemblerMIPS::SafeCallTarget(Label* name) {
1251 1252 1253
  __ bind(name);
  __ Subu(ra, ra, Operand(masm_->CodeObject()));
  __ push(ra);
1254 1255 1256 1257
}


void RegExpMacroAssemblerMIPS::Push(Register source) {
1258
  DCHECK(source != backtrack_stackpointer());
1259 1260 1261 1262
  __ Addu(backtrack_stackpointer(),
          backtrack_stackpointer(),
          Operand(-kPointerSize));
  __ sw(source, MemOperand(backtrack_stackpointer()));
1263 1264 1265 1266
}


void RegExpMacroAssemblerMIPS::Pop(Register target) {
1267
  DCHECK(target != backtrack_stackpointer());
1268 1269
  __ lw(target, MemOperand(backtrack_stackpointer()));
  __ Addu(backtrack_stackpointer(), backtrack_stackpointer(), kPointerSize);
1270 1271 1272 1273
}


void RegExpMacroAssemblerMIPS::CheckPreemption() {
1274 1275
  // Check for preemption.
  ExternalReference stack_limit =
1276
      ExternalReference::address_of_jslimit(masm_->isolate());
1277 1278 1279
  __ li(a0, Operand(stack_limit));
  __ lw(a0, MemOperand(a0));
  SafeCall(&check_preempt_label_, ls, sp, Operand(a0));
1280 1281 1282 1283
}


void RegExpMacroAssemblerMIPS::CheckStackLimit() {
1284
  ExternalReference stack_limit =
1285 1286
      ExternalReference::address_of_regexp_stack_limit_address(
          masm_->isolate());
1287 1288 1289 1290

  __ li(a0, Operand(stack_limit));
  __ lw(a0, MemOperand(a0));
  SafeCall(&stack_overflow_label_, ls, backtrack_stackpointer(), Operand(a0));
1291 1292 1293 1294
}


void RegExpMacroAssemblerMIPS::LoadCurrentCharacterUnchecked(int cp_offset,
1295
                                                             int characters) {
1296 1297
  Register offset = current_input_offset();
  if (cp_offset != 0) {
1298 1299 1300
    // t7 is not being used to store the capture start index at this point.
    __ Addu(t7, current_input_offset(), Operand(cp_offset * char_size()));
    offset = t7;
1301 1302 1303
  }
  // We assume that we cannot do unaligned loads on MIPS, so this function
  // must only be used to load a single character at a time.
1304
  DCHECK_EQ(1, characters);
1305
  __ Addu(t5, end_of_input_address(), Operand(offset));
1306
  if (mode_ == LATIN1) {
1307 1308
    __ lbu(current_character(), MemOperand(t5, 0));
  } else {
1309
    DCHECK_EQ(UC16, mode_);
1310 1311
    __ lhu(current_character(), MemOperand(t5, 0));
  }
1312 1313 1314 1315 1316
}


#undef __

1317 1318
}  // namespace internal
}  // namespace v8
1319 1320

#endif  // V8_TARGET_ARCH_MIPS