simulator-mips.cc 113 KB
Newer Older
1
// Copyright 2011 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
#include <limits.h>
6 7
#include <stdarg.h>
#include <stdlib.h>
8
#include <cmath>
9

10
#include "src/v8.h"
11

12
#if V8_TARGET_ARCH_MIPS
13

14
#include "src/assembler.h"
15
#include "src/base/bits.h"
16
#include "src/codegen.h"
17 18 19
#include "src/disasm.h"
#include "src/mips/constants-mips.h"
#include "src/mips/simulator-mips.h"
20
#include "src/ostreams.h"
21 22 23


// Only build the simulator if not compiling for real MIPS hardware.
24
#if defined(USE_SIMULATOR)
25

26 27
namespace v8 {
namespace internal {
28

29
// Utils functions.
30
bool HaveSameSign(int32_t a, int32_t b) {
31 32 33 34 35 36 37 38 39 40
  return ((a ^ b) >= 0);
}


uint32_t get_fcsr_condition_bit(uint32_t cc) {
  if (cc == 0) {
    return 23;
  } else {
    return 24 + cc;
  }
41 42 43 44 45 46 47 48 49
}


// This macro provides a platform independent use of sscanf. The reason for
// SScanF not being implemented in a platform independent was through
// ::v8::internal::OS in the same way as SNPrintF is that the Windows C Run-Time
// Library does not provide vsscanf.
#define SScanF sscanf  // NOLINT

50
// The MipsDebugger class is used by the simulator while debugging simulated
51
// code.
52
class MipsDebugger {
53
 public:
54
  explicit MipsDebugger(Simulator* sim) : sim_(sim) { }
55
  ~MipsDebugger();
56 57 58

  void Stop(Instruction* instr);
  void Debug();
59 60 61
  // Print all registers with a nice formatting.
  void PrintAllRegs();
  void PrintAllRegsIncludingFPU();
62 63 64 65 66 67 68 69 70

 private:
  // We set the breakpoint code to 0xfffff to easily recognize it.
  static const Instr kBreakpointInstr = SPECIAL | BREAK | 0xfffff << 6;
  static const Instr kNopInstr =  0x0;

  Simulator* sim_;

  int32_t GetRegisterValue(int regnum);
71 72
  int32_t GetFPURegisterValue32(int regnum);
  int64_t GetFPURegisterValue64(int regnum);
73 74
  float GetFPURegisterValueFloat(int regnum);
  double GetFPURegisterValueDouble(int regnum);
75
  bool GetValue(const char* desc, int32_t* value);
76
  bool GetValue(const char* desc, int64_t* value);
77 78 79 80 81 82 83 84 85 86 87

  // Set or delete a breakpoint. Returns true if successful.
  bool SetBreakpoint(Instruction* breakpc);
  bool DeleteBreakpoint(Instruction* breakpc);

  // Undo and redo all breakpoints. This is needed to bracket disassembly and
  // execution to skip past breakpoints when run from the debugger.
  void UndoBreakpoints();
  void RedoBreakpoints();
};

88 89

MipsDebugger::~MipsDebugger() {
90 91
}

92

93 94 95 96 97 98 99 100 101 102 103 104
#ifdef GENERATED_CODE_COVERAGE
static FILE* coverage_log = NULL;


static void InitializeCoverage() {
  char* file_name = getenv("V8_GENERATED_CODE_COVERAGE_LOG");
  if (file_name != NULL) {
    coverage_log = fopen(file_name, "aw+");
  }
}


105
void MipsDebugger::Stop(Instruction* instr) {
106 107 108 109 110 111
  // Get the stop code.
  uint32_t code = instr->Bits(25, 6);
  // Retrieve the encoded address, which comes just after this stop.
  char** msg_address =
    reinterpret_cast<char**>(sim_->get_pc() + Instr::kInstrSize);
  char* msg = *msg_address;
112
  DCHECK(msg != NULL);
113 114

  // Update this stop description.
115 116
  if (!watched_stops_[code].desc) {
    watched_stops_[code].desc = msg;
117 118 119
  }

  if (strlen(msg) > 0) {
120 121 122 123
    if (coverage_log != NULL) {
      fprintf(coverage_log, "%s\n", str);
      fflush(coverage_log);
    }
124 125 126
    // Overwrite the instruction and address with nops.
    instr->SetInstructionBits(kNopInstr);
    reinterpret_cast<Instr*>(msg_address)->SetInstructionBits(kNopInstr);
127
  }
128
  sim_->set_pc(sim_->get_pc() + 2 * Instruction::kInstructionSize);
129 130
}

131

132
#else  // GENERATED_CODE_COVERAGE
133 134 135 136 137 138

#define UNSUPPORTED() printf("Unsupported instruction.\n");

static void InitializeCoverage() {}


139
void MipsDebugger::Stop(Instruction* instr) {
140 141 142 143 144 145
  // Get the stop code.
  uint32_t code = instr->Bits(25, 6);
  // Retrieve the encoded address, which comes just after this stop.
  char* msg = *reinterpret_cast<char**>(sim_->get_pc() +
      Instruction::kInstrSize);
  // Update this stop description.
146 147
  if (!sim_->watched_stops_[code].desc) {
    sim_->watched_stops_[code].desc = msg;
148 149 150
  }
  PrintF("Simulator hit %s (%u)\n", msg, code);
  sim_->set_pc(sim_->get_pc() + 2 * Instruction::kInstrSize);
151 152
  Debug();
}
153
#endif  // GENERATED_CODE_COVERAGE
154 155


156
int32_t MipsDebugger::GetRegisterValue(int regnum) {
157 158 159 160 161 162 163 164
  if (regnum == kNumSimuRegisters) {
    return sim_->get_pc();
  } else {
    return sim_->get_register(regnum);
  }
}


165
int32_t MipsDebugger::GetFPURegisterValue32(int regnum) {
166 167 168
  if (regnum == kNumFPURegisters) {
    return sim_->get_pc();
  } else {
169
    return sim_->get_fpu_register_word(regnum);
170 171 172 173
  }
}


174
int64_t MipsDebugger::GetFPURegisterValue64(int regnum) {
175 176 177
  if (regnum == kNumFPURegisters) {
    return sim_->get_pc();
  } else {
178
    return sim_->get_fpu_register(regnum);
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
  }
}


float MipsDebugger::GetFPURegisterValueFloat(int regnum) {
  if (regnum == kNumFPURegisters) {
    return sim_->get_pc();
  } else {
    return sim_->get_fpu_register_float(regnum);
  }
}


double MipsDebugger::GetFPURegisterValueDouble(int regnum) {
  if (regnum == kNumFPURegisters) {
    return sim_->get_pc();
  } else {
    return sim_->get_fpu_register_double(regnum);
  }
}


bool MipsDebugger::GetValue(const char* desc, int32_t* value) {
202
  int regnum = Registers::Number(desc);
203 204
  int fpuregnum = FPURegisters::Number(desc);

205 206 207
  if (regnum != kInvalidRegister) {
    *value = GetRegisterValue(regnum);
    return true;
208
  } else if (fpuregnum != kInvalidFPURegister) {
209
    *value = GetFPURegisterValue32(fpuregnum);
210 211 212
    return true;
  } else if (strncmp(desc, "0x", 2) == 0) {
    return SScanF(desc, "%x", reinterpret_cast<uint32_t*>(value)) == 1;
213 214 215 216 217 218 219
  } else {
    return SScanF(desc, "%i", value) == 1;
  }
  return false;
}


220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
bool MipsDebugger::GetValue(const char* desc, int64_t* value) {
  int regnum = Registers::Number(desc);
  int fpuregnum = FPURegisters::Number(desc);

  if (regnum != kInvalidRegister) {
    *value = GetRegisterValue(regnum);
    return true;
  } else if (fpuregnum != kInvalidFPURegister) {
    *value = GetFPURegisterValue64(fpuregnum);
    return true;
  } else if (strncmp(desc, "0x", 2) == 0) {
    return SScanF(desc + 2, "%" SCNx64,
                  reinterpret_cast<uint64_t*>(value)) == 1;
  } else {
    return SScanF(desc, "%" SCNu64, reinterpret_cast<uint64_t*>(value)) == 1;
  }
  return false;
}


240
bool MipsDebugger::SetBreakpoint(Instruction* breakpc) {
241 242 243 244 245 246 247 248 249 250 251 252 253 254
  // Check if a breakpoint can be set. If not return without any side-effects.
  if (sim_->break_pc_ != NULL) {
    return false;
  }

  // Set the breakpoint.
  sim_->break_pc_ = breakpc;
  sim_->break_instr_ = breakpc->InstructionBits();
  // Not setting the breakpoint instruction in the code itself. It will be set
  // when the debugger shell continues.
  return true;
}


255
bool MipsDebugger::DeleteBreakpoint(Instruction* breakpc) {
256 257 258 259 260 261 262 263 264 265
  if (sim_->break_pc_ != NULL) {
    sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
  }

  sim_->break_pc_ = NULL;
  sim_->break_instr_ = 0;
  return true;
}


266
void MipsDebugger::UndoBreakpoints() {
267 268 269 270 271 272
  if (sim_->break_pc_ != NULL) {
    sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
  }
}


273
void MipsDebugger::RedoBreakpoints() {
274 275 276 277 278
  if (sim_->break_pc_ != NULL) {
    sim_->break_pc_->SetInstructionBits(kBreakpointInstr);
  }
}

279 280

void MipsDebugger::PrintAllRegs() {
281 282 283
#define REG_INFO(n) Registers::Name(n), GetRegisterValue(n), GetRegisterValue(n)

  PrintF("\n");
284
  // at, v0, a0.
285 286
  PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n",
         REG_INFO(1), REG_INFO(2), REG_INFO(4));
287
  // v1, a1.
288 289
  PrintF("%26s\t%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n",
         "", REG_INFO(3), REG_INFO(5));
290
  // a2.
291
  PrintF("%26s\t%26s\t%3s: 0x%08x %10d\n", "", "", REG_INFO(6));
292
  // a3.
293 294 295 296 297 298 299 300
  PrintF("%26s\t%26s\t%3s: 0x%08x %10d\n", "", "", REG_INFO(7));
  PrintF("\n");
  // t0-t7, s0-s7
  for (int i = 0; i < 8; i++) {
    PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n",
           REG_INFO(8+i), REG_INFO(16+i));
  }
  PrintF("\n");
301
  // t8, k0, LO.
302 303
  PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n",
         REG_INFO(24), REG_INFO(26), REG_INFO(32));
304
  // t9, k1, HI.
305 306
  PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n",
         REG_INFO(25), REG_INFO(27), REG_INFO(33));
307
  // sp, fp, gp.
308 309
  PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n",
         REG_INFO(29), REG_INFO(30), REG_INFO(28));
310
  // pc.
311 312
  PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n",
         REG_INFO(31), REG_INFO(34));
313 314 315 316 317 318 319

#undef REG_INFO
#undef FPU_REG_INFO
}


void MipsDebugger::PrintAllRegsIncludingFPU() {
320 321 322 323 324 325 326 327
#define FPU_REG_INFO32(n) FPURegisters::Name(n), FPURegisters::Name(n+1), \
        GetFPURegisterValue32(n+1), \
        GetFPURegisterValue32(n), \
        GetFPURegisterValueDouble(n)

#define FPU_REG_INFO64(n) FPURegisters::Name(n), \
        GetFPURegisterValue64(n), \
        GetFPURegisterValueDouble(n)
328 329 330 331

  PrintAllRegs();

  PrintF("\n\n");
332
  // f0, f1, f2, ... f31.
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
  // This must be a compile-time switch,
  // compiler will throw out warnings otherwise.
  if (kFpuMode == kFP64) {
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(0) );
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(1) );
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(2) );
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(3) );
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(4) );
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(5) );
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(6) );
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(7) );
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(8) );
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(9) );
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(10));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(11));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(12));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(13));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(14));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(15));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(16));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(17));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(18));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(19));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(20));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(21));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(22));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(23));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(24));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(25));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(26));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(27));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(28));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(29));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(30));
    PrintF("%3s: 0x%016llx %16.4e\n", FPU_REG_INFO64(31));
  } else {
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(0) );
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(2) );
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(4) );
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(6) );
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(8) );
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(10));
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(12));
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(14));
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(16));
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(18));
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(20));
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(22));
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(24));
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(26));
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(28));
    PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO32(30));
  }
386

387
#undef REG_INFO
388 389
#undef FPU_REG_INFO32
#undef FPU_REG_INFO64
390 391
}

392 393

