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