1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
12 #if V8_TARGET_ARCH_MIPS64
14 #include "src/assembler.h"
15 #include "src/base/bits.h"
16 #include "src/codegen.h"
17 #include "src/disasm.h"
18 #include "src/mips64/constants-mips64.h"
19 #include "src/mips64/simulator-mips64.h"
20 #include "src/ostreams.h"
22 // Only build the simulator if not compiling for real MIPS hardware.
23 #if defined(USE_SIMULATOR)
29 bool HaveSameSign(int64_t a, int64_t b) {
30 return ((a ^ b) >= 0);
34 uint32_t get_fcsr_condition_bit(uint32_t cc) {
43 static int64_t MultiplyHighSigned(int64_t u, int64_t v) {
45 int64_t u1, v1, w1, w2, t;
53 t = u1 * v0 + (w0 >> 32);
58 return u1 * v1 + w2 + (w1 >> 32);
62 // This macro provides a platform independent use of sscanf. The reason for
63 // SScanF not being implemented in a platform independent was through
64 // ::v8::internal::OS in the same way as SNPrintF is that the Windows C Run-Time
65 // Library does not provide vsscanf.
66 #define SScanF sscanf // NOLINT
68 // The MipsDebugger class is used by the simulator while debugging simulated
72 explicit MipsDebugger(Simulator* sim) : sim_(sim) { }
75 void Stop(Instruction* instr);
77 // Print all registers with a nice formatting.
79 void PrintAllRegsIncludingFPU();
82 // We set the breakpoint code to 0xfffff to easily recognize it.
83 static const Instr kBreakpointInstr = SPECIAL | BREAK | 0xfffff << 6;
84 static const Instr kNopInstr = 0x0;
88 int64_t GetRegisterValue(int regnum);
89 int64_t GetFPURegisterValue(int regnum);
90 float GetFPURegisterValueFloat(int regnum);
91 double GetFPURegisterValueDouble(int regnum);
92 bool GetValue(const char* desc, int64_t* value);
94 // Set or delete a breakpoint. Returns true if successful.
95 bool SetBreakpoint(Instruction* breakpc);
96 bool DeleteBreakpoint(Instruction* breakpc);
98 // Undo and redo all breakpoints. This is needed to bracket disassembly and
99 // execution to skip past breakpoints when run from the debugger.
100 void UndoBreakpoints();
101 void RedoBreakpoints();
105 MipsDebugger::~MipsDebugger() {
109 #ifdef GENERATED_CODE_COVERAGE
110 static FILE* coverage_log = NULL;
113 static void InitializeCoverage() {
114 char* file_name = getenv("V8_GENERATED_CODE_COVERAGE_LOG");
115 if (file_name != NULL) {
116 coverage_log = fopen(file_name, "aw+");
121 void MipsDebugger::Stop(Instruction* instr) {
122 // Get the stop code.
123 uint32_t code = instr->Bits(25, 6);
124 // Retrieve the encoded address, which comes just after this stop.
126 reinterpret_cast<char**>(sim_->get_pc() + Instr::kInstrSize);
127 char* msg = *msg_address;
130 // Update this stop description.
131 if (!watched_stops_[code].desc) {
132 watched_stops_[code].desc = msg;
135 if (strlen(msg) > 0) {
136 if (coverage_log != NULL) {
137 fprintf(coverage_log, "%s\n", str);
138 fflush(coverage_log);
140 // Overwrite the instruction and address with nops.
141 instr->SetInstructionBits(kNopInstr);
142 reinterpret_cast<Instr*>(msg_address)->SetInstructionBits(kNopInstr);
144 // TODO(yuyin): 2 -> 3?
145 sim_->set_pc(sim_->get_pc() + 3 * Instruction::kInstructionSize);
149 #else // GENERATED_CODE_COVERAGE
151 #define UNSUPPORTED() printf("Unsupported instruction.\n");
153 static void InitializeCoverage() {}
156 void MipsDebugger::Stop(Instruction* instr) {
157 // Get the stop code.
158 uint32_t code = instr->Bits(25, 6);
159 // Retrieve the encoded address, which comes just after this stop.
160 char* msg = *reinterpret_cast<char**>(sim_->get_pc() +
161 Instruction::kInstrSize);
162 // Update this stop description.
163 if (!sim_->watched_stops_[code].desc) {
164 sim_->watched_stops_[code].desc = msg;
166 PrintF("Simulator hit %s (%u)\n", msg, code);
167 // TODO(yuyin): 2 -> 3?
168 sim_->set_pc(sim_->get_pc() + 3 * Instruction::kInstrSize);
171 #endif // GENERATED_CODE_COVERAGE
174 int64_t MipsDebugger::GetRegisterValue(int regnum) {
175 if (regnum == kNumSimuRegisters) {
176 return sim_->get_pc();
178 return sim_->get_register(regnum);
183 int64_t MipsDebugger::GetFPURegisterValue(int regnum) {
184 if (regnum == kNumFPURegisters) {
185 return sim_->get_pc();
187 return sim_->get_fpu_register(regnum);
192 float MipsDebugger::GetFPURegisterValueFloat(int regnum) {
193 if (regnum == kNumFPURegisters) {
194 return sim_->get_pc();
196 return sim_->get_fpu_register_float(regnum);
201 double MipsDebugger::GetFPURegisterValueDouble(int regnum) {
202 if (regnum == kNumFPURegisters) {
203 return sim_->get_pc();
205 return sim_->get_fpu_register_double(regnum);
210 bool MipsDebugger::GetValue(const char* desc, int64_t* value) {
211 int regnum = Registers::Number(desc);
212 int fpuregnum = FPURegisters::Number(desc);
214 if (regnum != kInvalidRegister) {
215 *value = GetRegisterValue(regnum);
217 } else if (fpuregnum != kInvalidFPURegister) {
218 *value = GetFPURegisterValue(fpuregnum);
220 } else if (strncmp(desc, "0x", 2) == 0) {
221 return SScanF(desc + 2, "%" SCNx64,
222 reinterpret_cast<uint64_t*>(value)) == 1;
224 return SScanF(desc, "%" SCNu64, reinterpret_cast<uint64_t*>(value)) == 1;
230 bool MipsDebugger::SetBreakpoint(Instruction* breakpc) {
231 // Check if a breakpoint can be set. If not return without any side-effects.
232 if (sim_->break_pc_ != NULL) {
236 // Set the breakpoint.
237 sim_->break_pc_ = breakpc;
238 sim_->break_instr_ = breakpc->InstructionBits();
239 // Not setting the breakpoint instruction in the code itself. It will be set
240 // when the debugger shell continues.
245 bool MipsDebugger::DeleteBreakpoint(Instruction* breakpc) {
246 if (sim_->break_pc_ != NULL) {
247 sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
250 sim_->break_pc_ = NULL;
251 sim_->break_instr_ = 0;
256 void MipsDebugger::UndoBreakpoints() {
257 if (sim_->break_pc_ != NULL) {
258 sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
263 void MipsDebugger::RedoBreakpoints() {
264 if (sim_->break_pc_ != NULL) {
265 sim_->break_pc_->SetInstructionBits(kBreakpointInstr);
270 void MipsDebugger::PrintAllRegs() {
271 #define REG_INFO(n) Registers::Name(n), GetRegisterValue(n), GetRegisterValue(n)
275 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
276 REG_INFO(1), REG_INFO(2), REG_INFO(4));
278 PrintF("%34s\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
279 "", REG_INFO(3), REG_INFO(5));
281 PrintF("%34s\t%34s\t%3s: 0x%016lx %14ld\n", "", "", REG_INFO(6));
283 PrintF("%34s\t%34s\t%3s: 0x%016lx %14ld\n", "", "", REG_INFO(7));
286 for (int i = 0; i < 8; i++) {
287 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
288 REG_INFO(8+i), REG_INFO(16+i));
292 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
293 REG_INFO(24), REG_INFO(26), REG_INFO(32));
295 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
296 REG_INFO(25), REG_INFO(27), REG_INFO(33));
298 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
299 REG_INFO(29), REG_INFO(30), REG_INFO(28));
301 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
302 REG_INFO(31), REG_INFO(34));
309 void MipsDebugger::PrintAllRegsIncludingFPU() {
310 #define FPU_REG_INFO(n) FPURegisters::Name(n), \
311 GetFPURegisterValue(n), \
312 GetFPURegisterValueDouble(n)
317 // f0, f1, f2, ... f31.
318 // TODO(plind): consider printing 2 columns for space efficiency.
319 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(0) );
320 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(1) );
321 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(2) );
322 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(3) );
323 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(4) );
324 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(5) );
325 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(6) );
326 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(7) );
327 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(8) );
328 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(9) );
329 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(10));
330 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(11));
331 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(12));
332 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(13));
333 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(14));
334 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(15));
335 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(16));
336 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(17));
337 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(18));
338 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(19));
339 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(20));
340 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(21));
341 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(22));
342 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(23));
343 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(24));
344 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(25));
345 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(26));
346 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(27));
347 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(28));
348 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(29));
349 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(30));
350 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(31));
357 void MipsDebugger::Debug() {
358 intptr_t last_pc = -1;
361 #define COMMAND_SIZE 63
365 #define XSTR(a) STR(a)
367 char cmd[COMMAND_SIZE + 1];
368 char arg1[ARG_SIZE + 1];
369 char arg2[ARG_SIZE + 1];
370 char* argv[3] = { cmd, arg1, arg2 };
372 // Make sure to have a proper terminating character if reaching the limit.
373 cmd[COMMAND_SIZE] = 0;
377 // Undo all set breakpoints while running in the debugger shell. This will
378 // make them invisible to all commands.
381 while (!done && (sim_->get_pc() != Simulator::end_sim_pc)) {
382 if (last_pc != sim_->get_pc()) {
383 disasm::NameConverter converter;
384 disasm::Disassembler dasm(converter);
385 // Use a reasonably large buffer.
386 v8::internal::EmbeddedVector<char, 256> buffer;
387 dasm.InstructionDecode(buffer,
388 reinterpret_cast<byte*>(sim_->get_pc()));
389 PrintF(" 0x%016lx %s\n", sim_->get_pc(), buffer.start());
390 last_pc = sim_->get_pc();
392 char* line = ReadLine("sim> ");
396 char* last_input = sim_->last_debugger_input();
397 if (strcmp(line, "\n") == 0 && last_input != NULL) {
400 // Ownership is transferred to sim_;
401 sim_->set_last_debugger_input(line);
403 // Use sscanf to parse the individual parts of the command line. At the
404 // moment no command expects more than two parameters.
405 int argc = SScanF(line,
406 "%" XSTR(COMMAND_SIZE) "s "
407 "%" XSTR(ARG_SIZE) "s "
408 "%" XSTR(ARG_SIZE) "s",
410 if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) {
411 Instruction* instr = reinterpret_cast<Instruction*>(sim_->get_pc());
412 if (!(instr->IsTrap()) ||
413 instr->InstructionBits() == rtCallRedirInstr) {
414 sim_->InstructionDecode(
415 reinterpret_cast<Instruction*>(sim_->get_pc()));
417 // Allow si to jump over generated breakpoints.
418 PrintF("/!\\ Jumping over generated breakpoint.\n");
419 sim_->set_pc(sim_->get_pc() + Instruction::kInstrSize);
421 } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) {
422 // Execute the one instruction we broke at with breakpoints disabled.
423 sim_->InstructionDecode(reinterpret_cast<Instruction*>(sim_->get_pc()));
424 // Leave the debugger shell.
426 } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) {
430 if (strcmp(arg1, "all") == 0) {
432 } else if (strcmp(arg1, "allf") == 0) {
433 PrintAllRegsIncludingFPU();
435 int regnum = Registers::Number(arg1);
436 int fpuregnum = FPURegisters::Number(arg1);
438 if (regnum != kInvalidRegister) {
439 value = GetRegisterValue(regnum);
440 PrintF("%s: 0x%08lx %ld \n", arg1, value, value);
441 } else if (fpuregnum != kInvalidFPURegister) {
442 value = GetFPURegisterValue(fpuregnum);
443 dvalue = GetFPURegisterValueDouble(fpuregnum);
444 PrintF("%3s: 0x%016lx %16.4e\n",
445 FPURegisters::Name(fpuregnum), value, dvalue);
447 PrintF("%s unrecognized\n", arg1);
452 if (strcmp(arg2, "single") == 0) {
455 int fpuregnum = FPURegisters::Number(arg1);
457 if (fpuregnum != kInvalidFPURegister) {
458 value = GetFPURegisterValue(fpuregnum);
459 value &= 0xffffffffUL;
460 fvalue = GetFPURegisterValueFloat(fpuregnum);
461 PrintF("%s: 0x%08lx %11.4e\n", arg1, value, fvalue);
463 PrintF("%s unrecognized\n", arg1);
466 PrintF("print <fpu register> single\n");
469 PrintF("print <register> or print <fpu register> single\n");
472 } else if ((strcmp(cmd, "po") == 0)
473 || (strcmp(cmd, "printobject") == 0)) {
477 if (GetValue(arg1, &value)) {
478 Object* obj = reinterpret_cast<Object*>(value);
479 os << arg1 << ": \n";
484 os << Brief(obj) << "\n";
487 os << arg1 << " unrecognized\n";
490 PrintF("printobject <value>\n");
492 } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) {
497 if (strcmp(cmd, "stack") == 0) {
498 cur = reinterpret_cast<int64_t*>(sim_->get_register(Simulator::sp));
499 } else { // Command "mem".
501 if (!GetValue(arg1, &value)) {
502 PrintF("%s unrecognized\n", arg1);
505 cur = reinterpret_cast<int64_t*>(value);
510 if (argc == next_arg) {
513 if (!GetValue(argv[next_arg], &words)) {
520 PrintF(" 0x%012lx: 0x%016lx %14ld",
521 reinterpret_cast<intptr_t>(cur), *cur, *cur);
522 HeapObject* obj = reinterpret_cast<HeapObject*>(*cur);
523 int64_t value = *cur;
524 Heap* current_heap = v8::internal::Isolate::Current()->heap();
525 if (((value & 1) == 0) || current_heap->Contains(obj)) {
527 if ((value & 1) == 0) {
528 PrintF("smi %d", static_cast<int>(value >> 32));
538 } else if ((strcmp(cmd, "disasm") == 0) ||
539 (strcmp(cmd, "dpc") == 0) ||
540 (strcmp(cmd, "di") == 0)) {
541 disasm::NameConverter converter;
542 disasm::Disassembler dasm(converter);
543 // Use a reasonably large buffer.
544 v8::internal::EmbeddedVector<char, 256> buffer;
550 cur = reinterpret_cast<byte*>(sim_->get_pc());
551 end = cur + (10 * Instruction::kInstrSize);
552 } else if (argc == 2) {
553 int regnum = Registers::Number(arg1);
554 if (regnum != kInvalidRegister || strncmp(arg1, "0x", 2) == 0) {
555 // The argument is an address or a register name.
557 if (GetValue(arg1, &value)) {
558 cur = reinterpret_cast<byte*>(value);
559 // Disassemble 10 instructions at <arg1>.
560 end = cur + (10 * Instruction::kInstrSize);
563 // The argument is the number of instructions.
565 if (GetValue(arg1, &value)) {
566 cur = reinterpret_cast<byte*>(sim_->get_pc());
567 // Disassemble <arg1> instructions.
568 end = cur + (value * Instruction::kInstrSize);
574 if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
575 cur = reinterpret_cast<byte*>(value1);
576 end = cur + (value2 * Instruction::kInstrSize);
581 dasm.InstructionDecode(buffer, cur);
582 PrintF(" 0x%08lx %s\n",
583 reinterpret_cast<intptr_t>(cur), buffer.start());
584 cur += Instruction::kInstrSize;
586 } else if (strcmp(cmd, "gdb") == 0) {
587 PrintF("relinquishing control to gdb\n");
588 v8::base::OS::DebugBreak();
589 PrintF("regaining control from gdb\n");
590 } else if (strcmp(cmd, "break") == 0) {
593 if (GetValue(arg1, &value)) {
594 if (!SetBreakpoint(reinterpret_cast<Instruction*>(value))) {
595 PrintF("setting breakpoint failed\n");
598 PrintF("%s unrecognized\n", arg1);
601 PrintF("break <address>\n");
603 } else if (strcmp(cmd, "del") == 0) {
604 if (!DeleteBreakpoint(NULL)) {
605 PrintF("deleting breakpoint failed\n");
607 } else if (strcmp(cmd, "flags") == 0) {
608 PrintF("No flags on MIPS !\n");
609 } else if (strcmp(cmd, "stop") == 0) {
611 intptr_t stop_pc = sim_->get_pc() -
612 2 * Instruction::kInstrSize;
613 Instruction* stop_instr = reinterpret_cast<Instruction*>(stop_pc);
614 Instruction* msg_address =
615 reinterpret_cast<Instruction*>(stop_pc +
616 Instruction::kInstrSize);
617 if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) {
618 // Remove the current stop.
619 if (sim_->IsStopInstruction(stop_instr)) {
620 stop_instr->SetInstructionBits(kNopInstr);
621 msg_address->SetInstructionBits(kNopInstr);
623 PrintF("Not at debugger stop.\n");
625 } else if (argc == 3) {
626 // Print information about all/the specified breakpoint(s).
627 if (strcmp(arg1, "info") == 0) {
628 if (strcmp(arg2, "all") == 0) {
629 PrintF("Stop information:\n");
630 for (uint32_t i = kMaxWatchpointCode + 1;
633 sim_->PrintStopInfo(i);
635 } else if (GetValue(arg2, &value)) {
636 sim_->PrintStopInfo(value);
638 PrintF("Unrecognized argument.\n");
640 } else if (strcmp(arg1, "enable") == 0) {
641 // Enable all/the specified breakpoint(s).
642 if (strcmp(arg2, "all") == 0) {
643 for (uint32_t i = kMaxWatchpointCode + 1;
648 } else if (GetValue(arg2, &value)) {
649 sim_->EnableStop(value);
651 PrintF("Unrecognized argument.\n");
653 } else if (strcmp(arg1, "disable") == 0) {
654 // Disable all/the specified breakpoint(s).
655 if (strcmp(arg2, "all") == 0) {
656 for (uint32_t i = kMaxWatchpointCode + 1;
659 sim_->DisableStop(i);
661 } else if (GetValue(arg2, &value)) {
662 sim_->DisableStop(value);
664 PrintF("Unrecognized argument.\n");
668 PrintF("Wrong usage. Use help command for more information.\n");
670 } else if ((strcmp(cmd, "stat") == 0) || (strcmp(cmd, "st") == 0)) {
671 // Print registers and disassemble.
675 disasm::NameConverter converter;
676 disasm::Disassembler dasm(converter);
677 // Use a reasonably large buffer.
678 v8::internal::EmbeddedVector<char, 256> buffer;
684 cur = reinterpret_cast<byte*>(sim_->get_pc());
685 end = cur + (10 * Instruction::kInstrSize);
686 } else if (argc == 2) {
688 if (GetValue(arg1, &value)) {
689 cur = reinterpret_cast<byte*>(value);
690 // no length parameter passed, assume 10 instructions
691 end = cur + (10 * Instruction::kInstrSize);
696 if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
697 cur = reinterpret_cast<byte*>(value1);
698 end = cur + (value2 * Instruction::kInstrSize);
703 dasm.InstructionDecode(buffer, cur);
704 PrintF(" 0x%08lx %s\n",
705 reinterpret_cast<intptr_t>(cur), buffer.start());
706 cur += Instruction::kInstrSize;
708 } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) {
710 PrintF(" continue execution (alias 'c')\n");
712 PrintF(" step one instruction (alias 'si')\n");
713 PrintF("print <register>\n");
714 PrintF(" print register content (alias 'p')\n");
715 PrintF(" use register name 'all' to print all registers\n");
716 PrintF("printobject <register>\n");
717 PrintF(" print an object from a register (alias 'po')\n");
718 PrintF("stack [<words>]\n");
719 PrintF(" dump stack content, default dump 10 words)\n");
720 PrintF("mem <address> [<words>]\n");
721 PrintF(" dump memory content, default dump 10 words)\n");
723 PrintF(" print flags\n");
724 PrintF("disasm [<instructions>]\n");
725 PrintF("disasm [<address/register>]\n");
726 PrintF("disasm [[<address/register>] <instructions>]\n");
727 PrintF(" disassemble code, default is 10 instructions\n");
728 PrintF(" from pc (alias 'di')\n");
730 PrintF(" enter gdb\n");
731 PrintF("break <address>\n");
732 PrintF(" set a break point on the address\n");
734 PrintF(" delete the breakpoint\n");
735 PrintF("stop feature:\n");
736 PrintF(" Description:\n");
737 PrintF(" Stops are debug instructions inserted by\n");
738 PrintF(" the Assembler::stop() function.\n");
739 PrintF(" When hitting a stop, the Simulator will\n");
740 PrintF(" stop and and give control to the Debugger.\n");
741 PrintF(" All stop codes are watched:\n");
742 PrintF(" - They can be enabled / disabled: the Simulator\n");
743 PrintF(" will / won't stop when hitting them.\n");
744 PrintF(" - The Simulator keeps track of how many times they \n");
745 PrintF(" are met. (See the info command.) Going over a\n");
746 PrintF(" disabled stop still increases its counter. \n");
747 PrintF(" Commands:\n");
748 PrintF(" stop info all/<code> : print infos about number <code>\n");
749 PrintF(" or all stop(s).\n");
750 PrintF(" stop enable/disable all/<code> : enables / disables\n");
751 PrintF(" all or number <code> stop(s)\n");
752 PrintF(" stop unstop\n");
753 PrintF(" ignore the stop instruction at the current location\n");
754 PrintF(" from now on\n");
756 PrintF("Unknown command: %s\n", cmd);
761 // Add all the breakpoints back to stop execution and enter the debugger
773 static bool ICacheMatch(void* one, void* two) {
774 DCHECK((reinterpret_cast<intptr_t>(one) & CachePage::kPageMask) == 0);
775 DCHECK((reinterpret_cast<intptr_t>(two) & CachePage::kPageMask) == 0);
780 static uint32_t ICacheHash(void* key) {
781 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(key)) >> 2;
785 static bool AllOnOnePage(uintptr_t start, int size) {
786 intptr_t start_page = (start & ~CachePage::kPageMask);
787 intptr_t end_page = ((start + size) & ~CachePage::kPageMask);
788 return start_page == end_page;
792 void Simulator::set_last_debugger_input(char* input) {
793 DeleteArray(last_debugger_input_);
794 last_debugger_input_ = input;
798 void Simulator::FlushICache(v8::internal::HashMap* i_cache,
801 int64_t start = reinterpret_cast<int64_t>(start_addr);
802 int64_t intra_line = (start & CachePage::kLineMask);
805 size = ((size - 1) | CachePage::kLineMask) + 1;
806 int offset = (start & CachePage::kPageMask);
807 while (!AllOnOnePage(start, size - 1)) {
808 int bytes_to_flush = CachePage::kPageSize - offset;
809 FlushOnePage(i_cache, start, bytes_to_flush);
810 start += bytes_to_flush;
811 size -= bytes_to_flush;
812 DCHECK_EQ((int64_t)0, start & CachePage::kPageMask);
816 FlushOnePage(i_cache, start, size);
821 CachePage* Simulator::GetCachePage(v8::internal::HashMap* i_cache, void* page) {
822 v8::internal::HashMap::Entry* entry = i_cache->Lookup(page,
825 if (entry->value == NULL) {
826 CachePage* new_page = new CachePage();
827 entry->value = new_page;
829 return reinterpret_cast<CachePage*>(entry->value);
833 // Flush from start up to and not including start + size.
834 void Simulator::FlushOnePage(v8::internal::HashMap* i_cache,
837 DCHECK(size <= CachePage::kPageSize);
838 DCHECK(AllOnOnePage(start, size - 1));
839 DCHECK((start & CachePage::kLineMask) == 0);
840 DCHECK((size & CachePage::kLineMask) == 0);
841 void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask));
842 int offset = (start & CachePage::kPageMask);
843 CachePage* cache_page = GetCachePage(i_cache, page);
844 char* valid_bytemap = cache_page->ValidityByte(offset);
845 memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift);
849 void Simulator::CheckICache(v8::internal::HashMap* i_cache,
850 Instruction* instr) {
851 int64_t address = reinterpret_cast<int64_t>(instr);
852 void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask));
853 void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask));
854 int offset = (address & CachePage::kPageMask);
855 CachePage* cache_page = GetCachePage(i_cache, page);
856 char* cache_valid_byte = cache_page->ValidityByte(offset);
857 bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID);
858 char* cached_line = cache_page->CachedData(offset & ~CachePage::kLineMask);
860 // Check that the data in memory matches the contents of the I-cache.
861 CHECK_EQ(0, memcmp(reinterpret_cast<void*>(instr),
862 cache_page->CachedData(offset),
863 Instruction::kInstrSize));
865 // Cache miss. Load memory into the cache.
866 memcpy(cached_line, line, CachePage::kLineLength);
867 *cache_valid_byte = CachePage::LINE_VALID;
872 void Simulator::Initialize(Isolate* isolate) {
873 if (isolate->simulator_initialized()) return;
874 isolate->set_simulator_initialized(true);
875 ::v8::internal::ExternalReference::set_redirector(isolate,
876 &RedirectExternalReference);
880 Simulator::Simulator(Isolate* isolate) : isolate_(isolate) {
881 i_cache_ = isolate_->simulator_i_cache();
882 if (i_cache_ == NULL) {
883 i_cache_ = new v8::internal::HashMap(&ICacheMatch);
884 isolate_->set_simulator_i_cache(i_cache_);
887 // Set up simulator support first. Some of this information is needed to
888 // setup the architecture state.
889 stack_size_ = FLAG_sim_stack_size * KB;
890 stack_ = reinterpret_cast<char*>(malloc(stack_size_));
891 pc_modified_ = false;
897 // Set up architecture state.
898 // All registers are initialized to zero to start with.
899 for (int i = 0; i < kNumSimuRegisters; i++) {
902 for (int i = 0; i < kNumFPURegisters; i++) {
903 FPUregisters_[i] = 0;
907 // The sp is initialized to point to the bottom (high address) of the
908 // allocated stack area. To be safe in potential stack underflows we leave
909 // some buffer below.
910 registers_[sp] = reinterpret_cast<int64_t>(stack_) + stack_size_ - 64;
911 // The ra and pc are initialized to a known bad value that will cause an
912 // access violation if the simulator ever tries to execute it.
913 registers_[pc] = bad_ra;
914 registers_[ra] = bad_ra;
915 InitializeCoverage();
916 for (int i = 0; i < kNumExceptions; i++) {
920 last_debugger_input_ = NULL;
924 Simulator::~Simulator() {
928 // When the generated code calls an external reference we need to catch that in
929 // the simulator. The external reference will be a function compiled for the
930 // host architecture. We need to call that function instead of trying to
931 // execute it with the simulator. We do that by redirecting the external
932 // reference to a swi (software-interrupt) instruction that is handled by
933 // the simulator. We write the original destination of the jump just at a known
934 // offset from the swi instruction so the simulator knows what to call.
937 Redirection(void* external_function, ExternalReference::Type type)
938 : external_function_(external_function),
939 swi_instruction_(rtCallRedirInstr),
942 Isolate* isolate = Isolate::Current();
943 next_ = isolate->simulator_redirection();
944 Simulator::current(isolate)->
945 FlushICache(isolate->simulator_i_cache(),
946 reinterpret_cast<void*>(&swi_instruction_),
947 Instruction::kInstrSize);
948 isolate->set_simulator_redirection(this);
951 void* address_of_swi_instruction() {
952 return reinterpret_cast<void*>(&swi_instruction_);
955 void* external_function() { return external_function_; }
956 ExternalReference::Type type() { return type_; }
958 static Redirection* Get(void* external_function,
959 ExternalReference::Type type) {
960 Isolate* isolate = Isolate::Current();
961 Redirection* current = isolate->simulator_redirection();
962 for (; current != NULL; current = current->next_) {
963 if (current->external_function_ == external_function) return current;
965 return new Redirection(external_function, type);
968 static Redirection* FromSwiInstruction(Instruction* swi_instruction) {
969 char* addr_of_swi = reinterpret_cast<char*>(swi_instruction);
970 char* addr_of_redirection =
971 addr_of_swi - OFFSET_OF(Redirection, swi_instruction_);
972 return reinterpret_cast<Redirection*>(addr_of_redirection);
975 static void* ReverseRedirection(int64_t reg) {
976 Redirection* redirection = FromSwiInstruction(
977 reinterpret_cast<Instruction*>(reinterpret_cast<void*>(reg)));
978 return redirection->external_function();
982 void* external_function_;
983 uint32_t swi_instruction_;
984 ExternalReference::Type type_;
989 void* Simulator::RedirectExternalReference(void* external_function,
990 ExternalReference::Type type) {
991 Redirection* redirection = Redirection::Get(external_function, type);
992 return redirection->address_of_swi_instruction();
996 // Get the active Simulator for the current thread.
997 Simulator* Simulator::current(Isolate* isolate) {
998 v8::internal::Isolate::PerIsolateThreadData* isolate_data =
999 isolate->FindOrAllocatePerThreadDataForThisThread();
1000 DCHECK(isolate_data != NULL);
1001 DCHECK(isolate_data != NULL);
1003 Simulator* sim = isolate_data->simulator();
1005 // TODO(146): delete the simulator object when a thread/isolate goes away.
1006 sim = new Simulator(isolate);
1007 isolate_data->set_simulator(sim);
1013 // Sets the register in the architecture state. It will also deal with updating
1014 // Simulator internal state for special registers such as PC.
1015 void Simulator::set_register(int reg, int64_t value) {
1016 DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1018 pc_modified_ = true;
1021 // Zero register always holds 0.
1022 registers_[reg] = (reg == 0) ? 0 : value;
1026 void Simulator::set_dw_register(int reg, const int* dbl) {
1027 DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1028 registers_[reg] = dbl[1];
1029 registers_[reg] = registers_[reg] << 32;
1030 registers_[reg] += dbl[0];
1034 void Simulator::set_fpu_register(int fpureg, int64_t value) {
1035 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1036 FPUregisters_[fpureg] = value;
1040 void Simulator::set_fpu_register_word(int fpureg, int32_t value) {
1041 // Set ONLY lower 32-bits, leaving upper bits untouched.
1042 // TODO(plind): big endian issue.
1043 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1044 int32_t *pword = reinterpret_cast<int32_t*>(&FPUregisters_[fpureg]);
1049 void Simulator::set_fpu_register_hi_word(int fpureg, int32_t value) {
1050 // Set ONLY upper 32-bits, leaving lower bits untouched.
1051 // TODO(plind): big endian issue.
1052 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1053 int32_t *phiword = (reinterpret_cast<int32_t*>(&FPUregisters_[fpureg])) + 1;
1058 void Simulator::set_fpu_register_float(int fpureg, float value) {
1059 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1060 *bit_cast<float*>(&FPUregisters_[fpureg]) = value;
1064 void Simulator::set_fpu_register_double(int fpureg, double value) {
1065 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1066 *bit_cast<double*>(&FPUregisters_[fpureg]) = value;
1070 // Get the register from the architecture state. This function does handle
1071 // the special case of accessing the PC register.
1072 int64_t Simulator::get_register(int reg) const {
1073 DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1077 return registers_[reg] + ((reg == pc) ? Instruction::kPCReadOffset : 0);
1081 double Simulator::get_double_from_register_pair(int reg) {
1082 // TODO(plind): bad ABI stuff, refactor or remove.
1083 DCHECK((reg >= 0) && (reg < kNumSimuRegisters) && ((reg % 2) == 0));
1085 double dm_val = 0.0;
1086 // Read the bits from the unsigned integer register_[] array
1087 // into the double precision floating point value and return it.
1088 char buffer[sizeof(registers_[0])];
1089 memcpy(buffer, ®isters_[reg], sizeof(registers_[0]));
1090 memcpy(&dm_val, buffer, sizeof(registers_[0]));
1095 int64_t Simulator::get_fpu_register(int fpureg) const {
1096 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1097 return FPUregisters_[fpureg];
1101 int32_t Simulator::get_fpu_register_word(int fpureg) const {
1102 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1103 return static_cast<int32_t>(FPUregisters_[fpureg] & 0xffffffff);
1107 int32_t Simulator::get_fpu_register_signed_word(int fpureg) const {
1108 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1109 return static_cast<int32_t>(FPUregisters_[fpureg] & 0xffffffff);
1113 int32_t Simulator::get_fpu_register_hi_word(int fpureg) const {
1114 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1115 return static_cast<int32_t>((FPUregisters_[fpureg] >> 32) & 0xffffffff);
1119 float Simulator::get_fpu_register_float(int fpureg) const {
1120 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1121 return *bit_cast<float*>(const_cast<int64_t*>(&FPUregisters_[fpureg]));
1125 double Simulator::get_fpu_register_double(int fpureg) const {
1126 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1127 return *bit_cast<double*>(&FPUregisters_[fpureg]);
1131 // Runtime FP routines take up to two double arguments and zero
1132 // or one integer arguments. All are constructed here,
1133 // from a0-a3 or f12 and f13 (n64), or f14 (O32).
1134 void Simulator::GetFpArgs(double* x, double* y, int32_t* z) {
1135 if (!IsMipsSoftFloatABI) {
1136 const int fparg2 = (kMipsAbi == kN64) ? 13 : 14;
1137 *x = get_fpu_register_double(12);
1138 *y = get_fpu_register_double(fparg2);
1139 *z = get_register(a2);
1141 // TODO(plind): bad ABI stuff, refactor or remove.
1142 // We use a char buffer to get around the strict-aliasing rules which
1143 // otherwise allow the compiler to optimize away the copy.
1144 char buffer[sizeof(*x)];
1145 int32_t* reg_buffer = reinterpret_cast<int32_t*>(buffer);
1147 // Registers a0 and a1 -> x.
1148 reg_buffer[0] = get_register(a0);
1149 reg_buffer[1] = get_register(a1);
1150 memcpy(x, buffer, sizeof(buffer));
1151 // Registers a2 and a3 -> y.
1152 reg_buffer[0] = get_register(a2);
1153 reg_buffer[1] = get_register(a3);
1154 memcpy(y, buffer, sizeof(buffer));
1156 reg_buffer[0] = get_register(a2);
1157 memcpy(z, buffer, sizeof(*z));
1162 // The return value is either in v0/v1 or f0.
1163 void Simulator::SetFpResult(const double& result) {
1164 if (!IsMipsSoftFloatABI) {
1165 set_fpu_register_double(0, result);
1167 char buffer[2 * sizeof(registers_[0])];
1168 int64_t* reg_buffer = reinterpret_cast<int64_t*>(buffer);
1169 memcpy(buffer, &result, sizeof(buffer));
1170 // Copy result to v0 and v1.
1171 set_register(v0, reg_buffer[0]);
1172 set_register(v1, reg_buffer[1]);
1177 // Helper functions for setting and testing the FCSR register's bits.
1178 void Simulator::set_fcsr_bit(uint32_t cc, bool value) {
1182 FCSR_ &= ~(1 << cc);
1187 bool Simulator::test_fcsr_bit(uint32_t cc) {
1188 return FCSR_ & (1 << cc);
1192 // Sets the rounding error codes in FCSR based on the result of the rounding.
1193 // Returns true if the operation was invalid.
1194 bool Simulator::set_fcsr_round_error(double original, double rounded) {
1196 double max_int32 = std::numeric_limits<int32_t>::max();
1197 double min_int32 = std::numeric_limits<int32_t>::min();
1199 if (!std::isfinite(original) || !std::isfinite(rounded)) {
1200 set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1204 if (original != rounded) {
1205 set_fcsr_bit(kFCSRInexactFlagBit, true);
1208 if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1209 set_fcsr_bit(kFCSRUnderflowFlagBit, true);
1213 if (rounded > max_int32 || rounded < min_int32) {
1214 set_fcsr_bit(kFCSROverflowFlagBit, true);
1215 // The reference is not really clear but it seems this is required:
1216 set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1224 // Sets the rounding error codes in FCSR based on the result of the rounding.
1225 // Returns true if the operation was invalid.
1226 bool Simulator::set_fcsr_round64_error(double original, double rounded) {
1228 double max_int64 = std::numeric_limits<int64_t>::max();
1229 double min_int64 = std::numeric_limits<int64_t>::min();
1231 if (!std::isfinite(original) || !std::isfinite(rounded)) {
1232 set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1236 if (original != rounded) {
1237 set_fcsr_bit(kFCSRInexactFlagBit, true);
1240 if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1241 set_fcsr_bit(kFCSRUnderflowFlagBit, true);
1245 if (rounded > max_int64 || rounded < min_int64) {
1246 set_fcsr_bit(kFCSROverflowFlagBit, true);
1247 // The reference is not really clear but it seems this is required:
1248 set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1256 // Raw access to the PC register.
1257 void Simulator::set_pc(int64_t value) {
1258 pc_modified_ = true;
1259 registers_[pc] = value;
1263 bool Simulator::has_bad_pc() const {
1264 return ((registers_[pc] == bad_ra) || (registers_[pc] == end_sim_pc));
1268 // Raw access to the PC register without the special adjustment when reading.
1269 int64_t Simulator::get_pc() const {
1270 return registers_[pc];
1274 // The MIPS cannot do unaligned reads and writes. On some MIPS platforms an
1275 // interrupt is caused. On others it does a funky rotation thing. For now we
1276 // simply disallow unaligned reads, but at some point we may want to move to
1277 // emulating the rotate behaviour. Note that simulator runs have the runtime
1278 // system running directly on the host system and only generated code is
1279 // executed in the simulator. Since the host is typically IA32 we will not
1280 // get the correct MIPS-like behaviour on unaligned accesses.
1282 // TODO(plind): refactor this messy debug code when we do unaligned access.
1283 void Simulator::DieOrDebug() {
1284 if (1) { // Flag for this was removed.
1285 MipsDebugger dbg(this);
1293 void Simulator::TraceRegWr(int64_t value) {
1294 if (::v8::internal::FLAG_trace_sim) {
1295 SNPrintF(trace_buf_, "%016lx", value);
1300 // TODO(plind): consider making icount_ printing a flag option.
1301 void Simulator::TraceMemRd(int64_t addr, int64_t value) {
1302 if (::v8::internal::FLAG_trace_sim) {
1303 SNPrintF(trace_buf_, "%016lx <-- [%016lx] (%ld)",
1304 value, addr, icount_);
1309 void Simulator::TraceMemWr(int64_t addr, int64_t value, TraceType t) {
1310 if (::v8::internal::FLAG_trace_sim) {
1313 SNPrintF(trace_buf_, " %02x --> [%016lx]",
1314 static_cast<int8_t>(value), addr);
1317 SNPrintF(trace_buf_, " %04x --> [%016lx]",
1318 static_cast<int16_t>(value), addr);
1321 SNPrintF(trace_buf_, " %08x --> [%016lx]",
1322 static_cast<int32_t>(value), addr);
1325 SNPrintF(trace_buf_, "%016lx --> [%016lx] (%ld)",
1326 value, addr, icount_);
1333 // TODO(plind): sign-extend and zero-extend not implmented properly
1334 // on all the ReadXX functions, I don't think re-interpret cast does it.
1335 int32_t Simulator::ReadW(int64_t addr, Instruction* instr) {
1336 if (addr >=0 && addr < 0x400) {
1337 // This has to be a NULL-dereference, drop into debugger.
1338 PrintF("Memory read from bad address: 0x%08lx, pc=0x%08lx\n",
1339 addr, reinterpret_cast<intptr_t>(instr));
1342 if ((addr & 0x3) == 0) {
1343 int32_t* ptr = reinterpret_cast<int32_t*>(addr);
1344 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1347 PrintF("Unaligned read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1349 reinterpret_cast<intptr_t>(instr));
1355 uint32_t Simulator::ReadWU(int64_t addr, Instruction* instr) {
1356 if (addr >=0 && addr < 0x400) {
1357 // This has to be a NULL-dereference, drop into debugger.
1358 PrintF("Memory read from bad address: 0x%08lx, pc=0x%08lx\n",
1359 addr, reinterpret_cast<intptr_t>(instr));
1362 if ((addr & 0x3) == 0) {
1363 uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
1364 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1367 PrintF("Unaligned read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1369 reinterpret_cast<intptr_t>(instr));
1375 void Simulator::WriteW(int64_t addr, int value, Instruction* instr) {
1376 if (addr >= 0 && addr < 0x400) {
1377 // This has to be a NULL-dereference, drop into debugger.
1378 PrintF("Memory write to bad address: 0x%08lx, pc=0x%08lx\n",
1379 addr, reinterpret_cast<intptr_t>(instr));
1382 if ((addr & 0x3) == 0) {
1383 TraceMemWr(addr, value, WORD);
1384 int* ptr = reinterpret_cast<int*>(addr);
1388 PrintF("Unaligned write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1390 reinterpret_cast<intptr_t>(instr));
1395 int64_t Simulator::Read2W(int64_t addr, Instruction* instr) {
1396 if (addr >=0 && addr < 0x400) {
1397 // This has to be a NULL-dereference, drop into debugger.
1398 PrintF("Memory read from bad address: 0x%08lx, pc=0x%08lx\n",
1399 addr, reinterpret_cast<intptr_t>(instr));
1402 if ((addr & kPointerAlignmentMask) == 0) {
1403 int64_t* ptr = reinterpret_cast<int64_t*>(addr);
1404 TraceMemRd(addr, *ptr);
1407 PrintF("Unaligned read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1409 reinterpret_cast<intptr_t>(instr));
1415 void Simulator::Write2W(int64_t addr, int64_t value, Instruction* instr) {
1416 if (addr >= 0 && addr < 0x400) {
1417 // This has to be a NULL-dereference, drop into debugger.
1418 PrintF("Memory write to bad address: 0x%08lx, pc=0x%08lx\n",
1419 addr, reinterpret_cast<intptr_t>(instr));
1422 if ((addr & kPointerAlignmentMask) == 0) {
1423 TraceMemWr(addr, value, DWORD);
1424 int64_t* ptr = reinterpret_cast<int64_t*>(addr);
1428 PrintF("Unaligned write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1430 reinterpret_cast<intptr_t>(instr));
1435 double Simulator::ReadD(int64_t addr, Instruction* instr) {
1436 if ((addr & kDoubleAlignmentMask) == 0) {
1437 double* ptr = reinterpret_cast<double*>(addr);
1440 PrintF("Unaligned (double) read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1442 reinterpret_cast<intptr_t>(instr));
1448 void Simulator::WriteD(int64_t addr, double value, Instruction* instr) {
1449 if ((addr & kDoubleAlignmentMask) == 0) {
1450 double* ptr = reinterpret_cast<double*>(addr);
1454 PrintF("Unaligned (double) write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1456 reinterpret_cast<intptr_t>(instr));
1461 uint16_t Simulator::ReadHU(int64_t addr, Instruction* instr) {
1462 if ((addr & 1) == 0) {
1463 uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
1464 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1467 PrintF("Unaligned unsigned halfword read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1469 reinterpret_cast<intptr_t>(instr));
1475 int16_t Simulator::ReadH(int64_t addr, Instruction* instr) {
1476 if ((addr & 1) == 0) {
1477 int16_t* ptr = reinterpret_cast<int16_t*>(addr);
1478 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1481 PrintF("Unaligned signed halfword read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1483 reinterpret_cast<intptr_t>(instr));
1489 void Simulator::WriteH(int64_t addr, uint16_t value, Instruction* instr) {
1490 if ((addr & 1) == 0) {
1491 TraceMemWr(addr, value, HALF);
1492 uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
1497 "Unaligned unsigned halfword write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1499 reinterpret_cast<intptr_t>(instr));
1504 void Simulator::WriteH(int64_t addr, int16_t value, Instruction* instr) {
1505 if ((addr & 1) == 0) {
1506 TraceMemWr(addr, value, HALF);
1507 int16_t* ptr = reinterpret_cast<int16_t*>(addr);
1511 PrintF("Unaligned halfword write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1513 reinterpret_cast<intptr_t>(instr));
1518 uint32_t Simulator::ReadBU(int64_t addr) {
1519 uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
1520 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1525 int32_t Simulator::ReadB(int64_t addr) {
1526 int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1527 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1532 void Simulator::WriteB(int64_t addr, uint8_t value) {
1533 TraceMemWr(addr, value, BYTE);
1534 uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
1539 void Simulator::WriteB(int64_t addr, int8_t value) {
1540 TraceMemWr(addr, value, BYTE);
1541 int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1546 // Returns the limit of the stack area to enable checking for stack overflows.
1547 uintptr_t Simulator::StackLimit() const {
1548 // Leave a safety margin of 1024 bytes to prevent overrunning the stack when
1550 return reinterpret_cast<uintptr_t>(stack_) + 1024;
1554 // Unsupported instructions use Format to print an error and stop execution.
1555 void Simulator::Format(Instruction* instr, const char* format) {
1556 PrintF("Simulator found unsupported instruction:\n 0x%08lx: %s\n",
1557 reinterpret_cast<intptr_t>(instr), format);
1558 UNIMPLEMENTED_MIPS();
1562 // Calls into the V8 runtime are based on this very simple interface.
1563 // Note: To be able to return two values from some calls the code in runtime.cc
1564 // uses the ObjectPair which is essentially two 32-bit values stuffed into a
1565 // 64-bit value. With the code below we assume that all runtime calls return
1566 // 64 bits of result. If they don't, the v1 result register contains a bogus
1567 // value, which is fine because it is caller-saved.
1574 typedef ObjectPair (*SimulatorRuntimeCall)(int64_t arg0,
1582 // These prototypes handle the four types of FP calls.
1583 typedef int64_t (*SimulatorRuntimeCompareCall)(double darg0, double darg1);
1584 typedef double (*SimulatorRuntimeFPFPCall)(double darg0, double darg1);
1585 typedef double (*SimulatorRuntimeFPCall)(double darg0);
1586 typedef double (*SimulatorRuntimeFPIntCall)(double darg0, int32_t arg0);
1588 // This signature supports direct call in to API function native callback
1589 // (refer to InvocationCallback in v8.h).
1590 typedef void (*SimulatorRuntimeDirectApiCall)(int64_t arg0);
1591 typedef void (*SimulatorRuntimeProfilingApiCall)(int64_t arg0, void* arg1);
1593 // This signature supports direct call to accessor getter callback.
1594 typedef void (*SimulatorRuntimeDirectGetterCall)(int64_t arg0, int64_t arg1);
1595 typedef void (*SimulatorRuntimeProfilingGetterCall)(
1596 int64_t arg0, int64_t arg1, void* arg2);
1598 // Software interrupt instructions are used by the simulator to call into the
1599 // C-based V8 runtime. They are also used for debugging with simulator.
1600 void Simulator::SoftwareInterrupt(Instruction* instr) {
1601 // There are several instructions that could get us here,
1602 // the break_ instruction, or several variants of traps. All
1603 // Are "SPECIAL" class opcode, and are distinuished by function.
1604 int32_t func = instr->FunctionFieldRaw();
1605 uint32_t code = (func == BREAK) ? instr->Bits(25, 6) : -1;
1606 // We first check if we met a call_rt_redirected.
1607 if (instr->InstructionBits() == rtCallRedirInstr) {
1608 Redirection* redirection = Redirection::FromSwiInstruction(instr);
1609 int64_t arg0 = get_register(a0);
1610 int64_t arg1 = get_register(a1);
1611 int64_t arg2 = get_register(a2);
1612 int64_t arg3 = get_register(a3);
1615 if (kMipsAbi == kN64) {
1616 arg4 = get_register(a4); // Abi n64 register a4.
1617 arg5 = get_register(a5); // Abi n64 register a5.
1618 } else { // Abi O32.
1619 int64_t* stack_pointer = reinterpret_cast<int64_t*>(get_register(sp));
1620 // Args 4 and 5 are on the stack after the reserved space for args 0..3.
1621 arg4 = stack_pointer[4];
1622 arg5 = stack_pointer[5];
1625 (redirection->type() == ExternalReference::BUILTIN_FP_FP_CALL) ||
1626 (redirection->type() == ExternalReference::BUILTIN_COMPARE_CALL) ||
1627 (redirection->type() == ExternalReference::BUILTIN_FP_CALL) ||
1628 (redirection->type() == ExternalReference::BUILTIN_FP_INT_CALL);
1630 if (!IsMipsSoftFloatABI) {
1631 // With the hard floating point calling convention, double
1632 // arguments are passed in FPU registers. Fetch the arguments
1633 // from there and call the builtin using soft floating point
1635 switch (redirection->type()) {
1636 case ExternalReference::BUILTIN_FP_FP_CALL:
1637 case ExternalReference::BUILTIN_COMPARE_CALL:
1638 arg0 = get_fpu_register(f12);
1639 arg1 = get_fpu_register(f13);
1640 arg2 = get_fpu_register(f14);
1641 arg3 = get_fpu_register(f15);
1643 case ExternalReference::BUILTIN_FP_CALL:
1644 arg0 = get_fpu_register(f12);
1645 arg1 = get_fpu_register(f13);
1647 case ExternalReference::BUILTIN_FP_INT_CALL:
1648 arg0 = get_fpu_register(f12);
1649 arg1 = get_fpu_register(f13);
1650 arg2 = get_register(a2);
1657 // This is dodgy but it works because the C entry stubs are never moved.
1658 // See comment in codegen-arm.cc and bug 1242173.
1659 int64_t saved_ra = get_register(ra);
1662 reinterpret_cast<intptr_t>(redirection->external_function());
1664 // Based on CpuFeatures::IsSupported(FPU), Mips will use either hardware
1665 // FPU, or gcc soft-float routines. Hardware FPU is simulated in this
1666 // simulator. Soft-float has additional abstraction of ExternalReference,
1667 // to support serialization.
1669 double dval0, dval1; // one or two double parameters
1670 int32_t ival; // zero or one integer parameters
1671 int64_t iresult = 0; // integer return value
1672 double dresult = 0; // double return value
1673 GetFpArgs(&dval0, &dval1, &ival);
1674 SimulatorRuntimeCall generic_target =
1675 reinterpret_cast<SimulatorRuntimeCall>(external);
1676 if (::v8::internal::FLAG_trace_sim) {
1677 switch (redirection->type()) {
1678 case ExternalReference::BUILTIN_FP_FP_CALL:
1679 case ExternalReference::BUILTIN_COMPARE_CALL:
1680 PrintF("Call to host function at %p with args %f, %f",
1681 FUNCTION_ADDR(generic_target), dval0, dval1);
1683 case ExternalReference::BUILTIN_FP_CALL:
1684 PrintF("Call to host function at %p with arg %f",
1685 FUNCTION_ADDR(generic_target), dval0);
1687 case ExternalReference::BUILTIN_FP_INT_CALL:
1688 PrintF("Call to host function at %p with args %f, %d",
1689 FUNCTION_ADDR(generic_target), dval0, ival);
1696 switch (redirection->type()) {
1697 case ExternalReference::BUILTIN_COMPARE_CALL: {
1698 SimulatorRuntimeCompareCall target =
1699 reinterpret_cast<SimulatorRuntimeCompareCall>(external);
1700 iresult = target(dval0, dval1);
1701 set_register(v0, static_cast<int64_t>(iresult));
1702 // set_register(v1, static_cast<int64_t>(iresult >> 32));
1705 case ExternalReference::BUILTIN_FP_FP_CALL: {
1706 SimulatorRuntimeFPFPCall target =
1707 reinterpret_cast<SimulatorRuntimeFPFPCall>(external);
1708 dresult = target(dval0, dval1);
1709 SetFpResult(dresult);
1712 case ExternalReference::BUILTIN_FP_CALL: {
1713 SimulatorRuntimeFPCall target =
1714 reinterpret_cast<SimulatorRuntimeFPCall>(external);
1715 dresult = target(dval0);
1716 SetFpResult(dresult);
1719 case ExternalReference::BUILTIN_FP_INT_CALL: {
1720 SimulatorRuntimeFPIntCall target =
1721 reinterpret_cast<SimulatorRuntimeFPIntCall>(external);
1722 dresult = target(dval0, ival);
1723 SetFpResult(dresult);
1730 if (::v8::internal::FLAG_trace_sim) {
1731 switch (redirection->type()) {
1732 case ExternalReference::BUILTIN_COMPARE_CALL:
1733 PrintF("Returned %08x\n", static_cast<int32_t>(iresult));
1735 case ExternalReference::BUILTIN_FP_FP_CALL:
1736 case ExternalReference::BUILTIN_FP_CALL:
1737 case ExternalReference::BUILTIN_FP_INT_CALL:
1738 PrintF("Returned %f\n", dresult);
1745 } else if (redirection->type() == ExternalReference::DIRECT_API_CALL) {
1746 if (::v8::internal::FLAG_trace_sim) {
1747 PrintF("Call to host function at %p args %08lx\n",
1748 reinterpret_cast<void*>(external), arg0);
1750 SimulatorRuntimeDirectApiCall target =
1751 reinterpret_cast<SimulatorRuntimeDirectApiCall>(external);
1754 redirection->type() == ExternalReference::PROFILING_API_CALL) {
1755 if (::v8::internal::FLAG_trace_sim) {
1756 PrintF("Call to host function at %p args %08lx %08lx\n",
1757 reinterpret_cast<void*>(external), arg0, arg1);
1759 SimulatorRuntimeProfilingApiCall target =
1760 reinterpret_cast<SimulatorRuntimeProfilingApiCall>(external);
1761 target(arg0, Redirection::ReverseRedirection(arg1));
1763 redirection->type() == ExternalReference::DIRECT_GETTER_CALL) {
1764 if (::v8::internal::FLAG_trace_sim) {
1765 PrintF("Call to host function at %p args %08lx %08lx\n",
1766 reinterpret_cast<void*>(external), arg0, arg1);
1768 SimulatorRuntimeDirectGetterCall target =
1769 reinterpret_cast<SimulatorRuntimeDirectGetterCall>(external);
1772 redirection->type() == ExternalReference::PROFILING_GETTER_CALL) {
1773 if (::v8::internal::FLAG_trace_sim) {
1774 PrintF("Call to host function at %p args %08lx %08lx %08lx\n",
1775 reinterpret_cast<void*>(external), arg0, arg1, arg2);
1777 SimulatorRuntimeProfilingGetterCall target =
1778 reinterpret_cast<SimulatorRuntimeProfilingGetterCall>(external);
1779 target(arg0, arg1, Redirection::ReverseRedirection(arg2));
1781 SimulatorRuntimeCall target =
1782 reinterpret_cast<SimulatorRuntimeCall>(external);
1783 if (::v8::internal::FLAG_trace_sim) {
1785 "Call to host function at %p "
1786 "args %08lx, %08lx, %08lx, %08lx, %08lx, %08lx\n",
1787 FUNCTION_ADDR(target),
1795 // int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5);
1796 // set_register(v0, static_cast<int32_t>(result));
1797 // set_register(v1, static_cast<int32_t>(result >> 32));
1798 ObjectPair result = target(arg0, arg1, arg2, arg3, arg4, arg5);
1799 set_register(v0, (int64_t)(result.x));
1800 set_register(v1, (int64_t)(result.y));
1802 if (::v8::internal::FLAG_trace_sim) {
1803 PrintF("Returned %08lx : %08lx\n", get_register(v1), get_register(v0));
1805 set_register(ra, saved_ra);
1806 set_pc(get_register(ra));
1808 } else if (func == BREAK && code <= kMaxStopCode) {
1809 if (IsWatchpoint(code)) {
1810 PrintWatchpoint(code);
1812 IncreaseStopCounter(code);
1813 HandleStop(code, instr);
1816 // All remaining break_ codes, and all traps are handled here.
1817 MipsDebugger dbg(this);
1823 // Stop helper functions.
1824 bool Simulator::IsWatchpoint(uint64_t code) {
1825 return (code <= kMaxWatchpointCode);
1829 void Simulator::PrintWatchpoint(uint64_t code) {
1830 MipsDebugger dbg(this);
1832 PrintF("\n---- break %ld marker: %3d (instr count: %8ld) ----------"
1833 "----------------------------------",
1834 code, break_count_, icount_);
1835 dbg.PrintAllRegs(); // Print registers and continue running.
1839 void Simulator::HandleStop(uint64_t code, Instruction* instr) {
1840 // Stop if it is enabled, otherwise go on jumping over the stop
1841 // and the message address.
1842 if (IsEnabledStop(code)) {
1843 MipsDebugger dbg(this);
1846 set_pc(get_pc() + 2 * Instruction::kInstrSize);
1851 bool Simulator::IsStopInstruction(Instruction* instr) {
1852 int32_t func = instr->FunctionFieldRaw();
1853 uint32_t code = static_cast<uint32_t>(instr->Bits(25, 6));
1854 return (func == BREAK) && code > kMaxWatchpointCode && code <= kMaxStopCode;
1858 bool Simulator::IsEnabledStop(uint64_t code) {
1859 DCHECK(code <= kMaxStopCode);
1860 DCHECK(code > kMaxWatchpointCode);
1861 return !(watched_stops_[code].count & kStopDisabledBit);
1865 void Simulator::EnableStop(uint64_t code) {
1866 if (!IsEnabledStop(code)) {
1867 watched_stops_[code].count &= ~kStopDisabledBit;
1872 void Simulator::DisableStop(uint64_t code) {
1873 if (IsEnabledStop(code)) {
1874 watched_stops_[code].count |= kStopDisabledBit;
1879 void Simulator::IncreaseStopCounter(uint64_t code) {
1880 DCHECK(code <= kMaxStopCode);
1881 if ((watched_stops_[code].count & ~(1 << 31)) == 0x7fffffff) {
1882 PrintF("Stop counter for code %ld has overflowed.\n"
1883 "Enabling this code and reseting the counter to 0.\n", code);
1884 watched_stops_[code].count = 0;
1887 watched_stops_[code].count++;
1892 // Print a stop status.
1893 void Simulator::PrintStopInfo(uint64_t code) {
1894 if (code <= kMaxWatchpointCode) {
1895 PrintF("That is a watchpoint, not a stop.\n");
1897 } else if (code > kMaxStopCode) {
1898 PrintF("Code too large, only %u stops can be used\n", kMaxStopCode + 1);
1901 const char* state = IsEnabledStop(code) ? "Enabled" : "Disabled";
1902 int32_t count = watched_stops_[code].count & ~kStopDisabledBit;
1903 // Don't print the state of unused breakpoints.
1905 if (watched_stops_[code].desc) {
1906 PrintF("stop %ld - 0x%lx: \t%s, \tcounter = %i, \t%s\n",
1907 code, code, state, count, watched_stops_[code].desc);
1909 PrintF("stop %ld - 0x%lx: \t%s, \tcounter = %i\n",
1910 code, code, state, count);
1916 void Simulator::SignalExceptions() {
1917 for (int i = 1; i < kNumExceptions; i++) {
1918 if (exceptions[i] != 0) {
1919 V8_Fatal(__FILE__, __LINE__, "Error: Exception %i raised.", i);
1925 // Handle execution based on instruction types.
1927 void Simulator::ConfigureTypeRegister(Instruction* instr,
1932 int64_t* return_addr_reg,
1934 int64_t* i128resultH,
1935 int64_t* i128resultL) {
1936 // Every local variable declared here needs to be const.
1937 // This is to make sure that changed values are sent back to
1938 // DecodeTypeRegister correctly.
1940 // Instruction fields.
1941 const Opcode op = instr->OpcodeFieldRaw();
1942 const int64_t rs_reg = instr->RsValue();
1943 const int64_t rs = get_register(rs_reg);
1944 const uint64_t rs_u = static_cast<uint64_t>(rs);
1945 const int64_t rt_reg = instr->RtValue();
1946 const int64_t rt = get_register(rt_reg);
1947 const uint64_t rt_u = static_cast<uint64_t>(rt);
1948 const int64_t rd_reg = instr->RdValue();
1949 const uint64_t sa = instr->SaValue();
1951 const int32_t fs_reg = instr->FsValue();
1954 // ---------- Configuration.
1956 case COP1: // Coprocessor instructions.
1957 switch (instr->RsFieldRaw()) {
1959 // At the moment only FCSR is supported.
1960 DCHECK(fs_reg == kFCSRRegister);
1964 *alu_out = static_cast<int64_t>(get_fpu_register_word(fs_reg));
1967 *alu_out = get_fpu_register(fs_reg);
1970 *alu_out = get_fpu_register_hi_word(fs_reg);
1981 // Do everything in the execution step.
1984 // BC1 BC1EQZ BC1NEZ handled in DecodeTypeImmed, should never come here.
1991 switch (instr->FunctionFieldRaw()) {
1994 *next_pc = get_register(instr->RsValue());
1995 *return_addr_reg = instr->RdValue();
1998 *alu_out = (int32_t)rt << sa;
2001 *alu_out = rt << sa;
2004 *alu_out = rt << sa << 32;
2008 // Regular logical right shift of a word by a fixed number of
2009 // bits instruction. RS field is always equal to 0.
2010 *alu_out = (uint32_t)rt_u >> sa;
2012 // Logical right-rotate of a word by a fixed number of bits. This
2013 // is special case of SRL instruction, added in MIPS32 Release 2.
2014 // RS field is equal to 00001.
2015 *alu_out = ((uint32_t)rt_u >> sa) | ((uint32_t)rt_u << (32 - sa));
2019 *alu_out = rt_u >> sa;
2022 *alu_out = rt_u >> sa >> 32;
2025 *alu_out = (int32_t)rt >> sa;
2028 *alu_out = rt >> sa;
2031 *alu_out = rt >> sa >> 32;
2034 *alu_out = (int32_t)rt << rs;
2037 *alu_out = rt << rs;
2041 // Regular logical right-shift of a word by a variable number of
2042 // bits instruction. SA field is always equal to 0.
2043 *alu_out = (uint32_t)rt_u >> rs;
2045 // Logical right-rotate of a word by a variable number of bits.
2046 // This is special case od SRLV instruction, added in MIPS32
2047 // Release 2. SA field is equal to 00001.
2049 ((uint32_t)rt_u >> rs_u) | ((uint32_t)rt_u << (32 - rs_u));
2054 // Regular logical right-shift of a word by a variable number of
2055 // bits instruction. SA field is always equal to 0.
2056 *alu_out = rt_u >> rs;
2058 // Logical right-rotate of a word by a variable number of bits.
2059 // This is special case od SRLV instruction, added in MIPS32
2060 // Release 2. SA field is equal to 00001.
2061 *alu_out = (rt_u >> rs_u) | (rt_u << (32 - rs_u));
2065 *alu_out = (int32_t)rt >> rs;
2068 *alu_out = rt >> rs;
2070 case MFHI: // MFHI == CLZ on R6.
2071 if (kArchVariant != kMips64r6) {
2072 DCHECK(instr->SaValue() == 0);
2073 *alu_out = get_register(HI);
2075 // MIPS spec: If no bits were set in GPR rs, the result written to
2077 DCHECK(instr->SaValue() == 1);
2078 *alu_out = base::bits::CountLeadingZeros32(rs_u);
2082 *alu_out = get_register(LO);
2084 case MULT: { // MULT == D_MUL_MUH.
2085 int32_t rs_lo = static_cast<int32_t>(rs);
2086 int32_t rt_lo = static_cast<int32_t>(rt);
2087 *i64hilo = static_cast<int64_t>(rs_lo) * static_cast<int64_t>(rt_lo);
2091 *u64hilo = static_cast<uint64_t>(rs_u & 0xffffffff) *
2092 static_cast<uint64_t>(rt_u & 0xffffffff);
2094 case DMULT: // DMULT == D_MUL_MUH.
2095 if (kArchVariant != kMips64r6) {
2096 *i128resultH = MultiplyHighSigned(rs, rt);
2097 *i128resultL = rs * rt;
2099 switch (instr->SaValue()) {
2101 *i128resultL = rs * rt;
2104 *i128resultH = MultiplyHighSigned(rs, rt);
2107 UNIMPLEMENTED_MIPS();
2113 UNIMPLEMENTED_MIPS();
2117 if (HaveSameSign(rs, rt)) {
2119 exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue - rt);
2120 } else if (rs < 0) {
2121 exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue - rt);
2127 int32_t alu32_out = rs + rt;
2128 // Sign-extend result of 32bit operation into 64bit register.
2129 *alu_out = static_cast<int64_t>(alu32_out);
2137 if (!HaveSameSign(rs, rt)) {
2139 exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue + rt);
2140 } else if (rs < 0) {
2141 exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue + rt);
2147 int32_t alu32_out = rs - rt;
2148 // Sign-extend result of 32bit operation into 64bit register.
2149 *alu_out = static_cast<int64_t>(alu32_out);
2165 *alu_out = ~(rs | rt);
2168 *alu_out = rs < rt ? 1 : 0;
2171 *alu_out = rs_u < rt_u ? 1 : 0;
2173 // Break and trap instructions.
2176 *do_interrupt = true;
2179 *do_interrupt = rs >= rt;
2182 *do_interrupt = rs_u >= rt_u;
2185 *do_interrupt = rs < rt;
2188 *do_interrupt = rs_u < rt_u;
2191 *do_interrupt = rs == rt;
2194 *do_interrupt = rs != rt;
2199 // No action taken on decode.
2205 // div and divu never raise exceptions.
2212 switch (instr->FunctionFieldRaw()) {
2214 // Only the lower 32 bits are kept.
2215 *alu_out = (int32_t)rs_u * (int32_t)rt_u;
2218 // MIPS32 spec: If no bits were set in GPR rs, the result written to
2220 *alu_out = base::bits::CountLeadingZeros32(rs_u);
2227 switch (instr->FunctionFieldRaw()) {
2228 case INS: { // Mips32r2 instruction.
2229 // Interpret rd field as 5-bit msb of insert.
2230 uint16_t msb = rd_reg;
2231 // Interpret sa field as 5-bit lsb of insert.
2233 uint16_t size = msb - lsb + 1;
2234 uint64_t mask = (1ULL << size) - 1;
2235 *alu_out = (rt_u & ~(mask << lsb)) | ((rs_u & mask) << lsb);
2238 case EXT: { // Mips32r2 instruction.
2239 // Interpret rd field as 5-bit msb of extract.
2240 uint16_t msb = rd_reg;
2241 // Interpret sa field as 5-bit lsb of extract.
2243 uint16_t size = msb + 1;
2244 uint64_t mask = (1ULL << size) - 1;
2245 *alu_out = static_cast<int32_t>((rs_u & (mask << lsb)) >> lsb);
2248 case DEXT: { // Mips32r2 instruction.
2249 // Interpret rd field as 5-bit msb of extract.
2250 uint16_t msb = rd_reg;
2251 // Interpret sa field as 5-bit lsb of extract.
2253 uint16_t size = msb + 1;
2254 uint64_t mask = (1ULL << size) - 1;
2255 *alu_out = static_cast<int64_t>((rs_u & (mask << lsb)) >> lsb);
2268 void Simulator::DecodeTypeRegister(Instruction* instr) {
2269 // Instruction fields.
2270 const Opcode op = instr->OpcodeFieldRaw();
2271 const int64_t rs_reg = instr->RsValue();
2272 const int64_t rs = get_register(rs_reg);
2273 const uint64_t rs_u = static_cast<uint32_t>(rs);
2274 const int64_t rt_reg = instr->RtValue();
2275 const int64_t rt = get_register(rt_reg);
2276 const uint64_t rt_u = static_cast<uint32_t>(rt);
2277 const int64_t rd_reg = instr->RdValue();
2279 const int32_t fr_reg = instr->FrValue();
2280 const int32_t fs_reg = instr->FsValue();
2281 const int32_t ft_reg = instr->FtValue();
2282 const int64_t fd_reg = instr->FdValue();
2283 int64_t i64hilo = 0;
2284 uint64_t u64hilo = 0;
2287 // It should not be used as is. Instructions using it should always
2288 // initialize it first.
2289 int64_t alu_out = 0x12345678;
2291 // For break and trap instructions.
2292 bool do_interrupt = false;
2296 int64_t current_pc = get_pc();
2298 int64_t next_pc = 0;
2299 int64_t return_addr_reg = 31;
2301 int64_t i128resultH;
2302 int64_t i128resultL;
2304 // Set up the variables if needed before executing the instruction.
2305 ConfigureTypeRegister(instr,
2315 // ---------- Raise exceptions triggered.
2318 // ---------- Execution.
2321 switch (instr->RsFieldRaw()) {
2322 case BC1: // Branch on coprocessor condition.
2328 set_register(rt_reg, alu_out);
2333 set_register(rt_reg, alu_out);
2336 // At the moment only FCSR is supported.
2337 DCHECK(fs_reg == kFCSRRegister);
2338 FCSR_ = registers_[rt_reg];
2341 // Hardware writes upper 32-bits to zero on mtc1.
2342 set_fpu_register_hi_word(fs_reg, 0);
2343 set_fpu_register_word(fs_reg, registers_[rt_reg]);
2346 set_fpu_register(fs_reg, registers_[rt_reg]);
2349 set_fpu_register_hi_word(fs_reg, registers_[rt_reg]);
2353 switch (instr->FunctionFieldRaw()) {
2355 f = get_fpu_register_float(fs_reg);
2356 set_fpu_register_double(fd_reg, static_cast<double>(f));
2359 // CVT_W_S CVT_L_S TRUNC_W_S ROUND_W_S ROUND_L_S FLOOR_W_S FLOOR_L_S
2360 // CEIL_W_S CEIL_L_S CVT_PS_S are unimplemented.
2366 uint32_t cc, fcsr_cc;
2368 fs = get_fpu_register_double(fs_reg);
2369 ft = get_fpu_register_double(ft_reg);
2370 cc = instr->FCccValue();
2371 fcsr_cc = get_fcsr_condition_bit(cc);
2372 switch (instr->FunctionFieldRaw()) {
2374 set_fpu_register_double(fd_reg, fs + ft);
2377 set_fpu_register_double(fd_reg, fs - ft);
2380 set_fpu_register_double(fd_reg, fs * ft);
2383 set_fpu_register_double(fd_reg, fs / ft);
2386 set_fpu_register_double(fd_reg, fabs(fs));
2389 set_fpu_register_double(fd_reg, fs);
2392 set_fpu_register_double(fd_reg, -fs);
2395 set_fpu_register_double(fd_reg, fast_sqrt(fs));
2398 set_fcsr_bit(fcsr_cc, std::isnan(fs) || std::isnan(ft));
2401 set_fcsr_bit(fcsr_cc, (fs == ft));
2404 set_fcsr_bit(fcsr_cc,
2405 (fs == ft) || (std::isnan(fs) || std::isnan(ft)));
2408 set_fcsr_bit(fcsr_cc, (fs < ft));
2411 set_fcsr_bit(fcsr_cc,
2412 (fs < ft) || (std::isnan(fs) || std::isnan(ft)));
2415 set_fcsr_bit(fcsr_cc, (fs <= ft));
2418 set_fcsr_bit(fcsr_cc,
2419 (fs <= ft) || (std::isnan(fs) || std::isnan(ft)));
2421 case CVT_W_D: // Convert double to word.
2422 // Rounding modes are not yet supported.
2423 DCHECK((FCSR_ & 3) == 0);
2424 // In rounding mode 0 it should behave like ROUND.
2426 case ROUND_W_D: // Round double to word (round half to even).
2428 double rounded = std::floor(fs + 0.5);
2429 int32_t result = static_cast<int32_t>(rounded);
2430 if ((result & 1) != 0 && result - fs == 0.5) {
2431 // If the number is halfway between two integers,
2432 // round to the even one.
2435 set_fpu_register_word(fd_reg, result);
2436 if (set_fcsr_round_error(fs, rounded)) {
2437 set_fpu_register(fd_reg, kFPUInvalidResult);
2441 case TRUNC_W_D: // Truncate double to word (round towards 0).
2443 double rounded = trunc(fs);
2444 int32_t result = static_cast<int32_t>(rounded);
2445 set_fpu_register_word(fd_reg, result);
2446 if (set_fcsr_round_error(fs, rounded)) {
2447 set_fpu_register(fd_reg, kFPUInvalidResult);
2451 case FLOOR_W_D: // Round double to word towards negative infinity.
2453 double rounded = std::floor(fs);
2454 int32_t result = static_cast<int32_t>(rounded);
2455 set_fpu_register_word(fd_reg, result);
2456 if (set_fcsr_round_error(fs, rounded)) {
2457 set_fpu_register(fd_reg, kFPUInvalidResult);
2461 case CEIL_W_D: // Round double to word towards positive infinity.
2463 double rounded = std::ceil(fs);
2464 int32_t result = static_cast<int32_t>(rounded);
2465 set_fpu_register_word(fd_reg, result);
2466 if (set_fcsr_round_error(fs, rounded)) {
2467 set_fpu_register(fd_reg, kFPUInvalidResult);
2471 case CVT_S_D: // Convert double to float (single).
2472 set_fpu_register_float(fd_reg, static_cast<float>(fs));
2474 case CVT_L_D: // Mips64r2: Truncate double to 64-bit long-word.
2475 // Rounding modes are not yet supported.
2476 DCHECK((FCSR_ & 3) == 0);
2477 // In rounding mode 0 it should behave like ROUND.
2479 case ROUND_L_D: { // Mips64r2 instruction.
2480 // check error cases
2481 double rounded = fs > 0 ? floor(fs + 0.5) : ceil(fs - 0.5);
2482 int64_t result = static_cast<int64_t>(rounded);
2483 set_fpu_register(fd_reg, result);
2484 if (set_fcsr_round64_error(fs, rounded)) {
2485 set_fpu_register(fd_reg, kFPU64InvalidResult);
2489 case TRUNC_L_D: { // Mips64r2 instruction.
2490 double rounded = trunc(fs);
2491 int64_t result = static_cast<int64_t>(rounded);
2492 set_fpu_register(fd_reg, result);
2493 if (set_fcsr_round64_error(fs, rounded)) {
2494 set_fpu_register(fd_reg, kFPU64InvalidResult);
2498 case FLOOR_L_D: { // Mips64r2 instruction.
2499 double rounded = floor(fs);
2500 int64_t result = static_cast<int64_t>(rounded);
2501 set_fpu_register(fd_reg, result);
2502 if (set_fcsr_round64_error(fs, rounded)) {
2503 set_fpu_register(fd_reg, kFPU64InvalidResult);
2507 case CEIL_L_D: { // Mips64r2 instruction.
2508 double rounded = ceil(fs);
2509 int64_t result = static_cast<int64_t>(rounded);
2510 set_fpu_register(fd_reg, result);
2511 if (set_fcsr_round64_error(fs, rounded)) {
2512 set_fpu_register(fd_reg, kFPU64InvalidResult);
2517 UNIMPLEMENTED_MIPS();
2524 switch (instr->FunctionFieldRaw()) {
2525 case CVT_S_W: // Convert word to float (single).
2526 alu_out = get_fpu_register_signed_word(fs_reg);
2527 set_fpu_register_float(fd_reg, static_cast<float>(alu_out));
2529 case CVT_D_W: // Convert word to double.
2530 alu_out = get_fpu_register_signed_word(fs_reg);
2531 set_fpu_register_double(fd_reg, static_cast<double>(alu_out));
2533 default: // Mips64r6 CMP.S instructions unimplemented.
2538 fs = get_fpu_register_double(fs_reg);
2539 ft = get_fpu_register_double(ft_reg);
2540 switch (instr->FunctionFieldRaw()) {
2541 case CVT_D_L: // Mips32r2 instruction.
2542 i64 = get_fpu_register(fs_reg);
2543 set_fpu_register_double(fd_reg, static_cast<double>(i64));
2546 UNIMPLEMENTED_MIPS();
2548 case CMP_AF: // Mips64r6 CMP.D instructions.
2549 UNIMPLEMENTED_MIPS();
2552 if (std::isnan(fs) || std::isnan(ft)) {
2553 set_fpu_register(fd_reg, -1);
2555 set_fpu_register(fd_reg, 0);
2560 set_fpu_register(fd_reg, -1);
2562 set_fpu_register(fd_reg, 0);
2566 if ((fs == ft) || (std::isnan(fs) || std::isnan(ft))) {
2567 set_fpu_register(fd_reg, -1);
2569 set_fpu_register(fd_reg, 0);
2574 set_fpu_register(fd_reg, -1);
2576 set_fpu_register(fd_reg, 0);
2580 if ((fs < ft) || (std::isnan(fs) || std::isnan(ft))) {
2581 set_fpu_register(fd_reg, -1);
2583 set_fpu_register(fd_reg, 0);
2588 set_fpu_register(fd_reg, -1);
2590 set_fpu_register(fd_reg, 0);
2594 if ((fs <= ft) || (std::isnan(fs) || std::isnan(ft))) {
2595 set_fpu_register(fd_reg, -1);
2597 set_fpu_register(fd_reg, 0);
2600 default: // CMP_OR CMP_UNE CMP_NE UNIMPLEMENTED
2609 switch (instr->FunctionFieldRaw()) {
2612 fr = get_fpu_register_double(fr_reg);
2613 fs = get_fpu_register_double(fs_reg);
2614 ft = get_fpu_register_double(ft_reg);
2615 set_fpu_register_double(fd_reg, fs * ft + fr);
2622 switch (instr->FunctionFieldRaw()) {
2624 Instruction* branch_delay_instr = reinterpret_cast<Instruction*>(
2625 current_pc+Instruction::kInstrSize);
2626 BranchDelayInstructionDecode(branch_delay_instr);
2628 pc_modified_ = true;
2632 Instruction* branch_delay_instr = reinterpret_cast<Instruction*>(
2633 current_pc+Instruction::kInstrSize);
2634 BranchDelayInstructionDecode(branch_delay_instr);
2635 set_register(return_addr_reg,
2636 current_pc + 2 * Instruction::kInstrSize);
2638 pc_modified_ = true;
2641 // Instructions using HI and LO registers.
2643 if (kArchVariant != kMips64r6) {
2644 set_register(LO, static_cast<int32_t>(i64hilo & 0xffffffff));
2645 set_register(HI, static_cast<int32_t>(i64hilo >> 32));
2647 switch (instr->SaValue()) {
2649 set_register(rd_reg,
2650 static_cast<int32_t>(i64hilo & 0xffffffff));
2653 set_register(rd_reg, static_cast<int32_t>(i64hilo >> 32));
2656 UNIMPLEMENTED_MIPS();
2662 set_register(LO, static_cast<int32_t>(u64hilo & 0xffffffff));
2663 set_register(HI, static_cast<int32_t>(u64hilo >> 32));
2665 case DMULT: // DMULT == D_MUL_MUH.
2666 if (kArchVariant != kMips64r6) {
2667 set_register(LO, static_cast<int64_t>(i128resultL));
2668 set_register(HI, static_cast<int64_t>(i128resultH));
2670 switch (instr->SaValue()) {
2672 set_register(rd_reg, static_cast<int64_t>(i128resultL));
2675 set_register(rd_reg, static_cast<int64_t>(i128resultH));
2678 UNIMPLEMENTED_MIPS();
2684 UNIMPLEMENTED_MIPS();
2687 set_register(rd_reg, alu_out);
2691 switch (kArchVariant) {
2693 // Divide by zero and overflow was not checked in the
2694 // configuration step - div and divu do not raise exceptions. On
2695 // division by 0 the result will be UNPREDICTABLE. On overflow
2696 // (INT_MIN/-1), return INT_MIN which is what the hardware does.
2697 if (rs == INT_MIN && rt == -1) {
2698 set_register(LO, INT_MIN);
2699 set_register(HI, 0);
2700 } else if (rt != 0) {
2701 set_register(LO, rs / rt);
2702 set_register(HI, rs % rt);
2706 switch (instr->SaValue()) {
2708 if (rs == INT_MIN && rt == -1) {
2709 set_register(rd_reg, INT_MIN);
2710 } else if (rt != 0) {
2711 set_register(rd_reg, rs / rt);
2715 if (rs == INT_MIN && rt == -1) {
2716 set_register(rd_reg, 0);
2717 } else if (rt != 0) {
2718 set_register(rd_reg, rs % rt);
2722 UNIMPLEMENTED_MIPS();
2732 set_register(LO, rs_u / rt_u);
2733 set_register(HI, rs_u % rt_u);
2736 // Break and trap instructions.
2745 SoftwareInterrupt(instr);
2748 // Conditional moves.
2751 set_register(rd_reg, rs);
2756 uint32_t cc = instr->FBccValue();
2757 uint32_t fcsr_cc = get_fcsr_condition_bit(cc);
2758 if (instr->Bit(16)) { // Read Tf bit.
2759 if (test_fcsr_bit(fcsr_cc)) set_register(rd_reg, rs);
2761 if (!test_fcsr_bit(fcsr_cc)) set_register(rd_reg, rs);
2767 set_register(rd_reg, rs);
2771 default: // For other special opcodes we do the default operation.
2772 set_register(rd_reg, alu_out);
2773 TraceRegWr(alu_out);
2777 switch (instr->FunctionFieldRaw()) {
2779 set_register(rd_reg, alu_out);
2780 TraceRegWr(alu_out);
2781 // HI and LO are UNPREDICTABLE after the operation.
2782 set_register(LO, Unpredictable);
2783 set_register(HI, Unpredictable);
2785 default: // For other special2 opcodes we do the default operation.
2786 set_register(rd_reg, alu_out);
2790 switch (instr->FunctionFieldRaw()) {
2792 // Ins instr leaves result in Rt, rather than Rd.
2793 set_register(rt_reg, alu_out);
2794 TraceRegWr(alu_out);
2798 // Dext/Ext instr leaves result in Rt, rather than Rd.
2799 set_register(rt_reg, alu_out);
2800 TraceRegWr(alu_out);
2806 // Unimplemented opcodes raised an error in the configuration step before,
2807 // so we can use the default here to set the destination register in common
2810 set_register(rd_reg, alu_out);
2811 TraceRegWr(alu_out);
2816 // Type 2: instructions using a 16 bytes immediate. (e.g. addi, beq).
2817 void Simulator::DecodeTypeImmediate(Instruction* instr) {
2818 // Instruction fields.
2819 Opcode op = instr->OpcodeFieldRaw();
2820 int64_t rs = get_register(instr->RsValue());
2821 uint64_t rs_u = static_cast<uint64_t>(rs);
2822 int64_t rt_reg = instr->RtValue(); // Destination register.
2823 int64_t rt = get_register(rt_reg);
2824 int16_t imm16 = instr->Imm16Value();
2826 int32_t ft_reg = instr->FtValue(); // Destination register.
2827 int64_t ft = get_fpu_register(ft_reg);
2829 // Zero extended immediate.
2830 uint64_t oe_imm16 = 0xffff & imm16;
2831 // Sign extended immediate.
2832 int64_t se_imm16 = imm16;
2835 int64_t current_pc = get_pc();
2837 int64_t next_pc = bad_ra;
2839 // Used for conditional branch instructions.
2840 bool do_branch = false;
2841 bool execute_branch_delay_instruction = false;
2843 // Used for arithmetic instructions.
2844 int64_t alu_out = 0;
2846 double fp_out = 0.0;
2847 uint32_t cc, cc_value, fcsr_cc;
2849 // Used for memory instructions.
2851 // Value to be written in memory.
2852 uint64_t mem_value = 0x0;
2853 // Alignment for 32-bit integers used in LWL, LWR, etc.
2854 const int kInt32AlignmentMask = sizeof(uint32_t) - 1;
2856 // ---------- Configuration (and execution for REGIMM).
2858 // ------------- COP1. Coprocessor instructions.
2860 switch (instr->RsFieldRaw()) {
2861 case BC1: // Branch on coprocessor condition.
2862 cc = instr->FBccValue();
2863 fcsr_cc = get_fcsr_condition_bit(cc);
2864 cc_value = test_fcsr_bit(fcsr_cc);
2865 do_branch = (instr->FBtrueValue()) ? cc_value : !cc_value;
2866 execute_branch_delay_instruction = true;
2869 next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2871 next_pc = current_pc + kBranchReturnOffset;
2875 do_branch = (ft & 0x1) ? false : true;
2876 execute_branch_delay_instruction = true;
2879 next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2881 next_pc = current_pc + kBranchReturnOffset;
2885 do_branch = (ft & 0x1) ? true : false;
2886 execute_branch_delay_instruction = true;
2889 next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2891 next_pc = current_pc + kBranchReturnOffset;
2898 // ------------- REGIMM class.
2900 switch (instr->RtFieldRaw()) {
2902 do_branch = (rs < 0);
2908 do_branch = rs >= 0;
2911 do_branch = rs >= 0;
2916 switch (instr->RtFieldRaw()) {
2921 // Branch instructions common part.
2922 execute_branch_delay_instruction = true;
2925 next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2926 if (instr->IsLinkingInstruction()) {
2927 set_register(31, current_pc + kBranchReturnOffset);
2930 next_pc = current_pc + kBranchReturnOffset;
2935 break; // case REGIMM.
2936 // ------------- Branch instructions.
2937 // When comparing to zero, the encoding of rt field is always 0, so we don't
2938 // need to replace rt with zero.
2940 do_branch = (rs == rt);
2943 do_branch = rs != rt;
2946 do_branch = rs <= 0;
2951 // ------------- Arithmetic instructions.
2954 if (HaveSameSign(rs, se_imm16)) {
2956 exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue - se_imm16);
2957 } else if (rs < 0) {
2958 exceptions[kIntegerUnderflow] =
2959 rs < (Registers::kMinValue - se_imm16);
2962 alu_out = rs + se_imm16;
2965 int32_t alu32_out = rs + se_imm16;
2966 // Sign-extend result of 32bit operation into 64bit register.
2967 alu_out = static_cast<int64_t>(alu32_out);
2971 alu_out = rs + se_imm16;
2974 alu_out = (rs < se_imm16) ? 1 : 0;
2977 alu_out = (rs_u < static_cast<uint32_t>(se_imm16)) ? 1 : 0;
2980 alu_out = rs & oe_imm16;
2983 alu_out = rs | oe_imm16;
2986 alu_out = rs ^ oe_imm16;
2989 int32_t alu32_out = (oe_imm16 << 16);
2990 // Sign-extend result of 32bit operation into 64bit register.
2991 alu_out = static_cast<int64_t>(alu32_out);
2994 // ------------- Memory instructions.
2996 addr = rs + se_imm16;
2997 alu_out = ReadB(addr);
3000 addr = rs + se_imm16;
3001 alu_out = ReadH(addr, instr);
3004 // al_offset is offset of the effective address within an aligned word.
3005 uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
3006 uint8_t byte_shift = kInt32AlignmentMask - al_offset;
3007 uint32_t mask = (1 << byte_shift * 8) - 1;
3008 addr = rs + se_imm16 - al_offset;
3009 alu_out = ReadW(addr, instr);
3010 alu_out <<= byte_shift * 8;
3011 alu_out |= rt & mask;
3015 addr = rs + se_imm16;
3016 alu_out = ReadW(addr, instr);
3019 addr = rs + se_imm16;
3020 alu_out = ReadWU(addr, instr);
3023 addr = rs + se_imm16;
3024 alu_out = Read2W(addr, instr);
3027 addr = rs + se_imm16;
3028 alu_out = ReadBU(addr);
3031 addr = rs + se_imm16;
3032 alu_out = ReadHU(addr, instr);
3035 // al_offset is offset of the effective address within an aligned word.
3036 uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
3037 uint8_t byte_shift = kInt32AlignmentMask - al_offset;
3038 uint32_t mask = al_offset ? (~0 << (byte_shift + 1) * 8) : 0;
3039 addr = rs + se_imm16 - al_offset;
3040 alu_out = ReadW(addr, instr);
3041 alu_out = static_cast<uint32_t> (alu_out) >> al_offset * 8;
3042 alu_out |= rt & mask;
3046 addr = rs + se_imm16;
3049 addr = rs + se_imm16;
3052 uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
3053 uint8_t byte_shift = kInt32AlignmentMask - al_offset;
3054 uint32_t mask = byte_shift ? (~0 << (al_offset + 1) * 8) : 0;
3055 addr = rs + se_imm16 - al_offset;
3056 mem_value = ReadW(addr, instr) & mask;
3057 mem_value |= static_cast<uint32_t>(rt) >> byte_shift * 8;
3062 addr = rs + se_imm16;
3065 uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
3066 uint32_t mask = (1 << al_offset * 8) - 1;
3067 addr = rs + se_imm16 - al_offset;
3068 mem_value = ReadW(addr, instr);
3069 mem_value = (rt << al_offset * 8) | (mem_value & mask);
3073 addr = rs + se_imm16;
3074 alu_out = ReadW(addr, instr);
3077 addr = rs + se_imm16;
3078 fp_out = ReadD(addr, instr);
3082 addr = rs + se_imm16;
3088 // ---------- Raise exceptions triggered.
3091 // ---------- Execution.
3093 // ------------- Branch instructions.
3098 // Branch instructions common part.
3099 execute_branch_delay_instruction = true;
3102 next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
3103 if (instr->IsLinkingInstruction()) {
3104 set_register(31, current_pc + 2* Instruction::kInstrSize);
3107 next_pc = current_pc + 2 * Instruction::kInstrSize;
3110 // ------------- Arithmetic instructions.
3121 set_register(rt_reg, alu_out);
3122 TraceRegWr(alu_out);
3124 // ------------- Memory instructions.
3134 set_register(rt_reg, alu_out);
3137 WriteB(addr, static_cast<int8_t>(rt));
3140 WriteH(addr, static_cast<uint16_t>(rt), instr);
3143 WriteW(addr, mem_value, instr);
3146 WriteW(addr, rt, instr);
3149 Write2W(addr, rt, instr);
3152 WriteW(addr, mem_value, instr);
3155 set_fpu_register(ft_reg, kFPUInvalidResult); // Trash upper 32 bits.
3156 set_fpu_register_word(ft_reg, static_cast<int32_t>(alu_out));
3159 set_fpu_register_double(ft_reg, fp_out);
3162 addr = rs + se_imm16;
3163 WriteW(addr, get_fpu_register(ft_reg), instr);
3166 addr = rs + se_imm16;
3167 WriteD(addr, get_fpu_register_double(ft_reg), instr);
3174 if (execute_branch_delay_instruction) {
3175 // Execute branch delay slot
3176 // We don't check for end_sim_pc. First it should not be met as the current
3177 // pc is valid. Secondly a jump should always execute its branch delay slot.
3178 Instruction* branch_delay_instr =
3179 reinterpret_cast<Instruction*>(current_pc+Instruction::kInstrSize);
3180 BranchDelayInstructionDecode(branch_delay_instr);
3183 // If needed update pc after the branch delay execution.
3184 if (next_pc != bad_ra) {
3190 // Type 3: instructions using a 26 bytes immediate. (e.g. j, jal).
3191 void Simulator::DecodeTypeJump(Instruction* instr) {
3193 int32_t current_pc = get_pc();
3194 // Get unchanged bits of pc.
3195 int32_t pc_high_bits = current_pc & 0xf0000000;
3197 int32_t next_pc = pc_high_bits | (instr->Imm26Value() << 2);
3199 // Execute branch delay slot.
3200 // We don't check for end_sim_pc. First it should not be met as the current pc
3201 // is valid. Secondly a jump should always execute its branch delay slot.
3202 Instruction* branch_delay_instr =
3203 reinterpret_cast<Instruction*>(current_pc + Instruction::kInstrSize);
3204 BranchDelayInstructionDecode(branch_delay_instr);
3206 // Update pc and ra if necessary.
3207 // Do this after the branch delay execution.
3208 if (instr->IsLinkingInstruction()) {
3209 set_register(31, current_pc + 2 * Instruction::kInstrSize);
3212 pc_modified_ = true;
3216 // Executes the current instruction.
3217 void Simulator::InstructionDecode(Instruction* instr) {
3218 if (v8::internal::FLAG_check_icache) {
3219 CheckICache(isolate_->simulator_i_cache(), instr);
3221 pc_modified_ = false;
3223 v8::internal::EmbeddedVector<char, 256> buffer;
3225 if (::v8::internal::FLAG_trace_sim) {
3226 SNPrintF(trace_buf_, " ");
3227 disasm::NameConverter converter;
3228 disasm::Disassembler dasm(converter);
3229 // Use a reasonably large buffer.
3230 dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(instr));
3233 switch (instr->InstructionType()) {
3234 case Instruction::kRegisterType:
3235 DecodeTypeRegister(instr);
3237 case Instruction::kImmediateType:
3238 DecodeTypeImmediate(instr);
3240 case Instruction::kJumpType:
3241 DecodeTypeJump(instr);
3247 if (::v8::internal::FLAG_trace_sim) {
3248 PrintF(" 0x%08lx %-44s %s\n", reinterpret_cast<intptr_t>(instr),
3249 buffer.start(), trace_buf_.start());
3252 if (!pc_modified_) {
3253 set_register(pc, reinterpret_cast<int64_t>(instr) +
3254 Instruction::kInstrSize);
3260 void Simulator::Execute() {
3261 // Get the PC to simulate. Cannot use the accessor here as we need the
3262 // raw PC value and not the one used as input to arithmetic instructions.
3263 int64_t program_counter = get_pc();
3264 if (::v8::internal::FLAG_stop_sim_at == 0) {
3265 // Fast version of the dispatch loop without checking whether the simulator
3266 // should be stopping at a particular executed instruction.
3267 while (program_counter != end_sim_pc) {
3268 Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
3270 InstructionDecode(instr);
3271 program_counter = get_pc();
3274 // FLAG_stop_sim_at is at the non-default value. Stop in the debugger when
3275 // we reach the particular instuction count.
3276 while (program_counter != end_sim_pc) {
3277 Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
3279 if (icount_ == static_cast<int64_t>(::v8::internal::FLAG_stop_sim_at)) {
3280 MipsDebugger dbg(this);
3283 InstructionDecode(instr);
3285 program_counter = get_pc();
3291 void Simulator::CallInternal(byte* entry) {
3292 // Prepare to execute the code at entry.
3293 set_register(pc, reinterpret_cast<int64_t>(entry));
3294 // Put down marker for end of simulation. The simulator will stop simulation
3295 // when the PC reaches this value. By saving the "end simulation" value into
3296 // the LR the simulation stops when returning to this call point.
3297 set_register(ra, end_sim_pc);
3299 // Remember the values of callee-saved registers.
3300 // The code below assumes that r9 is not used as sb (static base) in
3301 // simulator code and therefore is regarded as a callee-saved register.
3302 int64_t s0_val = get_register(s0);
3303 int64_t s1_val = get_register(s1);
3304 int64_t s2_val = get_register(s2);
3305 int64_t s3_val = get_register(s3);
3306 int64_t s4_val = get_register(s4);
3307 int64_t s5_val = get_register(s5);
3308 int64_t s6_val = get_register(s6);
3309 int64_t s7_val = get_register(s7);
3310 int64_t gp_val = get_register(gp);
3311 int64_t sp_val = get_register(sp);
3312 int64_t fp_val = get_register(fp);
3314 // Set up the callee-saved registers with a known value. To be able to check
3315 // that they are preserved properly across JS execution.
3316 int64_t callee_saved_value = icount_;
3317 set_register(s0, callee_saved_value);
3318 set_register(s1, callee_saved_value);
3319 set_register(s2, callee_saved_value);
3320 set_register(s3, callee_saved_value);
3321 set_register(s4, callee_saved_value);
3322 set_register(s5, callee_saved_value);
3323 set_register(s6, callee_saved_value);
3324 set_register(s7, callee_saved_value);
3325 set_register(gp, callee_saved_value);
3326 set_register(fp, callee_saved_value);
3328 // Start the simulation.
3331 // Check that the callee-saved registers have been preserved.
3332 CHECK_EQ(callee_saved_value, get_register(s0));
3333 CHECK_EQ(callee_saved_value, get_register(s1));
3334 CHECK_EQ(callee_saved_value, get_register(s2));
3335 CHECK_EQ(callee_saved_value, get_register(s3));
3336 CHECK_EQ(callee_saved_value, get_register(s4));
3337 CHECK_EQ(callee_saved_value, get_register(s5));
3338 CHECK_EQ(callee_saved_value, get_register(s6));
3339 CHECK_EQ(callee_saved_value, get_register(s7));
3340 CHECK_EQ(callee_saved_value, get_register(gp));
3341 CHECK_EQ(callee_saved_value, get_register(fp));
3343 // Restore callee-saved registers with the original value.
3344 set_register(s0, s0_val);
3345 set_register(s1, s1_val);
3346 set_register(s2, s2_val);
3347 set_register(s3, s3_val);
3348 set_register(s4, s4_val);
3349 set_register(s5, s5_val);
3350 set_register(s6, s6_val);
3351 set_register(s7, s7_val);
3352 set_register(gp, gp_val);
3353 set_register(sp, sp_val);
3354 set_register(fp, fp_val);
3358 int64_t Simulator::Call(byte* entry, int argument_count, ...) {
3359 const int kRegisterPassedArguments = (kMipsAbi == kN64) ? 8 : 4;
3361 va_start(parameters, argument_count);
3362 // Set up arguments.
3364 // First four arguments passed in registers in both ABI's.
3365 DCHECK(argument_count >= 4);
3366 set_register(a0, va_arg(parameters, int64_t));
3367 set_register(a1, va_arg(parameters, int64_t));
3368 set_register(a2, va_arg(parameters, int64_t));
3369 set_register(a3, va_arg(parameters, int64_t));
3371 if (kMipsAbi == kN64) {
3372 // Up to eight arguments passed in registers in N64 ABI.
3373 // TODO(plind): N64 ABI calls these regs a4 - a7. Clarify this.
3374 if (argument_count >= 5) set_register(a4, va_arg(parameters, int64_t));
3375 if (argument_count >= 6) set_register(a5, va_arg(parameters, int64_t));
3376 if (argument_count >= 7) set_register(a6, va_arg(parameters, int64_t));
3377 if (argument_count >= 8) set_register(a7, va_arg(parameters, int64_t));
3380 // Remaining arguments passed on stack.
3381 int64_t original_stack = get_register(sp);
3382 // Compute position of stack on entry to generated code.
3383 int stack_args_count = (argument_count > kRegisterPassedArguments) ?
3384 (argument_count - kRegisterPassedArguments) : 0;
3385 int stack_args_size = stack_args_count * sizeof(int64_t) + kCArgsSlotsSize;
3386 int64_t entry_stack = original_stack - stack_args_size;
3388 if (base::OS::ActivationFrameAlignment() != 0) {
3389 entry_stack &= -base::OS::ActivationFrameAlignment();
3391 // Store remaining arguments on stack, from low to high memory.
3392 intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack);
3393 for (int i = kRegisterPassedArguments; i < argument_count; i++) {
3394 int stack_index = i - kRegisterPassedArguments + kCArgSlotCount;
3395 stack_argument[stack_index] = va_arg(parameters, int64_t);
3398 set_register(sp, entry_stack);
3400 CallInternal(entry);
3402 // Pop stack passed arguments.
3403 CHECK_EQ(entry_stack, get_register(sp));
3404 set_register(sp, original_stack);
3406 int64_t result = get_register(v0);
3411 double Simulator::CallFP(byte* entry, double d0, double d1) {
3412 if (!IsMipsSoftFloatABI) {
3413 const FPURegister fparg2 = (kMipsAbi == kN64) ? f13 : f14;
3414 set_fpu_register_double(f12, d0);
3415 set_fpu_register_double(fparg2, d1);
3418 DCHECK(sizeof(buffer[0]) * 2 == sizeof(d0));
3419 memcpy(buffer, &d0, sizeof(d0));
3420 set_dw_register(a0, buffer);
3421 memcpy(buffer, &d1, sizeof(d1));
3422 set_dw_register(a2, buffer);
3424 CallInternal(entry);
3425 if (!IsMipsSoftFloatABI) {
3426 return get_fpu_register_double(f0);
3428 return get_double_from_register_pair(v0);
3433 uintptr_t Simulator::PushAddress(uintptr_t address) {
3434 int64_t new_sp = get_register(sp) - sizeof(uintptr_t);
3435 uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp);
3436 *stack_slot = address;
3437 set_register(sp, new_sp);
3442 uintptr_t Simulator::PopAddress() {
3443 int64_t current_sp = get_register(sp);
3444 uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp);
3445 uintptr_t address = *stack_slot;
3446 set_register(sp, current_sp + sizeof(uintptr_t));
3453 } } // namespace v8::internal
3455 #endif // USE_SIMULATOR
3457 #endif // V8_TARGET_ARCH_MIPS64