void MipsDebugger::Debug() {
394 395 396 397 398 399 400 401 402 403 404 405
  intptr_t last_pc = -1;
  bool done = false;

#define COMMAND_SIZE 63
#define ARG_SIZE 255

#define STR(a) #a
#define XSTR(a) STR(a)

  char cmd[COMMAND_SIZE + 1];
  char arg1[ARG_SIZE + 1];
  char arg2[ARG_SIZE + 1];
406
  char* argv[3] = { cmd, arg1, arg2 };
407

408
  // Make sure to have a proper terminating character if reaching the limit.
409 410 411 412 413 414 415 416 417 418 419 420
  cmd[COMMAND_SIZE] = 0;
  arg1[ARG_SIZE] = 0;
  arg2[ARG_SIZE] = 0;

  // Undo all set breakpoints while running in the debugger shell. This will
  // make them invisible to all commands.
  UndoBreakpoints();

  while (!done && (sim_->get_pc() != Simulator::end_sim_pc)) {
    if (last_pc != sim_->get_pc()) {
      disasm::NameConverter converter;
      disasm::Disassembler dasm(converter);
421
      // Use a reasonably large buffer.
422 423
      v8::internal::EmbeddedVector<char, 256> buffer;
      dasm.InstructionDecode(buffer,
424
                             reinterpret_cast<byte*>(sim_->get_pc()));
425 426 427 428 429 430 431
      PrintF("  0x%08x  %s\n", sim_->get_pc(), buffer.start());
      last_pc = sim_->get_pc();
    }
    char* line = ReadLine("sim> ");
    if (line == NULL) {
      break;
    } else {
432 433 434 435 436 437 438
      char* last_input = sim_->last_debugger_input();
      if (strcmp(line, "\n") == 0 && last_input != NULL) {
        line = last_input;
      } else {
        // Ownership is transferred to sim_;
        sim_->set_last_debugger_input(line);
      }
439 440
      // Use sscanf to parse the individual parts of the command line. At the
      // moment no command expects more than two parameters.
441
      int argc = SScanF(line,
442 443 444 445 446
                        "%" XSTR(COMMAND_SIZE) "s "
                        "%" XSTR(ARG_SIZE) "s "
                        "%" XSTR(ARG_SIZE) "s",
                        cmd, arg1, arg2);
      if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) {
447 448 449
        Instruction* instr = reinterpret_cast<Instruction*>(sim_->get_pc());
        if (!(instr->IsTrap()) ||
            instr->InstructionBits() == rtCallRedirInstr) {
450
          sim_->InstructionDecode(
451
              reinterpret_cast<Instruction*>(sim_->get_pc()));
452 453 454
        } else {
          // Allow si to jump over generated breakpoints.
          PrintF("/!\\ Jumping over generated breakpoint.\n");
455
          sim_->set_pc(sim_->get_pc() + Instruction::kInstrSize);
456 457 458 459 460 461 462
        }
      } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) {
        // Execute the one instruction we broke at with breakpoints disabled.
        sim_->InstructionDecode(reinterpret_cast<Instruction*>(sim_->get_pc()));
        // Leave the debugger shell.
        done = true;
      } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) {
463
        if (argc == 2) {
464 465
          if (strcmp(arg1, "all") == 0) {
            PrintAllRegs();
466 467
          } else if (strcmp(arg1, "allf") == 0) {
            PrintAllRegsIncludingFPU();
468
          } else {
469 470 471 472
            int regnum = Registers::Number(arg1);
            int fpuregnum = FPURegisters::Number(arg1);

            if (regnum != kInvalidRegister) {
473
              int32_t value;
474
              value = GetRegisterValue(regnum);
475
              PrintF("%s: 0x%08x %d \n", arg1, value, value);
476
            } else if (fpuregnum != kInvalidFPURegister) {
477 478 479 480 481 482 483
              if (IsFp64Mode()) {
                int64_t value;
                double dvalue;
                value = GetFPURegisterValue64(fpuregnum);
                dvalue = GetFPURegisterValueDouble(fpuregnum);
                PrintF("%3s: 0x%016llx %16.4e\n",
                       FPURegisters::Name(fpuregnum), value, dvalue);
484
              } else {
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
                if (fpuregnum % 2 == 1) {
                  int32_t value;
                  float fvalue;
                  value = GetFPURegisterValue32(fpuregnum);
                  fvalue = GetFPURegisterValueFloat(fpuregnum);
                  PrintF("%s: 0x%08x %11.4e\n", arg1, value, fvalue);
                } else {
                  double dfvalue;
                  int32_t lvalue1 = GetFPURegisterValue32(fpuregnum);
                  int32_t lvalue2 = GetFPURegisterValue32(fpuregnum + 1);
                  dfvalue = GetFPURegisterValueDouble(fpuregnum);
                  PrintF("%3s,%3s: 0x%08x%08x %16.4e\n",
                         FPURegisters::Name(fpuregnum+1),
                         FPURegisters::Name(fpuregnum),
                         lvalue1,
                         lvalue2,
                         dfvalue);
                }
503
              }
504 505 506 507 508
            } else {
              PrintF("%s unrecognized\n", arg1);
            }
          }
        } else {
509 510 511 512 513 514 515
          if (argc == 3) {
            if (strcmp(arg2, "single") == 0) {
              int32_t value;
              float fvalue;
              int fpuregnum = FPURegisters::Number(arg1);

              if (fpuregnum != kInvalidFPURegister) {
516
                value = GetFPURegisterValue32(fpuregnum);
517 518 519 520 521 522 523 524 525 526 527
                fvalue = GetFPURegisterValueFloat(fpuregnum);
                PrintF("%s: 0x%08x %11.4e\n", arg1, value, fvalue);
              } else {
                PrintF("%s unrecognized\n", arg1);
              }
            } else {
              PrintF("print <fpu register> single\n");
            }
          } else {
            PrintF("print <register> or print <fpu register> single\n");
          }
528 529 530
        }
      } else if ((strcmp(cmd, "po") == 0)
                 || (strcmp(cmd, "printobject") == 0)) {
531
        if (argc == 2) {
532
          int32_t value;
533
          OFStream os(stdout);
534 535
          if (GetValue(arg1, &value)) {
            Object* obj = reinterpret_cast<Object*>(value);
536
            os << arg1 << ": \n";
537
#ifdef DEBUG
538 539
            obj->Print(os);
            os << "\n";
540
#else
541
            os << Brief(obj) << "\n";
542 543
#endif
          } else {
544
            os << arg1 << " unrecognized\n";
545 546 547 548
          }
        } else {
          PrintF("printobject <value>\n");
        }
549 550 551 552 553 554 555
      } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) {
        int32_t* cur = NULL;
        int32_t* end = NULL;
        int next_arg = 1;

        if (strcmp(cmd, "stack") == 0) {
          cur = reinterpret_cast<int32_t*>(sim_->get_register(Simulator::sp));
556
        } else {  // Command "mem".
557 558 559 560 561 562 563 564 565
          int32_t value;
          if (!GetValue(arg1, &value)) {
            PrintF("%s unrecognized\n", arg1);
            continue;
          }
          cur = reinterpret_cast<int32_t*>(value);
          next_arg++;
        }

566 567 568 569 570 571 572 573 574 575 576
        // TODO(palfia): optimize this.
        if (IsFp64Mode()) {
          int64_t words;
          if (argc == next_arg) {
            words = 10;
          } else {
            if (!GetValue(argv[next_arg], &words)) {
              words = 10;
            }
          }
          end = cur + words;
577
        } else {
578 579
          int32_t words;
          if (argc == next_arg) {
580
            words = 10;
581 582 583 584
          } else {
            if (!GetValue(argv[next_arg], &words)) {
              words = 10;
            }
585
          }
586
          end = cur + words;
587 588 589
        }

        while (cur < end) {
590
          PrintF("  0x%08x:  0x%08x %10d",
591
                 reinterpret_cast<intptr_t>(cur), *cur, *cur);
592 593 594
          HeapObject* obj = reinterpret_cast<HeapObject*>(*cur);
          int value = *cur;
          Heap* current_heap = v8::internal::Isolate::Current()->heap();
595
          if (((value & 1) == 0) || current_heap->Contains(obj)) {
596 597 598 599 600 601 602 603 604
            PrintF(" (");
            if ((value & 1) == 0) {
              PrintF("smi %d", value / 2);
            } else {
              obj->ShortPrint();
            }
            PrintF(")");
          }
          PrintF("\n");
605 606 607
          cur++;
        }

608 609 610
      } else if ((strcmp(cmd, "disasm") == 0) ||
                 (strcmp(cmd, "dpc") == 0) ||
                 (strcmp(cmd, "di") == 0)) {
611 612
        disasm::NameConverter converter;
        disasm::Disassembler dasm(converter);
613
        // Use a reasonably large buffer.
614 615
        v8::internal::EmbeddedVector<char, 256> buffer;

616 617
        byte* cur = NULL;
        byte* end = NULL;
618

619
        if (argc == 1) {
620
          cur = reinterpret_cast<byte*>(sim_->get_pc());
621 622
          end = cur + (10 * Instruction::kInstrSize);
        } else if (argc == 2) {
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
          int regnum = Registers::Number(arg1);
          if (regnum != kInvalidRegister || strncmp(arg1, "0x", 2) == 0) {
            // The argument is an address or a register name.
            int32_t value;
            if (GetValue(arg1, &value)) {
              cur = reinterpret_cast<byte*>(value);
              // Disassemble 10 instructions at <arg1>.
              end = cur + (10 * Instruction::kInstrSize);
            }
          } else {
            // The argument is the number of instructions.
            int32_t value;
            if (GetValue(arg1, &value)) {
              cur = reinterpret_cast<byte*>(sim_->get_pc());
              // Disassemble <arg1> instructions.
              end = cur + (value * Instruction::kInstrSize);
            }
640 641 642 643 644
          }
        } else {
          int32_t value1;
          int32_t value2;
          if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
645
            cur = reinterpret_cast<byte*>(value1);
646
            end = cur + (value2 * Instruction::kInstrSize);
647 648 649 650 651
          }
        }

        while (cur < end) {
          dasm.InstructionDecode(buffer, cur);
652 653 654
          PrintF("  0x%08x  %s\n",
              reinterpret_cast<intptr_t>(cur), buffer.start());
          cur += Instruction::kInstrSize;
655 656 657
        }
      } else if (strcmp(cmd, "gdb") == 0) {
        PrintF("relinquishing control to gdb\n");
658
        v8::base::OS::DebugBreak();
659 660
        PrintF("regaining control from gdb\n");
      } else if (strcmp(cmd, "break") == 0) {
661
        if (argc == 2) {
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
          int32_t value;
          if (GetValue(arg1, &value)) {
            if (!SetBreakpoint(reinterpret_cast<Instruction*>(value))) {
              PrintF("setting breakpoint failed\n");
            }
          } else {
            PrintF("%s unrecognized\n", arg1);
          }
        } else {
          PrintF("break <address>\n");
        }
      } else if (strcmp(cmd, "del") == 0) {
        if (!DeleteBreakpoint(NULL)) {
          PrintF("deleting breakpoint failed\n");
        }
      } else if (strcmp(cmd, "flags") == 0) {
        PrintF("No flags on MIPS !\n");
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
      } else if (strcmp(cmd, "stop") == 0) {
        int32_t value;
        intptr_t stop_pc = sim_->get_pc() -
            2 * Instruction::kInstrSize;
        Instruction* stop_instr = reinterpret_cast<Instruction*>(stop_pc);
        Instruction* msg_address =
          reinterpret_cast<Instruction*>(stop_pc +
              Instruction::kInstrSize);
        if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) {
          // Remove the current stop.
          if (sim_->IsStopInstruction(stop_instr)) {
            stop_instr->SetInstructionBits(kNopInstr);
            msg_address->SetInstructionBits(kNopInstr);
          } else {
            PrintF("Not at debugger stop.\n");
          }
        } else if (argc == 3) {
          // Print information about all/the specified breakpoint(s).
          if (strcmp(arg1, "info") == 0) {
            if (strcmp(arg2, "all") == 0) {
              PrintF("Stop information:\n");
              for (uint32_t i = kMaxWatchpointCode + 1;
                   i <= kMaxStopCode;
                   i++) {
                sim_->PrintStopInfo(i);
              }
            } else if (GetValue(arg2, &value)) {
              sim_->PrintStopInfo(value);
            } else {
              PrintF("Unrecognized argument.\n");
            }
          } else if (strcmp(arg1, "enable") == 0) {
            // Enable all/the specified breakpoint(s).
            if (strcmp(arg2, "all") == 0) {
              for (uint32_t i = kMaxWatchpointCode + 1;
                   i <= kMaxStopCode;
                   i++) {
                sim_->EnableStop(i);
              }
            } else if (GetValue(arg2, &value)) {
              sim_->EnableStop(value);
            } else {
              PrintF("Unrecognized argument.\n");
            }
          } else if (strcmp(arg1, "disable") == 0) {
            // Disable all/the specified breakpoint(s).
            if (strcmp(arg2, "all") == 0) {
              for (uint32_t i = kMaxWatchpointCode + 1;
                   i <= kMaxStopCode;
                   i++) {
                sim_->DisableStop(i);
              }
            } else if (GetValue(arg2, &value)) {
              sim_->DisableStop(value);
            } else {
              PrintF("Unrecognized argument.\n");
            }
          }
        } else {
          PrintF("Wrong usage. Use help command for more information.\n");
        }
740
      } else if ((strcmp(cmd, "stat") == 0) || (strcmp(cmd, "st") == 0)) {
741
        // Print registers and disassemble.
742 743 744 745 746
        PrintAllRegs();
        PrintF("\n");

        disasm::NameConverter converter;
        disasm::Disassembler dasm(converter);
747
        // Use a reasonably large buffer.
748 749
        v8::internal::EmbeddedVector<char, 256> buffer;

750 751
        byte* cur = NULL;
        byte* end = NULL;
752

753
        if (argc == 1) {
754
          cur = reinterpret_cast<byte*>(sim_->get_pc());
755 756
          end = cur + (10 * Instruction::kInstrSize);
        } else if (argc == 2) {
757 758
          int32_t value;
          if (GetValue(arg1, &value)) {
759
            cur = reinterpret_cast<byte*>(value);
760
            // no length parameter passed, assume 10 instructions
761
            end = cur + (10 * Instruction::kInstrSize);
762 763 764 765 766
          }
        } else {
          int32_t value1;
          int32_t value2;
          if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
767
            cur = reinterpret_cast<byte*>(value1);
768
            end = cur + (value2 * Instruction::kInstrSize);
769 770 771 772 773
          }
        }

        while (cur < end) {
          dasm.InstructionDecode(buffer, cur);
774 775 776
          PrintF("  0x%08x  %s\n",
                 reinterpret_cast<intptr_t>(cur), buffer.start());
          cur += Instruction::kInstrSize;
777 778 779 780 781 782 783 784 785 786 787
        }
      } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) {
        PrintF("cont\n");
        PrintF("  continue execution (alias 'c')\n");
        PrintF("stepi\n");
        PrintF("  step one instruction (alias 'si')\n");
        PrintF("print <register>\n");
        PrintF("  print register content (alias 'p')\n");
        PrintF("  use register name 'all' to print all registers\n");
        PrintF("printobject <register>\n");
        PrintF("  print an object from a register (alias 'po')\n");
788 789 790 791
        PrintF("stack [<words>]\n");
        PrintF("  dump stack content, default dump 10 words)\n");
        PrintF("mem <address> [<words>]\n");
        PrintF("  dump memory content, default dump 10 words)\n");
792 793 794
        PrintF("flags\n");
        PrintF("  print flags\n");
        PrintF("disasm [<instructions>]\n");
795 796 797 798
        PrintF("disasm [<address/register>]\n");
        PrintF("disasm [[<address/register>] <instructions>]\n");
        PrintF("  disassemble code, default is 10 instructions\n");
        PrintF("  from pc (alias 'di')\n");
799 800 801 802 803 804
        PrintF("gdb\n");
        PrintF("  enter gdb\n");
        PrintF("break <address>\n");
        PrintF("  set a break point on the address\n");
        PrintF("del\n");
        PrintF("  delete the breakpoint\n");
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
        PrintF("stop feature:\n");
        PrintF("  Description:\n");
        PrintF("    Stops are debug instructions inserted by\n");
        PrintF("    the Assembler::stop() function.\n");
        PrintF("    When hitting a stop, the Simulator will\n");
        PrintF("    stop and and give control to the Debugger.\n");
        PrintF("    All stop codes are watched:\n");
        PrintF("    - They can be enabled / disabled: the Simulator\n");
        PrintF("       will / won't stop when hitting them.\n");
        PrintF("    - The Simulator keeps track of how many times they \n");
        PrintF("      are met. (See the info command.) Going over a\n");
        PrintF("      disabled stop still increases its counter. \n");
        PrintF("  Commands:\n");
        PrintF("    stop info all/<code> : print infos about number <code>\n");
        PrintF("      or all stop(s).\n");
        PrintF("    stop enable/disable all/<code> : enables / disables\n");
        PrintF("      all or number <code> stop(s)\n");
        PrintF("    stop unstop\n");
        PrintF("      ignore the stop instruction at the current location\n");
        PrintF("      from now on\n");
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
      } else {
        PrintF("Unknown command: %s\n", cmd);
      }
    }
  }

  // Add all the breakpoints back to stop execution and enter the debugger
  // shell when hit.
  RedoBreakpoints();

#undef COMMAND_SIZE
#undef ARG_SIZE

#undef STR
#undef XSTR
}


843
static bool ICacheMatch(void* one, void* two) {
844 845
  DCHECK((reinterpret_cast<intptr_t>(one) & CachePage::kPageMask) == 0);
  DCHECK((reinterpret_cast<intptr_t>(two) & CachePage::kPageMask) == 0);
846 847 848
  return one == two;
}

849

850 851 852
static uint32_t ICacheHash(void* key) {
  return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(key)) >> 2;
}
853

854 855 856 857 858 859 860 861

static bool AllOnOnePage(uintptr_t start, int size) {
  intptr_t start_page = (start & ~CachePage::kPageMask);
  intptr_t end_page = ((start + size) & ~CachePage::kPageMask);
  return start_page == end_page;
}


862 863 864 865 866 867
void Simulator::set_last_debugger_input(char* input) {
  DeleteArray(last_debugger_input_);
  last_debugger_input_ = input;
}


868 869 870 871 872 873 874 875 876 877 878 879 880 881
void Simulator::FlushICache(v8::internal::HashMap* i_cache,
                            void* start_addr,
                            size_t size) {
  intptr_t start = reinterpret_cast<intptr_t>(start_addr);
  int intra_line = (start & CachePage::kLineMask);
  start -= intra_line;
  size += intra_line;
  size = ((size - 1) | CachePage::kLineMask) + 1;
  int offset = (start & CachePage::kPageMask);
  while (!AllOnOnePage(start, size - 1)) {
    int bytes_to_flush = CachePage::kPageSize - offset;
    FlushOnePage(i_cache, start, bytes_to_flush);
    start += bytes_to_flush;
    size -= bytes_to_flush;
882
    DCHECK_EQ(0, start & CachePage::kPageMask);
883 884 885 886 887 888 889 890 891
    offset = 0;
  }
  if (size != 0) {
    FlushOnePage(i_cache, start, size);
  }
}


CachePage* Simulator::GetCachePage(v8::internal::HashMap* i_cache, void* page) {
892 893
  v8::internal::HashMap::Entry* entry =
      i_cache->LookupOrInsert(page, ICacheHash(page));
894 895 896 897 898 899 900 901 902 903 904 905
  if (entry->value == NULL) {
    CachePage* new_page = new CachePage();
    entry->value = new_page;
  }
  return reinterpret_cast<CachePage*>(entry->value);
}


// Flush from start up to and not including start + size.
void Simulator::FlushOnePage(v8::internal::HashMap* i_cache,
                             intptr_t start,
                             int size) {
906 907 908 909
  DCHECK(size <= CachePage::kPageSize);
  DCHECK(AllOnOnePage(start, size - 1));
  DCHECK((start & CachePage::kLineMask) == 0);
  DCHECK((size & CachePage::kLineMask) == 0);
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
  void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask));
  int offset = (start & CachePage::kPageMask);
  CachePage* cache_page = GetCachePage(i_cache, page);
  char* valid_bytemap = cache_page->ValidityByte(offset);
  memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift);
}


