sh2: sync sh2 core with latest mame
[picodrive.git] / cpu / sh2 / compiler.c
1 /*
2  * SH2 recompiler
3  * (C) notaz, 2009,2010
4  *
5  * This work is licensed under the terms of MAME license.
6  * See COPYING file in the top-level directory.
7  *
8  * notes:
9  * - tcache, block descriptor, link buffer overflows result in sh2_translate()
10  *   failure, followed by full tcache invalidation for that region
11  * - jumps between blocks are tracked for SMC handling (in block_links[]),
12  *   except jumps between different tcaches
13  * - non-main block entries are called subblocks, as they have same tracking
14  *   structures that main blocks have.
15  *
16  * implemented:
17  * - static register allocation
18  * - remaining register caching and tracking in temporaries
19  * - block-local branch linking
20  * - block linking (except between tcaches)
21  * - some constant propagation
22  *
23  * TODO:
24  * - better constant propagation
25  * - stack caching?
26  * - bug fixing
27  */
28 #include <stddef.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <assert.h>
32
33 #include "../../pico/pico_int.h"
34 #include "sh2.h"
35 #include "compiler.h"
36 #include "../drc/cmn.h"
37 #include "../debug.h"
38
39 // features
40 #define PROPAGATE_CONSTANTS     1
41 #define LINK_BRANCHES           1
42
43 // limits (per block)
44 #define BLOCK_CYCLE_LIMIT       100
45 #define MAX_BLOCK_SIZE          (BLOCK_CYCLE_LIMIT * 6 * 6)
46
47 // max literal offset from the block end
48 #define MAX_LITERAL_OFFSET      32*2
49 #define MAX_LITERALS            (BLOCK_CYCLE_LIMIT / 4)
50 #define MAX_LOCAL_BRANCHES      32
51
52 // debug stuff {
53 #ifndef DRC_DEBUG
54 #define DRC_DEBUG 0
55 #endif
56
57 #if DRC_DEBUG
58 #define dbg(l,...) { \
59   if ((l) & DRC_DEBUG) \
60     elprintf(EL_STATUS, ##__VA_ARGS__); \
61 }
62
63 #include "mame/sh2dasm.h"
64 #include <platform/libpicofe/linux/host_dasm.h>
65 static int insns_compiled, hash_collisions, host_insn_count;
66 #define COUNT_OP \
67         host_insn_count++
68 #else // !DRC_DEBUG
69 #define COUNT_OP
70 #define dbg(...)
71 #endif
72
73 #if (DRC_DEBUG & 4)
74 static u8 *tcache_dsm_ptrs[3];
75 static char sh2dasm_buff[64];
76 #define do_host_disasm(tcid) \
77   host_dasm(tcache_dsm_ptrs[tcid], tcache_ptr - tcache_dsm_ptrs[tcid]); \
78   tcache_dsm_ptrs[tcid] = tcache_ptr
79 #else
80 #define do_host_disasm(x)
81 #endif
82
83 #if (DRC_DEBUG & 8) || defined(PDB)
84 static void REGPARM(3) *sh2_drc_log_entry(void *block, SH2 *sh2, u32 sr)
85 {
86   if (block != NULL) {
87     dbg(8, "= %csh2 enter %08x %p, c=%d", sh2->is_slave ? 's' : 'm',
88       sh2->pc, block, (signed int)sr >> 12);
89     pdb_step(sh2, sh2->pc);
90   }
91   return block;
92 }
93 #endif
94 // } debug
95
96 #define TCACHE_BUFFERS 3
97
98 // we have 3 translation cache buffers, split from one drc/cmn buffer.
99 // BIOS shares tcache with data array because it's only used for init
100 // and can be discarded early
101 // XXX: need to tune sizes
102 static const int tcache_sizes[TCACHE_BUFFERS] = {
103   DRC_TCACHE_SIZE * 6 / 8, // ROM, DRAM
104   DRC_TCACHE_SIZE / 8, // BIOS, data array in master sh2
105   DRC_TCACHE_SIZE / 8, // ... slave
106 };
107
108 static u8 *tcache_bases[TCACHE_BUFFERS];
109 static u8 *tcache_ptrs[TCACHE_BUFFERS];
110
111 // ptr for code emiters
112 static u8 *tcache_ptr;
113
114 typedef struct block_desc_ {
115   u32 addr;                  // SH2 PC address
116   void *tcache_ptr;          // translated block for above PC
117   struct block_desc_ *next;  // next block with the same PC hash
118 #if (DRC_DEBUG & 2)
119   int refcount;
120 #endif
121 } block_desc;
122
123 typedef struct block_link_ {
124   u32 target_pc;
125   void *jump;     // insn address
126 //  struct block_link_ *next;
127 } block_link;
128
129 static const int block_max_counts[TCACHE_BUFFERS] = {
130   4*1024,
131   256,
132   256,
133 };
134 static block_desc *block_tables[TCACHE_BUFFERS];
135 static block_link *block_links[TCACHE_BUFFERS]; 
136 static int block_counts[TCACHE_BUFFERS];
137 static int block_link_counts[TCACHE_BUFFERS];
138
139 // host register tracking
140 enum {
141   HR_FREE,
142   HR_CACHED, // 'val' has sh2_reg_e
143 //  HR_CONST,  // 'val' has a constant
144   HR_TEMP,   // reg used for temp storage
145 };
146
147 enum {
148   HRF_DIRTY  = 1 << 0, // reg has "dirty" value to be written to ctx
149   HRF_LOCKED = 1 << 1, // HR_CACHED can't be evicted
150 };
151
152 typedef struct {
153   u32 hreg:5;   // "host" reg
154   u32 greg:5;   // "guest" reg
155   u32 type:3;
156   u32 flags:3;
157   u32 stamp:16; // kind of a timestamp
158 } temp_reg_t;
159
160 // note: reg_temp[] must have at least the amount of
161 // registers used by handlers in worst case (currently 4)
162 #ifdef __arm__
163 #include "../drc/emit_arm.c"
164
165 static const int reg_map_g2h[] = {
166    4,  5,  6,  7,
167    8, -1, -1, -1,
168   -1, -1, -1, -1,
169   -1, -1, -1,  9, // r12 .. sp
170   -1, -1, -1, 10, // SHR_PC,  SHR_PPC, SHR_PR,   SHR_SR,
171   -1, -1, -1, -1, // SHR_GBR, SHR_VBR, SHR_MACH, SHR_MACL,
172 };
173
174 static temp_reg_t reg_temp[] = {
175   {  0, },
176   {  1, },
177   { 12, },
178   { 14, },
179   {  2, },
180   {  3, },
181 };
182
183 #elif defined(__i386__)
184 #include "../drc/emit_x86.c"
185
186 static const int reg_map_g2h[] = {
187   xSI,-1, -1, -1,
188   -1, -1, -1, -1,
189   -1, -1, -1, -1,
190   -1, -1, -1, -1,
191   -1, -1, -1, xDI,
192   -1, -1, -1, -1,
193 };
194
195 // ax, cx, dx are usually temporaries by convention
196 static temp_reg_t reg_temp[] = {
197   { xAX, },
198   { xBX, },
199   { xCX, },
200   { xDX, },
201 };
202
203 #else
204 #error unsupported arch
205 #endif
206
207 #define T       0x00000001
208 #define S       0x00000002
209 #define I       0x000000f0
210 #define Q       0x00000100
211 #define M       0x00000200
212 #define T_save  0x00000800
213
214 #define I_SHIFT 4
215 #define Q_SHIFT 8
216 #define M_SHIFT 9
217
218 // ROM hash table
219 #define MAX_HASH_ENTRIES 1024
220 #define HASH_MASK (MAX_HASH_ENTRIES - 1)
221 static void **hash_table;
222
223 #define HASH_FUNC(hash_tab, addr) \
224   ((block_desc **)(hash_tab))[(addr) & HASH_MASK]
225
226 static void REGPARM(1) (*sh2_drc_entry)(SH2 *sh2);
227 static void            (*sh2_drc_dispatcher)(void);
228 static void            (*sh2_drc_exit)(void);
229 static void            (*sh2_drc_test_irq)(void);
230
231 static u32  REGPARM(2) (*sh2_drc_read8)(u32 a, SH2 *sh2);
232 static u32  REGPARM(2) (*sh2_drc_read16)(u32 a, SH2 *sh2);
233 static u32  REGPARM(2) (*sh2_drc_read32)(u32 a, SH2 *sh2);
234 static void REGPARM(2) (*sh2_drc_write8)(u32 a, u32 d);
235 static void REGPARM(2) (*sh2_drc_write8_slot)(u32 a, u32 d);
236 static void REGPARM(2) (*sh2_drc_write16)(u32 a, u32 d);
237 static void REGPARM(2) (*sh2_drc_write16_slot)(u32 a, u32 d);
238 static int  REGPARM(3) (*sh2_drc_write32)(u32 a, u32 d, SH2 *sh2);
239
240 extern void REGPARM(2) sh2_do_op(SH2 *sh2, int opcode);
241
242 // address space stuff
243 static void *dr_get_pc_base(u32 pc, int is_slave)
244 {
245   void *ret = NULL;
246   u32 mask = 0;
247
248   if ((pc & ~0x7ff) == 0) {
249     // BIOS
250     ret = is_slave ? Pico32xMem->sh2_rom_s : Pico32xMem->sh2_rom_m;
251     mask = 0x7ff;
252   }
253   else if ((pc & 0xfffff000) == 0xc0000000) {
254     // data array
255     ret = Pico32xMem->data_array[is_slave];
256     mask = 0xfff;
257   }
258   else if ((pc & 0xc6000000) == 0x06000000) {
259     // SDRAM
260     ret = Pico32xMem->sdram;
261     mask = 0x03ffff;
262   }
263   else if ((pc & 0xc6000000) == 0x02000000) {
264     // ROM
265     ret = Pico.rom;
266     mask = 0x3fffff;
267   }
268
269   if (ret == NULL)
270     return (void *)-1; // NULL is valid value
271
272   return (char *)ret - (pc & ~mask);
273 }
274
275 static int dr_ctx_get_mem_ptr(u32 a, u32 *mask)
276 {
277   int poffs = -1;
278
279   if ((a & ~0x7ff) == 0) {
280     // BIOS
281     poffs = offsetof(SH2, p_bios);
282     *mask = 0x7ff;
283   }
284   else if ((a & 0xfffff000) == 0xc0000000) {
285     // data array
286     poffs = offsetof(SH2, p_da);
287     *mask = 0xfff;
288   }
289   else if ((a & 0xc6000000) == 0x06000000) {
290     // SDRAM
291     poffs = offsetof(SH2, p_sdram);
292     *mask = 0x03ffff;
293   }
294   else if ((a & 0xc6000000) == 0x02000000) {
295     // ROM
296     poffs = offsetof(SH2, p_rom);
297     *mask = 0x3fffff;
298   }
299
300   return poffs;
301 }
302
303 static block_desc *dr_get_bd(u32 pc, int is_slave, int *tcache_id)
304 {
305   *tcache_id = 0;
306
307   // we have full block id tables for data_array and RAM
308   // BIOS goes to data_array table too
309   if ((pc & 0xe0000000) == 0xc0000000 || (pc & ~0xfff) == 0) {
310     int blkid = Pico32xMem->drcblk_da[is_slave][(pc & 0xfff) >> SH2_DRCBLK_DA_SHIFT];
311     *tcache_id = 1 + is_slave;
312     if (blkid & 1)
313       return &block_tables[*tcache_id][blkid >> 1];
314   }
315   // RAM
316   else if ((pc & 0xc6000000) == 0x06000000) {
317     int blkid = Pico32xMem->drcblk_ram[(pc & 0x3ffff) >> SH2_DRCBLK_RAM_SHIFT];
318     if (blkid & 1)
319       return &block_tables[0][blkid >> 1];
320   }
321   // ROM
322   else if ((pc & 0xc6000000) == 0x02000000) {
323     block_desc *bd = HASH_FUNC(hash_table, pc);
324
325     for (; bd != NULL; bd = bd->next)
326       if (bd->addr == pc)
327         return bd;
328   }
329
330   return NULL;
331 }
332
333 // ---------------------------------------------------------------
334
335 // block management
336 static void REGPARM(1) flush_tcache(int tcid)
337 {
338   dbg(1, "tcache #%d flush! (%d/%d, bds %d/%d)", tcid,
339     tcache_ptrs[tcid] - tcache_bases[tcid], tcache_sizes[tcid],
340     block_counts[tcid], block_max_counts[tcid]);
341
342   block_counts[tcid] = 0;
343   block_link_counts[tcid] = 0;
344   tcache_ptrs[tcid] = tcache_bases[tcid];
345   if (tcid == 0) { // ROM, RAM
346     memset(hash_table, 0, sizeof(hash_table[0]) * MAX_HASH_ENTRIES);
347     memset(Pico32xMem->drcblk_ram, 0, sizeof(Pico32xMem->drcblk_ram));
348   }
349   else
350     memset(Pico32xMem->drcblk_da[tcid - 1], 0, sizeof(Pico32xMem->drcblk_da[0]));
351 #if (DRC_DEBUG & 4)
352   tcache_dsm_ptrs[tcid] = tcache_bases[tcid];
353 #endif
354 }
355
356 #if LINK_BRANCHES
357 // add block links (tracked branches)
358 static int dr_add_block_link(u32 target_pc, void *jump, int tcache_id)
359 {
360   block_link *bl = block_links[tcache_id];
361   int cnt = block_link_counts[tcache_id];
362
363   if (cnt >= block_max_counts[tcache_id] * 2) {
364     dbg(1, "bl overflow for tcache %d\n", tcache_id);
365     return -1;
366   }
367
368   bl[cnt].target_pc = target_pc;
369   bl[cnt].jump = jump;
370   block_link_counts[tcache_id]++;
371
372   return 0;
373 }
374 #endif
375
376 static block_desc *dr_add_block(u32 addr, int is_slave, int *blk_id)
377 {
378   block_desc *bd;
379   int tcache_id;
380   int *bcount;
381
382   bd = dr_get_bd(addr, is_slave, &tcache_id);
383   if (bd != NULL) {
384     dbg(2, "block override for %08x", addr);
385     bd->tcache_ptr = tcache_ptr;
386     *blk_id = bd - block_tables[tcache_id];
387     return bd;
388   }
389
390   bcount = &block_counts[tcache_id];
391   if (*bcount >= block_max_counts[tcache_id]) {
392     dbg(1, "bd overflow for tcache %d", tcache_id);
393     return NULL;
394   }
395   if (*bcount == 0)
396     (*bcount)++; // not using descriptor 0
397
398   bd = &block_tables[tcache_id][*bcount];
399   bd->addr = addr;
400   bd->tcache_ptr = tcache_ptr;
401   *blk_id = *bcount;
402   (*bcount)++;
403
404   if ((addr & 0xc6000000) == 0x02000000) { // ROM
405     bd->next = HASH_FUNC(hash_table, addr);
406     HASH_FUNC(hash_table, addr) = bd;
407 #if (DRC_DEBUG & 2)
408     if (bd->next != NULL) {
409       printf(" hash collision with %08x\n", bd->next->addr);
410       hash_collisions++;
411     }
412 #endif
413   }
414
415   return bd;
416 }
417
418 static void REGPARM(3) *dr_lookup_block(u32 pc, int is_slave, int *tcache_id)
419 {
420   block_desc *bd = NULL;
421   void *block = NULL;
422
423   bd = dr_get_bd(pc, is_slave, tcache_id);
424   if (bd != NULL)
425     block = bd->tcache_ptr;
426
427 #if (DRC_DEBUG & 2)
428   if (bd != NULL)
429     bd->refcount++;
430 #endif
431   return block;
432 }
433
434 static void *dr_failure(void)
435 {
436   lprintf("recompilation failed\n");
437   exit(1);
438 }
439
440 static void *dr_prepare_ext_branch(u32 pc, SH2 *sh2, int tcache_id)
441 {
442 #if LINK_BRANCHES
443   int target_tcache_id;
444   void *target;
445   int ret;
446
447   target = dr_lookup_block(pc, sh2->is_slave, &target_tcache_id);
448   if (target_tcache_id == tcache_id) {
449     // allow linking blocks only from local cache
450     ret = dr_add_block_link(pc, tcache_ptr, tcache_id);
451     if (ret < 0)
452       return NULL;
453   }
454   if (target == NULL || target_tcache_id != tcache_id)
455     target = sh2_drc_dispatcher;
456
457   return target;
458 #else
459   return sh2_drc_dispatcher;
460 #endif
461 }
462
463 static void dr_link_blocks(void *target, u32 pc, int tcache_id)
464 {
465 #if LINK_BRANCHES
466   block_link *bl = block_links[tcache_id];
467   int cnt = block_link_counts[tcache_id];
468   int i;
469
470   for (i = 0; i < cnt; i++) {
471     if (bl[i].target_pc == pc) {
472       dbg(2, "- link from %p", bl[i].jump);
473       emith_jump_patch(bl[i].jump, target);
474       // XXX: sync ARM caches (old jump should be fine)?
475     }
476   }
477 #endif
478 }
479
480 #define ADD_TO_ARRAY(array, count, item, failcode) \
481   array[count++] = item; \
482   if (count >= ARRAY_SIZE(array)) { \
483     dbg(1, "warning: " #array " overflow"); \
484     failcode; \
485   }
486
487 static int find_in_array(u32 *array, size_t size, u32 what)
488 {
489   size_t i;
490   for (i = 0; i < size; i++)
491     if (what == array[i])
492       return i;
493
494   return -1;
495 }
496
497 // ---------------------------------------------------------------
498
499 // register cache / constant propagation stuff
500 typedef enum {
501   RC_GR_READ,
502   RC_GR_WRITE,
503   RC_GR_RMW,
504 } rc_gr_mode;
505
506 static int rcache_get_reg_(sh2_reg_e r, rc_gr_mode mode, int do_locking);
507
508 // guest regs with constants
509 static u32 dr_gcregs[24];
510 // a mask of constant/dirty regs
511 static u32 dr_gcregs_mask;
512 static u32 dr_gcregs_dirty;
513
514 #if PROPAGATE_CONSTANTS
515 static void gconst_new(sh2_reg_e r, u32 val)
516 {
517   int i;
518
519   dr_gcregs_mask  |= 1 << r;
520   dr_gcregs_dirty |= 1 << r;
521   dr_gcregs[r] = val;
522
523   // throw away old r that we might have cached
524   for (i = ARRAY_SIZE(reg_temp) - 1; i >= 0; i--) {
525     if ((reg_temp[i].type == HR_CACHED) &&
526          reg_temp[i].greg == r) {
527       reg_temp[i].type = HR_FREE;
528       reg_temp[i].flags = 0;
529     }
530   }
531 }
532 #endif
533
534 static int gconst_get(sh2_reg_e r, u32 *val)
535 {
536   if (dr_gcregs_mask & (1 << r)) {
537     *val = dr_gcregs[r];
538     return 1;
539   }
540   return 0;
541 }
542
543 static int gconst_check(sh2_reg_e r)
544 {
545   if ((dr_gcregs_mask | dr_gcregs_dirty) & (1 << r))
546     return 1;
547   return 0;
548 }
549
550 // update hr if dirty, else do nothing
551 static int gconst_try_read(int hr, sh2_reg_e r)
552 {
553   if (dr_gcregs_dirty & (1 << r)) {
554     emith_move_r_imm(hr, dr_gcregs[r]);
555     dr_gcregs_dirty &= ~(1 << r);
556     return 1;
557   }
558   return 0;
559 }
560
561 static void gconst_check_evict(sh2_reg_e r)
562 {
563   if (dr_gcregs_mask & (1 << r))
564     // no longer cached in reg, make dirty again
565     dr_gcregs_dirty |= 1 << r;
566 }
567
568 static void gconst_kill(sh2_reg_e r)
569 {
570   dr_gcregs_mask &= ~(1 << r);
571   dr_gcregs_dirty &= ~(1 << r);
572 }
573
574 static void gconst_clean(void)
575 {
576   int i;
577
578   for (i = 0; i < ARRAY_SIZE(dr_gcregs); i++)
579     if (dr_gcregs_dirty & (1 << i)) {
580       // using RC_GR_READ here: it will call gconst_try_read,
581       // cache the reg and mark it dirty.
582       rcache_get_reg_(i, RC_GR_READ, 0);
583     }
584 }
585
586 static void gconst_invalidate(void)
587 {
588   dr_gcregs_mask = dr_gcregs_dirty = 0;
589 }
590
591 static u16 rcache_counter;
592
593 static temp_reg_t *rcache_evict(void)
594 {
595   // evict reg with oldest stamp
596   int i, oldest = -1;
597   u16 min_stamp = (u16)-1;
598
599   for (i = 0; i < ARRAY_SIZE(reg_temp); i++) {
600     if (reg_temp[i].type == HR_CACHED && !(reg_temp[i].flags & HRF_LOCKED) &&
601         reg_temp[i].stamp <= min_stamp) {
602       min_stamp = reg_temp[i].stamp;
603       oldest = i;
604     }
605   }
606
607   if (oldest == -1) {
608     printf("no registers to evict, aborting\n");
609     exit(1);
610   }
611
612   i = oldest;
613   if (reg_temp[i].type == HR_CACHED) {
614     if (reg_temp[i].flags & HRF_DIRTY)
615       // writeback
616       emith_ctx_write(reg_temp[i].hreg, reg_temp[i].greg * 4);
617     gconst_check_evict(reg_temp[i].greg);
618   }
619
620   reg_temp[i].type = HR_FREE;
621   reg_temp[i].flags = 0;
622   return &reg_temp[i];
623 }
624
625 static int get_reg_static(sh2_reg_e r, rc_gr_mode mode)
626 {
627   int i = reg_map_g2h[r];
628   if (i != -1) {
629     if (mode != RC_GR_WRITE)
630       gconst_try_read(i, r);
631   }
632   return i;
633 }
634
635 // note: must not be called when doing conditional code
636 static int rcache_get_reg_(sh2_reg_e r, rc_gr_mode mode, int do_locking)
637 {
638   temp_reg_t *tr;
639   int i, ret;
640
641   // maybe statically mapped?
642   ret = get_reg_static(r, mode);
643   if (ret != -1)
644     goto end;
645
646   rcache_counter++;
647
648   // maybe already cached?
649   // if so, prefer against gconst (they must be in sync)
650   for (i = ARRAY_SIZE(reg_temp) - 1; i >= 0; i--) {
651     if (reg_temp[i].type == HR_CACHED && reg_temp[i].greg == r) {
652       reg_temp[i].stamp = rcache_counter;
653       if (mode != RC_GR_READ)
654         reg_temp[i].flags |= HRF_DIRTY;
655       ret = reg_temp[i].hreg;
656       goto end;
657     }
658   }
659
660   // use any free reg
661   for (i = ARRAY_SIZE(reg_temp) - 1; i >= 0; i--) {
662     if (reg_temp[i].type == HR_FREE) {
663       tr = &reg_temp[i];
664       goto do_alloc;
665     }
666   }
667
668   tr = rcache_evict();
669
670 do_alloc:
671   tr->type = HR_CACHED;
672   if (do_locking)
673     tr->flags |= HRF_LOCKED;
674   if (mode != RC_GR_READ)
675     tr->flags |= HRF_DIRTY;
676   tr->greg = r;
677   tr->stamp = rcache_counter;
678   ret = tr->hreg;
679
680   if (mode != RC_GR_WRITE) {
681     if (gconst_check(r)) {
682       if (gconst_try_read(ret, r))
683         tr->flags |= HRF_DIRTY;
684     }
685     else
686       emith_ctx_read(tr->hreg, r * 4);
687   }
688
689 end:
690   if (mode != RC_GR_READ)
691     gconst_kill(r);
692
693   return ret;
694 }
695
696 static int rcache_get_reg(sh2_reg_e r, rc_gr_mode mode)
697 {
698   return rcache_get_reg_(r, mode, 1);
699 }
700
701 static int rcache_get_tmp(void)
702 {
703   temp_reg_t *tr;
704   int i;
705
706   for (i = 0; i < ARRAY_SIZE(reg_temp); i++)
707     if (reg_temp[i].type == HR_FREE) {
708       tr = &reg_temp[i];
709       goto do_alloc;
710     }
711
712   tr = rcache_evict();
713
714 do_alloc:
715   tr->type = HR_TEMP;
716   return tr->hreg;
717 }
718
719 static int rcache_get_arg_id(int arg)
720 {
721   int i, r = 0;
722   host_arg2reg(r, arg);
723
724   for (i = 0; i < ARRAY_SIZE(reg_temp); i++)
725     if (reg_temp[i].hreg == r)
726       break;
727
728   if (i == ARRAY_SIZE(reg_temp)) // can't happen
729     exit(1);
730
731   if (reg_temp[i].type == HR_CACHED) {
732     // writeback
733     if (reg_temp[i].flags & HRF_DIRTY)
734       emith_ctx_write(reg_temp[i].hreg, reg_temp[i].greg * 4);
735     gconst_check_evict(reg_temp[i].greg);
736   }
737   else if (reg_temp[i].type == HR_TEMP) {
738     printf("arg %d reg %d already used, aborting\n", arg, r);
739     exit(1);
740   }
741
742   reg_temp[i].type = HR_FREE;
743   reg_temp[i].flags = 0;
744
745   return i;
746 }
747
748 // get a reg to be used as function arg
749 static int rcache_get_tmp_arg(int arg)
750 {
751   int id = rcache_get_arg_id(arg);
752   reg_temp[id].type = HR_TEMP;
753
754   return reg_temp[id].hreg;
755 }
756
757 // same but caches a reg. RC_GR_READ only.
758 static int rcache_get_reg_arg(int arg, sh2_reg_e r)
759 {
760   int i, srcr, dstr, dstid;
761   int dirty = 0, src_dirty = 0;
762
763   dstid = rcache_get_arg_id(arg);
764   dstr = reg_temp[dstid].hreg;
765
766   // maybe already statically mapped?
767   srcr = get_reg_static(r, RC_GR_READ);
768   if (srcr != -1)
769     goto do_cache;
770
771   // maybe already cached?
772   for (i = ARRAY_SIZE(reg_temp) - 1; i >= 0; i--) {
773     if ((reg_temp[i].type == HR_CACHED) &&
774          reg_temp[i].greg == r)
775     {
776       srcr = reg_temp[i].hreg;
777       if (reg_temp[i].flags & HRF_DIRTY)
778         src_dirty = 1;
779       goto do_cache;
780     }
781   }
782
783   // must read
784   srcr = dstr;
785   if (gconst_check(r)) {
786     if (gconst_try_read(srcr, r))
787       dirty = 1;
788   }
789   else
790     emith_ctx_read(srcr, r * 4);
791
792 do_cache:
793   if (dstr != srcr)
794     emith_move_r_r(dstr, srcr);
795 #if 1
796   else
797     dirty |= src_dirty;
798
799   if (dirty)
800     // must clean, callers might want to modify the arg before call
801     emith_ctx_write(dstr, r * 4);
802 #else
803   if (dirty)
804     reg_temp[dstid].flags |= HRF_DIRTY;
805 #endif
806
807   reg_temp[dstid].stamp = ++rcache_counter;
808   reg_temp[dstid].type = HR_CACHED;
809   reg_temp[dstid].greg = r;
810   reg_temp[dstid].flags |= HRF_LOCKED;
811   return dstr;
812 }
813
814 static void rcache_free_tmp(int hr)
815 {
816   int i;
817   for (i = 0; i < ARRAY_SIZE(reg_temp); i++)
818     if (reg_temp[i].hreg == hr)
819       break;
820
821   if (i == ARRAY_SIZE(reg_temp) || reg_temp[i].type != HR_TEMP) {
822     printf("rcache_free_tmp fail: #%i hr %d, type %d\n", i, hr, reg_temp[i].type);
823     return;
824   }
825
826   reg_temp[i].type = HR_FREE;
827   reg_temp[i].flags = 0;
828 }
829
830 static void rcache_unlock(int hr)
831 {
832   int i;
833   for (i = 0; i < ARRAY_SIZE(reg_temp); i++)
834     if (reg_temp[i].type == HR_CACHED && reg_temp[i].hreg == hr)
835       reg_temp[i].flags &= ~HRF_LOCKED;
836 }
837
838 static void rcache_unlock_all(void)
839 {
840   int i;
841   for (i = 0; i < ARRAY_SIZE(reg_temp); i++)
842     reg_temp[i].flags &= ~HRF_LOCKED;
843 }
844
845 static void rcache_clean(void)
846 {
847   int i;
848   gconst_clean();
849
850   for (i = 0; i < ARRAY_SIZE(reg_temp); i++)
851     if (reg_temp[i].type == HR_CACHED && (reg_temp[i].flags & HRF_DIRTY)) {
852       // writeback
853       emith_ctx_write(reg_temp[i].hreg, reg_temp[i].greg * 4);
854       reg_temp[i].flags &= ~HRF_DIRTY;
855     }
856 }
857
858 static void rcache_invalidate(void)
859 {
860   int i;
861   for (i = 0; i < ARRAY_SIZE(reg_temp); i++) {
862     reg_temp[i].type = HR_FREE;
863     reg_temp[i].flags = 0;
864   }
865   rcache_counter = 0;
866
867   gconst_invalidate();
868 }
869
870 static void rcache_flush(void)
871 {
872   rcache_clean();
873   rcache_invalidate();
874 }
875
876 // ---------------------------------------------------------------
877
878 static int emit_get_rbase_and_offs(u32 a, u32 *offs)
879 {
880   u32 mask = 0;
881   int poffs;
882   int hr;
883
884   poffs = dr_ctx_get_mem_ptr(a, &mask);
885   if (poffs == -1)
886     return -1;
887
888   // XXX: could use some related reg
889   hr = rcache_get_tmp();
890   emith_ctx_read(hr, poffs);
891   emith_add_r_imm(hr, a & mask & ~0xff);
892   *offs = a & 0xff; // XXX: ARM oriented..
893   return hr;
894 }
895
896 static void emit_move_r_imm32(sh2_reg_e dst, u32 imm)
897 {
898 #if PROPAGATE_CONSTANTS
899   gconst_new(dst, imm);
900 #else
901   int hr = rcache_get_reg(dst, RC_GR_WRITE);
902   emith_move_r_imm(hr, imm);
903 #endif
904 }
905
906 static void emit_move_r_r(sh2_reg_e dst, sh2_reg_e src)
907 {
908   int hr_d = rcache_get_reg(dst, RC_GR_WRITE);
909   int hr_s = rcache_get_reg(src, RC_GR_READ);
910
911   emith_move_r_r(hr_d, hr_s);
912 }
913
914 // T must be clear, and comparison done just before this
915 static void emit_or_t_if_eq(int srr)
916 {
917   EMITH_SJMP_START(DCOND_NE);
918   emith_or_r_imm_c(DCOND_EQ, srr, T);
919   EMITH_SJMP_END(DCOND_NE);
920 }
921
922 // arguments must be ready
923 // reg cache must be clean before call
924 static int emit_memhandler_read_(int size, int ram_check)
925 {
926   int arg0, arg1;
927   host_arg2reg(arg0, 0);
928
929   rcache_clean();
930
931   // must writeback cycles for poll detection stuff
932   // FIXME: rm
933   if (reg_map_g2h[SHR_SR] != -1)
934     emith_ctx_write(reg_map_g2h[SHR_SR], SHR_SR * 4);
935
936   arg1 = rcache_get_tmp_arg(1);
937   emith_move_r_r(arg1, CONTEXT_REG);
938
939 #ifndef PDB_NET
940   if (ram_check && Pico.rom == (void *)0x02000000 && Pico32xMem->sdram == (void *)0x06000000) {
941     int tmp = rcache_get_tmp();
942     emith_and_r_r_imm(tmp, arg0, 0xfb000000);
943     emith_cmp_r_imm(tmp, 0x02000000);
944     switch (size) {
945     case 0: // 8
946       EMITH_SJMP3_START(DCOND_NE);
947       emith_eor_r_imm_c(DCOND_EQ, arg0, 1);
948       emith_read8_r_r_offs_c(DCOND_EQ, arg0, arg0, 0);
949       EMITH_SJMP3_MID(DCOND_NE);
950       emith_call_cond(DCOND_NE, sh2_drc_read8);
951       EMITH_SJMP3_END();
952       break;
953     case 1: // 16
954       EMITH_SJMP3_START(DCOND_NE);
955       emith_read16_r_r_offs_c(DCOND_EQ, arg0, arg0, 0);
956       EMITH_SJMP3_MID(DCOND_NE);
957       emith_call_cond(DCOND_NE, sh2_drc_read16);
958       EMITH_SJMP3_END();
959       break;
960     case 2: // 32
961       EMITH_SJMP3_START(DCOND_NE);
962       emith_read_r_r_offs_c(DCOND_EQ, arg0, arg0, 0);
963       emith_ror_c(DCOND_EQ, arg0, arg0, 16);
964       EMITH_SJMP3_MID(DCOND_NE);
965       emith_call_cond(DCOND_NE, sh2_drc_read32);
966       EMITH_SJMP3_END();
967       break;
968     }
969   }
970   else
971 #endif
972   {
973     switch (size) {
974     case 0: // 8
975       emith_call(sh2_drc_read8);
976       break;
977     case 1: // 16
978       emith_call(sh2_drc_read16);
979       break;
980     case 2: // 32
981       emith_call(sh2_drc_read32);
982       break;
983     }
984   }
985   rcache_invalidate();
986
987   if (reg_map_g2h[SHR_SR] != -1)
988     emith_ctx_read(reg_map_g2h[SHR_SR], SHR_SR * 4);
989
990   // assuming arg0 and retval reg matches
991   return rcache_get_tmp_arg(0);
992 }
993
994 static int emit_memhandler_read(int size)
995 {
996   return emit_memhandler_read_(size, 1);
997 }
998
999 static int emit_memhandler_read_rr(sh2_reg_e rd, sh2_reg_e rs, u32 offs, int size)
1000 {
1001   int hr, hr2, ram_check = 1;
1002   u32 val, offs2;
1003
1004   if (gconst_get(rs, &val)) {
1005     hr = emit_get_rbase_and_offs(val + offs, &offs2);
1006     if (hr != -1) {
1007       hr2 = rcache_get_reg(rd, RC_GR_WRITE);
1008       switch (size) {
1009       case 0: // 8
1010         emith_read8_r_r_offs(hr2, hr, offs2 ^ 1);
1011         emith_sext(hr2, hr2, 8);
1012         break;
1013       case 1: // 16
1014         emith_read16_r_r_offs(hr2, hr, offs2);
1015         emith_sext(hr2, hr2, 16);
1016         break;
1017       case 2: // 32
1018         emith_read_r_r_offs(hr2, hr, offs2);
1019         emith_ror(hr2, hr2, 16);
1020         break;
1021       }
1022       rcache_free_tmp(hr);
1023       return hr2;
1024     }
1025
1026     ram_check = 0;
1027   }
1028
1029   hr = rcache_get_reg_arg(0, rs);
1030   if (offs != 0)
1031     emith_add_r_imm(hr, offs);
1032   hr  = emit_memhandler_read_(size, ram_check);
1033   hr2 = rcache_get_reg(rd, RC_GR_WRITE);
1034   if (size != 2) {
1035     emith_sext(hr2, hr, (size == 1) ? 16 : 8);
1036   } else
1037     emith_move_r_r(hr2, hr);
1038   rcache_free_tmp(hr);
1039
1040   return hr2;
1041 }
1042
1043 static void emit_memhandler_write(int size, u32 pc, int delay)
1044 {
1045   int ctxr;
1046   host_arg2reg(ctxr, 2);
1047   if (reg_map_g2h[SHR_SR] != -1)
1048     emith_ctx_write(reg_map_g2h[SHR_SR], SHR_SR * 4);
1049
1050   switch (size) {
1051   case 0: // 8
1052     // XXX: consider inlining sh2_drc_write8
1053     if (delay) {
1054       emith_call(sh2_drc_write8_slot);
1055     } else {
1056       emit_move_r_imm32(SHR_PC, pc);
1057       rcache_clean();
1058       emith_call(sh2_drc_write8);
1059     }
1060     break;
1061   case 1: // 16
1062     if (delay) {
1063       emith_call(sh2_drc_write16_slot);
1064     } else {
1065       emit_move_r_imm32(SHR_PC, pc);
1066       rcache_clean();
1067       emith_call(sh2_drc_write16);
1068     }
1069     break;
1070   case 2: // 32
1071     emith_move_r_r(ctxr, CONTEXT_REG);
1072     emith_call(sh2_drc_write32);
1073     break;
1074   }
1075
1076   if (reg_map_g2h[SHR_SR] != -1)
1077     emith_ctx_read(reg_map_g2h[SHR_SR], SHR_SR * 4);
1078   rcache_invalidate();
1079 }
1080
1081 // @(Rx,Ry)
1082 static int emit_indirect_indexed_read(int rx, int ry, int size)
1083 {
1084   int a0, t;
1085   a0 = rcache_get_reg_arg(0, rx);
1086   t  = rcache_get_reg(ry, RC_GR_READ);
1087   emith_add_r_r(a0, t);
1088   return emit_memhandler_read(size);
1089 }
1090
1091 // read @Rn, @rm
1092 static void emit_indirect_read_double(u32 *rnr, u32 *rmr, int rn, int rm, int size)
1093 {
1094   int tmp;
1095
1096   rcache_get_reg_arg(0, rn);
1097   tmp = emit_memhandler_read(size);
1098   emith_ctx_write(tmp, offsetof(SH2, drc_tmp));
1099   rcache_free_tmp(tmp);
1100   tmp = rcache_get_reg(rn, RC_GR_RMW);
1101   emith_add_r_imm(tmp, 1 << size);
1102   rcache_unlock(tmp);
1103
1104   rcache_get_reg_arg(0, rm);
1105   *rmr = emit_memhandler_read(size);
1106   *rnr = rcache_get_tmp();
1107   emith_ctx_read(*rnr, offsetof(SH2, drc_tmp));
1108   tmp = rcache_get_reg(rm, RC_GR_RMW);
1109   emith_add_r_imm(tmp, 1 << size);
1110   rcache_unlock(tmp);
1111 }
1112  
1113 static void emit_do_static_regs(int is_write, int tmpr)
1114 {
1115   int i, r, count;
1116
1117   for (i = 0; i < ARRAY_SIZE(reg_map_g2h); i++) {
1118     r = reg_map_g2h[i];
1119     if (r == -1)
1120       continue;
1121
1122     for (count = 1; i < ARRAY_SIZE(reg_map_g2h) - 1; i++, r++) {
1123       if (reg_map_g2h[i + 1] != r + 1)
1124         break;
1125       count++;
1126     }
1127
1128     if (count > 1) {
1129       // i, r point to last item
1130       if (is_write)
1131         emith_ctx_write_multiple(r - count + 1, (i - count + 1) * 4, count, tmpr);
1132       else
1133         emith_ctx_read_multiple(r - count + 1, (i - count + 1) * 4, count, tmpr);
1134     } else {
1135       if (is_write)
1136         emith_ctx_write(r, i * 4);
1137       else
1138         emith_ctx_read(r, i * 4);
1139     }
1140   }
1141 }
1142
1143 static void emit_block_entry(void)
1144 {
1145   int arg0;
1146
1147   host_arg2reg(arg0, 0);
1148
1149 #if (DRC_DEBUG & 8) || defined(PDB)
1150   int arg1, arg2;
1151   host_arg2reg(arg1, 1);
1152   host_arg2reg(arg2, 2);
1153
1154   emit_do_static_regs(1, arg2);
1155   emith_move_r_r(arg1, CONTEXT_REG);
1156   emith_move_r_r(arg2, rcache_get_reg(SHR_SR, RC_GR_READ));
1157   emith_call(sh2_drc_log_entry);
1158   rcache_invalidate();
1159 #endif
1160   emith_tst_r_r(arg0, arg0);
1161   EMITH_SJMP_START(DCOND_EQ);
1162   emith_jump_reg_c(DCOND_NE, arg0);
1163   EMITH_SJMP_END(DCOND_EQ);
1164 }
1165
1166 #define DELAYED_OP \
1167   drcf.delayed_op = 2
1168
1169 #define DELAY_SAVE_T(sr) { \
1170   emith_bic_r_imm(sr, T_save); \
1171   emith_tst_r_imm(sr, T);      \
1172   EMITH_SJMP_START(DCOND_EQ);  \
1173   emith_or_r_imm_c(DCOND_NE, sr, T_save); \
1174   EMITH_SJMP_END(DCOND_EQ);    \
1175   drcf.use_saved_t = 1;        \
1176 }
1177
1178 #define FLUSH_CYCLES(sr) \
1179   if (cycles > 0) { \
1180     emith_sub_r_imm(sr, cycles << 12); \
1181     cycles = 0; \
1182   }
1183
1184 #define CHECK_UNHANDLED_BITS(mask) { \
1185   if ((op & (mask)) != 0) \
1186     goto default_; \
1187 }
1188
1189 #define FETCH_OP(pc) \
1190   dr_pc_base[(pc) / 2]
1191
1192 #define FETCH32(a) \
1193   ((dr_pc_base[(a) / 2] << 16) | dr_pc_base[(a) / 2 + 1])
1194
1195 #define GET_Fx() \
1196   ((op >> 4) & 0x0f)
1197
1198 #define GET_Rm GET_Fx
1199
1200 #define GET_Rn() \
1201   ((op >> 8) & 0x0f)
1202
1203 #define CHECK_FX_LT(n) \
1204   if (GET_Fx() >= n) \
1205     goto default_
1206
1207 // op_flags: data from 1st pass
1208 #define OP_FLAGS(pc) op_flags[((pc) - base_pc) / 2]
1209 #define OF_DELAY_OP (1 << 0)
1210
1211 static void REGPARM(2) *sh2_translate(SH2 *sh2, int tcache_id)
1212 {
1213   // XXX: maybe use structs instead?
1214   u32 branch_target_pc[MAX_LOCAL_BRANCHES];
1215   void *branch_target_ptr[MAX_LOCAL_BRANCHES];
1216   int branch_target_blkid[MAX_LOCAL_BRANCHES];
1217   int branch_target_count = 0;
1218   void *branch_patch_ptr[MAX_LOCAL_BRANCHES];
1219   u32 branch_patch_pc[MAX_LOCAL_BRANCHES];
1220   int branch_patch_count = 0;
1221   u32 literal_addr[MAX_LITERALS];
1222   int literal_addr_count = 0;
1223   int pending_branch_cond = -1;
1224   int pending_branch_pc = 0;
1225   u8 op_flags[BLOCK_CYCLE_LIMIT + 1];
1226   struct {
1227     u32 delayed_op:2;
1228     u32 test_irq:1;
1229     u32 use_saved_t:1; // delayed op modifies T
1230   } drcf = { 0, };
1231
1232   // PC of current, first, last, last_target_blk SH2 insn
1233   u32 pc, base_pc, end_pc, out_pc;
1234   void *block_entry;
1235   block_desc *this_block;
1236   u16 *dr_pc_base;
1237   int blkid_main = 0;
1238   int skip_op = 0;
1239   u32 tmp, tmp2;
1240   int cycles;
1241   int op;
1242   int i;
1243
1244   base_pc = sh2->pc;
1245
1246   // get base/validate PC
1247   dr_pc_base = dr_get_pc_base(base_pc, sh2->is_slave);
1248   if (dr_pc_base == (void *)-1) {
1249     printf("invalid PC, aborting: %08x\n", base_pc);
1250     // FIXME: be less destructive
1251     exit(1);
1252   }
1253
1254   tcache_ptr = tcache_ptrs[tcache_id];
1255   this_block = dr_add_block(base_pc, sh2->is_slave, &blkid_main);
1256   if (this_block == NULL)
1257     return NULL;
1258
1259   // predict tcache overflow
1260   tmp = tcache_ptr - tcache_bases[tcache_id];
1261   if (tmp > tcache_sizes[tcache_id] - MAX_BLOCK_SIZE) {
1262     dbg(1, "tcache %d overflow", tcache_id);
1263     return NULL;
1264   }
1265
1266   block_entry = tcache_ptr;
1267   dbg(2, "== %csh2 block #%d,%d %08x -> %p", sh2->is_slave ? 's' : 'm',
1268     tcache_id, blkid_main, base_pc, block_entry);
1269
1270   dr_link_blocks(tcache_ptr, base_pc, tcache_id);
1271
1272   // 1st pass: scan forward for local branches
1273   memset(op_flags, 0, sizeof(op_flags));
1274   for (cycles = 0, pc = base_pc; cycles < BLOCK_CYCLE_LIMIT; cycles++, pc += 2) {
1275     op = FETCH_OP(pc);
1276     if ((op & 0xf000) == 0xa000 || (op & 0xf000) == 0xb000) { // BRA, BSR
1277       signed int offs = ((signed int)(op << 20) >> 19);
1278       pc += 2;
1279       OP_FLAGS(pc) |= OF_DELAY_OP;
1280       ADD_TO_ARRAY(branch_target_pc, branch_target_count, pc + offs + 2,);
1281       break;
1282     }
1283     if ((op & 0xf000) == 0) {
1284       op &= 0xff;
1285       if (op == 0x1b) // SLEEP
1286         break;
1287       if (op == 0x23 || op == 0x03 || op == 0x0b || op == 0x2b) { // BRAF, BSRF, RTS, RTE
1288         pc += 2;
1289         OP_FLAGS(pc) |= OF_DELAY_OP;
1290         break;
1291       }
1292       continue;
1293     }
1294     if ((op & 0xf0df) == 0x400b) { // JMP, JSR
1295       pc += 2;
1296       OP_FLAGS(pc) |= OF_DELAY_OP;
1297       break;
1298     }
1299     if ((op & 0xf900) == 0x8900) { // BT(S), BF(S)
1300       signed int offs = ((signed int)(op << 24) >> 23);
1301       if (op & 0x0400)
1302         OP_FLAGS(pc + 2) |= OF_DELAY_OP;
1303       ADD_TO_ARRAY(branch_target_pc, branch_target_count, pc + offs + 4, break);
1304     }
1305     if ((op & 0xff00) == 0xc300) // TRAPA
1306       break;
1307   }
1308
1309   end_pc = pc;
1310
1311   // clean branch_targets that are not really local,
1312   // and that land on delay slots
1313   for (i = 0, tmp = 0; i < branch_target_count; i++) {
1314     pc = branch_target_pc[i];
1315     if (base_pc <= pc && pc <= end_pc && !(OP_FLAGS(pc) & OF_DELAY_OP))
1316       branch_target_pc[tmp++] = branch_target_pc[i];
1317
1318     if (i == branch_target_count - 1) // workaround gcc 4.5.2 bug?
1319       break;
1320   }
1321
1322   branch_target_count = tmp;
1323   if (branch_target_count > 0) {
1324     memset(branch_target_ptr, 0, sizeof(branch_target_ptr[0]) * branch_target_count);
1325     memset(branch_target_blkid, 0, sizeof(branch_target_blkid[0]) * branch_target_count);
1326   }
1327
1328   // -------------------------------------------------
1329   // 2nd pass: actual compilation
1330   out_pc = 0;
1331   pc = base_pc;
1332   for (cycles = 0; pc <= end_pc || drcf.delayed_op; )
1333   {
1334     u32 tmp3, tmp4, sr;
1335
1336     if (drcf.delayed_op > 0)
1337       drcf.delayed_op--;
1338
1339     op = FETCH_OP(pc);
1340
1341     i = find_in_array(branch_target_pc, branch_target_count, pc);
1342     if (i >= 0 || pc == base_pc)
1343     {
1344       if (pc != base_pc)
1345       {
1346         /* make "subblock" - just a mid-block entry */
1347         block_desc *subblock;
1348
1349         sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
1350         FLUSH_CYCLES(sr);
1351         // decide if to flush rcache
1352         if ((op & 0xf0ff) == 0x4010 && FETCH_OP(pc + 2) == 0x8bfd) // DT; BF #-2
1353           rcache_clean();
1354         else
1355           rcache_flush();
1356         do_host_disasm(tcache_id);
1357
1358         dbg(2, "-- %csh2 subblock #%d,%d %08x -> %p", sh2->is_slave ? 's' : 'm',
1359           tcache_id, branch_target_blkid[i], pc, tcache_ptr);
1360
1361         subblock = dr_add_block(pc, sh2->is_slave, &branch_target_blkid[i]);
1362         if (subblock == NULL)
1363           return NULL;
1364
1365         // since we made a block entry, link any other blocks that jump to current pc
1366         dr_link_blocks(tcache_ptr, pc, tcache_id);
1367       }
1368       if (i >= 0)
1369         branch_target_ptr[i] = tcache_ptr;
1370
1371       // must update PC
1372       emit_move_r_imm32(SHR_PC, pc);
1373       rcache_clean();
1374
1375       // check cycles
1376       sr = rcache_get_reg(SHR_SR, RC_GR_READ);
1377       emith_cmp_r_imm(sr, 0);
1378       emith_jump_cond(DCOND_LE, sh2_drc_exit);
1379       do_host_disasm(tcache_id);
1380       rcache_unlock_all();
1381     }
1382
1383 #if (DRC_DEBUG & 2)
1384     insns_compiled++;
1385 #if (DRC_DEBUG & 4)
1386     DasmSH2(sh2dasm_buff, pc, op);
1387     printf("%08x %04x %s\n", pc, op, sh2dasm_buff);
1388 #endif
1389 #endif
1390
1391     pc += 2;
1392     cycles++;
1393
1394     if (skip_op > 0) {
1395       skip_op--;
1396       continue;
1397     }
1398
1399     switch ((op >> 12) & 0x0f)
1400     {
1401     /////////////////////////////////////////////
1402     case 0x00:
1403       switch (op & 0x0f)
1404       {
1405       case 0x02:
1406         tmp = rcache_get_reg(GET_Rn(), RC_GR_WRITE);
1407         switch (GET_Fx())
1408         {
1409         case 0: // STC SR,Rn  0000nnnn00000010
1410           tmp2 = SHR_SR;
1411           break;
1412         case 1: // STC GBR,Rn 0000nnnn00010010
1413           tmp2 = SHR_GBR;
1414           break;
1415         case 2: // STC VBR,Rn 0000nnnn00100010
1416           tmp2 = SHR_VBR;
1417           break;
1418         default:
1419           goto default_;
1420         }
1421         tmp3 = rcache_get_reg(tmp2, RC_GR_READ);
1422         emith_move_r_r(tmp, tmp3);
1423         if (tmp2 == SHR_SR)
1424           emith_clear_msb(tmp, tmp, 22); // reserved bits defined by ISA as 0
1425         goto end_op;
1426       case 0x03:
1427         CHECK_UNHANDLED_BITS(0xd0);
1428         // BRAF Rm    0000mmmm00100011
1429         // BSRF Rm    0000mmmm00000011
1430         DELAYED_OP;
1431         tmp  = rcache_get_reg(SHR_PC, RC_GR_WRITE);
1432         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_READ);
1433         emith_move_r_r(tmp, tmp2);
1434         if (op & 0x20)
1435           emith_add_r_imm(tmp, pc + 2);
1436         else { // BSRF
1437           tmp3 = rcache_get_reg(SHR_PR, RC_GR_WRITE);
1438           emith_move_r_imm(tmp3, pc + 2);
1439           emith_add_r_r(tmp, tmp3);
1440         }
1441         out_pc = (u32)-1;
1442         cycles++;
1443         goto end_op;
1444       case 0x04: // MOV.B Rm,@(R0,Rn)   0000nnnnmmmm0100
1445       case 0x05: // MOV.W Rm,@(R0,Rn)   0000nnnnmmmm0101
1446       case 0x06: // MOV.L Rm,@(R0,Rn)   0000nnnnmmmm0110
1447         rcache_clean();
1448         tmp  = rcache_get_reg_arg(1, GET_Rm());
1449         tmp2 = rcache_get_reg_arg(0, SHR_R0);
1450         tmp3 = rcache_get_reg(GET_Rn(), RC_GR_READ);
1451         emith_add_r_r(tmp2, tmp3);
1452         emit_memhandler_write(op & 3, pc, drcf.delayed_op);
1453         goto end_op;
1454       case 0x07:
1455         // MUL.L     Rm,Rn      0000nnnnmmmm0111
1456         tmp  = rcache_get_reg(GET_Rn(), RC_GR_READ);
1457         tmp2 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1458         tmp3 = rcache_get_reg(SHR_MACL, RC_GR_WRITE);
1459         emith_mul(tmp3, tmp2, tmp);
1460         cycles++;
1461         goto end_op;
1462       case 0x08:
1463         CHECK_UNHANDLED_BITS(0xf00);
1464         switch (GET_Fx())
1465         {
1466         case 0: // CLRT               0000000000001000
1467           sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
1468           if (drcf.delayed_op)
1469             DELAY_SAVE_T(sr);
1470           emith_bic_r_imm(sr, T);
1471           break;
1472         case 1: // SETT               0000000000011000
1473           sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
1474           if (drcf.delayed_op)
1475             DELAY_SAVE_T(sr);
1476           emith_or_r_imm(sr, T);
1477           break;
1478         case 2: // CLRMAC             0000000000101000
1479           emit_move_r_imm32(SHR_MACL, 0);
1480           emit_move_r_imm32(SHR_MACH, 0);
1481           break;
1482         default:
1483           goto default_;
1484         }
1485         goto end_op;
1486       case 0x09:
1487         switch (GET_Fx())
1488         {
1489         case 0: // NOP        0000000000001001
1490           CHECK_UNHANDLED_BITS(0xf00);
1491           break;
1492         case 1: // DIV0U      0000000000011001
1493           CHECK_UNHANDLED_BITS(0xf00);
1494           sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
1495           if (drcf.delayed_op)
1496             DELAY_SAVE_T(sr);
1497           emith_bic_r_imm(sr, M|Q|T);
1498           break;
1499         case 2: // MOVT Rn    0000nnnn00101001
1500           sr   = rcache_get_reg(SHR_SR, RC_GR_READ);
1501           tmp2 = rcache_get_reg(GET_Rn(), RC_GR_WRITE);
1502           emith_clear_msb(tmp2, sr, 31);
1503           break;
1504         default:
1505           goto default_;
1506         }
1507         goto end_op;
1508       case 0x0a:
1509         tmp = rcache_get_reg(GET_Rn(), RC_GR_WRITE);
1510         switch (GET_Fx())
1511         {
1512         case 0: // STS      MACH,Rn   0000nnnn00001010
1513           tmp2 = SHR_MACH;
1514           break;
1515         case 1: // STS      MACL,Rn   0000nnnn00011010
1516           tmp2 = SHR_MACL;
1517           break;
1518         case 2: // STS      PR,Rn     0000nnnn00101010
1519           tmp2 = SHR_PR;
1520           break;
1521         default:
1522           goto default_;
1523         }
1524         tmp2 = rcache_get_reg(tmp2, RC_GR_READ);
1525         emith_move_r_r(tmp, tmp2);
1526         goto end_op;
1527       case 0x0b:
1528         CHECK_UNHANDLED_BITS(0xf00);
1529         switch (GET_Fx())
1530         {
1531         case 0: // RTS        0000000000001011
1532           DELAYED_OP;
1533           emit_move_r_r(SHR_PC, SHR_PR);
1534           out_pc = (u32)-1;
1535           cycles++;
1536           break;
1537         case 1: // SLEEP      0000000000011011
1538           tmp = rcache_get_reg(SHR_SR, RC_GR_RMW);
1539           emith_clear_msb(tmp, tmp, 20); // clear cycles
1540           out_pc = out_pc - 2;
1541           cycles = 1;
1542           goto end_op;
1543         case 2: // RTE        0000000000101011
1544           DELAYED_OP;
1545           // pop PC
1546           emit_memhandler_read_rr(SHR_PC, SHR_SP, 0, 2);
1547           // pop SR
1548           tmp = rcache_get_reg_arg(0, SHR_SP);
1549           emith_add_r_imm(tmp, 4);
1550           tmp = emit_memhandler_read(2);
1551           sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
1552           emith_write_sr(sr, tmp);
1553           rcache_free_tmp(tmp);
1554           tmp = rcache_get_reg(SHR_SP, RC_GR_RMW);
1555           emith_add_r_imm(tmp, 4*2);
1556           drcf.test_irq = 1;
1557           out_pc = (u32)-1;
1558           cycles += 3;
1559           break;
1560         default:
1561           goto default_;
1562         }
1563         goto end_op;
1564       case 0x0c: // MOV.B    @(R0,Rm),Rn      0000nnnnmmmm1100
1565       case 0x0d: // MOV.W    @(R0,Rm),Rn      0000nnnnmmmm1101
1566       case 0x0e: // MOV.L    @(R0,Rm),Rn      0000nnnnmmmm1110
1567         tmp = emit_indirect_indexed_read(SHR_R0, GET_Rm(), op & 3);
1568         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_WRITE);
1569         if ((op & 3) != 2) {
1570           emith_sext(tmp2, tmp, (op & 1) ? 16 : 8);
1571         } else
1572           emith_move_r_r(tmp2, tmp);
1573         rcache_free_tmp(tmp);
1574         goto end_op;
1575       case 0x0f: // MAC.L   @Rm+,@Rn+  0000nnnnmmmm1111
1576         emit_indirect_read_double(&tmp, &tmp2, GET_Rn(), GET_Rm(), 2);
1577         tmp4 = rcache_get_reg(SHR_MACH, RC_GR_RMW);
1578         /* MS 16 MAC bits unused if saturated */
1579         sr = rcache_get_reg(SHR_SR, RC_GR_READ);
1580         emith_tst_r_imm(sr, S);
1581         EMITH_SJMP_START(DCOND_EQ);
1582         emith_clear_msb_c(DCOND_NE, tmp4, tmp4, 16);
1583         EMITH_SJMP_END(DCOND_EQ);
1584         rcache_unlock(sr);
1585         tmp3 = rcache_get_reg(SHR_MACL, RC_GR_RMW); // might evict SR
1586         emith_mula_s64(tmp3, tmp4, tmp, tmp2);
1587         rcache_free_tmp(tmp2);
1588         sr = rcache_get_reg(SHR_SR, RC_GR_READ); // reget just in case
1589         emith_tst_r_imm(sr, S);
1590
1591         EMITH_JMP_START(DCOND_EQ);
1592         emith_asr(tmp, tmp4, 15);
1593         emith_cmp_r_imm(tmp, -1); // negative overflow (0x80000000..0xffff7fff)
1594         EMITH_SJMP_START(DCOND_GE);
1595         emith_move_r_imm_c(DCOND_LT, tmp4, 0x8000);
1596         emith_move_r_imm_c(DCOND_LT, tmp3, 0x0000);
1597         EMITH_SJMP_END(DCOND_GE);
1598         emith_cmp_r_imm(tmp, 0); // positive overflow (0x00008000..0x7fffffff)
1599         EMITH_SJMP_START(DCOND_LE);
1600         emith_move_r_imm_c(DCOND_GT, tmp4, 0x00007fff);
1601         emith_move_r_imm_c(DCOND_GT, tmp3, 0xffffffff);
1602         EMITH_SJMP_END(DCOND_LE);
1603         EMITH_JMP_END(DCOND_EQ);
1604
1605         rcache_free_tmp(tmp);
1606         cycles += 3;
1607         goto end_op;
1608       }
1609       goto default_;
1610
1611     /////////////////////////////////////////////
1612     case 0x01:
1613       // MOV.L Rm,@(disp,Rn) 0001nnnnmmmmdddd
1614       rcache_clean();
1615       tmp  = rcache_get_reg_arg(0, GET_Rn());
1616       tmp2 = rcache_get_reg_arg(1, GET_Rm());
1617       if (op & 0x0f)
1618         emith_add_r_imm(tmp, (op & 0x0f) * 4);
1619       emit_memhandler_write(2, pc, drcf.delayed_op);
1620       goto end_op;
1621
1622     case 0x02:
1623       switch (op & 0x0f)
1624       {
1625       case 0x00: // MOV.B Rm,@Rn        0010nnnnmmmm0000
1626       case 0x01: // MOV.W Rm,@Rn        0010nnnnmmmm0001
1627       case 0x02: // MOV.L Rm,@Rn        0010nnnnmmmm0010
1628         rcache_clean();
1629         rcache_get_reg_arg(0, GET_Rn());
1630         rcache_get_reg_arg(1, GET_Rm());
1631         emit_memhandler_write(op & 3, pc, drcf.delayed_op);
1632         goto end_op;
1633       case 0x04: // MOV.B Rm,@–Rn       0010nnnnmmmm0100
1634       case 0x05: // MOV.W Rm,@–Rn       0010nnnnmmmm0101
1635       case 0x06: // MOV.L Rm,@–Rn       0010nnnnmmmm0110
1636         tmp = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1637         emith_sub_r_imm(tmp, (1 << (op & 3)));
1638         rcache_clean();
1639         rcache_get_reg_arg(0, GET_Rn());
1640         rcache_get_reg_arg(1, GET_Rm());
1641         emit_memhandler_write(op & 3, pc, drcf.delayed_op);
1642         goto end_op;
1643       case 0x07: // DIV0S Rm,Rn         0010nnnnmmmm0111
1644         sr   = rcache_get_reg(SHR_SR, RC_GR_RMW);
1645         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_READ);
1646         tmp3 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1647         if (drcf.delayed_op)
1648           DELAY_SAVE_T(sr);
1649         emith_bic_r_imm(sr, M|Q|T);
1650         emith_tst_r_imm(tmp2, (1<<31));
1651         EMITH_SJMP_START(DCOND_EQ);
1652         emith_or_r_imm_c(DCOND_NE, sr, Q);
1653         EMITH_SJMP_END(DCOND_EQ);
1654         emith_tst_r_imm(tmp3, (1<<31));
1655         EMITH_SJMP_START(DCOND_EQ);
1656         emith_or_r_imm_c(DCOND_NE, sr, M);
1657         EMITH_SJMP_END(DCOND_EQ);
1658         emith_teq_r_r(tmp2, tmp3);
1659         EMITH_SJMP_START(DCOND_PL);
1660         emith_or_r_imm_c(DCOND_MI, sr, T);
1661         EMITH_SJMP_END(DCOND_PL);
1662         goto end_op;
1663       case 0x08: // TST Rm,Rn           0010nnnnmmmm1000
1664         sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
1665         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_READ);
1666         tmp3 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1667         if (drcf.delayed_op)
1668           DELAY_SAVE_T(sr);
1669         emith_bic_r_imm(sr, T);
1670         emith_tst_r_r(tmp2, tmp3);
1671         emit_or_t_if_eq(sr);
1672         goto end_op;
1673       case 0x09: // AND Rm,Rn           0010nnnnmmmm1001
1674         tmp  = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1675         tmp2 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1676         emith_and_r_r(tmp, tmp2);
1677         goto end_op;
1678       case 0x0a: // XOR Rm,Rn           0010nnnnmmmm1010
1679         tmp  = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1680         tmp2 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1681         emith_eor_r_r(tmp, tmp2);
1682         goto end_op;
1683       case 0x0b: // OR  Rm,Rn           0010nnnnmmmm1011
1684         tmp  = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1685         tmp2 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1686         emith_or_r_r(tmp, tmp2);
1687         goto end_op;
1688       case 0x0c: // CMP/STR Rm,Rn       0010nnnnmmmm1100
1689         tmp  = rcache_get_tmp();
1690         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_READ);
1691         tmp3 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1692         emith_eor_r_r_r(tmp, tmp2, tmp3);
1693         sr   = rcache_get_reg(SHR_SR, RC_GR_RMW);
1694         if (drcf.delayed_op)
1695           DELAY_SAVE_T(sr);
1696         emith_bic_r_imm(sr, T);
1697         emith_tst_r_imm(tmp, 0x000000ff);
1698         emit_or_t_if_eq(tmp);
1699         emith_tst_r_imm(tmp, 0x0000ff00);
1700         emit_or_t_if_eq(tmp);
1701         emith_tst_r_imm(tmp, 0x00ff0000);
1702         emit_or_t_if_eq(tmp);
1703         emith_tst_r_imm(tmp, 0xff000000);
1704         emit_or_t_if_eq(tmp);
1705         rcache_free_tmp(tmp);
1706         goto end_op;
1707       case 0x0d: // XTRCT  Rm,Rn        0010nnnnmmmm1101
1708         tmp  = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1709         tmp2 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1710         emith_lsr(tmp, tmp, 16);
1711         emith_or_r_r_lsl(tmp, tmp2, 16);
1712         goto end_op;
1713       case 0x0e: // MULU.W Rm,Rn        0010nnnnmmmm1110
1714       case 0x0f: // MULS.W Rm,Rn        0010nnnnmmmm1111
1715         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_READ);
1716         tmp  = rcache_get_reg(SHR_MACL, RC_GR_WRITE);
1717         if (op & 1) {
1718           emith_sext(tmp, tmp2, 16);
1719         } else
1720           emith_clear_msb(tmp, tmp2, 16);
1721         tmp3 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1722         tmp2 = rcache_get_tmp();
1723         if (op & 1) {
1724           emith_sext(tmp2, tmp3, 16);
1725         } else
1726           emith_clear_msb(tmp2, tmp3, 16);
1727         emith_mul(tmp, tmp, tmp2);
1728         rcache_free_tmp(tmp2);
1729 //      FIXME: causes timing issues in Doom?
1730 //        cycles++;
1731         goto end_op;
1732       }
1733       goto default_;
1734
1735     /////////////////////////////////////////////
1736     case 0x03:
1737       switch (op & 0x0f)
1738       {
1739       case 0x00: // CMP/EQ Rm,Rn        0011nnnnmmmm0000
1740       case 0x02: // CMP/HS Rm,Rn        0011nnnnmmmm0010
1741       case 0x03: // CMP/GE Rm,Rn        0011nnnnmmmm0011
1742       case 0x06: // CMP/HI Rm,Rn        0011nnnnmmmm0110
1743       case 0x07: // CMP/GT Rm,Rn        0011nnnnmmmm0111
1744         sr   = rcache_get_reg(SHR_SR, RC_GR_RMW);
1745         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_READ);
1746         tmp3 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1747         if (drcf.delayed_op)
1748           DELAY_SAVE_T(sr);
1749         emith_bic_r_imm(sr, T);
1750         emith_cmp_r_r(tmp2, tmp3);
1751         switch (op & 0x07)
1752         {
1753         case 0x00: // CMP/EQ
1754           emit_or_t_if_eq(sr);
1755           break;
1756         case 0x02: // CMP/HS
1757           EMITH_SJMP_START(DCOND_LO);
1758           emith_or_r_imm_c(DCOND_HS, sr, T);
1759           EMITH_SJMP_END(DCOND_LO);
1760           break;
1761         case 0x03: // CMP/GE
1762           EMITH_SJMP_START(DCOND_LT);
1763           emith_or_r_imm_c(DCOND_GE, sr, T);
1764           EMITH_SJMP_END(DCOND_LT);
1765           break;
1766         case 0x06: // CMP/HI
1767           EMITH_SJMP_START(DCOND_LS);
1768           emith_or_r_imm_c(DCOND_HI, sr, T);
1769           EMITH_SJMP_END(DCOND_LS);
1770           break;
1771         case 0x07: // CMP/GT
1772           EMITH_SJMP_START(DCOND_LE);
1773           emith_or_r_imm_c(DCOND_GT, sr, T);
1774           EMITH_SJMP_END(DCOND_LE);
1775           break;
1776         }
1777         goto end_op;
1778       case 0x04: // DIV1    Rm,Rn       0011nnnnmmmm0100
1779         // Q1 = carry(Rn = (Rn << 1) | T)
1780         // if Q ^ M
1781         //   Q2 = carry(Rn += Rm)
1782         // else
1783         //   Q2 = carry(Rn -= Rm)
1784         // Q = M ^ Q1 ^ Q2
1785         // T = (Q == M) = !(Q ^ M) = !(Q1 ^ Q2)
1786         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1787         tmp3 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1788         sr   = rcache_get_reg(SHR_SR, RC_GR_RMW);
1789         if (drcf.delayed_op)
1790           DELAY_SAVE_T(sr);
1791         emith_tpop_carry(sr, 0);
1792         emith_adcf_r_r(tmp2, tmp2);
1793         emith_tpush_carry(sr, 0);            // keep Q1 in T for now
1794         tmp4 = rcache_get_tmp();
1795         emith_and_r_r_imm(tmp4, sr, M);
1796         emith_eor_r_r_lsr(sr, tmp4, M_SHIFT - Q_SHIFT); // Q ^= M
1797         rcache_free_tmp(tmp4);
1798         // add or sub, invert T if carry to get Q1 ^ Q2
1799         // in: (Q ^ M) passed in Q, Q1 in T
1800         emith_sh2_div1_step(tmp2, tmp3, sr);
1801         emith_bic_r_imm(sr, Q);
1802         emith_tst_r_imm(sr, M);
1803         EMITH_SJMP_START(DCOND_EQ);
1804         emith_or_r_imm_c(DCOND_NE, sr, Q);  // Q = M
1805         EMITH_SJMP_END(DCOND_EQ);
1806         emith_tst_r_imm(sr, T);
1807         EMITH_SJMP_START(DCOND_EQ);
1808         emith_eor_r_imm_c(DCOND_NE, sr, Q); // Q = M ^ Q1 ^ Q2
1809         EMITH_SJMP_END(DCOND_EQ);
1810         emith_eor_r_imm(sr, T);             // T = !(Q1 ^ Q2)
1811         goto end_op;
1812       case 0x05: // DMULU.L Rm,Rn       0011nnnnmmmm0101
1813         tmp  = rcache_get_reg(GET_Rn(), RC_GR_READ);
1814         tmp2 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1815         tmp3 = rcache_get_reg(SHR_MACL, RC_GR_WRITE);
1816         tmp4 = rcache_get_reg(SHR_MACH, RC_GR_WRITE);
1817         emith_mul_u64(tmp3, tmp4, tmp, tmp2);
1818         goto end_op;
1819       case 0x08: // SUB     Rm,Rn       0011nnnnmmmm1000
1820       case 0x0c: // ADD     Rm,Rn       0011nnnnmmmm1100
1821         tmp  = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1822         tmp2 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1823         if (op & 4) {
1824           emith_add_r_r(tmp, tmp2);
1825         } else
1826           emith_sub_r_r(tmp, tmp2);
1827         goto end_op;
1828       case 0x0a: // SUBC    Rm,Rn       0011nnnnmmmm1010
1829       case 0x0e: // ADDC    Rm,Rn       0011nnnnmmmm1110
1830         tmp  = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1831         tmp2 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1832         sr   = rcache_get_reg(SHR_SR, RC_GR_RMW);
1833         if (drcf.delayed_op)
1834           DELAY_SAVE_T(sr);
1835         if (op & 4) { // adc
1836           emith_tpop_carry(sr, 0);
1837           emith_adcf_r_r(tmp, tmp2);
1838           emith_tpush_carry(sr, 0);
1839         } else {
1840           emith_tpop_carry(sr, 1);
1841           emith_sbcf_r_r(tmp, tmp2);
1842           emith_tpush_carry(sr, 1);
1843         }
1844         goto end_op;
1845       case 0x0b: // SUBV    Rm,Rn       0011nnnnmmmm1011
1846       case 0x0f: // ADDV    Rm,Rn       0011nnnnmmmm1111
1847         tmp  = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1848         tmp2 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1849         sr   = rcache_get_reg(SHR_SR, RC_GR_RMW);
1850         if (drcf.delayed_op)
1851           DELAY_SAVE_T(sr);
1852         emith_bic_r_imm(sr, T);
1853         if (op & 4) {
1854           emith_addf_r_r(tmp, tmp2);
1855         } else
1856           emith_subf_r_r(tmp, tmp2);
1857         EMITH_SJMP_START(DCOND_VC);
1858         emith_or_r_imm_c(DCOND_VS, sr, T);
1859         EMITH_SJMP_END(DCOND_VC);
1860         goto end_op;
1861       case 0x0d: // DMULS.L Rm,Rn       0011nnnnmmmm1101
1862         tmp  = rcache_get_reg(GET_Rn(), RC_GR_READ);
1863         tmp2 = rcache_get_reg(GET_Rm(), RC_GR_READ);
1864         tmp3 = rcache_get_reg(SHR_MACL, RC_GR_WRITE);
1865         tmp4 = rcache_get_reg(SHR_MACH, RC_GR_WRITE);
1866         emith_mul_s64(tmp3, tmp4, tmp, tmp2);
1867         goto end_op;
1868       }
1869       goto default_;
1870
1871     /////////////////////////////////////////////
1872     case 0x04:
1873       switch (op & 0x0f)
1874       {
1875       case 0x00:
1876         switch (GET_Fx())
1877         {
1878         case 0: // SHLL Rn    0100nnnn00000000
1879         case 2: // SHAL Rn    0100nnnn00100000
1880           tmp = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1881           sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
1882           if (drcf.delayed_op)
1883             DELAY_SAVE_T(sr);
1884           emith_tpop_carry(sr, 0); // dummy
1885           emith_lslf(tmp, tmp, 1);
1886           emith_tpush_carry(sr, 0);
1887           goto end_op;
1888         case 1: // DT Rn      0100nnnn00010000
1889           sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
1890           if (drcf.delayed_op)
1891             DELAY_SAVE_T(sr);
1892           if (FETCH_OP(pc) == 0x8bfd) { // BF #-2
1893             if (gconst_get(GET_Rn(), &tmp)) {
1894               // XXX: limit burned cycles
1895               emit_move_r_imm32(GET_Rn(), 0);
1896               emith_or_r_imm(sr, T);
1897               cycles += tmp * 4 + 1; // +1 syncs with noconst version, not sure why
1898               skip_op = 1;
1899             }
1900             else
1901               emith_sh2_dtbf_loop();
1902             goto end_op;
1903           }
1904           tmp = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1905           emith_bic_r_imm(sr, T);
1906           emith_subf_r_imm(tmp, 1);
1907           emit_or_t_if_eq(sr);
1908           goto end_op;
1909         }
1910         goto default_;
1911       case 0x01:
1912         switch (GET_Fx())
1913         {
1914         case 0: // SHLR Rn    0100nnnn00000001
1915         case 2: // SHAR Rn    0100nnnn00100001
1916           tmp = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1917           sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
1918           if (drcf.delayed_op)
1919             DELAY_SAVE_T(sr);
1920           emith_tpop_carry(sr, 0); // dummy
1921           if (op & 0x20) {
1922             emith_asrf(tmp, tmp, 1);
1923           } else
1924             emith_lsrf(tmp, tmp, 1);
1925           emith_tpush_carry(sr, 0);
1926           goto end_op;
1927         case 1: // CMP/PZ Rn  0100nnnn00010001
1928           tmp = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1929           sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
1930           if (drcf.delayed_op)
1931             DELAY_SAVE_T(sr);
1932           emith_bic_r_imm(sr, T);
1933           emith_cmp_r_imm(tmp, 0);
1934           EMITH_SJMP_START(DCOND_LT);
1935           emith_or_r_imm_c(DCOND_GE, sr, T);
1936           EMITH_SJMP_END(DCOND_LT);
1937           goto end_op;
1938         }
1939         goto default_;
1940       case 0x02:
1941       case 0x03:
1942         switch (op & 0x3f)
1943         {
1944         case 0x02: // STS.L    MACH,@–Rn 0100nnnn00000010
1945           tmp = SHR_MACH;
1946           break;
1947         case 0x12: // STS.L    MACL,@–Rn 0100nnnn00010010
1948           tmp = SHR_MACL;
1949           break;
1950         case 0x22: // STS.L    PR,@–Rn   0100nnnn00100010
1951           tmp = SHR_PR;
1952           break;
1953         case 0x03: // STC.L    SR,@–Rn   0100nnnn00000011
1954           tmp = SHR_SR;
1955           break;
1956         case 0x13: // STC.L    GBR,@–Rn  0100nnnn00010011
1957           tmp = SHR_GBR;
1958           break;
1959         case 0x23: // STC.L    VBR,@–Rn  0100nnnn00100011
1960           tmp = SHR_VBR;
1961           break;
1962         default:
1963           goto default_;
1964         }
1965         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1966         emith_sub_r_imm(tmp2, 4);
1967         rcache_clean();
1968         rcache_get_reg_arg(0, GET_Rn());
1969         tmp3 = rcache_get_reg_arg(1, tmp);
1970         if (tmp == SHR_SR)
1971           emith_clear_msb(tmp3, tmp3, 22); // reserved bits defined by ISA as 0
1972         emit_memhandler_write(2, pc, drcf.delayed_op);
1973         goto end_op;
1974       case 0x04:
1975       case 0x05:
1976         switch (op & 0x3f)
1977         {
1978         case 0x04: // ROTL   Rn          0100nnnn00000100
1979         case 0x05: // ROTR   Rn          0100nnnn00000101
1980           tmp = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1981           sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
1982           if (drcf.delayed_op)
1983             DELAY_SAVE_T(sr);
1984           emith_tpop_carry(sr, 0); // dummy
1985           if (op & 1) {
1986             emith_rorf(tmp, tmp, 1);
1987           } else
1988             emith_rolf(tmp, tmp, 1);
1989           emith_tpush_carry(sr, 0);
1990           goto end_op;
1991         case 0x24: // ROTCL  Rn          0100nnnn00100100
1992         case 0x25: // ROTCR  Rn          0100nnnn00100101
1993           tmp = rcache_get_reg(GET_Rn(), RC_GR_RMW);
1994           sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
1995           if (drcf.delayed_op)
1996             DELAY_SAVE_T(sr);
1997           emith_tpop_carry(sr, 0);
1998           if (op & 1) {
1999             emith_rorcf(tmp);
2000           } else
2001             emith_rolcf(tmp);
2002           emith_tpush_carry(sr, 0);
2003           goto end_op;
2004         case 0x15: // CMP/PL Rn          0100nnnn00010101
2005           tmp = rcache_get_reg(GET_Rn(), RC_GR_RMW);
2006           sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
2007           if (drcf.delayed_op)
2008             DELAY_SAVE_T(sr);
2009           emith_bic_r_imm(sr, T);
2010           emith_cmp_r_imm(tmp, 0);
2011           EMITH_SJMP_START(DCOND_LE);
2012           emith_or_r_imm_c(DCOND_GT, sr, T);
2013           EMITH_SJMP_END(DCOND_LE);
2014           goto end_op;
2015         }
2016         goto default_;
2017       case 0x06:
2018       case 0x07:
2019         switch (op & 0x3f)
2020         {
2021         case 0x06: // LDS.L @Rm+,MACH 0100mmmm00000110
2022           tmp = SHR_MACH;
2023           break;
2024         case 0x16: // LDS.L @Rm+,MACL 0100mmmm00010110
2025           tmp = SHR_MACL;
2026           break;
2027         case 0x26: // LDS.L @Rm+,PR   0100mmmm00100110
2028           tmp = SHR_PR;
2029           break;
2030         case 0x07: // LDC.L @Rm+,SR   0100mmmm00000111
2031           tmp = SHR_SR;
2032           break;
2033         case 0x17: // LDC.L @Rm+,GBR  0100mmmm00010111
2034           tmp = SHR_GBR;
2035           break;
2036         case 0x27: // LDC.L @Rm+,VBR  0100mmmm00100111
2037           tmp = SHR_VBR;
2038           break;
2039         default:
2040           goto default_;
2041         }
2042         rcache_get_reg_arg(0, GET_Rn());
2043         tmp2 = emit_memhandler_read(2);
2044         if (tmp == SHR_SR) {
2045           sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
2046           if (drcf.delayed_op)
2047             DELAY_SAVE_T(sr);
2048           emith_write_sr(sr, tmp2);
2049           drcf.test_irq = 1;
2050         } else {
2051           tmp = rcache_get_reg(tmp, RC_GR_WRITE);
2052           emith_move_r_r(tmp, tmp2);
2053         }
2054         rcache_free_tmp(tmp2);
2055         tmp = rcache_get_reg(GET_Rn(), RC_GR_RMW);
2056         emith_add_r_imm(tmp, 4);
2057         goto end_op;
2058       case 0x08:
2059       case 0x09:
2060         switch (GET_Fx())
2061         {
2062         case 0:
2063           // SHLL2 Rn        0100nnnn00001000
2064           // SHLR2 Rn        0100nnnn00001001
2065           tmp = 2;
2066           break;
2067         case 1:
2068           // SHLL8 Rn        0100nnnn00011000
2069           // SHLR8 Rn        0100nnnn00011001
2070           tmp = 8;
2071           break;
2072         case 2:
2073           // SHLL16 Rn       0100nnnn00101000
2074           // SHLR16 Rn       0100nnnn00101001
2075           tmp = 16;
2076           break;
2077         default:
2078           goto default_;
2079         }
2080         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_RMW);
2081         if (op & 1) {
2082           emith_lsr(tmp2, tmp2, tmp);
2083         } else
2084           emith_lsl(tmp2, tmp2, tmp);
2085         goto end_op;
2086       case 0x0a:
2087         switch (GET_Fx())
2088         {
2089         case 0: // LDS      Rm,MACH   0100mmmm00001010
2090           tmp2 = SHR_MACH;
2091           break;
2092         case 1: // LDS      Rm,MACL   0100mmmm00011010
2093           tmp2 = SHR_MACL;
2094           break;
2095         case 2: // LDS      Rm,PR     0100mmmm00101010
2096           tmp2 = SHR_PR;
2097           break;
2098         default:
2099           goto default_;
2100         }
2101         emit_move_r_r(tmp2, GET_Rn());
2102         goto end_op;
2103       case 0x0b:
2104         switch (GET_Fx())
2105         {
2106         case 0: // JSR  @Rm   0100mmmm00001011
2107         case 2: // JMP  @Rm   0100mmmm00101011
2108           DELAYED_OP;
2109           if (!(op & 0x20))
2110             emit_move_r_imm32(SHR_PR, pc + 2);
2111           emit_move_r_r(SHR_PC, (op >> 8) & 0x0f);
2112           out_pc = (u32)-1;
2113           cycles++;
2114           break;
2115         case 1: // TAS.B @Rn  0100nnnn00011011
2116           // XXX: is TAS working on 32X?
2117           rcache_get_reg_arg(0, GET_Rn());
2118           tmp = emit_memhandler_read(0);
2119           sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
2120           if (drcf.delayed_op)
2121             DELAY_SAVE_T(sr);
2122           emith_bic_r_imm(sr, T);
2123           emith_cmp_r_imm(tmp, 0);
2124           emit_or_t_if_eq(sr);
2125           rcache_clean();
2126           emith_or_r_imm(tmp, 0x80);
2127           tmp2 = rcache_get_tmp_arg(1); // assuming it differs to tmp
2128           emith_move_r_r(tmp2, tmp);
2129           rcache_free_tmp(tmp);
2130           rcache_get_reg_arg(0, GET_Rn());
2131           emit_memhandler_write(0, pc, drcf.delayed_op);
2132           cycles += 3;
2133           break;
2134         default:
2135           goto default_;
2136         }
2137         goto end_op;
2138       case 0x0e:
2139         tmp = rcache_get_reg(GET_Rn(), RC_GR_READ);
2140         switch (GET_Fx())
2141         {
2142         case 0: // LDC Rm,SR   0100mmmm00001110
2143           tmp2 = SHR_SR;
2144           break;
2145         case 1: // LDC Rm,GBR  0100mmmm00011110
2146           tmp2 = SHR_GBR;
2147           break;
2148         case 2: // LDC Rm,VBR  0100mmmm00101110
2149           tmp2 = SHR_VBR;
2150           break;
2151         default:
2152           goto default_;
2153         }
2154         if (tmp2 == SHR_SR) {
2155           sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
2156           if (drcf.delayed_op)
2157             DELAY_SAVE_T(sr);
2158           emith_write_sr(sr, tmp);
2159           drcf.test_irq = 1;
2160         } else {
2161           tmp2 = rcache_get_reg(tmp2, RC_GR_WRITE);
2162           emith_move_r_r(tmp2, tmp);
2163         }
2164         goto end_op;
2165       case 0x0f:
2166         // MAC.W @Rm+,@Rn+  0100nnnnmmmm1111
2167         emit_indirect_read_double(&tmp, &tmp2, GET_Rn(), GET_Rm(), 1);
2168         emith_sext(tmp, tmp, 16);
2169         emith_sext(tmp2, tmp2, 16);
2170         tmp3 = rcache_get_reg(SHR_MACL, RC_GR_RMW);
2171         tmp4 = rcache_get_reg(SHR_MACH, RC_GR_RMW);
2172         emith_mula_s64(tmp3, tmp4, tmp, tmp2);
2173         rcache_free_tmp(tmp2);
2174         // XXX: MACH should be untouched when S is set?
2175         sr = rcache_get_reg(SHR_SR, RC_GR_READ);
2176         emith_tst_r_imm(sr, S);
2177         EMITH_JMP_START(DCOND_EQ);
2178
2179         emith_asr(tmp, tmp3, 31);
2180         emith_eorf_r_r(tmp, tmp4); // tmp = ((signed)macl >> 31) ^ mach
2181         EMITH_JMP_START(DCOND_EQ);
2182         emith_move_r_imm(tmp3, 0x80000000);
2183         emith_tst_r_r(tmp4, tmp4);
2184         EMITH_SJMP_START(DCOND_MI);
2185         emith_sub_r_imm_c(DCOND_PL, tmp3, 1); // positive
2186         EMITH_SJMP_END(DCOND_MI);
2187         EMITH_JMP_END(DCOND_EQ);
2188
2189         EMITH_JMP_END(DCOND_EQ);
2190         rcache_free_tmp(tmp);
2191         cycles += 2;
2192         goto end_op;
2193       }
2194       goto default_;
2195
2196     /////////////////////////////////////////////
2197     case 0x05:
2198       // MOV.L @(disp,Rm),Rn 0101nnnnmmmmdddd
2199       emit_memhandler_read_rr(GET_Rn(), GET_Rm(), (op & 0x0f) * 4, 2);
2200       goto end_op;
2201
2202     /////////////////////////////////////////////
2203     case 0x06:
2204       switch (op & 0x0f)
2205       {
2206       case 0x00: // MOV.B @Rm,Rn        0110nnnnmmmm0000
2207       case 0x01: // MOV.W @Rm,Rn        0110nnnnmmmm0001
2208       case 0x02: // MOV.L @Rm,Rn        0110nnnnmmmm0010
2209       case 0x04: // MOV.B @Rm+,Rn       0110nnnnmmmm0100
2210       case 0x05: // MOV.W @Rm+,Rn       0110nnnnmmmm0101
2211       case 0x06: // MOV.L @Rm+,Rn       0110nnnnmmmm0110
2212         emit_memhandler_read_rr(GET_Rn(), GET_Rm(), 0, op & 3);
2213         if ((op & 7) >= 4 && GET_Rn() != GET_Rm()) {
2214           tmp = rcache_get_reg(GET_Rm(), RC_GR_RMW);
2215           emith_add_r_imm(tmp, (1 << (op & 3)));
2216         }
2217         goto end_op;
2218       case 0x03:
2219       case 0x07 ... 0x0f:
2220         tmp  = rcache_get_reg(GET_Rm(), RC_GR_READ);
2221         tmp2 = rcache_get_reg(GET_Rn(), RC_GR_WRITE);
2222         switch (op & 0x0f)
2223         {
2224         case 0x03: // MOV    Rm,Rn        0110nnnnmmmm0011
2225           emith_move_r_r(tmp2, tmp);
2226           break;
2227         case 0x07: // NOT    Rm,Rn        0110nnnnmmmm0111
2228           emith_mvn_r_r(tmp2, tmp);
2229           break;
2230         case 0x08: // SWAP.B Rm,Rn        0110nnnnmmmm1000
2231           tmp3 = tmp2;
2232           if (tmp == tmp2)
2233             tmp3 = rcache_get_tmp();
2234           tmp4 = rcache_get_tmp();
2235           emith_lsr(tmp3, tmp, 16);
2236           emith_or_r_r_lsl(tmp3, tmp, 24);
2237           emith_and_r_r_imm(tmp4, tmp, 0xff00);
2238           emith_or_r_r_lsl(tmp3, tmp4, 8);
2239           emith_rol(tmp2, tmp3, 16);
2240           rcache_free_tmp(tmp4);
2241           if (tmp == tmp2)
2242             rcache_free_tmp(tmp3);
2243           break;
2244         case 0x09: // SWAP.W Rm,Rn        0110nnnnmmmm1001
2245           emith_rol(tmp2, tmp, 16);
2246           break;
2247         case 0x0a: // NEGC   Rm,Rn        0110nnnnmmmm1010
2248           sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
2249           if (drcf.delayed_op)
2250             DELAY_SAVE_T(sr);
2251           emith_tpop_carry(sr, 1);
2252           emith_negcf_r_r(tmp2, tmp);
2253           emith_tpush_carry(sr, 1);
2254           break;
2255         case 0x0b: // NEG    Rm,Rn        0110nnnnmmmm1011
2256           emith_neg_r_r(tmp2, tmp);
2257           break;
2258         case 0x0c: // EXTU.B Rm,Rn        0110nnnnmmmm1100
2259           emith_clear_msb(tmp2, tmp, 24);
2260           break;
2261         case 0x0d: // EXTU.W Rm,Rn        0110nnnnmmmm1101
2262           emith_clear_msb(tmp2, tmp, 16);
2263           break;
2264         case 0x0e: // EXTS.B Rm,Rn        0110nnnnmmmm1110
2265           emith_sext(tmp2, tmp, 8);
2266           break;
2267         case 0x0f: // EXTS.W Rm,Rn        0110nnnnmmmm1111
2268           emith_sext(tmp2, tmp, 16);
2269           break;
2270         }
2271         goto end_op;
2272       }
2273       goto default_;
2274
2275     /////////////////////////////////////////////
2276     case 0x07:
2277       // ADD #imm,Rn  0111nnnniiiiiiii
2278       tmp = rcache_get_reg(GET_Rn(), RC_GR_RMW);
2279       if (op & 0x80) { // adding negative
2280         emith_sub_r_imm(tmp, -op & 0xff);
2281       } else
2282         emith_add_r_imm(tmp, op & 0xff);
2283       goto end_op;
2284
2285     /////////////////////////////////////////////
2286     case 0x08:
2287       switch (op & 0x0f00)
2288       {
2289       case 0x0000: // MOV.B R0,@(disp,Rn)  10000000nnnndddd
2290       case 0x0100: // MOV.W R0,@(disp,Rn)  10000001nnnndddd
2291         rcache_clean();
2292         tmp  = rcache_get_reg_arg(0, GET_Rm());
2293         tmp2 = rcache_get_reg_arg(1, SHR_R0);
2294         tmp3 = (op & 0x100) >> 8;
2295         if (op & 0x0f)
2296           emith_add_r_imm(tmp, (op & 0x0f) << tmp3);
2297         emit_memhandler_write(tmp3, pc, drcf.delayed_op);
2298         goto end_op;
2299       case 0x0400: // MOV.B @(disp,Rm),R0  10000100mmmmdddd
2300       case 0x0500: // MOV.W @(disp,Rm),R0  10000101mmmmdddd
2301         tmp = (op & 0x100) >> 8;
2302         emit_memhandler_read_rr(SHR_R0, GET_Rm(), (op & 0x0f) << tmp, tmp);
2303         goto end_op;
2304       case 0x0800: // CMP/EQ #imm,R0       10001000iiiiiiii
2305         // XXX: could use cmn
2306         tmp  = rcache_get_tmp();
2307         tmp2 = rcache_get_reg(0, RC_GR_READ);
2308         sr   = rcache_get_reg(SHR_SR, RC_GR_RMW);
2309         if (drcf.delayed_op)
2310           DELAY_SAVE_T(sr);
2311         emith_move_r_imm_s8(tmp, op & 0xff);
2312         emith_bic_r_imm(sr, T);
2313         emith_cmp_r_r(tmp2, tmp);
2314         emit_or_t_if_eq(sr);
2315         rcache_free_tmp(tmp);
2316         goto end_op;
2317       case 0x0d00: // BT/S label 10001101dddddddd
2318       case 0x0f00: // BF/S label 10001111dddddddd
2319         DELAYED_OP;
2320         cycles--;
2321         // fallthrough
2322       case 0x0900: // BT   label 10001001dddddddd
2323       case 0x0b00: // BF   label 10001011dddddddd
2324         // will handle conditional branches later
2325         pending_branch_cond = (op & 0x0200) ? DCOND_EQ : DCOND_NE;
2326         i = ((signed int)(op << 24) >> 23);
2327         pending_branch_pc = pc + i + 2;
2328         cycles += 2;
2329         goto end_op;
2330       }
2331       goto default_;
2332
2333     /////////////////////////////////////////////
2334     case 0x09:
2335       // MOV.W @(disp,PC),Rn  1001nnnndddddddd
2336       tmp = pc + (op & 0xff) * 2 + 2;
2337 #if PROPAGATE_CONSTANTS
2338       if (tmp < end_pc + MAX_LITERAL_OFFSET && literal_addr_count < MAX_LITERALS) {
2339         ADD_TO_ARRAY(literal_addr, literal_addr_count, tmp,);
2340         gconst_new(GET_Rn(), (u32)(int)(signed short)FETCH_OP(tmp));
2341       }
2342       else
2343 #endif
2344       {
2345         tmp2 = rcache_get_tmp_arg(0);
2346         emith_move_r_imm(tmp2, tmp);
2347         tmp2 = emit_memhandler_read(1);
2348         tmp3 = rcache_get_reg(GET_Rn(), RC_GR_WRITE);
2349         emith_sext(tmp3, tmp2, 16);
2350         rcache_free_tmp(tmp2);
2351       }
2352       goto end_op;
2353
2354     /////////////////////////////////////////////
2355     case 0x0a:
2356       // BRA  label 1010dddddddddddd
2357       DELAYED_OP;
2358       sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
2359       tmp = ((signed int)(op << 20) >> 19);
2360       out_pc = pc + tmp + 2;
2361       if (tmp == (u32)-4)
2362         emith_clear_msb(sr, sr, 20); // burn cycles
2363       cycles++;
2364       break;
2365
2366     /////////////////////////////////////////////
2367     case 0x0b:
2368       // BSR  label 1011dddddddddddd
2369       DELAYED_OP;
2370       emit_move_r_imm32(SHR_PR, pc + 2);
2371       tmp = ((signed int)(op << 20) >> 19);
2372       out_pc = pc + tmp + 2;
2373       cycles++;
2374       break;
2375
2376     /////////////////////////////////////////////
2377     case 0x0c:
2378       switch (op & 0x0f00)
2379       {
2380       case 0x0000: // MOV.B R0,@(disp,GBR)   11000000dddddddd
2381       case 0x0100: // MOV.W R0,@(disp,GBR)   11000001dddddddd
2382       case 0x0200: // MOV.L R0,@(disp,GBR)   11000010dddddddd
2383         rcache_clean();
2384         tmp  = rcache_get_reg_arg(0, SHR_GBR);
2385         tmp2 = rcache_get_reg_arg(1, SHR_R0);
2386         tmp3 = (op & 0x300) >> 8;
2387         emith_add_r_imm(tmp, (op & 0xff) << tmp3);
2388         emit_memhandler_write(tmp3, pc, drcf.delayed_op);
2389         goto end_op;
2390       case 0x0400: // MOV.B @(disp,GBR),R0   11000100dddddddd
2391       case 0x0500: // MOV.W @(disp,GBR),R0   11000101dddddddd
2392       case 0x0600: // MOV.L @(disp,GBR),R0   11000110dddddddd
2393         tmp = (op & 0x300) >> 8;
2394         emit_memhandler_read_rr(SHR_R0, SHR_GBR, (op & 0xff) << tmp, tmp);
2395         goto end_op;
2396       case 0x0300: // TRAPA #imm      11000011iiiiiiii
2397         tmp = rcache_get_reg(SHR_SP, RC_GR_RMW);
2398         emith_sub_r_imm(tmp, 4*2);
2399         // push SR
2400         tmp = rcache_get_reg_arg(0, SHR_SP);
2401         emith_add_r_imm(tmp, 4);
2402         tmp = rcache_get_reg_arg(1, SHR_SR);
2403         emith_clear_msb(tmp, tmp, 22);
2404         emit_memhandler_write(2, pc, drcf.delayed_op);
2405         // push PC
2406         rcache_get_reg_arg(0, SHR_SP);
2407         tmp = rcache_get_tmp_arg(1);
2408         emith_move_r_imm(tmp, pc);
2409         emit_memhandler_write(2, pc, drcf.delayed_op);
2410         // obtain new PC
2411         emit_memhandler_read_rr(SHR_PC, SHR_VBR, (op & 0xff) * 4, 2);
2412         out_pc = (u32)-1;
2413         cycles += 7;
2414         goto end_op;
2415       case 0x0700: // MOVA @(disp,PC),R0    11000111dddddddd
2416         emit_move_r_imm32(SHR_R0, (pc + (op & 0xff) * 4 + 2) & ~3);
2417         goto end_op;
2418       case 0x0800: // TST #imm,R0           11001000iiiiiiii
2419         tmp = rcache_get_reg(SHR_R0, RC_GR_READ);
2420         sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
2421         if (drcf.delayed_op)
2422           DELAY_SAVE_T(sr);
2423         emith_bic_r_imm(sr, T);
2424         emith_tst_r_imm(tmp, op & 0xff);
2425         emit_or_t_if_eq(sr);
2426         goto end_op;
2427       case 0x0900: // AND #imm,R0           11001001iiiiiiii
2428         tmp = rcache_get_reg(SHR_R0, RC_GR_RMW);
2429         emith_and_r_imm(tmp, op & 0xff);
2430         goto end_op;
2431       case 0x0a00: // XOR #imm,R0           11001010iiiiiiii
2432         tmp = rcache_get_reg(SHR_R0, RC_GR_RMW);
2433         emith_eor_r_imm(tmp, op & 0xff);
2434         goto end_op;
2435       case 0x0b00: // OR  #imm,R0           11001011iiiiiiii
2436         tmp = rcache_get_reg(SHR_R0, RC_GR_RMW);
2437         emith_or_r_imm(tmp, op & 0xff);
2438         goto end_op;
2439       case 0x0c00: // TST.B #imm,@(R0,GBR)  11001100iiiiiiii
2440         tmp = emit_indirect_indexed_read(SHR_R0, SHR_GBR, 0);
2441         sr  = rcache_get_reg(SHR_SR, RC_GR_RMW);
2442         if (drcf.delayed_op)
2443           DELAY_SAVE_T(sr);
2444         emith_bic_r_imm(sr, T);
2445         emith_tst_r_imm(tmp, op & 0xff);
2446         emit_or_t_if_eq(sr);
2447         rcache_free_tmp(tmp);
2448         cycles += 2;
2449         goto end_op;
2450       case 0x0d00: // AND.B #imm,@(R0,GBR)  11001101iiiiiiii
2451         tmp = emit_indirect_indexed_read(SHR_R0, SHR_GBR, 0);
2452         emith_and_r_imm(tmp, op & 0xff);
2453         goto end_rmw_op;
2454       case 0x0e00: // XOR.B #imm,@(R0,GBR)  11001110iiiiiiii
2455         tmp = emit_indirect_indexed_read(SHR_R0, SHR_GBR, 0);
2456         emith_eor_r_imm(tmp, op & 0xff);
2457         goto end_rmw_op;
2458       case 0x0f00: // OR.B  #imm,@(R0,GBR)  11001111iiiiiiii
2459         tmp = emit_indirect_indexed_read(SHR_R0, SHR_GBR, 0);
2460         emith_or_r_imm(tmp, op & 0xff);
2461       end_rmw_op:
2462         tmp2 = rcache_get_tmp_arg(1);
2463         emith_move_r_r(tmp2, tmp);
2464         rcache_free_tmp(tmp);
2465         tmp3 = rcache_get_reg_arg(0, SHR_GBR);
2466         tmp4 = rcache_get_reg(SHR_R0, RC_GR_READ);
2467         emith_add_r_r(tmp3, tmp4);
2468         emit_memhandler_write(0, pc, drcf.delayed_op);
2469         cycles += 2;
2470         goto end_op;
2471       }
2472       goto default_;
2473
2474     /////////////////////////////////////////////
2475     case 0x0d:
2476       // MOV.L @(disp,PC),Rn  1101nnnndddddddd
2477       tmp = (pc + (op & 0xff) * 4 + 2) & ~3;
2478 #if PROPAGATE_CONSTANTS
2479       if (tmp < end_pc + MAX_LITERAL_OFFSET && literal_addr_count < MAX_LITERALS) {
2480         ADD_TO_ARRAY(literal_addr, literal_addr_count, tmp,);
2481         gconst_new(GET_Rn(), FETCH32(tmp));
2482       }
2483       else
2484 #endif
2485       {
2486         tmp2 = rcache_get_tmp_arg(0);
2487         emith_move_r_imm(tmp2, tmp);
2488         tmp2 = emit_memhandler_read(2);
2489         tmp3 = rcache_get_reg(GET_Rn(), RC_GR_WRITE);
2490         emith_move_r_r(tmp3, tmp2);
2491         rcache_free_tmp(tmp2);
2492       }
2493       goto end_op;
2494
2495     /////////////////////////////////////////////
2496     case 0x0e:
2497       // MOV #imm,Rn   1110nnnniiiiiiii
2498       emit_move_r_imm32(GET_Rn(), (u32)(signed int)(signed char)op);
2499       goto end_op;
2500
2501     default:
2502     default_:
2503       elprintf(EL_ANOMALY, "%csh2 drc: unhandled op %04x @ %08x",
2504         sh2->is_slave ? 's' : 'm', op, pc - 2);
2505 #ifdef DRC_DEBUG_INTERP
2506       emit_move_r_imm32(SHR_PC, pc - 2);
2507       rcache_flush();
2508       emith_pass_arg_r(0, CONTEXT_REG);
2509       emith_pass_arg_imm(1, op);
2510       emith_call(sh2_do_op);
2511 #endif
2512       break;
2513     }
2514
2515 end_op:
2516     rcache_unlock_all();
2517
2518     // conditional branch handling (with/without delay)
2519     if (pending_branch_cond != -1 && drcf.delayed_op != 2)
2520     {
2521       u32 target_pc = pending_branch_pc;
2522       void *target;
2523
2524       sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
2525       // handle cycles
2526       FLUSH_CYCLES(sr);
2527       rcache_clean();
2528       if (drcf.use_saved_t)
2529         emith_tst_r_imm(sr, T_save);
2530       else
2531         emith_tst_r_imm(sr, T);
2532
2533 #if LINK_BRANCHES
2534       if (find_in_array(branch_target_pc, branch_target_count, target_pc) >= 0) {
2535         // local branch
2536         // XXX: jumps back can be linked already
2537         branch_patch_pc[branch_patch_count] = target_pc;
2538         branch_patch_ptr[branch_patch_count] = tcache_ptr;
2539         emith_jump_cond_patchable(pending_branch_cond, tcache_ptr);
2540
2541         branch_patch_count++;
2542         if (branch_patch_count == MAX_LOCAL_BRANCHES) {
2543           dbg(1, "warning: too many local branches");
2544           break;
2545         }
2546       }
2547       else
2548 #endif
2549       {
2550         // can't resolve branch locally, make a block exit
2551         emit_move_r_imm32(SHR_PC, target_pc);
2552         rcache_clean();
2553
2554         target = dr_prepare_ext_branch(target_pc, sh2, tcache_id);
2555         if (target == NULL)
2556           return NULL;
2557         emith_jump_cond_patchable(pending_branch_cond, target);
2558       }
2559
2560       drcf.use_saved_t = 0;
2561       pending_branch_cond = -1;
2562     }
2563
2564     // test irq?
2565     // XXX: delay slots..
2566     if (drcf.test_irq && drcf.delayed_op != 2) {
2567       if (!drcf.delayed_op)
2568         emit_move_r_imm32(SHR_PC, pc);
2569       sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
2570       FLUSH_CYCLES(sr);
2571       rcache_flush();
2572       emith_call(sh2_drc_test_irq);
2573       drcf.test_irq = 0;
2574     }
2575
2576     do_host_disasm(tcache_id);
2577
2578     if (out_pc != 0 && drcf.delayed_op != 2)
2579       break;
2580   }
2581
2582   tmp = rcache_get_reg(SHR_SR, RC_GR_RMW);
2583   FLUSH_CYCLES(tmp);
2584   rcache_flush();
2585
2586   if (out_pc == (u32)-1) {
2587     // indirect jump -> back to dispatcher
2588     emith_jump(sh2_drc_dispatcher);
2589   } else {
2590     void *target;
2591     if (out_pc == 0)
2592       out_pc = pc;
2593     emit_move_r_imm32(SHR_PC, out_pc);
2594     rcache_flush();
2595
2596     target = dr_prepare_ext_branch(out_pc, sh2, tcache_id);
2597     if (target == NULL)
2598       return NULL;
2599     emith_jump_patchable(target);
2600   }
2601
2602   // link local branches
2603   for (i = 0; i < branch_patch_count; i++) {
2604     void *target;
2605     int t;
2606     t = find_in_array(branch_target_pc, branch_target_count, branch_patch_pc[i]);
2607     target = branch_target_ptr[t];
2608     if (target == NULL) {
2609       // flush pc and go back to dispatcher (this should no longer happen)
2610       dbg(1, "stray branch to %08x %p", branch_patch_pc[i], tcache_ptr);
2611       target = tcache_ptr;
2612       emit_move_r_imm32(SHR_PC, branch_patch_pc[i]);
2613       rcache_flush();
2614       emith_jump(sh2_drc_dispatcher);
2615     }
2616     emith_jump_patch(branch_patch_ptr[i], target);
2617   }
2618
2619   end_pc = pc;
2620
2621   // mark memory blocks as containing compiled code
2622   // override any overlay blocks as they become unreachable anyway
2623   if (tcache_id != 0 || (this_block->addr & 0xc7fc0000) == 0x06000000)
2624   {
2625     u16 *drc_ram_blk = NULL;
2626     u32 mask = 0, shift = 0;
2627
2628     if (tcache_id != 0) {
2629       // data array, BIOS
2630       drc_ram_blk = Pico32xMem->drcblk_da[sh2->is_slave];
2631       shift = SH2_DRCBLK_DA_SHIFT;
2632       mask = 0xfff;
2633     }
2634     else if ((this_block->addr & 0xc7fc0000) == 0x06000000) {
2635       // SDRAM
2636       drc_ram_blk = Pico32xMem->drcblk_ram;
2637       shift = SH2_DRCBLK_RAM_SHIFT;
2638       mask = 0x3ffff;
2639     }
2640
2641     drc_ram_blk[(base_pc >> shift) & mask] = (blkid_main << 1) | 1;
2642     for (pc = base_pc + 2; pc < end_pc; pc += 2)
2643       drc_ram_blk[(pc >> shift) & mask] = blkid_main << 1;
2644
2645     // mark subblocks
2646     for (i = 0; i < branch_target_count; i++)
2647       if (branch_target_blkid[i] != 0)
2648         drc_ram_blk[(branch_target_pc[i] >> shift) & mask] =
2649           (branch_target_blkid[i] << 1) | 1;
2650
2651     // mark literals
2652     for (i = 0; i < literal_addr_count; i++) {
2653       tmp = literal_addr[i];
2654       drc_ram_blk[(tmp >> shift) & mask] = blkid_main << 1;
2655       if (!(tmp & 3)) // assume long
2656         drc_ram_blk[((tmp + 2) >> shift) & mask] = blkid_main << 1;
2657     }
2658   }
2659
2660   tcache_ptrs[tcache_id] = tcache_ptr;
2661
2662   host_instructions_updated(block_entry, tcache_ptr);
2663
2664   do_host_disasm(tcache_id);
2665   dbg(2, " block #%d,%d tcache %d/%d, insns %d -> %d %.3f",
2666     tcache_id, block_counts[tcache_id],
2667     tcache_ptr - tcache_bases[tcache_id], tcache_sizes[tcache_id],
2668     insns_compiled, host_insn_count, (double)host_insn_count / insns_compiled);
2669   if ((sh2->pc & 0xc6000000) == 0x02000000) // ROM
2670     dbg(2, "  hash collisions %d/%d", hash_collisions, block_counts[tcache_id]);
2671 /*
2672  printf("~~~\n");
2673  tcache_dsm_ptrs[tcache_id] = block_entry;
2674  do_host_disasm(tcache_id);
2675  printf("~~~\n");
2676 */
2677
2678 #if (DRC_DEBUG & 4)
2679   fflush(stdout);
2680 #endif
2681
2682   return block_entry;
2683 }
2684
2685 static void sh2_generate_utils(void)
2686 {
2687   int arg0, arg1, arg2, sr, tmp;
2688   void *sh2_drc_write_end, *sh2_drc_write_slot_end;
2689
2690   sh2_drc_write32 = p32x_sh2_write32;
2691   sh2_drc_read8  = p32x_sh2_read8;
2692   sh2_drc_read16 = p32x_sh2_read16;
2693   sh2_drc_read32 = p32x_sh2_read32;
2694
2695   host_arg2reg(arg0, 0);
2696   host_arg2reg(arg1, 1);
2697   host_arg2reg(arg2, 2);
2698   emith_move_r_r(arg0, arg0); // nop
2699
2700   // sh2_drc_exit(void)
2701   sh2_drc_exit = (void *)tcache_ptr;
2702   emit_do_static_regs(1, arg2);
2703   emith_sh2_drc_exit();
2704
2705   // sh2_drc_dispatcher(void)
2706   sh2_drc_dispatcher = (void *)tcache_ptr;
2707   sr = rcache_get_reg(SHR_SR, RC_GR_READ);
2708   emith_cmp_r_imm(sr, 0);
2709   emith_jump_cond(DCOND_LT, sh2_drc_exit);
2710   rcache_invalidate();
2711   emith_ctx_read(arg0, SHR_PC * 4);
2712   emith_ctx_read(arg1, offsetof(SH2, is_slave));
2713   emith_add_r_r_imm(arg2, CONTEXT_REG, offsetof(SH2, drc_tmp));
2714   emith_call(dr_lookup_block);
2715   emit_block_entry();
2716   // lookup failed, call sh2_translate()
2717   emith_move_r_r(arg0, CONTEXT_REG);
2718   emith_ctx_read(arg1, offsetof(SH2, drc_tmp)); // tcache_id
2719   emith_call(sh2_translate);
2720   emit_block_entry();
2721   // sh2_translate() failed, flush cache and retry
2722   emith_ctx_read(arg0, offsetof(SH2, drc_tmp));
2723   emith_call(flush_tcache);
2724   emith_move_r_r(arg0, CONTEXT_REG);
2725   emith_ctx_read(arg1, offsetof(SH2, drc_tmp));
2726   emith_call(sh2_translate);
2727   emit_block_entry();
2728   // XXX: can't translate, fail
2729   emith_call(dr_failure);
2730
2731   // sh2_drc_test_irq(void)
2732   // assumes it's called from main function (may jump to dispatcher)
2733   sh2_drc_test_irq = (void *)tcache_ptr;
2734   emith_ctx_read(arg1, offsetof(SH2, pending_level));
2735   sr = rcache_get_reg(SHR_SR, RC_GR_READ);
2736   emith_lsr(arg0, sr, I_SHIFT);
2737   emith_and_r_imm(arg0, 0x0f);
2738   emith_cmp_r_r(arg1, arg0); // pending_level > ((sr >> 4) & 0x0f)?
2739   EMITH_SJMP_START(DCOND_GT);
2740   emith_ret_c(DCOND_LE);     // nope, return
2741   EMITH_SJMP_END(DCOND_GT);
2742   // adjust SP
2743   tmp = rcache_get_reg(SHR_SP, RC_GR_RMW);
2744   emith_sub_r_imm(tmp, 4*2);
2745   rcache_clean();
2746   // push SR
2747   tmp = rcache_get_reg_arg(0, SHR_SP);
2748   emith_add_r_imm(tmp, 4);
2749   tmp = rcache_get_reg_arg(1, SHR_SR);
2750   emith_clear_msb(tmp, tmp, 22);
2751   emith_move_r_r(arg2, CONTEXT_REG);
2752   emith_call(p32x_sh2_write32); // XXX: use sh2_drc_write32?
2753   rcache_invalidate();
2754   // push PC
2755   rcache_get_reg_arg(0, SHR_SP);
2756   emith_ctx_read(arg1, SHR_PC * 4);
2757   emith_move_r_r(arg2, CONTEXT_REG);
2758   emith_call(p32x_sh2_write32);
2759   rcache_invalidate();
2760   // update I, cycles, do callback
2761   emith_ctx_read(arg1, offsetof(SH2, pending_level));
2762   sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
2763   emith_bic_r_imm(sr, I);
2764   emith_or_r_r_lsl(sr, arg1, I_SHIFT);
2765   emith_sub_r_imm(sr, 13 << 12); // at least 13 cycles
2766   rcache_flush();
2767   emith_move_r_r(arg0, CONTEXT_REG);
2768   emith_call_ctx(offsetof(SH2, irq_callback)); // vector = sh2->irq_callback(sh2, level);
2769   // obtain new PC
2770   emith_lsl(arg0, arg0, 2);
2771   emith_ctx_read(arg1, SHR_VBR * 4);
2772   emith_add_r_r(arg0, arg1);
2773   emit_memhandler_read(2);
2774   emith_ctx_write(arg0, SHR_PC * 4);
2775 #ifdef __i386__
2776   emith_add_r_imm(xSP, 4); // fix stack
2777 #endif
2778   emith_jump(sh2_drc_dispatcher);
2779   rcache_invalidate();
2780
2781   // sh2_drc_entry(SH2 *sh2)
2782   sh2_drc_entry = (void *)tcache_ptr;
2783   emith_sh2_drc_entry();
2784   emith_move_r_r(CONTEXT_REG, arg0); // move ctx, arg0
2785   emit_do_static_regs(0, arg2);
2786   emith_call(sh2_drc_test_irq);
2787   emith_jump(sh2_drc_dispatcher);
2788
2789   // write-caused irq detection
2790   sh2_drc_write_end = tcache_ptr;
2791   emith_tst_r_r(arg0, arg0);
2792   EMITH_SJMP_START(DCOND_NE);
2793   emith_jump_ctx_c(DCOND_EQ, offsetof(SH2, drc_tmp)); // return
2794   EMITH_SJMP_END(DCOND_NE);
2795   emith_call(sh2_drc_test_irq);
2796   emith_jump_ctx(offsetof(SH2, drc_tmp));
2797
2798   // write-caused irq detection for writes in delay slot
2799   sh2_drc_write_slot_end = tcache_ptr;
2800   emith_tst_r_r(arg0, arg0);
2801   EMITH_SJMP_START(DCOND_NE);
2802   emith_jump_ctx_c(DCOND_EQ, offsetof(SH2, drc_tmp));
2803   EMITH_SJMP_END(DCOND_NE);
2804   // just burn cycles to get back to dispatcher after branch is handled
2805   sr = rcache_get_reg(SHR_SR, RC_GR_RMW);
2806   emith_ctx_write(sr, offsetof(SH2, irq_cycles));
2807   emith_clear_msb(sr, sr, 20); // clear cycles
2808   rcache_flush();
2809   emith_jump_ctx(offsetof(SH2, drc_tmp));
2810
2811   // sh2_drc_write8(u32 a, u32 d)
2812   sh2_drc_write8 = (void *)tcache_ptr;
2813   emith_ret_to_ctx(offsetof(SH2, drc_tmp));
2814   emith_ctx_read(arg2, offsetof(SH2, write8_tab));
2815   emith_sh2_wcall(arg0, arg2, sh2_drc_write_end);
2816
2817   // sh2_drc_write16(u32 a, u32 d)
2818   sh2_drc_write16 = (void *)tcache_ptr;
2819   emith_ret_to_ctx(offsetof(SH2, drc_tmp));
2820   emith_ctx_read(arg2, offsetof(SH2, write16_tab));
2821   emith_sh2_wcall(arg0, arg2, sh2_drc_write_end);
2822
2823   // sh2_drc_write8_slot(u32 a, u32 d)
2824   sh2_drc_write8_slot = (void *)tcache_ptr;
2825   emith_ret_to_ctx(offsetof(SH2, drc_tmp));
2826   emith_ctx_read(arg2, offsetof(SH2, write8_tab));
2827   emith_sh2_wcall(arg0, arg2, sh2_drc_write_slot_end);
2828
2829   // sh2_drc_write16_slot(u32 a, u32 d)
2830   sh2_drc_write16_slot = (void *)tcache_ptr;
2831   emith_ret_to_ctx(offsetof(SH2, drc_tmp));
2832   emith_ctx_read(arg2, offsetof(SH2, write16_tab));
2833   emith_sh2_wcall(arg0, arg2, sh2_drc_write_slot_end);
2834
2835 #ifdef PDB_NET
2836   // debug
2837   #define MAKE_READ_WRAPPER(func) { \
2838     void *tmp = (void *)tcache_ptr; \
2839     emith_push_ret(); \
2840     emith_call(func); \
2841     emith_ctx_read(arg2, offsetof(SH2, pdb_io_csum[0]));  \
2842     emith_addf_r_r(arg2, arg0);                           \
2843     emith_ctx_write(arg2, offsetof(SH2, pdb_io_csum[0])); \
2844     emith_ctx_read(arg2, offsetof(SH2, pdb_io_csum[1]));  \
2845     emith_adc_r_imm(arg2, 0x01000000);                    \
2846     emith_ctx_write(arg2, offsetof(SH2, pdb_io_csum[1])); \
2847     emith_pop_and_ret(); \
2848     func = tmp; \
2849   }
2850   #define MAKE_WRITE_WRAPPER(func) { \
2851     void *tmp = (void *)tcache_ptr; \
2852     emith_ctx_read(arg2, offsetof(SH2, pdb_io_csum[0]));  \
2853     emith_addf_r_r(arg2, arg1);                           \
2854     emith_ctx_write(arg2, offsetof(SH2, pdb_io_csum[0])); \
2855     emith_ctx_read(arg2, offsetof(SH2, pdb_io_csum[1]));  \
2856     emith_adc_r_imm(arg2, 0x01000000);                    \
2857     emith_ctx_write(arg2, offsetof(SH2, pdb_io_csum[1])); \
2858     emith_move_r_r(arg2, CONTEXT_REG);                    \
2859     emith_jump(func); \
2860     func = tmp; \
2861   }
2862
2863   MAKE_READ_WRAPPER(sh2_drc_read8);
2864   MAKE_READ_WRAPPER(sh2_drc_read16);
2865   MAKE_READ_WRAPPER(sh2_drc_read32);
2866   MAKE_WRITE_WRAPPER(sh2_drc_write8);
2867   MAKE_WRITE_WRAPPER(sh2_drc_write8_slot);
2868   MAKE_WRITE_WRAPPER(sh2_drc_write16);
2869   MAKE_WRITE_WRAPPER(sh2_drc_write16_slot);
2870   MAKE_WRITE_WRAPPER(sh2_drc_write32);
2871 #if (DRC_DEBUG & 4)
2872   host_dasm_new_symbol(sh2_drc_read8);
2873   host_dasm_new_symbol(sh2_drc_read16);
2874   host_dasm_new_symbol(sh2_drc_read32);
2875   host_dasm_new_symbol(sh2_drc_write32);
2876 #endif
2877 #endif
2878
2879   rcache_invalidate();
2880 #if (DRC_DEBUG & 4)
2881   host_dasm_new_symbol(sh2_drc_entry);
2882   host_dasm_new_symbol(sh2_drc_dispatcher);
2883   host_dasm_new_symbol(sh2_drc_exit);
2884   host_dasm_new_symbol(sh2_drc_test_irq);
2885   host_dasm_new_symbol(sh2_drc_write_end);
2886   host_dasm_new_symbol(sh2_drc_write_slot_end);
2887   host_dasm_new_symbol(sh2_drc_write8);
2888   host_dasm_new_symbol(sh2_drc_write8_slot);
2889   host_dasm_new_symbol(sh2_drc_write16);
2890   host_dasm_new_symbol(sh2_drc_write16_slot);
2891 #endif
2892 }
2893
2894 static void *sh2_smc_rm_block_entry(block_desc *bd, int tcache_id)
2895 {
2896   void *tmp;
2897
2898   // XXX: kill links somehow?
2899   dbg(2, "  killing entry %08x, blkid %d", bd->addr, bd - block_tables[tcache_id]);
2900   if (bd->addr == 0 || bd->tcache_ptr == NULL) {
2901     dbg(1, "  killing dead block!? %08x", bd->addr);
2902     return bd->tcache_ptr;
2903   }
2904
2905   // since we never reuse space of dead blocks,
2906   // insert jump to dispatcher for blocks that are linked to this point
2907   //emith_jump_at(bd->tcache_ptr, sh2_drc_dispatcher);
2908
2909   // attempt to handle self-modifying blocks by exiting at nearest known PC
2910   tmp = tcache_ptr;
2911   tcache_ptr = bd->tcache_ptr;
2912   emit_move_r_imm32(SHR_PC, bd->addr);
2913   rcache_flush();
2914   emith_jump(sh2_drc_dispatcher);
2915   tcache_ptr = tmp;
2916
2917   bd->addr = 0;
2918   return bd->tcache_ptr;
2919 }
2920
2921 static void sh2_smc_rm_block(u32 a, u16 *drc_ram_blk, int tcache_id, u32 shift, u32 mask)
2922 {
2923   //block_link *bl = block_links[tcache_id];
2924   //int bl_count = block_link_counts[tcache_id];
2925   block_desc *btab = block_tables[tcache_id];
2926   u16 *p = drc_ram_blk + ((a & mask) >> shift);
2927   u16 *pmax = drc_ram_blk + (mask >> shift);
2928   void *tcache_min, *tcache_max;
2929   int zeros;
2930   u16 *pt;
2931
2932   // Figure out what the main block is, as subblocks also have the flag set.
2933   // This relies on sub having single entry. It's possible that innocent
2934   // block might be hit, but that's not such a big deal.
2935   if ((p[0] >> 1) != (p[1] >> 1)) {
2936     for (; p > drc_ram_blk; p--)
2937       if (p[-1] == 0 || (p[-1] >> 1) == (*p >> 1))
2938         break;
2939   }
2940   pt = p;
2941
2942   for (; p > drc_ram_blk; p--)
2943     if ((*p & 1))
2944       break;
2945
2946   if (!(*p & 1)) {
2947     dbg(1, "smc rm: missing block start for %08x?", a);
2948     p = pt;
2949   }
2950
2951   if (*p == 0)
2952     return;
2953
2954   tcache_min = tcache_max = sh2_smc_rm_block_entry(&btab[*p >> 1], tcache_id);
2955   *p = 0;
2956
2957   for (p++, zeros = 0; p < pmax && zeros < MAX_LITERAL_OFFSET / 2; p++) {
2958     int id = *p >> 1;
2959     if (id == 0) {
2960       // there can be holes because games sometimes keep variables
2961       // directly in literal pool and we don't inline them to avoid recompile
2962       // (Star Wars Arcade)
2963       zeros++;
2964       continue;
2965     }
2966     if (*p & 1) {
2967       if (id == (p[1] >> 1))
2968         // hit other block
2969         break;
2970       tcache_max = sh2_smc_rm_block_entry(&btab[id], tcache_id);
2971     }
2972     *p = 0;
2973   }
2974
2975   host_instructions_updated(tcache_min, (void *)((char *)tcache_max + 4*4 + 4));
2976 }
2977
2978 void sh2_drc_wcheck_ram(unsigned int a, int val, int cpuid)
2979 {
2980   dbg(2, "%csh2 smc check @%08x", cpuid ? 's' : 'm', a);
2981   sh2_smc_rm_block(a, Pico32xMem->drcblk_ram, 0, SH2_DRCBLK_RAM_SHIFT, 0x3ffff);
2982 }
2983
2984 void sh2_drc_wcheck_da(unsigned int a, int val, int cpuid)
2985 {
2986   dbg(2, "%csh2 smc check @%08x", cpuid ? 's' : 'm', a);
2987   sh2_smc_rm_block(a, Pico32xMem->drcblk_da[cpuid],
2988     1 + cpuid, SH2_DRCBLK_DA_SHIFT, 0xfff);
2989 }
2990
2991 int sh2_execute(SH2 *sh2c, int cycles)
2992 {
2993   int ret_cycles;
2994
2995   sh2c->cycles_timeslice = cycles;
2996
2997   // cycles are kept in SHR_SR unused bits (upper 20)
2998   // bit11 contains T saved for delay slot
2999   // others are usual SH2 flags
3000   sh2c->sr &= 0x3f3;
3001   sh2c->sr |= cycles << 12;
3002   sh2_drc_entry(sh2c);
3003
3004   // TODO: irq cycles
3005   ret_cycles = (signed int)sh2c->sr >> 12;
3006   if (ret_cycles > 0)
3007     dbg(1, "warning: drc returned with cycles: %d", ret_cycles);
3008
3009   return sh2c->cycles_timeslice - ret_cycles;
3010 }
3011
3012 #if (DRC_DEBUG & 2)
3013 void block_stats(void)
3014 {
3015   int c, b, i, total = 0;
3016
3017   printf("block stats:\n");
3018   for (b = 0; b < ARRAY_SIZE(block_tables); b++)
3019     for (i = 0; i < block_counts[b]; i++)
3020       if (block_tables[b][i].addr != 0)
3021         total += block_tables[b][i].refcount;
3022
3023   for (c = 0; c < 10; c++) {
3024     block_desc *blk, *maxb = NULL;
3025     int max = 0;
3026     for (b = 0; b < ARRAY_SIZE(block_tables); b++) {
3027       for (i = 0; i < block_counts[b]; i++) {
3028         blk = &block_tables[b][i];
3029         if (blk->addr != 0 && blk->refcount > max) {
3030           max = blk->refcount;
3031           maxb = blk;
3032         }
3033       }
3034     }
3035     if (maxb == NULL)
3036       break;
3037     printf("%08x %9d %2.3f%%\n", maxb->addr, maxb->refcount,
3038       (double)maxb->refcount / total * 100.0);
3039     maxb->refcount = 0;
3040   }
3041
3042   for (b = 0; b < ARRAY_SIZE(block_tables); b++)
3043     for (i = 0; i < block_counts[b]; i++)
3044       block_tables[b][i].refcount = 0;
3045 }
3046 #else
3047 #define block_stats()
3048 #endif
3049
3050 void sh2_drc_flush_all(void)
3051 {
3052   block_stats();
3053   flush_tcache(0);
3054   flush_tcache(1);
3055   flush_tcache(2);
3056 }
3057
3058 void sh2_drc_mem_setup(SH2 *sh2)
3059 {
3060   // fill the convenience pointers
3061   sh2->p_bios = sh2->is_slave ? Pico32xMem->sh2_rom_s : Pico32xMem->sh2_rom_m;
3062   sh2->p_da = Pico32xMem->data_array[sh2->is_slave];
3063   sh2->p_sdram = Pico32xMem->sdram;
3064   sh2->p_rom = Pico.rom;
3065 }
3066
3067 int sh2_drc_init(SH2 *sh2)
3068 {
3069   int i;
3070
3071   if (block_tables[0] == NULL)
3072   {
3073     for (i = 0; i < TCACHE_BUFFERS; i++) {
3074       block_tables[i] = calloc(block_max_counts[i], sizeof(*block_tables[0]));
3075       if (block_tables[i] == NULL)
3076         goto fail;
3077       // max 2 block links (exits) per block
3078       block_links[i] = calloc(block_max_counts[i] * 2, sizeof(*block_links[0]));
3079       if (block_links[i] == NULL)
3080         goto fail;
3081     }
3082     memset(block_counts, 0, sizeof(block_counts));
3083     memset(block_link_counts, 0, sizeof(block_link_counts));
3084
3085     drc_cmn_init();
3086     tcache_ptr = tcache;
3087     sh2_generate_utils();
3088     host_instructions_updated(tcache, tcache_ptr);
3089
3090     tcache_bases[0] = tcache_ptrs[0] = tcache_ptr;
3091     for (i = 1; i < ARRAY_SIZE(tcache_bases); i++)
3092       tcache_bases[i] = tcache_ptrs[i] = tcache_bases[i - 1] + tcache_sizes[i - 1];
3093
3094     // tmp
3095     PicoOpt |= POPT_DIS_VDP_FIFO;
3096
3097 #if (DRC_DEBUG & 4)
3098     for (i = 0; i < ARRAY_SIZE(block_tables); i++)
3099       tcache_dsm_ptrs[i] = tcache_bases[i];
3100     // disasm the utils
3101     tcache_dsm_ptrs[0] = tcache;
3102     do_host_disasm(0);
3103 #endif
3104 #if (DRC_DEBUG & 1)
3105     hash_collisions = 0;
3106 #endif
3107   }
3108
3109   if (hash_table == NULL) {
3110     hash_table = calloc(sizeof(hash_table[0]), MAX_HASH_ENTRIES);
3111     if (hash_table == NULL)
3112       goto fail;
3113   }
3114
3115   return 0;
3116
3117 fail:
3118   sh2_drc_finish(sh2);
3119   return -1;
3120 }
3121
3122 void sh2_drc_finish(SH2 *sh2)
3123 {
3124   int i;
3125
3126   if (block_tables[0] != NULL) {
3127     block_stats();
3128
3129     for (i = 0; i < TCACHE_BUFFERS; i++) {
3130 #if (DRC_DEBUG & 4)
3131       printf("~~~ tcache %d\n", i);
3132       tcache_dsm_ptrs[i] = tcache_bases[i];
3133       tcache_ptr = tcache_ptrs[i];
3134       do_host_disasm(i);
3135 #endif
3136
3137       if (block_tables[i] != NULL)
3138         free(block_tables[i]);
3139       block_tables[i] = NULL;
3140       if (block_links[i] == NULL)
3141         free(block_links[i]);
3142       block_links[i] = NULL;
3143     }
3144
3145     drc_cmn_cleanup();
3146   }
3147
3148   if (hash_table != NULL) {
3149     free(hash_table);
3150     hash_table = NULL;
3151   }
3152 }
3153
3154 // vim:shiftwidth=2:expandtab