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