void Simulator::CheckICache(v8::internal::HashMap* i_cache,
                            Instruction* instr) {
  intptr_t address = reinterpret_cast<intptr_t>(instr);
  void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask));
  void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask));
  int offset = (address & CachePage::kPageMask);
  CachePage* cache_page = GetCachePage(i_cache, page);
  char* cache_valid_byte = cache_page->ValidityByte(offset);
  bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID);
  char* cached_line = cache_page->CachedData(offset & ~CachePage::kLineMask);
  if (cache_hit) {
    // Check that the data in memory matches the contents of the I-cache.
930 931 932
    CHECK_EQ(0, memcmp(reinterpret_cast<void*>(instr),
                       cache_page->CachedData(offset),
                       Instruction::kInstrSize));
933 934
  } else {
    // Cache miss.  Load memory into the cache.
935
    memcpy(cached_line, line, CachePage::kLineLength);
936 937 938
    *cache_valid_byte = CachePage::LINE_VALID;
  }
}
939 940


941 942 943 944 945
void Simulator::Initialize(Isolate* isolate) {
  if (isolate->simulator_initialized()) return;
  isolate->set_simulator_initialized(true);
  ::v8::internal::ExternalReference::set_redirector(isolate,
                                                    &RedirectExternalReference);
946 947 948
}


949
Simulator::Simulator(Isolate* isolate) : isolate_(isolate) {
950 951 952 953 954
  i_cache_ = isolate_->simulator_i_cache();
  if (i_cache_ == NULL) {
    i_cache_ = new v8::internal::HashMap(&ICacheMatch);
    isolate_->set_simulator_i_cache(i_cache_);
  }
955
  Initialize(isolate);
956
  // Set up simulator support first. Some of this information is needed to
957
  // setup the architecture state.
958
  stack_ = reinterpret_cast<char*>(malloc(stack_size_));
959 960
  pc_modified_ = false;
  icount_ = 0;
961
  break_count_ = 0;
962 963 964
  break_pc_ = NULL;
  break_instr_ = 0;

965
  // Set up architecture state.
966 967 968 969
  // All registers are initialized to zero to start with.
  for (int i = 0; i < kNumSimuRegisters; i++) {
    registers_[i] = 0;
  }
970 971 972 973
  for (int i = 0; i < kNumFPURegisters; i++) {
    FPUregisters_[i] = 0;
  }
  FCSR_ = 0;
974 975 976 977

  // The sp is initialized to point to the bottom (high address) of the
  // allocated stack area. To be safe in potential stack underflows we leave
  // some buffer below.
978
  registers_[sp] = reinterpret_cast<int32_t>(stack_) + stack_size_ - 64;
979 980 981 982 983
  // The ra and pc are initialized to a known bad value that will cause an
  // access violation if the simulator ever tries to execute it.
  registers_[pc] = bad_ra;
  registers_[ra] = bad_ra;
  InitializeCoverage();
984 985 986
  for (int i = 0; i < kNumExceptions; i++) {
    exceptions[i] = 0;
  }
987 988

  last_debugger_input_ = NULL;
989
}
990 991 992 993


Simulator::~Simulator() {
}
994 995 996 997 998 999 1000 1001 1002 1003 1004


// When the generated code calls an external reference we need to catch that in
// the simulator.  The external reference will be a function compiled for the
// host architecture.  We need to call that function instead of trying to
// execute it with the simulator.  We do that by redirecting the external
// reference to a swi (software-interrupt) instruction that is handled by
// the simulator.  We write the original destination of the jump just at a known
// offset from the swi instruction so the simulator knows what to call.
class Redirection {
 public:
1005
  Redirection(void* external_function, ExternalReference::Type type)
1006 1007
      : external_function_(external_function),
        swi_instruction_(rtCallRedirInstr),
1008 1009 1010 1011 1012 1013 1014 1015 1016
        type_(type),
        next_(NULL) {
    Isolate* isolate = Isolate::Current();
    next_ = isolate->simulator_redirection();
    Simulator::current(isolate)->
        FlushICache(isolate->simulator_i_cache(),
                    reinterpret_cast<void*>(&swi_instruction_),
                    Instruction::kInstrSize);
    isolate->set_simulator_redirection(this);
1017 1018 1019 1020 1021 1022 1023
  }

  void* address_of_swi_instruction() {
    return reinterpret_cast<void*>(&swi_instruction_);
  }

  void* external_function() { return external_function_; }
1024
  ExternalReference::Type type() { return type_; }
1025

1026 1027 1028 1029 1030
  static Redirection* Get(void* external_function,
                          ExternalReference::Type type) {
    Isolate* isolate = Isolate::Current();
    Redirection* current = isolate->simulator_redirection();
    for (; current != NULL; current = current->next_) {
1031 1032
      if (current->external_function_ == external_function) return current;
    }
1033
    return new Redirection(external_function, type);
1034 1035 1036 1037 1038 1039 1040 1041 1042
  }

  static Redirection* FromSwiInstruction(Instruction* swi_instruction) {
    char* addr_of_swi = reinterpret_cast<char*>(swi_instruction);
    char* addr_of_redirection =
        addr_of_swi - OFFSET_OF(Redirection, swi_instruction_);
    return reinterpret_cast<Redirection*>(addr_of_redirection);
  }

1043 1044 1045 1046 1047 1048
  static void* ReverseRedirection(int32_t reg) {
    Redirection* redirection = FromSwiInstruction(
        reinterpret_cast<Instruction*>(reinterpret_cast<void*>(reg)));
    return redirection->external_function();
  }

1049 1050 1051
 private:
  void* external_function_;
  uint32_t swi_instruction_;
1052
  ExternalReference::Type type_;
1053 1054 1055 1056 1057
  Redirection* next_;
};


void* Simulator::RedirectExternalReference(void* external_function,
1058 1059
                                           ExternalReference::Type type) {
  Redirection* redirection = Redirection::Get(external_function, type);
1060 1061 1062 1063 1064
  return redirection->address_of_swi_instruction();
}


// Get the active Simulator for the current thread.
1065 1066
Simulator* Simulator::current(Isolate* isolate) {
  v8::internal::Isolate::PerIsolateThreadData* isolate_data =
1067
       isolate->FindOrAllocatePerThreadDataForThisThread();
1068 1069
  DCHECK(isolate_data != NULL);
  DCHECK(isolate_data != NULL);
1070 1071

  Simulator* sim = isolate_data->simulator();
1072
  if (sim == NULL) {
1073
    // TODO(146): delete the simulator object when a thread/isolate goes away.
1074
    sim = new Simulator(isolate);
1075
    isolate_data->set_simulator(sim);
1076 1077 1078 1079 1080 1081 1082 1083
  }
  return sim;
}


// Sets the register in the architecture state. It will also deal with updating
// Simulator internal state for special registers such as PC.
void Simulator::set_register(int reg, int32_t value) {
1084
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1085 1086 1087 1088
  if (reg == pc) {
    pc_modified_ = true;
  }

1089
  // Zero register always holds 0.
1090 1091 1092
  registers_[reg] = (reg == 0) ? 0 : value;
}

1093

1094
void Simulator::set_dw_register(int reg, const int* dbl) {
1095
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1096 1097 1098 1099 1100
  registers_[reg] = dbl[0];
  registers_[reg + 1] = dbl[1];
}


1101 1102
void Simulator::set_fpu_register(int fpureg, int64_t value) {
  DCHECK(IsFp64Mode());
1103
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1104 1105 1106
  FPUregisters_[fpureg] = value;
}

1107

1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
void Simulator::set_fpu_register_word(int fpureg, int32_t value) {
  // Set ONLY lower 32-bits, leaving upper bits untouched.
  // TODO(plind): big endian issue.
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
  int32_t *pword = reinterpret_cast<int32_t*>(&FPUregisters_[fpureg]);
  *pword = value;
}


void Simulator::set_fpu_register_hi_word(int fpureg, int32_t value) {
  // Set ONLY upper 32-bits, leaving lower bits untouched.
  // TODO(plind): big endian issue.
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
  int32_t *phiword = (reinterpret_cast<int32_t*>(&FPUregisters_[fpureg])) + 1;
  *phiword = value;
}


1126
void Simulator::set_fpu_register_float(int fpureg, float value) {
1127
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1128
  *bit_cast<float*>(&FPUregisters_[fpureg]) = value;
1129 1130 1131
}


1132
void Simulator::set_fpu_register_double(int fpureg, double value) {
1133 1134
  if (IsFp64Mode()) {
    DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1135
    *bit_cast<double*>(&FPUregisters_[fpureg]) = value;
1136 1137
  } else {
    DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters) && ((fpureg % 2) == 0));
1138
    int64_t i64 = bit_cast<int64_t>(value);
1139 1140 1141
    set_fpu_register_word(fpureg, i64 & 0xffffffff);
    set_fpu_register_word(fpureg + 1, i64 >> 32);
  }
1142 1143 1144 1145 1146 1147
}


// Get the register from the architecture state. This function does handle
// the special case of accessing the PC register.
int32_t Simulator::get_register(int reg) const {
1148
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1149 1150 1151 1152 1153 1154
  if (reg == 0)
    return 0;
  else
    return registers_[reg] + ((reg == pc) ? Instruction::kPCReadOffset : 0);
}

1155

1156
double Simulator::get_double_from_register_pair(int reg) {
1157
  // TODO(plind): bad ABI stuff, refactor or remove.
1158
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters) && ((reg % 2) == 0));
1159 1160 1161 1162 1163

  double dm_val = 0.0;
  // Read the bits from the unsigned integer register_[] array
  // into the double precision floating point value and return it.
  char buffer[2 * sizeof(registers_[0])];
1164 1165
  memcpy(buffer, &registers_[reg], 2 * sizeof(registers_[0]));
  memcpy(&dm_val, buffer, 2 * sizeof(registers_[0]));
1166 1167 1168 1169
  return(dm_val);
}


1170 1171
int64_t Simulator::get_fpu_register(int fpureg) const {
  DCHECK(IsFp64Mode());
1172
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1173 1174 1175
  return FPUregisters_[fpureg];
}

1176

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
int32_t Simulator::get_fpu_register_word(int fpureg) const {
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
  return static_cast<int32_t>(FPUregisters_[fpureg] & 0xffffffff);
}


int32_t Simulator::get_fpu_register_signed_word(int fpureg) const {
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
  return static_cast<int32_t>(FPUregisters_[fpureg] & 0xffffffff);
}


int32_t Simulator::get_fpu_register_hi_word(int fpureg) const {
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
  return static_cast<int32_t>((FPUregisters_[fpureg] >> 32) & 0xffffffff);
1192 1193 1194 1195
}


float Simulator::get_fpu_register_float(int fpureg) const {
1196
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1197
  return *bit_cast<float*>(const_cast<int64_t*>(&FPUregisters_[fpureg]));
1198 1199 1200
}


1201
double Simulator::get_fpu_register_double(int fpureg) const {
1202 1203
  if (IsFp64Mode()) {
    DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1204
    return *bit_cast<double*>(&FPUregisters_[fpureg]);
1205 1206 1207 1208 1209
  } else {
    DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters) && ((fpureg % 2) == 0));
    int64_t i64;
    i64 = static_cast<uint32_t>(get_fpu_register_word(fpureg));
    i64 |= static_cast<uint64_t>(get_fpu_register_word(fpureg + 1)) << 32;
1210
    return bit_cast<double>(i64);
1211
  }
1212 1213 1214
}


1215 1216
// Runtime FP routines take up to two double arguments and zero
// or one integer arguments. All are constructed here,
1217
// from a0-a3 or f12 and f14.
1218
void Simulator::GetFpArgs(double* x, double* y, int32_t* z) {
1219 1220 1221
  if (!IsMipsSoftFloatABI) {
    *x = get_fpu_register_double(12);
    *y = get_fpu_register_double(14);
1222
    *z = get_register(a2);
1223
  } else {
1224
    // TODO(plind): bad ABI stuff, refactor or remove.
1225 1226 1227 1228 1229 1230 1231 1232
    // We use a char buffer to get around the strict-aliasing rules which
    // otherwise allow the compiler to optimize away the copy.
    char buffer[sizeof(*x)];
    int32_t* reg_buffer = reinterpret_cast<int32_t*>(buffer);

    // Registers a0 and a1 -> x.
    reg_buffer[0] = get_register(a0);
    reg_buffer[1] = get_register(a1);
1233
    memcpy(x, buffer, sizeof(buffer));
1234 1235 1236
    // Registers a2 and a3 -> y.
    reg_buffer[0] = get_register(a2);
    reg_buffer[1] = get_register(a3);
1237
    memcpy(y, buffer, sizeof(buffer));
1238
    // Register 2 -> z.
1239
    reg_buffer[0] = get_register(a2);
1240
    memcpy(z, buffer, sizeof(*z));
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
  }
}


// The return value is either in v0/v1 or f0.
void Simulator::SetFpResult(const double& result) {
  if (!IsMipsSoftFloatABI) {
    set_fpu_register_double(0, result);
  } else {
    char buffer[2 * sizeof(registers_[0])];
    int32_t* reg_buffer = reinterpret_cast<int32_t*>(buffer);
1252
    memcpy(buffer, &result, sizeof(buffer));
1253 1254 1255 1256 1257 1258 1259
    // Copy result to v0 and v1.
    set_register(v0, reg_buffer[0]);
    set_register(v1, reg_buffer[1]);
  }
}


1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
// Helper functions for setting and testing the FCSR register's bits.
void Simulator::set_fcsr_bit(uint32_t cc, bool value) {
  if (value) {
    FCSR_ |= (1 << cc);
  } else {
    FCSR_ &= ~(1 << cc);
  }
}


bool Simulator::test_fcsr_bit(uint32_t cc) {
  return FCSR_ & (1 << cc);
1272 1273
}

1274

1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
void Simulator::set_fcsr_rounding_mode(FPURoundingMode mode) {
  FCSR_ |= mode & kFPURoundingModeMask;
}


unsigned int Simulator::get_fcsr_rounding_mode() {
  return FCSR_ & kFPURoundingModeMask;
}


1285 1286
// Sets the rounding error codes in FCSR based on the result of the rounding.
// Returns true if the operation was invalid.
1287
bool Simulator::set_fcsr_round_error(double original, double rounded) {
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
  bool ret = false;
  double max_int32 = std::numeric_limits<int32_t>::max();
  double min_int32 = std::numeric_limits<int32_t>::min();

  if (!std::isfinite(original) || !std::isfinite(rounded)) {
    set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
    ret = true;
  }

  if (original != rounded) {
    set_fcsr_bit(kFCSRInexactFlagBit, true);
  }

1301
  if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1302 1303 1304 1305
    set_fcsr_bit(kFCSRUnderflowFlagBit, true);
    ret = true;
  }

1306
  if (rounded > max_int32 || rounded < min_int32) {
1307 1308 1309 1310 1311 1312 1313
    set_fcsr_bit(kFCSROverflowFlagBit, true);
    // The reference is not really clear but it seems this is required:
    set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
    ret = true;
  }

  return ret;
1314 1315 1316
}


1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
void Simulator::round_according_to_fcsr(double toRound, double& rounded,
                                        int32_t& rounded_int, double fs) {
  // 0 RN (round to nearest): Round a result to the nearest
  // representable value; if the result is exactly halfway between
  // two representable values, round to zero. Behave like round_w_d.

  // 1 RZ (round toward zero): Round a result to the closest
  // representable value whose absolute value is less than or
  // equal to the infinitely accurate result. Behave like trunc_w_d.

  // 2 RP (round up, or toward  infinity): Round a result to the
  // next representable value up. Behave like ceil_w_d.

  // 3 RD (round down, or toward −infinity): Round a result to
  // the next representable value down. Behave like floor_w_d.
  switch (get_fcsr_rounding_mode()) {
    case kRoundToNearest:
      rounded = std::floor(fs + 0.5);
      rounded_int = static_cast<int32_t>(rounded);
      if ((rounded_int & 1) != 0 && rounded_int - fs == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        rounded_int--;
      }
      break;
    case kRoundToZero:
      rounded = trunc(fs);
      rounded_int = static_cast<int32_t>(rounded);
      break;
    case kRoundToPlusInf:
      rounded = std::ceil(fs);
      rounded_int = static_cast<int32_t>(rounded);
      break;
    case kRoundToMinusInf:
      rounded = std::floor(fs);
      rounded_int = static_cast<int32_t>(rounded);
      break;
  }
}


1358 1359 1360 1361 1362 1363
// Raw access to the PC register.
void Simulator::set_pc(int32_t value) {
  pc_modified_ = true;
  registers_[pc] = value;
}

1364 1365 1366 1367 1368 1369

bool Simulator::has_bad_pc() const {
  return ((registers_[pc] == bad_ra) || (registers_[pc] == end_sim_pc));
}


1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
// Raw access to the PC register without the special adjustment when reading.
int32_t Simulator::get_pc() const {
  return registers_[pc];
}


