Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / v8 / src / mips64 / simulator-mips64.cc
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.
4
5 #include <limits.h>
6 #include <stdarg.h>
7 #include <stdlib.h>
8 #include <cmath>
9
10 #include "src/v8.h"
11
12 #if V8_TARGET_ARCH_MIPS64
13
14 #include "src/assembler.h"
15 #include "src/base/bits.h"
16 #include "src/disasm.h"
17 #include "src/mips64/constants-mips64.h"
18 #include "src/mips64/simulator-mips64.h"
19 #include "src/ostreams.h"
20
21 // Only build the simulator if not compiling for real MIPS hardware.
22 #if defined(USE_SIMULATOR)
23
24 namespace v8 {
25 namespace internal {
26
27 // Utils functions.
28 bool HaveSameSign(int64_t a, int64_t b) {
29   return ((a ^ b) >= 0);
30 }
31
32
33 uint32_t get_fcsr_condition_bit(uint32_t cc) {
34   if (cc == 0) {
35     return 23;
36   } else {
37     return 24 + cc;
38   }
39 }
40
41
42 static int64_t MultiplyHighSigned(int64_t u, int64_t v) {
43   uint64_t u0, v0, w0;
44   int64_t u1, v1, w1, w2, t;
45
46   u0 = u & 0xffffffffL;
47   u1 = u >> 32;
48   v0 = v & 0xffffffffL;
49   v1 = v >> 32;
50
51   w0 = u0 * v0;
52   t = u1 * v0 + (w0 >> 32);
53   w1 = t & 0xffffffffL;
54   w2 = t >> 32;
55   w1 = u0 * v1 + w1;
56
57   return u1 * v1 + w2 + (w1 >> 32);
58 }
59
60
61 // This macro provides a platform independent use of sscanf. The reason for
62 // SScanF not being implemented in a platform independent was through
63 // ::v8::internal::OS in the same way as SNPrintF is that the Windows C Run-Time
64 // Library does not provide vsscanf.
65 #define SScanF sscanf  // NOLINT
66
67 // The MipsDebugger class is used by the simulator while debugging simulated
68 // code.
69 class MipsDebugger {
70  public:
71   explicit MipsDebugger(Simulator* sim) : sim_(sim) { }
72   ~MipsDebugger();
73
74   void Stop(Instruction* instr);
75   void Debug();
76   // Print all registers with a nice formatting.
77   void PrintAllRegs();
78   void PrintAllRegsIncludingFPU();
79
80  private:
81   // We set the breakpoint code to 0xfffff to easily recognize it.
82   static const Instr kBreakpointInstr = SPECIAL | BREAK | 0xfffff << 6;
83   static const Instr kNopInstr =  0x0;
84
85   Simulator* sim_;
86
87   int64_t GetRegisterValue(int regnum);
88   int64_t GetFPURegisterValue(int regnum);
89   float GetFPURegisterValueFloat(int regnum);
90   double GetFPURegisterValueDouble(int regnum);
91   bool GetValue(const char* desc, int64_t* value);
92
93   // Set or delete a breakpoint. Returns true if successful.
94   bool SetBreakpoint(Instruction* breakpc);
95   bool DeleteBreakpoint(Instruction* breakpc);
96
97   // Undo and redo all breakpoints. This is needed to bracket disassembly and
98   // execution to skip past breakpoints when run from the debugger.
99   void UndoBreakpoints();
100   void RedoBreakpoints();
101 };
102
103
104 MipsDebugger::~MipsDebugger() {
105 }
106
107
108 #ifdef GENERATED_CODE_COVERAGE
109 static FILE* coverage_log = NULL;
110
111
112 static void InitializeCoverage() {
113   char* file_name = getenv("V8_GENERATED_CODE_COVERAGE_LOG");
114   if (file_name != NULL) {
115     coverage_log = fopen(file_name, "aw+");
116   }
117 }
118
119
120 void MipsDebugger::Stop(Instruction* instr) {
121   // Get the stop code.
122   uint32_t code = instr->Bits(25, 6);
123   // Retrieve the encoded address, which comes just after this stop.
124   char** msg_address =
125     reinterpret_cast<char**>(sim_->get_pc() + Instr::kInstrSize);
126   char* msg = *msg_address;
127   DCHECK(msg != NULL);
128
129   // Update this stop description.
130   if (!watched_stops_[code].desc) {
131     watched_stops_[code].desc = msg;
132   }
133
134   if (strlen(msg) > 0) {
135     if (coverage_log != NULL) {
136       fprintf(coverage_log, "%s\n", str);
137       fflush(coverage_log);
138     }
139     // Overwrite the instruction and address with nops.
140     instr->SetInstructionBits(kNopInstr);
141     reinterpret_cast<Instr*>(msg_address)->SetInstructionBits(kNopInstr);
142   }
143   // TODO(yuyin): 2 -> 3?
144   sim_->set_pc(sim_->get_pc() + 3 * Instruction::kInstructionSize);
145 }
146
147
148 #else  // GENERATED_CODE_COVERAGE
149
150 #define UNSUPPORTED() printf("Unsupported instruction.\n");
151
152 static void InitializeCoverage() {}
153
154
155 void MipsDebugger::Stop(Instruction* instr) {
156   // Get the stop code.
157   uint32_t code = instr->Bits(25, 6);
158   // Retrieve the encoded address, which comes just after this stop.
159   char* msg = *reinterpret_cast<char**>(sim_->get_pc() +
160       Instruction::kInstrSize);
161   // Update this stop description.
162   if (!sim_->watched_stops_[code].desc) {
163     sim_->watched_stops_[code].desc = msg;
164   }
165   PrintF("Simulator hit %s (%u)\n", msg, code);
166   // TODO(yuyin): 2 -> 3?
167   sim_->set_pc(sim_->get_pc() + 3 * Instruction::kInstrSize);
168   Debug();
169 }
170 #endif  // GENERATED_CODE_COVERAGE
171
172
173 int64_t MipsDebugger::GetRegisterValue(int regnum) {
174   if (regnum == kNumSimuRegisters) {
175     return sim_->get_pc();
176   } else {
177     return sim_->get_register(regnum);
178   }
179 }
180
181
182 int64_t MipsDebugger::GetFPURegisterValue(int regnum) {
183   if (regnum == kNumFPURegisters) {
184     return sim_->get_pc();
185   } else {
186     return sim_->get_fpu_register(regnum);
187   }
188 }
189
190
191 float MipsDebugger::GetFPURegisterValueFloat(int regnum) {
192   if (regnum == kNumFPURegisters) {
193     return sim_->get_pc();
194   } else {
195     return sim_->get_fpu_register_float(regnum);
196   }
197 }
198
199
200 double MipsDebugger::GetFPURegisterValueDouble(int regnum) {
201   if (regnum == kNumFPURegisters) {
202     return sim_->get_pc();
203   } else {
204     return sim_->get_fpu_register_double(regnum);
205   }
206 }
207
208
209 bool MipsDebugger::GetValue(const char* desc, int64_t* value) {
210   int regnum = Registers::Number(desc);
211   int fpuregnum = FPURegisters::Number(desc);
212
213   if (regnum != kInvalidRegister) {
214     *value = GetRegisterValue(regnum);
215     return true;
216   } else if (fpuregnum != kInvalidFPURegister) {
217     *value = GetFPURegisterValue(fpuregnum);
218     return true;
219   } else if (strncmp(desc, "0x", 2) == 0) {
220     return SScanF(desc + 2, "%" SCNx64,
221                   reinterpret_cast<uint64_t*>(value)) == 1;
222   } else {
223     return SScanF(desc, "%" SCNu64, reinterpret_cast<uint64_t*>(value)) == 1;
224   }
225   return false;
226 }
227
228
229 bool MipsDebugger::SetBreakpoint(Instruction* breakpc) {
230   // Check if a breakpoint can be set. If not return without any side-effects.
231   if (sim_->break_pc_ != NULL) {
232     return false;
233   }
234
235   // Set the breakpoint.
236   sim_->break_pc_ = breakpc;
237   sim_->break_instr_ = breakpc->InstructionBits();
238   // Not setting the breakpoint instruction in the code itself. It will be set
239   // when the debugger shell continues.
240   return true;
241 }
242
243
244 bool MipsDebugger::DeleteBreakpoint(Instruction* breakpc) {
245   if (sim_->break_pc_ != NULL) {
246     sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
247   }
248
249   sim_->break_pc_ = NULL;
250   sim_->break_instr_ = 0;
251   return true;
252 }
253
254
255 void MipsDebugger::UndoBreakpoints() {
256   if (sim_->break_pc_ != NULL) {
257     sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
258   }
259 }
260
261
262 void MipsDebugger::RedoBreakpoints() {
263   if (sim_->break_pc_ != NULL) {
264     sim_->break_pc_->SetInstructionBits(kBreakpointInstr);
265   }
266 }
267
268
269 void MipsDebugger::PrintAllRegs() {
270 #define REG_INFO(n) Registers::Name(n), GetRegisterValue(n), GetRegisterValue(n)
271
272   PrintF("\n");
273   // at, v0, a0.
274   PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
275          REG_INFO(1), REG_INFO(2), REG_INFO(4));
276   // v1, a1.
277   PrintF("%34s\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
278          "", REG_INFO(3), REG_INFO(5));
279   // a2.
280   PrintF("%34s\t%34s\t%3s: 0x%016lx %14ld\n", "", "", REG_INFO(6));
281   // a3.
282   PrintF("%34s\t%34s\t%3s: 0x%016lx %14ld\n", "", "", REG_INFO(7));
283   PrintF("\n");
284   // a4-t3, s0-s7
285   for (int i = 0; i < 8; i++) {
286     PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
287            REG_INFO(8+i), REG_INFO(16+i));
288   }
289   PrintF("\n");
290   // t8, k0, LO.
291   PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
292          REG_INFO(24), REG_INFO(26), REG_INFO(32));
293   // t9, k1, HI.
294   PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
295          REG_INFO(25), REG_INFO(27), REG_INFO(33));
296   // sp, fp, gp.
297   PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
298          REG_INFO(29), REG_INFO(30), REG_INFO(28));
299   // pc.
300   PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
301          REG_INFO(31), REG_INFO(34));
302
303 #undef REG_INFO
304 #undef FPU_REG_INFO
305 }
306
307
308 void MipsDebugger::PrintAllRegsIncludingFPU() {
309 #define FPU_REG_INFO(n) FPURegisters::Name(n), \
310         GetFPURegisterValue(n), \
311         GetFPURegisterValueDouble(n)
312
313   PrintAllRegs();
314
315   PrintF("\n\n");
316   // f0, f1, f2, ... f31.
317   // TODO(plind): consider printing 2 columns for space efficiency.
318   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(0) );
319   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(1) );
320   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(2) );
321   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(3) );
322   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(4) );
323   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(5) );
324   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(6) );
325   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(7) );
326   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(8) );
327   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(9) );
328   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(10));
329   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(11));
330   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(12));
331   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(13));
332   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(14));
333   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(15));
334   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(16));
335   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(17));
336   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(18));
337   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(19));
338   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(20));
339   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(21));
340   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(22));
341   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(23));
342   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(24));
343   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(25));
344   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(26));
345   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(27));
346   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(28));
347   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(29));
348   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(30));
349   PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(31));
350
351 #undef REG_INFO
352 #undef FPU_REG_INFO
353 }
354
355
356 void MipsDebugger::Debug() {
357   intptr_t last_pc = -1;
358   bool done = false;
359
360 #define COMMAND_SIZE 63
361 #define ARG_SIZE 255
362
363 #define STR(a) #a
364 #define XSTR(a) STR(a)
365
366   char cmd[COMMAND_SIZE + 1];
367   char arg1[ARG_SIZE + 1];
368   char arg2[ARG_SIZE + 1];
369   char* argv[3] = { cmd, arg1, arg2 };
370
371   // Make sure to have a proper terminating character if reaching the limit.
372   cmd[COMMAND_SIZE] = 0;
373   arg1[ARG_SIZE] = 0;
374   arg2[ARG_SIZE] = 0;
375
376   // Undo all set breakpoints while running in the debugger shell. This will
377   // make them invisible to all commands.
378   UndoBreakpoints();
379
380   while (!done && (sim_->get_pc() != Simulator::end_sim_pc)) {
381     if (last_pc != sim_->get_pc()) {
382       disasm::NameConverter converter;
383       disasm::Disassembler dasm(converter);
384       // Use a reasonably large buffer.
385       v8::internal::EmbeddedVector<char, 256> buffer;
386       dasm.InstructionDecode(buffer,
387                              reinterpret_cast<byte*>(sim_->get_pc()));
388       PrintF("  0x%016lx  %s\n", sim_->get_pc(), buffer.start());
389       last_pc = sim_->get_pc();
390     }
391     char* line = ReadLine("sim> ");
392     if (line == NULL) {
393       break;
394     } else {
395       char* last_input = sim_->last_debugger_input();
396       if (strcmp(line, "\n") == 0 && last_input != NULL) {
397         line = last_input;
398       } else {
399         // Ownership is transferred to sim_;
400         sim_->set_last_debugger_input(line);
401       }
402       // Use sscanf to parse the individual parts of the command line. At the
403       // moment no command expects more than two parameters.
404       int argc = SScanF(line,
405                         "%" XSTR(COMMAND_SIZE) "s "
406                         "%" XSTR(ARG_SIZE) "s "
407                         "%" XSTR(ARG_SIZE) "s",
408                         cmd, arg1, arg2);
409       if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) {
410         Instruction* instr = reinterpret_cast<Instruction*>(sim_->get_pc());
411         if (!(instr->IsTrap()) ||
412             instr->InstructionBits() == rtCallRedirInstr) {
413           sim_->InstructionDecode(
414               reinterpret_cast<Instruction*>(sim_->get_pc()));
415         } else {
416           // Allow si to jump over generated breakpoints.
417           PrintF("/!\\ Jumping over generated breakpoint.\n");
418           sim_->set_pc(sim_->get_pc() + Instruction::kInstrSize);
419         }
420       } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) {
421         // Execute the one instruction we broke at with breakpoints disabled.
422         sim_->InstructionDecode(reinterpret_cast<Instruction*>(sim_->get_pc()));
423         // Leave the debugger shell.
424         done = true;
425       } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) {
426         if (argc == 2) {
427           int64_t value;
428           double dvalue;
429           if (strcmp(arg1, "all") == 0) {
430             PrintAllRegs();
431           } else if (strcmp(arg1, "allf") == 0) {
432             PrintAllRegsIncludingFPU();
433           } else {
434             int regnum = Registers::Number(arg1);
435             int fpuregnum = FPURegisters::Number(arg1);
436
437             if (regnum != kInvalidRegister) {
438               value = GetRegisterValue(regnum);
439               PrintF("%s: 0x%08lx %ld \n", arg1, value, value);
440             } else if (fpuregnum != kInvalidFPURegister) {
441               value = GetFPURegisterValue(fpuregnum);
442               dvalue = GetFPURegisterValueDouble(fpuregnum);
443               PrintF("%3s: 0x%016lx %16.4e\n",
444                      FPURegisters::Name(fpuregnum), value, dvalue);
445             } else {
446               PrintF("%s unrecognized\n", arg1);
447             }
448           }
449         } else {
450           if (argc == 3) {
451             if (strcmp(arg2, "single") == 0) {
452               int64_t value;
453               float fvalue;
454               int fpuregnum = FPURegisters::Number(arg1);
455
456               if (fpuregnum != kInvalidFPURegister) {
457                 value = GetFPURegisterValue(fpuregnum);
458                 value &= 0xffffffffUL;
459                 fvalue = GetFPURegisterValueFloat(fpuregnum);
460                 PrintF("%s: 0x%08lx %11.4e\n", arg1, value, fvalue);
461               } else {
462                 PrintF("%s unrecognized\n", arg1);
463               }
464             } else {
465               PrintF("print <fpu register> single\n");
466             }
467           } else {
468             PrintF("print <register> or print <fpu register> single\n");
469           }
470         }
471       } else if ((strcmp(cmd, "po") == 0)
472                  || (strcmp(cmd, "printobject") == 0)) {
473         if (argc == 2) {
474           int64_t value;
475           OFStream os(stdout);
476           if (GetValue(arg1, &value)) {
477             Object* obj = reinterpret_cast<Object*>(value);
478             os << arg1 << ": \n";
479 #ifdef DEBUG
480             obj->Print(os);
481             os << "\n";
482 #else
483             os << Brief(obj) << "\n";
484 #endif
485           } else {
486             os << arg1 << " unrecognized\n";
487           }
488         } else {
489           PrintF("printobject <value>\n");
490         }
491       } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) {
492         int64_t* cur = NULL;
493         int64_t* end = NULL;
494         int next_arg = 1;
495
496         if (strcmp(cmd, "stack") == 0) {
497           cur = reinterpret_cast<int64_t*>(sim_->get_register(Simulator::sp));
498         } else {  // Command "mem".
499           int64_t value;
500           if (!GetValue(arg1, &value)) {
501             PrintF("%s unrecognized\n", arg1);
502             continue;
503           }
504           cur = reinterpret_cast<int64_t*>(value);
505           next_arg++;
506         }
507
508         int64_t words;
509         if (argc == next_arg) {
510           words = 10;
511         } else {
512           if (!GetValue(argv[next_arg], &words)) {
513             words = 10;
514           }
515         }
516         end = cur + words;
517
518         while (cur < end) {
519           PrintF("  0x%012lx:  0x%016lx %14ld",
520                  reinterpret_cast<intptr_t>(cur), *cur, *cur);
521           HeapObject* obj = reinterpret_cast<HeapObject*>(*cur);
522           int64_t value = *cur;
523           Heap* current_heap = v8::internal::Isolate::Current()->heap();
524           if (((value & 1) == 0) || current_heap->Contains(obj)) {
525             PrintF(" (");
526             if ((value & 1) == 0) {
527               PrintF("smi %d", static_cast<int>(value >> 32));
528             } else {
529               obj->ShortPrint();
530             }
531             PrintF(")");
532           }
533           PrintF("\n");
534           cur++;
535         }
536
537       } else if ((strcmp(cmd, "disasm") == 0) ||
538                  (strcmp(cmd, "dpc") == 0) ||
539                  (strcmp(cmd, "di") == 0)) {
540         disasm::NameConverter converter;
541         disasm::Disassembler dasm(converter);
542         // Use a reasonably large buffer.
543         v8::internal::EmbeddedVector<char, 256> buffer;
544
545         byte* cur = NULL;
546         byte* end = NULL;
547
548         if (argc == 1) {
549           cur = reinterpret_cast<byte*>(sim_->get_pc());
550           end = cur + (10 * Instruction::kInstrSize);
551         } else if (argc == 2) {
552           int regnum = Registers::Number(arg1);
553           if (regnum != kInvalidRegister || strncmp(arg1, "0x", 2) == 0) {
554             // The argument is an address or a register name.
555             int64_t value;
556             if (GetValue(arg1, &value)) {
557               cur = reinterpret_cast<byte*>(value);
558               // Disassemble 10 instructions at <arg1>.
559               end = cur + (10 * Instruction::kInstrSize);
560             }
561           } else {
562             // The argument is the number of instructions.
563             int64_t value;
564             if (GetValue(arg1, &value)) {
565               cur = reinterpret_cast<byte*>(sim_->get_pc());
566               // Disassemble <arg1> instructions.
567               end = cur + (value * Instruction::kInstrSize);
568             }
569           }
570         } else {
571           int64_t value1;
572           int64_t value2;
573           if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
574             cur = reinterpret_cast<byte*>(value1);
575             end = cur + (value2 * Instruction::kInstrSize);
576           }
577         }
578
579         while (cur < end) {
580           dasm.InstructionDecode(buffer, cur);
581           PrintF("  0x%08lx  %s\n",
582               reinterpret_cast<intptr_t>(cur), buffer.start());
583           cur += Instruction::kInstrSize;
584         }
585       } else if (strcmp(cmd, "gdb") == 0) {
586         PrintF("relinquishing control to gdb\n");
587         v8::base::OS::DebugBreak();
588         PrintF("regaining control from gdb\n");
589       } else if (strcmp(cmd, "break") == 0) {
590         if (argc == 2) {
591           int64_t value;
592           if (GetValue(arg1, &value)) {
593             if (!SetBreakpoint(reinterpret_cast<Instruction*>(value))) {
594               PrintF("setting breakpoint failed\n");
595             }
596           } else {
597             PrintF("%s unrecognized\n", arg1);
598           }
599         } else {
600           PrintF("break <address>\n");
601         }
602       } else if (strcmp(cmd, "del") == 0) {
603         if (!DeleteBreakpoint(NULL)) {
604           PrintF("deleting breakpoint failed\n");
605         }
606       } else if (strcmp(cmd, "flags") == 0) {
607         PrintF("No flags on MIPS !\n");
608       } else if (strcmp(cmd, "stop") == 0) {
609         int64_t value;
610         intptr_t stop_pc = sim_->get_pc() -
611             2 * Instruction::kInstrSize;
612         Instruction* stop_instr = reinterpret_cast<Instruction*>(stop_pc);
613         Instruction* msg_address =
614           reinterpret_cast<Instruction*>(stop_pc +
615               Instruction::kInstrSize);
616         if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) {
617           // Remove the current stop.
618           if (sim_->IsStopInstruction(stop_instr)) {
619             stop_instr->SetInstructionBits(kNopInstr);
620             msg_address->SetInstructionBits(kNopInstr);
621           } else {
622             PrintF("Not at debugger stop.\n");
623           }
624         } else if (argc == 3) {
625           // Print information about all/the specified breakpoint(s).
626           if (strcmp(arg1, "info") == 0) {
627             if (strcmp(arg2, "all") == 0) {
628               PrintF("Stop information:\n");
629               for (uint32_t i = kMaxWatchpointCode + 1;
630                    i <= kMaxStopCode;
631                    i++) {
632                 sim_->PrintStopInfo(i);
633               }
634             } else if (GetValue(arg2, &value)) {
635               sim_->PrintStopInfo(value);
636             } else {
637               PrintF("Unrecognized argument.\n");
638             }
639           } else if (strcmp(arg1, "enable") == 0) {
640             // Enable all/the specified breakpoint(s).
641             if (strcmp(arg2, "all") == 0) {
642               for (uint32_t i = kMaxWatchpointCode + 1;
643                    i <= kMaxStopCode;
644                    i++) {
645                 sim_->EnableStop(i);
646               }
647             } else if (GetValue(arg2, &value)) {
648               sim_->EnableStop(value);
649             } else {
650               PrintF("Unrecognized argument.\n");
651             }
652           } else if (strcmp(arg1, "disable") == 0) {
653             // Disable all/the specified breakpoint(s).
654             if (strcmp(arg2, "all") == 0) {
655               for (uint32_t i = kMaxWatchpointCode + 1;
656                    i <= kMaxStopCode;
657                    i++) {
658                 sim_->DisableStop(i);
659               }
660             } else if (GetValue(arg2, &value)) {
661               sim_->DisableStop(value);
662             } else {
663               PrintF("Unrecognized argument.\n");
664             }
665           }
666         } else {
667           PrintF("Wrong usage. Use help command for more information.\n");
668         }
669       } else if ((strcmp(cmd, "stat") == 0) || (strcmp(cmd, "st") == 0)) {
670         // Print registers and disassemble.
671         PrintAllRegs();
672         PrintF("\n");
673
674         disasm::NameConverter converter;
675         disasm::Disassembler dasm(converter);
676         // Use a reasonably large buffer.
677         v8::internal::EmbeddedVector<char, 256> buffer;
678
679         byte* cur = NULL;
680         byte* end = NULL;
681
682         if (argc == 1) {
683           cur = reinterpret_cast<byte*>(sim_->get_pc());
684           end = cur + (10 * Instruction::kInstrSize);
685         } else if (argc == 2) {
686           int64_t value;
687           if (GetValue(arg1, &value)) {
688             cur = reinterpret_cast<byte*>(value);
689             // no length parameter passed, assume 10 instructions
690             end = cur + (10 * Instruction::kInstrSize);
691           }
692         } else {
693           int64_t value1;
694           int64_t value2;
695           if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
696             cur = reinterpret_cast<byte*>(value1);
697             end = cur + (value2 * Instruction::kInstrSize);
698           }
699         }
700
701         while (cur < end) {
702           dasm.InstructionDecode(buffer, cur);
703           PrintF("  0x%08lx  %s\n",
704                  reinterpret_cast<intptr_t>(cur), buffer.start());
705           cur += Instruction::kInstrSize;
706         }
707       } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) {
708         PrintF("cont\n");
709         PrintF("  continue execution (alias 'c')\n");
710         PrintF("stepi\n");
711         PrintF("  step one instruction (alias 'si')\n");
712         PrintF("print <register>\n");
713         PrintF("  print register content (alias 'p')\n");
714         PrintF("  use register name 'all' to print all registers\n");
715         PrintF("printobject <register>\n");
716         PrintF("  print an object from a register (alias 'po')\n");
717         PrintF("stack [<words>]\n");
718         PrintF("  dump stack content, default dump 10 words)\n");
719         PrintF("mem <address> [<words>]\n");
720         PrintF("  dump memory content, default dump 10 words)\n");
721         PrintF("flags\n");
722         PrintF("  print flags\n");
723         PrintF("disasm [<instructions>]\n");
724         PrintF("disasm [<address/register>]\n");
725         PrintF("disasm [[<address/register>] <instructions>]\n");
726         PrintF("  disassemble code, default is 10 instructions\n");
727         PrintF("  from pc (alias 'di')\n");
728         PrintF("gdb\n");
729         PrintF("  enter gdb\n");
730         PrintF("break <address>\n");
731         PrintF("  set a break point on the address\n");
732         PrintF("del\n");
733         PrintF("  delete the breakpoint\n");
734         PrintF("stop feature:\n");
735         PrintF("  Description:\n");
736         PrintF("    Stops are debug instructions inserted by\n");
737         PrintF("    the Assembler::stop() function.\n");
738         PrintF("    When hitting a stop, the Simulator will\n");
739         PrintF("    stop and and give control to the Debugger.\n");
740         PrintF("    All stop codes are watched:\n");
741         PrintF("    - They can be enabled / disabled: the Simulator\n");
742         PrintF("       will / won't stop when hitting them.\n");
743         PrintF("    - The Simulator keeps track of how many times they \n");
744         PrintF("      are met. (See the info command.) Going over a\n");
745         PrintF("      disabled stop still increases its counter. \n");
746         PrintF("  Commands:\n");
747         PrintF("    stop info all/<code> : print infos about number <code>\n");
748         PrintF("      or all stop(s).\n");
749         PrintF("    stop enable/disable all/<code> : enables / disables\n");
750         PrintF("      all or number <code> stop(s)\n");
751         PrintF("    stop unstop\n");
752         PrintF("      ignore the stop instruction at the current location\n");
753         PrintF("      from now on\n");
754       } else {
755         PrintF("Unknown command: %s\n", cmd);
756       }
757     }
758   }
759
760   // Add all the breakpoints back to stop execution and enter the debugger
761   // shell when hit.
762   RedoBreakpoints();
763
764 #undef COMMAND_SIZE
765 #undef ARG_SIZE
766
767 #undef STR
768 #undef XSTR
769 }
770
771
772 static bool ICacheMatch(void* one, void* two) {
773   DCHECK((reinterpret_cast<intptr_t>(one) & CachePage::kPageMask) == 0);
774   DCHECK((reinterpret_cast<intptr_t>(two) & CachePage::kPageMask) == 0);
775   return one == two;
776 }
777
778
779 static uint32_t ICacheHash(void* key) {
780   return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(key)) >> 2;
781 }
782
783
784 static bool AllOnOnePage(uintptr_t start, int size) {
785   intptr_t start_page = (start & ~CachePage::kPageMask);
786   intptr_t end_page = ((start + size) & ~CachePage::kPageMask);
787   return start_page == end_page;
788 }
789
790
791 void Simulator::set_last_debugger_input(char* input) {
792   DeleteArray(last_debugger_input_);
793   last_debugger_input_ = input;
794 }
795
796
797 void Simulator::FlushICache(v8::internal::HashMap* i_cache,
798                             void* start_addr,
799                             size_t size) {
800   int64_t start = reinterpret_cast<int64_t>(start_addr);
801   int64_t intra_line = (start & CachePage::kLineMask);
802   start -= intra_line;
803   size += intra_line;
804   size = ((size - 1) | CachePage::kLineMask) + 1;
805   int offset = (start & CachePage::kPageMask);
806   while (!AllOnOnePage(start, size - 1)) {
807     int bytes_to_flush = CachePage::kPageSize - offset;
808     FlushOnePage(i_cache, start, bytes_to_flush);
809     start += bytes_to_flush;
810     size -= bytes_to_flush;
811     DCHECK_EQ((uint64_t)0, start & CachePage::kPageMask);
812     offset = 0;
813   }
814   if (size != 0) {
815     FlushOnePage(i_cache, start, size);
816   }
817 }
818
819
820 CachePage* Simulator::GetCachePage(v8::internal::HashMap* i_cache, void* page) {
821   v8::internal::HashMap::Entry* entry = i_cache->Lookup(page,
822                                                         ICacheHash(page),
823                                                         true);
824   if (entry->value == NULL) {
825     CachePage* new_page = new CachePage();
826     entry->value = new_page;
827   }
828   return reinterpret_cast<CachePage*>(entry->value);
829 }
830
831
832 // Flush from start up to and not including start + size.
833 void Simulator::FlushOnePage(v8::internal::HashMap* i_cache,
834                              intptr_t start,
835                              int size) {
836   DCHECK(size <= CachePage::kPageSize);
837   DCHECK(AllOnOnePage(start, size - 1));
838   DCHECK((start & CachePage::kLineMask) == 0);
839   DCHECK((size & CachePage::kLineMask) == 0);
840   void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask));
841   int offset = (start & CachePage::kPageMask);
842   CachePage* cache_page = GetCachePage(i_cache, page);
843   char* valid_bytemap = cache_page->ValidityByte(offset);
844   memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift);
845 }
846
847
848 void Simulator::CheckICache(v8::internal::HashMap* i_cache,
849                             Instruction* instr) {
850   int64_t address = reinterpret_cast<int64_t>(instr);
851   void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask));
852   void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask));
853   int offset = (address & CachePage::kPageMask);
854   CachePage* cache_page = GetCachePage(i_cache, page);
855   char* cache_valid_byte = cache_page->ValidityByte(offset);
856   bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID);
857   char* cached_line = cache_page->CachedData(offset & ~CachePage::kLineMask);
858   if (cache_hit) {
859     // Check that the data in memory matches the contents of the I-cache.
860     CHECK_EQ(0, memcmp(reinterpret_cast<void*>(instr),
861                        cache_page->CachedData(offset),
862                        Instruction::kInstrSize));
863   } else {
864     // Cache miss.  Load memory into the cache.
865     memcpy(cached_line, line, CachePage::kLineLength);
866     *cache_valid_byte = CachePage::LINE_VALID;
867   }
868 }
869
870
871 void Simulator::Initialize(Isolate* isolate) {
872   if (isolate->simulator_initialized()) return;
873   isolate->set_simulator_initialized(true);
874   ::v8::internal::ExternalReference::set_redirector(isolate,
875                                                     &RedirectExternalReference);
876 }
877
878
879 Simulator::Simulator(Isolate* isolate) : isolate_(isolate) {
880   i_cache_ = isolate_->simulator_i_cache();
881   if (i_cache_ == NULL) {
882     i_cache_ = new v8::internal::HashMap(&ICacheMatch);
883     isolate_->set_simulator_i_cache(i_cache_);
884   }
885   Initialize(isolate);
886   // Set up simulator support first. Some of this information is needed to
887   // setup the architecture state.
888   stack_size_ = FLAG_sim_stack_size * KB;
889   stack_ = reinterpret_cast<char*>(malloc(stack_size_));
890   pc_modified_ = false;
891   icount_ = 0;
892   break_count_ = 0;
893   break_pc_ = NULL;
894   break_instr_ = 0;
895
896   // Set up architecture state.
897   // All registers are initialized to zero to start with.
898   for (int i = 0; i < kNumSimuRegisters; i++) {
899     registers_[i] = 0;
900   }
901   for (int i = 0; i < kNumFPURegisters; i++) {
902     FPUregisters_[i] = 0;
903   }
904   FCSR_ = 0;
905
906   // The sp is initialized to point to the bottom (high address) of the
907   // allocated stack area. To be safe in potential stack underflows we leave
908   // some buffer below.
909   registers_[sp] = reinterpret_cast<int64_t>(stack_) + stack_size_ - 64;
910   // The ra and pc are initialized to a known bad value that will cause an
911   // access violation if the simulator ever tries to execute it.
912   registers_[pc] = bad_ra;
913   registers_[ra] = bad_ra;
914   InitializeCoverage();
915   for (int i = 0; i < kNumExceptions; i++) {
916     exceptions[i] = 0;
917   }
918
919   last_debugger_input_ = NULL;
920 }
921
922
923 Simulator::~Simulator() {
924 }
925
926
927 // When the generated code calls an external reference we need to catch that in
928 // the simulator.  The external reference will be a function compiled for the
929 // host architecture.  We need to call that function instead of trying to
930 // execute it with the simulator.  We do that by redirecting the external
931 // reference to a swi (software-interrupt) instruction that is handled by
932 // the simulator.  We write the original destination of the jump just at a known
933 // offset from the swi instruction so the simulator knows what to call.
934 class Redirection {
935  public:
936   Redirection(void* external_function, ExternalReference::Type type)
937       : external_function_(external_function),
938         swi_instruction_(rtCallRedirInstr),
939         type_(type),
940         next_(NULL) {
941     Isolate* isolate = Isolate::Current();
942     next_ = isolate->simulator_redirection();
943     Simulator::current(isolate)->
944         FlushICache(isolate->simulator_i_cache(),
945                     reinterpret_cast<void*>(&swi_instruction_),
946                     Instruction::kInstrSize);
947     isolate->set_simulator_redirection(this);
948   }
949
950   void* address_of_swi_instruction() {
951     return reinterpret_cast<void*>(&swi_instruction_);
952   }
953
954   void* external_function() { return external_function_; }
955   ExternalReference::Type type() { return type_; }
956
957   static Redirection* Get(void* external_function,
958                           ExternalReference::Type type) {
959     Isolate* isolate = Isolate::Current();
960     Redirection* current = isolate->simulator_redirection();
961     for (; current != NULL; current = current->next_) {
962       if (current->external_function_ == external_function) return current;
963     }
964     return new Redirection(external_function, type);
965   }
966
967   static Redirection* FromSwiInstruction(Instruction* swi_instruction) {
968     char* addr_of_swi = reinterpret_cast<char*>(swi_instruction);
969     char* addr_of_redirection =
970         addr_of_swi - OFFSET_OF(Redirection, swi_instruction_);
971     return reinterpret_cast<Redirection*>(addr_of_redirection);
972   }
973
974   static void* ReverseRedirection(int64_t reg) {
975     Redirection* redirection = FromSwiInstruction(
976         reinterpret_cast<Instruction*>(reinterpret_cast<void*>(reg)));
977     return redirection->external_function();
978   }
979
980  private:
981   void* external_function_;
982   uint32_t swi_instruction_;
983   ExternalReference::Type type_;
984   Redirection* next_;
985 };
986
987
988 void* Simulator::RedirectExternalReference(void* external_function,
989                                            ExternalReference::Type type) {
990   Redirection* redirection = Redirection::Get(external_function, type);
991   return redirection->address_of_swi_instruction();
992 }
993
994
995 // Get the active Simulator for the current thread.
996 Simulator* Simulator::current(Isolate* isolate) {
997   v8::internal::Isolate::PerIsolateThreadData* isolate_data =
998        isolate->FindOrAllocatePerThreadDataForThisThread();
999   DCHECK(isolate_data != NULL);
1000   DCHECK(isolate_data != NULL);
1001
1002   Simulator* sim = isolate_data->simulator();
1003   if (sim == NULL) {
1004     // TODO(146): delete the simulator object when a thread/isolate goes away.
1005     sim = new Simulator(isolate);
1006     isolate_data->set_simulator(sim);
1007   }
1008   return sim;
1009 }
1010
1011
1012 // Sets the register in the architecture state. It will also deal with updating
1013 // Simulator internal state for special registers such as PC.
1014 void Simulator::set_register(int reg, int64_t value) {
1015   DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1016   if (reg == pc) {
1017     pc_modified_ = true;
1018   }
1019
1020   // Zero register always holds 0.
1021   registers_[reg] = (reg == 0) ? 0 : value;
1022 }
1023
1024
1025 void Simulator::set_dw_register(int reg, const int* dbl) {
1026   DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1027   registers_[reg] = dbl[1];
1028   registers_[reg] = registers_[reg] << 32;
1029   registers_[reg] += dbl[0];
1030 }
1031
1032
1033 void Simulator::set_fpu_register(int fpureg, int64_t value) {
1034   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1035   FPUregisters_[fpureg] = value;
1036 }
1037
1038
1039 void Simulator::set_fpu_register_word(int fpureg, int32_t value) {
1040   // Set ONLY lower 32-bits, leaving upper bits untouched.
1041   // TODO(plind): big endian issue.
1042   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1043   int32_t *pword = reinterpret_cast<int32_t*>(&FPUregisters_[fpureg]);
1044   *pword = value;
1045 }
1046
1047
1048 void Simulator::set_fpu_register_hi_word(int fpureg, int32_t value) {
1049   // Set ONLY upper 32-bits, leaving lower bits untouched.
1050   // TODO(plind): big endian issue.
1051   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1052   int32_t *phiword = (reinterpret_cast<int32_t*>(&FPUregisters_[fpureg])) + 1;
1053   *phiword = value;
1054 }
1055
1056
1057 void Simulator::set_fpu_register_float(int fpureg, float value) {
1058   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1059   *bit_cast<float*>(&FPUregisters_[fpureg]) = value;
1060 }
1061
1062
1063 void Simulator::set_fpu_register_double(int fpureg, double value) {
1064   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1065   *bit_cast<double*>(&FPUregisters_[fpureg]) = value;
1066 }
1067
1068
1069 // Get the register from the architecture state. This function does handle
1070 // the special case of accessing the PC register.
1071 int64_t Simulator::get_register(int reg) const {
1072   DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1073   if (reg == 0)
1074     return 0;
1075   else
1076     return registers_[reg] + ((reg == pc) ? Instruction::kPCReadOffset : 0);
1077 }
1078
1079
1080 double Simulator::get_double_from_register_pair(int reg) {
1081   // TODO(plind): bad ABI stuff, refactor or remove.
1082   DCHECK((reg >= 0) && (reg < kNumSimuRegisters) && ((reg % 2) == 0));
1083
1084   double dm_val = 0.0;
1085   // Read the bits from the unsigned integer register_[] array
1086   // into the double precision floating point value and return it.
1087   char buffer[sizeof(registers_[0])];
1088   memcpy(buffer, &registers_[reg], sizeof(registers_[0]));
1089   memcpy(&dm_val, buffer, sizeof(registers_[0]));
1090   return(dm_val);
1091 }
1092
1093
1094 int64_t Simulator::get_fpu_register(int fpureg) const {
1095   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1096   return FPUregisters_[fpureg];
1097 }
1098
1099
1100 int32_t Simulator::get_fpu_register_word(int fpureg) const {
1101   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1102   return static_cast<int32_t>(FPUregisters_[fpureg] & 0xffffffff);
1103 }
1104
1105
1106 int32_t Simulator::get_fpu_register_signed_word(int fpureg) const {
1107   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1108   return static_cast<int32_t>(FPUregisters_[fpureg] & 0xffffffff);
1109 }
1110
1111
1112 int32_t Simulator::get_fpu_register_hi_word(int fpureg) const {
1113   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1114   return static_cast<int32_t>((FPUregisters_[fpureg] >> 32) & 0xffffffff);
1115 }
1116
1117
1118 float Simulator::get_fpu_register_float(int fpureg) const {
1119   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1120   return *bit_cast<float*>(const_cast<int64_t*>(&FPUregisters_[fpureg]));
1121 }
1122
1123
1124 double Simulator::get_fpu_register_double(int fpureg) const {
1125   DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1126   return *bit_cast<double*>(&FPUregisters_[fpureg]);
1127 }
1128
1129
1130 // Runtime FP routines take up to two double arguments and zero
1131 // or one integer arguments. All are constructed here,
1132 // from a0-a3 or f12 and f13 (n64), or f14 (O32).
1133 void Simulator::GetFpArgs(double* x, double* y, int32_t* z) {
1134   if (!IsMipsSoftFloatABI) {
1135     const int fparg2 = (kMipsAbi == kN64) ? 13 : 14;
1136     *x = get_fpu_register_double(12);
1137     *y = get_fpu_register_double(fparg2);
1138     *z = get_register(a2);
1139   } else {
1140   // TODO(plind): bad ABI stuff, refactor or remove.
1141     // We use a char buffer to get around the strict-aliasing rules which
1142     // otherwise allow the compiler to optimize away the copy.
1143     char buffer[sizeof(*x)];
1144     int32_t* reg_buffer = reinterpret_cast<int32_t*>(buffer);
1145
1146     // Registers a0 and a1 -> x.
1147     reg_buffer[0] = get_register(a0);
1148     reg_buffer[1] = get_register(a1);
1149     memcpy(x, buffer, sizeof(buffer));
1150     // Registers a2 and a3 -> y.
1151     reg_buffer[0] = get_register(a2);
1152     reg_buffer[1] = get_register(a3);
1153     memcpy(y, buffer, sizeof(buffer));
1154     // Register 2 -> z.
1155     reg_buffer[0] = get_register(a2);
1156     memcpy(z, buffer, sizeof(*z));
1157   }
1158 }
1159
1160
1161 // The return value is either in v0/v1 or f0.
1162 void Simulator::SetFpResult(const double& result) {
1163   if (!IsMipsSoftFloatABI) {
1164     set_fpu_register_double(0, result);
1165   } else {
1166     char buffer[2 * sizeof(registers_[0])];
1167     int64_t* reg_buffer = reinterpret_cast<int64_t*>(buffer);
1168     memcpy(buffer, &result, sizeof(buffer));
1169     // Copy result to v0 and v1.
1170     set_register(v0, reg_buffer[0]);
1171     set_register(v1, reg_buffer[1]);
1172   }
1173 }
1174
1175
1176 // Helper functions for setting and testing the FCSR register's bits.
1177 void Simulator::set_fcsr_bit(uint32_t cc, bool value) {
1178   if (value) {
1179     FCSR_ |= (1 << cc);
1180   } else {
1181     FCSR_ &= ~(1 << cc);
1182   }
1183 }
1184
1185
1186 bool Simulator::test_fcsr_bit(uint32_t cc) {
1187   return FCSR_ & (1 << cc);
1188 }
1189
1190
1191 // Sets the rounding error codes in FCSR based on the result of the rounding.
1192 // Returns true if the operation was invalid.
1193 bool Simulator::set_fcsr_round_error(double original, double rounded) {
1194   bool ret = false;
1195   double max_int32 = std::numeric_limits<int32_t>::max();
1196   double min_int32 = std::numeric_limits<int32_t>::min();
1197
1198   if (!std::isfinite(original) || !std::isfinite(rounded)) {
1199     set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1200     ret = true;
1201   }
1202
1203   if (original != rounded) {
1204     set_fcsr_bit(kFCSRInexactFlagBit, true);
1205   }
1206
1207   if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1208     set_fcsr_bit(kFCSRUnderflowFlagBit, true);
1209     ret = true;
1210   }
1211
1212   if (rounded > max_int32 || rounded < min_int32) {
1213     set_fcsr_bit(kFCSROverflowFlagBit, true);
1214     // The reference is not really clear but it seems this is required:
1215     set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1216     ret = true;
1217   }
1218
1219   return ret;
1220 }
1221
1222
1223 // Sets the rounding error codes in FCSR based on the result of the rounding.
1224 // Returns true if the operation was invalid.
1225 bool Simulator::set_fcsr_round64_error(double original, double rounded) {
1226   bool ret = false;
1227   double max_int64 = std::numeric_limits<int64_t>::max();
1228   double min_int64 = std::numeric_limits<int64_t>::min();
1229
1230   if (!std::isfinite(original) || !std::isfinite(rounded)) {
1231     set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1232     ret = true;
1233   }
1234
1235   if (original != rounded) {
1236     set_fcsr_bit(kFCSRInexactFlagBit, true);
1237   }
1238
1239   if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1240     set_fcsr_bit(kFCSRUnderflowFlagBit, true);
1241     ret = true;
1242   }
1243
1244   if (rounded > max_int64 || rounded < min_int64) {
1245     set_fcsr_bit(kFCSROverflowFlagBit, true);
1246     // The reference is not really clear but it seems this is required:
1247     set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1248     ret = true;
1249   }
1250
1251   return ret;
1252 }
1253
1254
1255 // Raw access to the PC register.
1256 void Simulator::set_pc(int64_t value) {
1257   pc_modified_ = true;
1258   registers_[pc] = value;
1259 }
1260
1261
1262 bool Simulator::has_bad_pc() const {
1263   return ((registers_[pc] == bad_ra) || (registers_[pc] == end_sim_pc));
1264 }
1265
1266
1267 // Raw access to the PC register without the special adjustment when reading.
1268 int64_t Simulator::get_pc() const {
1269   return registers_[pc];
1270 }
1271
1272
1273 // The MIPS cannot do unaligned reads and writes.  On some MIPS platforms an
1274 // interrupt is caused.  On others it does a funky rotation thing.  For now we
1275 // simply disallow unaligned reads, but at some point we may want to move to
1276 // emulating the rotate behaviour.  Note that simulator runs have the runtime
1277 // system running directly on the host system and only generated code is
1278 // executed in the simulator.  Since the host is typically IA32 we will not
1279 // get the correct MIPS-like behaviour on unaligned accesses.
1280
1281 // TODO(plind): refactor this messy debug code when we do unaligned access.
1282 void Simulator::DieOrDebug() {
1283   if (1) {  // Flag for this was removed.
1284     MipsDebugger dbg(this);
1285     dbg.Debug();
1286   } else {
1287     base::OS::Abort();
1288   }
1289 }
1290
1291
1292 void Simulator::TraceRegWr(int64_t value) {
1293   if (::v8::internal::FLAG_trace_sim) {
1294     SNPrintF(trace_buf_, "%016lx", value);
1295   }
1296 }
1297
1298
1299 // TODO(plind): consider making icount_ printing a flag option.
1300 void Simulator::TraceMemRd(int64_t addr, int64_t value) {
1301   if (::v8::internal::FLAG_trace_sim) {
1302     SNPrintF(trace_buf_, "%016lx <-- [%016lx]    (%ld)",
1303              value, addr, icount_);
1304   }
1305 }
1306
1307
1308 void Simulator::TraceMemWr(int64_t addr, int64_t value, TraceType t) {
1309   if (::v8::internal::FLAG_trace_sim) {
1310     switch (t) {
1311       case BYTE:
1312         SNPrintF(trace_buf_, "               %02x --> [%016lx]",
1313                  static_cast<int8_t>(value), addr);
1314         break;
1315       case HALF:
1316         SNPrintF(trace_buf_, "            %04x --> [%016lx]",
1317                  static_cast<int16_t>(value), addr);
1318         break;
1319       case WORD:
1320         SNPrintF(trace_buf_, "        %08x --> [%016lx]",
1321                  static_cast<int32_t>(value), addr);
1322         break;
1323       case DWORD:
1324         SNPrintF(trace_buf_, "%016lx --> [%016lx]    (%ld)",
1325                  value, addr, icount_);
1326         break;
1327     }
1328   }
1329 }
1330
1331
1332 // TODO(plind): sign-extend and zero-extend not implmented properly
1333 // on all the ReadXX functions, I don't think re-interpret cast does it.
1334 int32_t Simulator::ReadW(int64_t addr, Instruction* instr) {
1335   if (addr >=0 && addr < 0x400) {
1336     // This has to be a NULL-dereference, drop into debugger.
1337     PrintF("Memory read from bad address: 0x%08lx, pc=0x%08lx\n",
1338            addr, reinterpret_cast<intptr_t>(instr));
1339     DieOrDebug();
1340   }
1341   if ((addr & 0x3) == 0) {
1342     int32_t* ptr = reinterpret_cast<int32_t*>(addr);
1343     TraceMemRd(addr, static_cast<int64_t>(*ptr));
1344     return *ptr;
1345   }
1346   PrintF("Unaligned read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1347          addr,
1348          reinterpret_cast<intptr_t>(instr));
1349   DieOrDebug();
1350   return 0;
1351 }
1352
1353
1354 uint32_t Simulator::ReadWU(int64_t addr, Instruction* instr) {
1355   if (addr >=0 && addr < 0x400) {
1356     // This has to be a NULL-dereference, drop into debugger.
1357     PrintF("Memory read from bad address: 0x%08lx, pc=0x%08lx\n",
1358            addr, reinterpret_cast<intptr_t>(instr));
1359     DieOrDebug();
1360   }
1361   if ((addr & 0x3) == 0) {
1362     uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
1363     TraceMemRd(addr, static_cast<int64_t>(*ptr));
1364     return *ptr;
1365   }
1366   PrintF("Unaligned read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1367          addr,
1368          reinterpret_cast<intptr_t>(instr));
1369   DieOrDebug();
1370   return 0;
1371 }
1372
1373
1374 void Simulator::WriteW(int64_t addr, int value, Instruction* instr) {
1375   if (addr >= 0 && addr < 0x400) {
1376     // This has to be a NULL-dereference, drop into debugger.
1377     PrintF("Memory write to bad address: 0x%08lx, pc=0x%08lx\n",
1378            addr, reinterpret_cast<intptr_t>(instr));
1379     DieOrDebug();
1380   }
1381   if ((addr & 0x3) == 0) {
1382     TraceMemWr(addr, value, WORD);
1383     int* ptr = reinterpret_cast<int*>(addr);
1384     *ptr = value;
1385     return;
1386   }
1387   PrintF("Unaligned write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1388          addr,
1389          reinterpret_cast<intptr_t>(instr));
1390   DieOrDebug();
1391 }
1392
1393
1394 int64_t Simulator::Read2W(int64_t addr, Instruction* instr) {
1395   if (addr >=0 && addr < 0x400) {
1396     // This has to be a NULL-dereference, drop into debugger.
1397     PrintF("Memory read from bad address: 0x%08lx, pc=0x%08lx\n",
1398            addr, reinterpret_cast<intptr_t>(instr));
1399     DieOrDebug();
1400   }
1401   if ((addr & kPointerAlignmentMask) == 0) {
1402     int64_t* ptr = reinterpret_cast<int64_t*>(addr);
1403     TraceMemRd(addr, *ptr);
1404     return *ptr;
1405   }
1406   PrintF("Unaligned read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1407          addr,
1408          reinterpret_cast<intptr_t>(instr));
1409   DieOrDebug();
1410   return 0;
1411 }
1412
1413
1414 void Simulator::Write2W(int64_t addr, int64_t value, Instruction* instr) {
1415   if (addr >= 0 && addr < 0x400) {
1416     // This has to be a NULL-dereference, drop into debugger.
1417     PrintF("Memory write to bad address: 0x%08lx, pc=0x%08lx\n",
1418            addr, reinterpret_cast<intptr_t>(instr));
1419     DieOrDebug();
1420   }
1421   if ((addr & kPointerAlignmentMask) == 0) {
1422     TraceMemWr(addr, value, DWORD);
1423     int64_t* ptr = reinterpret_cast<int64_t*>(addr);
1424     *ptr = value;
1425     return;
1426   }
1427   PrintF("Unaligned write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1428          addr,
1429          reinterpret_cast<intptr_t>(instr));
1430   DieOrDebug();
1431 }
1432
1433
1434 double Simulator::ReadD(int64_t addr, Instruction* instr) {
1435   if ((addr & kDoubleAlignmentMask) == 0) {
1436     double* ptr = reinterpret_cast<double*>(addr);
1437     return *ptr;
1438   }
1439   PrintF("Unaligned (double) read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1440          addr,
1441          reinterpret_cast<intptr_t>(instr));
1442   base::OS::Abort();
1443   return 0;
1444 }
1445
1446
1447 void Simulator::WriteD(int64_t addr, double value, Instruction* instr) {
1448   if ((addr & kDoubleAlignmentMask) == 0) {
1449     double* ptr = reinterpret_cast<double*>(addr);
1450     *ptr = value;
1451     return;
1452   }
1453   PrintF("Unaligned (double) write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1454          addr,
1455          reinterpret_cast<intptr_t>(instr));
1456   DieOrDebug();
1457 }
1458
1459
1460 uint16_t Simulator::ReadHU(int64_t addr, Instruction* instr) {
1461   if ((addr & 1) == 0) {
1462     uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
1463     TraceMemRd(addr, static_cast<int64_t>(*ptr));
1464     return *ptr;
1465   }
1466   PrintF("Unaligned unsigned halfword read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1467          addr,
1468          reinterpret_cast<intptr_t>(instr));
1469   DieOrDebug();
1470   return 0;
1471 }
1472
1473
1474 int16_t Simulator::ReadH(int64_t addr, Instruction* instr) {
1475   if ((addr & 1) == 0) {
1476     int16_t* ptr = reinterpret_cast<int16_t*>(addr);
1477     TraceMemRd(addr, static_cast<int64_t>(*ptr));
1478     return *ptr;
1479   }
1480   PrintF("Unaligned signed halfword read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1481          addr,
1482          reinterpret_cast<intptr_t>(instr));
1483   DieOrDebug();
1484   return 0;
1485 }
1486
1487
1488 void Simulator::WriteH(int64_t addr, uint16_t value, Instruction* instr) {
1489   if ((addr & 1) == 0) {
1490     TraceMemWr(addr, value, HALF);
1491     uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
1492     *ptr = value;
1493     return;
1494   }
1495   PrintF(
1496       "Unaligned unsigned halfword write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1497       addr,
1498       reinterpret_cast<intptr_t>(instr));
1499   DieOrDebug();
1500 }
1501
1502
1503 void Simulator::WriteH(int64_t addr, int16_t value, Instruction* instr) {
1504   if ((addr & 1) == 0) {
1505     TraceMemWr(addr, value, HALF);
1506     int16_t* ptr = reinterpret_cast<int16_t*>(addr);
1507     *ptr = value;
1508     return;
1509   }
1510   PrintF("Unaligned halfword write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1511          addr,
1512          reinterpret_cast<intptr_t>(instr));
1513   DieOrDebug();
1514 }
1515
1516
1517 uint32_t Simulator::ReadBU(int64_t addr) {
1518   uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
1519   TraceMemRd(addr, static_cast<int64_t>(*ptr));
1520   return *ptr & 0xff;
1521 }
1522
1523
1524 int32_t Simulator::ReadB(int64_t addr) {
1525   int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1526   TraceMemRd(addr, static_cast<int64_t>(*ptr));
1527   return *ptr;
1528 }
1529
1530
1531 void Simulator::WriteB(int64_t addr, uint8_t value) {
1532   TraceMemWr(addr, value, BYTE);
1533   uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
1534   *ptr = value;
1535 }
1536
1537
1538 void Simulator::WriteB(int64_t addr, int8_t value) {
1539   TraceMemWr(addr, value, BYTE);
1540   int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1541   *ptr = value;
1542 }
1543
1544
1545 // Returns the limit of the stack area to enable checking for stack overflows.
1546 uintptr_t Simulator::StackLimit() const {
1547   // Leave a safety margin of 1024 bytes to prevent overrunning the stack when
1548   // pushing values.
1549   return reinterpret_cast<uintptr_t>(stack_) + 1024;
1550 }
1551
1552
1553 // Unsupported instructions use Format to print an error and stop execution.
1554 void Simulator::Format(Instruction* instr, const char* format) {
1555   PrintF("Simulator found unsupported instruction:\n 0x%08lx: %s\n",
1556          reinterpret_cast<intptr_t>(instr), format);
1557   UNIMPLEMENTED_MIPS();
1558 }
1559
1560
1561 // Calls into the V8 runtime are based on this very simple interface.
1562 // Note: To be able to return two values from some calls the code in runtime.cc
1563 // uses the ObjectPair which is essentially two 32-bit values stuffed into a
1564 // 64-bit value. With the code below we assume that all runtime calls return
1565 // 64 bits of result. If they don't, the v1 result register contains a bogus
1566 // value, which is fine because it is caller-saved.
1567
1568 struct ObjectPair {
1569   Object* x;
1570   Object* y;
1571 };
1572
1573 typedef ObjectPair (*SimulatorRuntimeCall)(int64_t arg0,
1574                                         int64_t arg1,
1575                                         int64_t arg2,
1576                                         int64_t arg3,
1577                                         int64_t arg4,
1578                                         int64_t arg5);
1579
1580
1581 // These prototypes handle the four types of FP calls.
1582 typedef int64_t (*SimulatorRuntimeCompareCall)(double darg0, double darg1);
1583 typedef double (*SimulatorRuntimeFPFPCall)(double darg0, double darg1);
1584 typedef double (*SimulatorRuntimeFPCall)(double darg0);
1585 typedef double (*SimulatorRuntimeFPIntCall)(double darg0, int32_t arg0);
1586
1587 // This signature supports direct call in to API function native callback
1588 // (refer to InvocationCallback in v8.h).
1589 typedef void (*SimulatorRuntimeDirectApiCall)(int64_t arg0);
1590 typedef void (*SimulatorRuntimeProfilingApiCall)(int64_t arg0, void* arg1);
1591
1592 // This signature supports direct call to accessor getter callback.
1593 typedef void (*SimulatorRuntimeDirectGetterCall)(int64_t arg0, int64_t arg1);
1594 typedef void (*SimulatorRuntimeProfilingGetterCall)(
1595     int64_t arg0, int64_t arg1, void* arg2);
1596
1597 // Software interrupt instructions are used by the simulator to call into the
1598 // C-based V8 runtime. They are also used for debugging with simulator.
1599 void Simulator::SoftwareInterrupt(Instruction* instr) {
1600   // There are several instructions that could get us here,
1601   // the break_ instruction, or several variants of traps. All
1602   // Are "SPECIAL" class opcode, and are distinuished by function.
1603   int32_t func = instr->FunctionFieldRaw();
1604   uint32_t code = (func == BREAK) ? instr->Bits(25, 6) : -1;
1605   // We first check if we met a call_rt_redirected.
1606   if (instr->InstructionBits() == rtCallRedirInstr) {
1607     Redirection* redirection = Redirection::FromSwiInstruction(instr);
1608     int64_t arg0 = get_register(a0);
1609     int64_t arg1 = get_register(a1);
1610     int64_t arg2 = get_register(a2);
1611     int64_t arg3 = get_register(a3);
1612     int64_t arg4, arg5;
1613
1614     if (kMipsAbi == kN64) {
1615       arg4 = get_register(a4);  // Abi n64 register a4.
1616       arg5 = get_register(a5);  // Abi n64 register a5.
1617     } else {  // Abi O32.
1618       int64_t* stack_pointer = reinterpret_cast<int64_t*>(get_register(sp));
1619       // Args 4 and 5 are on the stack after the reserved space for args 0..3.
1620       arg4 = stack_pointer[4];
1621       arg5 = stack_pointer[5];
1622     }
1623     bool fp_call =
1624          (redirection->type() == ExternalReference::BUILTIN_FP_FP_CALL) ||
1625          (redirection->type() == ExternalReference::BUILTIN_COMPARE_CALL) ||
1626          (redirection->type() == ExternalReference::BUILTIN_FP_CALL) ||
1627          (redirection->type() == ExternalReference::BUILTIN_FP_INT_CALL);
1628
1629     if (!IsMipsSoftFloatABI) {
1630       // With the hard floating point calling convention, double
1631       // arguments are passed in FPU registers. Fetch the arguments
1632       // from there and call the builtin using soft floating point
1633       // convention.
1634       switch (redirection->type()) {
1635       case ExternalReference::BUILTIN_FP_FP_CALL:
1636       case ExternalReference::BUILTIN_COMPARE_CALL:
1637         arg0 = get_fpu_register(f12);
1638         arg1 = get_fpu_register(f13);
1639         arg2 = get_fpu_register(f14);
1640         arg3 = get_fpu_register(f15);
1641         break;
1642       case ExternalReference::BUILTIN_FP_CALL:
1643         arg0 = get_fpu_register(f12);
1644         arg1 = get_fpu_register(f13);
1645         break;
1646       case ExternalReference::BUILTIN_FP_INT_CALL:
1647         arg0 = get_fpu_register(f12);
1648         arg1 = get_fpu_register(f13);
1649         arg2 = get_register(a2);
1650         break;
1651       default:
1652         break;
1653       }
1654     }
1655
1656     // This is dodgy but it works because the C entry stubs are never moved.
1657     // See comment in codegen-arm.cc and bug 1242173.
1658     int64_t saved_ra = get_register(ra);
1659
1660     intptr_t external =
1661           reinterpret_cast<intptr_t>(redirection->external_function());
1662
1663     // Based on CpuFeatures::IsSupported(FPU), Mips will use either hardware
1664     // FPU, or gcc soft-float routines. Hardware FPU is simulated in this
1665     // simulator. Soft-float has additional abstraction of ExternalReference,
1666     // to support serialization.
1667     if (fp_call) {
1668       double dval0, dval1;  // one or two double parameters
1669       int32_t ival;         // zero or one integer parameters
1670       int64_t iresult = 0;  // integer return value
1671       double dresult = 0;   // double return value
1672       GetFpArgs(&dval0, &dval1, &ival);
1673       SimulatorRuntimeCall generic_target =
1674           reinterpret_cast<SimulatorRuntimeCall>(external);
1675       if (::v8::internal::FLAG_trace_sim) {
1676         switch (redirection->type()) {
1677           case ExternalReference::BUILTIN_FP_FP_CALL:
1678           case ExternalReference::BUILTIN_COMPARE_CALL:
1679             PrintF("Call to host function at %p with args %f, %f",
1680                    FUNCTION_ADDR(generic_target), dval0, dval1);
1681             break;
1682           case ExternalReference::BUILTIN_FP_CALL:
1683             PrintF("Call to host function at %p with arg %f",
1684                 FUNCTION_ADDR(generic_target), dval0);
1685             break;
1686           case ExternalReference::BUILTIN_FP_INT_CALL:
1687             PrintF("Call to host function at %p with args %f, %d",
1688                    FUNCTION_ADDR(generic_target), dval0, ival);
1689             break;
1690           default:
1691             UNREACHABLE();
1692             break;
1693         }
1694       }
1695       switch (redirection->type()) {
1696       case ExternalReference::BUILTIN_COMPARE_CALL: {
1697         SimulatorRuntimeCompareCall target =
1698           reinterpret_cast<SimulatorRuntimeCompareCall>(external);
1699         iresult = target(dval0, dval1);
1700         set_register(v0, static_cast<int64_t>(iresult));
1701       //  set_register(v1, static_cast<int64_t>(iresult >> 32));
1702         break;
1703       }
1704       case ExternalReference::BUILTIN_FP_FP_CALL: {
1705         SimulatorRuntimeFPFPCall target =
1706           reinterpret_cast<SimulatorRuntimeFPFPCall>(external);
1707         dresult = target(dval0, dval1);
1708         SetFpResult(dresult);
1709         break;
1710       }
1711       case ExternalReference::BUILTIN_FP_CALL: {
1712         SimulatorRuntimeFPCall target =
1713           reinterpret_cast<SimulatorRuntimeFPCall>(external);
1714         dresult = target(dval0);
1715         SetFpResult(dresult);
1716         break;
1717       }
1718       case ExternalReference::BUILTIN_FP_INT_CALL: {
1719         SimulatorRuntimeFPIntCall target =
1720           reinterpret_cast<SimulatorRuntimeFPIntCall>(external);
1721         dresult = target(dval0, ival);
1722         SetFpResult(dresult);
1723         break;
1724       }
1725       default:
1726         UNREACHABLE();
1727         break;
1728       }
1729       if (::v8::internal::FLAG_trace_sim) {
1730         switch (redirection->type()) {
1731         case ExternalReference::BUILTIN_COMPARE_CALL:
1732           PrintF("Returned %08x\n", static_cast<int32_t>(iresult));
1733           break;
1734         case ExternalReference::BUILTIN_FP_FP_CALL:
1735         case ExternalReference::BUILTIN_FP_CALL:
1736         case ExternalReference::BUILTIN_FP_INT_CALL:
1737           PrintF("Returned %f\n", dresult);
1738           break;
1739         default:
1740           UNREACHABLE();
1741           break;
1742         }
1743       }
1744     } else if (redirection->type() == ExternalReference::DIRECT_API_CALL) {
1745       if (::v8::internal::FLAG_trace_sim) {
1746         PrintF("Call to host function at %p args %08lx\n",
1747             reinterpret_cast<void*>(external), arg0);
1748       }
1749       SimulatorRuntimeDirectApiCall target =
1750           reinterpret_cast<SimulatorRuntimeDirectApiCall>(external);
1751       target(arg0);
1752     } else if (
1753         redirection->type() == ExternalReference::PROFILING_API_CALL) {
1754       if (::v8::internal::FLAG_trace_sim) {
1755         PrintF("Call to host function at %p args %08lx %08lx\n",
1756             reinterpret_cast<void*>(external), arg0, arg1);
1757       }
1758       SimulatorRuntimeProfilingApiCall target =
1759           reinterpret_cast<SimulatorRuntimeProfilingApiCall>(external);
1760       target(arg0, Redirection::ReverseRedirection(arg1));
1761     } else if (
1762         redirection->type() == ExternalReference::DIRECT_GETTER_CALL) {
1763       if (::v8::internal::FLAG_trace_sim) {
1764         PrintF("Call to host function at %p args %08lx %08lx\n",
1765             reinterpret_cast<void*>(external), arg0, arg1);
1766       }
1767       SimulatorRuntimeDirectGetterCall target =
1768           reinterpret_cast<SimulatorRuntimeDirectGetterCall>(external);
1769       target(arg0, arg1);
1770     } else if (
1771         redirection->type() == ExternalReference::PROFILING_GETTER_CALL) {
1772       if (::v8::internal::FLAG_trace_sim) {
1773         PrintF("Call to host function at %p args %08lx %08lx %08lx\n",
1774             reinterpret_cast<void*>(external), arg0, arg1, arg2);
1775       }
1776       SimulatorRuntimeProfilingGetterCall target =
1777           reinterpret_cast<SimulatorRuntimeProfilingGetterCall>(external);
1778       target(arg0, arg1, Redirection::ReverseRedirection(arg2));
1779     } else {
1780       SimulatorRuntimeCall target =
1781                   reinterpret_cast<SimulatorRuntimeCall>(external);
1782       if (::v8::internal::FLAG_trace_sim) {
1783         PrintF(
1784             "Call to host function at %p "
1785             "args %08lx, %08lx, %08lx, %08lx, %08lx, %08lx\n",
1786             FUNCTION_ADDR(target),
1787             arg0,
1788             arg1,
1789             arg2,
1790             arg3,
1791             arg4,
1792             arg5);
1793       }
1794       // int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5);
1795       // set_register(v0, static_cast<int32_t>(result));
1796       // set_register(v1, static_cast<int32_t>(result >> 32));
1797       ObjectPair result = target(arg0, arg1, arg2, arg3, arg4, arg5);
1798       set_register(v0, (int64_t)(result.x));
1799       set_register(v1, (int64_t)(result.y));
1800     }
1801      if (::v8::internal::FLAG_trace_sim) {
1802       PrintF("Returned %08lx : %08lx\n", get_register(v1), get_register(v0));
1803     }
1804     set_register(ra, saved_ra);
1805     set_pc(get_register(ra));
1806
1807   } else if (func == BREAK && code <= kMaxStopCode) {
1808     if (IsWatchpoint(code)) {
1809       PrintWatchpoint(code);
1810     } else {
1811       IncreaseStopCounter(code);
1812       HandleStop(code, instr);
1813     }
1814   } else {
1815     // All remaining break_ codes, and all traps are handled here.
1816     MipsDebugger dbg(this);
1817     dbg.Debug();
1818   }
1819 }
1820
1821
1822 // Stop helper functions.
1823 bool Simulator::IsWatchpoint(uint64_t code) {
1824   return (code <= kMaxWatchpointCode);
1825 }
1826
1827
1828 void Simulator::PrintWatchpoint(uint64_t code) {
1829   MipsDebugger dbg(this);
1830   ++break_count_;
1831   PrintF("\n---- break %ld marker: %3d  (instr count: %8ld) ----------"
1832          "----------------------------------",
1833          code, break_count_, icount_);
1834   dbg.PrintAllRegs();  // Print registers and continue running.
1835 }
1836
1837
1838 void Simulator::HandleStop(uint64_t code, Instruction* instr) {
1839   // Stop if it is enabled, otherwise go on jumping over the stop
1840   // and the message address.
1841   if (IsEnabledStop(code)) {
1842     MipsDebugger dbg(this);
1843     dbg.Stop(instr);
1844   } else {
1845     set_pc(get_pc() + 2 * Instruction::kInstrSize);
1846   }
1847 }
1848
1849
1850 bool Simulator::IsStopInstruction(Instruction* instr) {
1851   int32_t func = instr->FunctionFieldRaw();
1852   uint32_t code = static_cast<uint32_t>(instr->Bits(25, 6));
1853   return (func == BREAK) && code > kMaxWatchpointCode && code <= kMaxStopCode;
1854 }
1855
1856
1857 bool Simulator::IsEnabledStop(uint64_t code) {
1858   DCHECK(code <= kMaxStopCode);
1859   DCHECK(code > kMaxWatchpointCode);
1860   return !(watched_stops_[code].count & kStopDisabledBit);
1861 }
1862
1863
1864 void Simulator::EnableStop(uint64_t code) {
1865   if (!IsEnabledStop(code)) {
1866     watched_stops_[code].count &= ~kStopDisabledBit;
1867   }
1868 }
1869
1870
1871 void Simulator::DisableStop(uint64_t code) {
1872   if (IsEnabledStop(code)) {
1873     watched_stops_[code].count |= kStopDisabledBit;
1874   }
1875 }
1876
1877
1878 void Simulator::IncreaseStopCounter(uint64_t code) {
1879   DCHECK(code <= kMaxStopCode);
1880   if ((watched_stops_[code].count & ~(1 << 31)) == 0x7fffffff) {
1881     PrintF("Stop counter for code %ld has overflowed.\n"
1882            "Enabling this code and reseting the counter to 0.\n", code);
1883     watched_stops_[code].count = 0;
1884     EnableStop(code);
1885   } else {
1886     watched_stops_[code].count++;
1887   }
1888 }
1889
1890
1891 // Print a stop status.
1892 void Simulator::PrintStopInfo(uint64_t code) {
1893   if (code <= kMaxWatchpointCode) {
1894     PrintF("That is a watchpoint, not a stop.\n");
1895     return;
1896   } else if (code > kMaxStopCode) {
1897     PrintF("Code too large, only %u stops can be used\n", kMaxStopCode + 1);
1898     return;
1899   }
1900   const char* state = IsEnabledStop(code) ? "Enabled" : "Disabled";
1901   int32_t count = watched_stops_[code].count & ~kStopDisabledBit;
1902   // Don't print the state of unused breakpoints.
1903   if (count != 0) {
1904     if (watched_stops_[code].desc) {
1905       PrintF("stop %ld - 0x%lx: \t%s, \tcounter = %i, \t%s\n",
1906              code, code, state, count, watched_stops_[code].desc);
1907     } else {
1908       PrintF("stop %ld - 0x%lx: \t%s, \tcounter = %i\n",
1909              code, code, state, count);
1910     }
1911   }
1912 }
1913
1914
1915 void Simulator::SignalExceptions() {
1916   for (int i = 1; i < kNumExceptions; i++) {
1917     if (exceptions[i] != 0) {
1918       V8_Fatal(__FILE__, __LINE__, "Error: Exception %i raised.", i);
1919     }
1920   }
1921 }
1922
1923
1924 // Handle execution based on instruction types.
1925
1926 void Simulator::ConfigureTypeRegister(Instruction* instr,
1927                                       int64_t* alu_out,
1928                                       int64_t* i64hilo,
1929                                       uint64_t* u64hilo,
1930                                       int64_t* next_pc,
1931                                       int64_t* return_addr_reg,
1932                                       bool* do_interrupt,
1933                                       int64_t* i128resultH,
1934                                       int64_t* i128resultL) {
1935   // Every local variable declared here needs to be const.
1936   // This is to make sure that changed values are sent back to
1937   // DecodeTypeRegister correctly.
1938
1939   // Instruction fields.
1940   const Opcode   op     = instr->OpcodeFieldRaw();
1941   const int64_t  rs_reg = instr->RsValue();
1942   const int64_t  rs     = get_register(rs_reg);
1943   const uint64_t rs_u   = static_cast<uint64_t>(rs);
1944   const int64_t  rt_reg = instr->RtValue();
1945   const int64_t  rt     = get_register(rt_reg);
1946   const uint64_t rt_u   = static_cast<uint64_t>(rt);
1947   const int64_t  rd_reg = instr->RdValue();
1948   const uint64_t sa     = instr->SaValue();
1949
1950   const int32_t  fs_reg = instr->FsValue();
1951
1952
1953   // ---------- Configuration.
1954   switch (op) {
1955     case COP1:    // Coprocessor instructions.
1956       switch (instr->RsFieldRaw()) {
1957         case CFC1:
1958           // At the moment only FCSR is supported.
1959           DCHECK(fs_reg == kFCSRRegister);
1960           *alu_out = FCSR_;
1961           break;
1962         case MFC1:
1963           *alu_out = static_cast<int64_t>(get_fpu_register_word(fs_reg));
1964           break;
1965         case DMFC1:
1966           *alu_out = get_fpu_register(fs_reg);
1967           break;
1968         case MFHC1:
1969           *alu_out = get_fpu_register_hi_word(fs_reg);
1970           break;
1971         case CTC1:
1972         case MTC1:
1973         case DMTC1:
1974         case MTHC1:
1975         case S:
1976         case D:
1977         case W:
1978         case L:
1979         case PS:
1980           // Do everything in the execution step.
1981           break;
1982         default:
1983         // BC1 BC1EQZ BC1NEZ handled in DecodeTypeImmed, should never come here.
1984            UNREACHABLE();
1985       }
1986       break;
1987     case COP1X:
1988       break;
1989     case SPECIAL:
1990       switch (instr->FunctionFieldRaw()) {
1991         case JR:
1992         case JALR:
1993           *next_pc = get_register(instr->RsValue());
1994           *return_addr_reg = instr->RdValue();
1995           break;
1996         case SLL:
1997           *alu_out = (int32_t)rt << sa;
1998           break;
1999         case DSLL:
2000           *alu_out = rt << sa;
2001           break;
2002         case DSLL32:
2003           *alu_out = rt << sa << 32;
2004           break;
2005         case SRL:
2006           if (rs_reg == 0) {
2007             // Regular logical right shift of a word by a fixed number of
2008             // bits instruction. RS field is always equal to 0.
2009             *alu_out = (uint32_t)rt_u >> sa;
2010           } else {
2011             // Logical right-rotate of a word by a fixed number of bits. This
2012             // is special case of SRL instruction, added in MIPS32 Release 2.
2013             // RS field is equal to 00001.
2014             *alu_out = ((uint32_t)rt_u >> sa) | ((uint32_t)rt_u << (32 - sa));
2015           }
2016           break;
2017         case DSRL:
2018           *alu_out = rt_u >> sa;
2019           break;
2020         case DSRL32:
2021           *alu_out = rt_u >> sa >> 32;
2022           break;
2023         case SRA:
2024           *alu_out = (int32_t)rt >> sa;
2025           break;
2026         case DSRA:
2027           *alu_out = rt >> sa;
2028           break;
2029         case DSRA32:
2030           *alu_out = rt >> sa >> 32;
2031           break;
2032         case SLLV:
2033           *alu_out = (int32_t)rt << rs;
2034           break;
2035         case DSLLV:
2036           *alu_out = rt << rs;
2037           break;
2038         case SRLV:
2039           if (sa == 0) {
2040             // Regular logical right-shift of a word by a variable number of
2041             // bits instruction. SA field is always equal to 0.
2042             *alu_out = (uint32_t)rt_u >> rs;
2043           } else {
2044             // Logical right-rotate of a word by a variable number of bits.
2045             // This is special case od SRLV instruction, added in MIPS32
2046             // Release 2. SA field is equal to 00001.
2047             *alu_out =
2048                 ((uint32_t)rt_u >> rs_u) | ((uint32_t)rt_u << (32 - rs_u));
2049           }
2050           break;
2051         case DSRLV:
2052           if (sa == 0) {
2053             // Regular logical right-shift of a word by a variable number of
2054             // bits instruction. SA field is always equal to 0.
2055             *alu_out = rt_u >> rs;
2056           } else {
2057             // Logical right-rotate of a word by a variable number of bits.
2058             // This is special case od SRLV instruction, added in MIPS32
2059             // Release 2. SA field is equal to 00001.
2060             *alu_out = (rt_u >> rs_u) | (rt_u << (32 - rs_u));
2061           }
2062           break;
2063         case SRAV:
2064           *alu_out = (int32_t)rt >> rs;
2065           break;
2066         case DSRAV:
2067           *alu_out = rt >> rs;
2068           break;
2069         case MFHI:  // MFHI == CLZ on R6.
2070           if (kArchVariant != kMips64r6) {
2071             DCHECK(instr->SaValue() == 0);
2072             *alu_out = get_register(HI);
2073           } else {
2074             // MIPS spec: If no bits were set in GPR rs, the result written to
2075             // GPR rd is 32.
2076             DCHECK(instr->SaValue() == 1);
2077             *alu_out = base::bits::CountLeadingZeros32(rs_u);
2078           }
2079           break;
2080         case MFLO:
2081           *alu_out = get_register(LO);
2082           break;
2083         case MULT:  // MULT == D_MUL_MUH.
2084           // TODO(plind) - Unify MULT/DMULT with single set of 64-bit HI/Lo
2085           // regs.
2086           // TODO(plind) - make the 32-bit MULT ops conform to spec regarding
2087           //   checking of 32-bit input values, and un-define operations of HW.
2088           *i64hilo = rs * rt;
2089           break;
2090         case MULTU:
2091           *u64hilo = static_cast<uint64_t>(rs_u) * static_cast<uint64_t>(rt_u);
2092           break;
2093         case DMULT:  // DMULT == D_MUL_MUH.
2094           if (kArchVariant != kMips64r6) {
2095             *i128resultH = MultiplyHighSigned(rs, rt);
2096             *i128resultL = rs * rt;
2097           } else {
2098             switch (instr->SaValue()) {
2099               case MUL_OP:
2100                 *i128resultL = rs * rt;
2101                 break;
2102               case MUH_OP:
2103                 *i128resultH = MultiplyHighSigned(rs, rt);
2104                 break;
2105               default:
2106                 UNIMPLEMENTED_MIPS();
2107                 break;
2108             }
2109           }
2110           break;
2111         case DMULTU:
2112           UNIMPLEMENTED_MIPS();
2113           break;
2114         case ADD:
2115         case DADD:
2116           if (HaveSameSign(rs, rt)) {
2117             if (rs > 0) {
2118               exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue - rt);
2119             } else if (rs < 0) {
2120               exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue - rt);
2121             }
2122           }
2123           *alu_out = rs + rt;
2124           break;
2125         case ADDU: {
2126             int32_t alu32_out = rs + rt;
2127             // Sign-extend result of 32bit operation into 64bit register.
2128             *alu_out = static_cast<int64_t>(alu32_out);
2129           }
2130           break;
2131         case DADDU:
2132           *alu_out = rs + rt;
2133           break;
2134         case SUB:
2135         case DSUB:
2136           if (!HaveSameSign(rs, rt)) {
2137             if (rs > 0) {
2138               exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue + rt);
2139             } else if (rs < 0) {
2140               exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue + rt);
2141             }
2142           }
2143           *alu_out = rs - rt;
2144           break;
2145         case SUBU: {
2146             int32_t alu32_out = rs - rt;
2147             // Sign-extend result of 32bit operation into 64bit register.
2148             *alu_out = static_cast<int64_t>(alu32_out);
2149           }
2150           break;
2151         case DSUBU:
2152           *alu_out = rs - rt;
2153           break;
2154         case AND:
2155           *alu_out = rs & rt;
2156           break;
2157         case OR:
2158           *alu_out = rs | rt;
2159           break;
2160         case XOR:
2161           *alu_out = rs ^ rt;
2162           break;
2163         case NOR:
2164           *alu_out = ~(rs | rt);
2165           break;
2166         case SLT:
2167           *alu_out = rs < rt ? 1 : 0;
2168           break;
2169         case SLTU:
2170           *alu_out = rs_u < rt_u ? 1 : 0;
2171           break;
2172         // Break and trap instructions.
2173         case BREAK:
2174
2175           *do_interrupt = true;
2176           break;
2177         case TGE:
2178           *do_interrupt = rs >= rt;
2179           break;
2180         case TGEU:
2181           *do_interrupt = rs_u >= rt_u;
2182           break;
2183         case TLT:
2184           *do_interrupt = rs < rt;
2185           break;
2186         case TLTU:
2187           *do_interrupt = rs_u < rt_u;
2188           break;
2189         case TEQ:
2190           *do_interrupt = rs == rt;
2191           break;
2192         case TNE:
2193           *do_interrupt = rs != rt;
2194           break;
2195         case MOVN:
2196         case MOVZ:
2197         case MOVCI:
2198           // No action taken on decode.
2199           break;
2200         case DIV:
2201         case DIVU:
2202         case DDIV:
2203         case DDIVU:
2204           // div and divu never raise exceptions.
2205           break;
2206         default:
2207           UNREACHABLE();
2208       }
2209       break;
2210     case SPECIAL2:
2211       switch (instr->FunctionFieldRaw()) {
2212         case MUL:
2213           // Only the lower 32 bits are kept.
2214           *alu_out = (int32_t)rs_u * (int32_t)rt_u;
2215           break;
2216         case CLZ:
2217           // MIPS32 spec: If no bits were set in GPR rs, the result written to
2218           // GPR rd is 32.
2219           *alu_out = base::bits::CountLeadingZeros32(rs_u);
2220           break;
2221         default:
2222           UNREACHABLE();
2223       }
2224       break;
2225     case SPECIAL3:
2226       switch (instr->FunctionFieldRaw()) {
2227         case INS: {   // Mips32r2 instruction.
2228           // Interpret rd field as 5-bit msb of insert.
2229           uint16_t msb = rd_reg;
2230           // Interpret sa field as 5-bit lsb of insert.
2231           uint16_t lsb = sa;
2232           uint16_t size = msb - lsb + 1;
2233           uint32_t mask = (1 << size) - 1;
2234           *alu_out = (rt_u & ~(mask << lsb)) | ((rs_u & mask) << lsb);
2235           break;
2236         }
2237         case EXT: {   // Mips32r2 instruction.
2238           // Interpret rd field as 5-bit msb of extract.
2239           uint16_t msb = rd_reg;
2240           // Interpret sa field as 5-bit lsb of extract.
2241           uint16_t lsb = sa;
2242           uint16_t size = msb + 1;
2243           uint32_t mask = (1 << size) - 1;
2244           *alu_out = (rs_u & (mask << lsb)) >> lsb;
2245           break;
2246         }
2247         default:
2248           UNREACHABLE();
2249       }
2250       break;
2251     default:
2252       UNREACHABLE();
2253   }
2254 }
2255
2256
2257 void Simulator::DecodeTypeRegister(Instruction* instr) {
2258   // Instruction fields.
2259   const Opcode   op     = instr->OpcodeFieldRaw();
2260   const int64_t  rs_reg = instr->RsValue();
2261   const int64_t  rs     = get_register(rs_reg);
2262   const uint64_t rs_u   = static_cast<uint32_t>(rs);
2263   const int64_t  rt_reg = instr->RtValue();
2264   const int64_t  rt     = get_register(rt_reg);
2265   const uint64_t rt_u   = static_cast<uint32_t>(rt);
2266   const int64_t  rd_reg = instr->RdValue();
2267
2268   const int32_t  fr_reg = instr->FrValue();
2269   const int32_t  fs_reg = instr->FsValue();
2270   const int32_t  ft_reg = instr->FtValue();
2271   const int64_t  fd_reg = instr->FdValue();
2272   int64_t  i64hilo = 0;
2273   uint64_t u64hilo = 0;
2274
2275   // ALU output.
2276   // It should not be used as is. Instructions using it should always
2277   // initialize it first.
2278   int64_t alu_out = 0x12345678;
2279
2280   // For break and trap instructions.
2281   bool do_interrupt = false;
2282
2283   // For jr and jalr.
2284   // Get current pc.
2285   int64_t current_pc = get_pc();
2286   // Next pc
2287   int64_t next_pc = 0;
2288   int64_t return_addr_reg = 31;
2289
2290   int64_t i128resultH;
2291   int64_t i128resultL;
2292
2293   // Set up the variables if needed before executing the instruction.
2294   ConfigureTypeRegister(instr,
2295                         &alu_out,
2296                         &i64hilo,
2297                         &u64hilo,
2298                         &next_pc,
2299                         &return_addr_reg,
2300                         &do_interrupt,
2301                         &i128resultH,
2302                         &i128resultL);
2303
2304   // ---------- Raise exceptions triggered.
2305   SignalExceptions();
2306
2307   // ---------- Execution.
2308   switch (op) {
2309     case COP1:
2310       switch (instr->RsFieldRaw()) {
2311         case BC1:   // Branch on coprocessor condition.
2312         case BC1EQZ:
2313         case BC1NEZ:
2314           UNREACHABLE();
2315           break;
2316         case CFC1:
2317           set_register(rt_reg, alu_out);
2318           break;
2319         case MFC1:
2320         case DMFC1:
2321         case MFHC1:
2322           set_register(rt_reg, alu_out);
2323           break;
2324         case CTC1:
2325           // At the moment only FCSR is supported.
2326           DCHECK(fs_reg == kFCSRRegister);
2327           FCSR_ = registers_[rt_reg];
2328           break;
2329         case MTC1:
2330           // Hardware writes upper 32-bits to zero on mtc1.
2331           set_fpu_register_hi_word(fs_reg, 0);
2332           set_fpu_register_word(fs_reg, registers_[rt_reg]);
2333           break;
2334         case DMTC1:
2335           set_fpu_register(fs_reg, registers_[rt_reg]);
2336           break;
2337         case MTHC1:
2338           set_fpu_register_hi_word(fs_reg, registers_[rt_reg]);
2339           break;
2340         case S:
2341           float f;
2342           switch (instr->FunctionFieldRaw()) {
2343             case CVT_D_S:
2344               f = get_fpu_register_float(fs_reg);
2345               set_fpu_register_double(fd_reg, static_cast<double>(f));
2346               break;
2347             default:
2348             // CVT_W_S CVT_L_S TRUNC_W_S ROUND_W_S ROUND_L_S FLOOR_W_S FLOOR_L_S
2349             // CEIL_W_S CEIL_L_S CVT_PS_S are unimplemented.
2350               UNREACHABLE();
2351           }
2352           break;
2353         case D:
2354           double ft, fs;
2355           uint32_t cc, fcsr_cc;
2356           int64_t  i64;
2357           fs = get_fpu_register_double(fs_reg);
2358           ft = get_fpu_register_double(ft_reg);
2359           cc = instr->FCccValue();
2360           fcsr_cc = get_fcsr_condition_bit(cc);
2361           switch (instr->FunctionFieldRaw()) {
2362             case ADD_D:
2363               set_fpu_register_double(fd_reg, fs + ft);
2364               break;
2365             case SUB_D:
2366               set_fpu_register_double(fd_reg, fs - ft);
2367               break;
2368             case MUL_D:
2369               set_fpu_register_double(fd_reg, fs * ft);
2370               break;
2371             case DIV_D:
2372               set_fpu_register_double(fd_reg, fs / ft);
2373               break;
2374             case ABS_D:
2375               set_fpu_register_double(fd_reg, fabs(fs));
2376               break;
2377             case MOV_D:
2378               set_fpu_register_double(fd_reg, fs);
2379               break;
2380             case NEG_D:
2381               set_fpu_register_double(fd_reg, -fs);
2382               break;
2383             case SQRT_D:
2384               set_fpu_register_double(fd_reg, sqrt(fs));
2385               break;
2386             case C_UN_D:
2387               set_fcsr_bit(fcsr_cc, std::isnan(fs) || std::isnan(ft));
2388               break;
2389             case C_EQ_D:
2390               set_fcsr_bit(fcsr_cc, (fs == ft));
2391               break;
2392             case C_UEQ_D:
2393               set_fcsr_bit(fcsr_cc,
2394                            (fs == ft) || (std::isnan(fs) || std::isnan(ft)));
2395               break;
2396             case C_OLT_D:
2397               set_fcsr_bit(fcsr_cc, (fs < ft));
2398               break;
2399             case C_ULT_D:
2400               set_fcsr_bit(fcsr_cc,
2401                            (fs < ft) || (std::isnan(fs) || std::isnan(ft)));
2402               break;
2403             case C_OLE_D:
2404               set_fcsr_bit(fcsr_cc, (fs <= ft));
2405               break;
2406             case C_ULE_D:
2407               set_fcsr_bit(fcsr_cc,
2408                            (fs <= ft) || (std::isnan(fs) || std::isnan(ft)));
2409               break;
2410             case CVT_W_D:   // Convert double to word.
2411               // Rounding modes are not yet supported.
2412               DCHECK((FCSR_ & 3) == 0);
2413               // In rounding mode 0 it should behave like ROUND.
2414               // No break.
2415             case ROUND_W_D:  // Round double to word (round half to even).
2416               {
2417                 double rounded = std::floor(fs + 0.5);
2418                 int32_t result = static_cast<int32_t>(rounded);
2419                 if ((result & 1) != 0 && result - fs == 0.5) {
2420                   // If the number is halfway between two integers,
2421                   // round to the even one.
2422                   result--;
2423                 }
2424                 set_fpu_register_word(fd_reg, result);
2425                 if (set_fcsr_round_error(fs, rounded)) {
2426                   set_fpu_register(fd_reg, kFPUInvalidResult);
2427                 }
2428               }
2429               break;
2430             case TRUNC_W_D:  // Truncate double to word (round towards 0).
2431               {
2432                 double rounded = trunc(fs);
2433                 int32_t result = static_cast<int32_t>(rounded);
2434                 set_fpu_register_word(fd_reg, result);
2435                 if (set_fcsr_round_error(fs, rounded)) {
2436                   set_fpu_register(fd_reg, kFPUInvalidResult);
2437                 }
2438               }
2439               break;
2440             case FLOOR_W_D:  // Round double to word towards negative infinity.
2441               {
2442                 double rounded = std::floor(fs);
2443                 int32_t result = static_cast<int32_t>(rounded);
2444                 set_fpu_register_word(fd_reg, result);
2445                 if (set_fcsr_round_error(fs, rounded)) {
2446                   set_fpu_register(fd_reg, kFPUInvalidResult);
2447                 }
2448               }
2449               break;
2450             case CEIL_W_D:  // Round double to word towards positive infinity.
2451               {
2452                 double rounded = std::ceil(fs);
2453                 int32_t result = static_cast<int32_t>(rounded);
2454                 set_fpu_register_word(fd_reg, result);
2455                 if (set_fcsr_round_error(fs, rounded)) {
2456                   set_fpu_register(fd_reg, kFPUInvalidResult);
2457                 }
2458               }
2459               break;
2460             case CVT_S_D:  // Convert double to float (single).
2461               set_fpu_register_float(fd_reg, static_cast<float>(fs));
2462               break;
2463             case CVT_L_D:   // Mips64r2: Truncate double to 64-bit long-word.
2464               // Rounding modes are not yet supported.
2465               DCHECK((FCSR_ & 3) == 0);
2466               // In rounding mode 0 it should behave like ROUND.
2467               // No break.
2468             case ROUND_L_D: {  // Mips64r2 instruction.
2469               // check error cases
2470               double rounded = fs > 0 ? floor(fs + 0.5) : ceil(fs - 0.5);
2471               int64_t result = static_cast<int64_t>(rounded);
2472               set_fpu_register(fd_reg, result);
2473               if (set_fcsr_round64_error(fs, rounded)) {
2474                 set_fpu_register(fd_reg, kFPU64InvalidResult);
2475               }
2476               break;
2477             }
2478             case TRUNC_L_D: {  // Mips64r2 instruction.
2479               double rounded = trunc(fs);
2480               int64_t result = static_cast<int64_t>(rounded);
2481               set_fpu_register(fd_reg, result);
2482               if (set_fcsr_round64_error(fs, rounded)) {
2483                 set_fpu_register(fd_reg, kFPU64InvalidResult);
2484               }
2485               break;
2486             }
2487             case FLOOR_L_D: {  // Mips64r2 instruction.
2488               double rounded = floor(fs);
2489               int64_t result = static_cast<int64_t>(rounded);
2490               set_fpu_register(fd_reg, result);
2491               if (set_fcsr_round64_error(fs, rounded)) {
2492                 set_fpu_register(fd_reg, kFPU64InvalidResult);
2493               }
2494               break;
2495             }
2496             case CEIL_L_D: {  // Mips64r2 instruction.
2497               double rounded = ceil(fs);
2498               int64_t result = static_cast<int64_t>(rounded);
2499               set_fpu_register(fd_reg, result);
2500               if (set_fcsr_round64_error(fs, rounded)) {
2501                 set_fpu_register(fd_reg, kFPU64InvalidResult);
2502               }
2503               break;
2504             }
2505             case C_F_D:
2506               UNIMPLEMENTED_MIPS();
2507               break;
2508             default:
2509               UNREACHABLE();
2510           }
2511           break;
2512         case W:
2513           switch (instr->FunctionFieldRaw()) {
2514             case CVT_S_W:   // Convert word to float (single).
2515               alu_out = get_fpu_register_signed_word(fs_reg);
2516               set_fpu_register_float(fd_reg, static_cast<float>(alu_out));
2517               break;
2518             case CVT_D_W:   // Convert word to double.
2519               alu_out = get_fpu_register_signed_word(fs_reg);
2520               set_fpu_register_double(fd_reg, static_cast<double>(alu_out));
2521               break;
2522             default:  // Mips64r6 CMP.S instructions unimplemented.
2523               UNREACHABLE();
2524           }
2525           break;
2526         case L:
2527           fs = get_fpu_register_double(fs_reg);
2528           ft = get_fpu_register_double(ft_reg);
2529           switch (instr->FunctionFieldRaw()) {
2530             case CVT_D_L:  // Mips32r2 instruction.
2531               i64 = get_fpu_register(fs_reg);
2532               set_fpu_register_double(fd_reg, static_cast<double>(i64));
2533               break;
2534             case CVT_S_L:
2535               UNIMPLEMENTED_MIPS();
2536               break;
2537             case CMP_AF:  // Mips64r6 CMP.D instructions.
2538               UNIMPLEMENTED_MIPS();
2539               break;
2540             case CMP_UN:
2541               if (std::isnan(fs) || std::isnan(ft)) {
2542                 set_fpu_register(fd_reg, -1);
2543               } else {
2544                 set_fpu_register(fd_reg, 0);
2545               }
2546               break;
2547             case CMP_EQ:
2548               if (fs == ft) {
2549                 set_fpu_register(fd_reg, -1);
2550               } else {
2551                 set_fpu_register(fd_reg, 0);
2552               }
2553               break;
2554             case CMP_UEQ:
2555               if ((fs == ft) || (std::isnan(fs) || std::isnan(ft))) {
2556                 set_fpu_register(fd_reg, -1);
2557               } else {
2558                 set_fpu_register(fd_reg, 0);
2559               }
2560               break;
2561             case CMP_LT:
2562               if (fs < ft) {
2563                 set_fpu_register(fd_reg, -1);
2564               } else {
2565                 set_fpu_register(fd_reg, 0);
2566               }
2567               break;
2568             case CMP_ULT:
2569               if ((fs < ft) || (std::isnan(fs) || std::isnan(ft))) {
2570                 set_fpu_register(fd_reg, -1);
2571               } else {
2572                 set_fpu_register(fd_reg, 0);
2573               }
2574               break;
2575             case CMP_LE:
2576               if (fs <= ft) {
2577                 set_fpu_register(fd_reg, -1);
2578               } else {
2579                 set_fpu_register(fd_reg, 0);
2580               }
2581               break;
2582             case CMP_ULE:
2583               if ((fs <= ft) || (std::isnan(fs) || std::isnan(ft))) {
2584                 set_fpu_register(fd_reg, -1);
2585               } else {
2586                 set_fpu_register(fd_reg, 0);
2587               }
2588               break;
2589             default:  // CMP_OR CMP_UNE CMP_NE UNIMPLEMENTED
2590               UNREACHABLE();
2591           }
2592           break;
2593         default:
2594           UNREACHABLE();
2595       }
2596       break;
2597     case COP1X:
2598       switch (instr->FunctionFieldRaw()) {
2599         case MADD_D:
2600           double fr, ft, fs;
2601           fr = get_fpu_register_double(fr_reg);
2602           fs = get_fpu_register_double(fs_reg);
2603           ft = get_fpu_register_double(ft_reg);
2604           set_fpu_register_double(fd_reg, fs * ft + fr);
2605           break;
2606         default:
2607           UNREACHABLE();
2608       }
2609       break;
2610     case SPECIAL:
2611       switch (instr->FunctionFieldRaw()) {
2612         case JR: {
2613           Instruction* branch_delay_instr = reinterpret_cast<Instruction*>(
2614               current_pc+Instruction::kInstrSize);
2615           BranchDelayInstructionDecode(branch_delay_instr);
2616           set_pc(next_pc);
2617           pc_modified_ = true;
2618           break;
2619         }
2620         case JALR: {
2621           Instruction* branch_delay_instr = reinterpret_cast<Instruction*>(
2622               current_pc+Instruction::kInstrSize);
2623           BranchDelayInstructionDecode(branch_delay_instr);
2624           set_register(return_addr_reg,
2625                        current_pc + 2 * Instruction::kInstrSize);
2626           set_pc(next_pc);
2627           pc_modified_ = true;
2628           break;
2629         }
2630         // Instructions using HI and LO registers.
2631         case MULT:
2632           if (kArchVariant != kMips64r6) {
2633             set_register(LO, static_cast<int32_t>(i64hilo & 0xffffffff));
2634             set_register(HI, static_cast<int32_t>(i64hilo >> 32));
2635           } else {
2636             switch (instr->SaValue()) {
2637               case MUL_OP:
2638                 set_register(rd_reg,
2639                     static_cast<int32_t>(i64hilo & 0xffffffff));
2640                 break;
2641               case MUH_OP:
2642                 set_register(rd_reg, static_cast<int32_t>(i64hilo >> 32));
2643                 break;
2644               default:
2645                 UNIMPLEMENTED_MIPS();
2646                 break;
2647             }
2648           }
2649           break;
2650         case MULTU:
2651           set_register(LO, static_cast<int32_t>(u64hilo & 0xffffffff));
2652           set_register(HI, static_cast<int32_t>(u64hilo >> 32));
2653           break;
2654         case DMULT:  // DMULT == D_MUL_MUH.
2655           if (kArchVariant != kMips64r6) {
2656             set_register(LO, static_cast<int64_t>(i128resultL));
2657             set_register(HI, static_cast<int64_t>(i128resultH));
2658           } else {
2659             switch (instr->SaValue()) {
2660               case MUL_OP:
2661                 set_register(rd_reg, static_cast<int64_t>(i128resultL));
2662                 break;
2663               case MUH_OP:
2664                 set_register(rd_reg, static_cast<int64_t>(i128resultH));
2665                 break;
2666               default:
2667                 UNIMPLEMENTED_MIPS();
2668                 break;
2669             }
2670           }
2671           break;
2672         case DMULTU:
2673           UNIMPLEMENTED_MIPS();
2674           break;
2675         case DSLL:
2676           set_register(rd_reg, alu_out);
2677           break;
2678         case DIV:
2679         case DDIV:
2680           switch (kArchVariant) {
2681             case kMips64r2:
2682               // Divide by zero and overflow was not checked in the
2683               // configuration step - div and divu do not raise exceptions. On
2684               // division by 0 the result will be UNPREDICTABLE. On overflow
2685               // (INT_MIN/-1), return INT_MIN which is what the hardware does.
2686               if (rs == INT_MIN && rt == -1) {
2687                 set_register(LO, INT_MIN);
2688                 set_register(HI, 0);
2689               } else if (rt != 0) {
2690                 set_register(LO, rs / rt);
2691                 set_register(HI, rs % rt);
2692               }
2693               break;
2694             case kMips64r6:
2695               switch (instr->SaValue()) {
2696                 case DIV_OP:
2697                   if (rs == INT_MIN && rt == -1) {
2698                     set_register(rd_reg, INT_MIN);
2699                   } else if (rt != 0) {
2700                     set_register(rd_reg, rs / rt);
2701                   }
2702                   break;
2703                 case MOD_OP:
2704                   if (rs == INT_MIN && rt == -1) {
2705                     set_register(rd_reg, 0);
2706                   } else if (rt != 0) {
2707                     set_register(rd_reg, rs % rt);
2708                   }
2709                   break;
2710                 default:
2711                   UNIMPLEMENTED_MIPS();
2712                   break;
2713               }
2714               break;
2715             default:
2716               break;
2717           }
2718           break;
2719         case DIVU:
2720           if (rt_u != 0) {
2721             set_register(LO, rs_u / rt_u);
2722             set_register(HI, rs_u % rt_u);
2723           }
2724           break;
2725         // Break and trap instructions.
2726         case BREAK:
2727         case TGE:
2728         case TGEU:
2729         case TLT:
2730         case TLTU:
2731         case TEQ:
2732         case TNE:
2733           if (do_interrupt) {
2734             SoftwareInterrupt(instr);
2735           }
2736           break;
2737         // Conditional moves.
2738         case MOVN:
2739           if (rt) {
2740             set_register(rd_reg, rs);
2741             TraceRegWr(rs);
2742           }
2743           break;
2744         case MOVCI: {
2745           uint32_t cc = instr->FBccValue();
2746           uint32_t fcsr_cc = get_fcsr_condition_bit(cc);
2747           if (instr->Bit(16)) {  // Read Tf bit.
2748             if (test_fcsr_bit(fcsr_cc)) set_register(rd_reg, rs);
2749           } else {
2750             if (!test_fcsr_bit(fcsr_cc)) set_register(rd_reg, rs);
2751           }
2752           break;
2753         }
2754         case MOVZ:
2755           if (!rt) {
2756             set_register(rd_reg, rs);
2757             TraceRegWr(rs);
2758           }
2759           break;
2760         default:  // For other special opcodes we do the default operation.
2761           set_register(rd_reg, alu_out);
2762           TraceRegWr(alu_out);
2763       }
2764       break;
2765     case SPECIAL2:
2766       switch (instr->FunctionFieldRaw()) {
2767         case MUL:
2768           set_register(rd_reg, alu_out);
2769           TraceRegWr(alu_out);
2770           // HI and LO are UNPREDICTABLE after the operation.
2771           set_register(LO, Unpredictable);
2772           set_register(HI, Unpredictable);
2773           break;
2774         default:  // For other special2 opcodes we do the default operation.
2775           set_register(rd_reg, alu_out);
2776       }
2777       break;
2778     case SPECIAL3:
2779       switch (instr->FunctionFieldRaw()) {
2780         case INS:
2781           // Ins instr leaves result in Rt, rather than Rd.
2782           set_register(rt_reg, alu_out);
2783           TraceRegWr(alu_out);
2784           break;
2785         case EXT:
2786           // Ext instr leaves result in Rt, rather than Rd.
2787           set_register(rt_reg, alu_out);
2788           TraceRegWr(alu_out);
2789           break;
2790         default:
2791           UNREACHABLE();
2792       }
2793       break;
2794     // Unimplemented opcodes raised an error in the configuration step before,
2795     // so we can use the default here to set the destination register in common
2796     // cases.
2797     default:
2798       set_register(rd_reg, alu_out);
2799       TraceRegWr(alu_out);
2800   }
2801 }
2802
2803
2804 // Type 2: instructions using a 16 bytes immediate. (e.g. addi, beq).
2805 void Simulator::DecodeTypeImmediate(Instruction* instr) {
2806   // Instruction fields.
2807   Opcode   op     = instr->OpcodeFieldRaw();
2808   int64_t  rs     = get_register(instr->RsValue());
2809   uint64_t rs_u   = static_cast<uint64_t>(rs);
2810   int64_t  rt_reg = instr->RtValue();  // Destination register.
2811   int64_t  rt     = get_register(rt_reg);
2812   int16_t  imm16  = instr->Imm16Value();
2813
2814   int32_t  ft_reg = instr->FtValue();  // Destination register.
2815   int64_t  ft     = get_fpu_register(ft_reg);
2816
2817   // Zero extended immediate.
2818   uint32_t  oe_imm16 = 0xffff & imm16;
2819   // Sign extended immediate.
2820   int32_t   se_imm16 = imm16;
2821
2822   // Get current pc.
2823   int64_t current_pc = get_pc();
2824   // Next pc.
2825   int64_t next_pc = bad_ra;
2826
2827   // Used for conditional branch instructions.
2828   bool do_branch = false;
2829   bool execute_branch_delay_instruction = false;
2830
2831   // Used for arithmetic instructions.
2832   int64_t alu_out = 0;
2833   // Floating point.
2834   double fp_out = 0.0;
2835   uint32_t cc, cc_value, fcsr_cc;
2836
2837   // Used for memory instructions.
2838   int64_t addr = 0x0;
2839   // Value to be written in memory.
2840   uint64_t mem_value = 0x0;
2841   // Alignment for 32-bit integers used in LWL, LWR, etc.
2842   const int kInt32AlignmentMask = sizeof(uint32_t) - 1;
2843
2844   // ---------- Configuration (and execution for REGIMM).
2845   switch (op) {
2846     // ------------- COP1. Coprocessor instructions.
2847     case COP1:
2848       switch (instr->RsFieldRaw()) {
2849         case BC1:   // Branch on coprocessor condition.
2850           cc = instr->FBccValue();
2851           fcsr_cc = get_fcsr_condition_bit(cc);
2852           cc_value = test_fcsr_bit(fcsr_cc);
2853           do_branch = (instr->FBtrueValue()) ? cc_value : !cc_value;
2854           execute_branch_delay_instruction = true;
2855           // Set next_pc.
2856           if (do_branch) {
2857             next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2858           } else {
2859             next_pc = current_pc + kBranchReturnOffset;
2860           }
2861           break;
2862         case BC1EQZ:
2863           do_branch = (ft & 0x1) ? false : true;
2864           execute_branch_delay_instruction = true;
2865           // Set next_pc.
2866           if (do_branch) {
2867             next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2868           } else {
2869             next_pc = current_pc + kBranchReturnOffset;
2870           }
2871           break;
2872         case BC1NEZ:
2873           do_branch = (ft & 0x1) ? true : false;
2874           execute_branch_delay_instruction = true;
2875           // Set next_pc.
2876           if (do_branch) {
2877             next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2878           } else {
2879             next_pc = current_pc + kBranchReturnOffset;
2880           }
2881           break;
2882         default:
2883           UNREACHABLE();
2884       }
2885       break;
2886     // ------------- REGIMM class.
2887     case REGIMM:
2888       switch (instr->RtFieldRaw()) {
2889         case BLTZ:
2890           do_branch = (rs  < 0);
2891           break;
2892         case BLTZAL:
2893           do_branch = rs  < 0;
2894           break;
2895         case BGEZ:
2896           do_branch = rs >= 0;
2897           break;
2898         case BGEZAL:
2899           do_branch = rs >= 0;
2900           break;
2901         default:
2902           UNREACHABLE();
2903       }
2904       switch (instr->RtFieldRaw()) {
2905         case BLTZ:
2906         case BLTZAL:
2907         case BGEZ:
2908         case BGEZAL:
2909           // Branch instructions common part.
2910           execute_branch_delay_instruction = true;
2911           // Set next_pc.
2912           if (do_branch) {
2913             next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2914             if (instr->IsLinkingInstruction()) {
2915               set_register(31, current_pc + kBranchReturnOffset);
2916             }
2917           } else {
2918             next_pc = current_pc + kBranchReturnOffset;
2919           }
2920         default:
2921           break;
2922         }
2923     break;  // case REGIMM.
2924     // ------------- Branch instructions.
2925     // When comparing to zero, the encoding of rt field is always 0, so we don't
2926     // need to replace rt with zero.
2927     case BEQ:
2928       do_branch = (rs == rt);
2929       break;
2930     case BNE:
2931       do_branch = rs != rt;
2932       break;
2933     case BLEZ:
2934       do_branch = rs <= 0;
2935       break;
2936     case BGTZ:
2937       do_branch = rs  > 0;
2938       break;
2939     // ------------- Arithmetic instructions.
2940     case ADDI:
2941     case DADDI:
2942       if (HaveSameSign(rs, se_imm16)) {
2943         if (rs > 0) {
2944           exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue - se_imm16);
2945         } else if (rs < 0) {
2946           exceptions[kIntegerUnderflow] =
2947               rs < (Registers::kMinValue - se_imm16);
2948         }
2949       }
2950       alu_out = rs + se_imm16;
2951       break;
2952     case ADDIU: {
2953         int32_t alu32_out = rs + se_imm16;
2954         // Sign-extend result of 32bit operation into 64bit register.
2955         alu_out = static_cast<int64_t>(alu32_out);
2956       }
2957       break;
2958     case DADDIU:
2959       alu_out = rs + se_imm16;
2960       break;
2961     case SLTI:
2962       alu_out = (rs < se_imm16) ? 1 : 0;
2963       break;
2964     case SLTIU:
2965       alu_out = (rs_u < static_cast<uint32_t>(se_imm16)) ? 1 : 0;
2966       break;
2967     case ANDI:
2968         alu_out = rs & oe_imm16;
2969       break;
2970     case ORI:
2971         alu_out = rs | oe_imm16;
2972       break;
2973     case XORI:
2974         alu_out = rs ^ oe_imm16;
2975       break;
2976     case LUI: {
2977         int32_t alu32_out = (oe_imm16 << 16);
2978         // Sign-extend result of 32bit operation into 64bit register.
2979         alu_out = static_cast<int64_t>(alu32_out);
2980       }
2981       break;
2982     // ------------- Memory instructions.
2983     case LB:
2984       addr = rs + se_imm16;
2985       alu_out = ReadB(addr);
2986       break;
2987     case LH:
2988       addr = rs + se_imm16;
2989       alu_out = ReadH(addr, instr);
2990       break;
2991     case LWL: {
2992       // al_offset is offset of the effective address within an aligned word.
2993       uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
2994       uint8_t byte_shift = kInt32AlignmentMask - al_offset;
2995       uint32_t mask = (1 << byte_shift * 8) - 1;
2996       addr = rs + se_imm16 - al_offset;
2997       alu_out = ReadW(addr, instr);
2998       alu_out <<= byte_shift * 8;
2999       alu_out |= rt & mask;
3000       break;
3001     }
3002     case LW:
3003       addr = rs + se_imm16;
3004       alu_out = ReadW(addr, instr);
3005       break;
3006     case LWU:
3007       addr = rs + se_imm16;
3008       alu_out = ReadWU(addr, instr);
3009       break;
3010     case LD:
3011       addr = rs + se_imm16;
3012       alu_out = Read2W(addr, instr);
3013       break;
3014     case LBU:
3015       addr = rs + se_imm16;
3016       alu_out = ReadBU(addr);
3017       break;
3018     case LHU:
3019       addr = rs + se_imm16;
3020       alu_out = ReadHU(addr, instr);
3021       break;
3022     case LWR: {
3023       // al_offset is offset of the effective address within an aligned word.
3024       uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
3025       uint8_t byte_shift = kInt32AlignmentMask - al_offset;
3026       uint32_t mask = al_offset ? (~0 << (byte_shift + 1) * 8) : 0;
3027       addr = rs + se_imm16 - al_offset;
3028       alu_out = ReadW(addr, instr);
3029       alu_out = static_cast<uint32_t> (alu_out) >> al_offset * 8;
3030       alu_out |= rt & mask;
3031       break;
3032     }
3033     case SB:
3034       addr = rs + se_imm16;
3035       break;
3036     case SH:
3037       addr = rs + se_imm16;
3038       break;
3039     case SWL: {
3040       uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
3041       uint8_t byte_shift = kInt32AlignmentMask - al_offset;
3042       uint32_t mask = byte_shift ? (~0 << (al_offset + 1) * 8) : 0;
3043       addr = rs + se_imm16 - al_offset;
3044       mem_value = ReadW(addr, instr) & mask;
3045       mem_value |= static_cast<uint32_t>(rt) >> byte_shift * 8;
3046       break;
3047     }
3048     case SW:
3049     case SD:
3050       addr = rs + se_imm16;
3051       break;
3052     case SWR: {
3053       uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
3054       uint32_t mask = (1 << al_offset * 8) - 1;
3055       addr = rs + se_imm16 - al_offset;
3056       mem_value = ReadW(addr, instr);
3057       mem_value = (rt << al_offset * 8) | (mem_value & mask);
3058       break;
3059     }
3060     case LWC1:
3061       addr = rs + se_imm16;
3062       alu_out = ReadW(addr, instr);
3063       break;
3064     case LDC1:
3065       addr = rs + se_imm16;
3066       fp_out = ReadD(addr, instr);
3067       break;
3068     case SWC1:
3069     case SDC1:
3070       addr = rs + se_imm16;
3071       break;
3072     default:
3073       UNREACHABLE();
3074   }
3075
3076   // ---------- Raise exceptions triggered.
3077   SignalExceptions();
3078
3079   // ---------- Execution.
3080   switch (op) {
3081     // ------------- Branch instructions.
3082     case BEQ:
3083     case BNE:
3084     case BLEZ:
3085     case BGTZ:
3086       // Branch instructions common part.
3087       execute_branch_delay_instruction = true;
3088       // Set next_pc.
3089       if (do_branch) {
3090         next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
3091         if (instr->IsLinkingInstruction()) {
3092           set_register(31, current_pc + 2* Instruction::kInstrSize);
3093         }
3094       } else {
3095         next_pc = current_pc + 2 * Instruction::kInstrSize;
3096       }
3097       break;
3098     // ------------- Arithmetic instructions.
3099     case ADDI:
3100     case DADDI:
3101     case ADDIU:
3102     case DADDIU:
3103     case SLTI:
3104     case SLTIU:
3105     case ANDI:
3106     case ORI:
3107     case XORI:
3108     case LUI:
3109       set_register(rt_reg, alu_out);
3110       TraceRegWr(alu_out);
3111       break;
3112     // ------------- Memory instructions.
3113     case LB:
3114     case LH:
3115     case LWL:
3116     case LW:
3117     case LWU:
3118     case LD:
3119     case LBU:
3120     case LHU:
3121     case LWR:
3122       set_register(rt_reg, alu_out);
3123       break;
3124     case SB:
3125       WriteB(addr, static_cast<int8_t>(rt));
3126       break;
3127     case SH:
3128       WriteH(addr, static_cast<uint16_t>(rt), instr);
3129       break;
3130     case SWL:
3131       WriteW(addr, mem_value, instr);
3132       break;
3133     case SW:
3134       WriteW(addr, rt, instr);
3135       break;
3136     case SD:
3137       Write2W(addr, rt, instr);
3138       break;
3139     case SWR:
3140       WriteW(addr, mem_value, instr);
3141       break;
3142     case LWC1:
3143       set_fpu_register(ft_reg, kFPUInvalidResult);  // Trash upper 32 bits.
3144       set_fpu_register_word(ft_reg, static_cast<int32_t>(alu_out));
3145       break;
3146     case LDC1:
3147       set_fpu_register_double(ft_reg, fp_out);
3148       break;
3149     case SWC1:
3150       addr = rs + se_imm16;
3151       WriteW(addr, get_fpu_register(ft_reg), instr);
3152       break;
3153     case SDC1:
3154       addr = rs + se_imm16;
3155       WriteD(addr, get_fpu_register_double(ft_reg), instr);
3156       break;
3157     default:
3158       break;
3159   }
3160
3161
3162   if (execute_branch_delay_instruction) {
3163     // Execute branch delay slot
3164     // We don't check for end_sim_pc. First it should not be met as the current
3165     // pc is valid. Secondly a jump should always execute its branch delay slot.
3166     Instruction* branch_delay_instr =
3167       reinterpret_cast<Instruction*>(current_pc+Instruction::kInstrSize);
3168     BranchDelayInstructionDecode(branch_delay_instr);
3169   }
3170
3171   // If needed update pc after the branch delay execution.
3172   if (next_pc != bad_ra) {
3173     set_pc(next_pc);
3174   }
3175 }
3176
3177
3178 // Type 3: instructions using a 26 bytes immediate. (e.g. j, jal).
3179 void Simulator::DecodeTypeJump(Instruction* instr) {
3180   // Get current pc.
3181   int32_t current_pc = get_pc();
3182   // Get unchanged bits of pc.
3183   int32_t pc_high_bits = current_pc & 0xf0000000;
3184   // Next pc.
3185   int32_t next_pc = pc_high_bits | (instr->Imm26Value() << 2);
3186
3187   // Execute branch delay slot.
3188   // We don't check for end_sim_pc. First it should not be met as the current pc
3189   // is valid. Secondly a jump should always execute its branch delay slot.
3190   Instruction* branch_delay_instr =
3191       reinterpret_cast<Instruction*>(current_pc + Instruction::kInstrSize);
3192   BranchDelayInstructionDecode(branch_delay_instr);
3193
3194   // Update pc and ra if necessary.
3195   // Do this after the branch delay execution.
3196   if (instr->IsLinkingInstruction()) {
3197     set_register(31, current_pc + 2 * Instruction::kInstrSize);
3198   }
3199   set_pc(next_pc);
3200   pc_modified_ = true;
3201 }
3202
3203
3204 // Executes the current instruction.
3205 void Simulator::InstructionDecode(Instruction* instr) {
3206   if (v8::internal::FLAG_check_icache) {
3207     CheckICache(isolate_->simulator_i_cache(), instr);
3208   }
3209   pc_modified_ = false;
3210
3211   v8::internal::EmbeddedVector<char, 256> buffer;
3212
3213   if (::v8::internal::FLAG_trace_sim) {
3214     SNPrintF(trace_buf_, " ");
3215     disasm::NameConverter converter;
3216     disasm::Disassembler dasm(converter);
3217     // Use a reasonably large buffer.
3218     dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(instr));
3219   }
3220
3221   switch (instr->InstructionType()) {
3222     case Instruction::kRegisterType:
3223       DecodeTypeRegister(instr);
3224       break;
3225     case Instruction::kImmediateType:
3226       DecodeTypeImmediate(instr);
3227       break;
3228     case Instruction::kJumpType:
3229       DecodeTypeJump(instr);
3230       break;
3231     default:
3232       UNSUPPORTED();
3233   }
3234
3235   if (::v8::internal::FLAG_trace_sim) {
3236     PrintF("  0x%08lx  %-44s   %s\n", reinterpret_cast<intptr_t>(instr),
3237         buffer.start(), trace_buf_.start());
3238   }
3239
3240   if (!pc_modified_) {
3241     set_register(pc, reinterpret_cast<int64_t>(instr) +
3242                  Instruction::kInstrSize);
3243   }
3244 }
3245
3246
3247
3248 void Simulator::Execute() {
3249   // Get the PC to simulate. Cannot use the accessor here as we need the
3250   // raw PC value and not the one used as input to arithmetic instructions.
3251   int64_t program_counter = get_pc();
3252   if (::v8::internal::FLAG_stop_sim_at == 0) {
3253     // Fast version of the dispatch loop without checking whether the simulator
3254     // should be stopping at a particular executed instruction.
3255     while (program_counter != end_sim_pc) {
3256       Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
3257       icount_++;
3258       InstructionDecode(instr);
3259       program_counter = get_pc();
3260     }
3261   } else {
3262     // FLAG_stop_sim_at is at the non-default value. Stop in the debugger when
3263     // we reach the particular instuction count.
3264     while (program_counter != end_sim_pc) {
3265       Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
3266       icount_++;
3267       if (icount_ == static_cast<int64_t>(::v8::internal::FLAG_stop_sim_at)) {
3268         MipsDebugger dbg(this);
3269         dbg.Debug();
3270       } else {
3271         InstructionDecode(instr);
3272       }
3273       program_counter = get_pc();
3274     }
3275   }
3276 }
3277
3278
3279 void Simulator::CallInternal(byte* entry) {
3280   // Prepare to execute the code at entry.
3281   set_register(pc, reinterpret_cast<int64_t>(entry));
3282   // Put down marker for end of simulation. The simulator will stop simulation
3283   // when the PC reaches this value. By saving the "end simulation" value into
3284   // the LR the simulation stops when returning to this call point.
3285   set_register(ra, end_sim_pc);
3286
3287   // Remember the values of callee-saved registers.
3288   // The code below assumes that r9 is not used as sb (static base) in
3289   // simulator code and therefore is regarded as a callee-saved register.
3290   int64_t s0_val = get_register(s0);
3291   int64_t s1_val = get_register(s1);
3292   int64_t s2_val = get_register(s2);
3293   int64_t s3_val = get_register(s3);
3294   int64_t s4_val = get_register(s4);
3295   int64_t s5_val = get_register(s5);
3296   int64_t s6_val = get_register(s6);
3297   int64_t s7_val = get_register(s7);
3298   int64_t gp_val = get_register(gp);
3299   int64_t sp_val = get_register(sp);
3300   int64_t fp_val = get_register(fp);
3301
3302   // Set up the callee-saved registers with a known value. To be able to check
3303   // that they are preserved properly across JS execution.
3304   int64_t callee_saved_value = icount_;
3305   set_register(s0, callee_saved_value);
3306   set_register(s1, callee_saved_value);
3307   set_register(s2, callee_saved_value);
3308   set_register(s3, callee_saved_value);
3309   set_register(s4, callee_saved_value);
3310   set_register(s5, callee_saved_value);
3311   set_register(s6, callee_saved_value);
3312   set_register(s7, callee_saved_value);
3313   set_register(gp, callee_saved_value);
3314   set_register(fp, callee_saved_value);
3315
3316   // Start the simulation.
3317   Execute();
3318
3319   // Check that the callee-saved registers have been preserved.
3320   CHECK_EQ(callee_saved_value, get_register(s0));
3321   CHECK_EQ(callee_saved_value, get_register(s1));
3322   CHECK_EQ(callee_saved_value, get_register(s2));
3323   CHECK_EQ(callee_saved_value, get_register(s3));
3324   CHECK_EQ(callee_saved_value, get_register(s4));
3325   CHECK_EQ(callee_saved_value, get_register(s5));
3326   CHECK_EQ(callee_saved_value, get_register(s6));
3327   CHECK_EQ(callee_saved_value, get_register(s7));
3328   CHECK_EQ(callee_saved_value, get_register(gp));
3329   CHECK_EQ(callee_saved_value, get_register(fp));
3330
3331   // Restore callee-saved registers with the original value.
3332   set_register(s0, s0_val);
3333   set_register(s1, s1_val);
3334   set_register(s2, s2_val);
3335   set_register(s3, s3_val);
3336   set_register(s4, s4_val);
3337   set_register(s5, s5_val);
3338   set_register(s6, s6_val);
3339   set_register(s7, s7_val);
3340   set_register(gp, gp_val);
3341   set_register(sp, sp_val);
3342   set_register(fp, fp_val);
3343 }
3344
3345
3346 int64_t Simulator::Call(byte* entry, int argument_count, ...) {
3347   const int kRegisterPassedArguments = (kMipsAbi == kN64) ? 8 : 4;
3348   va_list parameters;
3349   va_start(parameters, argument_count);
3350   // Set up arguments.
3351
3352   // First four arguments passed in registers in both ABI's.
3353   DCHECK(argument_count >= 4);
3354   set_register(a0, va_arg(parameters, int64_t));
3355   set_register(a1, va_arg(parameters, int64_t));
3356   set_register(a2, va_arg(parameters, int64_t));
3357   set_register(a3, va_arg(parameters, int64_t));
3358
3359   if (kMipsAbi == kN64) {
3360     // Up to eight arguments passed in registers in N64 ABI.
3361     // TODO(plind): N64 ABI calls these regs a4 - a7. Clarify this.
3362     if (argument_count >= 5) set_register(a4, va_arg(parameters, int64_t));
3363     if (argument_count >= 6) set_register(a5, va_arg(parameters, int64_t));
3364     if (argument_count >= 7) set_register(a6, va_arg(parameters, int64_t));
3365     if (argument_count >= 8) set_register(a7, va_arg(parameters, int64_t));
3366   }
3367
3368   // Remaining arguments passed on stack.
3369   int64_t original_stack = get_register(sp);
3370   // Compute position of stack on entry to generated code.
3371   int stack_args_count = (argument_count > kRegisterPassedArguments) ?
3372                          (argument_count - kRegisterPassedArguments) : 0;
3373   int stack_args_size = stack_args_count * sizeof(int64_t) + kCArgsSlotsSize;
3374   int64_t entry_stack = original_stack - stack_args_size;
3375
3376   if (base::OS::ActivationFrameAlignment() != 0) {
3377     entry_stack &= -base::OS::ActivationFrameAlignment();
3378   }
3379   // Store remaining arguments on stack, from low to high memory.
3380   intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack);
3381   for (int i = kRegisterPassedArguments; i < argument_count; i++) {
3382     int stack_index = i - kRegisterPassedArguments + kCArgSlotCount;
3383     stack_argument[stack_index] = va_arg(parameters, int64_t);
3384   }
3385   va_end(parameters);
3386   set_register(sp, entry_stack);
3387
3388   CallInternal(entry);
3389
3390   // Pop stack passed arguments.
3391   CHECK_EQ(entry_stack, get_register(sp));
3392   set_register(sp, original_stack);
3393
3394   int64_t result = get_register(v0);
3395   return result;
3396 }
3397
3398
3399 double Simulator::CallFP(byte* entry, double d0, double d1) {
3400   if (!IsMipsSoftFloatABI) {
3401     const FPURegister fparg2 = (kMipsAbi == kN64) ? f13 : f14;
3402     set_fpu_register_double(f12, d0);
3403     set_fpu_register_double(fparg2, d1);
3404   } else {
3405     int buffer[2];
3406     DCHECK(sizeof(buffer[0]) * 2 == sizeof(d0));
3407     memcpy(buffer, &d0, sizeof(d0));
3408     set_dw_register(a0, buffer);
3409     memcpy(buffer, &d1, sizeof(d1));
3410     set_dw_register(a2, buffer);
3411   }
3412   CallInternal(entry);
3413   if (!IsMipsSoftFloatABI) {
3414     return get_fpu_register_double(f0);
3415   } else {
3416     return get_double_from_register_pair(v0);
3417   }
3418 }
3419
3420
3421 uintptr_t Simulator::PushAddress(uintptr_t address) {
3422   int64_t new_sp = get_register(sp) - sizeof(uintptr_t);
3423   uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp);
3424   *stack_slot = address;
3425   set_register(sp, new_sp);
3426   return new_sp;
3427 }
3428
3429
3430 uintptr_t Simulator::PopAddress() {
3431   int64_t current_sp = get_register(sp);
3432   uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp);
3433   uintptr_t address = *stack_slot;
3434   set_register(sp, current_sp + sizeof(uintptr_t));
3435   return address;
3436 }
3437
3438
3439 #undef UNSUPPORTED
3440
3441 } }  // namespace v8::internal
3442
3443 #endif  // USE_SIMULATOR
3444
3445 #endif  // V8_TARGET_ARCH_MIPS64