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