// The MIPS cannot do unaligned reads and writes.  On some MIPS platforms an
// interrupt is caused.  On others it does a funky rotation thing.  For now we
// simply disallow unaligned reads, but at some point we may want to move to
// emulating the rotate behaviour.  Note that simulator runs have the runtime
// system running directly on the host system and only generated code is
// executed in the simulator.  Since the host is typically IA32 we will not
// get the correct MIPS-like behaviour on unaligned accesses.

int Simulator::ReadW(int32_t addr, Instruction* instr) {
1385
  if (addr >=0 && addr < 0x400) {
1386
    // This has to be a NULL-dereference, drop into debugger.
1387 1388
    PrintF("Memory read from bad address: 0x%08x, pc=0x%08x\n",
           addr, reinterpret_cast<intptr_t>(instr));
1389 1390 1391 1392
    MipsDebugger dbg(this);
    dbg.Debug();
  }
  if ((addr & kPointerAlignmentMask) == 0) {
1393 1394 1395
    intptr_t* ptr = reinterpret_cast<intptr_t*>(addr);
    return *ptr;
  }
1396 1397 1398
  PrintF("Unaligned read at 0x%08x, pc=0x%08" V8PRIxPTR "\n",
         addr,
         reinterpret_cast<intptr_t>(instr));
1399 1400
  MipsDebugger dbg(this);
  dbg.Debug();
1401 1402 1403 1404 1405
  return 0;
}


void Simulator::WriteW(int32_t addr, int value, Instruction* instr) {
1406
  if (addr >= 0 && addr < 0x400) {
1407
    // This has to be a NULL-dereference, drop into debugger.
1408 1409
    PrintF("Memory write to bad address: 0x%08x, pc=0x%08x\n",
           addr, reinterpret_cast<intptr_t>(instr));
1410 1411 1412 1413
    MipsDebugger dbg(this);
    dbg.Debug();
  }
  if ((addr & kPointerAlignmentMask) == 0) {
1414 1415 1416 1417
    intptr_t* ptr = reinterpret_cast<intptr_t*>(addr);
    *ptr = value;
    return;
  }
1418 1419 1420
  PrintF("Unaligned write at 0x%08x, pc=0x%08" V8PRIxPTR "\n",
         addr,
         reinterpret_cast<intptr_t>(instr));
1421 1422
  MipsDebugger dbg(this);
  dbg.Debug();
1423 1424 1425 1426 1427 1428 1429 1430
}


double Simulator::ReadD(int32_t addr, Instruction* instr) {
  if ((addr & kDoubleAlignmentMask) == 0) {
    double* ptr = reinterpret_cast<double*>(addr);
    return *ptr;
  }
1431 1432 1433
  PrintF("Unaligned (double) read at 0x%08x, pc=0x%08" V8PRIxPTR "\n",
         addr,
         reinterpret_cast<intptr_t>(instr));
1434
  base::OS::Abort();
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
  return 0;
}


void Simulator::WriteD(int32_t addr, double value, Instruction* instr) {
  if ((addr & kDoubleAlignmentMask) == 0) {
    double* ptr = reinterpret_cast<double*>(addr);
    *ptr = value;
    return;
  }
1445 1446 1447
  PrintF("Unaligned (double) write at 0x%08x, pc=0x%08" V8PRIxPTR "\n",
         addr,
         reinterpret_cast<intptr_t>(instr));
1448
  base::OS::Abort();
1449 1450 1451 1452 1453 1454 1455 1456
}


uint16_t Simulator::ReadHU(int32_t addr, Instruction* instr) {
  if ((addr & 1) == 0) {
    uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
    return *ptr;
  }
1457 1458 1459
  PrintF("Unaligned unsigned halfword read at 0x%08x, pc=0x%08" V8PRIxPTR "\n",
         addr,
         reinterpret_cast<intptr_t>(instr));
1460
  base::OS::Abort();
1461 1462 1463 1464 1465 1466 1467 1468 1469
  return 0;
}


int16_t Simulator::ReadH(int32_t addr, Instruction* instr) {
  if ((addr & 1) == 0) {
    int16_t* ptr = reinterpret_cast<int16_t*>(addr);
    return *ptr;
  }
1470 1471 1472
  PrintF("Unaligned signed halfword read at 0x%08x, pc=0x%08" V8PRIxPTR "\n",
         addr,
         reinterpret_cast<intptr_t>(instr));
1473
  base::OS::Abort();
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
  return 0;
}


void Simulator::WriteH(int32_t addr, uint16_t value, Instruction* instr) {
  if ((addr & 1) == 0) {
    uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
    *ptr = value;
    return;
  }
1484 1485 1486
  PrintF("Unaligned unsigned halfword write at 0x%08x, pc=0x%08" V8PRIxPTR "\n",
         addr,
         reinterpret_cast<intptr_t>(instr));
1487
  base::OS::Abort();
1488 1489 1490 1491 1492 1493 1494 1495 1496
}


void Simulator::WriteH(int32_t addr, int16_t value, Instruction* instr) {
  if ((addr & 1) == 0) {
    int16_t* ptr = reinterpret_cast<int16_t*>(addr);
    *ptr = value;
    return;
  }
1497 1498 1499
  PrintF("Unaligned halfword write at 0x%08x, pc=0x%08" V8PRIxPTR "\n",
         addr,
         reinterpret_cast<intptr_t>(instr));
1500
  base::OS::Abort();
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
}


uint32_t Simulator::ReadBU(int32_t addr) {
  uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
  return *ptr & 0xff;
}


int32_t Simulator::ReadB(int32_t addr) {
  int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1512
  return *ptr;
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
}


void Simulator::WriteB(int32_t addr, uint8_t value) {
  uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
  *ptr = value;
}


void Simulator::WriteB(int32_t addr, int8_t value) {
  int8_t* ptr = reinterpret_cast<int8_t*>(addr);
  *ptr = value;
}


// Returns the limit of the stack area to enable checking for stack overflows.
uintptr_t Simulator::StackLimit() const {
1530
  // Leave a safety margin of 1024 bytes to prevent overrunning the stack when
1531
  // pushing values.
1532
  return reinterpret_cast<uintptr_t>(stack_) + 1024;
1533 1534 1535 1536 1537 1538
}


// Unsupported instructions use Format to print an error and stop execution.
void Simulator::Format(Instruction* instr, const char* format) {
  PrintF("Simulator found unsupported instruction:\n 0x%08x: %s\n",
1539
         reinterpret_cast<intptr_t>(instr), format);
1540 1541 1542 1543 1544 1545 1546 1547
  UNIMPLEMENTED_MIPS();
}


// Calls into the V8 runtime are based on this very simple interface.
// Note: To be able to return two values from some calls the code in runtime.cc
// uses the ObjectPair which is essentially two 32-bit values stuffed into a
// 64-bit value. With the code below we assume that all runtime calls return
1548
// 64 bits of result. If they don't, the v1 result register contains a bogus
1549 1550 1551 1552
// value, which is fine because it is caller-saved.
typedef int64_t (*SimulatorRuntimeCall)(int32_t arg0,
                                        int32_t arg1,
                                        int32_t arg2,
1553 1554 1555
                                        int32_t arg3,
                                        int32_t arg4,
                                        int32_t arg5);
1556 1557 1558 1559 1560 1561

// These prototypes handle the four types of FP calls.
typedef int64_t (*SimulatorRuntimeCompareCall)(double darg0, double darg1);
typedef double (*SimulatorRuntimeFPFPCall)(double darg0, double darg1);
typedef double (*SimulatorRuntimeFPCall)(double darg0);
typedef double (*SimulatorRuntimeFPIntCall)(double darg0, int32_t arg0);
1562

1563 1564
// This signature supports direct call in to API function native callback
// (refer to InvocationCallback in v8.h).
1565
typedef void (*SimulatorRuntimeDirectApiCall)(int32_t arg0);
1566
typedef void (*SimulatorRuntimeProfilingApiCall)(int32_t arg0, void* arg1);
1567 1568

// This signature supports direct call to accessor getter callback.
1569 1570
typedef void (*SimulatorRuntimeDirectGetterCall)(int32_t arg0, int32_t arg1);
typedef void (*SimulatorRuntimeProfilingGetterCall)(
1571
    int32_t arg0, int32_t arg1, void* arg2);
1572

1573
// Software interrupt instructions are used by the simulator to call into the
1574
// C-based V8 runtime. They are also used for debugging with simulator.
1575
void Simulator::SoftwareInterrupt(Instruction* instr) {
1576 1577 1578 1579
  // There are several instructions that could get us here,
  // the break_ instruction, or several variants of traps. All
  // Are "SPECIAL" class opcode, and are distinuished by function.
  int32_t func = instr->FunctionFieldRaw();
1580
  uint32_t code = (func == BREAK) ? instr->Bits(25, 6) : -1;
1581

1582 1583 1584 1585 1586 1587 1588
  // We first check if we met a call_rt_redirected.
  if (instr->InstructionBits() == rtCallRedirInstr) {
    Redirection* redirection = Redirection::FromSwiInstruction(instr);
    int32_t arg0 = get_register(a0);
    int32_t arg1 = get_register(a1);
    int32_t arg2 = get_register(a2);
    int32_t arg3 = get_register(a3);
1589 1590

    int32_t* stack_pointer = reinterpret_cast<int32_t*>(get_register(sp));
1591 1592 1593
    // Args 4 and 5 are on the stack after the reserved space for args 0..3.
    int32_t arg4 = stack_pointer[4];
    int32_t arg5 = stack_pointer[5];
1594 1595 1596 1597 1598 1599 1600

    bool fp_call =
         (redirection->type() == ExternalReference::BUILTIN_FP_FP_CALL) ||
         (redirection->type() == ExternalReference::BUILTIN_COMPARE_CALL) ||
         (redirection->type() == ExternalReference::BUILTIN_FP_CALL) ||
         (redirection->type() == ExternalReference::BUILTIN_FP_INT_CALL);

1601 1602 1603 1604 1605 1606 1607 1608
    if (!IsMipsSoftFloatABI) {
      // With the hard floating point calling convention, double
      // arguments are passed in FPU registers. Fetch the arguments
      // from there and call the builtin using soft floating point
      // convention.
      switch (redirection->type()) {
      case ExternalReference::BUILTIN_FP_FP_CALL:
      case ExternalReference::BUILTIN_COMPARE_CALL:
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
        if (IsFp64Mode()) {
          arg0 = get_fpu_register_word(f12);
          arg1 = get_fpu_register_hi_word(f12);
          arg2 = get_fpu_register_word(f14);
          arg3 = get_fpu_register_hi_word(f14);
        } else {
          arg0 = get_fpu_register_word(f12);
          arg1 = get_fpu_register_word(f13);
          arg2 = get_fpu_register_word(f14);
          arg3 = get_fpu_register_word(f15);
        }
1620 1621
        break;
      case ExternalReference::BUILTIN_FP_CALL:
1622 1623 1624 1625 1626 1627 1628
        if (IsFp64Mode()) {
          arg0 = get_fpu_register_word(f12);
          arg1 = get_fpu_register_hi_word(f12);
        } else {
          arg0 = get_fpu_register_word(f12);
          arg1 = get_fpu_register_word(f13);
        }
1629 1630
        break;
      case ExternalReference::BUILTIN_FP_INT_CALL:
1631 1632 1633 1634 1635 1636 1637
        if (IsFp64Mode()) {
          arg0 = get_fpu_register_word(f12);
          arg1 = get_fpu_register_hi_word(f12);
        } else {
          arg0 = get_fpu_register_word(f12);
          arg1 = get_fpu_register_word(f13);
        }
1638 1639 1640 1641 1642 1643 1644
        arg2 = get_register(a2);
        break;
      default:
        break;
      }
    }

1645 1646 1647
    // This is dodgy but it works because the C entry stubs are never moved.
    // See comment in codegen-arm.cc and bug 1242173.
    int32_t saved_ra = get_register(ra);
1648 1649

    intptr_t external =
1650
          reinterpret_cast<intptr_t>(redirection->external_function());
1651 1652 1653 1654

    // Based on CpuFeatures::IsSupported(FPU), Mips will use either hardware
    // FPU, or gcc soft-float routines. Hardware FPU is simulated in this
    // simulator. Soft-float has additional abstraction of ExternalReference,
1655
    // to support serialization.
1656
    if (fp_call) {
1657 1658 1659 1660 1661 1662 1663
      double dval0, dval1;  // one or two double parameters
      int32_t ival;         // zero or one integer parameters
      int64_t iresult = 0;  // integer return value
      double dresult = 0;   // double return value
      GetFpArgs(&dval0, &dval1, &ival);
      SimulatorRuntimeCall generic_target =
          reinterpret_cast<SimulatorRuntimeCall>(external);
1664
      if (::v8::internal::FLAG_trace_sim) {
1665 1666 1667 1668
        switch (redirection->type()) {
          case ExternalReference::BUILTIN_FP_FP_CALL:
          case ExternalReference::BUILTIN_COMPARE_CALL:
            PrintF("Call to host function at %p with args %f, %f",
1669
                   FUNCTION_ADDR(generic_target), dval0, dval1);
1670 1671 1672
            break;
          case ExternalReference::BUILTIN_FP_CALL:
            PrintF("Call to host function at %p with arg %f",
1673
                FUNCTION_ADDR(generic_target), dval0);
1674 1675 1676
            break;
          case ExternalReference::BUILTIN_FP_INT_CALL:
            PrintF("Call to host function at %p with args %f, %d",
1677
                   FUNCTION_ADDR(generic_target), dval0, ival);
1678 1679 1680 1681 1682 1683
            break;
          default:
            UNREACHABLE();
            break;
        }
      }
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
      switch (redirection->type()) {
      case ExternalReference::BUILTIN_COMPARE_CALL: {
        SimulatorRuntimeCompareCall target =
          reinterpret_cast<SimulatorRuntimeCompareCall>(external);
        iresult = target(dval0, dval1);
        set_register(v0, static_cast<int32_t>(iresult));
        set_register(v1, static_cast<int32_t>(iresult >> 32));
        break;
      }
      case ExternalReference::BUILTIN_FP_FP_CALL: {
        SimulatorRuntimeFPFPCall target =
          reinterpret_cast<SimulatorRuntimeFPFPCall>(external);
        dresult = target(dval0, dval1);
        SetFpResult(dresult);
        break;
      }
      case ExternalReference::BUILTIN_FP_CALL: {
1701
        SimulatorRuntimeFPCall target =
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
          reinterpret_cast<SimulatorRuntimeFPCall>(external);
        dresult = target(dval0);
        SetFpResult(dresult);
        break;
      }
      case ExternalReference::BUILTIN_FP_INT_CALL: {
        SimulatorRuntimeFPIntCall target =
          reinterpret_cast<SimulatorRuntimeFPIntCall>(external);
        dresult = target(dval0, ival);
        SetFpResult(dresult);
        break;
      }
      default:
        UNREACHABLE();
        break;
      }
      if (::v8::internal::FLAG_trace_sim) {
        switch (redirection->type()) {
        case ExternalReference::BUILTIN_COMPARE_CALL:
          PrintF("Returned %08x\n", static_cast<int32_t>(iresult));
          break;
        case ExternalReference::BUILTIN_FP_FP_CALL:
        case ExternalReference::BUILTIN_FP_CALL:
        case ExternalReference::BUILTIN_FP_INT_CALL:
          PrintF("Returned %f\n", dresult);
          break;
        default:
          UNREACHABLE();
          break;
        }
1732
      }
1733 1734 1735 1736
    } else if (redirection->type() == ExternalReference::DIRECT_API_CALL) {
      if (::v8::internal::FLAG_trace_sim) {
        PrintF("Call to host function at %p args %08x\n",
            reinterpret_cast<void*>(external), arg0);
1737
      }
1738 1739 1740
      SimulatorRuntimeDirectApiCall target =
          reinterpret_cast<SimulatorRuntimeDirectApiCall>(external);
      target(arg0);
1741
    } else if (
1742 1743 1744 1745
        redirection->type() == ExternalReference::PROFILING_API_CALL) {
      if (::v8::internal::FLAG_trace_sim) {
        PrintF("Call to host function at %p args %08x %08x\n",
            reinterpret_cast<void*>(external), arg0, arg1);
1746
      }
1747 1748
      SimulatorRuntimeProfilingApiCall target =
          reinterpret_cast<SimulatorRuntimeProfilingApiCall>(external);
1749
      target(arg0, Redirection::ReverseRedirection(arg1));
1750
    } else if (
1751 1752 1753 1754
        redirection->type() == ExternalReference::DIRECT_GETTER_CALL) {
      if (::v8::internal::FLAG_trace_sim) {
        PrintF("Call to host function at %p args %08x %08x\n",
            reinterpret_cast<void*>(external), arg0, arg1);
1755
      }
1756 1757 1758
      SimulatorRuntimeDirectGetterCall target =
          reinterpret_cast<SimulatorRuntimeDirectGetterCall>(external);
      target(arg0, arg1);
1759
    } else if (
1760 1761 1762 1763
        redirection->type() == ExternalReference::PROFILING_GETTER_CALL) {
      if (::v8::internal::FLAG_trace_sim) {
        PrintF("Call to host function at %p args %08x %08x %08x\n",
            reinterpret_cast<void*>(external), arg0, arg1, arg2);
1764
      }
1765 1766
      SimulatorRuntimeProfilingGetterCall target =
          reinterpret_cast<SimulatorRuntimeProfilingGetterCall>(external);
1767
      target(arg0, arg1, Redirection::ReverseRedirection(arg2));
1768 1769
    } else {
      SimulatorRuntimeCall target =
1770 1771
                  reinterpret_cast<SimulatorRuntimeCall>(external);
      if (::v8::internal::FLAG_trace_sim) {
1772
        PrintF(
1773 1774
            "Call to host function at %p "
            "args %08x, %08x, %08x, %08x, %08x, %08x\n",
1775 1776 1777 1778
            FUNCTION_ADDR(target),
            arg0,
            arg1,
            arg2,
1779 1780 1781
            arg3,
            arg4,
            arg5);
1782
      }
1783 1784 1785 1786 1787 1788
      int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5);
      set_register(v0, static_cast<int32_t>(result));
      set_register(v1, static_cast<int32_t>(result >> 32));
    }
    if (::v8::internal::FLAG_trace_sim) {
      PrintF("Returned %08x : %08x\n", get_register(v1), get_register(v0));
1789 1790 1791
    }
    set_register(ra, saved_ra);
    set_pc(get_register(ra));
1792

1793 1794 1795 1796 1797 1798 1799
  } else if (func == BREAK && code <= kMaxStopCode) {
    if (IsWatchpoint(code)) {
      PrintWatchpoint(code);
    } else {
      IncreaseStopCounter(code);
      HandleStop(code, instr);
    }
1800
  } else {
1801 1802
    // All remaining break_ codes, and all traps are handled here.
    MipsDebugger dbg(this);
1803 1804 1805 1806
    dbg.Debug();
  }
}

1807

1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
// Stop helper functions.
bool Simulator::IsWatchpoint(uint32_t code) {
  return (code <= kMaxWatchpointCode);
}


void Simulator::PrintWatchpoint(uint32_t code) {
  MipsDebugger dbg(this);
  ++break_count_;
  PrintF("\n---- break %d marker: %3d  (instr count: %8d) ----------"
         "----------------------------------",
         code, break_count_, icount_);
  dbg.PrintAllRegs();  // Print registers and continue running.
}


void Simulator::HandleStop(uint32_t code, Instruction* instr) {
  // Stop if it is enabled, otherwise go on jumping over the stop
  // and the message address.
  if (IsEnabledStop(code)) {
    MipsDebugger dbg(this);
    dbg.Stop(instr);
  } else {
    set_pc(get_pc() + 2 * Instruction::kInstrSize);
  }
}


bool Simulator::IsStopInstruction(Instruction* instr) {
  int32_t func = instr->FunctionFieldRaw();
  uint32_t code = static_cast<uint32_t>(instr->Bits(25, 6));
  return (func == BREAK) && code > kMaxWatchpointCode && code <= kMaxStopCode;
}


bool Simulator::IsEnabledStop(uint32_t code) {
1844 1845
  DCHECK(code <= kMaxStopCode);
  DCHECK(code > kMaxWatchpointCode);
1846
  return !(watched_stops_[code].count & kStopDisabledBit);
1847 1848 1849 1850 1851
}


void Simulator::EnableStop(uint32_t code) {
  if (!IsEnabledStop(code)) {
1852
    watched_stops_[code].count &= ~kStopDisabledBit;
1853 1854 1855 1856 1857 1858
  }
}


void Simulator::DisableStop(uint32_t code) {
  if (IsEnabledStop(code)) {
1859
    watched_stops_[code].count |= kStopDisabledBit;
1860 1861 1862 1863 1864
  }
}


void Simulator::IncreaseStopCounter(uint32_t code) {
1865
  DCHECK(code <= kMaxStopCode);
1866
  if ((watched_stops_[code].count & ~(1 << 31)) == 0x7fffffff) {
1867 1868
    PrintF("Stop counter for code %i has overflowed.\n"
           "Enabling this code and reseting the counter to 0.\n", code);
1869
    watched_stops_[code].count = 0;
1870 1871
    EnableStop(code);
  } else {
1872
    watched_stops_[code].count++;
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
  }
}


// Print a stop status.
void Simulator::PrintStopInfo(uint32_t code) {
  if (code <= kMaxWatchpointCode) {
    PrintF("That is a watchpoint, not a stop.\n");
    return;
  } else if (code > kMaxStopCode) {
    PrintF("Code too large, only %u stops can be used\n", kMaxStopCode + 1);
    return;
  }
  const char* state = IsEnabledStop(code) ? "Enabled" : "Disabled";
1887
  int32_t count = watched_stops_[code].count & ~kStopDisabledBit;
1888 1889
  // Don't print the state of unused breakpoints.
  if (count != 0) {
1890
    if (watched_stops_[code].desc) {
1891
      PrintF("stop %i - 0x%x: \t%s, \tcounter = %i, \t%s\n",
1892
             code, code, state, count, watched_stops_[code].desc);
1893 1894 1895 1896 1897 1898 1899 1900
    } else {
      PrintF("stop %i - 0x%x: \t%s, \tcounter = %i\n",
             code, code, state, count);
    }
  }
}


1901 1902 1903 1904 1905 1906 1907 1908 1909
void Simulator::SignalExceptions() {
  for (int i = 1; i < kNumExceptions; i++) {
    if (exceptions[i] != 0) {
      V8_Fatal(__FILE__, __LINE__, "Error: Exception %i raised.", i);
    }
  }
}


1910
// Handle execution based on instruction types.
1911

1912
void Simulator::ConfigureTypeRegister(Instruction* instr,
1913 1914 1915 1916 1917 1918
                                      int32_t* alu_out,
                                      int64_t* i64hilo,
                                      uint64_t* u64hilo,
                                      int32_t* next_pc,
                                      int32_t* return_addr_reg,
                                      bool* do_interrupt) {
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
  // Every local variable declared here needs to be const.
  // This is to make sure that changed values are sent back to
  // DecodeTypeRegister correctly.

  // Instruction fields.
  const Opcode   op     = instr->OpcodeFieldRaw();
  const int32_t  rs_reg = instr->RsValue();
  const int32_t  rs     = get_register(rs_reg);
  const uint32_t rs_u   = static_cast<uint32_t>(rs);
  const int32_t  rt_reg = instr->RtValue();
  const int32_t  rt     = get_register(rt_reg);
  const uint32_t rt_u   = static_cast<uint32_t>(rt);
  const int32_t  rd_reg = instr->RdValue();
  const uint32_t sa     = instr->SaValue();

  const int32_t  fs_reg = instr->FsValue();
1935 1936


1937
  // ---------- Configuration.
1938
  switch (op) {
1939
    case COP1:    // Coprocessor instructions.
1940
      switch (instr->RsFieldRaw()) {
1941 1942
        case CFC1:
          // At the moment only FCSR is supported.
1943
          DCHECK(fs_reg == kFCSRRegister);
1944
          *alu_out = FCSR_;
1945
          break;
1946
        case MFC1:
1947
          *alu_out = get_fpu_register_word(fs_reg);
1948 1949
          break;
        case MFHC1:
1950
          *alu_out = get_fpu_register_hi_word(fs_reg);
1951
          break;
1952
        case CTC1:
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
        case MTC1:
        case MTHC1:
        case S:
        case D:
        case W:
        case L:
        case PS:
          // Do everything in the execution step.
          break;
        default:
1963 1964
        // BC1 BC1EQZ BC1NEZ handled in DecodeTypeImmed, should never come here.
          UNREACHABLE();
1965
      }
1966
      break;
1967 1968
    case COP1X:
      break;
1969 1970 1971 1972
    case SPECIAL:
      switch (instr->FunctionFieldRaw()) {
        case JR:
        case JALR:
1973 1974
          *next_pc = get_register(instr->RsValue());
          *return_addr_reg = instr->RdValue();
1975 1976
          break;
        case SLL:
1977
          *alu_out = rt << sa;
1978 1979
          break;
        case SRL:
1980 1981 1982
          if (rs_reg == 0) {
            // Regular logical right shift of a word by a fixed number of
            // bits instruction. RS field is always equal to 0.
1983
            *alu_out = rt_u >> sa;
1984 1985 1986
          } else {
            // Logical right-rotate of a word by a fixed number of bits. This
            // is special case of SRL instruction, added in MIPS32 Release 2.
1987
            // RS field is equal to 00001.
1988
            *alu_out = base::bits::RotateRight32(rt_u, sa);
1989
          }
1990 1991
          break;
        case SRA:
1992
          *alu_out = rt >> sa;
1993 1994
          break;
        case SLLV:
1995
          *alu_out = rt << rs;
1996 1997
          break;
        case SRLV:
1998 1999 2000
          if (sa == 0) {
            // Regular logical right-shift of a word by a variable number of
            // bits instruction. SA field is always equal to 0.
2001
            *alu_out = rt_u >> rs;
2002 2003 2004
          } else {
            // Logical right-rotate of a word by a variable number of bits.
            // This is special case od SRLV instruction, added in MIPS32
2005
            // Release 2. SA field is equal to 00001.
2006
            *alu_out = base::bits::RotateRight32(rt_u, rs_u);
2007
          }
2008 2009
          break;
        case SRAV:
2010
          *alu_out = rt >> rs;
2011
          break;
2012 2013 2014 2015 2016 2017 2018 2019
        case MFHI:  // MFHI == CLZ on R6.
          if (!IsMipsArchVariant(kMips32r6)) {
            DCHECK(instr->SaValue() == 0);
            *alu_out = get_register(HI);
          } else {
            // MIPS spec: If no bits were set in GPR rs, the result written to
            // GPR rd is 32.
            DCHECK(instr->SaValue() == 1);
2020
            *alu_out = base::bits::CountLeadingZeros32(rs_u);
2021
          }
2022 2023
          break;
        case MFLO:
2024
          *alu_out = get_register(LO);
2025
          break;
2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
        case MULT:  // MULT == MUL_MUH.
          if (!IsMipsArchVariant(kMips32r6)) {
            *i64hilo = static_cast<int64_t>(rs) * static_cast<int64_t>(rt);
          } else {
            switch (instr->SaValue()) {
              case MUL_OP:
              case MUH_OP:
                *i64hilo = static_cast<int64_t>(rs) * static_cast<int64_t>(rt);
                break;
              default:
                UNIMPLEMENTED_MIPS();
                break;
            }
          }
2040
          break;
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
        case MULTU:  // MULTU == MUL_MUH_U.
          if (!IsMipsArchVariant(kMips32r6)) {
            *u64hilo = static_cast<uint64_t>(rs_u) *
                static_cast<uint64_t>(rt_u);
          } else {
            switch (instr->SaValue()) {
              case MUL_OP:
              case MUH_OP:
                *u64hilo = static_cast<uint64_t>(rs_u) *
                    static_cast<uint64_t>(rt_u);
                break;
              default:
                UNIMPLEMENTED_MIPS();
                break;
            }
          }
2057 2058 2059 2060 2061 2062 2063 2064 2065
          break;
        case ADD:
          if (HaveSameSign(rs, rt)) {
            if (rs > 0) {
              exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue - rt);
            } else if (rs < 0) {
              exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue - rt);
            }
          }
2066
          *alu_out = rs + rt;
2067 2068
          break;
        case ADDU:
2069
          *alu_out = rs + rt;
2070 2071 2072 2073 2074 2075 2076 2077 2078
          break;
        case SUB:
          if (!HaveSameSign(rs, rt)) {
            if (rs > 0) {
              exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue + rt);
            } else if (rs < 0) {
              exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue + rt);
            }
          }
2079
          *alu_out = rs - rt;
2080 2081
          break;
        case SUBU:
2082
          *alu_out = rs - rt;
2083 2084
          break;
        case AND:
2085
          *alu_out = rs & rt;
2086 2087
          break;
        case OR:
2088
          *alu_out = rs | rt;
2089 2090
          break;
        case XOR:
2091
          *alu_out = rs ^ rt;
2092 2093
          break;
        case NOR:
2094
          *alu_out = ~(rs | rt);
2095 2096
          break;
        case SLT:
2097
          *alu_out = rs < rt ? 1 : 0;
2098 2099
          break;
        case SLTU:
2100
          *alu_out = rs_u < rt_u ? 1 : 0;
2101
          break;
2102
        // Break and trap instructions.
2103
        case BREAK:
2104
          *do_interrupt = true;
2105 2106
          break;
        case TGE:
2107
          *do_interrupt = rs >= rt;
2108 2109
          break;
        case TGEU:
2110
          *do_interrupt = rs_u >= rt_u;
2111 2112
          break;
        case TLT:
2113
          *do_interrupt = rs < rt;
2114 2115
          break;
        case TLTU:
2116
          *do_interrupt = rs_u < rt_u;
2117 2118
          break;
        case TEQ:
2119
          *do_interrupt = rs == rt;
2120 2121
          break;
        case TNE:
2122
          *do_interrupt = rs != rt;
2123
          break;
2124 2125 2126 2127 2128
        case MOVN:
        case MOVZ:
        case MOVCI:
          // No action taken on decode.
          break;
2129 2130 2131
        case DIV:
        case DIVU:
          // div and divu never raise exceptions.
2132 2133
        case SELEQZ_S:
        case SELNEZ_S:
2134
          break;
2135 2136
        default:
          UNREACHABLE();
2137
      }
2138 2139 2140 2141
      break;
    case SPECIAL2:
      switch (instr->FunctionFieldRaw()) {
        case MUL:
2142
          *alu_out = rs_u * rt_u;  // Only the lower 32 bits are kept.
2143
          break;
2144
        case CLZ:
2145 2146
          // MIPS32 spec: If no bits were set in GPR rs, the result written to
          // GPR rd is 32.
2147
          *alu_out = base::bits::CountLeadingZeros32(rs_u);
2148
          break;
2149 2150
        default:
          UNREACHABLE();
2151
      }
2152 2153 2154 2155
      break;
    case SPECIAL3:
      switch (instr->FunctionFieldRaw()) {
        case INS: {   // Mips32r2 instruction.
2156
          // Interpret rd field as 5-bit msb of insert.
2157 2158 2159 2160 2161
          uint16_t msb = rd_reg;
          // Interpret sa field as 5-bit lsb of insert.
          uint16_t lsb = sa;
          uint16_t size = msb - lsb + 1;
          uint32_t mask = (1 << size) - 1;
2162
          *alu_out = (rt_u & ~(mask << lsb)) | ((rs_u & mask) << lsb);
2163 2164 2165
          break;
        }
        case EXT: {   // Mips32r2 instruction.
2166
          // Interpret rd field as 5-bit msb of extract.
2167 2168 2169 2170 2171
          uint16_t msb = rd_reg;
          // Interpret sa field as 5-bit lsb of extract.
          uint16_t lsb = sa;
          uint16_t size = msb + 1;
          uint32_t mask = (1 << size) - 1;
2172
          *alu_out = (rs_u & (mask << lsb)) >> lsb;
2173 2174 2175 2176
          break;
        }
        default:
          UNREACHABLE();
2177
      }
2178 2179 2180
      break;
    default:
      UNREACHABLE();
2181
  }
2182 2183 2184
}


2185 2186 2187 2188 2189
void Simulator::DecodeTypeRegisterDRsType(Instruction* instr,
                                          const int32_t& fr_reg,
                                          const int32_t& fs_reg,
                                          const int32_t& ft_reg,
                                          const int32_t& fd_reg) {
2190
  double ft, fs, fd;
2191 2192 2193
  uint32_t cc, fcsr_cc;
  int64_t i64;
  fs = get_fpu_register_double(fs_reg);
2194
  ft = get_fpu_register_double(ft_reg);
2195 2196
  int64_t ft_int = bit_cast<int64_t>(ft);
  int64_t fd_int = bit_cast<int64_t>(fd);
2197 2198 2199
  cc = instr->FCccValue();
  fcsr_cc = get_fcsr_condition_bit(cc);
  switch (instr->FunctionFieldRaw()) {
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
    case RINT: {
      DCHECK(IsMipsArchVariant(kMips32r6));
      double result, temp, temp_result;
      double upper = std::ceil(fs);
      double lower = std::floor(fs);
      switch (get_fcsr_rounding_mode()) {
        case kRoundToNearest:
          if (upper - fs < fs - lower) {
            result = upper;
          } else if (upper - fs > fs - lower) {
            result = lower;
          } else {
            temp_result = upper / 2;
            double reminder = modf(temp_result, &temp);
            if (reminder == 0) {
              result = upper;
            } else {
              result = lower;
            }
          }
          break;
        case kRoundToZero:
          result = (fs > 0 ? lower : upper);
          break;
        case kRoundToPlusInf:
          result = upper;
          break;
        case kRoundToMinusInf:
          result = lower;
          break;
      }
      set_fpu_register_double(fd_reg, result);
      if (result != fs) {
        set_fcsr_bit(kFCSRInexactFlagBit, true);
      }
      break;
    }
2237 2238 2239 2240
    case SEL:
      DCHECK(IsMipsArchVariant(kMips32r6));
      set_fpu_register_double(fd_reg, (fd_int & 0x1) == 0 ? fs : ft);
      break;
2241 2242 2243 2244 2245 2246 2247 2248
    case SELEQZ_C:
      DCHECK(IsMipsArchVariant(kMips32r6));
      set_fpu_register_double(fd_reg, (ft_int & 0x1) == 0 ? fs : 0.0);
      break;
    case SELNEZ_C:
      DCHECK(IsMipsArchVariant(kMips32r6));
      set_fpu_register_double(fd_reg, (ft_int & 0x1) != 0 ? fs : 0.0);
      break;
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
    case MIN:
      DCHECK(IsMipsArchVariant(kMips32r6));
      fs = get_fpu_register_double(fs_reg);
      if (std::isnan(fs) && std::isnan(ft)) {
        set_fpu_register_double(fd_reg, fs);
      } else if (std::isnan(fs) && !std::isnan(ft)) {
        set_fpu_register_double(fd_reg, ft);
      } else if (!std::isnan(fs) && std::isnan(ft)) {
        set_fpu_register_double(fd_reg, fs);
      } else {
        set_fpu_register_double(fd_reg, (fs >= ft) ? ft : fs);
      }
      break;
    case MAX:
      DCHECK(IsMipsArchVariant(kMips32r6));
      fs = get_fpu_register_double(fs_reg);
      if (std::isnan(fs) && std::isnan(ft)) {
        set_fpu_register_double(fd_reg, fs);
      } else if (std::isnan(fs) && !std::isnan(ft)) {
        set_fpu_register_double(fd_reg, ft);
      } else if (!std::isnan(fs) && std::isnan(ft)) {
        set_fpu_register_double(fd_reg, fs);
      } else {
        set_fpu_register_double(fd_reg, (fs <= ft) ? ft : fs);
      }
      break;
      break;
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
    case ADD_D:
      set_fpu_register_double(fd_reg, fs + ft);
      break;
    case SUB_D:
      set_fpu_register_double(fd_reg, fs - ft);
      break;
    case MUL_D:
      set_fpu_register_double(fd_reg, fs * ft);
      break;
    case DIV_D:
      set_fpu_register_double(fd_reg, fs / ft);
      break;
    case ABS_D:
      set_fpu_register_double(fd_reg, fabs(fs));
      break;
    case MOV_D:
      set_fpu_register_double(fd_reg, fs);
      break;
    case NEG_D:
      set_fpu_register_double(fd_reg, -fs);
      break;
    case SQRT_D:
      set_fpu_register_double(fd_reg, fast_sqrt(fs));
      break;
    case C_UN_D:
      set_fcsr_bit(fcsr_cc, std::isnan(fs) || std::isnan(ft));
      break;
    case C_EQ_D:
      set_fcsr_bit(fcsr_cc, (fs == ft));
      break;
    case C_UEQ_D:
      set_fcsr_bit(fcsr_cc, (fs == ft) || (std::isnan(fs) || std::isnan(ft)));
      break;
    case C_OLT_D:
      set_fcsr_bit(fcsr_cc, (fs < ft));
      break;
    case C_ULT_D:
      set_fcsr_bit(fcsr_cc, (fs < ft) || (std::isnan(fs) || std::isnan(ft)));
      break;
    case C_OLE_D:
      set_fcsr_bit(fcsr_cc, (fs <= ft));
      break;
    case C_ULE_D:
      set_fcsr_bit(fcsr_cc, (fs <= ft) || (std::isnan(fs) || std::isnan(ft)));
      break;
2321 2322 2323 2324 2325 2326 2327 2328 2329
    case CVT_W_D: {  // Convert double to word.
      double rounded;
      int32_t result;
      round_according_to_fcsr(fs, rounded, result, fs);
      set_fpu_register_word(fd_reg, result);
      if (set_fcsr_round_error(fs, rounded)) {
        set_fpu_register_word(fd_reg, kFPUInvalidResult);
      }
    } break;
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
    case ROUND_W_D:  // Round double to word (round half to even).
    {
      double rounded = std::floor(fs + 0.5);
      int32_t result = static_cast<int32_t>(rounded);
      if ((result & 1) != 0 && result - fs == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        result--;
      }
      set_fpu_register_word(fd_reg, result);
      if (set_fcsr_round_error(fs, rounded)) {
        set_fpu_register_word(fd_reg, kFPUInvalidResult);
      }
    } break;
    case TRUNC_W_D:  // Truncate double to word (round towards 0).
    {
      double rounded = trunc(fs);
      int32_t result = static_cast<int32_t>(rounded);
      set_fpu_register_word(fd_reg, result);
      if (set_fcsr_round_error(fs, rounded)) {
        set_fpu_register_word(fd_reg, kFPUInvalidResult);
      }
    } break;
    case FLOOR_W_D:  // Round double to word towards negative infinity.
    {
      double rounded = std::floor(fs);
      int32_t result = static_cast<int32_t>(rounded);
      set_fpu_register_word(fd_reg, result);
      if (set_fcsr_round_error(fs, rounded)) {
        set_fpu_register_word(fd_reg, kFPUInvalidResult);
      }
    } break;
    case CEIL_W_D:  // Round double to word towards positive infinity.
    {
      double rounded = std::ceil(fs);
      int32_t result = static_cast<int32_t>(rounded);
      set_fpu_register_word(fd_reg, result);
      if (set_fcsr_round_error(fs, rounded)) {
        set_fpu_register_word(fd_reg, kFPUInvalidResult);
      }
    } break;
    case CVT_S_D:  // Convert double to float (single).
      set_fpu_register_float(fd_reg, static_cast<float>(fs));
      break;
    case CVT_L_D: {  // Mips32r2: Truncate double to 64-bit long-word.
      double rounded = trunc(fs);
      i64 = static_cast<int64_t>(rounded);
      if (IsFp64Mode()) {
        set_fpu_register(fd_reg, i64);
      } else {
2380 2381
        set_fpu_register_word(fd_reg, i64 & 0xffffffff);
        set_fpu_register_word(fd_reg + 1, i64 >> 32);
2382 2383 2384 2385 2386 2387 2388 2389 2390
      }
      break;
    }
    case TRUNC_L_D: {  // Mips32r2 instruction.
      double rounded = trunc(fs);
      i64 = static_cast<int64_t>(rounded);
      if (IsFp64Mode()) {
        set_fpu_register(fd_reg, i64);
      } else {
2391 2392
        set_fpu_register_word(fd_reg, i64 & 0xffffffff);
        set_fpu_register_word(fd_reg + 1, i64 >> 32);
2393 2394 2395 2396
      }
      break;
    }
    case ROUND_L_D: {  // Mips32r2 instruction.
2397 2398
      double rounded = fs > 0 ? std::floor(fs + 0.5) : std::ceil(fs - 0.5);
      i64 = static_cast<int64_t>(rounded);
2399 2400 2401
      if (IsFp64Mode()) {
        set_fpu_register(fd_reg, i64);
      } else {
2402 2403
        set_fpu_register_word(fd_reg, i64 & 0xffffffff);
        set_fpu_register_word(fd_reg + 1, i64 >> 32);
2404 2405 2406
      }
      break;
    }
2407 2408
    case FLOOR_L_D:  // Mips32r2 instruction.
      i64 = static_cast<int64_t>(std::floor(fs));
2409 2410 2411
      if (IsFp64Mode()) {
        set_fpu_register(fd_reg, i64);
      } else {
2412 2413
        set_fpu_register_word(fd_reg, i64 & 0xffffffff);
        set_fpu_register_word(fd_reg + 1, i64 >> 32);
2414 2415
      }
      break;
2416 2417
    case CEIL_L_D:  // Mips32r2 instruction.
      i64 = static_cast<int64_t>(std::ceil(fs));
2418 2419 2420
      if (IsFp64Mode()) {
        set_fpu_register(fd_reg, i64);
      } else {
2421 2422
        set_fpu_register_word(fd_reg, i64 & 0xffffffff);
        set_fpu_register_word(fd_reg + 1, i64 >> 32);
2423 2424 2425 2426 2427 2428 2429 2430 2431
      }
      break;
    case C_F_D:
      UNIMPLEMENTED_MIPS();
      break;
    default:
      UNREACHABLE();
  }
}
2432 2433


2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
void Simulator::DecodeTypeRegisterWRsType(Instruction* instr, int32_t& alu_out,
                                          const int32_t& fd_reg,
                                          const int32_t& fs_reg) {
  switch (instr->FunctionFieldRaw()) {
    case CVT_S_W:  // Convert word to float (single).
      alu_out = get_fpu_register_signed_word(fs_reg);
      set_fpu_register_float(fd_reg, static_cast<float>(alu_out));
      break;
    case CVT_D_W:  // Convert word to double.
      alu_out = get_fpu_register_signed_word(fs_reg);
      set_fpu_register_double(fd_reg, static_cast<double>(alu_out));
      break;
    default:  // Mips64r6 CMP.S instructions unimplemented.
      UNREACHABLE();
  }
}
2450 2451


2452 2453 2454 2455
void Simulator::DecodeTypeRegisterSRsType(Instruction* instr,
                                          const int32_t& ft_reg,
                                          const int32_t& fs_reg,
                                          const int32_t& fd_reg) {
2456
  float fs, ft;
2457 2458
  fs = get_fpu_register_float(fs_reg);
  ft = get_fpu_register_float(ft_reg);
2459
  int64_t ft_int = static_cast<int64_t>(get_fpu_register_double(ft_reg));
2460 2461 2462
  uint32_t cc, fcsr_cc;
  cc = instr->FCccValue();
  fcsr_cc = get_fcsr_condition_bit(cc);
2463
  switch (instr->FunctionFieldRaw()) {
2464
    case ADD_D:
2465 2466
      set_fpu_register_float(fd_reg, fs + ft);
      break;
2467
    case SUB_D:
2468 2469
      set_fpu_register_float(fd_reg, fs - ft);
      break;
2470
    case MUL_D:
2471 2472
      set_fpu_register_float(fd_reg, fs * ft);
      break;
2473
    case DIV_D:
2474 2475
      set_fpu_register_float(fd_reg, fs / ft);
      break;
2476
    case ABS_D:
2477 2478
      set_fpu_register_float(fd_reg, fabs(fs));
      break;
2479
    case MOV_D:
2480 2481
      set_fpu_register_float(fd_reg, fs);
      break;
2482
    case NEG_D:
2483 2484
      set_fpu_register_float(fd_reg, -fs);
      break;
2485
    case SQRT_D:
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
      set_fpu_register_float(fd_reg, fast_sqrt(fs));
      break;
    case C_UN_D:
      set_fcsr_bit(fcsr_cc, std::isnan(fs) || std::isnan(ft));
      break;
    case C_EQ_D:
      set_fcsr_bit(fcsr_cc, (fs == ft));
      break;
    case C_UEQ_D:
      set_fcsr_bit(fcsr_cc, (fs == ft) || (std::isnan(fs) || std::isnan(ft)));
      break;
    case C_OLT_D:
      set_fcsr_bit(fcsr_cc, (fs < ft));
      break;
    case C_ULT_D:
      set_fcsr_bit(fcsr_cc, (fs < ft) || (std::isnan(fs) || std::isnan(ft)));
      break;
    case C_OLE_D:
      set_fcsr_bit(fcsr_cc, (fs <= ft));
      break;
    case C_ULE_D:
      set_fcsr_bit(fcsr_cc, (fs <= ft) || (std::isnan(fs) || std::isnan(ft)));
      break;
2509
    case CVT_D_S:
2510
      set_fpu_register_double(fd_reg, static_cast<double>(fs));
2511 2512 2513
      break;
    case SELEQZ_C:
      DCHECK(IsMipsArchVariant(kMips32r6));
2514 2515
      set_fpu_register_double(
          fd_reg, (ft_int & 0x1) == 0 ? get_fpu_register_double(fs_reg) : 0.0);
2516 2517 2518
      break;
    case SELNEZ_C:
      DCHECK(IsMipsArchVariant(kMips32r6));
2519 2520
      set_fpu_register_double(
          fd_reg, (ft_int & 0x1) != 0 ? get_fpu_register_double(fs_reg) : 0.0);
2521 2522
      break;
    default:
2523
      // CVT_W_S CVT_L_S TRUNC_W_S ROUND_W_S ROUND_L_S FLOOR_W_S FLOOR_L_S
2524 2525 2526 2527
      // CEIL_W_S CEIL_L_S CVT_PS_S are unimplemented.
      UNREACHABLE();
  }
}
2528 2529


2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
void Simulator::DecodeTypeRegisterLRsType(Instruction* instr,
                                          const int32_t& ft_reg,
                                          const int32_t& fs_reg,
                                          const int32_t& fd_reg) {
  double fs = get_fpu_register_double(fs_reg);
  double ft = get_fpu_register_double(ft_reg);
  switch (instr->FunctionFieldRaw()) {
    case CVT_D_L:  // Mips32r2 instruction.
      // Watch the signs here, we want 2 32-bit vals
      // to make a sign-64.
      int64_t i64;
      if (IsFp64Mode()) {
        i64 = get_fpu_register(fs_reg);
      } else {
        i64 = static_cast<uint32_t>(get_fpu_register_word(fs_reg));
        i64 |= static_cast<int64_t>(get_fpu_register_word(fs_reg + 1)) << 32;
2546
      }
2547
      set_fpu_register_double(fd_reg, static_cast<double>(i64));
2548
      break;
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559
    case CVT_S_L:
      UNIMPLEMENTED_MIPS();
      break;
    case CMP_AF:  // Mips64r6 CMP.D instructions.
      UNIMPLEMENTED_MIPS();
      break;
    case CMP_UN:
      if (std::isnan(fs) || std::isnan(ft)) {
        set_fpu_register(fd_reg, -1);
      } else {
        set_fpu_register(fd_reg, 0);
2560
      }
2561
      break;
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
    case CMP_EQ:
      if (fs == ft) {
        set_fpu_register(fd_reg, -1);
      } else {
        set_fpu_register(fd_reg, 0);
      }
      break;
    case CMP_UEQ:
      if ((fs == ft) || (std::isnan(fs) || std::isnan(ft))) {
        set_fpu_register(fd_reg, -1);
      } else {
        set_fpu_register(fd_reg, 0);
      }
      break;
    case CMP_LT:
      if (fs < ft) {
        set_fpu_register(fd_reg, -1);
      } else {
        set_fpu_register(fd_reg, 0);
      }
      break;
    case CMP_ULT:
      if ((fs < ft) || (std::isnan(fs) || std::isnan(ft))) {
        set_fpu_register(fd_reg, -1);
      } else {
        set_fpu_register(fd_reg, 0);
      }
      break;
    case CMP_LE:
      if (fs <= ft) {
        set_fpu_register(fd_reg, -1);
      } else {
        set_fpu_register(fd_reg, 0);
      }
      break;
    case CMP_ULE:
      if ((fs <= ft) || (std::isnan(fs) || std::isnan(ft))) {
        set_fpu_register(fd_reg, -1);
      } else {
        set_fpu_register(fd_reg, 0);
      }
      break;
    default:  // CMP_OR CMP_UNE CMP_NE UNIMPLEMENTED.
      UNREACHABLE();
  }
}


void Simulator::DecodeTypeRegisterCOP1(
    Instruction* instr, const int32_t& rs_reg, const int32_t& rs,
    const uint32_t& rs_u, const int32_t& rt_reg, const int32_t& rt,
    const uint32_t& rt_u, const int32_t& rd_reg, const int32_t& fr_reg,
    const int32_t& fs_reg, const int32_t& ft_reg, const int32_t& fd_reg,
    int64_t& i64hilo, uint64_t& u64hilo, int32_t& alu_out, bool& do_interrupt,
    int32_t& current_pc, int32_t& next_pc, int32_t& return_addr_reg) {
  switch (instr->RsFieldRaw()) {
    case CFC1:
      set_register(rt_reg, alu_out);
      break;
    case MFC1:
      set_register(rt_reg, alu_out);
      break;
    case MFHC1:
      set_register(rt_reg, alu_out);
      break;
    case CTC1:
      // At the moment only FCSR is supported.
      DCHECK(fs_reg == kFCSRRegister);
      FCSR_ = registers_[rt_reg];
      break;
    case MTC1:
      // Hardware writes upper 32-bits to zero on mtc1.
      set_fpu_register_hi_word(fs_reg, 0);
      set_fpu_register_word(fs_reg, registers_[rt_reg]);
      break;
    case MTHC1:
      set_fpu_register_hi_word(fs_reg, registers_[rt_reg]);
      break;
    case S: {
      DecodeTypeRegisterSRsType(instr, ft_reg, fs_reg, fd_reg);
      break;
    }
    case D:
      DecodeTypeRegisterDRsType(instr, fr_reg, fs_reg, ft_reg, fd_reg);
      break;
    case W:
      DecodeTypeRegisterWRsType(instr, alu_out, fd_reg, fs_reg);
      break;
    case L:
      DecodeTypeRegisterLRsType(instr, ft_reg, fs_reg, fd_reg);
      break;
    default:
      UNREACHABLE();
  }
}


void Simulator::DecodeTypeRegisterCOP1X(Instruction* instr,
                                        const int32_t& fr_reg,
                                        const int32_t& fs_reg,
                                        const int32_t& ft_reg,
                                        const int32_t& fd_reg) {
  switch (instr->FunctionFieldRaw()) {
    case MADD_D:
      double fr, ft, fs;
      fr = get_fpu_register_double(fr_reg);
      fs = get_fpu_register_double(fs_reg);
      ft = get_fpu_register_double(ft_reg);
      set_fpu_register_double(fd_reg, fs * ft + fr);
      break;
    default:
      UNREACHABLE();
  }
}


void Simulator::DecodeTypeRegisterSPECIAL(
    Instruction* instr, const int32_t& rs_reg, const int32_t& rs,
    const uint32_t& rs_u, const int32_t& rt_reg, const int32_t& rt,
    const uint32_t& rt_u, const int32_t& rd_reg, const int32_t& fr_reg,
    const int32_t& fs_reg, const int32_t& ft_reg, const int32_t& fd_reg,
    int64_t& i64hilo, uint64_t& u64hilo, int32_t& alu_out, bool& do_interrupt,
    int32_t& current_pc, int32_t& next_pc, int32_t& return_addr_reg) {
  switch (instr->FunctionFieldRaw()) {
    case SELEQZ_S:
      DCHECK(IsMipsArchVariant(kMips32r6));
      set_register(rd_reg, rt == 0 ? rs : 0);
      break;
    case SELNEZ_S:
      DCHECK(IsMipsArchVariant(kMips32r6));
      set_register(rd_reg, rt != 0 ? rs : 0);
      break;
2694 2695
        case JR: {
          Instruction* branch_delay_instr = reinterpret_cast<Instruction*>(
2696
              current_pc+Instruction::kInstrSize);
2697 2698 2699 2700 2701 2702 2703
          BranchDelayInstructionDecode(branch_delay_instr);
          set_pc(next_pc);
          pc_modified_ = true;
          break;
        }
        case JALR: {
          Instruction* branch_delay_instr = reinterpret_cast<Instruction*>(
2704
              current_pc+Instruction::kInstrSize);
2705
          BranchDelayInstructionDecode(branch_delay_instr);
2706 2707
          set_register(return_addr_reg,
                       current_pc + 2 * Instruction::kInstrSize);
2708 2709 2710 2711 2712 2713
          set_pc(next_pc);
          pc_modified_ = true;
          break;
        }
        // Instructions using HI and LO registers.
        case MULT:
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
          if (!IsMipsArchVariant(kMips32r6)) {
            set_register(LO, static_cast<int32_t>(i64hilo & 0xffffffff));
            set_register(HI, static_cast<int32_t>(i64hilo >> 32));
          } else {
            switch (instr->SaValue()) {
              case MUL_OP:
                set_register(rd_reg,
                    static_cast<int32_t>(i64hilo & 0xffffffff));
                break;
              case MUH_OP:
                set_register(rd_reg, static_cast<int32_t>(i64hilo >> 32));
                break;
              default:
                UNIMPLEMENTED_MIPS();
                break;
            }
          }
2731
          break;
2732
        case MULTU:
2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
          if (!IsMipsArchVariant(kMips32r6)) {
            set_register(LO, static_cast<int32_t>(u64hilo & 0xffffffff));
            set_register(HI, static_cast<int32_t>(u64hilo >> 32));
          } else {
            switch (instr->SaValue()) {
              case MUL_OP:
                set_register(rd_reg,
                    static_cast<int32_t>(u64hilo & 0xffffffff));
                break;
              case MUH_OP:
                set_register(rd_reg, static_cast<int32_t>(u64hilo >> 32));
                break;
              default:
                UNIMPLEMENTED_MIPS();
                break;
            }
          }
2750 2751
          break;
        case DIV:
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
          if (IsMipsArchVariant(kMips32r6)) {
            switch (instr->SaValue()) {
              case DIV_OP:
                if (rs == INT_MIN && rt == -1) {
                  set_register(rd_reg, INT_MIN);
                } else if (rt != 0) {
                  set_register(rd_reg, rs / rt);
                }
                break;
              case MOD_OP:
                if (rs == INT_MIN && rt == -1) {
                  set_register(rd_reg, 0);
                } else if (rt != 0) {
                  set_register(rd_reg, rs % rt);
                }
                break;
              default:
                UNIMPLEMENTED_MIPS();
                break;
            }
          } else {
            // Divide by zero and overflow was not checked in the
            // configuration step - div and divu do not raise exceptions. On
            // division by 0 the result will be UNPREDICTABLE. On overflow
            // (INT_MIN/-1), return INT_MIN which is what the hardware does.
            if (rs == INT_MIN && rt == -1) {
              set_register(LO, INT_MIN);
              set_register(HI, 0);
            } else if (rt != 0) {
              set_register(LO, rs / rt);
              set_register(HI, rs % rt);
            }
2784
          }
2785 2786
          break;
        case DIVU:
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807
          if (IsMipsArchVariant(kMips32r6)) {
            switch (instr->SaValue()) {
              case DIV_OP:
                if (rt_u != 0) {
                  set_register(rd_reg, rs_u / rt_u);
                }
                break;
              case MOD_OP:
                if (rt_u != 0) {
                  set_register(rd_reg, rs_u % rt_u);
                }
                break;
              default:
                UNIMPLEMENTED_MIPS();
                break;
              }
          } else {
            if (rt_u != 0) {
              set_register(LO, rs_u / rt_u);
              set_register(HI, rs_u % rt_u);
            }
2808
          }
2809
          break;
2810
        // Break and trap instructions.
2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821
        case BREAK:
        case TGE:
        case TGEU:
        case TLT:
        case TLTU:
        case TEQ:
        case TNE:
          if (do_interrupt) {
            SoftwareInterrupt(instr);
          }
          break;
2822 2823 2824 2825 2826
        // Conditional moves.
        case MOVN:
          if (rt) set_register(rd_reg, rs);
          break;
        case MOVCI: {
2827
          uint32_t cc = instr->FBccValue();
2828
          uint32_t fcsr_cc = get_fcsr_condition_bit(cc);
2829
          if (instr->Bit(16)) {  // Read Tf bit.
2830 2831 2832 2833 2834 2835 2836 2837 2838
            if (test_fcsr_bit(fcsr_cc)) set_register(rd_reg, rs);
          } else {
            if (!test_fcsr_bit(fcsr_cc)) set_register(rd_reg, rs);
          }
          break;
        }
        case MOVZ:
          if (!rt) set_register(rd_reg, rs);
          break;
2839 2840
        default:  // For other special opcodes we do the default operation.
          set_register(rd_reg, alu_out);
2841
      }
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934
}


void Simulator::DecodeTypeRegisterSPECIAL2(Instruction* instr,
                                           const int32_t& rd_reg,
                                           int32_t& alu_out) {
  switch (instr->FunctionFieldRaw()) {
    case MUL:
      set_register(rd_reg, alu_out);
      // HI and LO are UNPREDICTABLE after the operation.
      set_register(LO, Unpredictable);
      set_register(HI, Unpredictable);
      break;
    default:  // For other special2 opcodes we do the default operation.
      set_register(rd_reg, alu_out);
  }
}


void Simulator::DecodeTypeRegisterSPECIAL3(Instruction* instr,
                                           const int32_t& rt_reg,
                                           int32_t& alu_out) {
  switch (instr->FunctionFieldRaw()) {
    case INS:
      // Ins instr leaves result in Rt, rather than Rd.
      set_register(rt_reg, alu_out);
      break;
    case EXT:
      // Ext instr leaves result in Rt, rather than Rd.
      set_register(rt_reg, alu_out);
      break;
    default:
      UNREACHABLE();
  }
}


void Simulator::DecodeTypeRegister(Instruction* instr) {
  // Instruction fields.
  const Opcode op = instr->OpcodeFieldRaw();
  const int32_t rs_reg = instr->RsValue();
  const int32_t rs = get_register(rs_reg);
  const uint32_t rs_u = static_cast<uint32_t>(rs);
  const int32_t rt_reg = instr->RtValue();
  const int32_t rt = get_register(rt_reg);
  const uint32_t rt_u = static_cast<uint32_t>(rt);
  const int32_t rd_reg = instr->RdValue();

  const int32_t fr_reg = instr->FrValue();
  const int32_t fs_reg = instr->FsValue();
  const int32_t ft_reg = instr->FtValue();
  const int32_t fd_reg = instr->FdValue();
  int64_t i64hilo = 0;
  uint64_t u64hilo = 0;

  // ALU output.
  // It should not be used as is. Instructions using it should always
  // initialize it first.
  int32_t alu_out = 0x12345678;

  // For break and trap instructions.
  bool do_interrupt = false;

  // For jr and jalr.
  // Get current pc.
  int32_t current_pc = get_pc();
  // Next pc
  int32_t next_pc = 0;
  int32_t return_addr_reg = 31;

  // Set up the variables if needed before executing the instruction.
  ConfigureTypeRegister(instr, &alu_out, &i64hilo, &u64hilo, &next_pc,
                        &return_addr_reg, &do_interrupt);

  // ---------- Raise exceptions triggered.
  SignalExceptions();

  // ---------- Execution.
  switch (op) {
    case COP1:
      DecodeTypeRegisterCOP1(instr, rs_reg, rs, rs_u, rt_reg, rt, rt_u, rd_reg,
                             fr_reg, fs_reg, ft_reg, fd_reg, i64hilo, u64hilo,
                             alu_out, do_interrupt, current_pc, next_pc,
                             return_addr_reg);
      break;
    case COP1X:
      DecodeTypeRegisterCOP1X(instr, fr_reg, fs_reg, ft_reg, fd_reg);
      break;
    case SPECIAL:
      DecodeTypeRegisterSPECIAL(instr, rs_reg, rs, rs_u, rt_reg, rt, rt_u,
                                rd_reg, fr_reg, fs_reg, ft_reg, fd_reg, i64hilo,
                                u64hilo, alu_out, do_interrupt, current_pc,
                                next_pc, return_addr_reg);
2935 2936
      break;
    case SPECIAL2:
2937
      DecodeTypeRegisterSPECIAL2(instr, rd_reg, alu_out);
2938 2939
      break;
    case SPECIAL3:
2940
      DecodeTypeRegisterSPECIAL3(instr, rt_reg, alu_out);
2941 2942 2943 2944 2945 2946
      break;
    // Unimplemented opcodes raised an error in the configuration step before,
    // so we can use the default here to set the destination register in common
    // cases.
    default:
      set_register(rd_reg, alu_out);
2947
  }
2948 2949
}

2950

2951
// Type 2: instructions using a 16 bytes immediate. (e.g. addi, beq).
2952
void Simulator::DecodeTypeImmediate(Instruction* instr) {
2953
  // Instruction fields.
2954
  Opcode   op     = instr->OpcodeFieldRaw();
2955
  int32_t  rs     = get_register(instr->RsValue());
2956
  uint32_t rs_u   = static_cast<uint32_t>(rs);
2957
  int32_t  rt_reg = instr->RtValue();  // Destination register.
2958
  int32_t  rt     = get_register(rt_reg);
2959
  int16_t  imm16  = instr->Imm16Value();
2960

2961
  int32_t  ft_reg = instr->FtValue();  // Destination register.
2962
  int64_t  ft;
2963

2964
  // Zero extended immediate.
2965
  uint32_t  oe_imm16 = 0xffff & imm16;
2966
  // Sign extended immediate.
2967 2968 2969 2970 2971 2972 2973
  int32_t   se_imm16 = imm16;

  // Get current pc.
  int32_t current_pc = get_pc();
  // Next pc.
  int32_t next_pc = bad_ra;

2974
  // Used for conditional branch instructions.
2975 2976 2977
  bool do_branch = false;
  bool execute_branch_delay_instruction = false;

2978
  // Used for arithmetic instructions.
2979
  int32_t alu_out = 0;
2980
  // Floating point.
2981
  double fp_out = 0.0;
2982
  uint32_t cc, cc_value, fcsr_cc;
2983

2984
  // Used for memory instructions.
2985
  int32_t addr = 0x0;
2986
  // Value to be written in memory.
2987
  uint32_t mem_value = 0x0;
2988

2989
  // ---------- Configuration (and execution for REGIMM).
2990
  switch (op) {
2991
    // ------------- COP1. Coprocessor instructions.
2992 2993
    case COP1:
      switch (instr->RsFieldRaw()) {
2994 2995 2996 2997 2998 2999
        case BC1:   // Branch on coprocessor condition.
          cc = instr->FBccValue();
          fcsr_cc = get_fcsr_condition_bit(cc);
          cc_value = test_fcsr_bit(fcsr_cc);
          do_branch = (instr->FBtrueValue()) ? cc_value : !cc_value;
          execute_branch_delay_instruction = true;
3000
          // Set next_pc.
3001 3002 3003 3004 3005
          if (do_branch) {
            next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
          } else {
            next_pc = current_pc + kBranchReturnOffset;
          }
3006
          break;
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
        case BC1EQZ:
          ft = get_fpu_register(ft_reg);
          do_branch = (ft & 0x1) ? false : true;
          execute_branch_delay_instruction = true;
          // Set next_pc.
          if (do_branch) {
            next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
          } else {
            next_pc = current_pc + kBranchReturnOffset;
          }
          break;
        case BC1NEZ:
          ft = get_fpu_register(ft_reg);
          do_branch = (ft & 0x1) ? true : false;
          execute_branch_delay_instruction = true;
          // Set next_pc.
          if (do_branch) {
            next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
          } else {
            next_pc = current_pc + kBranchReturnOffset;
          }
          break;
3029 3030
        default:
          UNREACHABLE();
3031
      }
3032
      break;
3033
    // ------------- REGIMM class.
3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
    case REGIMM:
      switch (instr->RtFieldRaw()) {
        case BLTZ:
          do_branch = (rs  < 0);
          break;
        case BLTZAL:
          do_branch = rs  < 0;
          break;
        case BGEZ:
          do_branch = rs >= 0;
          break;
        case BGEZAL:
          do_branch = rs >= 0;
          break;
        default:
          UNREACHABLE();
3050
      }
3051 3052 3053 3054 3055 3056 3057
      switch (instr->RtFieldRaw()) {
        case BLTZ:
        case BLTZAL:
        case BGEZ:
        case BGEZAL:
          // Branch instructions common part.
          execute_branch_delay_instruction = true;
3058
          // Set next_pc.
3059
          if (do_branch) {
3060
            next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
3061 3062 3063 3064 3065 3066 3067 3068
            if (instr->IsLinkingInstruction()) {
              set_register(31, current_pc + kBranchReturnOffset);
            }
          } else {
            next_pc = current_pc + kBranchReturnOffset;
          }
        default:
          break;
3069
        }
3070 3071
    break;  // case REGIMM.
    // ------------- Branch instructions.
3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
    // When comparing to zero, the encoding of rt field is always 0, so we don't
    // need to replace rt with zero.
    case BEQ:
      do_branch = (rs == rt);
      break;
    case BNE:
      do_branch = rs != rt;
      break;
    case BLEZ:
      do_branch = rs <= 0;
      break;
    case BGTZ:
      do_branch = rs  > 0;
      break;
3086
    // ------------- Arithmetic instructions.
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118
    case ADDI:
      if (HaveSameSign(rs, se_imm16)) {
        if (rs > 0) {
          exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue - se_imm16);
        } else if (rs < 0) {
          exceptions[kIntegerUnderflow] =
              rs < (Registers::kMinValue - se_imm16);
        }
      }
      alu_out = rs + se_imm16;
      break;
    case ADDIU:
      alu_out = rs + se_imm16;
      break;
    case SLTI:
      alu_out = (rs < se_imm16) ? 1 : 0;
      break;
    case SLTIU:
      alu_out = (rs_u < static_cast<uint32_t>(se_imm16)) ? 1 : 0;
      break;
    case ANDI:
        alu_out = rs & oe_imm16;
      break;
    case ORI:
        alu_out = rs | oe_imm16;
      break;
    case XORI:
        alu_out = rs ^ oe_imm16;
      break;
    case LUI:
        alu_out = (oe_imm16 << 16);
      break;
3119
    // ------------- Memory instructions.
3120 3121 3122 3123
    case LB:
      addr = rs + se_imm16;
      alu_out = ReadB(addr);
      break;
3124 3125 3126 3127 3128
    case LH:
      addr = rs + se_imm16;
      alu_out = ReadH(addr, instr);
      break;
    case LWL: {
3129
      // al_offset is offset of the effective address within an aligned word.
3130 3131 3132 3133 3134 3135 3136 3137 3138
      uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask;
      uint8_t byte_shift = kPointerAlignmentMask - al_offset;
      uint32_t mask = (1 << byte_shift * 8) - 1;
      addr = rs + se_imm16 - al_offset;
      alu_out = ReadW(addr, instr);
      alu_out <<= byte_shift * 8;
      alu_out |= rt & mask;
      break;
    }
3139 3140 3141 3142 3143 3144 3145 3146
    case LW:
      addr = rs + se_imm16;
      alu_out = ReadW(addr, instr);
      break;
    case LBU:
      addr = rs + se_imm16;
      alu_out = ReadBU(addr);
      break;
3147 3148 3149 3150 3151
    case LHU:
      addr = rs + se_imm16;
      alu_out = ReadHU(addr, instr);
      break;
    case LWR: {
3152
      // al_offset is offset of the effective address within an aligned word.
3153 3154 3155 3156 3157 3158 3159 3160 3161
      uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask;
      uint8_t byte_shift = kPointerAlignmentMask - al_offset;
      uint32_t mask = al_offset ? (~0 << (byte_shift + 1) * 8) : 0;
      addr = rs + se_imm16 - al_offset;
      alu_out = ReadW(addr, instr);
      alu_out = static_cast<uint32_t> (alu_out) >> al_offset * 8;
      alu_out |= rt & mask;
      break;
    }
3162 3163 3164
    case SB:
      addr = rs + se_imm16;
      break;
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
    case SH:
      addr = rs + se_imm16;
      break;
    case SWL: {
      uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask;
      uint8_t byte_shift = kPointerAlignmentMask - al_offset;
      uint32_t mask = byte_shift ? (~0 << (al_offset + 1) * 8) : 0;
      addr = rs + se_imm16 - al_offset;
      mem_value = ReadW(addr, instr) & mask;
      mem_value |= static_cast<uint32_t>(rt) >> byte_shift * 8;
      break;
    }
3177 3178 3179
    case SW:
      addr = rs + se_imm16;
      break;
3180 3181 3182 3183 3184 3185 3186 3187
    case SWR: {
      uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask;
      uint32_t mask = (1 << al_offset * 8) - 1;
      addr = rs + se_imm16 - al_offset;
      mem_value = ReadW(addr, instr);
      mem_value = (rt << al_offset * 8) | (mem_value & mask);
      break;
    }
3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
    case LWC1:
      addr = rs + se_imm16;
      alu_out = ReadW(addr, instr);
      break;
    case LDC1:
      addr = rs + se_imm16;
      fp_out = ReadD(addr, instr);
      break;
    case SWC1:
    case SDC1:
      addr = rs + se_imm16;
      break;
    default:
      UNREACHABLE();
3202
  }
3203 3204 3205 3206

  // ---------- Raise exceptions triggered.
  SignalExceptions();

3207
  // ---------- Execution.
3208
  switch (op) {
3209
    // ------------- Branch instructions.
3210 3211 3212 3213 3214 3215
    case BEQ:
    case BNE:
    case BLEZ:
    case BGTZ:
      // Branch instructions common part.
      execute_branch_delay_instruction = true;
3216
      // Set next_pc.
3217
      if (do_branch) {
3218
        next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
3219
        if (instr->IsLinkingInstruction()) {
3220
          set_register(31, current_pc + 2* Instruction::kInstrSize);
3221 3222
        }
      } else {
3223
        next_pc = current_pc + 2 * Instruction::kInstrSize;
3224 3225
      }
      break;
3226
    // ------------- Arithmetic instructions.
3227 3228 3229 3230 3231 3232 3233 3234 3235 3236
    case ADDI:
    case ADDIU:
    case SLTI:
    case SLTIU:
    case ANDI:
    case ORI:
    case XORI:
    case LUI:
      set_register(rt_reg, alu_out);
      break;
3237
    // ------------- Memory instructions.
3238
    case LB:
3239 3240
    case LH:
    case LWL:
3241 3242
    case LW:
    case LBU:
3243 3244
    case LHU:
    case LWR:
3245 3246 3247 3248 3249
      set_register(rt_reg, alu_out);
      break;
    case SB:
      WriteB(addr, static_cast<int8_t>(rt));
      break;
3250 3251 3252 3253 3254 3255
    case SH:
      WriteH(addr, static_cast<uint16_t>(rt), instr);
      break;
    case SWL:
      WriteW(addr, mem_value, instr);
      break;
3256 3257 3258
    case SW:
      WriteW(addr, rt, instr);
      break;
3259 3260 3261
    case SWR:
      WriteW(addr, mem_value, instr);
      break;
3262
    case LWC1:
3263 3264
      set_fpu_register_hi_word(ft_reg, 0);
      set_fpu_register_word(ft_reg, alu_out);
3265 3266 3267 3268 3269 3270
      break;
    case LDC1:
      set_fpu_register_double(ft_reg, fp_out);
      break;
    case SWC1:
      addr = rs + se_imm16;
3271
      WriteW(addr, get_fpu_register_word(ft_reg), instr);
3272 3273 3274
      break;
    case SDC1:
      addr = rs + se_imm16;
3275
      WriteD(addr, get_fpu_register_double(ft_reg), instr);
3276 3277 3278
      break;
    default:
      break;
3279
  }
3280 3281 3282 3283 3284 3285 3286


  if (execute_branch_delay_instruction) {
    // Execute branch delay slot
    // We don't check for end_sim_pc. First it should not be met as the current
    // pc is valid. Secondly a jump should always execute its branch delay slot.
    Instruction* branch_delay_instr =
3287
      reinterpret_cast<Instruction*>(current_pc+Instruction::kInstrSize);
3288 3289 3290 3291 3292 3293 3294 3295 3296
    BranchDelayInstructionDecode(branch_delay_instr);
  }

  // If needed update pc after the branch delay execution.
  if (next_pc != bad_ra) {
    set_pc(next_pc);
  }
}

3297

3298
// Type 3: instructions using a 26 bytes immediate. (e.g. j, jal).
3299 3300 3301 3302 3303
void Simulator::DecodeTypeJump(Instruction* instr) {
  // Get current pc.
  int32_t current_pc = get_pc();
  // Get unchanged bits of pc.
  int32_t pc_high_bits = current_pc & 0xf0000000;
3304
  // Next pc.
3305
  int32_t next_pc = pc_high_bits | (instr->Imm26Value() << 2);
3306

3307
  // Execute branch delay slot.
3308 3309 3310
  // We don't check for end_sim_pc. First it should not be met as the current pc
  // is valid. Secondly a jump should always execute its branch delay slot.
  Instruction* branch_delay_instr =
3311
      reinterpret_cast<Instruction*>(current_pc + Instruction::kInstrSize);
3312 3313 3314 3315 3316
  BranchDelayInstructionDecode(branch_delay_instr);

  // Update pc and ra if necessary.
  // Do this after the branch delay execution.
  if (instr->IsLinkingInstruction()) {
3317
    set_register(31, current_pc + 2 * Instruction::kInstrSize);
3318 3319 3320 3321 3322
  }
  set_pc(next_pc);
  pc_modified_ = true;
}

3323

3324 3325
// Executes the current instruction.
void Simulator::InstructionDecode(Instruction* instr) {
3326 3327 3328
  if (v8::internal::FLAG_check_icache) {
    CheckICache(isolate_->simulator_i_cache(), instr);
  }
3329 3330 3331 3332
  pc_modified_ = false;
  if (::v8::internal::FLAG_trace_sim) {
    disasm::NameConverter converter;
    disasm::Disassembler dasm(converter);
3333
    // Use a reasonably large buffer.
3334
    v8::internal::EmbeddedVector<char, 256> buffer;
3335
    dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(instr));
3336
    PrintF("  0x%08x  %s\n", reinterpret_cast<intptr_t>(instr),
3337
        buffer.start());
3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354
  }

  switch (instr->InstructionType()) {
    case Instruction::kRegisterType:
      DecodeTypeRegister(instr);
      break;
    case Instruction::kImmediateType:
      DecodeTypeImmediate(instr);
      break;
    case Instruction::kJumpType:
      DecodeTypeJump(instr);
      break;
    default:
      UNSUPPORTED();
  }
  if (!pc_modified_) {
    set_register(pc, reinterpret_cast<int32_t>(instr) +
3355
                 Instruction::kInstrSize);
3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380
  }
}



void Simulator::Execute() {
  // Get the PC to simulate. Cannot use the accessor here as we need the
  // raw PC value and not the one used as input to arithmetic instructions.
  int program_counter = get_pc();
  if (::v8::internal::FLAG_stop_sim_at == 0) {
    // Fast version of the dispatch loop without checking whether the simulator
    // should be stopping at a particular executed instruction.
    while (program_counter != end_sim_pc) {
      Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
      icount_++;
      InstructionDecode(instr);
      program_counter = get_pc();
    }
  } else {
    // FLAG_stop_sim_at is at the non-default value. Stop in the debugger when
    // we reach the particular instuction count.
    while (program_counter != end_sim_pc) {
      Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
      icount_++;
      if (icount_ == ::v8::internal::FLAG_stop_sim_at) {
3381
        MipsDebugger dbg(this);
3382 3383 3384 3385 3386 3387 3388 3389 3390 3391
        dbg.Debug();
      } else {
        InstructionDecode(instr);
      }
      program_counter = get_pc();
    }
  }
}


3392
void Simulator::CallInternal(byte* entry) {
3393
  // Prepare to execute the code at entry.
3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
  set_register(pc, reinterpret_cast<int32_t>(entry));
  // Put down marker for end of simulation. The simulator will stop simulation
  // when the PC reaches this value. By saving the "end simulation" value into
  // the LR the simulation stops when returning to this call point.
  set_register(ra, end_sim_pc);

  // Remember the values of callee-saved registers.
  // The code below assumes that r9 is not used as sb (static base) in
  // simulator code and therefore is regarded as a callee-saved register.
  int32_t s0_val = get_register(s0);
  int32_t s1_val = get_register(s1);
  int32_t s2_val = get_register(s2);
  int32_t s3_val = get_register(s3);
  int32_t s4_val = get_register(s4);
  int32_t s5_val = get_register(s5);
  int32_t s6_val = get_register(s6);
  int32_t s7_val = get_register(s7);
  int32_t gp_val = get_register(gp);
  int32_t sp_val = get_register(sp);
  int32_t fp_val = get_register(fp);

3415
  // Set up the callee-saved registers with a known value. To be able to check
3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428
  // that they are preserved properly across JS execution.
  int32_t callee_saved_value = icount_;
  set_register(s0, callee_saved_value);
  set_register(s1, callee_saved_value);
  set_register(s2, callee_saved_value);
  set_register(s3, callee_saved_value);
  set_register(s4, callee_saved_value);
  set_register(s5, callee_saved_value);
  set_register(s6, callee_saved_value);
  set_register(s7, callee_saved_value);
  set_register(gp, callee_saved_value);
  set_register(fp, callee_saved_value);

3429
  // Start the simulation.
3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455
  Execute();

  // Check that the callee-saved registers have been preserved.
  CHECK_EQ(callee_saved_value, get_register(s0));
  CHECK_EQ(callee_saved_value, get_register(s1));
  CHECK_EQ(callee_saved_value, get_register(s2));
  CHECK_EQ(callee_saved_value, get_register(s3));
  CHECK_EQ(callee_saved_value, get_register(s4));
  CHECK_EQ(callee_saved_value, get_register(s5));
  CHECK_EQ(callee_saved_value, get_register(s6));
  CHECK_EQ(callee_saved_value, get_register(s7));
  CHECK_EQ(callee_saved_value, get_register(gp));
  CHECK_EQ(callee_saved_value, get_register(fp));

  // Restore callee-saved registers with the original value.
  set_register(s0, s0_val);
  set_register(s1, s1_val);
  set_register(s2, s2_val);
  set_register(s3, s3_val);
  set_register(s4, s4_val);
  set_register(s5, s5_val);
  set_register(s6, s6_val);
  set_register(s7, s7_val);
  set_register(gp, gp_val);
  set_register(sp, sp_val);
  set_register(fp, fp_val);
3456 3457 3458 3459 3460 3461 3462 3463 3464
}


int32_t Simulator::Call(byte* entry, int argument_count, ...) {
  va_list parameters;
  va_start(parameters, argument_count);
  // Set up arguments.

  // First four arguments passed in registers.
3465
  DCHECK(argument_count >= 4);
3466 3467 3468 3469 3470 3471 3472 3473 3474 3475
  set_register(a0, va_arg(parameters, int32_t));
  set_register(a1, va_arg(parameters, int32_t));
  set_register(a2, va_arg(parameters, int32_t));
  set_register(a3, va_arg(parameters, int32_t));

  // Remaining arguments passed on stack.
  int original_stack = get_register(sp);
  // Compute position of stack on entry to generated code.
  int entry_stack = (original_stack - (argument_count - 4) * sizeof(int32_t)
                                    - kCArgsSlotsSize);
3476 3477
  if (base::OS::ActivationFrameAlignment() != 0) {
    entry_stack &= -base::OS::ActivationFrameAlignment();
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487
  }
  // Store remaining arguments on stack, from low to high memory.
  intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack);
  for (int i = 4; i < argument_count; i++) {
    stack_argument[i - 4 + kCArgSlotCount] = va_arg(parameters, int32_t);
  }
  va_end(parameters);
  set_register(sp, entry_stack);

  CallInternal(entry);
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497

  // Pop stack passed arguments.
  CHECK_EQ(entry_stack, get_register(sp));
  set_register(sp, original_stack);

  int32_t result = get_register(v0);
  return result;
}


3498 3499 3500 3501 3502 3503
double Simulator::CallFP(byte* entry, double d0, double d1) {
  if (!IsMipsSoftFloatABI) {
    set_fpu_register_double(f12, d0);
    set_fpu_register_double(f14, d1);
  } else {
    int buffer[2];
3504
    DCHECK(sizeof(buffer[0]) * 2 == sizeof(d0));
3505
    memcpy(buffer, &d0, sizeof(d0));
3506
    set_dw_register(a0, buffer);
3507
    memcpy(buffer, &d1, sizeof(d1));
3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518
    set_dw_register(a2, buffer);
  }
  CallInternal(entry);
  if (!IsMipsSoftFloatABI) {
    return get_fpu_register_double(f0);
  } else {
    return get_double_from_register_pair(v0);
  }
}


3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538
uintptr_t Simulator::PushAddress(uintptr_t address) {
  int new_sp = get_register(sp) - sizeof(uintptr_t);
  uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp);
  *stack_slot = address;
  set_register(sp, new_sp);
  return new_sp;
}


uintptr_t Simulator::PopAddress() {
  int current_sp = get_register(sp);
  uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp);
  uintptr_t address = *stack_slot;
  set_register(sp, current_sp + sizeof(uintptr_t));
  return address;
}


#undef UNSUPPORTED

3539
} }  // namespace v8::internal
3540

3541
#endif  // USE_SIMULATOR
3542

3543
#endif  // V8_TARGET_ARCH_MIPS