psxinterpreter: yet more exceptions, new config option
[pcsx_rearmed.git] / libpcsxcore / new_dynarec / new_dynarec.c
1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  *   Mupen64plus - new_dynarec.c                                           *
3  *   Copyright (C) 2009-2011 Ari64                                         *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
19  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
20
21 #include <stdlib.h>
22 #include <stdint.h> //include for uint64_t
23 #include <assert.h>
24 #include <errno.h>
25 #include <sys/mman.h>
26 #ifdef __MACH__
27 #include <libkern/OSCacheControl.h>
28 #endif
29 #ifdef _3DS
30 #include <3ds_utils.h>
31 #endif
32 #ifdef HAVE_LIBNX
33 #include <switch.h>
34 static Jit g_jit;
35 #endif
36
37 #include "new_dynarec_config.h"
38 #include "../psxhle.h"
39 #include "../psxinterpreter.h"
40 #include "../gte.h"
41 #include "emu_if.h" // emulator interface
42 #include "arm_features.h"
43
44 #define unused __attribute__((unused))
45 #ifdef __clang__
46 #define noinline __attribute__((noinline))
47 #else
48 #define noinline __attribute__((noinline,noclone))
49 #endif
50 #ifndef ARRAY_SIZE
51 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
52 #endif
53 #ifndef min
54 #define min(a, b) ((b) < (a) ? (b) : (a))
55 #endif
56 #ifndef max
57 #define max(a, b) ((b) > (a) ? (b) : (a))
58 #endif
59
60 //#define DISASM
61 //#define ASSEM_PRINT
62 //#define INV_DEBUG_W
63 //#define STAT_PRINT
64
65 #ifdef ASSEM_PRINT
66 #define assem_debug printf
67 #else
68 #define assem_debug(...)
69 #endif
70 //#define inv_debug printf
71 #define inv_debug(...)
72
73 #ifdef __i386__
74 #include "assem_x86.h"
75 #endif
76 #ifdef __x86_64__
77 #include "assem_x64.h"
78 #endif
79 #ifdef __arm__
80 #include "assem_arm.h"
81 #endif
82 #ifdef __aarch64__
83 #include "assem_arm64.h"
84 #endif
85
86 #define RAM_SIZE 0x200000
87 #define MAXBLOCK 4096
88 #define MAX_OUTPUT_BLOCK_SIZE 262144
89 #define EXPIRITY_OFFSET (MAX_OUTPUT_BLOCK_SIZE * 2)
90 #define PAGE_COUNT 1024
91
92 #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
93 #define INVALIDATE_USE_COND_CALL
94 #endif
95
96 #ifdef VITA
97 // apparently Vita has a 16MB limit, so either we cut tc in half,
98 // or use this hack (it's a hack because tc size was designed to be power-of-2)
99 #define TC_REDUCE_BYTES 4096
100 #else
101 #define TC_REDUCE_BYTES 0
102 #endif
103
104 struct ndrc_tramp
105 {
106   struct tramp_insns ops[2048 / sizeof(struct tramp_insns)];
107   const void *f[2048 / sizeof(void *)];
108 };
109
110 struct ndrc_mem
111 {
112   u_char translation_cache[(1 << TARGET_SIZE_2) - TC_REDUCE_BYTES];
113   struct ndrc_tramp tramp;
114 };
115
116 #ifdef BASE_ADDR_DYNAMIC
117 static struct ndrc_mem *ndrc;
118 #else
119 static struct ndrc_mem ndrc_ __attribute__((aligned(4096)));
120 static struct ndrc_mem *ndrc = &ndrc_;
121 #endif
122 #ifdef TC_WRITE_OFFSET
123 # ifdef __GLIBC__
124 # include <sys/types.h>
125 # include <sys/stat.h>
126 # include <fcntl.h>
127 # include <unistd.h>
128 # endif
129 static long ndrc_write_ofs;
130 #define NDRC_WRITE_OFFSET(x) (void *)((char *)(x) + ndrc_write_ofs)
131 #else
132 #define NDRC_WRITE_OFFSET(x) (x)
133 #endif
134
135 // stubs
136 enum stub_type {
137   CC_STUB = 1,
138   FP_STUB = 2,
139   LOADB_STUB = 3,
140   LOADH_STUB = 4,
141   LOADW_STUB = 5,
142   LOADD_STUB = 6,
143   LOADBU_STUB = 7,
144   LOADHU_STUB = 8,
145   STOREB_STUB = 9,
146   STOREH_STUB = 10,
147   STOREW_STUB = 11,
148   STORED_STUB = 12,
149   STORELR_STUB = 13,
150   INVCODE_STUB = 14,
151 };
152
153 // regmap_pre[i]    - regs before [i] insn starts; dirty things here that
154 //                    don't match .regmap will be written back
155 // [i].regmap_entry - regs that must be set up if someone jumps here
156 // [i].regmap       - regs [i] insn will read/(over)write
157 // branch_regs[i].* - same as above but for branches, takes delay slot into account
158 struct regstat
159 {
160   signed char regmap_entry[HOST_REGS];
161   signed char regmap[HOST_REGS];
162   uint64_t wasdirty;
163   uint64_t dirty;
164   uint64_t u;
165   u_int wasconst;                // before; for example 'lw r2, (r2)' wasconst is true
166   u_int isconst;                 //  ... but isconst is false when r2 is known
167   u_int loadedconst;             // host regs that have constants loaded
168   //u_int waswritten;              // MIPS regs that were used as store base before
169 };
170
171 struct ht_entry
172 {
173   u_int vaddr[2];
174   void *tcaddr[2];
175 };
176
177 struct code_stub
178 {
179   enum stub_type type;
180   void *addr;
181   void *retaddr;
182   u_int a;
183   uintptr_t b;
184   uintptr_t c;
185   u_int d;
186   u_int e;
187 };
188
189 struct link_entry
190 {
191   void *addr;
192   u_int target;
193   u_int internal;
194 };
195
196 struct block_info
197 {
198   struct block_info *next;
199   const void *source;
200   const void *copy;
201   u_int start; // vaddr of the block start
202   u_int len;   // of the whole block source
203   u_int tc_offs;
204   //u_int tc_len;
205   u_int reg_sv_flags;
206   u_char is_dirty;
207   u_char inv_near_misses;
208   u_short jump_in_cnt;
209   struct {
210     u_int vaddr;
211     void *addr;
212   } jump_in[0];
213 };
214
215 struct jump_info
216 {
217   int alloc;
218   int count;
219   struct {
220     u_int target_vaddr;
221     void *stub;
222   } e[0];
223 };
224
225 static struct decoded_insn
226 {
227   u_char itype;
228   u_char opcode;
229   u_char opcode2;
230   u_char rs1;
231   u_char rs2;
232   u_char rt1;
233   u_char rt2;
234   u_char use_lt1:1;
235   u_char bt:1;
236   u_char ooo:1;
237   u_char is_ds:1;
238   u_char is_jump:1;
239   u_char is_ujump:1;
240   u_char is_load:1;
241   u_char is_store:1;
242 } dops[MAXBLOCK];
243
244   static u_char *out;
245   static char invalid_code[0x100000];
246   static struct ht_entry hash_table[65536];
247   static struct block_info *blocks[PAGE_COUNT];
248   static struct jump_info *jumps[PAGE_COUNT];
249   static u_int start;
250   static u_int *source;
251   static uint64_t gte_rs[MAXBLOCK]; // gte: 32 data and 32 ctl regs
252   static uint64_t gte_rt[MAXBLOCK];
253   static uint64_t gte_unneeded[MAXBLOCK];
254   static u_int smrv[32]; // speculated MIPS register values
255   static u_int smrv_strong; // mask or regs that are likely to have correct values
256   static u_int smrv_weak; // same, but somewhat less likely
257   static u_int smrv_strong_next; // same, but after current insn executes
258   static u_int smrv_weak_next;
259   static int imm[MAXBLOCK];
260   static u_int ba[MAXBLOCK];
261   static uint64_t unneeded_reg[MAXBLOCK];
262   static uint64_t branch_unneeded_reg[MAXBLOCK];
263   // see 'struct regstat' for a description
264   static signed char regmap_pre[MAXBLOCK][HOST_REGS];
265   // contains 'real' consts at [i] insn, but may differ from what's actually
266   // loaded in host reg as 'final' value is always loaded, see get_final_value()
267   static uint32_t current_constmap[HOST_REGS];
268   static uint32_t constmap[MAXBLOCK][HOST_REGS];
269   static struct regstat regs[MAXBLOCK];
270   static struct regstat branch_regs[MAXBLOCK];
271   static signed char minimum_free_regs[MAXBLOCK];
272   static int ccadj[MAXBLOCK];
273   static int slen;
274   static void *instr_addr[MAXBLOCK];
275   static struct link_entry link_addr[MAXBLOCK];
276   static int linkcount;
277   static struct code_stub stubs[MAXBLOCK*3];
278   static int stubcount;
279   static u_int literals[1024][2];
280   static int literalcount;
281   static int is_delayslot;
282   static char shadow[1048576]  __attribute__((aligned(16)));
283   static void *copy;
284   static u_int expirep;
285   static u_int stop_after_jal;
286   static u_int f1_hack;
287 #ifdef STAT_PRINT
288   static int stat_bc_direct;
289   static int stat_bc_pre;
290   static int stat_bc_restore;
291   static int stat_ht_lookups;
292   static int stat_jump_in_lookups;
293   static int stat_restore_tries;
294   static int stat_restore_compares;
295   static int stat_inv_addr_calls;
296   static int stat_inv_hits;
297   static int stat_blocks;
298   static int stat_links;
299   #define stat_inc(s) s++
300   #define stat_dec(s) s--
301   #define stat_clear(s) s = 0
302 #else
303   #define stat_inc(s)
304   #define stat_dec(s)
305   #define stat_clear(s)
306 #endif
307
308   int new_dynarec_hacks;
309   int new_dynarec_hacks_pergame;
310   int new_dynarec_hacks_old;
311   int new_dynarec_did_compile;
312
313   #define HACK_ENABLED(x) ((new_dynarec_hacks | new_dynarec_hacks_pergame) & (x))
314
315   extern int cycle_count; // ... until end of the timeslice, counts -N -> 0
316   extern int last_count;  // last absolute target, often = next_interupt
317   extern int pcaddr;
318   extern int pending_exception;
319   extern int branch_target;
320   extern uintptr_t ram_offset;
321   extern uintptr_t mini_ht[32][2];
322
323   /* registers that may be allocated */
324   /* 1-31 gpr */
325 #define LOREG 32 // lo
326 #define HIREG 33 // hi
327 //#define FSREG 34 // FPU status (FCSR)
328 #define CSREG 35 // Coprocessor status
329 #define CCREG 36 // Cycle count
330 #define INVCP 37 // Pointer to invalid_code
331 //#define MMREG 38 // Pointer to memory_map
332 #define ROREG 39 // ram offset (if rdram!=0x80000000)
333 #define TEMPREG 40
334 #define FTEMP 40 // FPU temporary register
335 #define PTEMP 41 // Prefetch temporary register
336 //#define TLREG 42 // TLB mapping offset
337 #define RHASH 43 // Return address hash
338 #define RHTBL 44 // Return address hash table address
339 #define RTEMP 45 // JR/JALR address register
340 #define MAXREG 45
341 #define AGEN1 46 // Address generation temporary register
342 //#define AGEN2 47 // Address generation temporary register
343 //#define MGEN1 48 // Maptable address generation temporary register
344 //#define MGEN2 49 // Maptable address generation temporary register
345 #define BTREG 50 // Branch target temporary register
346
347   /* instruction types */
348 #define NOP 0     // No operation
349 #define LOAD 1    // Load
350 #define STORE 2   // Store
351 #define LOADLR 3  // Unaligned load
352 #define STORELR 4 // Unaligned store
353 #define MOV 5     // Move
354 #define ALU 6     // Arithmetic/logic
355 #define MULTDIV 7 // Multiply/divide
356 #define SHIFT 8   // Shift by register
357 #define SHIFTIMM 9// Shift by immediate
358 #define IMM16 10  // 16-bit immediate
359 #define RJUMP 11  // Unconditional jump to register
360 #define UJUMP 12  // Unconditional jump
361 #define CJUMP 13  // Conditional branch (BEQ/BNE/BGTZ/BLEZ)
362 #define SJUMP 14  // Conditional branch (regimm format)
363 #define COP0 15   // Coprocessor 0
364 #define COP1 16   // Coprocessor 1
365 #define C1LS 17   // Coprocessor 1 load/store
366 //#define FJUMP 18  // Conditional branch (floating point)
367 //#define FLOAT 19  // Floating point unit
368 //#define FCONV 20  // Convert integer to float
369 //#define FCOMP 21  // Floating point compare (sets FSREG)
370 #define SYSCALL 22// SYSCALL,BREAK
371 #define OTHER 23  // Other
372 //#define SPAN 24   // Branch/delay slot spans 2 pages
373 #define NI 25     // Not implemented
374 #define HLECALL 26// PCSX fake opcodes for HLE
375 #define COP2 27   // Coprocessor 2 move
376 #define C2LS 28   // Coprocessor 2 load/store
377 #define C2OP 29   // Coprocessor 2 operation
378 #define INTCALL 30// Call interpreter to handle rare corner cases
379
380   /* branch codes */
381 #define TAKEN 1
382 #define NOTTAKEN 2
383 #define NULLDS 3
384
385 #define DJT_1 (void *)1l // no function, just a label in assem_debug log
386 #define DJT_2 (void *)2l
387
388 // asm linkage
389 void dyna_linker();
390 void cc_interrupt();
391 void fp_exception();
392 void fp_exception_ds();
393 void jump_syscall   (u_int u0, u_int u1, u_int pc);
394 void jump_syscall_ds(u_int u0, u_int u1, u_int pc);
395 void jump_break   (u_int u0, u_int u1, u_int pc);
396 void jump_break_ds(u_int u0, u_int u1, u_int pc);
397 void jump_to_new_pc();
398 void call_gteStall();
399 void new_dyna_leave();
400
401 void *ndrc_get_addr_ht_param(u_int vaddr, int can_compile);
402 void *ndrc_get_addr_ht(u_int vaddr);
403 void ndrc_add_jump_out(u_int vaddr, void *src);
404 void ndrc_write_invalidate_one(u_int addr);
405 static void ndrc_write_invalidate_many(u_int addr, u_int end);
406
407 static int new_recompile_block(u_int addr);
408 static void invalidate_block(struct block_info *block);
409
410 // Needed by assembler
411 static void wb_register(signed char r, const signed char regmap[], uint64_t dirty);
412 static void wb_dirtys(const signed char i_regmap[], uint64_t i_dirty);
413 static void wb_needed_dirtys(const signed char i_regmap[], uint64_t i_dirty, int addr);
414 static void load_all_regs(const signed char i_regmap[]);
415 static void load_needed_regs(const signed char i_regmap[], const signed char next_regmap[]);
416 static void load_regs_entry(int t);
417 static void load_all_consts(const signed char regmap[], u_int dirty, int i);
418 static u_int get_host_reglist(const signed char *regmap);
419
420 static int get_final_value(int hr, int i, int *value);
421 static void add_stub(enum stub_type type, void *addr, void *retaddr,
422   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e);
423 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
424   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist);
425 static void add_to_linker(void *addr, u_int target, int ext);
426 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
427   int addr, int *offset_reg, int *addr_reg_override);
428 static void *get_direct_memhandler(void *table, u_int addr,
429   enum stub_type type, uintptr_t *addr_host);
430 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist);
431 static void pass_args(int a0, int a1);
432 static void emit_far_jump(const void *f);
433 static void emit_far_call(const void *f);
434
435 #ifdef VITA
436 #include <psp2/kernel/sysmem.h>
437 static int sceBlock;
438 // note: this interacts with RetroArch's Vita bootstrap code: bootstrap/vita/sbrk.c
439 extern int getVMBlock();
440 int _newlib_vm_size_user = sizeof(*ndrc);
441 #endif
442
443 static void mprotect_w_x(void *start, void *end, int is_x)
444 {
445 #ifdef NO_WRITE_EXEC
446   #if defined(VITA)
447   // *Open* enables write on all memory that was
448   // allocated by sceKernelAllocMemBlockForVM()?
449   if (is_x)
450     sceKernelCloseVMDomain();
451   else
452     sceKernelOpenVMDomain();
453   #elif defined(HAVE_LIBNX)
454   Result rc;
455   // check to avoid the full flush in jitTransitionToExecutable()
456   if (g_jit.type != JitType_CodeMemory) {
457     if (is_x)
458       rc = jitTransitionToExecutable(&g_jit);
459     else
460       rc = jitTransitionToWritable(&g_jit);
461     if (R_FAILED(rc))
462       ;//SysPrintf("jitTransition %d %08x\n", is_x, rc);
463   }
464   #elif defined(TC_WRITE_OFFSET)
465   // separated rx and rw areas are always available
466   #else
467   u_long mstart = (u_long)start & ~4095ul;
468   u_long mend = (u_long)end;
469   if (mprotect((void *)mstart, mend - mstart,
470                PROT_READ | (is_x ? PROT_EXEC : PROT_WRITE)) != 0)
471     SysPrintf("mprotect(%c) failed: %s\n", is_x ? 'x' : 'w', strerror(errno));
472   #endif
473 #endif
474 }
475
476 static void start_tcache_write(void *start, void *end)
477 {
478   mprotect_w_x(start, end, 0);
479 }
480
481 static void end_tcache_write(void *start, void *end)
482 {
483 #if defined(__arm__) || defined(__aarch64__)
484   size_t len = (char *)end - (char *)start;
485   #if   defined(__BLACKBERRY_QNX__)
486   msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
487   #elif defined(__MACH__)
488   sys_cache_control(kCacheFunctionPrepareForExecution, start, len);
489   #elif defined(VITA)
490   sceKernelSyncVMDomain(sceBlock, start, len);
491   #elif defined(_3DS)
492   ctr_flush_invalidate_cache();
493   #elif defined(HAVE_LIBNX)
494   if (g_jit.type == JitType_CodeMemory) {
495     armDCacheClean(start, len);
496     armICacheInvalidate((char *)start - ndrc_write_ofs, len);
497     // as of v4.2.1 libnx lacks isb
498     __asm__ volatile("isb" ::: "memory");
499   }
500   #elif defined(__aarch64__)
501   // as of 2021, __clear_cache() is still broken on arm64
502   // so here is a custom one :(
503   clear_cache_arm64(start, end);
504   #else
505   __clear_cache(start, end);
506   #endif
507   (void)len;
508 #endif
509
510   mprotect_w_x(start, end, 1);
511 }
512
513 static void *start_block(void)
514 {
515   u_char *end = out + MAX_OUTPUT_BLOCK_SIZE;
516   if (end > ndrc->translation_cache + sizeof(ndrc->translation_cache))
517     end = ndrc->translation_cache + sizeof(ndrc->translation_cache);
518   start_tcache_write(NDRC_WRITE_OFFSET(out), NDRC_WRITE_OFFSET(end));
519   return out;
520 }
521
522 static void end_block(void *start)
523 {
524   end_tcache_write(NDRC_WRITE_OFFSET(start), NDRC_WRITE_OFFSET(out));
525 }
526
527 #ifdef NDRC_CACHE_FLUSH_ALL
528
529 static int needs_clear_cache;
530
531 static void mark_clear_cache(void *target)
532 {
533   if (!needs_clear_cache) {
534     start_tcache_write(NDRC_WRITE_OFFSET(ndrc), NDRC_WRITE_OFFSET(ndrc + 1));
535     needs_clear_cache = 1;
536   }
537 }
538
539 static void do_clear_cache(void)
540 {
541   if (needs_clear_cache) {
542     end_tcache_write(NDRC_WRITE_OFFSET(ndrc), NDRC_WRITE_OFFSET(ndrc + 1));
543     needs_clear_cache = 0;
544   }
545 }
546
547 #else
548
549 // also takes care of w^x mappings when patching code
550 static u_int needs_clear_cache[1<<(TARGET_SIZE_2-17)];
551
552 static void mark_clear_cache(void *target)
553 {
554   uintptr_t offset = (u_char *)target - ndrc->translation_cache;
555   u_int mask = 1u << ((offset >> 12) & 31);
556   if (!(needs_clear_cache[offset >> 17] & mask)) {
557     char *start = (char *)NDRC_WRITE_OFFSET((uintptr_t)target & ~4095l);
558     start_tcache_write(start, start + 4095);
559     needs_clear_cache[offset >> 17] |= mask;
560   }
561 }
562
563 // Clearing the cache is rather slow on ARM Linux, so mark the areas
564 // that need to be cleared, and then only clear these areas once.
565 static void do_clear_cache(void)
566 {
567   int i, j;
568   for (i = 0; i < (1<<(TARGET_SIZE_2-17)); i++)
569   {
570     u_int bitmap = needs_clear_cache[i];
571     if (!bitmap)
572       continue;
573     for (j = 0; j < 32; j++)
574     {
575       u_char *start, *end;
576       if (!(bitmap & (1u << j)))
577         continue;
578
579       start = ndrc->translation_cache + i*131072 + j*4096;
580       end = start + 4095;
581       for (j++; j < 32; j++) {
582         if (!(bitmap & (1u << j)))
583           break;
584         end += 4096;
585       }
586       end_tcache_write(NDRC_WRITE_OFFSET(start), NDRC_WRITE_OFFSET(end));
587     }
588     needs_clear_cache[i] = 0;
589   }
590 }
591
592 #endif // NDRC_CACHE_FLUSH_ALL
593
594 #define NO_CYCLE_PENALTY_THR 12
595
596 int cycle_multiplier_old;
597 static int cycle_multiplier_active;
598
599 static int CLOCK_ADJUST(int x)
600 {
601   int m = cycle_multiplier_active;
602   int s = (x >> 31) | 1;
603   return (x * m + s * 50) / 100;
604 }
605
606 static int ds_writes_rjump_rs(int i)
607 {
608   return dops[i].rs1 != 0 && (dops[i].rs1 == dops[i+1].rt1 || dops[i].rs1 == dops[i+1].rt2);
609 }
610
611 // psx addr mirror masking (for invalidation)
612 static u_int pmmask(u_int vaddr)
613 {
614   vaddr &= ~0xe0000000;
615   if (vaddr < 0x01000000)
616     vaddr &= ~0x00e00000; // RAM mirrors
617   return vaddr;
618 }
619
620 static u_int get_page(u_int vaddr)
621 {
622   u_int page = pmmask(vaddr) >> 12;
623   if (page >= PAGE_COUNT / 2)
624     page = PAGE_COUNT / 2 + (page & (PAGE_COUNT / 2 - 1));
625   return page;
626 }
627
628 // get a page for looking for a block that has vaddr
629 // (needed because the block may start in previous page)
630 static u_int get_page_prev(u_int vaddr)
631 {
632   assert(MAXBLOCK <= (1 << 12));
633   u_int page = get_page(vaddr);
634   if (page & 511)
635     page--;
636   return page;
637 }
638
639 static struct ht_entry *hash_table_get(u_int vaddr)
640 {
641   return &hash_table[((vaddr>>16)^vaddr)&0xFFFF];
642 }
643
644 static void hash_table_add(u_int vaddr, void *tcaddr)
645 {
646   struct ht_entry *ht_bin = hash_table_get(vaddr);
647   assert(tcaddr);
648   ht_bin->vaddr[1] = ht_bin->vaddr[0];
649   ht_bin->tcaddr[1] = ht_bin->tcaddr[0];
650   ht_bin->vaddr[0] = vaddr;
651   ht_bin->tcaddr[0] = tcaddr;
652 }
653
654 static void hash_table_remove(int vaddr)
655 {
656   //printf("remove hash: %x\n",vaddr);
657   struct ht_entry *ht_bin = hash_table_get(vaddr);
658   if (ht_bin->vaddr[1] == vaddr) {
659     ht_bin->vaddr[1] = -1;
660     ht_bin->tcaddr[1] = NULL;
661   }
662   if (ht_bin->vaddr[0] == vaddr) {
663     ht_bin->vaddr[0] = ht_bin->vaddr[1];
664     ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
665     ht_bin->vaddr[1] = -1;
666     ht_bin->tcaddr[1] = NULL;
667   }
668 }
669
670 static void mark_invalid_code(u_int vaddr, u_int len, char invalid)
671 {
672   u_int vaddr_m = vaddr & 0x1fffffff;
673   u_int i, j;
674   for (i = vaddr_m & ~0xfff; i < vaddr_m + len; i += 0x1000) {
675     // ram mirrors, but should not hurt bios
676     for (j = 0; j < 0x800000; j += 0x200000) {
677       invalid_code[(i|j) >> 12] =
678       invalid_code[(i|j|0x80000000u) >> 12] =
679       invalid_code[(i|j|0xa0000000u) >> 12] = invalid;
680     }
681   }
682   if (!invalid && vaddr + len > inv_code_start && vaddr <= inv_code_end)
683     inv_code_start = inv_code_end = ~0;
684 }
685
686 static int doesnt_expire_soon(u_char *tcaddr)
687 {
688   u_int diff = (u_int)(tcaddr - out) & ((1u << TARGET_SIZE_2) - 1u);
689   return diff > EXPIRITY_OFFSET + MAX_OUTPUT_BLOCK_SIZE;
690 }
691
692 static unused void check_for_block_changes(u_int start, u_int end)
693 {
694   u_int start_page = get_page_prev(start);
695   u_int end_page = get_page(end - 1);
696   u_int page;
697
698   for (page = start_page; page <= end_page; page++) {
699     struct block_info *block;
700     for (block = blocks[page]; block != NULL; block = block->next) {
701       if (block->is_dirty)
702         continue;
703       if (memcmp(block->source, block->copy, block->len)) {
704         printf("bad block %08x-%08x %016llx %016llx @%08x\n",
705           block->start, block->start + block->len,
706           *(long long *)block->source, *(long long *)block->copy, psxRegs.pc);
707         fflush(stdout);
708         abort();
709       }
710     }
711   }
712 }
713
714 static void *try_restore_block(u_int vaddr, u_int start_page, u_int end_page)
715 {
716   void *found_clean = NULL;
717   u_int i, page;
718
719   stat_inc(stat_restore_tries);
720   for (page = start_page; page <= end_page; page++) {
721     struct block_info *block;
722     for (block = blocks[page]; block != NULL; block = block->next) {
723       if (vaddr < block->start)
724         break;
725       if (!block->is_dirty || vaddr >= block->start + block->len)
726         continue;
727       for (i = 0; i < block->jump_in_cnt; i++)
728         if (block->jump_in[i].vaddr == vaddr)
729           break;
730       if (i == block->jump_in_cnt)
731         continue;
732       assert(block->source && block->copy);
733       stat_inc(stat_restore_compares);
734       if (memcmp(block->source, block->copy, block->len))
735         continue;
736
737       block->is_dirty = block->inv_near_misses = 0;
738       found_clean = block->jump_in[i].addr;
739       hash_table_add(vaddr, found_clean);
740       mark_invalid_code(block->start, block->len, 0);
741       stat_inc(stat_bc_restore);
742       inv_debug("INV: restored %08x %p (%d)\n", vaddr, found_clean, block->jump_in_cnt);
743       return found_clean;
744     }
745   }
746   return NULL;
747 }
748
749 // Get address from virtual address
750 // This is called from the recompiled JR/JALR instructions
751 static void noinline *get_addr(u_int vaddr, int can_compile)
752 {
753   u_int start_page = get_page_prev(vaddr);
754   u_int i, page, end_page = get_page(vaddr);
755   void *found_clean = NULL;
756
757   stat_inc(stat_jump_in_lookups);
758   for (page = start_page; page <= end_page; page++) {
759     const struct block_info *block;
760     for (block = blocks[page]; block != NULL; block = block->next) {
761       if (vaddr < block->start)
762         break;
763       if (block->is_dirty || vaddr >= block->start + block->len)
764         continue;
765       for (i = 0; i < block->jump_in_cnt; i++)
766         if (block->jump_in[i].vaddr == vaddr)
767           break;
768       if (i == block->jump_in_cnt)
769         continue;
770       found_clean = block->jump_in[i].addr;
771       hash_table_add(vaddr, found_clean);
772       return found_clean;
773     }
774   }
775   found_clean = try_restore_block(vaddr, start_page, end_page);
776   if (found_clean)
777     return found_clean;
778
779   if (!can_compile)
780     return NULL;
781
782   int r = new_recompile_block(vaddr);
783   if (r == 0)
784     return ndrc_get_addr_ht(vaddr);
785
786   // generate an address error
787   psxRegs.CP0.n.SR |= 2;
788   psxRegs.CP0.n.Cause = (vaddr<<31) | (4<<2);
789   psxRegs.CP0.n.EPC = (vaddr&1) ? vaddr-5 : vaddr;
790   psxRegs.CP0.n.BadVAddr = vaddr & ~1;
791   return ndrc_get_addr_ht(0x80000080);
792 }
793
794 // Look up address in hash table first
795 void *ndrc_get_addr_ht_param(u_int vaddr, int can_compile)
796 {
797   //check_for_block_changes(vaddr, vaddr + MAXBLOCK);
798   const struct ht_entry *ht_bin = hash_table_get(vaddr);
799   stat_inc(stat_ht_lookups);
800   if (ht_bin->vaddr[0] == vaddr) return ht_bin->tcaddr[0];
801   if (ht_bin->vaddr[1] == vaddr) return ht_bin->tcaddr[1];
802   return get_addr(vaddr, can_compile);
803 }
804
805 void *ndrc_get_addr_ht(u_int vaddr)
806 {
807   return ndrc_get_addr_ht_param(vaddr, 1);
808 }
809
810 static void clear_all_regs(signed char regmap[])
811 {
812   memset(regmap, -1, sizeof(regmap[0]) * HOST_REGS);
813 }
814
815 // get_reg: get allocated host reg from mips reg
816 // returns -1 if no such mips reg was allocated
817 #if defined(__arm__) && defined(HAVE_ARMV6) && HOST_REGS == 13 && EXCLUDE_REG == 11
818
819 extern signed char get_reg(const signed char regmap[], signed char r);
820
821 #else
822
823 static signed char get_reg(const signed char regmap[], signed char r)
824 {
825   int hr;
826   for (hr = 0; hr < HOST_REGS; hr++) {
827     if (hr == EXCLUDE_REG)
828       continue;
829     if (regmap[hr] == r)
830       return hr;
831   }
832   return -1;
833 }
834
835 #endif
836
837 // get reg as mask bit (1 << hr)
838 static u_int get_regm(const signed char regmap[], signed char r)
839 {
840   return (1u << (get_reg(regmap, r) & 31)) & ~(1u << 31);
841 }
842
843 static signed char get_reg_temp(const signed char regmap[])
844 {
845   int hr;
846   for (hr = 0; hr < HOST_REGS; hr++) {
847     if (hr == EXCLUDE_REG)
848       continue;
849     if (regmap[hr] == (signed char)-1)
850       return hr;
851   }
852   return -1;
853 }
854
855 // Find a register that is available for two consecutive cycles
856 static signed char get_reg2(signed char regmap1[], const signed char regmap2[], int r)
857 {
858   int hr;
859   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap1[hr]==r&&regmap2[hr]==r) return hr;
860   return -1;
861 }
862
863 // reverse reg map: mips -> host
864 #define RRMAP_SIZE 64
865 static void make_rregs(const signed char regmap[], signed char rrmap[RRMAP_SIZE],
866   u_int *regs_can_change)
867 {
868   u_int r, hr, hr_can_change = 0;
869   memset(rrmap, -1, RRMAP_SIZE);
870   for (hr = 0; hr < HOST_REGS; )
871   {
872     r = regmap[hr];
873     rrmap[r & (RRMAP_SIZE - 1)] = hr;
874     // only add mips $1-$31+$lo, others shifted out
875     hr_can_change |= (uint64_t)1 << (hr + ((r - 1) & 32));
876     hr++;
877     if (hr == EXCLUDE_REG)
878       hr++;
879   }
880   hr_can_change |= 1u << (rrmap[33] & 31);
881   hr_can_change |= 1u << (rrmap[CCREG] & 31);
882   hr_can_change &= ~(1u << 31);
883   *regs_can_change = hr_can_change;
884 }
885
886 // same as get_reg, but takes rrmap
887 static signed char get_rreg(signed char rrmap[RRMAP_SIZE], signed char r)
888 {
889   assert(0 <= r && r < RRMAP_SIZE);
890   return rrmap[r];
891 }
892
893 static int count_free_regs(const signed char regmap[])
894 {
895   int count=0;
896   int hr;
897   for(hr=0;hr<HOST_REGS;hr++)
898   {
899     if(hr!=EXCLUDE_REG) {
900       if(regmap[hr]<0) count++;
901     }
902   }
903   return count;
904 }
905
906 static void dirty_reg(struct regstat *cur, signed char reg)
907 {
908   int hr;
909   if (!reg) return;
910   hr = get_reg(cur->regmap, reg);
911   if (hr >= 0)
912     cur->dirty |= 1<<hr;
913 }
914
915 static void set_const(struct regstat *cur, signed char reg, uint32_t value)
916 {
917   int hr;
918   if (!reg) return;
919   hr = get_reg(cur->regmap, reg);
920   if (hr >= 0) {
921     cur->isconst |= 1<<hr;
922     current_constmap[hr] = value;
923   }
924 }
925
926 static void clear_const(struct regstat *cur, signed char reg)
927 {
928   int hr;
929   if (!reg) return;
930   hr = get_reg(cur->regmap, reg);
931   if (hr >= 0)
932     cur->isconst &= ~(1<<hr);
933 }
934
935 static int is_const(const struct regstat *cur, signed char reg)
936 {
937   int hr;
938   if (reg < 0) return 0;
939   if (!reg) return 1;
940   hr = get_reg(cur->regmap, reg);
941   if (hr >= 0)
942     return (cur->isconst>>hr)&1;
943   return 0;
944 }
945
946 static uint32_t get_const(const struct regstat *cur, signed char reg)
947 {
948   int hr;
949   if (!reg) return 0;
950   hr = get_reg(cur->regmap, reg);
951   if (hr >= 0)
952     return current_constmap[hr];
953
954   SysPrintf("Unknown constant in r%d\n", reg);
955   abort();
956 }
957
958 // Least soon needed registers
959 // Look at the next ten instructions and see which registers
960 // will be used.  Try not to reallocate these.
961 static void lsn(u_char hsn[], int i, int *preferred_reg)
962 {
963   int j;
964   int b=-1;
965   for(j=0;j<9;j++)
966   {
967     if(i+j>=slen) {
968       j=slen-i-1;
969       break;
970     }
971     if (dops[i+j].is_ujump)
972     {
973       // Don't go past an unconditonal jump
974       j++;
975       break;
976     }
977   }
978   for(;j>=0;j--)
979   {
980     if(dops[i+j].rs1) hsn[dops[i+j].rs1]=j;
981     if(dops[i+j].rs2) hsn[dops[i+j].rs2]=j;
982     if(dops[i+j].rt1) hsn[dops[i+j].rt1]=j;
983     if(dops[i+j].rt2) hsn[dops[i+j].rt2]=j;
984     if(dops[i+j].itype==STORE || dops[i+j].itype==STORELR) {
985       // Stores can allocate zero
986       hsn[dops[i+j].rs1]=j;
987       hsn[dops[i+j].rs2]=j;
988     }
989     if (ram_offset && (dops[i+j].is_load || dops[i+j].is_store))
990       hsn[ROREG] = j;
991     // On some architectures stores need invc_ptr
992     #if defined(HOST_IMM8)
993     if (dops[i+j].is_store)
994       hsn[INVCP] = j;
995     #endif
996     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
997     {
998       hsn[CCREG]=j;
999       b=j;
1000     }
1001   }
1002   if(b>=0)
1003   {
1004     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
1005     {
1006       // Follow first branch
1007       int t=(ba[i+b]-start)>>2;
1008       j=7-b;if(t+j>=slen) j=slen-t-1;
1009       for(;j>=0;j--)
1010       {
1011         if(dops[t+j].rs1) if(hsn[dops[t+j].rs1]>j+b+2) hsn[dops[t+j].rs1]=j+b+2;
1012         if(dops[t+j].rs2) if(hsn[dops[t+j].rs2]>j+b+2) hsn[dops[t+j].rs2]=j+b+2;
1013         //if(dops[t+j].rt1) if(hsn[dops[t+j].rt1]>j+b+2) hsn[dops[t+j].rt1]=j+b+2;
1014         //if(dops[t+j].rt2) if(hsn[dops[t+j].rt2]>j+b+2) hsn[dops[t+j].rt2]=j+b+2;
1015       }
1016     }
1017     // TODO: preferred register based on backward branch
1018   }
1019   // Delay slot should preferably not overwrite branch conditions or cycle count
1020   if (i > 0 && dops[i-1].is_jump) {
1021     if(dops[i-1].rs1) if(hsn[dops[i-1].rs1]>1) hsn[dops[i-1].rs1]=1;
1022     if(dops[i-1].rs2) if(hsn[dops[i-1].rs2]>1) hsn[dops[i-1].rs2]=1;
1023     hsn[CCREG]=1;
1024     // ...or hash tables
1025     hsn[RHASH]=1;
1026     hsn[RHTBL]=1;
1027   }
1028   // Coprocessor load/store needs FTEMP, even if not declared
1029   if(dops[i].itype==C2LS) {
1030     hsn[FTEMP]=0;
1031   }
1032   // Load L/R also uses FTEMP as a temporary register
1033   if(dops[i].itype==LOADLR) {
1034     hsn[FTEMP]=0;
1035   }
1036   // Also SWL/SWR/SDL/SDR
1037   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) {
1038     hsn[FTEMP]=0;
1039   }
1040   // Don't remove the miniht registers
1041   if(dops[i].itype==UJUMP||dops[i].itype==RJUMP)
1042   {
1043     hsn[RHASH]=0;
1044     hsn[RHTBL]=0;
1045   }
1046 }
1047
1048 // We only want to allocate registers if we're going to use them again soon
1049 static int needed_again(int r, int i)
1050 {
1051   int j;
1052   int b=-1;
1053   int rn=10;
1054
1055   if (i > 0 && dops[i-1].is_ujump)
1056   {
1057     if(ba[i-1]<start || ba[i-1]>start+slen*4-4)
1058       return 0; // Don't need any registers if exiting the block
1059   }
1060   for(j=0;j<9;j++)
1061   {
1062     if(i+j>=slen) {
1063       j=slen-i-1;
1064       break;
1065     }
1066     if (dops[i+j].is_ujump)
1067     {
1068       // Don't go past an unconditonal jump
1069       j++;
1070       break;
1071     }
1072     if(dops[i+j].itype==SYSCALL||dops[i+j].itype==HLECALL||dops[i+j].itype==INTCALL||((source[i+j]&0xfc00003f)==0x0d))
1073     {
1074       break;
1075     }
1076   }
1077   for(;j>=1;j--)
1078   {
1079     if(dops[i+j].rs1==r) rn=j;
1080     if(dops[i+j].rs2==r) rn=j;
1081     if((unneeded_reg[i+j]>>r)&1) rn=10;
1082     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
1083     {
1084       b=j;
1085     }
1086   }
1087   if(rn<10) return 1;
1088   (void)b;
1089   return 0;
1090 }
1091
1092 // Try to match register allocations at the end of a loop with those
1093 // at the beginning
1094 static int loop_reg(int i, int r, int hr)
1095 {
1096   int j,k;
1097   for(j=0;j<9;j++)
1098   {
1099     if(i+j>=slen) {
1100       j=slen-i-1;
1101       break;
1102     }
1103     if (dops[i+j].is_ujump)
1104     {
1105       // Don't go past an unconditonal jump
1106       j++;
1107       break;
1108     }
1109   }
1110   k=0;
1111   if(i>0){
1112     if(dops[i-1].itype==UJUMP||dops[i-1].itype==CJUMP||dops[i-1].itype==SJUMP)
1113       k--;
1114   }
1115   for(;k<j;k++)
1116   {
1117     assert(r < 64);
1118     if((unneeded_reg[i+k]>>r)&1) return hr;
1119     if(i+k>=0&&(dops[i+k].itype==UJUMP||dops[i+k].itype==CJUMP||dops[i+k].itype==SJUMP))
1120     {
1121       if(ba[i+k]>=start && ba[i+k]<(start+i*4))
1122       {
1123         int t=(ba[i+k]-start)>>2;
1124         int reg=get_reg(regs[t].regmap_entry,r);
1125         if(reg>=0) return reg;
1126         //reg=get_reg(regs[t+1].regmap_entry,r);
1127         //if(reg>=0) return reg;
1128       }
1129     }
1130   }
1131   return hr;
1132 }
1133
1134
1135 // Allocate every register, preserving source/target regs
1136 static void alloc_all(struct regstat *cur,int i)
1137 {
1138   int hr;
1139
1140   for(hr=0;hr<HOST_REGS;hr++) {
1141     if(hr!=EXCLUDE_REG) {
1142       if((cur->regmap[hr]!=dops[i].rs1)&&(cur->regmap[hr]!=dops[i].rs2)&&
1143          (cur->regmap[hr]!=dops[i].rt1)&&(cur->regmap[hr]!=dops[i].rt2))
1144       {
1145         cur->regmap[hr]=-1;
1146         cur->dirty&=~(1<<hr);
1147       }
1148       // Don't need zeros
1149       if(cur->regmap[hr]==0)
1150       {
1151         cur->regmap[hr]=-1;
1152         cur->dirty&=~(1<<hr);
1153       }
1154     }
1155   }
1156 }
1157
1158 #ifndef NDEBUG
1159 static int host_tempreg_in_use;
1160
1161 static void host_tempreg_acquire(void)
1162 {
1163   assert(!host_tempreg_in_use);
1164   host_tempreg_in_use = 1;
1165 }
1166
1167 static void host_tempreg_release(void)
1168 {
1169   host_tempreg_in_use = 0;
1170 }
1171 #else
1172 static void host_tempreg_acquire(void) {}
1173 static void host_tempreg_release(void) {}
1174 #endif
1175
1176 #ifdef ASSEM_PRINT
1177 extern void gen_interupt();
1178 extern void do_insn_cmp();
1179 #define FUNCNAME(f) { f, " " #f }
1180 static const struct {
1181   void *addr;
1182   const char *name;
1183 } function_names[] = {
1184   FUNCNAME(cc_interrupt),
1185   FUNCNAME(gen_interupt),
1186   FUNCNAME(ndrc_get_addr_ht),
1187   FUNCNAME(jump_handler_read8),
1188   FUNCNAME(jump_handler_read16),
1189   FUNCNAME(jump_handler_read32),
1190   FUNCNAME(jump_handler_write8),
1191   FUNCNAME(jump_handler_write16),
1192   FUNCNAME(jump_handler_write32),
1193   FUNCNAME(ndrc_write_invalidate_one),
1194   FUNCNAME(ndrc_write_invalidate_many),
1195   FUNCNAME(jump_to_new_pc),
1196   FUNCNAME(jump_break),
1197   FUNCNAME(jump_break_ds),
1198   FUNCNAME(jump_syscall),
1199   FUNCNAME(jump_syscall_ds),
1200   FUNCNAME(call_gteStall),
1201   FUNCNAME(new_dyna_leave),
1202   FUNCNAME(pcsx_mtc0),
1203   FUNCNAME(pcsx_mtc0_ds),
1204 #ifdef DRC_DBG
1205   FUNCNAME(do_insn_cmp),
1206 #endif
1207 };
1208
1209 static const char *func_name(const void *a)
1210 {
1211   int i;
1212   for (i = 0; i < sizeof(function_names)/sizeof(function_names[0]); i++)
1213     if (function_names[i].addr == a)
1214       return function_names[i].name;
1215   return "";
1216 }
1217 #else
1218 #define func_name(x) ""
1219 #endif
1220
1221 #ifdef __i386__
1222 #include "assem_x86.c"
1223 #endif
1224 #ifdef __x86_64__
1225 #include "assem_x64.c"
1226 #endif
1227 #ifdef __arm__
1228 #include "assem_arm.c"
1229 #endif
1230 #ifdef __aarch64__
1231 #include "assem_arm64.c"
1232 #endif
1233
1234 static void *get_trampoline(const void *f)
1235 {
1236   struct ndrc_tramp *tramp = NDRC_WRITE_OFFSET(&ndrc->tramp);
1237   size_t i;
1238
1239   for (i = 0; i < ARRAY_SIZE(tramp->f); i++) {
1240     if (tramp->f[i] == f || tramp->f[i] == NULL)
1241       break;
1242   }
1243   if (i == ARRAY_SIZE(tramp->f)) {
1244     SysPrintf("trampoline table is full, last func %p\n", f);
1245     abort();
1246   }
1247   if (tramp->f[i] == NULL) {
1248     start_tcache_write(&tramp->f[i], &tramp->f[i + 1]);
1249     tramp->f[i] = f;
1250     end_tcache_write(&tramp->f[i], &tramp->f[i + 1]);
1251 #ifdef HAVE_LIBNX
1252     // invalidate the RX mirror (unsure if necessary, but just in case...)
1253     armDCacheFlush(&ndrc->tramp.f[i], sizeof(ndrc->tramp.f[i]));
1254 #endif
1255   }
1256   return &ndrc->tramp.ops[i];
1257 }
1258
1259 static void emit_far_jump(const void *f)
1260 {
1261   if (can_jump_or_call(f)) {
1262     emit_jmp(f);
1263     return;
1264   }
1265
1266   f = get_trampoline(f);
1267   emit_jmp(f);
1268 }
1269
1270 static void emit_far_call(const void *f)
1271 {
1272   if (can_jump_or_call(f)) {
1273     emit_call(f);
1274     return;
1275   }
1276
1277   f = get_trampoline(f);
1278   emit_call(f);
1279 }
1280
1281 // Check if an address is already compiled
1282 // but don't return addresses which are about to expire from the cache
1283 static void *check_addr(u_int vaddr)
1284 {
1285   struct ht_entry *ht_bin = hash_table_get(vaddr);
1286   size_t i;
1287   for (i = 0; i < ARRAY_SIZE(ht_bin->vaddr); i++) {
1288     if (ht_bin->vaddr[i] == vaddr)
1289       if (doesnt_expire_soon(ht_bin->tcaddr[i]))
1290         return ht_bin->tcaddr[i];
1291   }
1292
1293   // refactor to get_addr_nocompile?
1294   u_int start_page = get_page_prev(vaddr);
1295   u_int page, end_page = get_page(vaddr);
1296
1297   stat_inc(stat_jump_in_lookups);
1298   for (page = start_page; page <= end_page; page++) {
1299     const struct block_info *block;
1300     for (block = blocks[page]; block != NULL; block = block->next) {
1301       if (vaddr < block->start)
1302         break;
1303       if (block->is_dirty || vaddr >= block->start + block->len)
1304         continue;
1305       if (!doesnt_expire_soon(ndrc->translation_cache + block->tc_offs))
1306         continue;
1307       for (i = 0; i < block->jump_in_cnt; i++)
1308         if (block->jump_in[i].vaddr == vaddr)
1309           break;
1310       if (i == block->jump_in_cnt)
1311         continue;
1312
1313       // Update existing entry with current address
1314       void *addr = block->jump_in[i].addr;
1315       if (ht_bin->vaddr[0] == vaddr) {
1316         ht_bin->tcaddr[0] = addr;
1317         return addr;
1318       }
1319       if (ht_bin->vaddr[1] == vaddr) {
1320         ht_bin->tcaddr[1] = addr;
1321         return addr;
1322       }
1323       // Insert into hash table with low priority.
1324       // Don't evict existing entries, as they are probably
1325       // addresses that are being accessed frequently.
1326       if (ht_bin->vaddr[0] == -1) {
1327         ht_bin->vaddr[0] = vaddr;
1328         ht_bin->tcaddr[0] = addr;
1329       }
1330       else if (ht_bin->vaddr[1] == -1) {
1331         ht_bin->vaddr[1] = vaddr;
1332         ht_bin->tcaddr[1] = addr;
1333       }
1334       return addr;
1335     }
1336   }
1337   return NULL;
1338 }
1339
1340 static void blocks_clear(struct block_info **head)
1341 {
1342   struct block_info *cur, *next;
1343
1344   if ((cur = *head)) {
1345     *head = NULL;
1346     while (cur) {
1347       next = cur->next;
1348       free(cur);
1349       cur = next;
1350     }
1351   }
1352 }
1353
1354 static int blocks_remove_matching_addrs(struct block_info **head,
1355   u_int base_offs, int shift)
1356 {
1357   struct block_info *next;
1358   int hit = 0;
1359   while (*head) {
1360     if ((((*head)->tc_offs ^ base_offs) >> shift) == 0) {
1361       inv_debug("EXP: rm block %08x (tc_offs %x)\n", (*head)->start, (*head)->tc_offs);
1362       invalidate_block(*head);
1363       next = (*head)->next;
1364       free(*head);
1365       *head = next;
1366       stat_dec(stat_blocks);
1367       hit = 1;
1368     }
1369     else
1370     {
1371       head = &((*head)->next);
1372     }
1373   }
1374   return hit;
1375 }
1376
1377 // This is called when we write to a compiled block (see do_invstub)
1378 static void unlink_jumps_vaddr_range(u_int start, u_int end)
1379 {
1380   u_int page, start_page = get_page(start), end_page = get_page(end - 1);
1381   int i;
1382
1383   for (page = start_page; page <= end_page; page++) {
1384     struct jump_info *ji = jumps[page];
1385     if (ji == NULL)
1386       continue;
1387     for (i = 0; i < ji->count; ) {
1388       if (ji->e[i].target_vaddr < start || ji->e[i].target_vaddr >= end) {
1389         i++;
1390         continue;
1391       }
1392
1393       inv_debug("INV: rm link to %08x (tc_offs %zx)\n", ji->e[i].target_vaddr,
1394         (u_char *)ji->e[i].stub - ndrc->translation_cache);
1395       void *host_addr = find_extjump_insn(ji->e[i].stub);
1396       mark_clear_cache(host_addr);
1397       set_jump_target(host_addr, ji->e[i].stub); // point back to dyna_linker stub
1398
1399       stat_dec(stat_links);
1400       ji->count--;
1401       if (i < ji->count) {
1402         ji->e[i] = ji->e[ji->count];
1403         continue;
1404       }
1405       i++;
1406     }
1407   }
1408 }
1409
1410 static void unlink_jumps_tc_range(struct jump_info *ji, u_int base_offs, int shift)
1411 {
1412   int i;
1413   if (ji == NULL)
1414     return;
1415   for (i = 0; i < ji->count; ) {
1416     u_int tc_offs = (u_char *)ji->e[i].stub - ndrc->translation_cache;
1417     if (((tc_offs ^ base_offs) >> shift) != 0) {
1418       i++;
1419       continue;
1420     }
1421
1422     inv_debug("EXP: rm link to %08x (tc_offs %x)\n", ji->e[i].target_vaddr, tc_offs);
1423     stat_dec(stat_links);
1424     ji->count--;
1425     if (i < ji->count) {
1426       ji->e[i] = ji->e[ji->count];
1427       continue;
1428     }
1429     i++;
1430   }
1431 }
1432
1433 static void invalidate_block(struct block_info *block)
1434 {
1435   u_int i;
1436
1437   block->is_dirty = 1;
1438   unlink_jumps_vaddr_range(block->start, block->start + block->len);
1439   for (i = 0; i < block->jump_in_cnt; i++)
1440     hash_table_remove(block->jump_in[i].vaddr);
1441 }
1442
1443 static int invalidate_range(u_int start, u_int end,
1444   u32 *inv_start_ret, u32 *inv_end_ret)
1445 {
1446   struct block_info *last_block = NULL;
1447   u_int start_page = get_page_prev(start);
1448   u_int end_page = get_page(end - 1);
1449   u_int start_m = pmmask(start);
1450   u_int end_m = pmmask(end - 1);
1451   u_int inv_start, inv_end;
1452   u_int blk_start_m, blk_end_m;
1453   u_int page;
1454   int hit = 0;
1455
1456   // additional area without code (to supplement invalid_code[]), [start, end)
1457   // avoids excessive ndrc_write_invalidate*() calls
1458   inv_start = start_m & ~0xfff;
1459   inv_end = end_m | 0xfff;
1460
1461   for (page = start_page; page <= end_page; page++) {
1462     struct block_info *block;
1463     for (block = blocks[page]; block != NULL; block = block->next) {
1464       if (block->is_dirty)
1465         continue;
1466       last_block = block;
1467       blk_end_m = pmmask(block->start + block->len);
1468       if (blk_end_m <= start_m) {
1469         inv_start = max(inv_start, blk_end_m);
1470         continue;
1471       }
1472       blk_start_m = pmmask(block->start);
1473       if (end_m <= blk_start_m) {
1474         inv_end = min(inv_end, blk_start_m - 1);
1475         continue;
1476       }
1477       if (!block->source) // "hack" block - leave it alone
1478         continue;
1479
1480       hit++;
1481       invalidate_block(block);
1482       stat_inc(stat_inv_hits);
1483     }
1484   }
1485
1486   if (!hit && last_block && last_block->source) {
1487     // could be some leftover unused block, uselessly trapping writes
1488     last_block->inv_near_misses++;
1489     if (last_block->inv_near_misses > 128) {
1490       invalidate_block(last_block);
1491       stat_inc(stat_inv_hits);
1492       hit++;
1493     }
1494   }
1495   if (hit) {
1496     do_clear_cache();
1497 #ifdef USE_MINI_HT
1498     memset(mini_ht, -1, sizeof(mini_ht));
1499 #endif
1500   }
1501
1502   if (inv_start <= (start_m & ~0xfff) && inv_end >= (start_m | 0xfff))
1503     // the whole page is empty now
1504     mark_invalid_code(start, 1, 1);
1505
1506   if (inv_start_ret) *inv_start_ret = inv_start | (start & 0xe0000000);
1507   if (inv_end_ret) *inv_end_ret = inv_end | (end & 0xe0000000);
1508   return hit;
1509 }
1510
1511 void new_dynarec_invalidate_range(unsigned int start, unsigned int end)
1512 {
1513   invalidate_range(start, end, NULL, NULL);
1514 }
1515
1516 static void ndrc_write_invalidate_many(u_int start, u_int end)
1517 {
1518   // this check is done by the caller
1519   //if (inv_code_start<=addr&&addr<=inv_code_end) { rhits++; return; }
1520   int ret = invalidate_range(start, end, &inv_code_start, &inv_code_end);
1521 #ifdef INV_DEBUG_W
1522   int invc = invalid_code[start >> 12];
1523   u_int len = end - start;
1524   if (ret)
1525     printf("INV ADDR: %08x/%02x hit %d blocks\n", start, len, ret);
1526   else
1527     printf("INV ADDR: %08x/%02x miss, inv %08x-%08x invc %d->%d\n", start, len,
1528       inv_code_start, inv_code_end, invc, invalid_code[start >> 12]);
1529   check_for_block_changes(start, end);
1530 #endif
1531   stat_inc(stat_inv_addr_calls);
1532   (void)ret;
1533 }
1534
1535 void ndrc_write_invalidate_one(u_int addr)
1536 {
1537   ndrc_write_invalidate_many(addr, addr + 4);
1538 }
1539
1540 // This is called when loading a save state.
1541 // Anything could have changed, so invalidate everything.
1542 void new_dynarec_invalidate_all_pages(void)
1543 {
1544   struct block_info *block;
1545   u_int page;
1546   for (page = 0; page < ARRAY_SIZE(blocks); page++) {
1547     for (block = blocks[page]; block != NULL; block = block->next) {
1548       if (block->is_dirty)
1549         continue;
1550       if (!block->source) // hack block?
1551         continue;
1552       invalidate_block(block);
1553     }
1554   }
1555
1556   #ifdef USE_MINI_HT
1557   memset(mini_ht, -1, sizeof(mini_ht));
1558   #endif
1559   do_clear_cache();
1560 }
1561
1562 // Add an entry to jump_out after making a link
1563 // src should point to code by emit_extjump()
1564 void ndrc_add_jump_out(u_int vaddr, void *src)
1565 {
1566   inv_debug("ndrc_add_jump_out: %p -> %x\n", src, vaddr);
1567   u_int page = get_page(vaddr);
1568   struct jump_info *ji;
1569
1570   stat_inc(stat_links);
1571   check_extjump2(src);
1572   ji = jumps[page];
1573   if (ji == NULL) {
1574     ji = malloc(sizeof(*ji) + sizeof(ji->e[0]) * 16);
1575     ji->alloc = 16;
1576     ji->count = 0;
1577   }
1578   else if (ji->count >= ji->alloc) {
1579     ji->alloc += 16;
1580     ji = realloc(ji, sizeof(*ji) + sizeof(ji->e[0]) * ji->alloc);
1581   }
1582   jumps[page] = ji;
1583   ji->e[ji->count].target_vaddr = vaddr;
1584   ji->e[ji->count].stub = src;
1585   ji->count++;
1586 }
1587
1588 /* Register allocation */
1589
1590 // Note: registers are allocated clean (unmodified state)
1591 // if you intend to modify the register, you must call dirty_reg().
1592 static void alloc_reg(struct regstat *cur,int i,signed char reg)
1593 {
1594   int r,hr;
1595   int preferred_reg = PREFERRED_REG_FIRST
1596     + reg % (PREFERRED_REG_LAST - PREFERRED_REG_FIRST + 1);
1597   if (reg == CCREG) preferred_reg = HOST_CCREG;
1598   if (reg == PTEMP || reg == FTEMP) preferred_reg = 12;
1599   assert(PREFERRED_REG_FIRST != EXCLUDE_REG && EXCLUDE_REG != HOST_REGS);
1600   assert(reg >= 0);
1601
1602   // Don't allocate unused registers
1603   if((cur->u>>reg)&1) return;
1604
1605   // see if it's already allocated
1606   if (get_reg(cur->regmap, reg) >= 0)
1607     return;
1608
1609   // Keep the same mapping if the register was already allocated in a loop
1610   preferred_reg = loop_reg(i,reg,preferred_reg);
1611
1612   // Try to allocate the preferred register
1613   if(cur->regmap[preferred_reg]==-1) {
1614     cur->regmap[preferred_reg]=reg;
1615     cur->dirty&=~(1<<preferred_reg);
1616     cur->isconst&=~(1<<preferred_reg);
1617     return;
1618   }
1619   r=cur->regmap[preferred_reg];
1620   assert(r < 64);
1621   if((cur->u>>r)&1) {
1622     cur->regmap[preferred_reg]=reg;
1623     cur->dirty&=~(1<<preferred_reg);
1624     cur->isconst&=~(1<<preferred_reg);
1625     return;
1626   }
1627
1628   // Clear any unneeded registers
1629   // We try to keep the mapping consistent, if possible, because it
1630   // makes branches easier (especially loops).  So we try to allocate
1631   // first (see above) before removing old mappings.  If this is not
1632   // possible then go ahead and clear out the registers that are no
1633   // longer needed.
1634   for(hr=0;hr<HOST_REGS;hr++)
1635   {
1636     r=cur->regmap[hr];
1637     if(r>=0) {
1638       assert(r < 64);
1639       if((cur->u>>r)&1) {cur->regmap[hr]=-1;break;}
1640     }
1641   }
1642
1643   // Try to allocate any available register, but prefer
1644   // registers that have not been used recently.
1645   if (i > 0) {
1646     for (hr = PREFERRED_REG_FIRST; ; ) {
1647       if (cur->regmap[hr] < 0) {
1648         int oldreg = regs[i-1].regmap[hr];
1649         if (oldreg < 0 || (oldreg != dops[i-1].rs1 && oldreg != dops[i-1].rs2
1650              && oldreg != dops[i-1].rt1 && oldreg != dops[i-1].rt2))
1651         {
1652           cur->regmap[hr]=reg;
1653           cur->dirty&=~(1<<hr);
1654           cur->isconst&=~(1<<hr);
1655           return;
1656         }
1657       }
1658       hr++;
1659       if (hr == EXCLUDE_REG)
1660         hr++;
1661       if (hr == HOST_REGS)
1662         hr = 0;
1663       if (hr == PREFERRED_REG_FIRST)
1664         break;
1665     }
1666   }
1667
1668   // Try to allocate any available register
1669   for (hr = PREFERRED_REG_FIRST; ; ) {
1670     if (cur->regmap[hr] < 0) {
1671       cur->regmap[hr]=reg;
1672       cur->dirty&=~(1<<hr);
1673       cur->isconst&=~(1<<hr);
1674       return;
1675     }
1676     hr++;
1677     if (hr == EXCLUDE_REG)
1678       hr++;
1679     if (hr == HOST_REGS)
1680       hr = 0;
1681     if (hr == PREFERRED_REG_FIRST)
1682       break;
1683   }
1684
1685   // Ok, now we have to evict someone
1686   // Pick a register we hopefully won't need soon
1687   u_char hsn[MAXREG+1];
1688   memset(hsn,10,sizeof(hsn));
1689   int j;
1690   lsn(hsn,i,&preferred_reg);
1691   //printf("eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",cur->regmap[0],cur->regmap[1],cur->regmap[2],cur->regmap[3],cur->regmap[5],cur->regmap[6],cur->regmap[7]);
1692   //printf("hsn(%x): %d %d %d %d %d %d %d\n",start+i*4,hsn[cur->regmap[0]&63],hsn[cur->regmap[1]&63],hsn[cur->regmap[2]&63],hsn[cur->regmap[3]&63],hsn[cur->regmap[5]&63],hsn[cur->regmap[6]&63],hsn[cur->regmap[7]&63]);
1693   if(i>0) {
1694     // Don't evict the cycle count at entry points, otherwise the entry
1695     // stub will have to write it.
1696     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1697     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1698     for(j=10;j>=3;j--)
1699     {
1700       // Alloc preferred register if available
1701       if(hsn[r=cur->regmap[preferred_reg]&63]==j) {
1702         for(hr=0;hr<HOST_REGS;hr++) {
1703           // Evict both parts of a 64-bit register
1704           if(cur->regmap[hr]==r) {
1705             cur->regmap[hr]=-1;
1706             cur->dirty&=~(1<<hr);
1707             cur->isconst&=~(1<<hr);
1708           }
1709         }
1710         cur->regmap[preferred_reg]=reg;
1711         return;
1712       }
1713       for(r=1;r<=MAXREG;r++)
1714       {
1715         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1716           for(hr=0;hr<HOST_REGS;hr++) {
1717             if(hr!=HOST_CCREG||j<hsn[CCREG]) {
1718               if(cur->regmap[hr]==r) {
1719                 cur->regmap[hr]=reg;
1720                 cur->dirty&=~(1<<hr);
1721                 cur->isconst&=~(1<<hr);
1722                 return;
1723               }
1724             }
1725           }
1726         }
1727       }
1728     }
1729   }
1730   for(j=10;j>=0;j--)
1731   {
1732     for(r=1;r<=MAXREG;r++)
1733     {
1734       if(hsn[r]==j) {
1735         for(hr=0;hr<HOST_REGS;hr++) {
1736           if(cur->regmap[hr]==r) {
1737             cur->regmap[hr]=reg;
1738             cur->dirty&=~(1<<hr);
1739             cur->isconst&=~(1<<hr);
1740             return;
1741           }
1742         }
1743       }
1744     }
1745   }
1746   SysPrintf("This shouldn't happen (alloc_reg)");abort();
1747 }
1748
1749 // Allocate a temporary register.  This is done without regard to
1750 // dirty status or whether the register we request is on the unneeded list
1751 // Note: This will only allocate one register, even if called multiple times
1752 static void alloc_reg_temp(struct regstat *cur,int i,signed char reg)
1753 {
1754   int r,hr;
1755   int preferred_reg = -1;
1756
1757   // see if it's already allocated
1758   for(hr=0;hr<HOST_REGS;hr++)
1759   {
1760     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==reg) return;
1761   }
1762
1763   // Try to allocate any available register
1764   for(hr=HOST_REGS-1;hr>=0;hr--) {
1765     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1766       cur->regmap[hr]=reg;
1767       cur->dirty&=~(1<<hr);
1768       cur->isconst&=~(1<<hr);
1769       return;
1770     }
1771   }
1772
1773   // Find an unneeded register
1774   for(hr=HOST_REGS-1;hr>=0;hr--)
1775   {
1776     r=cur->regmap[hr];
1777     if(r>=0) {
1778       assert(r < 64);
1779       if((cur->u>>r)&1) {
1780         if(i==0||((unneeded_reg[i-1]>>r)&1)) {
1781           cur->regmap[hr]=reg;
1782           cur->dirty&=~(1<<hr);
1783           cur->isconst&=~(1<<hr);
1784           return;
1785         }
1786       }
1787     }
1788   }
1789
1790   // Ok, now we have to evict someone
1791   // Pick a register we hopefully won't need soon
1792   // TODO: we might want to follow unconditional jumps here
1793   // TODO: get rid of dupe code and make this into a function
1794   u_char hsn[MAXREG+1];
1795   memset(hsn,10,sizeof(hsn));
1796   int j;
1797   lsn(hsn,i,&preferred_reg);
1798   //printf("hsn: %d %d %d %d %d %d %d\n",hsn[cur->regmap[0]&63],hsn[cur->regmap[1]&63],hsn[cur->regmap[2]&63],hsn[cur->regmap[3]&63],hsn[cur->regmap[5]&63],hsn[cur->regmap[6]&63],hsn[cur->regmap[7]&63]);
1799   if(i>0) {
1800     // Don't evict the cycle count at entry points, otherwise the entry
1801     // stub will have to write it.
1802     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1803     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1804     for(j=10;j>=3;j--)
1805     {
1806       for(r=1;r<=MAXREG;r++)
1807       {
1808         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1809           for(hr=0;hr<HOST_REGS;hr++) {
1810             if(hr!=HOST_CCREG||hsn[CCREG]>2) {
1811               if(cur->regmap[hr]==r) {
1812                 cur->regmap[hr]=reg;
1813                 cur->dirty&=~(1<<hr);
1814                 cur->isconst&=~(1<<hr);
1815                 return;
1816               }
1817             }
1818           }
1819         }
1820       }
1821     }
1822   }
1823   for(j=10;j>=0;j--)
1824   {
1825     for(r=1;r<=MAXREG;r++)
1826     {
1827       if(hsn[r]==j) {
1828         for(hr=0;hr<HOST_REGS;hr++) {
1829           if(cur->regmap[hr]==r) {
1830             cur->regmap[hr]=reg;
1831             cur->dirty&=~(1<<hr);
1832             cur->isconst&=~(1<<hr);
1833             return;
1834           }
1835         }
1836       }
1837     }
1838   }
1839   SysPrintf("This shouldn't happen");abort();
1840 }
1841
1842 static void mov_alloc(struct regstat *current,int i)
1843 {
1844   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) {
1845     alloc_cc(current,i); // for stalls
1846     dirty_reg(current,CCREG);
1847   }
1848
1849   // Note: Don't need to actually alloc the source registers
1850   //alloc_reg(current,i,dops[i].rs1);
1851   alloc_reg(current,i,dops[i].rt1);
1852
1853   clear_const(current,dops[i].rs1);
1854   clear_const(current,dops[i].rt1);
1855   dirty_reg(current,dops[i].rt1);
1856 }
1857
1858 static void shiftimm_alloc(struct regstat *current,int i)
1859 {
1860   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
1861   {
1862     if(dops[i].rt1) {
1863       if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1864       else dops[i].use_lt1=!!dops[i].rs1;
1865       alloc_reg(current,i,dops[i].rt1);
1866       dirty_reg(current,dops[i].rt1);
1867       if(is_const(current,dops[i].rs1)) {
1868         int v=get_const(current,dops[i].rs1);
1869         if(dops[i].opcode2==0x00) set_const(current,dops[i].rt1,v<<imm[i]);
1870         if(dops[i].opcode2==0x02) set_const(current,dops[i].rt1,(u_int)v>>imm[i]);
1871         if(dops[i].opcode2==0x03) set_const(current,dops[i].rt1,v>>imm[i]);
1872       }
1873       else clear_const(current,dops[i].rt1);
1874     }
1875   }
1876   else
1877   {
1878     clear_const(current,dops[i].rs1);
1879     clear_const(current,dops[i].rt1);
1880   }
1881
1882   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
1883   {
1884     assert(0);
1885   }
1886   if(dops[i].opcode2==0x3c) // DSLL32
1887   {
1888     assert(0);
1889   }
1890   if(dops[i].opcode2==0x3e) // DSRL32
1891   {
1892     assert(0);
1893   }
1894   if(dops[i].opcode2==0x3f) // DSRA32
1895   {
1896     assert(0);
1897   }
1898 }
1899
1900 static void shift_alloc(struct regstat *current,int i)
1901 {
1902   if(dops[i].rt1) {
1903     if(dops[i].opcode2<=0x07) // SLLV/SRLV/SRAV
1904     {
1905       if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
1906       if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
1907       alloc_reg(current,i,dops[i].rt1);
1908       if(dops[i].rt1==dops[i].rs2) {
1909         alloc_reg_temp(current,i,-1);
1910         minimum_free_regs[i]=1;
1911       }
1912     } else { // DSLLV/DSRLV/DSRAV
1913       assert(0);
1914     }
1915     clear_const(current,dops[i].rs1);
1916     clear_const(current,dops[i].rs2);
1917     clear_const(current,dops[i].rt1);
1918     dirty_reg(current,dops[i].rt1);
1919   }
1920 }
1921
1922 static void alu_alloc(struct regstat *current,int i)
1923 {
1924   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
1925     if(dops[i].rt1) {
1926       if(dops[i].rs1&&dops[i].rs2) {
1927         alloc_reg(current,i,dops[i].rs1);
1928         alloc_reg(current,i,dops[i].rs2);
1929       }
1930       else {
1931         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1932         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1933       }
1934       alloc_reg(current,i,dops[i].rt1);
1935     }
1936   }
1937   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
1938     if(dops[i].rt1) {
1939       alloc_reg(current,i,dops[i].rs1);
1940       alloc_reg(current,i,dops[i].rs2);
1941       alloc_reg(current,i,dops[i].rt1);
1942     }
1943   }
1944   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
1945     if(dops[i].rt1) {
1946       if(dops[i].rs1&&dops[i].rs2) {
1947         alloc_reg(current,i,dops[i].rs1);
1948         alloc_reg(current,i,dops[i].rs2);
1949       }
1950       else
1951       {
1952         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1953         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1954       }
1955       alloc_reg(current,i,dops[i].rt1);
1956     }
1957   }
1958   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
1959     assert(0);
1960   }
1961   clear_const(current,dops[i].rs1);
1962   clear_const(current,dops[i].rs2);
1963   clear_const(current,dops[i].rt1);
1964   dirty_reg(current,dops[i].rt1);
1965 }
1966
1967 static void imm16_alloc(struct regstat *current,int i)
1968 {
1969   if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1970   else dops[i].use_lt1=!!dops[i].rs1;
1971   if(dops[i].rt1) alloc_reg(current,i,dops[i].rt1);
1972   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
1973     assert(0);
1974   }
1975   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
1976     clear_const(current,dops[i].rs1);
1977     clear_const(current,dops[i].rt1);
1978   }
1979   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
1980     if(is_const(current,dops[i].rs1)) {
1981       int v=get_const(current,dops[i].rs1);
1982       if(dops[i].opcode==0x0c) set_const(current,dops[i].rt1,v&imm[i]);
1983       if(dops[i].opcode==0x0d) set_const(current,dops[i].rt1,v|imm[i]);
1984       if(dops[i].opcode==0x0e) set_const(current,dops[i].rt1,v^imm[i]);
1985     }
1986     else clear_const(current,dops[i].rt1);
1987   }
1988   else if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
1989     if(is_const(current,dops[i].rs1)) {
1990       int v=get_const(current,dops[i].rs1);
1991       set_const(current,dops[i].rt1,v+imm[i]);
1992     }
1993     else clear_const(current,dops[i].rt1);
1994   }
1995   else {
1996     set_const(current,dops[i].rt1,imm[i]<<16); // LUI
1997   }
1998   dirty_reg(current,dops[i].rt1);
1999 }
2000
2001 static void load_alloc(struct regstat *current,int i)
2002 {
2003   clear_const(current,dops[i].rt1);
2004   //if(dops[i].rs1!=dops[i].rt1&&needed_again(dops[i].rs1,i)) clear_const(current,dops[i].rs1); // Does this help or hurt?
2005   if(!dops[i].rs1) current->u&=~1LL; // Allow allocating r0 if it's the source register
2006   if (needed_again(dops[i].rs1, i))
2007     alloc_reg(current, i, dops[i].rs1);
2008   if (ram_offset)
2009     alloc_reg(current, i, ROREG);
2010   if(dops[i].rt1&&!((current->u>>dops[i].rt1)&1)) {
2011     alloc_reg(current,i,dops[i].rt1);
2012     assert(get_reg(current->regmap,dops[i].rt1)>=0);
2013     if(dops[i].opcode==0x27||dops[i].opcode==0x37) // LWU/LD
2014     {
2015       assert(0);
2016     }
2017     else if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
2018     {
2019       assert(0);
2020     }
2021     dirty_reg(current,dops[i].rt1);
2022     // LWL/LWR need a temporary register for the old value
2023     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
2024     {
2025       alloc_reg(current,i,FTEMP);
2026       alloc_reg_temp(current,i,-1);
2027       minimum_free_regs[i]=1;
2028     }
2029   }
2030   else
2031   {
2032     // Load to r0 or unneeded register (dummy load)
2033     // but we still need a register to calculate the address
2034     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
2035     {
2036       alloc_reg(current,i,FTEMP); // LWL/LWR need another temporary
2037     }
2038     alloc_reg_temp(current,i,-1);
2039     minimum_free_regs[i]=1;
2040     if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
2041     {
2042       assert(0);
2043     }
2044   }
2045 }
2046
2047 static void store_alloc(struct regstat *current,int i)
2048 {
2049   clear_const(current,dops[i].rs2);
2050   if(!(dops[i].rs2)) current->u&=~1LL; // Allow allocating r0 if necessary
2051   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
2052   alloc_reg(current,i,dops[i].rs2);
2053   if(dops[i].opcode==0x2c||dops[i].opcode==0x2d||dops[i].opcode==0x3f) { // 64-bit SDL/SDR/SD
2054     assert(0);
2055   }
2056   if (ram_offset)
2057     alloc_reg(current, i, ROREG);
2058   #if defined(HOST_IMM8)
2059   // On CPUs without 32-bit immediates we need a pointer to invalid_code
2060   alloc_reg(current, i, INVCP);
2061   #endif
2062   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) { // SWL/SWL/SDL/SDR
2063     alloc_reg(current,i,FTEMP);
2064   }
2065   // We need a temporary register for address generation
2066   alloc_reg_temp(current,i,-1);
2067   minimum_free_regs[i]=1;
2068 }
2069
2070 static void c1ls_alloc(struct regstat *current,int i)
2071 {
2072   clear_const(current,dops[i].rt1);
2073   alloc_reg(current,i,CSREG); // Status
2074 }
2075
2076 static void c2ls_alloc(struct regstat *current,int i)
2077 {
2078   clear_const(current,dops[i].rt1);
2079   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
2080   alloc_reg(current,i,FTEMP);
2081   if (ram_offset)
2082     alloc_reg(current, i, ROREG);
2083   #if defined(HOST_IMM8)
2084   // On CPUs without 32-bit immediates we need a pointer to invalid_code
2085   if (dops[i].opcode == 0x3a) // SWC2
2086     alloc_reg(current,i,INVCP);
2087   #endif
2088   // We need a temporary register for address generation
2089   alloc_reg_temp(current,i,-1);
2090   minimum_free_regs[i]=1;
2091 }
2092
2093 #ifndef multdiv_alloc
2094 static void multdiv_alloc(struct regstat *current,int i)
2095 {
2096   //  case 0x18: MULT
2097   //  case 0x19: MULTU
2098   //  case 0x1A: DIV
2099   //  case 0x1B: DIVU
2100   //  case 0x1C: DMULT
2101   //  case 0x1D: DMULTU
2102   //  case 0x1E: DDIV
2103   //  case 0x1F: DDIVU
2104   clear_const(current,dops[i].rs1);
2105   clear_const(current,dops[i].rs2);
2106   alloc_cc(current,i); // for stalls
2107   if(dops[i].rs1&&dops[i].rs2)
2108   {
2109     if((dops[i].opcode2&4)==0) // 32-bit
2110     {
2111       current->u&=~(1LL<<HIREG);
2112       current->u&=~(1LL<<LOREG);
2113       alloc_reg(current,i,HIREG);
2114       alloc_reg(current,i,LOREG);
2115       alloc_reg(current,i,dops[i].rs1);
2116       alloc_reg(current,i,dops[i].rs2);
2117       dirty_reg(current,HIREG);
2118       dirty_reg(current,LOREG);
2119     }
2120     else // 64-bit
2121     {
2122       assert(0);
2123     }
2124   }
2125   else
2126   {
2127     // Multiply by zero is zero.
2128     // MIPS does not have a divide by zero exception.
2129     // The result is undefined, we return zero.
2130     alloc_reg(current,i,HIREG);
2131     alloc_reg(current,i,LOREG);
2132     dirty_reg(current,HIREG);
2133     dirty_reg(current,LOREG);
2134   }
2135 }
2136 #endif
2137
2138 static void cop0_alloc(struct regstat *current,int i)
2139 {
2140   if(dops[i].opcode2==0) // MFC0
2141   {
2142     if(dops[i].rt1) {
2143       clear_const(current,dops[i].rt1);
2144       alloc_all(current,i);
2145       alloc_reg(current,i,dops[i].rt1);
2146       dirty_reg(current,dops[i].rt1);
2147     }
2148   }
2149   else if(dops[i].opcode2==4) // MTC0
2150   {
2151     if(dops[i].rs1){
2152       clear_const(current,dops[i].rs1);
2153       alloc_reg(current,i,dops[i].rs1);
2154       alloc_all(current,i);
2155     }
2156     else {
2157       alloc_all(current,i); // FIXME: Keep r0
2158       current->u&=~1LL;
2159       alloc_reg(current,i,0);
2160     }
2161   }
2162   else
2163   {
2164     // RFE
2165     assert(dops[i].opcode2==0x10);
2166     alloc_all(current,i);
2167   }
2168   minimum_free_regs[i]=HOST_REGS;
2169 }
2170
2171 static void cop2_alloc(struct regstat *current,int i)
2172 {
2173   if (dops[i].opcode2 < 3) // MFC2/CFC2
2174   {
2175     alloc_cc(current,i); // for stalls
2176     dirty_reg(current,CCREG);
2177     if(dops[i].rt1){
2178       clear_const(current,dops[i].rt1);
2179       alloc_reg(current,i,dops[i].rt1);
2180       dirty_reg(current,dops[i].rt1);
2181     }
2182   }
2183   else if (dops[i].opcode2 > 3) // MTC2/CTC2
2184   {
2185     if(dops[i].rs1){
2186       clear_const(current,dops[i].rs1);
2187       alloc_reg(current,i,dops[i].rs1);
2188     }
2189     else {
2190       current->u&=~1LL;
2191       alloc_reg(current,i,0);
2192     }
2193   }
2194   alloc_reg_temp(current,i,-1);
2195   minimum_free_regs[i]=1;
2196 }
2197
2198 static void c2op_alloc(struct regstat *current,int i)
2199 {
2200   alloc_cc(current,i); // for stalls
2201   dirty_reg(current,CCREG);
2202   alloc_reg_temp(current,i,-1);
2203 }
2204
2205 static void syscall_alloc(struct regstat *current,int i)
2206 {
2207   alloc_cc(current,i);
2208   dirty_reg(current,CCREG);
2209   alloc_all(current,i);
2210   minimum_free_regs[i]=HOST_REGS;
2211   current->isconst=0;
2212 }
2213
2214 static void delayslot_alloc(struct regstat *current,int i)
2215 {
2216   switch(dops[i].itype) {
2217     case UJUMP:
2218     case CJUMP:
2219     case SJUMP:
2220     case RJUMP:
2221     case SYSCALL:
2222     case HLECALL:
2223     case IMM16:
2224       imm16_alloc(current,i);
2225       break;
2226     case LOAD:
2227     case LOADLR:
2228       load_alloc(current,i);
2229       break;
2230     case STORE:
2231     case STORELR:
2232       store_alloc(current,i);
2233       break;
2234     case ALU:
2235       alu_alloc(current,i);
2236       break;
2237     case SHIFT:
2238       shift_alloc(current,i);
2239       break;
2240     case MULTDIV:
2241       multdiv_alloc(current,i);
2242       break;
2243     case SHIFTIMM:
2244       shiftimm_alloc(current,i);
2245       break;
2246     case MOV:
2247       mov_alloc(current,i);
2248       break;
2249     case COP0:
2250       cop0_alloc(current,i);
2251       break;
2252     case COP1:
2253       break;
2254     case COP2:
2255       cop2_alloc(current,i);
2256       break;
2257     case C1LS:
2258       c1ls_alloc(current,i);
2259       break;
2260     case C2LS:
2261       c2ls_alloc(current,i);
2262       break;
2263     case C2OP:
2264       c2op_alloc(current,i);
2265       break;
2266   }
2267 }
2268
2269 static void add_stub(enum stub_type type, void *addr, void *retaddr,
2270   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e)
2271 {
2272   assert(stubcount < ARRAY_SIZE(stubs));
2273   stubs[stubcount].type = type;
2274   stubs[stubcount].addr = addr;
2275   stubs[stubcount].retaddr = retaddr;
2276   stubs[stubcount].a = a;
2277   stubs[stubcount].b = b;
2278   stubs[stubcount].c = c;
2279   stubs[stubcount].d = d;
2280   stubs[stubcount].e = e;
2281   stubcount++;
2282 }
2283
2284 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
2285   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist)
2286 {
2287   add_stub(type, addr, retaddr, i, addr_reg, (uintptr_t)i_regs, ccadj, reglist);
2288 }
2289
2290 // Write out a single register
2291 static void wb_register(signed char r, const signed char regmap[], uint64_t dirty)
2292 {
2293   int hr;
2294   for(hr=0;hr<HOST_REGS;hr++) {
2295     if(hr!=EXCLUDE_REG) {
2296       if(regmap[hr]==r) {
2297         if((dirty>>hr)&1) {
2298           assert(regmap[hr]<64);
2299           emit_storereg(r,hr);
2300         }
2301       }
2302     }
2303   }
2304 }
2305
2306 static void wb_valid(signed char pre[],signed char entry[],u_int dirty_pre,u_int dirty,uint64_t u)
2307 {
2308   //if(dirty_pre==dirty) return;
2309   int hr, r;
2310   for (hr = 0; hr < HOST_REGS; hr++) {
2311     r = pre[hr];
2312     if (r < 1 || r > 33 || ((u >> r) & 1))
2313       continue;
2314     if (((dirty_pre & ~dirty) >> hr) & 1)
2315       emit_storereg(r, hr);
2316   }
2317 }
2318
2319 // trashes r2
2320 static void pass_args(int a0, int a1)
2321 {
2322   if(a0==1&&a1==0) {
2323     // must swap
2324     emit_mov(a0,2); emit_mov(a1,1); emit_mov(2,0);
2325   }
2326   else if(a0!=0&&a1==0) {
2327     emit_mov(a1,1);
2328     if (a0>=0) emit_mov(a0,0);
2329   }
2330   else {
2331     if(a0>=0&&a0!=0) emit_mov(a0,0);
2332     if(a1>=0&&a1!=1) emit_mov(a1,1);
2333   }
2334 }
2335
2336 static void alu_assemble(int i, const struct regstat *i_regs)
2337 {
2338   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
2339     if(dops[i].rt1) {
2340       signed char s1,s2,t;
2341       t=get_reg(i_regs->regmap,dops[i].rt1);
2342       if(t>=0) {
2343         s1=get_reg(i_regs->regmap,dops[i].rs1);
2344         s2=get_reg(i_regs->regmap,dops[i].rs2);
2345         if(dops[i].rs1&&dops[i].rs2) {
2346           assert(s1>=0);
2347           assert(s2>=0);
2348           if(dops[i].opcode2&2) emit_sub(s1,s2,t);
2349           else emit_add(s1,s2,t);
2350         }
2351         else if(dops[i].rs1) {
2352           if(s1>=0) emit_mov(s1,t);
2353           else emit_loadreg(dops[i].rs1,t);
2354         }
2355         else if(dops[i].rs2) {
2356           if(s2>=0) {
2357             if(dops[i].opcode2&2) emit_neg(s2,t);
2358             else emit_mov(s2,t);
2359           }
2360           else {
2361             emit_loadreg(dops[i].rs2,t);
2362             if(dops[i].opcode2&2) emit_neg(t,t);
2363           }
2364         }
2365         else emit_zeroreg(t);
2366       }
2367     }
2368   }
2369   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
2370     assert(0);
2371   }
2372   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
2373     if(dops[i].rt1) {
2374       signed char s1l,s2l,t;
2375       {
2376         t=get_reg(i_regs->regmap,dops[i].rt1);
2377         //assert(t>=0);
2378         if(t>=0) {
2379           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2380           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2381           if(dops[i].rs2==0) // rx<r0
2382           {
2383             if(dops[i].opcode2==0x2a&&dops[i].rs1!=0) { // SLT
2384               assert(s1l>=0);
2385               emit_shrimm(s1l,31,t);
2386             }
2387             else // SLTU (unsigned can not be less than zero, 0<0)
2388               emit_zeroreg(t);
2389           }
2390           else if(dops[i].rs1==0) // r0<rx
2391           {
2392             assert(s2l>=0);
2393             if(dops[i].opcode2==0x2a) // SLT
2394               emit_set_gz32(s2l,t);
2395             else // SLTU (set if not zero)
2396               emit_set_nz32(s2l,t);
2397           }
2398           else{
2399             assert(s1l>=0);assert(s2l>=0);
2400             if(dops[i].opcode2==0x2a) // SLT
2401               emit_set_if_less32(s1l,s2l,t);
2402             else // SLTU
2403               emit_set_if_carry32(s1l,s2l,t);
2404           }
2405         }
2406       }
2407     }
2408   }
2409   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
2410     if(dops[i].rt1) {
2411       signed char s1l,s2l,tl;
2412       tl=get_reg(i_regs->regmap,dops[i].rt1);
2413       {
2414         if(tl>=0) {
2415           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2416           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2417           if(dops[i].rs1&&dops[i].rs2) {
2418             assert(s1l>=0);
2419             assert(s2l>=0);
2420             if(dops[i].opcode2==0x24) { // AND
2421               emit_and(s1l,s2l,tl);
2422             } else
2423             if(dops[i].opcode2==0x25) { // OR
2424               emit_or(s1l,s2l,tl);
2425             } else
2426             if(dops[i].opcode2==0x26) { // XOR
2427               emit_xor(s1l,s2l,tl);
2428             } else
2429             if(dops[i].opcode2==0x27) { // NOR
2430               emit_or(s1l,s2l,tl);
2431               emit_not(tl,tl);
2432             }
2433           }
2434           else
2435           {
2436             if(dops[i].opcode2==0x24) { // AND
2437               emit_zeroreg(tl);
2438             } else
2439             if(dops[i].opcode2==0x25||dops[i].opcode2==0x26) { // OR/XOR
2440               if(dops[i].rs1){
2441                 if(s1l>=0) emit_mov(s1l,tl);
2442                 else emit_loadreg(dops[i].rs1,tl); // CHECK: regmap_entry?
2443               }
2444               else
2445               if(dops[i].rs2){
2446                 if(s2l>=0) emit_mov(s2l,tl);
2447                 else emit_loadreg(dops[i].rs2,tl); // CHECK: regmap_entry?
2448               }
2449               else emit_zeroreg(tl);
2450             } else
2451             if(dops[i].opcode2==0x27) { // NOR
2452               if(dops[i].rs1){
2453                 if(s1l>=0) emit_not(s1l,tl);
2454                 else {
2455                   emit_loadreg(dops[i].rs1,tl);
2456                   emit_not(tl,tl);
2457                 }
2458               }
2459               else
2460               if(dops[i].rs2){
2461                 if(s2l>=0) emit_not(s2l,tl);
2462                 else {
2463                   emit_loadreg(dops[i].rs2,tl);
2464                   emit_not(tl,tl);
2465                 }
2466               }
2467               else emit_movimm(-1,tl);
2468             }
2469           }
2470         }
2471       }
2472     }
2473   }
2474 }
2475
2476 static void imm16_assemble(int i, const struct regstat *i_regs)
2477 {
2478   if (dops[i].opcode==0x0f) { // LUI
2479     if(dops[i].rt1) {
2480       signed char t;
2481       t=get_reg(i_regs->regmap,dops[i].rt1);
2482       //assert(t>=0);
2483       if(t>=0) {
2484         if(!((i_regs->isconst>>t)&1))
2485           emit_movimm(imm[i]<<16,t);
2486       }
2487     }
2488   }
2489   if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
2490     if(dops[i].rt1) {
2491       signed char s,t;
2492       t=get_reg(i_regs->regmap,dops[i].rt1);
2493       s=get_reg(i_regs->regmap,dops[i].rs1);
2494       if(dops[i].rs1) {
2495         //assert(t>=0);
2496         //assert(s>=0);
2497         if(t>=0) {
2498           if(!((i_regs->isconst>>t)&1)) {
2499             if(s<0) {
2500               if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2501               emit_addimm(t,imm[i],t);
2502             }else{
2503               if(!((i_regs->wasconst>>s)&1))
2504                 emit_addimm(s,imm[i],t);
2505               else
2506                 emit_movimm(constmap[i][s]+imm[i],t);
2507             }
2508           }
2509         }
2510       } else {
2511         if(t>=0) {
2512           if(!((i_regs->isconst>>t)&1))
2513             emit_movimm(imm[i],t);
2514         }
2515       }
2516     }
2517   }
2518   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
2519     if(dops[i].rt1) {
2520       signed char sl,tl;
2521       tl=get_reg(i_regs->regmap,dops[i].rt1);
2522       sl=get_reg(i_regs->regmap,dops[i].rs1);
2523       if(tl>=0) {
2524         if(dops[i].rs1) {
2525           assert(sl>=0);
2526           emit_addimm(sl,imm[i],tl);
2527         } else {
2528           emit_movimm(imm[i],tl);
2529         }
2530       }
2531     }
2532   }
2533   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
2534     if(dops[i].rt1) {
2535       //assert(dops[i].rs1!=0); // r0 might be valid, but it's probably a bug
2536       signed char sl,t;
2537       t=get_reg(i_regs->regmap,dops[i].rt1);
2538       sl=get_reg(i_regs->regmap,dops[i].rs1);
2539       //assert(t>=0);
2540       if(t>=0) {
2541         if(dops[i].rs1>0) {
2542             if(dops[i].opcode==0x0a) { // SLTI
2543               if(sl<0) {
2544                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2545                 emit_slti32(t,imm[i],t);
2546               }else{
2547                 emit_slti32(sl,imm[i],t);
2548               }
2549             }
2550             else { // SLTIU
2551               if(sl<0) {
2552                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2553                 emit_sltiu32(t,imm[i],t);
2554               }else{
2555                 emit_sltiu32(sl,imm[i],t);
2556               }
2557             }
2558         }else{
2559           // SLTI(U) with r0 is just stupid,
2560           // nonetheless examples can be found
2561           if(dops[i].opcode==0x0a) // SLTI
2562             if(0<imm[i]) emit_movimm(1,t);
2563             else emit_zeroreg(t);
2564           else // SLTIU
2565           {
2566             if(imm[i]) emit_movimm(1,t);
2567             else emit_zeroreg(t);
2568           }
2569         }
2570       }
2571     }
2572   }
2573   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
2574     if(dops[i].rt1) {
2575       signed char sl,tl;
2576       tl=get_reg(i_regs->regmap,dops[i].rt1);
2577       sl=get_reg(i_regs->regmap,dops[i].rs1);
2578       if(tl>=0 && !((i_regs->isconst>>tl)&1)) {
2579         if(dops[i].opcode==0x0c) //ANDI
2580         {
2581           if(dops[i].rs1) {
2582             if(sl<0) {
2583               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2584               emit_andimm(tl,imm[i],tl);
2585             }else{
2586               if(!((i_regs->wasconst>>sl)&1))
2587                 emit_andimm(sl,imm[i],tl);
2588               else
2589                 emit_movimm(constmap[i][sl]&imm[i],tl);
2590             }
2591           }
2592           else
2593             emit_zeroreg(tl);
2594         }
2595         else
2596         {
2597           if(dops[i].rs1) {
2598             if(sl<0) {
2599               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2600             }
2601             if(dops[i].opcode==0x0d) { // ORI
2602               if(sl<0) {
2603                 emit_orimm(tl,imm[i],tl);
2604               }else{
2605                 if(!((i_regs->wasconst>>sl)&1))
2606                   emit_orimm(sl,imm[i],tl);
2607                 else
2608                   emit_movimm(constmap[i][sl]|imm[i],tl);
2609               }
2610             }
2611             if(dops[i].opcode==0x0e) { // XORI
2612               if(sl<0) {
2613                 emit_xorimm(tl,imm[i],tl);
2614               }else{
2615                 if(!((i_regs->wasconst>>sl)&1))
2616                   emit_xorimm(sl,imm[i],tl);
2617                 else
2618                   emit_movimm(constmap[i][sl]^imm[i],tl);
2619               }
2620             }
2621           }
2622           else {
2623             emit_movimm(imm[i],tl);
2624           }
2625         }
2626       }
2627     }
2628   }
2629 }
2630
2631 static void shiftimm_assemble(int i, const struct regstat *i_regs)
2632 {
2633   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
2634   {
2635     if(dops[i].rt1) {
2636       signed char s,t;
2637       t=get_reg(i_regs->regmap,dops[i].rt1);
2638       s=get_reg(i_regs->regmap,dops[i].rs1);
2639       //assert(t>=0);
2640       if(t>=0&&!((i_regs->isconst>>t)&1)){
2641         if(dops[i].rs1==0)
2642         {
2643           emit_zeroreg(t);
2644         }
2645         else
2646         {
2647           if(s<0&&i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2648           if(imm[i]) {
2649             if(dops[i].opcode2==0) // SLL
2650             {
2651               emit_shlimm(s<0?t:s,imm[i],t);
2652             }
2653             if(dops[i].opcode2==2) // SRL
2654             {
2655               emit_shrimm(s<0?t:s,imm[i],t);
2656             }
2657             if(dops[i].opcode2==3) // SRA
2658             {
2659               emit_sarimm(s<0?t:s,imm[i],t);
2660             }
2661           }else{
2662             // Shift by zero
2663             if(s>=0 && s!=t) emit_mov(s,t);
2664           }
2665         }
2666       }
2667       //emit_storereg(dops[i].rt1,t); //DEBUG
2668     }
2669   }
2670   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
2671   {
2672     assert(0);
2673   }
2674   if(dops[i].opcode2==0x3c) // DSLL32
2675   {
2676     assert(0);
2677   }
2678   if(dops[i].opcode2==0x3e) // DSRL32
2679   {
2680     assert(0);
2681   }
2682   if(dops[i].opcode2==0x3f) // DSRA32
2683   {
2684     assert(0);
2685   }
2686 }
2687
2688 #ifndef shift_assemble
2689 static void shift_assemble(int i, const struct regstat *i_regs)
2690 {
2691   signed char s,t,shift;
2692   if (dops[i].rt1 == 0)
2693     return;
2694   assert(dops[i].opcode2<=0x07); // SLLV/SRLV/SRAV
2695   t = get_reg(i_regs->regmap, dops[i].rt1);
2696   s = get_reg(i_regs->regmap, dops[i].rs1);
2697   shift = get_reg(i_regs->regmap, dops[i].rs2);
2698   if (t < 0)
2699     return;
2700
2701   if(dops[i].rs1==0)
2702     emit_zeroreg(t);
2703   else if(dops[i].rs2==0) {
2704     assert(s>=0);
2705     if(s!=t) emit_mov(s,t);
2706   }
2707   else {
2708     host_tempreg_acquire();
2709     emit_andimm(shift,31,HOST_TEMPREG);
2710     switch(dops[i].opcode2) {
2711     case 4: // SLLV
2712       emit_shl(s,HOST_TEMPREG,t);
2713       break;
2714     case 6: // SRLV
2715       emit_shr(s,HOST_TEMPREG,t);
2716       break;
2717     case 7: // SRAV
2718       emit_sar(s,HOST_TEMPREG,t);
2719       break;
2720     default:
2721       assert(0);
2722     }
2723     host_tempreg_release();
2724   }
2725 }
2726
2727 #endif
2728
2729 enum {
2730   MTYPE_8000 = 0,
2731   MTYPE_8020,
2732   MTYPE_0000,
2733   MTYPE_A000,
2734   MTYPE_1F80,
2735 };
2736
2737 static int get_ptr_mem_type(u_int a)
2738 {
2739   if(a < 0x00200000) {
2740     if(a<0x1000&&((start>>20)==0xbfc||(start>>24)==0xa0))
2741       // return wrong, must use memhandler for BIOS self-test to pass
2742       // 007 does similar stuff from a00 mirror, weird stuff
2743       return MTYPE_8000;
2744     return MTYPE_0000;
2745   }
2746   if(0x1f800000 <= a && a < 0x1f801000)
2747     return MTYPE_1F80;
2748   if(0x80200000 <= a && a < 0x80800000)
2749     return MTYPE_8020;
2750   if(0xa0000000 <= a && a < 0xa0200000)
2751     return MTYPE_A000;
2752   return MTYPE_8000;
2753 }
2754
2755 static int get_ro_reg(const struct regstat *i_regs, int host_tempreg_free)
2756 {
2757   int r = get_reg(i_regs->regmap, ROREG);
2758   if (r < 0 && host_tempreg_free) {
2759     host_tempreg_acquire();
2760     emit_loadreg(ROREG, r = HOST_TEMPREG);
2761   }
2762   if (r < 0)
2763     abort();
2764   return r;
2765 }
2766
2767 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
2768   int addr, int *offset_reg, int *addr_reg_override)
2769 {
2770   void *jaddr = NULL;
2771   int type = 0;
2772   int mr = dops[i].rs1;
2773   *offset_reg = -1;
2774   if(((smrv_strong|smrv_weak)>>mr)&1) {
2775     type=get_ptr_mem_type(smrv[mr]);
2776     //printf("set %08x @%08x r%d %d\n", smrv[mr], start+i*4, mr, type);
2777   }
2778   else {
2779     // use the mirror we are running on
2780     type=get_ptr_mem_type(start);
2781     //printf("set nospec   @%08x r%d %d\n", start+i*4, mr, type);
2782   }
2783
2784   if(type==MTYPE_8020) { // RAM 80200000+ mirror
2785     host_tempreg_acquire();
2786     emit_andimm(addr,~0x00e00000,HOST_TEMPREG);
2787     addr=*addr_reg_override=HOST_TEMPREG;
2788     type=0;
2789   }
2790   else if(type==MTYPE_0000) { // RAM 0 mirror
2791     host_tempreg_acquire();
2792     emit_orimm(addr,0x80000000,HOST_TEMPREG);
2793     addr=*addr_reg_override=HOST_TEMPREG;
2794     type=0;
2795   }
2796   else if(type==MTYPE_A000) { // RAM A mirror
2797     host_tempreg_acquire();
2798     emit_andimm(addr,~0x20000000,HOST_TEMPREG);
2799     addr=*addr_reg_override=HOST_TEMPREG;
2800     type=0;
2801   }
2802   else if(type==MTYPE_1F80) { // scratchpad
2803     if (psxH == (void *)0x1f800000) {
2804       host_tempreg_acquire();
2805       emit_xorimm(addr,0x1f800000,HOST_TEMPREG);
2806       emit_cmpimm(HOST_TEMPREG,0x1000);
2807       host_tempreg_release();
2808       jaddr=out;
2809       emit_jc(0);
2810     }
2811     else {
2812       // do the usual RAM check, jump will go to the right handler
2813       type=0;
2814     }
2815   }
2816
2817   if (type == 0) // need ram check
2818   {
2819     emit_cmpimm(addr,RAM_SIZE);
2820     jaddr = out;
2821     #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
2822     // Hint to branch predictor that the branch is unlikely to be taken
2823     if (dops[i].rs1 >= 28)
2824       emit_jno_unlikely(0);
2825     else
2826     #endif
2827       emit_jno(0);
2828     if (ram_offset != 0)
2829       *offset_reg = get_ro_reg(i_regs, 0);
2830   }
2831
2832   return jaddr;
2833 }
2834
2835 // return memhandler, or get directly accessable address and return 0
2836 static void *get_direct_memhandler(void *table, u_int addr,
2837   enum stub_type type, uintptr_t *addr_host)
2838 {
2839   uintptr_t msb = 1ull << (sizeof(uintptr_t)*8 - 1);
2840   uintptr_t l1, l2 = 0;
2841   l1 = ((uintptr_t *)table)[addr>>12];
2842   if (!(l1 & msb)) {
2843     uintptr_t v = l1 << 1;
2844     *addr_host = v + addr;
2845     return NULL;
2846   }
2847   else {
2848     l1 <<= 1;
2849     if (type == LOADB_STUB || type == LOADBU_STUB || type == STOREB_STUB)
2850       l2 = ((uintptr_t *)l1)[0x1000/4 + 0x1000/2 + (addr&0xfff)];
2851     else if (type == LOADH_STUB || type == LOADHU_STUB || type == STOREH_STUB)
2852       l2 = ((uintptr_t *)l1)[0x1000/4 + (addr&0xfff)/2];
2853     else
2854       l2 = ((uintptr_t *)l1)[(addr&0xfff)/4];
2855     if (!(l2 & msb)) {
2856       uintptr_t v = l2 << 1;
2857       *addr_host = v + (addr&0xfff);
2858       return NULL;
2859     }
2860     return (void *)(l2 << 1);
2861   }
2862 }
2863
2864 static u_int get_host_reglist(const signed char *regmap)
2865 {
2866   u_int reglist = 0, hr;
2867   for (hr = 0; hr < HOST_REGS; hr++) {
2868     if (hr != EXCLUDE_REG && regmap[hr] >= 0)
2869       reglist |= 1 << hr;
2870   }
2871   return reglist;
2872 }
2873
2874 static u_int reglist_exclude(u_int reglist, int r1, int r2)
2875 {
2876   if (r1 >= 0)
2877     reglist &= ~(1u << r1);
2878   if (r2 >= 0)
2879     reglist &= ~(1u << r2);
2880   return reglist;
2881 }
2882
2883 // find a temp caller-saved register not in reglist (so assumed to be free)
2884 static int reglist_find_free(u_int reglist)
2885 {
2886   u_int free_regs = ~reglist & CALLER_SAVE_REGS;
2887   if (free_regs == 0)
2888     return -1;
2889   return __builtin_ctz(free_regs);
2890 }
2891
2892 static void do_load_word(int a, int rt, int offset_reg)
2893 {
2894   if (offset_reg >= 0)
2895     emit_ldr_dualindexed(offset_reg, a, rt);
2896   else
2897     emit_readword_indexed(0, a, rt);
2898 }
2899
2900 static void do_store_word(int a, int ofs, int rt, int offset_reg, int preseve_a)
2901 {
2902   if (offset_reg < 0) {
2903     emit_writeword_indexed(rt, ofs, a);
2904     return;
2905   }
2906   if (ofs != 0)
2907     emit_addimm(a, ofs, a);
2908   emit_str_dualindexed(offset_reg, a, rt);
2909   if (ofs != 0 && preseve_a)
2910     emit_addimm(a, -ofs, a);
2911 }
2912
2913 static void do_store_hword(int a, int ofs, int rt, int offset_reg, int preseve_a)
2914 {
2915   if (offset_reg < 0) {
2916     emit_writehword_indexed(rt, ofs, a);
2917     return;
2918   }
2919   if (ofs != 0)
2920     emit_addimm(a, ofs, a);
2921   emit_strh_dualindexed(offset_reg, a, rt);
2922   if (ofs != 0 && preseve_a)
2923     emit_addimm(a, -ofs, a);
2924 }
2925
2926 static void do_store_byte(int a, int rt, int offset_reg)
2927 {
2928   if (offset_reg >= 0)
2929     emit_strb_dualindexed(offset_reg, a, rt);
2930   else
2931     emit_writebyte_indexed(rt, 0, a);
2932 }
2933
2934 static void load_assemble(int i, const struct regstat *i_regs, int ccadj_)
2935 {
2936   int s,tl,addr;
2937   int offset;
2938   void *jaddr=0;
2939   int memtarget=0,c=0;
2940   int offset_reg = -1;
2941   int fastio_reg_override = -1;
2942   u_int reglist=get_host_reglist(i_regs->regmap);
2943   tl=get_reg(i_regs->regmap,dops[i].rt1);
2944   s=get_reg(i_regs->regmap,dops[i].rs1);
2945   offset=imm[i];
2946   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2947   if(s>=0) {
2948     c=(i_regs->wasconst>>s)&1;
2949     if (c) {
2950       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2951     }
2952   }
2953   //printf("load_assemble: c=%d\n",c);
2954   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2955   // FIXME: Even if the load is a NOP, we should check for pagefaults...
2956   if((tl<0&&(!c||(((u_int)constmap[i][s]+offset)>>16)==0x1f80))
2957     ||dops[i].rt1==0) {
2958       // could be FIFO, must perform the read
2959       // ||dummy read
2960       assem_debug("(forced read)\n");
2961       tl=get_reg_temp(i_regs->regmap);
2962       assert(tl>=0);
2963   }
2964   if(offset||s<0||c) addr=tl;
2965   else addr=s;
2966   //if(tl<0) tl=get_reg_temp(i_regs->regmap);
2967  if(tl>=0) {
2968   //printf("load_assemble: c=%d\n",c);
2969   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2970   assert(tl>=0); // Even if the load is a NOP, we must check for pagefaults and I/O
2971   reglist&=~(1<<tl);
2972   if(!c) {
2973     #ifdef R29_HACK
2974     // Strmnnrmn's speed hack
2975     if(dops[i].rs1!=29||start<0x80001000||start>=0x80000000+RAM_SIZE)
2976     #endif
2977     {
2978       jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
2979                 &offset_reg, &fastio_reg_override);
2980     }
2981   }
2982   else if (ram_offset && memtarget) {
2983     offset_reg = get_ro_reg(i_regs, 0);
2984   }
2985   int dummy=(dops[i].rt1==0)||(tl!=get_reg(i_regs->regmap,dops[i].rt1)); // ignore loads to r0 and unneeded reg
2986   switch (dops[i].opcode) {
2987   case 0x20: // LB
2988     if(!c||memtarget) {
2989       if(!dummy) {
2990         int a = tl;
2991         if (!c) a = addr;
2992         if (fastio_reg_override >= 0)
2993           a = fastio_reg_override;
2994
2995         if (offset_reg >= 0)
2996           emit_ldrsb_dualindexed(offset_reg, a, tl);
2997         else
2998           emit_movsbl_indexed(0, a, tl);
2999       }
3000       if(jaddr)
3001         add_stub_r(LOADB_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3002     }
3003     else
3004       inline_readstub(LOADB_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3005     break;
3006   case 0x21: // LH
3007     if(!c||memtarget) {
3008       if(!dummy) {
3009         int a = tl;
3010         if (!c) a = addr;
3011         if (fastio_reg_override >= 0)
3012           a = fastio_reg_override;
3013         if (offset_reg >= 0)
3014           emit_ldrsh_dualindexed(offset_reg, a, tl);
3015         else
3016           emit_movswl_indexed(0, a, tl);
3017       }
3018       if(jaddr)
3019         add_stub_r(LOADH_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3020     }
3021     else
3022       inline_readstub(LOADH_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3023     break;
3024   case 0x23: // LW
3025     if(!c||memtarget) {
3026       if(!dummy) {
3027         int a = addr;
3028         if (fastio_reg_override >= 0)
3029           a = fastio_reg_override;
3030         do_load_word(a, tl, offset_reg);
3031       }
3032       if(jaddr)
3033         add_stub_r(LOADW_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3034     }
3035     else
3036       inline_readstub(LOADW_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3037     break;
3038   case 0x24: // LBU
3039     if(!c||memtarget) {
3040       if(!dummy) {
3041         int a = tl;
3042         if (!c) a = addr;
3043         if (fastio_reg_override >= 0)
3044           a = fastio_reg_override;
3045
3046         if (offset_reg >= 0)
3047           emit_ldrb_dualindexed(offset_reg, a, tl);
3048         else
3049           emit_movzbl_indexed(0, a, tl);
3050       }
3051       if(jaddr)
3052         add_stub_r(LOADBU_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3053     }
3054     else
3055       inline_readstub(LOADBU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3056     break;
3057   case 0x25: // LHU
3058     if(!c||memtarget) {
3059       if(!dummy) {
3060         int a = tl;
3061         if(!c) a = addr;
3062         if (fastio_reg_override >= 0)
3063           a = fastio_reg_override;
3064         if (offset_reg >= 0)
3065           emit_ldrh_dualindexed(offset_reg, a, tl);
3066         else
3067           emit_movzwl_indexed(0, a, tl);
3068       }
3069       if(jaddr)
3070         add_stub_r(LOADHU_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3071     }
3072     else
3073       inline_readstub(LOADHU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3074     break;
3075   case 0x27: // LWU
3076   case 0x37: // LD
3077   default:
3078     assert(0);
3079   }
3080  }
3081  if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3082    host_tempreg_release();
3083 }
3084
3085 #ifndef loadlr_assemble
3086 static void loadlr_assemble(int i, const struct regstat *i_regs, int ccadj_)
3087 {
3088   int s,tl,temp,temp2,addr;
3089   int offset;
3090   void *jaddr=0;
3091   int memtarget=0,c=0;
3092   int offset_reg = -1;
3093   int fastio_reg_override = -1;
3094   u_int reglist=get_host_reglist(i_regs->regmap);
3095   tl=get_reg(i_regs->regmap,dops[i].rt1);
3096   s=get_reg(i_regs->regmap,dops[i].rs1);
3097   temp=get_reg_temp(i_regs->regmap);
3098   temp2=get_reg(i_regs->regmap,FTEMP);
3099   addr=get_reg(i_regs->regmap,AGEN1+(i&1));
3100   assert(addr<0);
3101   offset=imm[i];
3102   reglist|=1<<temp;
3103   if(offset||s<0||c) addr=temp2;
3104   else addr=s;
3105   if(s>=0) {
3106     c=(i_regs->wasconst>>s)&1;
3107     if(c) {
3108       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3109     }
3110   }
3111   if(!c) {
3112     emit_shlimm(addr,3,temp);
3113     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
3114       emit_andimm(addr,0xFFFFFFFC,temp2); // LWL/LWR
3115     }else{
3116       emit_andimm(addr,0xFFFFFFF8,temp2); // LDL/LDR
3117     }
3118     jaddr = emit_fastpath_cmp_jump(i, i_regs, temp2,
3119               &offset_reg, &fastio_reg_override);
3120   }
3121   else {
3122     if (ram_offset && memtarget) {
3123       offset_reg = get_ro_reg(i_regs, 0);
3124     }
3125     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
3126       emit_movimm(((constmap[i][s]+offset)<<3)&24,temp); // LWL/LWR
3127     }else{
3128       emit_movimm(((constmap[i][s]+offset)<<3)&56,temp); // LDL/LDR
3129     }
3130   }
3131   if (dops[i].opcode==0x22||dops[i].opcode==0x26) { // LWL/LWR
3132     if(!c||memtarget) {
3133       int a = temp2;
3134       if (fastio_reg_override >= 0)
3135         a = fastio_reg_override;
3136       do_load_word(a, temp2, offset_reg);
3137       if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3138         host_tempreg_release();
3139       if(jaddr) add_stub_r(LOADW_STUB,jaddr,out,i,temp2,i_regs,ccadj_,reglist);
3140     }
3141     else
3142       inline_readstub(LOADW_STUB,i,(constmap[i][s]+offset)&0xFFFFFFFC,i_regs->regmap,FTEMP,ccadj_,reglist);
3143     if(dops[i].rt1) {
3144       assert(tl>=0);
3145       emit_andimm(temp,24,temp);
3146       if (dops[i].opcode==0x22) // LWL
3147         emit_xorimm(temp,24,temp);
3148       host_tempreg_acquire();
3149       emit_movimm(-1,HOST_TEMPREG);
3150       if (dops[i].opcode==0x26) {
3151         emit_shr(temp2,temp,temp2);
3152         emit_bic_lsr(tl,HOST_TEMPREG,temp,tl);
3153       }else{
3154         emit_shl(temp2,temp,temp2);
3155         emit_bic_lsl(tl,HOST_TEMPREG,temp,tl);
3156       }
3157       host_tempreg_release();
3158       emit_or(temp2,tl,tl);
3159     }
3160     //emit_storereg(dops[i].rt1,tl); // DEBUG
3161   }
3162   if (dops[i].opcode==0x1A||dops[i].opcode==0x1B) { // LDL/LDR
3163     assert(0);
3164   }
3165 }
3166 #endif
3167
3168 static void do_invstub(int n)
3169 {
3170   literal_pool(20);
3171   assem_debug("do_invstub\n");
3172   u_int reglist = stubs[n].a;
3173   u_int addrr = stubs[n].b;
3174   int ofs_start = stubs[n].c;
3175   int ofs_end = stubs[n].d;
3176   int len = ofs_end - ofs_start;
3177   u_int rightr = 0;
3178
3179   set_jump_target(stubs[n].addr, out);
3180   save_regs(reglist);
3181   if (addrr != 0 || ofs_start != 0)
3182     emit_addimm(addrr, ofs_start, 0);
3183   emit_readword(&inv_code_start, 2);
3184   emit_readword(&inv_code_end, 3);
3185   if (len != 0)
3186     emit_addimm(0, len + 4, (rightr = 1));
3187   emit_cmp(0, 2);
3188   emit_cmpcs(3, rightr);
3189   void *jaddr = out;
3190   emit_jc(0);
3191   void *func = (len != 0)
3192     ? (void *)ndrc_write_invalidate_many
3193     : (void *)ndrc_write_invalidate_one;
3194   emit_far_call(func);
3195   set_jump_target(jaddr, out);
3196   restore_regs(reglist);
3197   emit_jmp(stubs[n].retaddr);
3198 }
3199
3200 static void do_store_smc_check(int i, const struct regstat *i_regs, u_int reglist, int addr)
3201 {
3202   if (HACK_ENABLED(NDHACK_NO_SMC_CHECK))
3203     return;
3204   // this can't be used any more since we started to check exact
3205   // block boundaries in invalidate_range()
3206   //if (i_regs->waswritten & (1<<dops[i].rs1))
3207   //  return;
3208   // (naively) assume nobody will run code from stack
3209   if (dops[i].rs1 == 29)
3210     return;
3211
3212   int j, imm_maxdiff = 32, imm_min = imm[i], imm_max = imm[i], count = 1;
3213   if (i < slen - 1 && dops[i+1].is_store && dops[i+1].rs1 == dops[i].rs1
3214       && abs(imm[i+1] - imm[i]) <= imm_maxdiff)
3215     return;
3216   for (j = i - 1; j >= 0; j--) {
3217     if (!dops[j].is_store || dops[j].rs1 != dops[i].rs1
3218         || abs(imm[j] - imm[j+1]) > imm_maxdiff)
3219       break;
3220     count++;
3221     if (imm_min > imm[j])
3222       imm_min = imm[j];
3223     if (imm_max < imm[j])
3224       imm_max = imm[j];
3225   }
3226 #if defined(HOST_IMM8)
3227   int ir = get_reg(i_regs->regmap, INVCP);
3228   assert(ir >= 0);
3229   host_tempreg_acquire();
3230   emit_ldrb_indexedsr12_reg(ir, addr, HOST_TEMPREG);
3231 #else
3232   emit_cmpmem_indexedsr12_imm(invalid_code, addr, 1);
3233   #error not handled
3234 #endif
3235 #ifdef INVALIDATE_USE_COND_CALL
3236   if (count == 1) {
3237     emit_cmpimm(HOST_TEMPREG, 1);
3238     emit_callne(invalidate_addr_reg[addr]);
3239     host_tempreg_release();
3240     return;
3241   }
3242 #endif
3243   void *jaddr = emit_cbz(HOST_TEMPREG, 0);
3244   host_tempreg_release();
3245   imm_min -= imm[i];
3246   imm_max -= imm[i];
3247   add_stub(INVCODE_STUB, jaddr, out, reglist|(1<<HOST_CCREG),
3248     addr, imm_min, imm_max, 0);
3249 }
3250
3251 static void store_assemble(int i, const struct regstat *i_regs, int ccadj_)
3252 {
3253   int s,tl;
3254   int addr,temp;
3255   int offset;
3256   void *jaddr=0;
3257   enum stub_type type=0;
3258   int memtarget=0,c=0;
3259   int agr=AGEN1+(i&1);
3260   int offset_reg = -1;
3261   int fastio_reg_override = -1;
3262   u_int reglist=get_host_reglist(i_regs->regmap);
3263   tl=get_reg(i_regs->regmap,dops[i].rs2);
3264   s=get_reg(i_regs->regmap,dops[i].rs1);
3265   temp=get_reg(i_regs->regmap,agr);
3266   if(temp<0) temp=get_reg_temp(i_regs->regmap);
3267   offset=imm[i];
3268   if(s>=0) {
3269     c=(i_regs->wasconst>>s)&1;
3270     if(c) {
3271       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3272     }
3273   }
3274   assert(tl>=0);
3275   assert(temp>=0);
3276   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
3277   if(offset||s<0||c) addr=temp;
3278   else addr=s;
3279   if (!c) {
3280     jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
3281               &offset_reg, &fastio_reg_override);
3282   }
3283   else if (ram_offset && memtarget) {
3284     offset_reg = get_ro_reg(i_regs, 0);
3285   }
3286
3287   switch (dops[i].opcode) {
3288   case 0x28: // SB
3289     if(!c||memtarget) {
3290       int a = temp;
3291       if (!c) a = addr;
3292       if (fastio_reg_override >= 0)
3293         a = fastio_reg_override;
3294       do_store_byte(a, tl, offset_reg);
3295     }
3296     type = STOREB_STUB;
3297     break;
3298   case 0x29: // SH
3299     if(!c||memtarget) {
3300       int a = temp;
3301       if (!c) a = addr;
3302       if (fastio_reg_override >= 0)
3303         a = fastio_reg_override;
3304       do_store_hword(a, 0, tl, offset_reg, 1);
3305     }
3306     type = STOREH_STUB;
3307     break;
3308   case 0x2B: // SW
3309     if(!c||memtarget) {
3310       int a = addr;
3311       if (fastio_reg_override >= 0)
3312         a = fastio_reg_override;
3313       do_store_word(a, 0, tl, offset_reg, 1);
3314     }
3315     type = STOREW_STUB;
3316     break;
3317   case 0x3F: // SD
3318   default:
3319     assert(0);
3320   }
3321   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3322     host_tempreg_release();
3323   if(jaddr) {
3324     // PCSX store handlers don't check invcode again
3325     reglist|=1<<addr;
3326     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3327     jaddr=0;
3328   }
3329   {
3330     if(!c||memtarget) {
3331       #ifdef DESTRUCTIVE_SHIFT
3332       // The x86 shift operation is 'destructive'; it overwrites the
3333       // source register, so we need to make a copy first and use that.
3334       addr=temp;
3335       #endif
3336       do_store_smc_check(i, i_regs, reglist, addr);
3337     }
3338   }
3339   u_int addr_val=constmap[i][s]+offset;
3340   if(jaddr) {
3341     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3342   } else if(c&&!memtarget) {
3343     inline_writestub(type,i,addr_val,i_regs->regmap,dops[i].rs2,ccadj_,reglist);
3344   }
3345   // basic current block modification detection..
3346   // not looking back as that should be in mips cache already
3347   // (see Spyro2 title->attract mode)
3348   if(c&&start+i*4<addr_val&&addr_val<start+slen*4) {
3349     SysPrintf("write to %08x hits block %08x, pc=%08x\n",addr_val,start,start+i*4);
3350     assert(i_regs->regmap==regs[i].regmap); // not delay slot
3351     if(i_regs->regmap==regs[i].regmap) {
3352       load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3353       wb_dirtys(regs[i].regmap_entry,regs[i].wasdirty);
3354       emit_movimm(start+i*4+4,0);
3355       emit_writeword(0,&pcaddr);
3356       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3357       emit_far_call(ndrc_get_addr_ht);
3358       emit_jmpreg(0);
3359     }
3360   }
3361 }
3362
3363 static void storelr_assemble(int i, const struct regstat *i_regs, int ccadj_)
3364 {
3365   int s,tl;
3366   int temp;
3367   int offset;
3368   void *jaddr=0;
3369   void *case1, *case23, *case3;
3370   void *done0, *done1, *done2;
3371   int memtarget=0,c=0;
3372   int agr=AGEN1+(i&1);
3373   int offset_reg = -1;
3374   u_int reglist=get_host_reglist(i_regs->regmap);
3375   tl=get_reg(i_regs->regmap,dops[i].rs2);
3376   s=get_reg(i_regs->regmap,dops[i].rs1);
3377   temp=get_reg(i_regs->regmap,agr);
3378   if(temp<0) temp=get_reg_temp(i_regs->regmap);
3379   offset=imm[i];
3380   if(s>=0) {
3381     c=(i_regs->isconst>>s)&1;
3382     if(c) {
3383       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3384     }
3385   }
3386   assert(tl>=0);
3387   assert(temp>=0);
3388   if(!c) {
3389     emit_cmpimm(s<0||offset?temp:s,RAM_SIZE);
3390     if(!offset&&s!=temp) emit_mov(s,temp);
3391     jaddr=out;
3392     emit_jno(0);
3393   }
3394   else
3395   {
3396     if(!memtarget||!dops[i].rs1) {
3397       jaddr=out;
3398       emit_jmp(0);
3399     }
3400   }
3401   if (ram_offset)
3402     offset_reg = get_ro_reg(i_regs, 0);
3403
3404   if (dops[i].opcode==0x2C||dops[i].opcode==0x2D) { // SDL/SDR
3405     assert(0);
3406   }
3407
3408   emit_testimm(temp,2);
3409   case23=out;
3410   emit_jne(0);
3411   emit_testimm(temp,1);
3412   case1=out;
3413   emit_jne(0);
3414   // 0
3415   if (dops[i].opcode == 0x2A) { // SWL
3416     // Write msb into least significant byte
3417     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3418     do_store_byte(temp, tl, offset_reg);
3419     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3420   }
3421   else if (dops[i].opcode == 0x2E) { // SWR
3422     // Write entire word
3423     do_store_word(temp, 0, tl, offset_reg, 1);
3424   }
3425   done0 = out;
3426   emit_jmp(0);
3427   // 1
3428   set_jump_target(case1, out);
3429   if (dops[i].opcode == 0x2A) { // SWL
3430     // Write two msb into two least significant bytes
3431     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3432     do_store_hword(temp, -1, tl, offset_reg, 0);
3433     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3434   }
3435   else if (dops[i].opcode == 0x2E) { // SWR
3436     // Write 3 lsb into three most significant bytes
3437     do_store_byte(temp, tl, offset_reg);
3438     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3439     do_store_hword(temp, 1, tl, offset_reg, 0);
3440     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3441   }
3442   done1=out;
3443   emit_jmp(0);
3444   // 2,3
3445   set_jump_target(case23, out);
3446   emit_testimm(temp,1);
3447   case3 = out;
3448   emit_jne(0);
3449   // 2
3450   if (dops[i].opcode==0x2A) { // SWL
3451     // Write 3 msb into three least significant bytes
3452     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3453     do_store_hword(temp, -2, tl, offset_reg, 1);
3454     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3455     do_store_byte(temp, tl, offset_reg);
3456     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3457   }
3458   else if (dops[i].opcode == 0x2E) { // SWR
3459     // Write two lsb into two most significant bytes
3460     do_store_hword(temp, 0, tl, offset_reg, 1);
3461   }
3462   done2 = out;
3463   emit_jmp(0);
3464   // 3
3465   set_jump_target(case3, out);
3466   if (dops[i].opcode == 0x2A) { // SWL
3467     do_store_word(temp, -3, tl, offset_reg, 0);
3468   }
3469   else if (dops[i].opcode == 0x2E) { // SWR
3470     do_store_byte(temp, tl, offset_reg);
3471   }
3472   set_jump_target(done0, out);
3473   set_jump_target(done1, out);
3474   set_jump_target(done2, out);
3475   if (offset_reg == HOST_TEMPREG)
3476     host_tempreg_release();
3477   if(!c||!memtarget)
3478     add_stub_r(STORELR_STUB,jaddr,out,i,temp,i_regs,ccadj_,reglist);
3479   do_store_smc_check(i, i_regs, reglist, temp);
3480 }
3481
3482 static void cop0_assemble(int i, const struct regstat *i_regs, int ccadj_)
3483 {
3484   if(dops[i].opcode2==0) // MFC0
3485   {
3486     signed char t=get_reg(i_regs->regmap,dops[i].rt1);
3487     u_int copr=(source[i]>>11)&0x1f;
3488     //assert(t>=0); // Why does this happen?  OOT is weird
3489     if(t>=0&&dops[i].rt1!=0) {
3490       emit_readword(&reg_cop0[copr],t);
3491     }
3492   }
3493   else if(dops[i].opcode2==4) // MTC0
3494   {
3495     signed char s=get_reg(i_regs->regmap,dops[i].rs1);
3496     char copr=(source[i]>>11)&0x1f;
3497     assert(s>=0);
3498     wb_register(dops[i].rs1,i_regs->regmap,i_regs->dirty);
3499     if(copr==9||copr==11||copr==12||copr==13) {
3500       emit_readword(&last_count,HOST_TEMPREG);
3501       emit_loadreg(CCREG,HOST_CCREG); // TODO: do proper reg alloc
3502       emit_add(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3503       emit_addimm(HOST_CCREG,ccadj_,HOST_CCREG);
3504       emit_writeword(HOST_CCREG,&psxRegs.cycle);
3505     }
3506     // What a mess.  The status register (12) can enable interrupts,
3507     // so needs a special case to handle a pending interrupt.
3508     // The interrupt must be taken immediately, because a subsequent
3509     // instruction might disable interrupts again.
3510     if(copr==12||copr==13) {
3511       if (is_delayslot) {
3512         // burn cycles to cause cc_interrupt, which will
3513         // reschedule next_interupt. Relies on CCREG from above.
3514         assem_debug("MTC0 DS %d\n", copr);
3515         emit_writeword(HOST_CCREG,&last_count);
3516         emit_movimm(0,HOST_CCREG);
3517         emit_storereg(CCREG,HOST_CCREG);
3518         emit_loadreg(dops[i].rs1,1);
3519         emit_movimm(copr,0);
3520         emit_far_call(pcsx_mtc0_ds);
3521         emit_loadreg(dops[i].rs1,s);
3522         return;
3523       }
3524       emit_movimm(start+i*4+4,HOST_TEMPREG);
3525       emit_writeword(HOST_TEMPREG,&pcaddr);
3526       emit_movimm(0,HOST_TEMPREG);
3527       emit_writeword(HOST_TEMPREG,&pending_exception);
3528     }
3529     if(s==HOST_CCREG)
3530       emit_loadreg(dops[i].rs1,1);
3531     else if(s!=1)
3532       emit_mov(s,1);
3533     emit_movimm(copr,0);
3534     emit_far_call(pcsx_mtc0);
3535     if(copr==9||copr==11||copr==12||copr==13) {
3536       emit_readword(&psxRegs.cycle,HOST_CCREG);
3537       emit_readword(&next_interupt,HOST_TEMPREG);
3538       emit_addimm(HOST_CCREG,-ccadj_,HOST_CCREG);
3539       emit_sub(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3540       emit_writeword(HOST_TEMPREG,&last_count);
3541       emit_storereg(CCREG,HOST_CCREG);
3542     }
3543     if(copr==12||copr==13) {
3544       assert(!is_delayslot);
3545       emit_readword(&pending_exception,HOST_TEMPREG);
3546       emit_test(HOST_TEMPREG,HOST_TEMPREG);
3547       void *jaddr = out;
3548       emit_jeq(0);
3549       emit_readword(&pcaddr, 0);
3550       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3551       emit_far_call(ndrc_get_addr_ht);
3552       emit_jmpreg(0);
3553       set_jump_target(jaddr, out);
3554     }
3555     emit_loadreg(dops[i].rs1,s);
3556   }
3557   else
3558   {
3559     assert(dops[i].opcode2==0x10);
3560     //if((source[i]&0x3f)==0x10) // RFE
3561     {
3562       emit_readword(&psxRegs.CP0.n.SR,0);
3563       emit_andimm(0,0x3c,1);
3564       emit_andimm(0,~0xf,0);
3565       emit_orrshr_imm(1,2,0);
3566       emit_writeword(0,&psxRegs.CP0.n.SR);
3567     }
3568   }
3569 }
3570
3571 static void cop1_unusable(int i, const struct regstat *i_regs)
3572 {
3573   // XXX: should just just do the exception instead
3574   //if(!cop1_usable)
3575   {
3576     void *jaddr=out;
3577     emit_jmp(0);
3578     add_stub_r(FP_STUB,jaddr,out,i,0,i_regs,is_delayslot,0);
3579   }
3580 }
3581
3582 static void cop1_assemble(int i, const struct regstat *i_regs)
3583 {
3584   cop1_unusable(i, i_regs);
3585 }
3586
3587 static void c1ls_assemble(int i, const struct regstat *i_regs)
3588 {
3589   cop1_unusable(i, i_regs);
3590 }
3591
3592 // FP_STUB
3593 static void do_cop1stub(int n)
3594 {
3595   literal_pool(256);
3596   assem_debug("do_cop1stub %x\n",start+stubs[n].a*4);
3597   set_jump_target(stubs[n].addr, out);
3598   int i=stubs[n].a;
3599 //  int rs=stubs[n].b;
3600   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3601   int ds=stubs[n].d;
3602   if(!ds) {
3603     load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3604     //if(i_regs!=&regs[i]) printf("oops: regs[i]=%x i_regs=%x",(int)&regs[i],(int)i_regs);
3605   }
3606   //else {printf("fp exception in delay slot\n");}
3607   wb_dirtys(i_regs->regmap_entry,i_regs->wasdirty);
3608   if(regs[i].regmap_entry[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
3609   emit_movimm(start+(i-ds)*4,0); // Get PC
3610   emit_addimm(HOST_CCREG,ccadj[i],HOST_CCREG); // CHECK: is this right?  There should probably be an extra cycle...
3611   emit_far_jump(ds?fp_exception_ds:fp_exception);
3612 }
3613
3614 static int cop2_is_stalling_op(int i, int *cycles)
3615 {
3616   if (dops[i].opcode == 0x3a) { // SWC2
3617     *cycles = 0;
3618     return 1;
3619   }
3620   if (dops[i].itype == COP2 && (dops[i].opcode2 == 0 || dops[i].opcode2 == 2)) { // MFC2/CFC2
3621     *cycles = 0;
3622     return 1;
3623   }
3624   if (dops[i].itype == C2OP) {
3625     *cycles = gte_cycletab[source[i] & 0x3f];
3626     return 1;
3627   }
3628   // ... what about MTC2/CTC2/LWC2?
3629   return 0;
3630 }
3631
3632 #if 0
3633 static void log_gte_stall(int stall, u_int cycle)
3634 {
3635   if ((u_int)stall <= 44)
3636     printf("x    stall %2d %u\n", stall, cycle + last_count);
3637 }
3638
3639 static void emit_log_gte_stall(int i, int stall, u_int reglist)
3640 {
3641   save_regs(reglist);
3642   if (stall > 0)
3643     emit_movimm(stall, 0);
3644   else
3645     emit_mov(HOST_TEMPREG, 0);
3646   emit_addimm(HOST_CCREG, ccadj[i], 1);
3647   emit_far_call(log_gte_stall);
3648   restore_regs(reglist);
3649 }
3650 #endif
3651
3652 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist)
3653 {
3654   int j = i, other_gte_op_cycles = -1, stall = -MAXBLOCK, cycles_passed;
3655   int rtmp = reglist_find_free(reglist);
3656
3657   if (HACK_ENABLED(NDHACK_NO_STALLS))
3658     return;
3659   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3660     // happens occasionally... cc evicted? Don't bother then
3661     //printf("no cc %08x\n", start + i*4);
3662     return;
3663   }
3664   if (!dops[i].bt) {
3665     for (j = i - 1; j >= 0; j--) {
3666       //if (dops[j].is_ds) break;
3667       if (cop2_is_stalling_op(j, &other_gte_op_cycles) || dops[j].bt)
3668         break;
3669       if (j > 0 && ccadj[j - 1] > ccadj[j])
3670         break;
3671     }
3672     j = max(j, 0);
3673   }
3674   cycles_passed = ccadj[i] - ccadj[j];
3675   if (other_gte_op_cycles >= 0)
3676     stall = other_gte_op_cycles - cycles_passed;
3677   else if (cycles_passed >= 44)
3678     stall = 0; // can't stall
3679   if (stall == -MAXBLOCK && rtmp >= 0) {
3680     // unknown stall, do the expensive runtime check
3681     assem_debug("; cop2_do_stall_check\n");
3682 #if 0 // too slow
3683     save_regs(reglist);
3684     emit_movimm(gte_cycletab[op], 0);
3685     emit_addimm(HOST_CCREG, ccadj[i], 1);
3686     emit_far_call(call_gteStall);
3687     restore_regs(reglist);
3688 #else
3689     host_tempreg_acquire();
3690     emit_readword(&psxRegs.gteBusyCycle, rtmp);
3691     emit_addimm(rtmp, -ccadj[i], rtmp);
3692     emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3693     emit_cmpimm(HOST_TEMPREG, 44);
3694     emit_cmovb_reg(rtmp, HOST_CCREG);
3695     //emit_log_gte_stall(i, 0, reglist);
3696     host_tempreg_release();
3697 #endif
3698   }
3699   else if (stall > 0) {
3700     //emit_log_gte_stall(i, stall, reglist);
3701     emit_addimm(HOST_CCREG, stall, HOST_CCREG);
3702   }
3703
3704   // save gteBusyCycle, if needed
3705   if (gte_cycletab[op] == 0)
3706     return;
3707   other_gte_op_cycles = -1;
3708   for (j = i + 1; j < slen; j++) {
3709     if (cop2_is_stalling_op(j, &other_gte_op_cycles))
3710       break;
3711     if (dops[j].is_jump) {
3712       // check ds
3713       if (j + 1 < slen && cop2_is_stalling_op(j + 1, &other_gte_op_cycles))
3714         j++;
3715       break;
3716     }
3717   }
3718   if (other_gte_op_cycles >= 0)
3719     // will handle stall when assembling that op
3720     return;
3721   cycles_passed = ccadj[min(j, slen -1)] - ccadj[i];
3722   if (cycles_passed >= 44)
3723     return;
3724   assem_debug("; save gteBusyCycle\n");
3725   host_tempreg_acquire();
3726 #if 0
3727   emit_readword(&last_count, HOST_TEMPREG);
3728   emit_add(HOST_TEMPREG, HOST_CCREG, HOST_TEMPREG);
3729   emit_addimm(HOST_TEMPREG, ccadj[i], HOST_TEMPREG);
3730   emit_addimm(HOST_TEMPREG, gte_cycletab[op]), HOST_TEMPREG);
3731   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3732 #else
3733   emit_addimm(HOST_CCREG, ccadj[i] + gte_cycletab[op], HOST_TEMPREG);
3734   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3735 #endif
3736   host_tempreg_release();
3737 }
3738
3739 static int is_mflohi(int i)
3740 {
3741   return (dops[i].itype == MOV && (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG));
3742 }
3743
3744 static int check_multdiv(int i, int *cycles)
3745 {
3746   if (dops[i].itype != MULTDIV)
3747     return 0;
3748   if (dops[i].opcode2 == 0x18 || dops[i].opcode2 == 0x19) // MULT(U)
3749     *cycles = 11; // approx from 7 11 14
3750   else
3751     *cycles = 37;
3752   return 1;
3753 }
3754
3755 static void multdiv_prepare_stall(int i, const struct regstat *i_regs, int ccadj_)
3756 {
3757   int j, found = 0, c = 0;
3758   if (HACK_ENABLED(NDHACK_NO_STALLS))
3759     return;
3760   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3761     // happens occasionally... cc evicted? Don't bother then
3762     return;
3763   }
3764   for (j = i + 1; j < slen; j++) {
3765     if (dops[j].bt)
3766       break;
3767     if ((found = is_mflohi(j)))
3768       break;
3769     if (dops[j].is_jump) {
3770       // check ds
3771       if (j + 1 < slen && (found = is_mflohi(j + 1)))
3772         j++;
3773       break;
3774     }
3775   }
3776   if (found)
3777     // handle all in multdiv_do_stall()
3778     return;
3779   check_multdiv(i, &c);
3780   assert(c > 0);
3781   assem_debug("; muldiv prepare stall %d\n", c);
3782   host_tempreg_acquire();
3783   emit_addimm(HOST_CCREG, ccadj_ + c, HOST_TEMPREG);
3784   emit_writeword(HOST_TEMPREG, &psxRegs.muldivBusyCycle);
3785   host_tempreg_release();
3786 }
3787
3788 static void multdiv_do_stall(int i, const struct regstat *i_regs)
3789 {
3790   int j, known_cycles = 0;
3791   u_int reglist = get_host_reglist(i_regs->regmap);
3792   int rtmp = get_reg_temp(i_regs->regmap);
3793   if (rtmp < 0)
3794     rtmp = reglist_find_free(reglist);
3795   if (HACK_ENABLED(NDHACK_NO_STALLS))
3796     return;
3797   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG || rtmp < 0) {
3798     // happens occasionally... cc evicted? Don't bother then
3799     //printf("no cc/rtmp %08x\n", start + i*4);
3800     return;
3801   }
3802   if (!dops[i].bt) {
3803     for (j = i - 1; j >= 0; j--) {
3804       if (dops[j].is_ds) break;
3805       if (check_multdiv(j, &known_cycles))
3806         break;
3807       if (is_mflohi(j))
3808         // already handled by this op
3809         return;
3810       if (dops[j].bt || (j > 0 && ccadj[j - 1] > ccadj[j]))
3811         break;
3812     }
3813     j = max(j, 0);
3814   }
3815   if (known_cycles > 0) {
3816     known_cycles -= ccadj[i] - ccadj[j];
3817     assem_debug("; muldiv stall resolved %d\n", known_cycles);
3818     if (known_cycles > 0)
3819       emit_addimm(HOST_CCREG, known_cycles, HOST_CCREG);
3820     return;
3821   }
3822   assem_debug("; muldiv stall unresolved\n");
3823   host_tempreg_acquire();
3824   emit_readword(&psxRegs.muldivBusyCycle, rtmp);
3825   emit_addimm(rtmp, -ccadj[i], rtmp);
3826   emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3827   emit_cmpimm(HOST_TEMPREG, 37);
3828   emit_cmovb_reg(rtmp, HOST_CCREG);
3829   //emit_log_gte_stall(i, 0, reglist);
3830   host_tempreg_release();
3831 }
3832
3833 static void cop2_get_dreg(u_int copr,signed char tl,signed char temp)
3834 {
3835   switch (copr) {
3836     case 1:
3837     case 3:
3838     case 5:
3839     case 8:
3840     case 9:
3841     case 10:
3842     case 11:
3843       emit_readword(&reg_cop2d[copr],tl);
3844       emit_signextend16(tl,tl);
3845       emit_writeword(tl,&reg_cop2d[copr]); // hmh
3846       break;
3847     case 7:
3848     case 16:
3849     case 17:
3850     case 18:
3851     case 19:
3852       emit_readword(&reg_cop2d[copr],tl);
3853       emit_andimm(tl,0xffff,tl);
3854       emit_writeword(tl,&reg_cop2d[copr]);
3855       break;
3856     case 15:
3857       emit_readword(&reg_cop2d[14],tl); // SXY2
3858       emit_writeword(tl,&reg_cop2d[copr]);
3859       break;
3860     case 28:
3861     case 29:
3862       c2op_mfc2_29_assemble(tl,temp);
3863       break;
3864     default:
3865       emit_readword(&reg_cop2d[copr],tl);
3866       break;
3867   }
3868 }
3869
3870 static void cop2_put_dreg(u_int copr,signed char sl,signed char temp)
3871 {
3872   switch (copr) {
3873     case 15:
3874       emit_readword(&reg_cop2d[13],temp);  // SXY1
3875       emit_writeword(sl,&reg_cop2d[copr]);
3876       emit_writeword(temp,&reg_cop2d[12]); // SXY0
3877       emit_readword(&reg_cop2d[14],temp);  // SXY2
3878       emit_writeword(sl,&reg_cop2d[14]);
3879       emit_writeword(temp,&reg_cop2d[13]); // SXY1
3880       break;
3881     case 28:
3882       emit_andimm(sl,0x001f,temp);
3883       emit_shlimm(temp,7,temp);
3884       emit_writeword(temp,&reg_cop2d[9]);
3885       emit_andimm(sl,0x03e0,temp);
3886       emit_shlimm(temp,2,temp);
3887       emit_writeword(temp,&reg_cop2d[10]);
3888       emit_andimm(sl,0x7c00,temp);
3889       emit_shrimm(temp,3,temp);
3890       emit_writeword(temp,&reg_cop2d[11]);
3891       emit_writeword(sl,&reg_cop2d[28]);
3892       break;
3893     case 30:
3894       emit_xorsar_imm(sl,sl,31,temp);
3895 #if defined(HAVE_ARMV5) || defined(__aarch64__)
3896       emit_clz(temp,temp);
3897 #else
3898       emit_movs(temp,HOST_TEMPREG);
3899       emit_movimm(0,temp);
3900       emit_jeq((int)out+4*4);
3901       emit_addpl_imm(temp,1,temp);
3902       emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
3903       emit_jns((int)out-2*4);
3904 #endif
3905       emit_writeword(sl,&reg_cop2d[30]);
3906       emit_writeword(temp,&reg_cop2d[31]);
3907       break;
3908     case 31:
3909       break;
3910     default:
3911       emit_writeword(sl,&reg_cop2d[copr]);
3912       break;
3913   }
3914 }
3915
3916 static void c2ls_assemble(int i, const struct regstat *i_regs, int ccadj_)
3917 {
3918   int s,tl;
3919   int ar;
3920   int offset;
3921   int memtarget=0,c=0;
3922   void *jaddr2=NULL;
3923   enum stub_type type;
3924   int agr=AGEN1+(i&1);
3925   int offset_reg = -1;
3926   int fastio_reg_override = -1;
3927   u_int reglist=get_host_reglist(i_regs->regmap);
3928   u_int copr=(source[i]>>16)&0x1f;
3929   s=get_reg(i_regs->regmap,dops[i].rs1);
3930   tl=get_reg(i_regs->regmap,FTEMP);
3931   offset=imm[i];
3932   assert(dops[i].rs1>0);
3933   assert(tl>=0);
3934
3935   if(i_regs->regmap[HOST_CCREG]==CCREG)
3936     reglist&=~(1<<HOST_CCREG);
3937
3938   // get the address
3939   if (dops[i].opcode==0x3a) { // SWC2
3940     ar=get_reg(i_regs->regmap,agr);
3941     if(ar<0) ar=get_reg_temp(i_regs->regmap);
3942     reglist|=1<<ar;
3943   } else { // LWC2
3944     ar=tl;
3945   }
3946   if(s>=0) c=(i_regs->wasconst>>s)&1;
3947   memtarget=c&&(((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE);
3948   if (!offset&&!c&&s>=0) ar=s;
3949   assert(ar>=0);
3950
3951   cop2_do_stall_check(0, i, i_regs, reglist);
3952
3953   if (dops[i].opcode==0x3a) { // SWC2
3954     cop2_get_dreg(copr,tl,-1);
3955     type=STOREW_STUB;
3956   }
3957   else
3958     type=LOADW_STUB;
3959
3960   if(c&&!memtarget) {
3961     jaddr2=out;
3962     emit_jmp(0); // inline_readstub/inline_writestub?
3963   }
3964   else {
3965     if(!c) {
3966       jaddr2 = emit_fastpath_cmp_jump(i, i_regs, ar,
3967                 &offset_reg, &fastio_reg_override);
3968     }
3969     else if (ram_offset && memtarget) {
3970       offset_reg = get_ro_reg(i_regs, 0);
3971     }
3972     switch (dops[i].opcode) {
3973     case 0x32: { // LWC2
3974       int a = ar;
3975       if (fastio_reg_override >= 0)
3976         a = fastio_reg_override;
3977       do_load_word(a, tl, offset_reg);
3978       break;
3979     }
3980     case 0x3a: { // SWC2
3981       #ifdef DESTRUCTIVE_SHIFT
3982       if(!offset&&!c&&s>=0) emit_mov(s,ar);
3983       #endif
3984       int a = ar;
3985       if (fastio_reg_override >= 0)
3986         a = fastio_reg_override;
3987       do_store_word(a, 0, tl, offset_reg, 1);
3988       break;
3989     }
3990     default:
3991       assert(0);
3992     }
3993   }
3994   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3995     host_tempreg_release();
3996   if(jaddr2)
3997     add_stub_r(type,jaddr2,out,i,ar,i_regs,ccadj_,reglist);
3998   if(dops[i].opcode==0x3a) // SWC2
3999     do_store_smc_check(i, i_regs, reglist, ar);
4000   if (dops[i].opcode==0x32) { // LWC2
4001     host_tempreg_acquire();
4002     cop2_put_dreg(copr,tl,HOST_TEMPREG);
4003     host_tempreg_release();
4004   }
4005 }
4006
4007 static void cop2_assemble(int i, const struct regstat *i_regs)
4008 {
4009   u_int copr = (source[i]>>11) & 0x1f;
4010   signed char temp = get_reg_temp(i_regs->regmap);
4011
4012   if (!HACK_ENABLED(NDHACK_NO_STALLS)) {
4013     u_int reglist = reglist_exclude(get_host_reglist(i_regs->regmap), temp, -1);
4014     if (dops[i].opcode2 == 0 || dops[i].opcode2 == 2) { // MFC2/CFC2
4015       signed char tl = get_reg(i_regs->regmap, dops[i].rt1);
4016       reglist = reglist_exclude(reglist, tl, -1);
4017     }
4018     cop2_do_stall_check(0, i, i_regs, reglist);
4019   }
4020   if (dops[i].opcode2==0) { // MFC2
4021     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
4022     if(tl>=0&&dops[i].rt1!=0)
4023       cop2_get_dreg(copr,tl,temp);
4024   }
4025   else if (dops[i].opcode2==4) { // MTC2
4026     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
4027     cop2_put_dreg(copr,sl,temp);
4028   }
4029   else if (dops[i].opcode2==2) // CFC2
4030   {
4031     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
4032     if(tl>=0&&dops[i].rt1!=0)
4033       emit_readword(&reg_cop2c[copr],tl);
4034   }
4035   else if (dops[i].opcode2==6) // CTC2
4036   {
4037     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
4038     switch(copr) {
4039       case 4:
4040       case 12:
4041       case 20:
4042       case 26:
4043       case 27:
4044       case 29:
4045       case 30:
4046         emit_signextend16(sl,temp);
4047         break;
4048       case 31:
4049         c2op_ctc2_31_assemble(sl,temp);
4050         break;
4051       default:
4052         temp=sl;
4053         break;
4054     }
4055     emit_writeword(temp,&reg_cop2c[copr]);
4056     assert(sl>=0);
4057   }
4058 }
4059
4060 static void do_unalignedwritestub(int n)
4061 {
4062   assem_debug("do_unalignedwritestub %x\n",start+stubs[n].a*4);
4063   literal_pool(256);
4064   set_jump_target(stubs[n].addr, out);
4065
4066   int i=stubs[n].a;
4067   struct regstat *i_regs=(struct regstat *)stubs[n].c;
4068   int addr=stubs[n].b;
4069   u_int reglist=stubs[n].e;
4070   signed char *i_regmap=i_regs->regmap;
4071   int temp2=get_reg(i_regmap,FTEMP);
4072   int rt;
4073   rt=get_reg(i_regmap,dops[i].rs2);
4074   assert(rt>=0);
4075   assert(addr>=0);
4076   assert(dops[i].opcode==0x2a||dops[i].opcode==0x2e); // SWL/SWR only implemented
4077   reglist|=(1<<addr);
4078   reglist&=~(1<<temp2);
4079
4080   // don't bother with it and call write handler
4081   save_regs(reglist);
4082   pass_args(addr,rt);
4083   int cc=get_reg(i_regmap,CCREG);
4084   if(cc<0)
4085     emit_loadreg(CCREG,2);
4086   emit_addimm(cc<0?2:cc,(int)stubs[n].d+1,2);
4087   emit_far_call((dops[i].opcode==0x2a?jump_handle_swl:jump_handle_swr));
4088   emit_addimm(0,-((int)stubs[n].d+1),cc<0?2:cc);
4089   if(cc<0)
4090     emit_storereg(CCREG,2);
4091   restore_regs(reglist);
4092   emit_jmp(stubs[n].retaddr); // return address
4093 }
4094
4095 #ifndef multdiv_assemble
4096 void multdiv_assemble(int i,struct regstat *i_regs)
4097 {
4098   printf("Need multdiv_assemble for this architecture.\n");
4099   abort();
4100 }
4101 #endif
4102
4103 static void mov_assemble(int i, const struct regstat *i_regs)
4104 {
4105   //if(dops[i].opcode2==0x10||dops[i].opcode2==0x12) { // MFHI/MFLO
4106   //if(dops[i].opcode2==0x11||dops[i].opcode2==0x13) { // MTHI/MTLO
4107   if(dops[i].rt1) {
4108     signed char sl,tl;
4109     tl=get_reg(i_regs->regmap,dops[i].rt1);
4110     //assert(tl>=0);
4111     if(tl>=0) {
4112       sl=get_reg(i_regs->regmap,dops[i].rs1);
4113       if(sl>=0) emit_mov(sl,tl);
4114       else emit_loadreg(dops[i].rs1,tl);
4115     }
4116   }
4117   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) // MFHI/MFLO
4118     multdiv_do_stall(i, i_regs);
4119 }
4120
4121 // call interpreter, exception handler, things that change pc/regs/cycles ...
4122 static void call_c_cpu_handler(int i, const struct regstat *i_regs, int ccadj_, u_int pc, void *func)
4123 {
4124   signed char ccreg=get_reg(i_regs->regmap,CCREG);
4125   assert(ccreg==HOST_CCREG);
4126   assert(!is_delayslot);
4127   (void)ccreg;
4128
4129   emit_movimm(pc,3); // Get PC
4130   emit_readword(&last_count,2);
4131   emit_writeword(3,&psxRegs.pc);
4132   emit_addimm(HOST_CCREG,ccadj_,HOST_CCREG);
4133   emit_add(2,HOST_CCREG,2);
4134   emit_writeword(2,&psxRegs.cycle);
4135   emit_addimm_ptr(FP,(u_char *)&psxRegs - (u_char *)&dynarec_local,0);
4136   emit_far_call(func);
4137   emit_far_jump(jump_to_new_pc);
4138 }
4139
4140 static void syscall_assemble(int i, const struct regstat *i_regs, int ccadj_)
4141 {
4142   // 'break' tends to be littered around to catch things like
4143   // division by 0 and is almost never executed, so don't emit much code here
4144   void *func = (dops[i].opcode2 == 0x0C)
4145     ? (is_delayslot ? jump_syscall_ds : jump_syscall)
4146     : (is_delayslot ? jump_break_ds : jump_break);
4147   assert(get_reg(i_regs->regmap, CCREG) == HOST_CCREG);
4148   emit_movimm(start + i*4, 2); // pc
4149   emit_addimm(HOST_CCREG, ccadj_ + CLOCK_ADJUST(1), HOST_CCREG);
4150   emit_far_jump(func);
4151 }
4152
4153 static void hlecall_bad()
4154 {
4155   SysPrintf("bad hlecall\n");
4156 }
4157
4158 static void hlecall_assemble(int i, const struct regstat *i_regs, int ccadj_)
4159 {
4160   void *hlefunc = hlecall_bad;
4161   uint32_t hleCode = source[i] & 0x03ffffff;
4162   if (hleCode < ARRAY_SIZE(psxHLEt))
4163     hlefunc = psxHLEt[hleCode];
4164
4165   call_c_cpu_handler(i, i_regs, ccadj_, start + i*4+4, hlefunc);
4166 }
4167
4168 static void intcall_assemble(int i, const struct regstat *i_regs, int ccadj_)
4169 {
4170   call_c_cpu_handler(i, i_regs, ccadj_, start + i*4, execI);
4171 }
4172
4173 static void speculate_mov(int rs,int rt)
4174 {
4175   if(rt!=0) {
4176     smrv_strong_next|=1<<rt;
4177     smrv[rt]=smrv[rs];
4178   }
4179 }
4180
4181 static void speculate_mov_weak(int rs,int rt)
4182 {
4183   if(rt!=0) {
4184     smrv_weak_next|=1<<rt;
4185     smrv[rt]=smrv[rs];
4186   }
4187 }
4188
4189 static void speculate_register_values(int i)
4190 {
4191   if(i==0) {
4192     memcpy(smrv,psxRegs.GPR.r,sizeof(smrv));
4193     // gp,sp are likely to stay the same throughout the block
4194     smrv_strong_next=(1<<28)|(1<<29)|(1<<30);
4195     smrv_weak_next=~smrv_strong_next;
4196     //printf(" llr %08x\n", smrv[4]);
4197   }
4198   smrv_strong=smrv_strong_next;
4199   smrv_weak=smrv_weak_next;
4200   switch(dops[i].itype) {
4201     case ALU:
4202       if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
4203       else if((smrv_strong>>dops[i].rs2)&1) speculate_mov(dops[i].rs2,dops[i].rt1);
4204       else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
4205       else if((smrv_weak>>dops[i].rs2)&1) speculate_mov_weak(dops[i].rs2,dops[i].rt1);
4206       else {
4207         smrv_strong_next&=~(1<<dops[i].rt1);
4208         smrv_weak_next&=~(1<<dops[i].rt1);
4209       }
4210       break;
4211     case SHIFTIMM:
4212       smrv_strong_next&=~(1<<dops[i].rt1);
4213       smrv_weak_next&=~(1<<dops[i].rt1);
4214       // fallthrough
4215     case IMM16:
4216       if(dops[i].rt1&&is_const(&regs[i],dops[i].rt1)) {
4217         int value,hr=get_reg(regs[i].regmap,dops[i].rt1);
4218         if(hr>=0) {
4219           if(get_final_value(hr,i,&value))
4220                smrv[dops[i].rt1]=value;
4221           else smrv[dops[i].rt1]=constmap[i][hr];
4222           smrv_strong_next|=1<<dops[i].rt1;
4223         }
4224       }
4225       else {
4226         if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
4227         else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
4228       }
4229       break;
4230     case LOAD:
4231       if(start<0x2000&&(dops[i].rt1==26||(smrv[dops[i].rt1]>>24)==0xa0)) {
4232         // special case for BIOS
4233         smrv[dops[i].rt1]=0xa0000000;
4234         smrv_strong_next|=1<<dops[i].rt1;
4235         break;
4236       }
4237       // fallthrough
4238     case SHIFT:
4239     case LOADLR:
4240     case MOV:
4241       smrv_strong_next&=~(1<<dops[i].rt1);
4242       smrv_weak_next&=~(1<<dops[i].rt1);
4243       break;
4244     case COP0:
4245     case COP2:
4246       if(dops[i].opcode2==0||dops[i].opcode2==2) { // MFC/CFC
4247         smrv_strong_next&=~(1<<dops[i].rt1);
4248         smrv_weak_next&=~(1<<dops[i].rt1);
4249       }
4250       break;
4251     case C2LS:
4252       if (dops[i].opcode==0x32) { // LWC2
4253         smrv_strong_next&=~(1<<dops[i].rt1);
4254         smrv_weak_next&=~(1<<dops[i].rt1);
4255       }
4256       break;
4257   }
4258 #if 0
4259   int r=4;
4260   printf("x %08x %08x %d %d c %08x %08x\n",smrv[r],start+i*4,
4261     ((smrv_strong>>r)&1),(smrv_weak>>r)&1,regs[i].isconst,regs[i].wasconst);
4262 #endif
4263 }
4264
4265 static void ujump_assemble(int i, const struct regstat *i_regs);
4266 static void rjump_assemble(int i, const struct regstat *i_regs);
4267 static void cjump_assemble(int i, const struct regstat *i_regs);
4268 static void sjump_assemble(int i, const struct regstat *i_regs);
4269
4270 static int assemble(int i, const struct regstat *i_regs, int ccadj_)
4271 {
4272   int ds = 0;
4273   switch (dops[i].itype) {
4274     case ALU:
4275       alu_assemble(i, i_regs);
4276       break;
4277     case IMM16:
4278       imm16_assemble(i, i_regs);
4279       break;
4280     case SHIFT:
4281       shift_assemble(i, i_regs);
4282       break;
4283     case SHIFTIMM:
4284       shiftimm_assemble(i, i_regs);
4285       break;
4286     case LOAD:
4287       load_assemble(i, i_regs, ccadj_);
4288       break;
4289     case LOADLR:
4290       loadlr_assemble(i, i_regs, ccadj_);
4291       break;
4292     case STORE:
4293       store_assemble(i, i_regs, ccadj_);
4294       break;
4295     case STORELR:
4296       storelr_assemble(i, i_regs, ccadj_);
4297       break;
4298     case COP0:
4299       cop0_assemble(i, i_regs, ccadj_);
4300       break;
4301     case COP1:
4302       cop1_assemble(i, i_regs);
4303       break;
4304     case C1LS:
4305       c1ls_assemble(i, i_regs);
4306       break;
4307     case COP2:
4308       cop2_assemble(i, i_regs);
4309       break;
4310     case C2LS:
4311       c2ls_assemble(i, i_regs, ccadj_);
4312       break;
4313     case C2OP:
4314       c2op_assemble(i, i_regs);
4315       break;
4316     case MULTDIV:
4317       multdiv_assemble(i, i_regs);
4318       multdiv_prepare_stall(i, i_regs, ccadj_);
4319       break;
4320     case MOV:
4321       mov_assemble(i, i_regs);
4322       break;
4323     case SYSCALL:
4324       syscall_assemble(i, i_regs, ccadj_);
4325       break;
4326     case HLECALL:
4327       hlecall_assemble(i, i_regs, ccadj_);
4328       break;
4329     case INTCALL:
4330       intcall_assemble(i, i_regs, ccadj_);
4331       break;
4332     case UJUMP:
4333       ujump_assemble(i, i_regs);
4334       ds = 1;
4335       break;
4336     case RJUMP:
4337       rjump_assemble(i, i_regs);
4338       ds = 1;
4339       break;
4340     case CJUMP:
4341       cjump_assemble(i, i_regs);
4342       ds = 1;
4343       break;
4344     case SJUMP:
4345       sjump_assemble(i, i_regs);
4346       ds = 1;
4347       break;
4348     case NOP:
4349     case OTHER:
4350     case NI:
4351       // not handled, just skip
4352       break;
4353     default:
4354       assert(0);
4355   }
4356   return ds;
4357 }
4358
4359 static void ds_assemble(int i, const struct regstat *i_regs)
4360 {
4361   speculate_register_values(i);
4362   is_delayslot = 1;
4363   switch (dops[i].itype) {
4364     case SYSCALL:
4365     case HLECALL:
4366     case INTCALL:
4367     case UJUMP:
4368     case RJUMP:
4369     case CJUMP:
4370     case SJUMP:
4371       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4372       break;
4373     default:
4374       assemble(i, i_regs, ccadj[i]);
4375   }
4376   is_delayslot = 0;
4377 }
4378
4379 // Is the branch target a valid internal jump?
4380 static int internal_branch(int addr)
4381 {
4382   if(addr&1) return 0; // Indirect (register) jump
4383   if(addr>=start && addr<start+slen*4-4)
4384   {
4385     return 1;
4386   }
4387   return 0;
4388 }
4389
4390 static void wb_invalidate(signed char pre[],signed char entry[],uint64_t dirty,uint64_t u)
4391 {
4392   int hr;
4393   for(hr=0;hr<HOST_REGS;hr++) {
4394     if(hr!=EXCLUDE_REG) {
4395       if(pre[hr]!=entry[hr]) {
4396         if(pre[hr]>=0) {
4397           if((dirty>>hr)&1) {
4398             if(get_reg(entry,pre[hr])<0) {
4399               assert(pre[hr]<64);
4400               if(!((u>>pre[hr])&1))
4401                 emit_storereg(pre[hr],hr);
4402             }
4403           }
4404         }
4405       }
4406     }
4407   }
4408   // Move from one register to another (no writeback)
4409   for(hr=0;hr<HOST_REGS;hr++) {
4410     if(hr!=EXCLUDE_REG) {
4411       if(pre[hr]!=entry[hr]) {
4412         if(pre[hr]>=0&&pre[hr]<TEMPREG) {
4413           int nr;
4414           if((nr=get_reg(entry,pre[hr]))>=0) {
4415             emit_mov(hr,nr);
4416           }
4417         }
4418       }
4419     }
4420   }
4421 }
4422
4423 // Load the specified registers
4424 // This only loads the registers given as arguments because
4425 // we don't want to load things that will be overwritten
4426 static inline void load_reg(signed char entry[], signed char regmap[], int rs)
4427 {
4428   int hr = get_reg(regmap, rs);
4429   if (hr >= 0 && entry[hr] != regmap[hr])
4430     emit_loadreg(regmap[hr], hr);
4431 }
4432
4433 static void load_regs(signed char entry[], signed char regmap[], int rs1, int rs2)
4434 {
4435   load_reg(entry, regmap, rs1);
4436   if (rs1 != rs2)
4437     load_reg(entry, regmap, rs2);
4438 }
4439
4440 // Load registers prior to the start of a loop
4441 // so that they are not loaded within the loop
4442 static void loop_preload(signed char pre[],signed char entry[])
4443 {
4444   int hr;
4445   for (hr = 0; hr < HOST_REGS; hr++) {
4446     int r = entry[hr];
4447     if (r >= 0 && pre[hr] != r && get_reg(pre, r) < 0) {
4448       assem_debug("loop preload:\n");
4449       if (r < TEMPREG)
4450         emit_loadreg(r, hr);
4451     }
4452   }
4453 }
4454
4455 // Generate address for load/store instruction
4456 // goes to AGEN for writes, FTEMP for LOADLR and cop1/2 loads
4457 static void address_generation(int i, const struct regstat *i_regs, signed char entry[])
4458 {
4459   if (dops[i].is_load || dops[i].is_store) {
4460     int ra=-1;
4461     int agr=AGEN1+(i&1);
4462     if(dops[i].itype==LOAD) {
4463       ra=get_reg(i_regs->regmap,dops[i].rt1);
4464       if(ra<0) ra=get_reg_temp(i_regs->regmap);
4465       assert(ra>=0);
4466     }
4467     if(dops[i].itype==LOADLR) {
4468       ra=get_reg(i_regs->regmap,FTEMP);
4469     }
4470     if(dops[i].itype==STORE||dops[i].itype==STORELR) {
4471       ra=get_reg(i_regs->regmap,agr);
4472       if(ra<0) ra=get_reg_temp(i_regs->regmap);
4473     }
4474     if(dops[i].itype==C2LS) {
4475       if ((dops[i].opcode&0x3b)==0x31||(dops[i].opcode&0x3b)==0x32) // LWC1/LDC1/LWC2/LDC2
4476         ra=get_reg(i_regs->regmap,FTEMP);
4477       else { // SWC1/SDC1/SWC2/SDC2
4478         ra=get_reg(i_regs->regmap,agr);
4479         if(ra<0) ra=get_reg_temp(i_regs->regmap);
4480       }
4481     }
4482     int rs=get_reg(i_regs->regmap,dops[i].rs1);
4483     if(ra>=0) {
4484       int offset=imm[i];
4485       int c=(i_regs->wasconst>>rs)&1;
4486       if(dops[i].rs1==0) {
4487         // Using r0 as a base address
4488         if(!entry||entry[ra]!=agr) {
4489           if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4490             emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4491           }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4492             emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4493           }else{
4494             emit_movimm(offset,ra);
4495           }
4496         } // else did it in the previous cycle
4497       }
4498       else if(rs<0) {
4499         if(!entry||entry[ra]!=dops[i].rs1)
4500           emit_loadreg(dops[i].rs1,ra);
4501         //if(!entry||entry[ra]!=dops[i].rs1)
4502         //  printf("poor load scheduling!\n");
4503       }
4504       else if(c) {
4505         if(dops[i].rs1!=dops[i].rt1||dops[i].itype!=LOAD) {
4506           if(!entry||entry[ra]!=agr) {
4507             if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4508               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4509             }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4510               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4511             }else{
4512               emit_movimm(constmap[i][rs]+offset,ra);
4513               regs[i].loadedconst|=1<<ra;
4514             }
4515           } // else did it in the previous cycle
4516         } // else load_consts already did it
4517       }
4518       if(offset&&!c&&dops[i].rs1) {
4519         if(rs>=0) {
4520           emit_addimm(rs,offset,ra);
4521         }else{
4522           emit_addimm(ra,offset,ra);
4523         }
4524       }
4525     }
4526   }
4527   // Preload constants for next instruction
4528   if (dops[i+1].is_load || dops[i+1].is_store) {
4529     int agr,ra;
4530     // Actual address
4531     agr=AGEN1+((i+1)&1);
4532     ra=get_reg(i_regs->regmap,agr);
4533     if(ra>=0) {
4534       int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
4535       int offset=imm[i+1];
4536       int c=(regs[i+1].wasconst>>rs)&1;
4537       if(c&&(dops[i+1].rs1!=dops[i+1].rt1||dops[i+1].itype!=LOAD)) {
4538         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4539           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4540         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4541           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4542         }else{
4543           emit_movimm(constmap[i+1][rs]+offset,ra);
4544           regs[i+1].loadedconst|=1<<ra;
4545         }
4546       }
4547       else if(dops[i+1].rs1==0) {
4548         // Using r0 as a base address
4549         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4550           emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4551         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4552           emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4553         }else{
4554           emit_movimm(offset,ra);
4555         }
4556       }
4557     }
4558   }
4559 }
4560
4561 static int get_final_value(int hr, int i, int *value)
4562 {
4563   int reg=regs[i].regmap[hr];
4564   while(i<slen-1) {
4565     if(regs[i+1].regmap[hr]!=reg) break;
4566     if(!((regs[i+1].isconst>>hr)&1)) break;
4567     if(dops[i+1].bt) break;
4568     i++;
4569   }
4570   if(i<slen-1) {
4571     if (dops[i].is_jump) {
4572       *value=constmap[i][hr];
4573       return 1;
4574     }
4575     if(!dops[i+1].bt) {
4576       if (dops[i+1].is_jump) {
4577         // Load in delay slot, out-of-order execution
4578         if(dops[i+2].itype==LOAD&&dops[i+2].rs1==reg&&dops[i+2].rt1==reg&&((regs[i+1].wasconst>>hr)&1))
4579         {
4580           // Precompute load address
4581           *value=constmap[i][hr]+imm[i+2];
4582           return 1;
4583         }
4584       }
4585       if(dops[i+1].itype==LOAD&&dops[i+1].rs1==reg&&dops[i+1].rt1==reg)
4586       {
4587         // Precompute load address
4588         *value=constmap[i][hr]+imm[i+1];
4589         //printf("c=%x imm=%lx\n",(long)constmap[i][hr],imm[i+1]);
4590         return 1;
4591       }
4592     }
4593   }
4594   *value=constmap[i][hr];
4595   //printf("c=%lx\n",(long)constmap[i][hr]);
4596   if(i==slen-1) return 1;
4597   assert(reg < 64);
4598   return !((unneeded_reg[i+1]>>reg)&1);
4599 }
4600
4601 // Load registers with known constants
4602 static void load_consts(signed char pre[],signed char regmap[],int i)
4603 {
4604   int hr,hr2;
4605   // propagate loaded constant flags
4606   if(i==0||dops[i].bt)
4607     regs[i].loadedconst=0;
4608   else {
4609     for(hr=0;hr<HOST_REGS;hr++) {
4610       if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((regs[i-1].isconst>>hr)&1)&&pre[hr]==regmap[hr]
4611          &&regmap[hr]==regs[i-1].regmap[hr]&&((regs[i-1].loadedconst>>hr)&1))
4612       {
4613         regs[i].loadedconst|=1<<hr;
4614       }
4615     }
4616   }
4617   // Load 32-bit regs
4618   for(hr=0;hr<HOST_REGS;hr++) {
4619     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4620       //if(entry[hr]!=regmap[hr]) {
4621       if(!((regs[i].loadedconst>>hr)&1)) {
4622         assert(regmap[hr]<64);
4623         if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4624           int value,similar=0;
4625           if(get_final_value(hr,i,&value)) {
4626             // see if some other register has similar value
4627             for(hr2=0;hr2<HOST_REGS;hr2++) {
4628               if(hr2!=EXCLUDE_REG&&((regs[i].loadedconst>>hr2)&1)) {
4629                 if(is_similar_value(value,constmap[i][hr2])) {
4630                   similar=1;
4631                   break;
4632                 }
4633               }
4634             }
4635             if(similar) {
4636               int value2;
4637               if(get_final_value(hr2,i,&value2)) // is this needed?
4638                 emit_movimm_from(value2,hr2,value,hr);
4639               else
4640                 emit_movimm(value,hr);
4641             }
4642             else if(value==0) {
4643               emit_zeroreg(hr);
4644             }
4645             else {
4646               emit_movimm(value,hr);
4647             }
4648           }
4649           regs[i].loadedconst|=1<<hr;
4650         }
4651       }
4652     }
4653   }
4654 }
4655
4656 static void load_all_consts(const signed char regmap[], u_int dirty, int i)
4657 {
4658   int hr;
4659   // Load 32-bit regs
4660   for(hr=0;hr<HOST_REGS;hr++) {
4661     if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((dirty>>hr)&1)) {
4662       assert(regmap[hr] < 64);
4663       if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4664         int value=constmap[i][hr];
4665         if(value==0) {
4666           emit_zeroreg(hr);
4667         }
4668         else {
4669           emit_movimm(value,hr);
4670         }
4671       }
4672     }
4673   }
4674 }
4675
4676 // Write out all dirty registers (except cycle count)
4677 static void wb_dirtys(const signed char i_regmap[], uint64_t i_dirty)
4678 {
4679   int hr;
4680   for(hr=0;hr<HOST_REGS;hr++) {
4681     if(hr!=EXCLUDE_REG) {
4682       if(i_regmap[hr]>0) {
4683         if(i_regmap[hr]!=CCREG) {
4684           if((i_dirty>>hr)&1) {
4685             assert(i_regmap[hr]<64);
4686             emit_storereg(i_regmap[hr],hr);
4687           }
4688         }
4689       }
4690     }
4691   }
4692 }
4693
4694 // Write out dirty registers that we need to reload (pair with load_needed_regs)
4695 // This writes the registers not written by store_regs_bt
4696 static void wb_needed_dirtys(const signed char i_regmap[], uint64_t i_dirty, int addr)
4697 {
4698   int hr;
4699   int t=(addr-start)>>2;
4700   for(hr=0;hr<HOST_REGS;hr++) {
4701     if(hr!=EXCLUDE_REG) {
4702       if(i_regmap[hr]>0) {
4703         if(i_regmap[hr]!=CCREG) {
4704           if(i_regmap[hr]==regs[t].regmap_entry[hr] && ((regs[t].dirty>>hr)&1)) {
4705             if((i_dirty>>hr)&1) {
4706               assert(i_regmap[hr]<64);
4707               emit_storereg(i_regmap[hr],hr);
4708             }
4709           }
4710         }
4711       }
4712     }
4713   }
4714 }
4715
4716 // Load all registers (except cycle count)
4717 static void load_all_regs(const signed char i_regmap[])
4718 {
4719   int hr;
4720   for(hr=0;hr<HOST_REGS;hr++) {
4721     if(hr!=EXCLUDE_REG) {
4722       if(i_regmap[hr]==0) {
4723         emit_zeroreg(hr);
4724       }
4725       else
4726       if(i_regmap[hr]>0 && i_regmap[hr]<TEMPREG && i_regmap[hr]!=CCREG)
4727       {
4728         emit_loadreg(i_regmap[hr],hr);
4729       }
4730     }
4731   }
4732 }
4733
4734 // Load all current registers also needed by next instruction
4735 static void load_needed_regs(const signed char i_regmap[], const signed char next_regmap[])
4736 {
4737   int hr;
4738   for(hr=0;hr<HOST_REGS;hr++) {
4739     if(hr!=EXCLUDE_REG) {
4740       if(get_reg(next_regmap,i_regmap[hr])>=0) {
4741         if(i_regmap[hr]==0) {
4742           emit_zeroreg(hr);
4743         }
4744         else
4745         if(i_regmap[hr]>0 && i_regmap[hr]<TEMPREG && i_regmap[hr]!=CCREG)
4746         {
4747           emit_loadreg(i_regmap[hr],hr);
4748         }
4749       }
4750     }
4751   }
4752 }
4753
4754 // Load all regs, storing cycle count if necessary
4755 static void load_regs_entry(int t)
4756 {
4757   int hr;
4758   if(dops[t].is_ds) emit_addimm(HOST_CCREG,CLOCK_ADJUST(1),HOST_CCREG);
4759   else if(ccadj[t]) emit_addimm(HOST_CCREG,-ccadj[t],HOST_CCREG);
4760   if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4761     emit_storereg(CCREG,HOST_CCREG);
4762   }
4763   // Load 32-bit regs
4764   for(hr=0;hr<HOST_REGS;hr++) {
4765     if(regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4766       if(regs[t].regmap_entry[hr]==0) {
4767         emit_zeroreg(hr);
4768       }
4769       else if(regs[t].regmap_entry[hr]!=CCREG)
4770       {
4771         emit_loadreg(regs[t].regmap_entry[hr],hr);
4772       }
4773     }
4774   }
4775 }
4776
4777 // Store dirty registers prior to branch
4778 static void store_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4779 {
4780   if(internal_branch(addr))
4781   {
4782     int t=(addr-start)>>2;
4783     int hr;
4784     for(hr=0;hr<HOST_REGS;hr++) {
4785       if(hr!=EXCLUDE_REG) {
4786         if(i_regmap[hr]>0 && i_regmap[hr]!=CCREG) {
4787           if(i_regmap[hr]!=regs[t].regmap_entry[hr] || !((regs[t].dirty>>hr)&1)) {
4788             if((i_dirty>>hr)&1) {
4789               assert(i_regmap[hr]<64);
4790               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4791                 emit_storereg(i_regmap[hr],hr);
4792             }
4793           }
4794         }
4795       }
4796     }
4797   }
4798   else
4799   {
4800     // Branch out of this block, write out all dirty regs
4801     wb_dirtys(i_regmap,i_dirty);
4802   }
4803 }
4804
4805 // Load all needed registers for branch target
4806 static void load_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4807 {
4808   //if(addr>=start && addr<(start+slen*4))
4809   if(internal_branch(addr))
4810   {
4811     int t=(addr-start)>>2;
4812     int hr;
4813     // Store the cycle count before loading something else
4814     if(i_regmap[HOST_CCREG]!=CCREG) {
4815       assert(i_regmap[HOST_CCREG]==-1);
4816     }
4817     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4818       emit_storereg(CCREG,HOST_CCREG);
4819     }
4820     // Load 32-bit regs
4821     for(hr=0;hr<HOST_REGS;hr++) {
4822       if(hr!=EXCLUDE_REG&&regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4823         if(i_regmap[hr]!=regs[t].regmap_entry[hr]) {
4824           if(regs[t].regmap_entry[hr]==0) {
4825             emit_zeroreg(hr);
4826           }
4827           else if(regs[t].regmap_entry[hr]!=CCREG)
4828           {
4829             emit_loadreg(regs[t].regmap_entry[hr],hr);
4830           }
4831         }
4832       }
4833     }
4834   }
4835 }
4836
4837 static int match_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4838 {
4839   if(addr>=start && addr<start+slen*4-4)
4840   {
4841     int t=(addr-start)>>2;
4842     int hr;
4843     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) return 0;
4844     for(hr=0;hr<HOST_REGS;hr++)
4845     {
4846       if(hr!=EXCLUDE_REG)
4847       {
4848         if(i_regmap[hr]!=regs[t].regmap_entry[hr])
4849         {
4850           if(regs[t].regmap_entry[hr]>=0&&(regs[t].regmap_entry[hr]|64)<TEMPREG+64)
4851           {
4852             return 0;
4853           }
4854           else
4855           if((i_dirty>>hr)&1)
4856           {
4857             if(i_regmap[hr]<TEMPREG)
4858             {
4859               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4860                 return 0;
4861             }
4862             else if(i_regmap[hr]>=64&&i_regmap[hr]<TEMPREG+64)
4863             {
4864               assert(0);
4865             }
4866           }
4867         }
4868         else // Same register but is it 32-bit or dirty?
4869         if(i_regmap[hr]>=0)
4870         {
4871           if(!((regs[t].dirty>>hr)&1))
4872           {
4873             if((i_dirty>>hr)&1)
4874             {
4875               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4876               {
4877                 //printf("%x: dirty no match\n",addr);
4878                 return 0;
4879               }
4880             }
4881           }
4882         }
4883       }
4884     }
4885     // Delay slots are not valid branch targets
4886     //if(t>0&&(dops[t-1].is_jump) return 0;
4887     // Delay slots require additional processing, so do not match
4888     if(dops[t].is_ds) return 0;
4889   }
4890   else
4891   {
4892     int hr;
4893     for(hr=0;hr<HOST_REGS;hr++)
4894     {
4895       if(hr!=EXCLUDE_REG)
4896       {
4897         if(i_regmap[hr]>=0)
4898         {
4899           if(hr!=HOST_CCREG||i_regmap[hr]!=CCREG)
4900           {
4901             if((i_dirty>>hr)&1)
4902             {
4903               return 0;
4904             }
4905           }
4906         }
4907       }
4908     }
4909   }
4910   return 1;
4911 }
4912
4913 #ifdef DRC_DBG
4914 static void drc_dbg_emit_do_cmp(int i, int ccadj_)
4915 {
4916   extern void do_insn_cmp();
4917   //extern int cycle;
4918   u_int hr, reglist = get_host_reglist(regs[i].regmap);
4919
4920   assem_debug("//do_insn_cmp %08x\n", start+i*4);
4921   save_regs(reglist);
4922   // write out changed consts to match the interpreter
4923   if (i > 0 && !dops[i].bt) {
4924     for (hr = 0; hr < HOST_REGS; hr++) {
4925       int reg = regs[i].regmap_entry[hr]; // regs[i-1].regmap[hr];
4926       if (hr == EXCLUDE_REG || reg < 0)
4927         continue;
4928       if (!((regs[i-1].isconst >> hr) & 1))
4929         continue;
4930       if (i > 1 && reg == regs[i-2].regmap[hr] && constmap[i-1][hr] == constmap[i-2][hr])
4931         continue;
4932       emit_movimm(constmap[i-1][hr],0);
4933       emit_storereg(reg, 0);
4934     }
4935   }
4936   emit_movimm(start+i*4,0);
4937   emit_writeword(0,&pcaddr);
4938   int cc = get_reg(regs[i].regmap_entry, CCREG);
4939   if (cc < 0)
4940     emit_loadreg(CCREG, cc = 0);
4941   emit_addimm(cc, ccadj_, 0);
4942   emit_writeword(0, &psxRegs.cycle);
4943   emit_far_call(do_insn_cmp);
4944   //emit_readword(&cycle,0);
4945   //emit_addimm(0,2,0);
4946   //emit_writeword(0,&cycle);
4947   (void)get_reg2;
4948   restore_regs(reglist);
4949   assem_debug("\\\\do_insn_cmp\n");
4950 }
4951 #else
4952 #define drc_dbg_emit_do_cmp(x,y)
4953 #endif
4954
4955 // Used when a branch jumps into the delay slot of another branch
4956 static void ds_assemble_entry(int i)
4957 {
4958   int t = (ba[i] - start) >> 2;
4959   int ccadj_ = -CLOCK_ADJUST(1);
4960   if (!instr_addr[t])
4961     instr_addr[t] = out;
4962   assem_debug("Assemble delay slot at %x\n",ba[i]);
4963   assem_debug("<->\n");
4964   drc_dbg_emit_do_cmp(t, ccadj_);
4965   if(regs[t].regmap_entry[HOST_CCREG]==CCREG&&regs[t].regmap[HOST_CCREG]!=CCREG)
4966     wb_register(CCREG,regs[t].regmap_entry,regs[t].wasdirty);
4967   load_regs(regs[t].regmap_entry,regs[t].regmap,dops[t].rs1,dops[t].rs2);
4968   address_generation(t,&regs[t],regs[t].regmap_entry);
4969   if (ram_offset && (dops[t].is_load || dops[t].is_store))
4970     load_reg(regs[t].regmap_entry,regs[t].regmap,ROREG);
4971   if (dops[t].is_store)
4972     load_reg(regs[t].regmap_entry,regs[t].regmap,INVCP);
4973   is_delayslot=0;
4974   switch (dops[t].itype) {
4975     case SYSCALL:
4976     case HLECALL:
4977     case INTCALL:
4978     case UJUMP:
4979     case RJUMP:
4980     case CJUMP:
4981     case SJUMP:
4982       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4983       break;
4984     default:
4985       assemble(t, &regs[t], ccadj_);
4986   }
4987   store_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4988   load_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4989   if(internal_branch(ba[i]+4))
4990     assem_debug("branch: internal\n");
4991   else
4992     assem_debug("branch: external\n");
4993   assert(internal_branch(ba[i]+4));
4994   add_to_linker(out,ba[i]+4,internal_branch(ba[i]+4));
4995   emit_jmp(0);
4996 }
4997
4998 // Load 2 immediates optimizing for small code size
4999 static void emit_mov2imm_compact(int imm1,u_int rt1,int imm2,u_int rt2)
5000 {
5001   emit_movimm(imm1,rt1);
5002   emit_movimm_from(imm1,rt1,imm2,rt2);
5003 }
5004
5005 static void do_cc(int i, const signed char i_regmap[], int *adj,
5006   int addr, int taken, int invert)
5007 {
5008   int count, count_plus2;
5009   void *jaddr;
5010   void *idle=NULL;
5011   int t=0;
5012   if(dops[i].itype==RJUMP)
5013   {
5014     *adj=0;
5015   }
5016   //if(ba[i]>=start && ba[i]<(start+slen*4))
5017   if(internal_branch(ba[i]))
5018   {
5019     t=(ba[i]-start)>>2;
5020     if(dops[t].is_ds) *adj=-CLOCK_ADJUST(1); // Branch into delay slot adds an extra cycle
5021     else *adj=ccadj[t];
5022   }
5023   else
5024   {
5025     *adj=0;
5026   }
5027   count = ccadj[i];
5028   count_plus2 = count + CLOCK_ADJUST(2);
5029   if(taken==TAKEN && i==(ba[i]-start)>>2 && source[i+1]==0) {
5030     // Idle loop
5031     if(count&1) emit_addimm_and_set_flags(2*(count+2),HOST_CCREG);
5032     idle=out;
5033     //emit_subfrommem(&idlecount,HOST_CCREG); // Count idle cycles
5034     emit_andimm(HOST_CCREG,3,HOST_CCREG);
5035     jaddr=out;
5036     emit_jmp(0);
5037   }
5038   else if(*adj==0||invert) {
5039     int cycles = count_plus2;
5040     // faster loop HACK
5041 #if 0
5042     if (t&&*adj) {
5043       int rel=t-i;
5044       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
5045         cycles=*adj+count+2-*adj;
5046     }
5047 #endif
5048     emit_addimm_and_set_flags(cycles, HOST_CCREG);
5049     jaddr = out;
5050     emit_jns(0);
5051   }
5052   else
5053   {
5054     emit_cmpimm(HOST_CCREG, -count_plus2);
5055     jaddr = out;
5056     emit_jns(0);
5057   }
5058   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:count_plus2,i,addr,taken,0);
5059 }
5060
5061 static void do_ccstub(int n)
5062 {
5063   literal_pool(256);
5064   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
5065   set_jump_target(stubs[n].addr, out);
5066   int i=stubs[n].b;
5067   if(stubs[n].d==NULLDS) {
5068     // Delay slot instruction is nullified ("likely" branch)
5069     wb_dirtys(regs[i].regmap,regs[i].dirty);
5070   }
5071   else if(stubs[n].d!=TAKEN) {
5072     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
5073   }
5074   else {
5075     if(internal_branch(ba[i]))
5076       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5077   }
5078   if(stubs[n].c!=-1)
5079   {
5080     // Save PC as return address
5081     emit_movimm(stubs[n].c,0);
5082     emit_writeword(0,&pcaddr);
5083   }
5084   else
5085   {
5086     // Return address depends on which way the branch goes
5087     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
5088     {
5089       int s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5090       int s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
5091       if(dops[i].rs1==0)
5092       {
5093         s1l=s2l;
5094         s2l=-1;
5095       }
5096       else if(dops[i].rs2==0)
5097       {
5098         s2l=-1;
5099       }
5100       assert(s1l>=0);
5101       #ifdef DESTRUCTIVE_WRITEBACK
5102       if(dops[i].rs1) {
5103         if((branch_regs[i].dirty>>s1l)&&1)
5104           emit_loadreg(dops[i].rs1,s1l);
5105       }
5106       else {
5107         if((branch_regs[i].dirty>>s1l)&1)
5108           emit_loadreg(dops[i].rs2,s1l);
5109       }
5110       if(s2l>=0)
5111         if((branch_regs[i].dirty>>s2l)&1)
5112           emit_loadreg(dops[i].rs2,s2l);
5113       #endif
5114       int hr=0;
5115       int addr=-1,alt=-1,ntaddr=-1;
5116       while(hr<HOST_REGS)
5117       {
5118         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5119            branch_regs[i].regmap[hr]!=dops[i].rs1 &&
5120            branch_regs[i].regmap[hr]!=dops[i].rs2 )
5121         {
5122           addr=hr++;break;
5123         }
5124         hr++;
5125       }
5126       while(hr<HOST_REGS)
5127       {
5128         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5129            branch_regs[i].regmap[hr]!=dops[i].rs1 &&
5130            branch_regs[i].regmap[hr]!=dops[i].rs2 )
5131         {
5132           alt=hr++;break;
5133         }
5134         hr++;
5135       }
5136       if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
5137       {
5138         while(hr<HOST_REGS)
5139         {
5140           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5141              branch_regs[i].regmap[hr]!=dops[i].rs1 &&
5142              branch_regs[i].regmap[hr]!=dops[i].rs2 )
5143           {
5144             ntaddr=hr;break;
5145           }
5146           hr++;
5147         }
5148         assert(hr<HOST_REGS);
5149       }
5150       if((dops[i].opcode&0x2f)==4) // BEQ
5151       {
5152         #ifdef HAVE_CMOV_IMM
5153         if(s2l>=0) emit_cmp(s1l,s2l);
5154         else emit_test(s1l,s1l);
5155         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5156         #else
5157         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5158         if(s2l>=0) emit_cmp(s1l,s2l);
5159         else emit_test(s1l,s1l);
5160         emit_cmovne_reg(alt,addr);
5161         #endif
5162       }
5163       if((dops[i].opcode&0x2f)==5) // BNE
5164       {
5165         #ifdef HAVE_CMOV_IMM
5166         if(s2l>=0) emit_cmp(s1l,s2l);
5167         else emit_test(s1l,s1l);
5168         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5169         #else
5170         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5171         if(s2l>=0) emit_cmp(s1l,s2l);
5172         else emit_test(s1l,s1l);
5173         emit_cmovne_reg(alt,addr);
5174         #endif
5175       }
5176       if((dops[i].opcode&0x2f)==6) // BLEZ
5177       {
5178         //emit_movimm(ba[i],alt);
5179         //emit_movimm(start+i*4+8,addr);
5180         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5181         emit_cmpimm(s1l,1);
5182         emit_cmovl_reg(alt,addr);
5183       }
5184       if((dops[i].opcode&0x2f)==7) // BGTZ
5185       {
5186         //emit_movimm(ba[i],addr);
5187         //emit_movimm(start+i*4+8,ntaddr);
5188         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5189         emit_cmpimm(s1l,1);
5190         emit_cmovl_reg(ntaddr,addr);
5191       }
5192       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==0) // BLTZ
5193       {
5194         //emit_movimm(ba[i],alt);
5195         //emit_movimm(start+i*4+8,addr);
5196         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5197         emit_test(s1l,s1l);
5198         emit_cmovs_reg(alt,addr);
5199       }
5200       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==1) // BGEZ
5201       {
5202         //emit_movimm(ba[i],addr);
5203         //emit_movimm(start+i*4+8,alt);
5204         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5205         emit_test(s1l,s1l);
5206         emit_cmovs_reg(alt,addr);
5207       }
5208       if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
5209         if(source[i]&0x10000) // BC1T
5210         {
5211           //emit_movimm(ba[i],alt);
5212           //emit_movimm(start+i*4+8,addr);
5213           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5214           emit_testimm(s1l,0x800000);
5215           emit_cmovne_reg(alt,addr);
5216         }
5217         else // BC1F
5218         {
5219           //emit_movimm(ba[i],addr);
5220           //emit_movimm(start+i*4+8,alt);
5221           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5222           emit_testimm(s1l,0x800000);
5223           emit_cmovne_reg(alt,addr);
5224         }
5225       }
5226       emit_writeword(addr,&pcaddr);
5227     }
5228     else
5229     if(dops[i].itype==RJUMP)
5230     {
5231       int r=get_reg(branch_regs[i].regmap,dops[i].rs1);
5232       if (ds_writes_rjump_rs(i)) {
5233         r=get_reg(branch_regs[i].regmap,RTEMP);
5234       }
5235       emit_writeword(r,&pcaddr);
5236     }
5237     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
5238   }
5239   // Update cycle count
5240   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
5241   if(stubs[n].a) emit_addimm(HOST_CCREG,(int)stubs[n].a,HOST_CCREG);
5242   emit_far_call(cc_interrupt);
5243   if(stubs[n].a) emit_addimm(HOST_CCREG,-(int)stubs[n].a,HOST_CCREG);
5244   if(stubs[n].d==TAKEN) {
5245     if(internal_branch(ba[i]))
5246       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
5247     else if(dops[i].itype==RJUMP) {
5248       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
5249         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
5250       else
5251         emit_loadreg(dops[i].rs1,get_reg(branch_regs[i].regmap,dops[i].rs1));
5252     }
5253   }else if(stubs[n].d==NOTTAKEN) {
5254     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
5255     else load_all_regs(branch_regs[i].regmap);
5256   }else if(stubs[n].d==NULLDS) {
5257     // Delay slot instruction is nullified ("likely" branch)
5258     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
5259     else load_all_regs(regs[i].regmap);
5260   }else{
5261     load_all_regs(branch_regs[i].regmap);
5262   }
5263   if (stubs[n].retaddr)
5264     emit_jmp(stubs[n].retaddr);
5265   else
5266     do_jump_vaddr(stubs[n].e);
5267 }
5268
5269 static void add_to_linker(void *addr, u_int target, int is_internal)
5270 {
5271   assert(linkcount < ARRAY_SIZE(link_addr));
5272   link_addr[linkcount].addr = addr;
5273   link_addr[linkcount].target = target;
5274   link_addr[linkcount].internal = is_internal;
5275   linkcount++;
5276 }
5277
5278 static void ujump_assemble_write_ra(int i)
5279 {
5280   int rt;
5281   unsigned int return_address;
5282   rt=get_reg(branch_regs[i].regmap,31);
5283   assem_debug("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5284   //assert(rt>=0);
5285   return_address=start+i*4+8;
5286   if(rt>=0) {
5287     #ifdef USE_MINI_HT
5288     if(internal_branch(return_address)&&dops[i+1].rt1!=31) {
5289       int temp=-1; // note: must be ds-safe
5290       #ifdef HOST_TEMPREG
5291       temp=HOST_TEMPREG;
5292       #endif
5293       if(temp>=0) do_miniht_insert(return_address,rt,temp);
5294       else emit_movimm(return_address,rt);
5295     }
5296     else
5297     #endif
5298     {
5299       #ifdef REG_PREFETCH
5300       if(temp>=0)
5301       {
5302         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5303       }
5304       #endif
5305       emit_movimm(return_address,rt); // PC into link register
5306       #ifdef IMM_PREFETCH
5307       emit_prefetch(hash_table_get(return_address));
5308       #endif
5309     }
5310   }
5311 }
5312
5313 static void ujump_assemble(int i, const struct regstat *i_regs)
5314 {
5315   int ra_done=0;
5316   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5317   address_generation(i+1,i_regs,regs[i].regmap_entry);
5318   #ifdef REG_PREFETCH
5319   int temp=get_reg(branch_regs[i].regmap,PTEMP);
5320   if(dops[i].rt1==31&&temp>=0)
5321   {
5322     signed char *i_regmap=i_regs->regmap;
5323     int return_address=start+i*4+8;
5324     if(get_reg(branch_regs[i].regmap,31)>0)
5325     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5326   }
5327   #endif
5328   if(dops[i].rt1==31&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5329     ujump_assemble_write_ra(i); // writeback ra for DS
5330     ra_done=1;
5331   }
5332   ds_assemble(i+1,i_regs);
5333   uint64_t bc_unneeded=branch_regs[i].u;
5334   bc_unneeded|=1|(1LL<<dops[i].rt1);
5335   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5336   load_reg(regs[i].regmap,branch_regs[i].regmap,CCREG);
5337   if(!ra_done&&dops[i].rt1==31)
5338     ujump_assemble_write_ra(i);
5339   int cc,adj;
5340   cc=get_reg(branch_regs[i].regmap,CCREG);
5341   assert(cc==HOST_CCREG);
5342   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5343   #ifdef REG_PREFETCH
5344   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5345   #endif
5346   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5347   if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5348   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5349   if(internal_branch(ba[i]))
5350     assem_debug("branch: internal\n");
5351   else
5352     assem_debug("branch: external\n");
5353   if (internal_branch(ba[i]) && dops[(ba[i]-start)>>2].is_ds) {
5354     ds_assemble_entry(i);
5355   }
5356   else {
5357     add_to_linker(out,ba[i],internal_branch(ba[i]));
5358     emit_jmp(0);
5359   }
5360 }
5361
5362 static void rjump_assemble_write_ra(int i)
5363 {
5364   int rt,return_address;
5365   assert(dops[i+1].rt1!=dops[i].rt1);
5366   assert(dops[i+1].rt2!=dops[i].rt1);
5367   rt=get_reg(branch_regs[i].regmap,dops[i].rt1);
5368   assem_debug("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5369   assert(rt>=0);
5370   return_address=start+i*4+8;
5371   #ifdef REG_PREFETCH
5372   if(temp>=0)
5373   {
5374     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5375   }
5376   #endif
5377   emit_movimm(return_address,rt); // PC into link register
5378   #ifdef IMM_PREFETCH
5379   emit_prefetch(hash_table_get(return_address));
5380   #endif
5381 }
5382
5383 static void rjump_assemble(int i, const struct regstat *i_regs)
5384 {
5385   int temp;
5386   int rs,cc;
5387   int ra_done=0;
5388   rs=get_reg(branch_regs[i].regmap,dops[i].rs1);
5389   assert(rs>=0);
5390   if (ds_writes_rjump_rs(i)) {
5391     // Delay slot abuse, make a copy of the branch address register
5392     temp=get_reg(branch_regs[i].regmap,RTEMP);
5393     assert(temp>=0);
5394     assert(regs[i].regmap[temp]==RTEMP);
5395     emit_mov(rs,temp);
5396     rs=temp;
5397   }
5398   address_generation(i+1,i_regs,regs[i].regmap_entry);
5399   #ifdef REG_PREFETCH
5400   if(dops[i].rt1==31)
5401   {
5402     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
5403       signed char *i_regmap=i_regs->regmap;
5404       int return_address=start+i*4+8;
5405       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5406     }
5407   }
5408   #endif
5409   #ifdef USE_MINI_HT
5410   if(dops[i].rs1==31) {
5411     int rh=get_reg(regs[i].regmap,RHASH);
5412     if(rh>=0) do_preload_rhash(rh);
5413   }
5414   #endif
5415   if(dops[i].rt1!=0&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5416     rjump_assemble_write_ra(i);
5417     ra_done=1;
5418   }
5419   ds_assemble(i+1,i_regs);
5420   uint64_t bc_unneeded=branch_regs[i].u;
5421   bc_unneeded|=1|(1LL<<dops[i].rt1);
5422   bc_unneeded&=~(1LL<<dops[i].rs1);
5423   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5424   load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,CCREG);
5425   if(!ra_done&&dops[i].rt1!=0)
5426     rjump_assemble_write_ra(i);
5427   cc=get_reg(branch_regs[i].regmap,CCREG);
5428   assert(cc==HOST_CCREG);
5429   (void)cc;
5430   #ifdef USE_MINI_HT
5431   int rh=get_reg(branch_regs[i].regmap,RHASH);
5432   int ht=get_reg(branch_regs[i].regmap,RHTBL);
5433   if(dops[i].rs1==31) {
5434     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
5435     do_preload_rhtbl(ht);
5436     do_rhash(rs,rh);
5437   }
5438   #endif
5439   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5440   #ifdef DESTRUCTIVE_WRITEBACK
5441   if((branch_regs[i].dirty>>rs)&1) {
5442     if(dops[i].rs1!=dops[i+1].rt1&&dops[i].rs1!=dops[i+1].rt2) {
5443       emit_loadreg(dops[i].rs1,rs);
5444     }
5445   }
5446   #endif
5447   #ifdef REG_PREFETCH
5448   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5449   #endif
5450   #ifdef USE_MINI_HT
5451   if(dops[i].rs1==31) {
5452     do_miniht_load(ht,rh);
5453   }
5454   #endif
5455   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
5456   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
5457   //assert(adj==0);
5458   emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5459   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
5460   if(dops[i+1].itype==COP0 && dops[i+1].opcode2==0x10)
5461     // special case for RFE
5462     emit_jmp(0);
5463   else
5464     emit_jns(0);
5465   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5466   #ifdef USE_MINI_HT
5467   if(dops[i].rs1==31) {
5468     do_miniht_jump(rs,rh,ht);
5469   }
5470   else
5471   #endif
5472   {
5473     do_jump_vaddr(rs);
5474   }
5475   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5476   if(dops[i].rt1!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
5477   #endif
5478 }
5479
5480 static void cjump_assemble(int i, const struct regstat *i_regs)
5481 {
5482   const signed char *i_regmap = i_regs->regmap;
5483   int cc;
5484   int match;
5485   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5486   assem_debug("match=%d\n",match);
5487   int s1l,s2l;
5488   int unconditional=0,nop=0;
5489   int invert=0;
5490   int internal=internal_branch(ba[i]);
5491   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5492   if(!match) invert=1;
5493   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5494   if(i>(ba[i]-start)>>2) invert=1;
5495   #endif
5496   #ifdef __aarch64__
5497   invert=1; // because of near cond. branches
5498   #endif
5499
5500   if(dops[i].ooo) {
5501     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5502     s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
5503   }
5504   else {
5505     s1l=get_reg(i_regmap,dops[i].rs1);
5506     s2l=get_reg(i_regmap,dops[i].rs2);
5507   }
5508   if(dops[i].rs1==0&&dops[i].rs2==0)
5509   {
5510     if(dops[i].opcode&1) nop=1;
5511     else unconditional=1;
5512     //assert(dops[i].opcode!=5);
5513     //assert(dops[i].opcode!=7);
5514     //assert(dops[i].opcode!=0x15);
5515     //assert(dops[i].opcode!=0x17);
5516   }
5517   else if(dops[i].rs1==0)
5518   {
5519     s1l=s2l;
5520     s2l=-1;
5521   }
5522   else if(dops[i].rs2==0)
5523   {
5524     s2l=-1;
5525   }
5526
5527   if(dops[i].ooo) {
5528     // Out of order execution (delay slot first)
5529     //printf("OOOE\n");
5530     address_generation(i+1,i_regs,regs[i].regmap_entry);
5531     ds_assemble(i+1,i_regs);
5532     int adj;
5533     uint64_t bc_unneeded=branch_regs[i].u;
5534     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5535     bc_unneeded|=1;
5536     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5537     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs2);
5538     load_reg(regs[i].regmap,branch_regs[i].regmap,CCREG);
5539     cc=get_reg(branch_regs[i].regmap,CCREG);
5540     assert(cc==HOST_CCREG);
5541     if(unconditional)
5542       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5543     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5544     //assem_debug("cycle count (adj)\n");
5545     if(unconditional) {
5546       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5547       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5548         if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5549         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5550         if(internal)
5551           assem_debug("branch: internal\n");
5552         else
5553           assem_debug("branch: external\n");
5554         if (internal && dops[(ba[i]-start)>>2].is_ds) {
5555           ds_assemble_entry(i);
5556         }
5557         else {
5558           add_to_linker(out,ba[i],internal);
5559           emit_jmp(0);
5560         }
5561         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5562         if(((u_int)out)&7) emit_addnop(0);
5563         #endif
5564       }
5565     }
5566     else if(nop) {
5567       emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5568       void *jaddr=out;
5569       emit_jns(0);
5570       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5571     }
5572     else {
5573       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5574       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5575       if(adj&&!invert) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5576
5577       //printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5578       assert(s1l>=0);
5579       if(dops[i].opcode==4) // BEQ
5580       {
5581         if(s2l>=0) emit_cmp(s1l,s2l);
5582         else emit_test(s1l,s1l);
5583         if(invert){
5584           nottaken=out;
5585           emit_jne(DJT_1);
5586         }else{
5587           add_to_linker(out,ba[i],internal);
5588           emit_jeq(0);
5589         }
5590       }
5591       if(dops[i].opcode==5) // BNE
5592       {
5593         if(s2l>=0) emit_cmp(s1l,s2l);
5594         else emit_test(s1l,s1l);
5595         if(invert){
5596           nottaken=out;
5597           emit_jeq(DJT_1);
5598         }else{
5599           add_to_linker(out,ba[i],internal);
5600           emit_jne(0);
5601         }
5602       }
5603       if(dops[i].opcode==6) // BLEZ
5604       {
5605         emit_cmpimm(s1l,1);
5606         if(invert){
5607           nottaken=out;
5608           emit_jge(DJT_1);
5609         }else{
5610           add_to_linker(out,ba[i],internal);
5611           emit_jl(0);
5612         }
5613       }
5614       if(dops[i].opcode==7) // BGTZ
5615       {
5616         emit_cmpimm(s1l,1);
5617         if(invert){
5618           nottaken=out;
5619           emit_jl(DJT_1);
5620         }else{
5621           add_to_linker(out,ba[i],internal);
5622           emit_jge(0);
5623         }
5624       }
5625       if(invert) {
5626         if(taken) set_jump_target(taken, out);
5627         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5628         if (match && (!internal || !dops[(ba[i]-start)>>2].is_ds)) {
5629           if(adj) {
5630             emit_addimm(cc,-adj,cc);
5631             add_to_linker(out,ba[i],internal);
5632           }else{
5633             emit_addnop(13);
5634             add_to_linker(out,ba[i],internal*2);
5635           }
5636           emit_jmp(0);
5637         }else
5638         #endif
5639         {
5640           if(adj) emit_addimm(cc,-adj,cc);
5641           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5642           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5643           if(internal)
5644             assem_debug("branch: internal\n");
5645           else
5646             assem_debug("branch: external\n");
5647           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5648             ds_assemble_entry(i);
5649           }
5650           else {
5651             add_to_linker(out,ba[i],internal);
5652             emit_jmp(0);
5653           }
5654         }
5655         set_jump_target(nottaken, out);
5656       }
5657
5658       if(nottaken1) set_jump_target(nottaken1, out);
5659       if(adj) {
5660         if(!invert) emit_addimm(cc,adj,cc);
5661       }
5662     } // (!unconditional)
5663   } // if(ooo)
5664   else
5665   {
5666     // In-order execution (branch first)
5667     void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5668     if(!unconditional&&!nop) {
5669       //printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5670       assert(s1l>=0);
5671       if((dops[i].opcode&0x2f)==4) // BEQ
5672       {
5673         if(s2l>=0) emit_cmp(s1l,s2l);
5674         else emit_test(s1l,s1l);
5675         nottaken=out;
5676         emit_jne(DJT_2);
5677       }
5678       if((dops[i].opcode&0x2f)==5) // BNE
5679       {
5680         if(s2l>=0) emit_cmp(s1l,s2l);
5681         else emit_test(s1l,s1l);
5682         nottaken=out;
5683         emit_jeq(DJT_2);
5684       }
5685       if((dops[i].opcode&0x2f)==6) // BLEZ
5686       {
5687         emit_cmpimm(s1l,1);
5688         nottaken=out;
5689         emit_jge(DJT_2);
5690       }
5691       if((dops[i].opcode&0x2f)==7) // BGTZ
5692       {
5693         emit_cmpimm(s1l,1);
5694         nottaken=out;
5695         emit_jl(DJT_2);
5696       }
5697     } // if(!unconditional)
5698     int adj;
5699     uint64_t ds_unneeded=branch_regs[i].u;
5700     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5701     ds_unneeded|=1;
5702     // branch taken
5703     if(!nop) {
5704       if(taken) set_jump_target(taken, out);
5705       assem_debug("1:\n");
5706       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5707       // load regs
5708       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5709       address_generation(i+1,&branch_regs[i],0);
5710       if (ram_offset)
5711         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
5712       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5713       ds_assemble(i+1,&branch_regs[i]);
5714       cc=get_reg(branch_regs[i].regmap,CCREG);
5715       if(cc==-1) {
5716         emit_loadreg(CCREG,cc=HOST_CCREG);
5717         // CHECK: Is the following instruction (fall thru) allocated ok?
5718       }
5719       assert(cc==HOST_CCREG);
5720       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5721       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5722       assem_debug("cycle count (adj)\n");
5723       if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5724       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5725       if(internal)
5726         assem_debug("branch: internal\n");
5727       else
5728         assem_debug("branch: external\n");
5729       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5730         ds_assemble_entry(i);
5731       }
5732       else {
5733         add_to_linker(out,ba[i],internal);
5734         emit_jmp(0);
5735       }
5736     }
5737     // branch not taken
5738     if(!unconditional) {
5739       if(nottaken1) set_jump_target(nottaken1, out);
5740       set_jump_target(nottaken, out);
5741       assem_debug("2:\n");
5742       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5743       // load regs
5744       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5745       address_generation(i+1,&branch_regs[i],0);
5746       if (ram_offset)
5747         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
5748       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5749       ds_assemble(i+1,&branch_regs[i]);
5750       cc=get_reg(branch_regs[i].regmap,CCREG);
5751       if (cc == -1) {
5752         // Cycle count isn't in a register, temporarily load it then write it out
5753         emit_loadreg(CCREG,HOST_CCREG);
5754         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5755         void *jaddr=out;
5756         emit_jns(0);
5757         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5758         emit_storereg(CCREG,HOST_CCREG);
5759       }
5760       else{
5761         cc=get_reg(i_regmap,CCREG);
5762         assert(cc==HOST_CCREG);
5763         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5764         void *jaddr=out;
5765         emit_jns(0);
5766         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5767       }
5768     }
5769   }
5770 }
5771
5772 static void sjump_assemble(int i, const struct regstat *i_regs)
5773 {
5774   const signed char *i_regmap = i_regs->regmap;
5775   int cc;
5776   int match;
5777   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5778   assem_debug("smatch=%d ooo=%d\n", match, dops[i].ooo);
5779   int s1l;
5780   int unconditional=0,nevertaken=0;
5781   int invert=0;
5782   int internal=internal_branch(ba[i]);
5783   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5784   if(!match) invert=1;
5785   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5786   if(i>(ba[i]-start)>>2) invert=1;
5787   #endif
5788   #ifdef __aarch64__
5789   invert=1; // because of near cond. branches
5790   #endif
5791
5792   //if(dops[i].opcode2>=0x10) return; // FIXME (BxxZAL)
5793   //assert(dops[i].opcode2<0x10||dops[i].rs1==0); // FIXME (BxxZAL)
5794
5795   if(dops[i].ooo) {
5796     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5797   }
5798   else {
5799     s1l=get_reg(i_regmap,dops[i].rs1);
5800   }
5801   if(dops[i].rs1==0)
5802   {
5803     if(dops[i].opcode2&1) unconditional=1;
5804     else nevertaken=1;
5805     // These are never taken (r0 is never less than zero)
5806     //assert(dops[i].opcode2!=0);
5807     //assert(dops[i].opcode2!=2);
5808     //assert(dops[i].opcode2!=0x10);
5809     //assert(dops[i].opcode2!=0x12);
5810   }
5811
5812   if(dops[i].ooo) {
5813     // Out of order execution (delay slot first)
5814     //printf("OOOE\n");
5815     address_generation(i+1,i_regs,regs[i].regmap_entry);
5816     ds_assemble(i+1,i_regs);
5817     int adj;
5818     uint64_t bc_unneeded=branch_regs[i].u;
5819     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5820     bc_unneeded|=1;
5821     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5822     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs1);
5823     load_reg(regs[i].regmap,branch_regs[i].regmap,CCREG);
5824     if(dops[i].rt1==31) {
5825       int rt,return_address;
5826       rt=get_reg(branch_regs[i].regmap,31);
5827       assem_debug("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5828       if(rt>=0) {
5829         // Save the PC even if the branch is not taken
5830         return_address=start+i*4+8;
5831         emit_movimm(return_address,rt); // PC into link register
5832         #ifdef IMM_PREFETCH
5833         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5834         #endif
5835       }
5836     }
5837     cc=get_reg(branch_regs[i].regmap,CCREG);
5838     assert(cc==HOST_CCREG);
5839     if(unconditional)
5840       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5841     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5842     assem_debug("cycle count (adj)\n");
5843     if(unconditional) {
5844       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5845       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5846         if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5847         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5848         if(internal)
5849           assem_debug("branch: internal\n");
5850         else
5851           assem_debug("branch: external\n");
5852         if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5853           ds_assemble_entry(i);
5854         }
5855         else {
5856           add_to_linker(out,ba[i],internal);
5857           emit_jmp(0);
5858         }
5859         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5860         if(((u_int)out)&7) emit_addnop(0);
5861         #endif
5862       }
5863     }
5864     else if(nevertaken) {
5865       emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5866       void *jaddr=out;
5867       emit_jns(0);
5868       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5869     }
5870     else {
5871       void *nottaken = NULL;
5872       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5873       if(adj&&!invert) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5874       {
5875         assert(s1l>=0);
5876         if((dops[i].opcode2&0xf)==0) // BLTZ/BLTZAL
5877         {
5878           emit_test(s1l,s1l);
5879           if(invert){
5880             nottaken=out;
5881             emit_jns(DJT_1);
5882           }else{
5883             add_to_linker(out,ba[i],internal);
5884             emit_js(0);
5885           }
5886         }
5887         if((dops[i].opcode2&0xf)==1) // BGEZ/BLTZAL
5888         {
5889           emit_test(s1l,s1l);
5890           if(invert){
5891             nottaken=out;
5892             emit_js(DJT_1);
5893           }else{
5894             add_to_linker(out,ba[i],internal);
5895             emit_jns(0);
5896           }
5897         }
5898       }
5899
5900       if(invert) {
5901         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5902         if (match && (!internal || !dops[(ba[i] - start) >> 2].is_ds)) {
5903           if(adj) {
5904             emit_addimm(cc,-adj,cc);
5905             add_to_linker(out,ba[i],internal);
5906           }else{
5907             emit_addnop(13);
5908             add_to_linker(out,ba[i],internal*2);
5909           }
5910           emit_jmp(0);
5911         }else
5912         #endif
5913         {
5914           if(adj) emit_addimm(cc,-adj,cc);
5915           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5916           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5917           if(internal)
5918             assem_debug("branch: internal\n");
5919           else
5920             assem_debug("branch: external\n");
5921           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5922             ds_assemble_entry(i);
5923           }
5924           else {
5925             add_to_linker(out,ba[i],internal);
5926             emit_jmp(0);
5927           }
5928         }
5929         set_jump_target(nottaken, out);
5930       }
5931
5932       if(adj) {
5933         if(!invert) emit_addimm(cc,adj,cc);
5934       }
5935     } // (!unconditional)
5936   } // if(ooo)
5937   else
5938   {
5939     // In-order execution (branch first)
5940     //printf("IOE\n");
5941     void *nottaken = NULL;
5942     if(dops[i].rt1==31) {
5943       int rt,return_address;
5944       rt=get_reg(branch_regs[i].regmap,31);
5945       if(rt>=0) {
5946         // Save the PC even if the branch is not taken
5947         return_address=start+i*4+8;
5948         emit_movimm(return_address,rt); // PC into link register
5949         #ifdef IMM_PREFETCH
5950         emit_prefetch(hash_table_get(return_address));
5951         #endif
5952       }
5953     }
5954     if(!unconditional) {
5955       //printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5956         assert(s1l>=0);
5957         if((dops[i].opcode2&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5958         {
5959           emit_test(s1l,s1l);
5960           nottaken=out;
5961           emit_jns(DJT_1);
5962         }
5963         if((dops[i].opcode2&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5964         {
5965           emit_test(s1l,s1l);
5966           nottaken=out;
5967           emit_js(DJT_1);
5968         }
5969     } // if(!unconditional)
5970     int adj;
5971     uint64_t ds_unneeded=branch_regs[i].u;
5972     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5973     ds_unneeded|=1;
5974     // branch taken
5975     if(!nevertaken) {
5976       //assem_debug("1:\n");
5977       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5978       // load regs
5979       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5980       address_generation(i+1,&branch_regs[i],0);
5981       if (ram_offset)
5982         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
5983       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5984       ds_assemble(i+1,&branch_regs[i]);
5985       cc=get_reg(branch_regs[i].regmap,CCREG);
5986       if(cc==-1) {
5987         emit_loadreg(CCREG,cc=HOST_CCREG);
5988         // CHECK: Is the following instruction (fall thru) allocated ok?
5989       }
5990       assert(cc==HOST_CCREG);
5991       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5992       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5993       assem_debug("cycle count (adj)\n");
5994       if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5995       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5996       if(internal)
5997         assem_debug("branch: internal\n");
5998       else
5999         assem_debug("branch: external\n");
6000       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
6001         ds_assemble_entry(i);
6002       }
6003       else {
6004         add_to_linker(out,ba[i],internal);
6005         emit_jmp(0);
6006       }
6007     }
6008     // branch not taken
6009     if(!unconditional) {
6010       set_jump_target(nottaken, out);
6011       assem_debug("1:\n");
6012       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
6013       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
6014       address_generation(i+1,&branch_regs[i],0);
6015       if (ram_offset)
6016         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
6017       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
6018       ds_assemble(i+1,&branch_regs[i]);
6019       cc=get_reg(branch_regs[i].regmap,CCREG);
6020       if (cc == -1) {
6021         // Cycle count isn't in a register, temporarily load it then write it out
6022         emit_loadreg(CCREG,HOST_CCREG);
6023         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
6024         void *jaddr=out;
6025         emit_jns(0);
6026         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
6027         emit_storereg(CCREG,HOST_CCREG);
6028       }
6029       else{
6030         cc=get_reg(i_regmap,CCREG);
6031         assert(cc==HOST_CCREG);
6032         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
6033         void *jaddr=out;
6034         emit_jns(0);
6035         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
6036       }
6037     }
6038   }
6039 }
6040
6041 static void check_regmap(signed char *regmap)
6042 {
6043 #ifndef NDEBUG
6044   int i,j;
6045   for (i = 0; i < HOST_REGS; i++) {
6046     if (regmap[i] < 0)
6047       continue;
6048     for (j = i + 1; j < HOST_REGS; j++)
6049       assert(regmap[i] != regmap[j]);
6050   }
6051 #endif
6052 }
6053
6054 #ifdef DISASM
6055 #include <inttypes.h>
6056 static char insn[MAXBLOCK][10];
6057
6058 #define set_mnemonic(i_, n_) \
6059   strcpy(insn[i_], n_)
6060
6061 void print_regmap(const char *name, const signed char *regmap)
6062 {
6063   char buf[5];
6064   int i, l;
6065   fputs(name, stdout);
6066   for (i = 0; i < HOST_REGS; i++) {
6067     l = 0;
6068     if (regmap[i] >= 0)
6069       l = snprintf(buf, sizeof(buf), "$%d", regmap[i]);
6070     for (; l < 3; l++)
6071       buf[l] = ' ';
6072     buf[l] = 0;
6073     printf(" r%d=%s", i, buf);
6074   }
6075   fputs("\n", stdout);
6076 }
6077
6078   /* disassembly */
6079 void disassemble_inst(int i)
6080 {
6081     if (dops[i].bt) printf("*"); else printf(" ");
6082     switch(dops[i].itype) {
6083       case UJUMP:
6084         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6085       case CJUMP:
6086         printf (" %x: %s r%d,r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2,i?start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14):*ba);break;
6087       case SJUMP:
6088         printf (" %x: %s r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14));break;
6089       case RJUMP:
6090         if (dops[i].opcode==0x9&&dops[i].rt1!=31)
6091           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1);
6092         else
6093           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6094         break;
6095       case IMM16:
6096         if(dops[i].opcode==0xf) //LUI
6097           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],dops[i].rt1,imm[i]&0xffff);
6098         else
6099           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6100         break;
6101       case LOAD:
6102       case LOADLR:
6103         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6104         break;
6105       case STORE:
6106       case STORELR:
6107         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rs2,dops[i].rs1,imm[i]);
6108         break;
6109       case ALU:
6110       case SHIFT:
6111         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,dops[i].rs2);
6112         break;
6113       case MULTDIV:
6114         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2);
6115         break;
6116       case SHIFTIMM:
6117         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6118         break;
6119       case MOV:
6120         if((dops[i].opcode2&0x1d)==0x10)
6121           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rt1);
6122         else if((dops[i].opcode2&0x1d)==0x11)
6123           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6124         else
6125           printf (" %x: %s\n",start+i*4,insn[i]);
6126         break;
6127       case COP0:
6128         if(dops[i].opcode2==0)
6129           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC0
6130         else if(dops[i].opcode2==4)
6131           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC0
6132         else printf (" %x: %s\n",start+i*4,insn[i]);
6133         break;
6134       case COP1:
6135         if(dops[i].opcode2<3)
6136           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC1
6137         else if(dops[i].opcode2>3)
6138           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC1
6139         else printf (" %x: %s\n",start+i*4,insn[i]);
6140         break;
6141       case COP2:
6142         if(dops[i].opcode2<3)
6143           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC2
6144         else if(dops[i].opcode2>3)
6145           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC2
6146         else printf (" %x: %s\n",start+i*4,insn[i]);
6147         break;
6148       case C1LS:
6149         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6150         break;
6151       case C2LS:
6152         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6153         break;
6154       case INTCALL:
6155         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6156         break;
6157       default:
6158         //printf (" %s %8x\n",insn[i],source[i]);
6159         printf (" %x: %s\n",start+i*4,insn[i]);
6160     }
6161     return;
6162     printf("D: %"PRIu64"  WD: %"PRIu64"  U: %"PRIu64"\n",
6163       regs[i].dirty, regs[i].wasdirty, unneeded_reg[i]);
6164     print_regmap("pre:   ", regmap_pre[i]);
6165     print_regmap("entry: ", regs[i].regmap_entry);
6166     print_regmap("map:   ", regs[i].regmap);
6167     if (dops[i].is_jump) {
6168       print_regmap("bentry:", branch_regs[i].regmap_entry);
6169       print_regmap("bmap:  ", branch_regs[i].regmap);
6170     }
6171 }
6172 #else
6173 #define set_mnemonic(i_, n_)
6174 static void disassemble_inst(int i) {}
6175 #endif // DISASM
6176
6177 #define DRC_TEST_VAL 0x74657374
6178
6179 static noinline void new_dynarec_test(void)
6180 {
6181   int (*testfunc)(void);
6182   void *beginning;
6183   int ret[2];
6184   size_t i;
6185
6186   // check structure linkage
6187   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6188   {
6189     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6190   }
6191
6192   SysPrintf("(%p) testing if we can run recompiled code @%p...\n",
6193     new_dynarec_test, out);
6194   ((volatile u_int *)NDRC_WRITE_OFFSET(out))[0]++; // make the cache dirty
6195
6196   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6197     out = ndrc->translation_cache;
6198     beginning = start_block();
6199     emit_movimm(DRC_TEST_VAL + i, 0); // test
6200     emit_ret();
6201     literal_pool(0);
6202     end_block(beginning);
6203     testfunc = beginning;
6204     ret[i] = testfunc();
6205   }
6206
6207   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6208     SysPrintf("test passed.\n");
6209   else
6210     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6211   out = ndrc->translation_cache;
6212 }
6213
6214 // clear the state completely, instead of just marking
6215 // things invalid like invalidate_all_pages() does
6216 void new_dynarec_clear_full(void)
6217 {
6218   int n;
6219   out = ndrc->translation_cache;
6220   memset(invalid_code,1,sizeof(invalid_code));
6221   memset(hash_table,0xff,sizeof(hash_table));
6222   memset(mini_ht,-1,sizeof(mini_ht));
6223   memset(shadow,0,sizeof(shadow));
6224   copy=shadow;
6225   expirep = EXPIRITY_OFFSET;
6226   pending_exception=0;
6227   literalcount=0;
6228   stop_after_jal=0;
6229   inv_code_start=inv_code_end=~0;
6230   hack_addr=0;
6231   f1_hack=0;
6232   for (n = 0; n < ARRAY_SIZE(blocks); n++)
6233     blocks_clear(&blocks[n]);
6234   for (n = 0; n < ARRAY_SIZE(jumps); n++) {
6235     free(jumps[n]);
6236     jumps[n] = NULL;
6237   }
6238   stat_clear(stat_blocks);
6239   stat_clear(stat_links);
6240
6241   cycle_multiplier_old = Config.cycle_multiplier;
6242   new_dynarec_hacks_old = new_dynarec_hacks;
6243 }
6244
6245 void new_dynarec_init(void)
6246 {
6247   SysPrintf("Init new dynarec, ndrc size %x\n", (int)sizeof(*ndrc));
6248
6249 #ifdef _3DS
6250   check_rosalina();
6251 #endif
6252 #ifdef BASE_ADDR_DYNAMIC
6253   #ifdef VITA
6254   sceBlock = getVMBlock(); //sceKernelAllocMemBlockForVM("code", sizeof(*ndrc));
6255   if (sceBlock <= 0)
6256     SysPrintf("sceKernelAllocMemBlockForVM failed: %x\n", sceBlock);
6257   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6258   if (ret < 0)
6259     SysPrintf("sceKernelGetMemBlockBase failed: %x\n", ret);
6260   sceKernelOpenVMDomain();
6261   sceClibPrintf("translation_cache = 0x%08lx\n ", (long)ndrc->translation_cache);
6262   #elif defined(_MSC_VER)
6263   ndrc = VirtualAlloc(NULL, sizeof(*ndrc), MEM_COMMIT | MEM_RESERVE,
6264     PAGE_EXECUTE_READWRITE);
6265   #elif defined(HAVE_LIBNX)
6266   Result rc = jitCreate(&g_jit, sizeof(*ndrc));
6267   if (R_FAILED(rc))
6268     SysPrintf("jitCreate failed: %08x\n", rc);
6269   SysPrintf("jitCreate: RX: %p RW: %p type: %d\n", g_jit.rx_addr, g_jit.rw_addr, g_jit.type);
6270   jitTransitionToWritable(&g_jit);
6271   ndrc = g_jit.rx_addr;
6272   ndrc_write_ofs = (char *)g_jit.rw_addr - (char *)ndrc;
6273   memset(NDRC_WRITE_OFFSET(&ndrc->tramp), 0, sizeof(ndrc->tramp));
6274   #else
6275   uintptr_t desired_addr = 0;
6276   int prot = PROT_READ | PROT_WRITE | PROT_EXEC;
6277   int flags = MAP_PRIVATE | MAP_ANONYMOUS;
6278   int fd = -1;
6279   #ifdef __ELF__
6280   extern char _end;
6281   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6282   #endif
6283   #ifdef TC_WRITE_OFFSET
6284   // mostly for testing
6285   fd = open("/dev/shm/pcsxr", O_CREAT | O_RDWR, 0600);
6286   ftruncate(fd, sizeof(*ndrc));
6287   void *mw = mmap(NULL, sizeof(*ndrc), PROT_READ | PROT_WRITE,
6288                   (flags = MAP_SHARED), fd, 0);
6289   assert(mw != MAP_FAILED);
6290   prot = PROT_READ | PROT_EXEC;
6291   #endif
6292   ndrc = mmap((void *)desired_addr, sizeof(*ndrc), prot, flags, fd, 0);
6293   if (ndrc == MAP_FAILED) {
6294     SysPrintf("mmap() failed: %s\n", strerror(errno));
6295     abort();
6296   }
6297   #ifdef TC_WRITE_OFFSET
6298   ndrc_write_ofs = (char *)mw - (char *)ndrc;
6299   #endif
6300   #endif
6301 #else
6302   #ifndef NO_WRITE_EXEC
6303   // not all systems allow execute in data segment by default
6304   // size must be 4K aligned for 3DS?
6305   if (mprotect(ndrc, sizeof(*ndrc),
6306                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6307     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6308   #endif
6309 #endif
6310   out = ndrc->translation_cache;
6311   new_dynarec_clear_full();
6312 #ifdef HOST_IMM8
6313   // Copy this into local area so we don't have to put it in every literal pool
6314   invc_ptr=invalid_code;
6315 #endif
6316   arch_init();
6317   new_dynarec_test();
6318   ram_offset=(uintptr_t)rdram-0x80000000;
6319   if (ram_offset!=0)
6320     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6321   SysPrintf("Mapped (RAM/scrp/ROM/LUTs/TC):\n");
6322   SysPrintf("%p/%p/%p/%p/%p\n", psxM, psxH, psxR, mem_rtab, out);
6323 }
6324
6325 void new_dynarec_cleanup(void)
6326 {
6327   int n;
6328 #ifdef BASE_ADDR_DYNAMIC
6329   #ifdef VITA
6330   // sceBlock is managed by retroarch's bootstrap code
6331   //sceKernelFreeMemBlock(sceBlock);
6332   //sceBlock = -1;
6333   #elif defined(HAVE_LIBNX)
6334   jitClose(&g_jit);
6335   ndrc = NULL;
6336   #else
6337   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6338     SysPrintf("munmap() failed\n");
6339   ndrc = NULL;
6340   #endif
6341 #endif
6342   for (n = 0; n < ARRAY_SIZE(blocks); n++)
6343     blocks_clear(&blocks[n]);
6344   for (n = 0; n < ARRAY_SIZE(jumps); n++) {
6345     free(jumps[n]);
6346     jumps[n] = NULL;
6347   }
6348   stat_clear(stat_blocks);
6349   stat_clear(stat_links);
6350   new_dynarec_print_stats();
6351 }
6352
6353 static u_int *get_source_start(u_int addr, u_int *limit)
6354 {
6355   if (addr < 0x00200000 ||
6356     (0xa0000000 <= addr && addr < 0xa0200000))
6357   {
6358     // used for BIOS calls mostly?
6359     *limit = (addr&0xa0000000)|0x00200000;
6360     return (u_int *)(rdram + (addr&0x1fffff));
6361   }
6362   else if (!Config.HLE && (
6363     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
6364     (0xbfc00000 <= addr && addr < 0xbfc80000)))
6365   {
6366     // BIOS. The multiplier should be much higher as it's uncached 8bit mem,
6367     // but timings in PCSX are too tied to the interpreter's 2-per-insn assumption
6368     if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6369       cycle_multiplier_active = 200;
6370
6371     *limit = (addr & 0xfff00000) | 0x80000;
6372     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
6373   }
6374   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
6375     *limit = (addr & 0x80600000) + 0x00200000;
6376     return (u_int *)(rdram + (addr&0x1fffff));
6377   }
6378   return NULL;
6379 }
6380
6381 static u_int scan_for_ret(u_int addr)
6382 {
6383   u_int limit = 0;
6384   u_int *mem;
6385
6386   mem = get_source_start(addr, &limit);
6387   if (mem == NULL)
6388     return addr;
6389
6390   if (limit > addr + 0x1000)
6391     limit = addr + 0x1000;
6392   for (; addr < limit; addr += 4, mem++) {
6393     if (*mem == 0x03e00008) // jr $ra
6394       return addr + 8;
6395   }
6396   return addr;
6397 }
6398
6399 struct savestate_block {
6400   uint32_t addr;
6401   uint32_t regflags;
6402 };
6403
6404 static int addr_cmp(const void *p1_, const void *p2_)
6405 {
6406   const struct savestate_block *p1 = p1_, *p2 = p2_;
6407   return p1->addr - p2->addr;
6408 }
6409
6410 int new_dynarec_save_blocks(void *save, int size)
6411 {
6412   struct savestate_block *sblocks = save;
6413   int maxcount = size / sizeof(sblocks[0]);
6414   struct savestate_block tmp_blocks[1024];
6415   struct block_info *block;
6416   int p, s, d, o, bcnt;
6417   u_int addr;
6418
6419   o = 0;
6420   for (p = 0; p < ARRAY_SIZE(blocks); p++) {
6421     bcnt = 0;
6422     for (block = blocks[p]; block != NULL; block = block->next) {
6423       if (block->is_dirty)
6424         continue;
6425       tmp_blocks[bcnt].addr = block->start;
6426       tmp_blocks[bcnt].regflags = block->reg_sv_flags;
6427       bcnt++;
6428     }
6429     if (bcnt < 1)
6430       continue;
6431     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
6432
6433     addr = tmp_blocks[0].addr;
6434     for (s = d = 0; s < bcnt; s++) {
6435       if (tmp_blocks[s].addr < addr)
6436         continue;
6437       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
6438         tmp_blocks[d++] = tmp_blocks[s];
6439       addr = scan_for_ret(tmp_blocks[s].addr);
6440     }
6441
6442     if (o + d > maxcount)
6443       d = maxcount - o;
6444     memcpy(&sblocks[o], tmp_blocks, d * sizeof(sblocks[0]));
6445     o += d;
6446   }
6447
6448   return o * sizeof(sblocks[0]);
6449 }
6450
6451 void new_dynarec_load_blocks(const void *save, int size)
6452 {
6453   const struct savestate_block *sblocks = save;
6454   int count = size / sizeof(sblocks[0]);
6455   struct block_info *block;
6456   u_int regs_save[32];
6457   u_int page;
6458   uint32_t f;
6459   int i, b;
6460
6461   // restore clean blocks, if any
6462   for (page = 0, b = i = 0; page < ARRAY_SIZE(blocks); page++) {
6463     for (block = blocks[page]; block != NULL; block = block->next, b++) {
6464       if (!block->is_dirty)
6465         continue;
6466       assert(block->source && block->copy);
6467       if (memcmp(block->source, block->copy, block->len))
6468         continue;
6469
6470       // see try_restore_block
6471       block->is_dirty = 0;
6472       mark_invalid_code(block->start, block->len, 0);
6473       i++;
6474     }
6475   }
6476   inv_debug("load_blocks: %d/%d clean blocks\n", i, b);
6477
6478   // change GPRs for speculation to at least partially work..
6479   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
6480   for (i = 1; i < 32; i++)
6481     psxRegs.GPR.r[i] = 0x80000000;
6482
6483   for (b = 0; b < count; b++) {
6484     for (f = sblocks[b].regflags, i = 0; f; f >>= 1, i++) {
6485       if (f & 1)
6486         psxRegs.GPR.r[i] = 0x1f800000;
6487     }
6488
6489     ndrc_get_addr_ht(sblocks[b].addr);
6490
6491     for (f = sblocks[b].regflags, i = 0; f; f >>= 1, i++) {
6492       if (f & 1)
6493         psxRegs.GPR.r[i] = 0x80000000;
6494     }
6495   }
6496
6497   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
6498 }
6499
6500 void new_dynarec_print_stats(void)
6501 {
6502 #ifdef STAT_PRINT
6503   printf("cc %3d,%3d,%3d lu%6d,%3d,%3d c%3d inv%3d,%3d tc_offs %zu b %u,%u\n",
6504     stat_bc_pre, stat_bc_direct, stat_bc_restore,
6505     stat_ht_lookups, stat_jump_in_lookups, stat_restore_tries,
6506     stat_restore_compares, stat_inv_addr_calls, stat_inv_hits,
6507     out - ndrc->translation_cache, stat_blocks, stat_links);
6508   stat_bc_direct = stat_bc_pre = stat_bc_restore =
6509   stat_ht_lookups = stat_jump_in_lookups = stat_restore_tries =
6510   stat_restore_compares = stat_inv_addr_calls = stat_inv_hits = 0;
6511 #endif
6512 }
6513
6514 static int apply_hacks(void)
6515 {
6516   int i;
6517   if (HACK_ENABLED(NDHACK_NO_COMPAT_HACKS))
6518     return 0;
6519   /* special hack(s) */
6520   for (i = 0; i < slen - 4; i++)
6521   {
6522     // lui a4, 0xf200; jal <rcnt_read>; addu a0, 2; slti v0, 28224
6523     if (source[i] == 0x3c04f200 && dops[i+1].itype == UJUMP
6524         && source[i+2] == 0x34840002 && dops[i+3].opcode == 0x0a
6525         && imm[i+3] == 0x6e40 && dops[i+3].rs1 == 2)
6526     {
6527       SysPrintf("PE2 hack @%08x\n", start + (i+3)*4);
6528       dops[i + 3].itype = NOP;
6529     }
6530   }
6531   i = slen;
6532   if (i > 10 && source[i-1] == 0 && source[i-2] == 0x03e00008
6533       && source[i-4] == 0x8fbf0018 && source[i-6] == 0x00c0f809
6534       && dops[i-7].itype == STORE)
6535   {
6536     i = i-8;
6537     if (dops[i].itype == IMM16)
6538       i--;
6539     // swl r2, 15(r6); swr r2, 12(r6); sw r6, *; jalr r6
6540     if (dops[i].itype == STORELR && dops[i].rs1 == 6
6541       && dops[i-1].itype == STORELR && dops[i-1].rs1 == 6)
6542     {
6543       SysPrintf("F1 hack from %08x, old dst %08x\n", start, hack_addr);
6544       f1_hack = 1;
6545       return 1;
6546     }
6547   }
6548   return 0;
6549 }
6550
6551 static noinline void pass1_disassemble(u_int pagelimit)
6552 {
6553   int i, j, done = 0, ni_count = 0;
6554   unsigned int type,op,op2;
6555
6556   for (i = 0; !done; i++)
6557   {
6558     memset(&dops[i], 0, sizeof(dops[i]));
6559     op2=0;
6560     minimum_free_regs[i]=0;
6561     dops[i].opcode=op=source[i]>>26;
6562     switch(op)
6563     {
6564       case 0x00: set_mnemonic(i, "special"); type=NI;
6565         op2=source[i]&0x3f;
6566         switch(op2)
6567         {
6568           case 0x00: set_mnemonic(i, "SLL"); type=SHIFTIMM; break;
6569           case 0x02: set_mnemonic(i, "SRL"); type=SHIFTIMM; break;
6570           case 0x03: set_mnemonic(i, "SRA"); type=SHIFTIMM; break;
6571           case 0x04: set_mnemonic(i, "SLLV"); type=SHIFT; break;
6572           case 0x06: set_mnemonic(i, "SRLV"); type=SHIFT; break;
6573           case 0x07: set_mnemonic(i, "SRAV"); type=SHIFT; break;
6574           case 0x08: set_mnemonic(i, "JR"); type=RJUMP; break;
6575           case 0x09: set_mnemonic(i, "JALR"); type=RJUMP; break;
6576           case 0x0C: set_mnemonic(i, "SYSCALL"); type=SYSCALL; break;
6577           case 0x0D: set_mnemonic(i, "BREAK"); type=SYSCALL; break;
6578           case 0x0F: set_mnemonic(i, "SYNC"); type=OTHER; break;
6579           case 0x10: set_mnemonic(i, "MFHI"); type=MOV; break;
6580           case 0x11: set_mnemonic(i, "MTHI"); type=MOV; break;
6581           case 0x12: set_mnemonic(i, "MFLO"); type=MOV; break;
6582           case 0x13: set_mnemonic(i, "MTLO"); type=MOV; break;
6583           case 0x18: set_mnemonic(i, "MULT"); type=MULTDIV; break;
6584           case 0x19: set_mnemonic(i, "MULTU"); type=MULTDIV; break;
6585           case 0x1A: set_mnemonic(i, "DIV"); type=MULTDIV; break;
6586           case 0x1B: set_mnemonic(i, "DIVU"); type=MULTDIV; break;
6587           case 0x20: set_mnemonic(i, "ADD"); type=ALU; break;
6588           case 0x21: set_mnemonic(i, "ADDU"); type=ALU; break;
6589           case 0x22: set_mnemonic(i, "SUB"); type=ALU; break;
6590           case 0x23: set_mnemonic(i, "SUBU"); type=ALU; break;
6591           case 0x24: set_mnemonic(i, "AND"); type=ALU; break;
6592           case 0x25: set_mnemonic(i, "OR"); type=ALU; break;
6593           case 0x26: set_mnemonic(i, "XOR"); type=ALU; break;
6594           case 0x27: set_mnemonic(i, "NOR"); type=ALU; break;
6595           case 0x2A: set_mnemonic(i, "SLT"); type=ALU; break;
6596           case 0x2B: set_mnemonic(i, "SLTU"); type=ALU; break;
6597           case 0x30: set_mnemonic(i, "TGE"); type=NI; break;
6598           case 0x31: set_mnemonic(i, "TGEU"); type=NI; break;
6599           case 0x32: set_mnemonic(i, "TLT"); type=NI; break;
6600           case 0x33: set_mnemonic(i, "TLTU"); type=NI; break;
6601           case 0x34: set_mnemonic(i, "TEQ"); type=NI; break;
6602           case 0x36: set_mnemonic(i, "TNE"); type=NI; break;
6603 #if 0
6604           case 0x14: set_mnemonic(i, "DSLLV"); type=SHIFT; break;
6605           case 0x16: set_mnemonic(i, "DSRLV"); type=SHIFT; break;
6606           case 0x17: set_mnemonic(i, "DSRAV"); type=SHIFT; break;
6607           case 0x1C: set_mnemonic(i, "DMULT"); type=MULTDIV; break;
6608           case 0x1D: set_mnemonic(i, "DMULTU"); type=MULTDIV; break;
6609           case 0x1E: set_mnemonic(i, "DDIV"); type=MULTDIV; break;
6610           case 0x1F: set_mnemonic(i, "DDIVU"); type=MULTDIV; break;
6611           case 0x2C: set_mnemonic(i, "DADD"); type=ALU; break;
6612           case 0x2D: set_mnemonic(i, "DADDU"); type=ALU; break;
6613           case 0x2E: set_mnemonic(i, "DSUB"); type=ALU; break;
6614           case 0x2F: set_mnemonic(i, "DSUBU"); type=ALU; break;
6615           case 0x38: set_mnemonic(i, "DSLL"); type=SHIFTIMM; break;
6616           case 0x3A: set_mnemonic(i, "DSRL"); type=SHIFTIMM; break;
6617           case 0x3B: set_mnemonic(i, "DSRA"); type=SHIFTIMM; break;
6618           case 0x3C: set_mnemonic(i, "DSLL32"); type=SHIFTIMM; break;
6619           case 0x3E: set_mnemonic(i, "DSRL32"); type=SHIFTIMM; break;
6620           case 0x3F: set_mnemonic(i, "DSRA32"); type=SHIFTIMM; break;
6621 #endif
6622         }
6623         break;
6624       case 0x01: set_mnemonic(i, "regimm"); type=NI;
6625         op2=(source[i]>>16)&0x1f;
6626         switch(op2)
6627         {
6628           case 0x00: set_mnemonic(i, "BLTZ"); type=SJUMP; break;
6629           case 0x01: set_mnemonic(i, "BGEZ"); type=SJUMP; break;
6630           //case 0x02: set_mnemonic(i, "BLTZL"); type=SJUMP; break;
6631           //case 0x03: set_mnemonic(i, "BGEZL"); type=SJUMP; break;
6632           //case 0x08: set_mnemonic(i, "TGEI"); type=NI; break;
6633           //case 0x09: set_mnemonic(i, "TGEIU"); type=NI; break;
6634           //case 0x0A: set_mnemonic(i, "TLTI"); type=NI; break;
6635           //case 0x0B: set_mnemonic(i, "TLTIU"); type=NI; break;
6636           //case 0x0C: set_mnemonic(i, "TEQI"); type=NI; break;
6637           //case 0x0E: set_mnemonic(i, "TNEI"); type=NI; break;
6638           case 0x10: set_mnemonic(i, "BLTZAL"); type=SJUMP; break;
6639           case 0x11: set_mnemonic(i, "BGEZAL"); type=SJUMP; break;
6640           //case 0x12: set_mnemonic(i, "BLTZALL"); type=SJUMP; break;
6641           //case 0x13: set_mnemonic(i, "BGEZALL"); type=SJUMP; break;
6642         }
6643         break;
6644       case 0x02: set_mnemonic(i, "J"); type=UJUMP; break;
6645       case 0x03: set_mnemonic(i, "JAL"); type=UJUMP; break;
6646       case 0x04: set_mnemonic(i, "BEQ"); type=CJUMP; break;
6647       case 0x05: set_mnemonic(i, "BNE"); type=CJUMP; break;
6648       case 0x06: set_mnemonic(i, "BLEZ"); type=CJUMP; break;
6649       case 0x07: set_mnemonic(i, "BGTZ"); type=CJUMP; break;
6650       case 0x08: set_mnemonic(i, "ADDI"); type=IMM16; break;
6651       case 0x09: set_mnemonic(i, "ADDIU"); type=IMM16; break;
6652       case 0x0A: set_mnemonic(i, "SLTI"); type=IMM16; break;
6653       case 0x0B: set_mnemonic(i, "SLTIU"); type=IMM16; break;
6654       case 0x0C: set_mnemonic(i, "ANDI"); type=IMM16; break;
6655       case 0x0D: set_mnemonic(i, "ORI"); type=IMM16; break;
6656       case 0x0E: set_mnemonic(i, "XORI"); type=IMM16; break;
6657       case 0x0F: set_mnemonic(i, "LUI"); type=IMM16; break;
6658       case 0x10: set_mnemonic(i, "cop0"); type=NI;
6659         op2=(source[i]>>21)&0x1f;
6660         switch(op2)
6661         {
6662           case 0x00: set_mnemonic(i, "MFC0"); type=COP0; break;
6663           case 0x02: set_mnemonic(i, "CFC0"); type=COP0; break;
6664           case 0x04: set_mnemonic(i, "MTC0"); type=COP0; break;
6665           case 0x06: set_mnemonic(i, "CTC0"); type=COP0; break;
6666           case 0x10: set_mnemonic(i, "RFE"); type=COP0; break;
6667         }
6668         break;
6669       case 0x11: set_mnemonic(i, "cop1"); type=COP1;
6670         op2=(source[i]>>21)&0x1f;
6671         break;
6672 #if 0
6673       case 0x14: set_mnemonic(i, "BEQL"); type=CJUMP; break;
6674       case 0x15: set_mnemonic(i, "BNEL"); type=CJUMP; break;
6675       case 0x16: set_mnemonic(i, "BLEZL"); type=CJUMP; break;
6676       case 0x17: set_mnemonic(i, "BGTZL"); type=CJUMP; break;
6677       case 0x18: set_mnemonic(i, "DADDI"); type=IMM16; break;
6678       case 0x19: set_mnemonic(i, "DADDIU"); type=IMM16; break;
6679       case 0x1A: set_mnemonic(i, "LDL"); type=LOADLR; break;
6680       case 0x1B: set_mnemonic(i, "LDR"); type=LOADLR; break;
6681 #endif
6682       case 0x20: set_mnemonic(i, "LB"); type=LOAD; break;
6683       case 0x21: set_mnemonic(i, "LH"); type=LOAD; break;
6684       case 0x22: set_mnemonic(i, "LWL"); type=LOADLR; break;
6685       case 0x23: set_mnemonic(i, "LW"); type=LOAD; break;
6686       case 0x24: set_mnemonic(i, "LBU"); type=LOAD; break;
6687       case 0x25: set_mnemonic(i, "LHU"); type=LOAD; break;
6688       case 0x26: set_mnemonic(i, "LWR"); type=LOADLR; break;
6689 #if 0
6690       case 0x27: set_mnemonic(i, "LWU"); type=LOAD; break;
6691 #endif
6692       case 0x28: set_mnemonic(i, "SB"); type=STORE; break;
6693       case 0x29: set_mnemonic(i, "SH"); type=STORE; break;
6694       case 0x2A: set_mnemonic(i, "SWL"); type=STORELR; break;
6695       case 0x2B: set_mnemonic(i, "SW"); type=STORE; break;
6696 #if 0
6697       case 0x2C: set_mnemonic(i, "SDL"); type=STORELR; break;
6698       case 0x2D: set_mnemonic(i, "SDR"); type=STORELR; break;
6699 #endif
6700       case 0x2E: set_mnemonic(i, "SWR"); type=STORELR; break;
6701       case 0x2F: set_mnemonic(i, "CACHE"); type=NOP; break;
6702       case 0x30: set_mnemonic(i, "LL"); type=NI; break;
6703       case 0x31: set_mnemonic(i, "LWC1"); type=C1LS; break;
6704 #if 0
6705       case 0x34: set_mnemonic(i, "LLD"); type=NI; break;
6706       case 0x35: set_mnemonic(i, "LDC1"); type=C1LS; break;
6707       case 0x37: set_mnemonic(i, "LD"); type=LOAD; break;
6708 #endif
6709       case 0x38: set_mnemonic(i, "SC"); type=NI; break;
6710       case 0x39: set_mnemonic(i, "SWC1"); type=C1LS; break;
6711 #if 0
6712       case 0x3C: set_mnemonic(i, "SCD"); type=NI; break;
6713       case 0x3D: set_mnemonic(i, "SDC1"); type=C1LS; break;
6714       case 0x3F: set_mnemonic(i, "SD"); type=STORE; break;
6715 #endif
6716       case 0x12: set_mnemonic(i, "COP2"); type=NI;
6717         op2=(source[i]>>21)&0x1f;
6718         //if (op2 & 0x10)
6719         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
6720           if (gte_handlers[source[i]&0x3f]!=NULL) {
6721 #ifdef DISASM
6722             if (gte_regnames[source[i]&0x3f]!=NULL)
6723               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
6724             else
6725               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
6726 #endif
6727             type=C2OP;
6728           }
6729         }
6730         else switch(op2)
6731         {
6732           case 0x00: set_mnemonic(i, "MFC2"); type=COP2; break;
6733           case 0x02: set_mnemonic(i, "CFC2"); type=COP2; break;
6734           case 0x04: set_mnemonic(i, "MTC2"); type=COP2; break;
6735           case 0x06: set_mnemonic(i, "CTC2"); type=COP2; break;
6736         }
6737         break;
6738       case 0x32: set_mnemonic(i, "LWC2"); type=C2LS; break;
6739       case 0x3A: set_mnemonic(i, "SWC2"); type=C2LS; break;
6740       case 0x3B: set_mnemonic(i, "HLECALL"); type=HLECALL; break;
6741       default: set_mnemonic(i, "???"); type=NI;
6742         SysPrintf("NI %08x @%08x (%08x)\n", source[i], start + i*4, start);
6743         break;
6744     }
6745     dops[i].itype=type;
6746     dops[i].opcode2=op2;
6747     /* Get registers/immediates */
6748     dops[i].use_lt1=0;
6749     gte_rs[i]=gte_rt[i]=0;
6750     switch(type) {
6751       case LOAD:
6752         dops[i].rs1=(source[i]>>21)&0x1f;
6753         dops[i].rs2=0;
6754         dops[i].rt1=(source[i]>>16)&0x1f;
6755         dops[i].rt2=0;
6756         imm[i]=(short)source[i];
6757         break;
6758       case STORE:
6759       case STORELR:
6760         dops[i].rs1=(source[i]>>21)&0x1f;
6761         dops[i].rs2=(source[i]>>16)&0x1f;
6762         dops[i].rt1=0;
6763         dops[i].rt2=0;
6764         imm[i]=(short)source[i];
6765         break;
6766       case LOADLR:
6767         // LWL/LWR only load part of the register,
6768         // therefore the target register must be treated as a source too
6769         dops[i].rs1=(source[i]>>21)&0x1f;
6770         dops[i].rs2=(source[i]>>16)&0x1f;
6771         dops[i].rt1=(source[i]>>16)&0x1f;
6772         dops[i].rt2=0;
6773         imm[i]=(short)source[i];
6774         break;
6775       case IMM16:
6776         if (op==0x0f) dops[i].rs1=0; // LUI instruction has no source register
6777         else dops[i].rs1=(source[i]>>21)&0x1f;
6778         dops[i].rs2=0;
6779         dops[i].rt1=(source[i]>>16)&0x1f;
6780         dops[i].rt2=0;
6781         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
6782           imm[i]=(unsigned short)source[i];
6783         }else{
6784           imm[i]=(short)source[i];
6785         }
6786         break;
6787       case UJUMP:
6788         dops[i].rs1=0;
6789         dops[i].rs2=0;
6790         dops[i].rt1=0;
6791         dops[i].rt2=0;
6792         // The JAL instruction writes to r31.
6793         if (op&1) {
6794           dops[i].rt1=31;
6795         }
6796         dops[i].rs2=CCREG;
6797         break;
6798       case RJUMP:
6799         dops[i].rs1=(source[i]>>21)&0x1f;
6800         dops[i].rs2=0;
6801         dops[i].rt1=0;
6802         dops[i].rt2=0;
6803         // The JALR instruction writes to rd.
6804         if (op2&1) {
6805           dops[i].rt1=(source[i]>>11)&0x1f;
6806         }
6807         dops[i].rs2=CCREG;
6808         break;
6809       case CJUMP:
6810         dops[i].rs1=(source[i]>>21)&0x1f;
6811         dops[i].rs2=(source[i]>>16)&0x1f;
6812         dops[i].rt1=0;
6813         dops[i].rt2=0;
6814         if(op&2) { // BGTZ/BLEZ
6815           dops[i].rs2=0;
6816         }
6817         break;
6818       case SJUMP:
6819         dops[i].rs1=(source[i]>>21)&0x1f;
6820         dops[i].rs2=CCREG;
6821         dops[i].rt1=0;
6822         dops[i].rt2=0;
6823         if(op2&0x10) { // BxxAL
6824           dops[i].rt1=31;
6825           // NOTE: If the branch is not taken, r31 is still overwritten
6826         }
6827         break;
6828       case ALU:
6829         dops[i].rs1=(source[i]>>21)&0x1f; // source
6830         dops[i].rs2=(source[i]>>16)&0x1f; // subtract amount
6831         dops[i].rt1=(source[i]>>11)&0x1f; // destination
6832         dops[i].rt2=0;
6833         break;
6834       case MULTDIV:
6835         dops[i].rs1=(source[i]>>21)&0x1f; // source
6836         dops[i].rs2=(source[i]>>16)&0x1f; // divisor
6837         dops[i].rt1=HIREG;
6838         dops[i].rt2=LOREG;
6839         break;
6840       case MOV:
6841         dops[i].rs1=0;
6842         dops[i].rs2=0;
6843         dops[i].rt1=0;
6844         dops[i].rt2=0;
6845         if(op2==0x10) dops[i].rs1=HIREG; // MFHI
6846         if(op2==0x11) dops[i].rt1=HIREG; // MTHI
6847         if(op2==0x12) dops[i].rs1=LOREG; // MFLO
6848         if(op2==0x13) dops[i].rt1=LOREG; // MTLO
6849         if((op2&0x1d)==0x10) dops[i].rt1=(source[i]>>11)&0x1f; // MFxx
6850         if((op2&0x1d)==0x11) dops[i].rs1=(source[i]>>21)&0x1f; // MTxx
6851         break;
6852       case SHIFT:
6853         dops[i].rs1=(source[i]>>16)&0x1f; // target of shift
6854         dops[i].rs2=(source[i]>>21)&0x1f; // shift amount
6855         dops[i].rt1=(source[i]>>11)&0x1f; // destination
6856         dops[i].rt2=0;
6857         break;
6858       case SHIFTIMM:
6859         dops[i].rs1=(source[i]>>16)&0x1f;
6860         dops[i].rs2=0;
6861         dops[i].rt1=(source[i]>>11)&0x1f;
6862         dops[i].rt2=0;
6863         imm[i]=(source[i]>>6)&0x1f;
6864         // DSxx32 instructions
6865         if(op2>=0x3c) imm[i]|=0x20;
6866         break;
6867       case COP0:
6868         dops[i].rs1=0;
6869         dops[i].rs2=0;
6870         dops[i].rt1=0;
6871         dops[i].rt2=0;
6872         if(op2==0||op2==2) dops[i].rt1=(source[i]>>16)&0x1F; // MFC0/CFC0
6873         if(op2==4||op2==6) dops[i].rs1=(source[i]>>16)&0x1F; // MTC0/CTC0
6874         if(op2==4&&((source[i]>>11)&0x1f)==12) dops[i].rt2=CSREG; // Status
6875         if(op2==16) if((source[i]&0x3f)==0x18) dops[i].rs2=CCREG; // ERET
6876         break;
6877       case COP1:
6878         dops[i].rs1=0;
6879         dops[i].rs2=0;
6880         dops[i].rt1=0;
6881         dops[i].rt2=0;
6882         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
6883         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
6884         dops[i].rs2=CSREG;
6885         break;
6886       case COP2:
6887         dops[i].rs1=0;
6888         dops[i].rs2=0;
6889         dops[i].rt1=0;
6890         dops[i].rt2=0;
6891         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC2/CFC2
6892         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC2/CTC2
6893         dops[i].rs2=CSREG;
6894         int gr=(source[i]>>11)&0x1F;
6895         switch(op2)
6896         {
6897           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
6898           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
6899           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
6900           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
6901         }
6902         break;
6903       case C1LS:
6904         dops[i].rs1=(source[i]>>21)&0x1F;
6905         dops[i].rs2=CSREG;
6906         dops[i].rt1=0;
6907         dops[i].rt2=0;
6908         imm[i]=(short)source[i];
6909         break;
6910       case C2LS:
6911         dops[i].rs1=(source[i]>>21)&0x1F;
6912         dops[i].rs2=0;
6913         dops[i].rt1=0;
6914         dops[i].rt2=0;
6915         imm[i]=(short)source[i];
6916         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
6917         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
6918         break;
6919       case C2OP:
6920         dops[i].rs1=0;
6921         dops[i].rs2=0;
6922         dops[i].rt1=0;
6923         dops[i].rt2=0;
6924         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
6925         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
6926         gte_rt[i]|=1ll<<63; // every op changes flags
6927         if((source[i]&0x3f)==GTE_MVMVA) {
6928           int v = (source[i] >> 15) & 3;
6929           gte_rs[i]&=~0xe3fll;
6930           if(v==3) gte_rs[i]|=0xe00ll;
6931           else gte_rs[i]|=3ll<<(v*2);
6932         }
6933         break;
6934       case SYSCALL:
6935       case HLECALL:
6936       case INTCALL:
6937         dops[i].rs1=CCREG;
6938         dops[i].rs2=0;
6939         dops[i].rt1=0;
6940         dops[i].rt2=0;
6941         break;
6942       default:
6943         dops[i].rs1=0;
6944         dops[i].rs2=0;
6945         dops[i].rt1=0;
6946         dops[i].rt2=0;
6947     }
6948     /* Calculate branch target addresses */
6949     if(type==UJUMP)
6950       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
6951     else if(type==CJUMP&&dops[i].rs1==dops[i].rs2&&(op&1))
6952       ba[i]=start+i*4+8; // Ignore never taken branch
6953     else if(type==SJUMP&&dops[i].rs1==0&&!(op2&1))
6954       ba[i]=start+i*4+8; // Ignore never taken branch
6955     else if(type==CJUMP||type==SJUMP)
6956       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
6957     else ba[i]=-1;
6958
6959     /* simplify always (not)taken branches */
6960     if (type == CJUMP && dops[i].rs1 == dops[i].rs2) {
6961       dops[i].rs1 = dops[i].rs2 = 0;
6962       if (!(op & 1)) {
6963         dops[i].itype = type = UJUMP;
6964         dops[i].rs2 = CCREG;
6965       }
6966     }
6967     else if (type == SJUMP && dops[i].rs1 == 0 && (op2 & 1))
6968       dops[i].itype = type = UJUMP;
6969
6970     dops[i].is_jump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP || dops[i].itype == CJUMP || dops[i].itype == SJUMP);
6971     dops[i].is_ujump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP); // || (source[i] >> 16) == 0x1000 // beq r0,r0
6972     dops[i].is_load = (dops[i].itype == LOAD || dops[i].itype == LOADLR || op == 0x32); // LWC2
6973     dops[i].is_store = (dops[i].itype == STORE || dops[i].itype == STORELR || op == 0x3a); // SWC2
6974
6975     /* messy cases to just pass over to the interpreter */
6976     if (i > 0 && dops[i-1].is_jump) {
6977       int do_in_intrp=0;
6978       // branch in delay slot?
6979       if (dops[i].is_jump) {
6980         // don't handle first branch and call interpreter if it's hit
6981         SysPrintf("branch in delay slot @%08x (%08x)\n", start + i*4, start);
6982         do_in_intrp=1;
6983       }
6984       // basic load delay detection
6985       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&dops[i].rt1!=0) {
6986         int t=(ba[i-1]-start)/4;
6987         if(0 <= t && t < i &&(dops[i].rt1==dops[t].rs1||dops[i].rt1==dops[t].rs2)&&dops[t].itype!=CJUMP&&dops[t].itype!=SJUMP) {
6988           // jump target wants DS result - potential load delay effect
6989           SysPrintf("load delay @%08x (%08x)\n", start + i*4, start);
6990           do_in_intrp=1;
6991           dops[t+1].bt=1; // expected return from interpreter
6992         }
6993         else if(i>=2&&dops[i-2].rt1==2&&dops[i].rt1==2&&dops[i].rs1!=2&&dops[i].rs2!=2&&dops[i-1].rs1!=2&&dops[i-1].rs2!=2&&
6994               !(i>=3&&dops[i-3].is_jump)) {
6995           // v0 overwrite like this is a sign of trouble, bail out
6996           SysPrintf("v0 overwrite @%08x (%08x)\n", start + i*4, start);
6997           do_in_intrp=1;
6998         }
6999       }
7000       if (do_in_intrp) {
7001         memset(&dops[i-1], 0, sizeof(dops[i-1]));
7002         dops[i-1].itype = INTCALL;
7003         dops[i-1].rs1 = CCREG;
7004         ba[i-1] = -1;
7005         done = 2;
7006         i--; // don't compile the DS
7007       }
7008     }
7009
7010     /* Is this the end of the block? */
7011     if (i > 0 && dops[i-1].is_ujump) {
7012       if (dops[i-1].rt1 == 0) { // not jal
7013         int found_bbranch = 0, t = (ba[i-1] - start) / 4;
7014         if ((u_int)(t - i) < 64 && start + (t+64)*4 < pagelimit) {
7015           // scan for a branch back to i+1
7016           for (j = t; j < t + 64; j++) {
7017             int tmpop = source[j] >> 26;
7018             if (tmpop == 1 || ((tmpop & ~3) == 4)) {
7019               int t2 = j + 1 + (int)(signed short)source[j];
7020               if (t2 == i + 1) {
7021                 //printf("blk expand %08x<-%08x\n", start + (i+1)*4, start + j*4);
7022                 found_bbranch = 1;
7023                 break;
7024               }
7025             }
7026           }
7027         }
7028         if (!found_bbranch)
7029           done = 2;
7030       }
7031       else {
7032         if(stop_after_jal) done=1;
7033         // Stop on BREAK
7034         if((source[i+1]&0xfc00003f)==0x0d) done=1;
7035       }
7036       // Don't recompile stuff that's already compiled
7037       if(check_addr(start+i*4+4)) done=1;
7038       // Don't get too close to the limit
7039       if(i>MAXBLOCK/2) done=1;
7040     }
7041     if (dops[i].itype == SYSCALL || dops[i].itype == HLECALL || dops[i].itype == INTCALL)
7042       done = stop_after_jal ? 1 : 2;
7043     if (done == 2) {
7044       // Does the block continue due to a branch?
7045       for(j=i-1;j>=0;j--)
7046       {
7047         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
7048         if(ba[j]==start+i*4+4) done=j=0;
7049         if(ba[j]==start+i*4+8) done=j=0;
7050       }
7051     }
7052     //assert(i<MAXBLOCK-1);
7053     if(start+i*4==pagelimit-4) done=1;
7054     assert(start+i*4<pagelimit);
7055     if (i==MAXBLOCK-1) done=1;
7056     // Stop if we're compiling junk
7057     if(dops[i].itype == NI && (++ni_count > 8 || dops[i].opcode == 0x11)) {
7058       done=stop_after_jal=1;
7059       SysPrintf("Disabled speculative precompilation\n");
7060     }
7061   }
7062   while (i > 0 && dops[i-1].is_jump)
7063     i--;
7064   assert(i > 0);
7065   assert(!dops[i-1].is_jump);
7066   slen = i;
7067 }
7068
7069 // Basic liveness analysis for MIPS registers
7070 static noinline void pass2_unneeded_regs(int istart,int iend,int r)
7071 {
7072   int i;
7073   uint64_t u,gte_u,b,gte_b;
7074   uint64_t temp_u,temp_gte_u=0;
7075   uint64_t gte_u_unknown=0;
7076   if (HACK_ENABLED(NDHACK_GTE_UNNEEDED))
7077     gte_u_unknown=~0ll;
7078   if(iend==slen-1) {
7079     u=1;
7080     gte_u=gte_u_unknown;
7081   }else{
7082     //u=unneeded_reg[iend+1];
7083     u=1;
7084     gte_u=gte_unneeded[iend+1];
7085   }
7086
7087   for (i=iend;i>=istart;i--)
7088   {
7089     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
7090     if(dops[i].is_jump)
7091     {
7092       // If subroutine call, flag return address as a possible branch target
7093       if(dops[i].rt1==31 && i<slen-2) dops[i+2].bt=1;
7094
7095       if(ba[i]<start || ba[i]>=(start+slen*4))
7096       {
7097         // Branch out of this block, flush all regs
7098         u=1;
7099         gte_u=gte_u_unknown;
7100         branch_unneeded_reg[i]=u;
7101         // Merge in delay slot
7102         u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7103         u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7104         u|=1;
7105         gte_u|=gte_rt[i+1];
7106         gte_u&=~gte_rs[i+1];
7107       }
7108       else
7109       {
7110         // Internal branch, flag target
7111         dops[(ba[i]-start)>>2].bt=1;
7112         if(ba[i]<=start+i*4) {
7113           // Backward branch
7114           if(dops[i].is_ujump)
7115           {
7116             // Unconditional branch
7117             temp_u=1;
7118             temp_gte_u=0;
7119           } else {
7120             // Conditional branch (not taken case)
7121             temp_u=unneeded_reg[i+2];
7122             temp_gte_u&=gte_unneeded[i+2];
7123           }
7124           // Merge in delay slot
7125           temp_u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7126           temp_u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7127           temp_u|=1;
7128           temp_gte_u|=gte_rt[i+1];
7129           temp_gte_u&=~gte_rs[i+1];
7130           temp_u|=(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2);
7131           temp_u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7132           temp_u|=1;
7133           temp_gte_u|=gte_rt[i];
7134           temp_gte_u&=~gte_rs[i];
7135           unneeded_reg[i]=temp_u;
7136           gte_unneeded[i]=temp_gte_u;
7137           // Only go three levels deep.  This recursion can take an
7138           // excessive amount of time if there are a lot of nested loops.
7139           if(r<2) {
7140             pass2_unneeded_regs((ba[i]-start)>>2,i-1,r+1);
7141           }else{
7142             unneeded_reg[(ba[i]-start)>>2]=1;
7143             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
7144           }
7145         } /*else*/ if(1) {
7146           if (dops[i].is_ujump)
7147           {
7148             // Unconditional branch
7149             u=unneeded_reg[(ba[i]-start)>>2];
7150             gte_u=gte_unneeded[(ba[i]-start)>>2];
7151             branch_unneeded_reg[i]=u;
7152             // Merge in delay slot
7153             u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7154             u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7155             u|=1;
7156             gte_u|=gte_rt[i+1];
7157             gte_u&=~gte_rs[i+1];
7158           } else {
7159             // Conditional branch
7160             b=unneeded_reg[(ba[i]-start)>>2];
7161             gte_b=gte_unneeded[(ba[i]-start)>>2];
7162             branch_unneeded_reg[i]=b;
7163             // Branch delay slot
7164             b|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7165             b&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7166             b|=1;
7167             gte_b|=gte_rt[i+1];
7168             gte_b&=~gte_rs[i+1];
7169             u&=b;
7170             gte_u&=gte_b;
7171             if(i<slen-1) {
7172               branch_unneeded_reg[i]&=unneeded_reg[i+2];
7173             } else {
7174               branch_unneeded_reg[i]=1;
7175             }
7176           }
7177         }
7178       }
7179     }
7180     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
7181     {
7182       // SYSCALL instruction (software interrupt)
7183       u=1;
7184     }
7185     else if(dops[i].itype==COP0 && dops[i].opcode2==0x10)
7186     {
7187       // RFE
7188       u=1;
7189     }
7190     //u=1; // DEBUG
7191     // Written registers are unneeded
7192     u|=1LL<<dops[i].rt1;
7193     u|=1LL<<dops[i].rt2;
7194     gte_u|=gte_rt[i];
7195     // Accessed registers are needed
7196     u&=~(1LL<<dops[i].rs1);
7197     u&=~(1LL<<dops[i].rs2);
7198     gte_u&=~gte_rs[i];
7199     if(gte_rs[i]&&dops[i].rt1&&(unneeded_reg[i+1]&(1ll<<dops[i].rt1)))
7200       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
7201     // Source-target dependencies
7202     // R0 is always unneeded
7203     u|=1;
7204     // Save it
7205     unneeded_reg[i]=u;
7206     gte_unneeded[i]=gte_u;
7207     /*
7208     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
7209     printf("U:");
7210     int r;
7211     for(r=1;r<=CCREG;r++) {
7212       if((unneeded_reg[i]>>r)&1) {
7213         if(r==HIREG) printf(" HI");
7214         else if(r==LOREG) printf(" LO");
7215         else printf(" r%d",r);
7216       }
7217     }
7218     printf("\n");
7219     */
7220   }
7221 }
7222
7223 static noinline void pass3_register_alloc(u_int addr)
7224 {
7225   struct regstat current; // Current register allocations/status
7226   clear_all_regs(current.regmap_entry);
7227   clear_all_regs(current.regmap);
7228   current.wasdirty = current.dirty = 0;
7229   current.u = unneeded_reg[0];
7230   alloc_reg(&current, 0, CCREG);
7231   dirty_reg(&current, CCREG);
7232   current.wasconst = 0;
7233   current.isconst = 0;
7234   current.loadedconst = 0;
7235   //current.waswritten = 0;
7236   int ds=0;
7237   int cc=0;
7238   int hr;
7239   int i, j;
7240
7241   if (addr & 1) {
7242     // First instruction is delay slot
7243     cc=-1;
7244     dops[1].bt=1;
7245     ds=1;
7246     unneeded_reg[0]=1;
7247     current.regmap[HOST_BTREG]=BTREG;
7248   }
7249
7250   for(i=0;i<slen;i++)
7251   {
7252     if(dops[i].bt)
7253     {
7254       for(hr=0;hr<HOST_REGS;hr++)
7255       {
7256         // Is this really necessary?
7257         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7258       }
7259       current.isconst=0;
7260       //current.waswritten=0;
7261     }
7262
7263     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7264     regs[i].wasconst=current.isconst;
7265     regs[i].wasdirty=current.dirty;
7266     regs[i].dirty=0;
7267     regs[i].u=0;
7268     regs[i].isconst=0;
7269     regs[i].loadedconst=0;
7270     if (!dops[i].is_jump) {
7271       if(i+1<slen) {
7272         current.u=unneeded_reg[i+1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7273         current.u|=1;
7274       } else {
7275         current.u=1;
7276       }
7277     } else {
7278       if(i+1<slen) {
7279         current.u=branch_unneeded_reg[i]&~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7280         current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7281         current.u|=1;
7282       } else {
7283         SysPrintf("oops, branch at end of block with no delay slot @%08x\n", start + i*4);
7284         abort();
7285       }
7286     }
7287     dops[i].is_ds=ds;
7288     if(ds) {
7289       ds=0; // Skip delay slot, already allocated as part of branch
7290       // ...but we need to alloc it in case something jumps here
7291       if(i+1<slen) {
7292         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7293       }else{
7294         current.u=branch_unneeded_reg[i-1];
7295       }
7296       current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7297       current.u|=1;
7298       struct regstat temp;
7299       memcpy(&temp,&current,sizeof(current));
7300       temp.wasdirty=temp.dirty;
7301       // TODO: Take into account unconditional branches, as below
7302       delayslot_alloc(&temp,i);
7303       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7304       regs[i].wasdirty=temp.wasdirty;
7305       regs[i].dirty=temp.dirty;
7306       regs[i].isconst=0;
7307       regs[i].wasconst=0;
7308       current.isconst=0;
7309       // Create entry (branch target) regmap
7310       for(hr=0;hr<HOST_REGS;hr++)
7311       {
7312         int r=temp.regmap[hr];
7313         if(r>=0) {
7314           if(r!=regmap_pre[i][hr]) {
7315             regs[i].regmap_entry[hr]=-1;
7316           }
7317           else
7318           {
7319               assert(r < 64);
7320               if((current.u>>r)&1) {
7321                 regs[i].regmap_entry[hr]=-1;
7322                 regs[i].regmap[hr]=-1;
7323                 //Don't clear regs in the delay slot as the branch might need them
7324                 //current.regmap[hr]=-1;
7325               }else
7326                 regs[i].regmap_entry[hr]=r;
7327           }
7328         } else {
7329           // First instruction expects CCREG to be allocated
7330           if(i==0&&hr==HOST_CCREG)
7331             regs[i].regmap_entry[hr]=CCREG;
7332           else
7333             regs[i].regmap_entry[hr]=-1;
7334         }
7335       }
7336     }
7337     else { // Not delay slot
7338       switch(dops[i].itype) {
7339         case UJUMP:
7340           //current.isconst=0; // DEBUG
7341           //current.wasconst=0; // DEBUG
7342           //regs[i].wasconst=0; // DEBUG
7343           clear_const(&current,dops[i].rt1);
7344           alloc_cc(&current,i);
7345           dirty_reg(&current,CCREG);
7346           if (dops[i].rt1==31) {
7347             alloc_reg(&current,i,31);
7348             dirty_reg(&current,31);
7349             //assert(dops[i+1].rs1!=31&&dops[i+1].rs2!=31);
7350             //assert(dops[i+1].rt1!=dops[i].rt1);
7351             #ifdef REG_PREFETCH
7352             alloc_reg(&current,i,PTEMP);
7353             #endif
7354           }
7355           dops[i].ooo=1;
7356           delayslot_alloc(&current,i+1);
7357           //current.isconst=0; // DEBUG
7358           ds=1;
7359           //printf("i=%d, isconst=%x\n",i,current.isconst);
7360           break;
7361         case RJUMP:
7362           //current.isconst=0;
7363           //current.wasconst=0;
7364           //regs[i].wasconst=0;
7365           clear_const(&current,dops[i].rs1);
7366           clear_const(&current,dops[i].rt1);
7367           alloc_cc(&current,i);
7368           dirty_reg(&current,CCREG);
7369           if (!ds_writes_rjump_rs(i)) {
7370             alloc_reg(&current,i,dops[i].rs1);
7371             if (dops[i].rt1!=0) {
7372               alloc_reg(&current,i,dops[i].rt1);
7373               dirty_reg(&current,dops[i].rt1);
7374               assert(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt1);
7375               assert(dops[i+1].rt1!=dops[i].rt1);
7376               #ifdef REG_PREFETCH
7377               alloc_reg(&current,i,PTEMP);
7378               #endif
7379             }
7380             #ifdef USE_MINI_HT
7381             if(dops[i].rs1==31) { // JALR
7382               alloc_reg(&current,i,RHASH);
7383               alloc_reg(&current,i,RHTBL);
7384             }
7385             #endif
7386             delayslot_alloc(&current,i+1);
7387           } else {
7388             // The delay slot overwrites our source register,
7389             // allocate a temporary register to hold the old value.
7390             current.isconst=0;
7391             current.wasconst=0;
7392             regs[i].wasconst=0;
7393             delayslot_alloc(&current,i+1);
7394             current.isconst=0;
7395             alloc_reg(&current,i,RTEMP);
7396           }
7397           //current.isconst=0; // DEBUG
7398           dops[i].ooo=1;
7399           ds=1;
7400           break;
7401         case CJUMP:
7402           //current.isconst=0;
7403           //current.wasconst=0;
7404           //regs[i].wasconst=0;
7405           clear_const(&current,dops[i].rs1);
7406           clear_const(&current,dops[i].rs2);
7407           if((dops[i].opcode&0x3E)==4) // BEQ/BNE
7408           {
7409             alloc_cc(&current,i);
7410             dirty_reg(&current,CCREG);
7411             if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7412             if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7413             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2))||
7414                (dops[i].rs2&&(dops[i].rs2==dops[i+1].rt1||dops[i].rs2==dops[i+1].rt2))) {
7415               // The delay slot overwrites one of our conditions.
7416               // Allocate the branch condition registers instead.
7417               current.isconst=0;
7418               current.wasconst=0;
7419               regs[i].wasconst=0;
7420               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7421               if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7422             }
7423             else
7424             {
7425               dops[i].ooo=1;
7426               delayslot_alloc(&current,i+1);
7427             }
7428           }
7429           else
7430           if((dops[i].opcode&0x3E)==6) // BLEZ/BGTZ
7431           {
7432             alloc_cc(&current,i);
7433             dirty_reg(&current,CCREG);
7434             alloc_reg(&current,i,dops[i].rs1);
7435             if(dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) {
7436               // The delay slot overwrites one of our conditions.
7437               // Allocate the branch condition registers instead.
7438               current.isconst=0;
7439               current.wasconst=0;
7440               regs[i].wasconst=0;
7441               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7442             }
7443             else
7444             {
7445               dops[i].ooo=1;
7446               delayslot_alloc(&current,i+1);
7447             }
7448           }
7449           else
7450           // Don't alloc the delay slot yet because we might not execute it
7451           if((dops[i].opcode&0x3E)==0x14) // BEQL/BNEL
7452           {
7453             current.isconst=0;
7454             current.wasconst=0;
7455             regs[i].wasconst=0;
7456             alloc_cc(&current,i);
7457             dirty_reg(&current,CCREG);
7458             alloc_reg(&current,i,dops[i].rs1);
7459             alloc_reg(&current,i,dops[i].rs2);
7460           }
7461           else
7462           if((dops[i].opcode&0x3E)==0x16) // BLEZL/BGTZL
7463           {
7464             current.isconst=0;
7465             current.wasconst=0;
7466             regs[i].wasconst=0;
7467             alloc_cc(&current,i);
7468             dirty_reg(&current,CCREG);
7469             alloc_reg(&current,i,dops[i].rs1);
7470           }
7471           ds=1;
7472           //current.isconst=0;
7473           break;
7474         case SJUMP:
7475           //current.isconst=0;
7476           //current.wasconst=0;
7477           //regs[i].wasconst=0;
7478           clear_const(&current,dops[i].rs1);
7479           clear_const(&current,dops[i].rt1);
7480           //if((dops[i].opcode2&0x1E)==0x0) // BLTZ/BGEZ
7481           if((dops[i].opcode2&0x0E)==0x0) // BLTZ/BGEZ
7482           {
7483             alloc_cc(&current,i);
7484             dirty_reg(&current,CCREG);
7485             alloc_reg(&current,i,dops[i].rs1);
7486             if (dops[i].rt1==31) { // BLTZAL/BGEZAL
7487               alloc_reg(&current,i,31);
7488               dirty_reg(&current,31);
7489               //#ifdef REG_PREFETCH
7490               //alloc_reg(&current,i,PTEMP);
7491               //#endif
7492             }
7493             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) // The delay slot overwrites the branch condition.
7494                ||(dops[i].rt1==31&&(dops[i+1].rs1==31||dops[i+1].rs2==31||dops[i+1].rt1==31||dops[i+1].rt2==31))) { // DS touches $ra
7495               // Allocate the branch condition registers instead.
7496               current.isconst=0;
7497               current.wasconst=0;
7498               regs[i].wasconst=0;
7499               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7500             }
7501             else
7502             {
7503               dops[i].ooo=1;
7504               delayslot_alloc(&current,i+1);
7505             }
7506           }
7507           else
7508           // Don't alloc the delay slot yet because we might not execute it
7509           if((dops[i].opcode2&0x1E)==0x2) // BLTZL/BGEZL
7510           {
7511             current.isconst=0;
7512             current.wasconst=0;
7513             regs[i].wasconst=0;
7514             alloc_cc(&current,i);
7515             dirty_reg(&current,CCREG);
7516             alloc_reg(&current,i,dops[i].rs1);
7517           }
7518           ds=1;
7519           //current.isconst=0;
7520           break;
7521         case IMM16:
7522           imm16_alloc(&current,i);
7523           break;
7524         case LOAD:
7525         case LOADLR:
7526           load_alloc(&current,i);
7527           break;
7528         case STORE:
7529         case STORELR:
7530           store_alloc(&current,i);
7531           break;
7532         case ALU:
7533           alu_alloc(&current,i);
7534           break;
7535         case SHIFT:
7536           shift_alloc(&current,i);
7537           break;
7538         case MULTDIV:
7539           multdiv_alloc(&current,i);
7540           break;
7541         case SHIFTIMM:
7542           shiftimm_alloc(&current,i);
7543           break;
7544         case MOV:
7545           mov_alloc(&current,i);
7546           break;
7547         case COP0:
7548           cop0_alloc(&current,i);
7549           break;
7550         case COP1:
7551           break;
7552         case COP2:
7553           cop2_alloc(&current,i);
7554           break;
7555         case C1LS:
7556           c1ls_alloc(&current,i);
7557           break;
7558         case C2LS:
7559           c2ls_alloc(&current,i);
7560           break;
7561         case C2OP:
7562           c2op_alloc(&current,i);
7563           break;
7564         case SYSCALL:
7565         case HLECALL:
7566         case INTCALL:
7567           syscall_alloc(&current,i);
7568           break;
7569       }
7570
7571       // Create entry (branch target) regmap
7572       for(hr=0;hr<HOST_REGS;hr++)
7573       {
7574         int r,or;
7575         r=current.regmap[hr];
7576         if(r>=0) {
7577           if(r!=regmap_pre[i][hr]) {
7578             // TODO: delay slot (?)
7579             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
7580             if(or<0||r>=TEMPREG){
7581               regs[i].regmap_entry[hr]=-1;
7582             }
7583             else
7584             {
7585               // Just move it to a different register
7586               regs[i].regmap_entry[hr]=r;
7587               // If it was dirty before, it's still dirty
7588               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r);
7589             }
7590           }
7591           else
7592           {
7593             // Unneeded
7594             if(r==0){
7595               regs[i].regmap_entry[hr]=0;
7596             }
7597             else
7598             {
7599               assert(r<64);
7600               if((current.u>>r)&1) {
7601                 regs[i].regmap_entry[hr]=-1;
7602                 //regs[i].regmap[hr]=-1;
7603                 current.regmap[hr]=-1;
7604               }else
7605                 regs[i].regmap_entry[hr]=r;
7606             }
7607           }
7608         } else {
7609           // Branches expect CCREG to be allocated at the target
7610           if(regmap_pre[i][hr]==CCREG)
7611             regs[i].regmap_entry[hr]=CCREG;
7612           else
7613             regs[i].regmap_entry[hr]=-1;
7614         }
7615       }
7616       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
7617     }
7618
7619 #if 0 // see do_store_smc_check()
7620     if(i>0&&(dops[i-1].itype==STORE||dops[i-1].itype==STORELR||(dops[i-1].itype==C2LS&&dops[i-1].opcode==0x3a))&&(u_int)imm[i-1]<0x800)
7621       current.waswritten|=1<<dops[i-1].rs1;
7622     current.waswritten&=~(1<<dops[i].rt1);
7623     current.waswritten&=~(1<<dops[i].rt2);
7624     if((dops[i].itype==STORE||dops[i].itype==STORELR||(dops[i].itype==C2LS&&dops[i].opcode==0x3a))&&(u_int)imm[i]>=0x800)
7625       current.waswritten&=~(1<<dops[i].rs1);
7626 #endif
7627
7628     /* Branch post-alloc */
7629     if(i>0)
7630     {
7631       current.wasdirty=current.dirty;
7632       switch(dops[i-1].itype) {
7633         case UJUMP:
7634           memcpy(&branch_regs[i-1],&current,sizeof(current));
7635           branch_regs[i-1].isconst=0;
7636           branch_regs[i-1].wasconst=0;
7637           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7638           alloc_cc(&branch_regs[i-1],i-1);
7639           dirty_reg(&branch_regs[i-1],CCREG);
7640           if(dops[i-1].rt1==31) { // JAL
7641             alloc_reg(&branch_regs[i-1],i-1,31);
7642             dirty_reg(&branch_regs[i-1],31);
7643           }
7644           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7645           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7646           break;
7647         case RJUMP:
7648           memcpy(&branch_regs[i-1],&current,sizeof(current));
7649           branch_regs[i-1].isconst=0;
7650           branch_regs[i-1].wasconst=0;
7651           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7652           alloc_cc(&branch_regs[i-1],i-1);
7653           dirty_reg(&branch_regs[i-1],CCREG);
7654           alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rs1);
7655           if(dops[i-1].rt1!=0) { // JALR
7656             alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rt1);
7657             dirty_reg(&branch_regs[i-1],dops[i-1].rt1);
7658           }
7659           #ifdef USE_MINI_HT
7660           if(dops[i-1].rs1==31) { // JALR
7661             alloc_reg(&branch_regs[i-1],i-1,RHASH);
7662             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
7663           }
7664           #endif
7665           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7666           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7667           break;
7668         case CJUMP:
7669           if((dops[i-1].opcode&0x3E)==4) // BEQ/BNE
7670           {
7671             alloc_cc(&current,i-1);
7672             dirty_reg(&current,CCREG);
7673             if((dops[i-1].rs1&&(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2))||
7674                (dops[i-1].rs2&&(dops[i-1].rs2==dops[i].rt1||dops[i-1].rs2==dops[i].rt2))) {
7675               // The delay slot overwrote one of our conditions
7676               // Delay slot goes after the test (in order)
7677               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7678               current.u|=1;
7679               delayslot_alloc(&current,i);
7680               current.isconst=0;
7681             }
7682             else
7683             {
7684               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7685               // Alloc the branch condition registers
7686               if(dops[i-1].rs1) alloc_reg(&current,i-1,dops[i-1].rs1);
7687               if(dops[i-1].rs2) alloc_reg(&current,i-1,dops[i-1].rs2);
7688             }
7689             memcpy(&branch_regs[i-1],&current,sizeof(current));
7690             branch_regs[i-1].isconst=0;
7691             branch_regs[i-1].wasconst=0;
7692             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7693             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7694           }
7695           else
7696           if((dops[i-1].opcode&0x3E)==6) // BLEZ/BGTZ
7697           {
7698             alloc_cc(&current,i-1);
7699             dirty_reg(&current,CCREG);
7700             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
7701               // The delay slot overwrote the branch condition
7702               // Delay slot goes after the test (in order)
7703               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7704               current.u|=1;
7705               delayslot_alloc(&current,i);
7706               current.isconst=0;
7707             }
7708             else
7709             {
7710               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
7711               // Alloc the branch condition register
7712               alloc_reg(&current,i-1,dops[i-1].rs1);
7713             }
7714             memcpy(&branch_regs[i-1],&current,sizeof(current));
7715             branch_regs[i-1].isconst=0;
7716             branch_regs[i-1].wasconst=0;
7717             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7718             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7719           }
7720           else
7721           // Alloc the delay slot in case the branch is taken
7722           if((dops[i-1].opcode&0x3E)==0x14) // BEQL/BNEL
7723           {
7724             memcpy(&branch_regs[i-1],&current,sizeof(current));
7725             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
7726             alloc_cc(&branch_regs[i-1],i);
7727             dirty_reg(&branch_regs[i-1],CCREG);
7728             delayslot_alloc(&branch_regs[i-1],i);
7729             branch_regs[i-1].isconst=0;
7730             alloc_reg(&current,i,CCREG); // Not taken path
7731             dirty_reg(&current,CCREG);
7732             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7733           }
7734           else
7735           if((dops[i-1].opcode&0x3E)==0x16) // BLEZL/BGTZL
7736           {
7737             memcpy(&branch_regs[i-1],&current,sizeof(current));
7738             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
7739             alloc_cc(&branch_regs[i-1],i);
7740             dirty_reg(&branch_regs[i-1],CCREG);
7741             delayslot_alloc(&branch_regs[i-1],i);
7742             branch_regs[i-1].isconst=0;
7743             alloc_reg(&current,i,CCREG); // Not taken path
7744             dirty_reg(&current,CCREG);
7745             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7746           }
7747           break;
7748         case SJUMP:
7749           //if((dops[i-1].opcode2&0x1E)==0) // BLTZ/BGEZ
7750           if((dops[i-1].opcode2&0x0E)==0) // BLTZ/BGEZ
7751           {
7752             alloc_cc(&current,i-1);
7753             dirty_reg(&current,CCREG);
7754             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
7755               // The delay slot overwrote the branch condition
7756               // Delay slot goes after the test (in order)
7757               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7758               current.u|=1;
7759               delayslot_alloc(&current,i);
7760               current.isconst=0;
7761             }
7762             else
7763             {
7764               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
7765               // Alloc the branch condition register
7766               alloc_reg(&current,i-1,dops[i-1].rs1);
7767             }
7768             memcpy(&branch_regs[i-1],&current,sizeof(current));
7769             branch_regs[i-1].isconst=0;
7770             branch_regs[i-1].wasconst=0;
7771             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7772             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7773           }
7774           else
7775           // Alloc the delay slot in case the branch is taken
7776           if((dops[i-1].opcode2&0x1E)==2) // BLTZL/BGEZL
7777           {
7778             memcpy(&branch_regs[i-1],&current,sizeof(current));
7779             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
7780             alloc_cc(&branch_regs[i-1],i);
7781             dirty_reg(&branch_regs[i-1],CCREG);
7782             delayslot_alloc(&branch_regs[i-1],i);
7783             branch_regs[i-1].isconst=0;
7784             alloc_reg(&current,i,CCREG); // Not taken path
7785             dirty_reg(&current,CCREG);
7786             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7787           }
7788           // FIXME: BLTZAL/BGEZAL
7789           if(dops[i-1].opcode2&0x10) { // BxxZAL
7790             alloc_reg(&branch_regs[i-1],i-1,31);
7791             dirty_reg(&branch_regs[i-1],31);
7792           }
7793           break;
7794       }
7795
7796       if (dops[i-1].is_ujump)
7797       {
7798         if(dops[i-1].rt1==31) // JAL/JALR
7799         {
7800           // Subroutine call will return here, don't alloc any registers
7801           current.dirty=0;
7802           clear_all_regs(current.regmap);
7803           alloc_reg(&current,i,CCREG);
7804           dirty_reg(&current,CCREG);
7805         }
7806         else if(i+1<slen)
7807         {
7808           // Internal branch will jump here, match registers to caller
7809           current.dirty=0;
7810           clear_all_regs(current.regmap);
7811           alloc_reg(&current,i,CCREG);
7812           dirty_reg(&current,CCREG);
7813           for(j=i-1;j>=0;j--)
7814           {
7815             if(ba[j]==start+i*4+4) {
7816               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
7817               current.dirty=branch_regs[j].dirty;
7818               break;
7819             }
7820           }
7821           while(j>=0) {
7822             if(ba[j]==start+i*4+4) {
7823               for(hr=0;hr<HOST_REGS;hr++) {
7824                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
7825                   current.regmap[hr]=-1;
7826                 }
7827                 current.dirty&=branch_regs[j].dirty;
7828               }
7829             }
7830             j--;
7831           }
7832         }
7833       }
7834     }
7835
7836     // Count cycles in between branches
7837     ccadj[i] = CLOCK_ADJUST(cc);
7838     if (i > 0 && (dops[i-1].is_jump || dops[i].itype == SYSCALL || dops[i].itype == HLECALL))
7839     {
7840       cc=0;
7841     }
7842 #if !defined(DRC_DBG)
7843     else if(dops[i].itype==C2OP&&gte_cycletab[source[i]&0x3f]>2)
7844     {
7845       // this should really be removed since the real stalls have been implemented,
7846       // but doing so causes sizeable perf regression against the older version
7847       u_int gtec = gte_cycletab[source[i] & 0x3f];
7848       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? gtec/2 : 2;
7849     }
7850     else if(i>1&&dops[i].itype==STORE&&dops[i-1].itype==STORE&&dops[i-2].itype==STORE&&!dops[i].bt)
7851     {
7852       cc+=4;
7853     }
7854     else if(dops[i].itype==C2LS)
7855     {
7856       // same as with C2OP
7857       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? 4 : 2;
7858     }
7859 #endif
7860     else
7861     {
7862       cc++;
7863     }
7864
7865     if(!dops[i].is_ds) {
7866       regs[i].dirty=current.dirty;
7867       regs[i].isconst=current.isconst;
7868       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
7869     }
7870     for(hr=0;hr<HOST_REGS;hr++) {
7871       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
7872         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
7873           regs[i].wasconst&=~(1<<hr);
7874         }
7875       }
7876     }
7877     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
7878     //regs[i].waswritten=current.waswritten;
7879   }
7880 }
7881
7882 static noinline void pass4_cull_unused_regs(void)
7883 {
7884   u_int last_needed_regs[4] = {0,0,0,0};
7885   u_int nr=0;
7886   int i;
7887
7888   for (i=slen-1;i>=0;i--)
7889   {
7890     int hr;
7891     __builtin_prefetch(regs[i-2].regmap);
7892     if(dops[i].is_jump)
7893     {
7894       if(ba[i]<start || ba[i]>=(start+slen*4))
7895       {
7896         // Branch out of this block, don't need anything
7897         nr=0;
7898       }
7899       else
7900       {
7901         // Internal branch
7902         // Need whatever matches the target
7903         nr=0;
7904         int t=(ba[i]-start)>>2;
7905         for(hr=0;hr<HOST_REGS;hr++)
7906         {
7907           if(regs[i].regmap_entry[hr]>=0) {
7908             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
7909           }
7910         }
7911       }
7912       // Conditional branch may need registers for following instructions
7913       if (!dops[i].is_ujump)
7914       {
7915         if(i<slen-2) {
7916           nr |= last_needed_regs[(i+2) & 3];
7917           for(hr=0;hr<HOST_REGS;hr++)
7918           {
7919             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
7920             //if((regmap_entry[i+2][hr])>=0) if(!((nr>>hr)&1)) printf("%x-bogus(%d=%d)\n",start+i*4,hr,regmap_entry[i+2][hr]);
7921           }
7922         }
7923       }
7924       // Don't need stuff which is overwritten
7925       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
7926       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
7927       // Merge in delay slot
7928       if (dops[i+1].rt1) nr &= ~get_regm(regs[i].regmap, dops[i+1].rt1);
7929       if (dops[i+1].rt2) nr &= ~get_regm(regs[i].regmap, dops[i+1].rt2);
7930       nr |= get_regm(regmap_pre[i], dops[i+1].rs1);
7931       nr |= get_regm(regmap_pre[i], dops[i+1].rs2);
7932       nr |= get_regm(regs[i].regmap_entry, dops[i+1].rs1);
7933       nr |= get_regm(regs[i].regmap_entry, dops[i+1].rs2);
7934       if (ram_offset && (dops[i+1].is_load || dops[i+1].is_store)) {
7935         nr |= get_regm(regmap_pre[i], ROREG);
7936         nr |= get_regm(regs[i].regmap_entry, ROREG);
7937       }
7938       if (dops[i+1].is_store) {
7939         nr |= get_regm(regmap_pre[i], INVCP);
7940         nr |= get_regm(regs[i].regmap_entry, INVCP);
7941       }
7942     }
7943     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
7944     {
7945       // SYSCALL instruction (software interrupt)
7946       nr=0;
7947     }
7948     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
7949     {
7950       // ERET instruction (return from interrupt)
7951       nr=0;
7952     }
7953     else // Non-branch
7954     {
7955       if(i<slen-1) {
7956         for(hr=0;hr<HOST_REGS;hr++) {
7957           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
7958           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
7959           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
7960           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
7961         }
7962       }
7963     }
7964     // Overwritten registers are not needed
7965     if (dops[i].rt1) nr &= ~get_regm(regs[i].regmap, dops[i].rt1);
7966     if (dops[i].rt2) nr &= ~get_regm(regs[i].regmap, dops[i].rt2);
7967     nr &= ~get_regm(regs[i].regmap, FTEMP);
7968     // Source registers are needed
7969     nr |= get_regm(regmap_pre[i], dops[i].rs1);
7970     nr |= get_regm(regmap_pre[i], dops[i].rs2);
7971     nr |= get_regm(regs[i].regmap_entry, dops[i].rs1);
7972     nr |= get_regm(regs[i].regmap_entry, dops[i].rs2);
7973     if (ram_offset && (dops[i].is_load || dops[i].is_store)) {
7974       nr |= get_regm(regmap_pre[i], ROREG);
7975       nr |= get_regm(regs[i].regmap_entry, ROREG);
7976     }
7977     if (dops[i].is_store) {
7978       nr |= get_regm(regmap_pre[i], INVCP);
7979       nr |= get_regm(regs[i].regmap_entry, INVCP);
7980     }
7981
7982     if (i > 0 && !dops[i].bt && regs[i].wasdirty)
7983     for(hr=0;hr<HOST_REGS;hr++)
7984     {
7985       // Don't store a register immediately after writing it,
7986       // may prevent dual-issue.
7987       // But do so if this is a branch target, otherwise we
7988       // might have to load the register before the branch.
7989       if((regs[i].wasdirty>>hr)&1) {
7990         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
7991           if(dops[i-1].rt1==regmap_pre[i][hr]) nr|=1<<hr;
7992           if(dops[i-1].rt2==regmap_pre[i][hr]) nr|=1<<hr;
7993         }
7994         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
7995           if(dops[i-1].rt1==regs[i].regmap_entry[hr]) nr|=1<<hr;
7996           if(dops[i-1].rt2==regs[i].regmap_entry[hr]) nr|=1<<hr;
7997         }
7998       }
7999     }
8000     // Cycle count is needed at branches.  Assume it is needed at the target too.
8001     if(i==0||dops[i].bt||dops[i].itype==CJUMP) {
8002       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8003       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8004     }
8005     // Save it
8006     last_needed_regs[i & 3] = nr;
8007
8008     // Deallocate unneeded registers
8009     for(hr=0;hr<HOST_REGS;hr++)
8010     {
8011       if(!((nr>>hr)&1)) {
8012         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
8013         if(dops[i].is_jump)
8014         {
8015           int map1 = 0, map2 = 0, temp = 0; // or -1 ??
8016           if (dops[i+1].is_load || dops[i+1].is_store)
8017             map1 = ROREG;
8018           if (dops[i+1].is_store)
8019             map2 = INVCP;
8020           if(dops[i+1].itype==LOADLR || dops[i+1].itype==STORELR || dops[i+1].itype==C2LS)
8021             temp = FTEMP;
8022           if(regs[i].regmap[hr]!=dops[i].rs1 && regs[i].regmap[hr]!=dops[i].rs2 &&
8023              regs[i].regmap[hr]!=dops[i].rt1 && regs[i].regmap[hr]!=dops[i].rt2 &&
8024              regs[i].regmap[hr]!=dops[i+1].rt1 && regs[i].regmap[hr]!=dops[i+1].rt2 &&
8025              regs[i].regmap[hr]!=dops[i+1].rs1 && regs[i].regmap[hr]!=dops[i+1].rs2 &&
8026              regs[i].regmap[hr]!=temp && regs[i].regmap[hr]!=PTEMP &&
8027              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
8028              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
8029              regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2)
8030           {
8031             regs[i].regmap[hr]=-1;
8032             regs[i].isconst&=~(1<<hr);
8033             regs[i].dirty&=~(1<<hr);
8034             regs[i+1].wasdirty&=~(1<<hr);
8035             if(branch_regs[i].regmap[hr]!=dops[i].rs1 && branch_regs[i].regmap[hr]!=dops[i].rs2 &&
8036                branch_regs[i].regmap[hr]!=dops[i].rt1 && branch_regs[i].regmap[hr]!=dops[i].rt2 &&
8037                branch_regs[i].regmap[hr]!=dops[i+1].rt1 && branch_regs[i].regmap[hr]!=dops[i+1].rt2 &&
8038                branch_regs[i].regmap[hr]!=dops[i+1].rs1 && branch_regs[i].regmap[hr]!=dops[i+1].rs2 &&
8039                branch_regs[i].regmap[hr]!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
8040                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
8041                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
8042                branch_regs[i].regmap[hr]!=map1 && branch_regs[i].regmap[hr]!=map2)
8043             {
8044               branch_regs[i].regmap[hr]=-1;
8045               branch_regs[i].regmap_entry[hr]=-1;
8046               if (!dops[i].is_ujump)
8047               {
8048                 if (i < slen-2) {
8049                   regmap_pre[i+2][hr]=-1;
8050                   regs[i+2].wasconst&=~(1<<hr);
8051                 }
8052               }
8053             }
8054           }
8055         }
8056         else
8057         {
8058           // Non-branch
8059           if(i>0)
8060           {
8061             int map1 = -1, map2 = -1, temp=-1;
8062             if (dops[i].is_load || dops[i].is_store)
8063               map1 = ROREG;
8064             if (dops[i].is_store)
8065               map2 = INVCP;
8066             if (dops[i].itype==LOADLR || dops[i].itype==STORELR || dops[i].itype==C2LS)
8067               temp = FTEMP;
8068             if(regs[i].regmap[hr]!=dops[i].rt1 && regs[i].regmap[hr]!=dops[i].rt2 &&
8069                regs[i].regmap[hr]!=dops[i].rs1 && regs[i].regmap[hr]!=dops[i].rs2 &&
8070                regs[i].regmap[hr]!=temp && regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2 &&
8071                //(dops[i].itype!=SPAN||regs[i].regmap[hr]!=CCREG)
8072                regs[i].regmap[hr] != CCREG)
8073             {
8074               if(i<slen-1&&!dops[i].is_ds) {
8075                 assert(regs[i].regmap[hr]<64);
8076                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8077                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8078                 {
8079                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8080                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8081                 }
8082                 regmap_pre[i+1][hr]=-1;
8083                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8084                 regs[i+1].wasconst&=~(1<<hr);
8085               }
8086               regs[i].regmap[hr]=-1;
8087               regs[i].isconst&=~(1<<hr);
8088               regs[i].dirty&=~(1<<hr);
8089               regs[i+1].wasdirty&=~(1<<hr);
8090             }
8091           }
8092         }
8093       } // if needed
8094     } // for hr
8095   }
8096 }
8097
8098 // If a register is allocated during a loop, try to allocate it for the
8099 // entire loop, if possible.  This avoids loading/storing registers
8100 // inside of the loop.
8101 static noinline void pass5a_preallocate1(void)
8102 {
8103   int i, j, hr;
8104   signed char f_regmap[HOST_REGS];
8105   clear_all_regs(f_regmap);
8106   for(i=0;i<slen-1;i++)
8107   {
8108     if(dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8109     {
8110       if(ba[i]>=start && ba[i]<(start+i*4))
8111       if(dops[i+1].itype==NOP||dops[i+1].itype==MOV||dops[i+1].itype==ALU
8112       ||dops[i+1].itype==SHIFTIMM||dops[i+1].itype==IMM16||dops[i+1].itype==LOAD
8113       ||dops[i+1].itype==STORE||dops[i+1].itype==STORELR||dops[i+1].itype==C1LS
8114       ||dops[i+1].itype==SHIFT||dops[i+1].itype==COP1
8115       ||dops[i+1].itype==COP2||dops[i+1].itype==C2LS||dops[i+1].itype==C2OP)
8116       {
8117         int t=(ba[i]-start)>>2;
8118         if(t > 0 && !dops[t-1].is_jump) // loop_preload can't handle jumps into delay slots
8119         if(t<2||(dops[t-2].itype!=UJUMP&&dops[t-2].itype!=RJUMP)||dops[t-2].rt1!=31) // call/ret assumes no registers allocated
8120         for(hr=0;hr<HOST_REGS;hr++)
8121         {
8122           if(regs[i].regmap[hr]>=0) {
8123             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8124               // dealloc old register
8125               int n;
8126               for(n=0;n<HOST_REGS;n++)
8127               {
8128                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8129               }
8130               // and alloc new one
8131               f_regmap[hr]=regs[i].regmap[hr];
8132             }
8133           }
8134           if(branch_regs[i].regmap[hr]>=0) {
8135             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8136               // dealloc old register
8137               int n;
8138               for(n=0;n<HOST_REGS;n++)
8139               {
8140                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8141               }
8142               // and alloc new one
8143               f_regmap[hr]=branch_regs[i].regmap[hr];
8144             }
8145           }
8146           if(dops[i].ooo) {
8147             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8148               f_regmap[hr]=branch_regs[i].regmap[hr];
8149           }else{
8150             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8151               f_regmap[hr]=branch_regs[i].regmap[hr];
8152           }
8153           // Avoid dirty->clean transition
8154           #ifdef DESTRUCTIVE_WRITEBACK
8155           if(t>0) if(get_reg(regmap_pre[t],f_regmap[hr])>=0) if((regs[t].wasdirty>>get_reg(regmap_pre[t],f_regmap[hr]))&1) f_regmap[hr]=-1;
8156           #endif
8157           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8158           // case above, however it's always a good idea.  We can't hoist the
8159           // load if the register was already allocated, so there's no point
8160           // wasting time analyzing most of these cases.  It only "succeeds"
8161           // when the mapping was different and the load can be replaced with
8162           // a mov, which is of negligible benefit.  So such cases are
8163           // skipped below.
8164           if(f_regmap[hr]>0) {
8165             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8166               int r=f_regmap[hr];
8167               for(j=t;j<=i;j++)
8168               {
8169                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8170                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8171                 assert(r < 64);
8172                 if(regs[j].regmap[hr]==f_regmap[hr]&&f_regmap[hr]<TEMPREG) {
8173                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8174                   int k;
8175                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8176                     if(get_reg(regs[i].regmap,f_regmap[hr])>=0) break;
8177                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8178                     k=i;
8179                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8180                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8181                         //printf("no free regs for store %x\n",start+(k-1)*4);
8182                         break;
8183                       }
8184                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8185                         //printf("no-match due to different register\n");
8186                         break;
8187                       }
8188                       if (dops[k-2].is_jump) {
8189                         //printf("no-match due to branch\n");
8190                         break;
8191                       }
8192                       // call/ret fast path assumes no registers allocated
8193                       if(k>2&&(dops[k-3].itype==UJUMP||dops[k-3].itype==RJUMP)&&dops[k-3].rt1==31) {
8194                         break;
8195                       }
8196                       k--;
8197                     }
8198                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8199                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8200                       while(k<i) {
8201                         regs[k].regmap_entry[hr]=f_regmap[hr];
8202                         regs[k].regmap[hr]=f_regmap[hr];
8203                         regmap_pre[k+1][hr]=f_regmap[hr];
8204                         regs[k].wasdirty&=~(1<<hr);
8205                         regs[k].dirty&=~(1<<hr);
8206                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8207                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8208                         regs[k].wasconst&=~(1<<hr);
8209                         regs[k].isconst&=~(1<<hr);
8210                         k++;
8211                       }
8212                     }
8213                     else {
8214                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8215                       break;
8216                     }
8217                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8218                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8219                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8220                       regs[i].regmap_entry[hr]=f_regmap[hr];
8221                       regs[i].regmap[hr]=f_regmap[hr];
8222                       regs[i].wasdirty&=~(1<<hr);
8223                       regs[i].dirty&=~(1<<hr);
8224                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8225                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8226                       regs[i].wasconst&=~(1<<hr);
8227                       regs[i].isconst&=~(1<<hr);
8228                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8229                       branch_regs[i].wasdirty&=~(1<<hr);
8230                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8231                       branch_regs[i].regmap[hr]=f_regmap[hr];
8232                       branch_regs[i].dirty&=~(1<<hr);
8233                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8234                       branch_regs[i].wasconst&=~(1<<hr);
8235                       branch_regs[i].isconst&=~(1<<hr);
8236                       if (!dops[i].is_ujump) {
8237                         regmap_pre[i+2][hr]=f_regmap[hr];
8238                         regs[i+2].wasdirty&=~(1<<hr);
8239                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8240                       }
8241                     }
8242                   }
8243                   for(k=t;k<j;k++) {
8244                     // Alloc register clean at beginning of loop,
8245                     // but may dirty it in pass 6
8246                     regs[k].regmap_entry[hr]=f_regmap[hr];
8247                     regs[k].regmap[hr]=f_regmap[hr];
8248                     regs[k].dirty&=~(1<<hr);
8249                     regs[k].wasconst&=~(1<<hr);
8250                     regs[k].isconst&=~(1<<hr);
8251                     if (dops[k].is_jump) {
8252                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8253                       branch_regs[k].regmap[hr]=f_regmap[hr];
8254                       branch_regs[k].dirty&=~(1<<hr);
8255                       branch_regs[k].wasconst&=~(1<<hr);
8256                       branch_regs[k].isconst&=~(1<<hr);
8257                       if (!dops[k].is_ujump) {
8258                         regmap_pre[k+2][hr]=f_regmap[hr];
8259                         regs[k+2].wasdirty&=~(1<<hr);
8260                       }
8261                     }
8262                     else
8263                     {
8264                       regmap_pre[k+1][hr]=f_regmap[hr];
8265                       regs[k+1].wasdirty&=~(1<<hr);
8266                     }
8267                   }
8268                   if(regs[j].regmap[hr]==f_regmap[hr])
8269                     regs[j].regmap_entry[hr]=f_regmap[hr];
8270                   break;
8271                 }
8272                 if(j==i) break;
8273                 if(regs[j].regmap[hr]>=0)
8274                   break;
8275                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8276                   //printf("no-match due to different register\n");
8277                   break;
8278                 }
8279                 if (dops[j].is_ujump)
8280                 {
8281                   // Stop on unconditional branch
8282                   break;
8283                 }
8284                 if(dops[j].itype==CJUMP||dops[j].itype==SJUMP)
8285                 {
8286                   if(dops[j].ooo) {
8287                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8288                       break;
8289                   }else{
8290                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8291                       break;
8292                   }
8293                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8294                     //printf("no-match due to different register (branch)\n");
8295                     break;
8296                   }
8297                 }
8298                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8299                   //printf("No free regs for store %x\n",start+j*4);
8300                   break;
8301                 }
8302                 assert(f_regmap[hr]<64);
8303               }
8304             }
8305           }
8306         }
8307       }
8308     }else{
8309       // Non branch or undetermined branch target
8310       for(hr=0;hr<HOST_REGS;hr++)
8311       {
8312         if(hr!=EXCLUDE_REG) {
8313           if(regs[i].regmap[hr]>=0) {
8314             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8315               // dealloc old register
8316               int n;
8317               for(n=0;n<HOST_REGS;n++)
8318               {
8319                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8320               }
8321               // and alloc new one
8322               f_regmap[hr]=regs[i].regmap[hr];
8323             }
8324           }
8325         }
8326       }
8327       // Try to restore cycle count at branch targets
8328       if(dops[i].bt) {
8329         for(j=i;j<slen-1;j++) {
8330           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8331           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8332             //printf("no free regs for store %x\n",start+j*4);
8333             break;
8334           }
8335         }
8336         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8337           int k=i;
8338           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8339           while(k<j) {
8340             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8341             regs[k].regmap[HOST_CCREG]=CCREG;
8342             regmap_pre[k+1][HOST_CCREG]=CCREG;
8343             regs[k+1].wasdirty|=1<<HOST_CCREG;
8344             regs[k].dirty|=1<<HOST_CCREG;
8345             regs[k].wasconst&=~(1<<HOST_CCREG);
8346             regs[k].isconst&=~(1<<HOST_CCREG);
8347             k++;
8348           }
8349           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8350         }
8351         // Work backwards from the branch target
8352         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8353         {
8354           //printf("Extend backwards\n");
8355           int k;
8356           k=i;
8357           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8358             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8359               //printf("no free regs for store %x\n",start+(k-1)*4);
8360               break;
8361             }
8362             k--;
8363           }
8364           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8365             //printf("Extend CC, %x ->\n",start+k*4);
8366             while(k<=i) {
8367               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8368               regs[k].regmap[HOST_CCREG]=CCREG;
8369               regmap_pre[k+1][HOST_CCREG]=CCREG;
8370               regs[k+1].wasdirty|=1<<HOST_CCREG;
8371               regs[k].dirty|=1<<HOST_CCREG;
8372               regs[k].wasconst&=~(1<<HOST_CCREG);
8373               regs[k].isconst&=~(1<<HOST_CCREG);
8374               k++;
8375             }
8376           }
8377           else {
8378             //printf("Fail Extend CC, %x ->\n",start+k*4);
8379           }
8380         }
8381       }
8382       if(dops[i].itype!=STORE&&dops[i].itype!=STORELR&&dops[i].itype!=C1LS&&dops[i].itype!=SHIFT&&
8383          dops[i].itype!=NOP&&dops[i].itype!=MOV&&dops[i].itype!=ALU&&dops[i].itype!=SHIFTIMM&&
8384          dops[i].itype!=IMM16&&dops[i].itype!=LOAD&&dops[i].itype!=COP1)
8385       {
8386         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8387       }
8388     }
8389   }
8390 }
8391
8392 // This allocates registers (if possible) one instruction prior
8393 // to use, which can avoid a load-use penalty on certain CPUs.
8394 static noinline void pass5b_preallocate2(void)
8395 {
8396   int i, hr;
8397   for(i=0;i<slen-1;i++)
8398   {
8399     if (!i || !dops[i-1].is_jump)
8400     {
8401       if(!dops[i+1].bt)
8402       {
8403         if(dops[i].itype==ALU||dops[i].itype==MOV||dops[i].itype==LOAD||dops[i].itype==SHIFTIMM||dops[i].itype==IMM16
8404            ||((dops[i].itype==COP1||dops[i].itype==COP2)&&dops[i].opcode2<3))
8405         {
8406           if(dops[i+1].rs1) {
8407             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs1))>=0)
8408             {
8409               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8410               {
8411                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8412                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8413                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8414                 regs[i].isconst&=~(1<<hr);
8415                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8416                 constmap[i][hr]=constmap[i+1][hr];
8417                 regs[i+1].wasdirty&=~(1<<hr);
8418                 regs[i].dirty&=~(1<<hr);
8419               }
8420             }
8421           }
8422           if(dops[i+1].rs2) {
8423             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs2))>=0)
8424             {
8425               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8426               {
8427                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8428                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8429                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8430                 regs[i].isconst&=~(1<<hr);
8431                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8432                 constmap[i][hr]=constmap[i+1][hr];
8433                 regs[i+1].wasdirty&=~(1<<hr);
8434                 regs[i].dirty&=~(1<<hr);
8435               }
8436             }
8437           }
8438           // Preload target address for load instruction (non-constant)
8439           if(dops[i+1].itype==LOAD&&dops[i+1].rs1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8440             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8441             {
8442               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8443               {
8444                 regs[i].regmap[hr]=dops[i+1].rs1;
8445                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8446                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8447                 regs[i].isconst&=~(1<<hr);
8448                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8449                 constmap[i][hr]=constmap[i+1][hr];
8450                 regs[i+1].wasdirty&=~(1<<hr);
8451                 regs[i].dirty&=~(1<<hr);
8452               }
8453             }
8454           }
8455           // Load source into target register
8456           if(dops[i+1].use_lt1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8457             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8458             {
8459               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8460               {
8461                 regs[i].regmap[hr]=dops[i+1].rs1;
8462                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8463                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8464                 regs[i].isconst&=~(1<<hr);
8465                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8466                 constmap[i][hr]=constmap[i+1][hr];
8467                 regs[i+1].wasdirty&=~(1<<hr);
8468                 regs[i].dirty&=~(1<<hr);
8469               }
8470             }
8471           }
8472           // Address for store instruction (non-constant)
8473           if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR
8474              ||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8475             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8476               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8477               if(hr<0) hr=get_reg_temp(regs[i+1].regmap);
8478               else {
8479                 regs[i+1].regmap[hr]=AGEN1+((i+1)&1);
8480                 regs[i+1].isconst&=~(1<<hr);
8481               }
8482               assert(hr>=0);
8483               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8484               {
8485                 regs[i].regmap[hr]=dops[i+1].rs1;
8486                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8487                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8488                 regs[i].isconst&=~(1<<hr);
8489                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8490                 constmap[i][hr]=constmap[i+1][hr];
8491                 regs[i+1].wasdirty&=~(1<<hr);
8492                 regs[i].dirty&=~(1<<hr);
8493               }
8494             }
8495           }
8496           if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
8497             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8498               int nr;
8499               hr=get_reg(regs[i+1].regmap,FTEMP);
8500               assert(hr>=0);
8501               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8502               {
8503                 regs[i].regmap[hr]=dops[i+1].rs1;
8504                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8505                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8506                 regs[i].isconst&=~(1<<hr);
8507                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8508                 constmap[i][hr]=constmap[i+1][hr];
8509                 regs[i+1].wasdirty&=~(1<<hr);
8510                 regs[i].dirty&=~(1<<hr);
8511               }
8512               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
8513               {
8514                 // move it to another register
8515                 regs[i+1].regmap[hr]=-1;
8516                 regmap_pre[i+2][hr]=-1;
8517                 regs[i+1].regmap[nr]=FTEMP;
8518                 regmap_pre[i+2][nr]=FTEMP;
8519                 regs[i].regmap[nr]=dops[i+1].rs1;
8520                 regmap_pre[i+1][nr]=dops[i+1].rs1;
8521                 regs[i+1].regmap_entry[nr]=dops[i+1].rs1;
8522                 regs[i].isconst&=~(1<<nr);
8523                 regs[i+1].isconst&=~(1<<nr);
8524                 regs[i].dirty&=~(1<<nr);
8525                 regs[i+1].wasdirty&=~(1<<nr);
8526                 regs[i+1].dirty&=~(1<<nr);
8527                 regs[i+2].wasdirty&=~(1<<nr);
8528               }
8529             }
8530           }
8531           if(dops[i+1].itype==LOAD||dops[i+1].itype==LOADLR||dops[i+1].itype==STORE||dops[i+1].itype==STORELR/*||dops[i+1].itype==C1LS||||dops[i+1].itype==C2LS*/) {
8532             hr = -1;
8533             if(dops[i+1].itype==LOAD)
8534               hr=get_reg(regs[i+1].regmap,dops[i+1].rt1);
8535             if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
8536               hr=get_reg(regs[i+1].regmap,FTEMP);
8537             if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SWC1/SDC1/SWC2/SDC2
8538               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
8539               if(hr<0) hr=get_reg_temp(regs[i+1].regmap);
8540             }
8541             if(hr>=0&&regs[i].regmap[hr]<0) {
8542               int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
8543               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
8544                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
8545                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
8546                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
8547                 regs[i].isconst&=~(1<<hr);
8548                 regs[i+1].wasdirty&=~(1<<hr);
8549                 regs[i].dirty&=~(1<<hr);
8550               }
8551             }
8552           }
8553         }
8554       }
8555     }
8556   }
8557 }
8558
8559 // Write back dirty registers as soon as we will no longer modify them,
8560 // so that we don't end up with lots of writes at the branches.
8561 static noinline void pass6_clean_registers(int istart, int iend, int wr)
8562 {
8563   static u_int wont_dirty[MAXBLOCK];
8564   static u_int will_dirty[MAXBLOCK];
8565   int i;
8566   int r;
8567   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
8568   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
8569   if(iend==slen-1) {
8570     will_dirty_i=will_dirty_next=0;
8571     wont_dirty_i=wont_dirty_next=0;
8572   }else{
8573     will_dirty_i=will_dirty_next=will_dirty[iend+1];
8574     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
8575   }
8576   for (i=iend;i>=istart;i--)
8577   {
8578     signed char rregmap_i[RRMAP_SIZE];
8579     u_int hr_candirty = 0;
8580     assert(HOST_REGS < 32);
8581     make_rregs(regs[i].regmap, rregmap_i, &hr_candirty);
8582     __builtin_prefetch(regs[i-1].regmap);
8583     if(dops[i].is_jump)
8584     {
8585       signed char branch_rregmap_i[RRMAP_SIZE];
8586       u_int branch_hr_candirty = 0;
8587       make_rregs(branch_regs[i].regmap, branch_rregmap_i, &branch_hr_candirty);
8588       if(ba[i]<start || ba[i]>=(start+slen*4))
8589       {
8590         // Branch out of this block, flush all regs
8591         will_dirty_i = 0;
8592         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8593         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8594         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8595         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8596         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8597         will_dirty_i &= branch_hr_candirty;
8598         if (dops[i].is_ujump)
8599         {
8600           // Unconditional branch
8601           wont_dirty_i = 0;
8602           // Merge in delay slot (will dirty)
8603           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8604           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8605           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8606           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8607           will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8608           will_dirty_i &= hr_candirty;
8609         }
8610         else
8611         {
8612           // Conditional branch
8613           wont_dirty_i = wont_dirty_next;
8614           // Merge in delay slot (will dirty)
8615           // (the original code had no explanation why these 2 are commented out)
8616           //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8617           //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8618           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8619           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8620           will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8621           will_dirty_i &= hr_candirty;
8622         }
8623         // Merge in delay slot (wont dirty)
8624         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8625         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8626         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8627         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8628         wont_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8629         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8630         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8631         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8632         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8633         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8634         wont_dirty_i &= ~(1u << 31);
8635         if(wr) {
8636           #ifndef DESTRUCTIVE_WRITEBACK
8637           branch_regs[i].dirty&=wont_dirty_i;
8638           #endif
8639           branch_regs[i].dirty|=will_dirty_i;
8640         }
8641       }
8642       else
8643       {
8644         // Internal branch
8645         if(ba[i]<=start+i*4) {
8646           // Backward branch
8647           if (dops[i].is_ujump)
8648           {
8649             // Unconditional branch
8650             temp_will_dirty=0;
8651             temp_wont_dirty=0;
8652             // Merge in delay slot (will dirty)
8653             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8654             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8655             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8656             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8657             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8658             temp_will_dirty &= branch_hr_candirty;
8659             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8660             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8661             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8662             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8663             temp_will_dirty |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8664             temp_will_dirty &= hr_candirty;
8665           } else {
8666             // Conditional branch (not taken case)
8667             temp_will_dirty=will_dirty_next;
8668             temp_wont_dirty=wont_dirty_next;
8669             // Merge in delay slot (will dirty)
8670             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8671             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8672             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8673             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8674             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8675             temp_will_dirty &= branch_hr_candirty;
8676             //temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8677             //temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8678             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8679             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8680             temp_will_dirty |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8681             temp_will_dirty &= hr_candirty;
8682           }
8683           // Merge in delay slot (wont dirty)
8684           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8685           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8686           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8687           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8688           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8689           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8690           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8691           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8692           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8693           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8694           temp_wont_dirty &= ~(1u << 31);
8695           // Deal with changed mappings
8696           if(i<iend) {
8697             for(r=0;r<HOST_REGS;r++) {
8698               if(r!=EXCLUDE_REG) {
8699                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
8700                   temp_will_dirty&=~(1<<r);
8701                   temp_wont_dirty&=~(1<<r);
8702                   if(regmap_pre[i][r]>0 && regmap_pre[i][r]<34) {
8703                     temp_will_dirty|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8704                     temp_wont_dirty|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8705                   } else {
8706                     temp_will_dirty|=1<<r;
8707                     temp_wont_dirty|=1<<r;
8708                   }
8709                 }
8710               }
8711             }
8712           }
8713           if(wr) {
8714             will_dirty[i]=temp_will_dirty;
8715             wont_dirty[i]=temp_wont_dirty;
8716             pass6_clean_registers((ba[i]-start)>>2,i-1,0);
8717           }else{
8718             // Limit recursion.  It can take an excessive amount
8719             // of time if there are a lot of nested loops.
8720             will_dirty[(ba[i]-start)>>2]=0;
8721             wont_dirty[(ba[i]-start)>>2]=-1;
8722           }
8723         }
8724         /*else*/ if(1)
8725         {
8726           if (dops[i].is_ujump)
8727           {
8728             // Unconditional branch
8729             will_dirty_i=0;
8730             wont_dirty_i=0;
8731           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
8732             for(r=0;r<HOST_REGS;r++) {
8733               if(r!=EXCLUDE_REG) {
8734                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
8735                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
8736                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
8737                 }
8738                 if(branch_regs[i].regmap[r]>=0) {
8739                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>branch_regs[i].regmap[r])&1)<<r;
8740                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>branch_regs[i].regmap[r])&1)<<r;
8741                 }
8742               }
8743             }
8744           //}
8745             // Merge in delay slot
8746             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8747             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8748             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8749             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8750             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8751             will_dirty_i &= branch_hr_candirty;
8752             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8753             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8754             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8755             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8756             will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8757             will_dirty_i &= hr_candirty;
8758           } else {
8759             // Conditional branch
8760             will_dirty_i=will_dirty_next;
8761             wont_dirty_i=wont_dirty_next;
8762           //if(ba[i]>start+i*4) // Disable recursion (for debugging)
8763             for(r=0;r<HOST_REGS;r++) {
8764               if(r!=EXCLUDE_REG) {
8765                 signed char target_reg=branch_regs[i].regmap[r];
8766                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
8767                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
8768                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
8769                 }
8770                 else if(target_reg>=0) {
8771                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>target_reg)&1)<<r;
8772                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>target_reg)&1)<<r;
8773                 }
8774               }
8775             }
8776             // Merge in delay slot
8777             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8778             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8779             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8780             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8781             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8782             will_dirty_i &= branch_hr_candirty;
8783             //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8784             //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8785             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8786             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8787             will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8788             will_dirty_i &= hr_candirty;
8789           }
8790           // Merge in delay slot (won't dirty)
8791           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8792           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8793           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8794           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8795           wont_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8796           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8797           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8798           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8799           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8800           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8801           wont_dirty_i &= ~(1u << 31);
8802           if(wr) {
8803             #ifndef DESTRUCTIVE_WRITEBACK
8804             branch_regs[i].dirty&=wont_dirty_i;
8805             #endif
8806             branch_regs[i].dirty|=will_dirty_i;
8807           }
8808         }
8809       }
8810     }
8811     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
8812     {
8813       // SYSCALL instruction (software interrupt)
8814       will_dirty_i=0;
8815       wont_dirty_i=0;
8816     }
8817     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
8818     {
8819       // ERET instruction (return from interrupt)
8820       will_dirty_i=0;
8821       wont_dirty_i=0;
8822     }
8823     will_dirty_next=will_dirty_i;
8824     wont_dirty_next=wont_dirty_i;
8825     will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8826     will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8827     will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8828     will_dirty_i &= hr_candirty;
8829     wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8830     wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8831     wont_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8832     wont_dirty_i &= ~(1u << 31);
8833     if (i > istart && !dops[i].is_jump) {
8834       // Don't store a register immediately after writing it,
8835       // may prevent dual-issue.
8836       wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i-1].rt1) & 31);
8837       wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i-1].rt2) & 31);
8838     }
8839     // Save it
8840     will_dirty[i]=will_dirty_i;
8841     wont_dirty[i]=wont_dirty_i;
8842     // Mark registers that won't be dirtied as not dirty
8843     if(wr) {
8844         regs[i].dirty|=will_dirty_i;
8845         #ifndef DESTRUCTIVE_WRITEBACK
8846         regs[i].dirty&=wont_dirty_i;
8847         if(dops[i].is_jump)
8848         {
8849           if (i < iend-1 && !dops[i].is_ujump) {
8850             for(r=0;r<HOST_REGS;r++) {
8851               if(r!=EXCLUDE_REG) {
8852                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
8853                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
8854                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
8855               }
8856             }
8857           }
8858         }
8859         else
8860         {
8861           if(i<iend) {
8862             for(r=0;r<HOST_REGS;r++) {
8863               if(r!=EXCLUDE_REG) {
8864                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
8865                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
8866                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
8867               }
8868             }
8869           }
8870         }
8871         #endif
8872     }
8873     // Deal with changed mappings
8874     temp_will_dirty=will_dirty_i;
8875     temp_wont_dirty=wont_dirty_i;
8876     for(r=0;r<HOST_REGS;r++) {
8877       if(r!=EXCLUDE_REG) {
8878         int nr;
8879         if(regs[i].regmap[r]==regmap_pre[i][r]) {
8880           if(wr) {
8881             #ifndef DESTRUCTIVE_WRITEBACK
8882             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
8883             #endif
8884             regs[i].wasdirty|=will_dirty_i&(1<<r);
8885           }
8886         }
8887         else if(regmap_pre[i][r]>=0&&(nr=get_rreg(rregmap_i,regmap_pre[i][r]))>=0) {
8888           // Register moved to a different register
8889           will_dirty_i&=~(1<<r);
8890           wont_dirty_i&=~(1<<r);
8891           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
8892           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
8893           if(wr) {
8894             #ifndef DESTRUCTIVE_WRITEBACK
8895             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
8896             #endif
8897             regs[i].wasdirty|=will_dirty_i&(1<<r);
8898           }
8899         }
8900         else {
8901           will_dirty_i&=~(1<<r);
8902           wont_dirty_i&=~(1<<r);
8903           if(regmap_pre[i][r]>0 && regmap_pre[i][r]<34) {
8904             will_dirty_i|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8905             wont_dirty_i|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8906           } else {
8907             wont_dirty_i|=1<<r;
8908             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
8909           }
8910         }
8911       }
8912     }
8913   }
8914 }
8915
8916 static noinline void pass10_expire_blocks(void)
8917 {
8918   u_int step = MAX_OUTPUT_BLOCK_SIZE / PAGE_COUNT / 2;
8919   // not sizeof(ndrc->translation_cache) due to vita hack
8920   u_int step_mask = ((1u << TARGET_SIZE_2) - 1u) & ~(step - 1u);
8921   u_int end = (out - ndrc->translation_cache + EXPIRITY_OFFSET) & step_mask;
8922   u_int base_shift = __builtin_ctz(MAX_OUTPUT_BLOCK_SIZE);
8923   int hit;
8924
8925   for (; expirep != end; expirep = ((expirep + step) & step_mask))
8926   {
8927     u_int base_offs = expirep & ~(MAX_OUTPUT_BLOCK_SIZE - 1);
8928     u_int block_i = expirep / step & (PAGE_COUNT - 1);
8929     u_int phase = (expirep >> (base_shift - 1)) & 1u;
8930     if (!(expirep & (MAX_OUTPUT_BLOCK_SIZE / 2 - 1))) {
8931       inv_debug("EXP: base_offs %x/%lx phase %u\n", base_offs,
8932         (long)(out - ndrc->translation_cache), phase);
8933     }
8934
8935     if (!phase) {
8936       hit = blocks_remove_matching_addrs(&blocks[block_i], base_offs, base_shift);
8937       if (hit) {
8938         do_clear_cache();
8939         #ifdef USE_MINI_HT
8940         memset(mini_ht, -1, sizeof(mini_ht));
8941         #endif
8942       }
8943     }
8944     else
8945       unlink_jumps_tc_range(jumps[block_i], base_offs, base_shift);
8946   }
8947 }
8948
8949 static struct block_info *new_block_info(u_int start, u_int len,
8950   const void *source, const void *copy, u_char *beginning, u_short jump_in_count)
8951 {
8952   struct block_info **b_pptr;
8953   struct block_info *block;
8954   u_int page = get_page(start);
8955
8956   block = malloc(sizeof(*block) + jump_in_count * sizeof(block->jump_in[0]));
8957   assert(block);
8958   assert(jump_in_count > 0);
8959   block->source = source;
8960   block->copy = copy;
8961   block->start = start;
8962   block->len = len;
8963   block->reg_sv_flags = 0;
8964   block->tc_offs = beginning - ndrc->translation_cache;
8965   //block->tc_len = out - beginning;
8966   block->is_dirty = 0;
8967   block->inv_near_misses = 0;
8968   block->jump_in_cnt = jump_in_count;
8969
8970   // insert sorted by start mirror-unmasked vaddr
8971   for (b_pptr = &blocks[page]; ; b_pptr = &((*b_pptr)->next)) {
8972     if (*b_pptr == NULL || (*b_pptr)->start >= start) {
8973       block->next = *b_pptr;
8974       *b_pptr = block;
8975       break;
8976     }
8977   }
8978   stat_inc(stat_blocks);
8979   return block;
8980 }
8981
8982 static int new_recompile_block(u_int addr)
8983 {
8984   u_int pagelimit = 0;
8985   u_int state_rflags = 0;
8986   int i;
8987
8988   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
8989
8990   // this is just for speculation
8991   for (i = 1; i < 32; i++) {
8992     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
8993       state_rflags |= 1 << i;
8994   }
8995
8996   assert(!(addr & 3));
8997   start = addr & ~3;
8998   new_dynarec_did_compile=1;
8999   if (Config.HLE && start == 0x80001000) // hlecall
9000   {
9001     // XXX: is this enough? Maybe check hleSoftCall?
9002     void *beginning = start_block();
9003
9004     emit_movimm(start,0);
9005     emit_writeword(0,&pcaddr);
9006     emit_far_jump(new_dyna_leave);
9007     literal_pool(0);
9008     end_block(beginning);
9009     struct block_info *block = new_block_info(start, 4, NULL, NULL, beginning, 1);
9010     block->jump_in[0].vaddr = start;
9011     block->jump_in[0].addr = beginning;
9012     return 0;
9013   }
9014   else if (f1_hack && hack_addr == 0) {
9015     void *beginning = start_block();
9016     emit_movimm(start, 0);
9017     emit_writeword(0, &hack_addr);
9018     emit_readword(&psxRegs.GPR.n.sp, 0);
9019     emit_readptr(&mem_rtab, 1);
9020     emit_shrimm(0, 12, 2);
9021     emit_readptr_dualindexedx_ptrlen(1, 2, 1);
9022     emit_addimm(0, 0x18, 0);
9023     emit_adds_ptr(1, 1, 1);
9024     emit_ldr_dualindexed(1, 0, 0);
9025     emit_writeword(0, &psxRegs.GPR.r[26]); // lw k0, 0x18(sp)
9026     emit_far_call(ndrc_get_addr_ht);
9027     emit_jmpreg(0); // jr k0
9028     literal_pool(0);
9029     end_block(beginning);
9030
9031     struct block_info *block = new_block_info(start, 4, NULL, NULL, beginning, 1);
9032     block->jump_in[0].vaddr = start;
9033     block->jump_in[0].addr = beginning;
9034     SysPrintf("F1 hack to   %08x\n", start);
9035     return 0;
9036   }
9037
9038   cycle_multiplier_active = Config.cycle_multiplier_override && Config.cycle_multiplier == CYCLE_MULT_DEFAULT
9039     ? Config.cycle_multiplier_override : Config.cycle_multiplier;
9040
9041   source = get_source_start(start, &pagelimit);
9042   if (source == NULL) {
9043     if (addr != hack_addr) {
9044       SysPrintf("Compile at bogus memory address: %08x\n", addr);
9045       hack_addr = addr;
9046     }
9047     //abort();
9048     return -1;
9049   }
9050
9051   /* Pass 1: disassemble */
9052   /* Pass 2: register dependencies, branch targets */
9053   /* Pass 3: register allocation */
9054   /* Pass 4: branch dependencies */
9055   /* Pass 5: pre-alloc */
9056   /* Pass 6: optimize clean/dirty state */
9057   /* Pass 7: flag 32-bit registers */
9058   /* Pass 8: assembly */
9059   /* Pass 9: linker */
9060   /* Pass 10: garbage collection / free memory */
9061
9062   /* Pass 1 disassembly */
9063
9064   pass1_disassemble(pagelimit);
9065
9066   int clear_hack_addr = apply_hacks();
9067
9068   /* Pass 2 - Register dependencies and branch targets */
9069
9070   pass2_unneeded_regs(0,slen-1,0);
9071
9072   /* Pass 3 - Register allocation */
9073
9074   pass3_register_alloc(addr);
9075
9076   /* Pass 4 - Cull unused host registers */
9077
9078   pass4_cull_unused_regs();
9079
9080   /* Pass 5 - Pre-allocate registers */
9081
9082   pass5a_preallocate1();
9083   pass5b_preallocate2();
9084
9085   /* Pass 6 - Optimize clean/dirty state */
9086   pass6_clean_registers(0, slen-1, 1);
9087
9088   /* Pass 7 - Identify 32-bit registers */
9089   for (i=slen-1;i>=0;i--)
9090   {
9091     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
9092     {
9093       // Conditional branch
9094       if((source[i]>>16)!=0x1000&&i<slen-2) {
9095         // Mark this address as a branch target since it may be called
9096         // upon return from interrupt
9097         dops[i+2].bt=1;
9098       }
9099     }
9100   }
9101
9102   /* Pass 8 - Assembly */
9103   linkcount=0;stubcount=0;
9104   is_delayslot=0;
9105   u_int dirty_pre=0;
9106   void *beginning=start_block();
9107   void *instr_addr0_override = NULL;
9108   int ds = 0;
9109
9110   if (start == 0x80030000) {
9111     // nasty hack for the fastbios thing
9112     // override block entry to this code
9113     instr_addr0_override = out;
9114     emit_movimm(start,0);
9115     // abuse io address var as a flag that we
9116     // have already returned here once
9117     emit_readword(&address,1);
9118     emit_writeword(0,&pcaddr);
9119     emit_writeword(0,&address);
9120     emit_cmp(0,1);
9121     #ifdef __aarch64__
9122     emit_jeq(out + 4*2);
9123     emit_far_jump(new_dyna_leave);
9124     #else
9125     emit_jne(new_dyna_leave);
9126     #endif
9127   }
9128   for(i=0;i<slen;i++)
9129   {
9130     __builtin_prefetch(regs[i+1].regmap);
9131     check_regmap(regmap_pre[i]);
9132     check_regmap(regs[i].regmap_entry);
9133     check_regmap(regs[i].regmap);
9134     //if(ds) printf("ds: ");
9135     disassemble_inst(i);
9136     if(ds) {
9137       ds=0; // Skip delay slot
9138       if(dops[i].bt) assem_debug("OOPS - branch into delay slot\n");
9139       instr_addr[i] = NULL;
9140     } else {
9141       speculate_register_values(i);
9142       #ifndef DESTRUCTIVE_WRITEBACK
9143       if (i < 2 || !dops[i-2].is_ujump)
9144       {
9145         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
9146       }
9147       if((dops[i].itype==CJUMP||dops[i].itype==SJUMP)) {
9148         dirty_pre=branch_regs[i].dirty;
9149       }else{
9150         dirty_pre=regs[i].dirty;
9151       }
9152       #endif
9153       // write back
9154       if (i < 2 || !dops[i-2].is_ujump)
9155       {
9156         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
9157         loop_preload(regmap_pre[i],regs[i].regmap_entry);
9158       }
9159       // branch target entry point
9160       instr_addr[i] = out;
9161       assem_debug("<->\n");
9162       drc_dbg_emit_do_cmp(i, ccadj[i]);
9163       if (clear_hack_addr) {
9164         emit_movimm(0, 0);
9165         emit_writeword(0, &hack_addr);
9166         clear_hack_addr = 0;
9167       }
9168
9169       // load regs
9170       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
9171         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
9172       load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i].rs1,dops[i].rs2);
9173       address_generation(i,&regs[i],regs[i].regmap_entry);
9174       load_consts(regmap_pre[i],regs[i].regmap,i);
9175       if(dops[i].is_jump)
9176       {
9177         // Load the delay slot registers if necessary
9178         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2&&(dops[i+1].rs1!=dops[i].rt1||dops[i].rt1==0))
9179           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9180         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2&&(dops[i+1].rs2!=dops[i].rt1||dops[i].rt1==0))
9181           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9182         if (ram_offset && (dops[i+1].is_load || dops[i+1].is_store))
9183           load_reg(regs[i].regmap_entry,regs[i].regmap,ROREG);
9184         if (dops[i+1].is_store)
9185           load_reg(regs[i].regmap_entry,regs[i].regmap,INVCP);
9186       }
9187       else if(i+1<slen)
9188       {
9189         // Preload registers for following instruction
9190         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2)
9191           if(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs1!=dops[i].rt2)
9192             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9193         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2)
9194           if(dops[i+1].rs2!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt2)
9195             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9196       }
9197       // TODO: if(is_ooo(i)) address_generation(i+1);
9198       if (!dops[i].is_jump || dops[i].itype == CJUMP)
9199         load_reg(regs[i].regmap_entry,regs[i].regmap,CCREG);
9200       if (ram_offset && (dops[i].is_load || dops[i].is_store))
9201         load_reg(regs[i].regmap_entry,regs[i].regmap,ROREG);
9202       if (dops[i].is_store)
9203         load_reg(regs[i].regmap_entry,regs[i].regmap,INVCP);
9204
9205       ds = assemble(i, &regs[i], ccadj[i]);
9206
9207       if (dops[i].is_ujump)
9208         literal_pool(1024);
9209       else
9210         literal_pool_jumpover(256);
9211     }
9212   }
9213
9214   assert(slen > 0);
9215   if (slen > 0 && dops[slen-1].itype == INTCALL) {
9216     // no ending needed for this block since INTCALL never returns
9217   }
9218   // If the block did not end with an unconditional branch,
9219   // add a jump to the next instruction.
9220   else if (i > 1) {
9221     if (!dops[i-2].is_ujump) {
9222       assert(!dops[i-1].is_jump);
9223       assert(i==slen);
9224       if(dops[i-2].itype!=CJUMP&&dops[i-2].itype!=SJUMP) {
9225         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9226         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9227           emit_loadreg(CCREG,HOST_CCREG);
9228         emit_addimm(HOST_CCREG, ccadj[i-1] + CLOCK_ADJUST(1), HOST_CCREG);
9229       }
9230       else
9231       {
9232         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
9233         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
9234       }
9235       add_to_linker(out,start+i*4,0);
9236       emit_jmp(0);
9237     }
9238   }
9239   else
9240   {
9241     assert(i>0);
9242     assert(!dops[i-1].is_jump);
9243     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9244     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9245       emit_loadreg(CCREG,HOST_CCREG);
9246     emit_addimm(HOST_CCREG, ccadj[i-1] + CLOCK_ADJUST(1), HOST_CCREG);
9247     add_to_linker(out,start+i*4,0);
9248     emit_jmp(0);
9249   }
9250
9251   // TODO: delay slot stubs?
9252   // Stubs
9253   for(i=0;i<stubcount;i++)
9254   {
9255     switch(stubs[i].type)
9256     {
9257       case LOADB_STUB:
9258       case LOADH_STUB:
9259       case LOADW_STUB:
9260       case LOADD_STUB:
9261       case LOADBU_STUB:
9262       case LOADHU_STUB:
9263         do_readstub(i);break;
9264       case STOREB_STUB:
9265       case STOREH_STUB:
9266       case STOREW_STUB:
9267       case STORED_STUB:
9268         do_writestub(i);break;
9269       case CC_STUB:
9270         do_ccstub(i);break;
9271       case INVCODE_STUB:
9272         do_invstub(i);break;
9273       case FP_STUB:
9274         do_cop1stub(i);break;
9275       case STORELR_STUB:
9276         do_unalignedwritestub(i);break;
9277     }
9278   }
9279
9280   if (instr_addr0_override)
9281     instr_addr[0] = instr_addr0_override;
9282
9283 #if 0
9284   /* check for improper expiration */
9285   for (i = 0; i < ARRAY_SIZE(jumps); i++) {
9286     int j;
9287     if (!jumps[i])
9288       continue;
9289     for (j = 0; j < jumps[i]->count; j++)
9290       assert(jumps[i]->e[j].stub < beginning || (u_char *)jumps[i]->e[j].stub > out);
9291   }
9292 #endif
9293
9294   /* Pass 9 - Linker */
9295   for(i=0;i<linkcount;i++)
9296   {
9297     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9298     literal_pool(64);
9299     if (!link_addr[i].internal)
9300     {
9301       void *stub = out;
9302       void *addr = check_addr(link_addr[i].target);
9303       emit_extjump(link_addr[i].addr, link_addr[i].target);
9304       if (addr) {
9305         set_jump_target(link_addr[i].addr, addr);
9306         ndrc_add_jump_out(link_addr[i].target,stub);
9307       }
9308       else
9309         set_jump_target(link_addr[i].addr, stub);
9310     }
9311     else
9312     {
9313       // Internal branch
9314       int target=(link_addr[i].target-start)>>2;
9315       assert(target>=0&&target<slen);
9316       assert(instr_addr[target]);
9317       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9318       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9319       //#else
9320       set_jump_target(link_addr[i].addr, instr_addr[target]);
9321       //#endif
9322     }
9323   }
9324
9325   u_int source_len = slen*4;
9326   if (dops[slen-1].itype == INTCALL && source_len > 4)
9327     // no need to treat the last instruction as compiled
9328     // as interpreter fully handles it
9329     source_len -= 4;
9330
9331   if ((u_char *)copy + source_len > (u_char *)shadow + sizeof(shadow))
9332     copy = shadow;
9333
9334   // External Branch Targets (jump_in)
9335   int jump_in_count = 1;
9336   assert(instr_addr[0]);
9337   for (i = 1; i < slen; i++)
9338   {
9339     if (dops[i].bt && instr_addr[i])
9340       jump_in_count++;
9341   }
9342
9343   struct block_info *block =
9344     new_block_info(start, slen * 4, source, copy, beginning, jump_in_count);
9345   block->reg_sv_flags = state_rflags;
9346
9347   int jump_in_i = 0;
9348   for (i = 0; i < slen; i++)
9349   {
9350     if ((i == 0 || dops[i].bt) && instr_addr[i])
9351     {
9352       assem_debug("%p (%d) <- %8x\n", instr_addr[i], i, start + i*4);
9353       u_int vaddr = start + i*4;
9354
9355       literal_pool(256);
9356       void *entry = out;
9357       load_regs_entry(i);
9358       if (entry == out)
9359         entry = instr_addr[i];
9360       else
9361         emit_jmp(instr_addr[i]);
9362
9363       block->jump_in[jump_in_i].vaddr = vaddr;
9364       block->jump_in[jump_in_i].addr = entry;
9365       jump_in_i++;
9366     }
9367   }
9368   assert(jump_in_i == jump_in_count);
9369   hash_table_add(block->jump_in[0].vaddr, block->jump_in[0].addr);
9370   // Write out the literal pool if necessary
9371   literal_pool(0);
9372   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9373   // Align code
9374   if(((u_int)out)&7) emit_addnop(13);
9375   #endif
9376   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9377   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9378   memcpy(copy, source, source_len);
9379   copy += source_len;
9380
9381   end_block(beginning);
9382
9383   // If we're within 256K of the end of the buffer,
9384   // start over from the beginning. (Is 256K enough?)
9385   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9386     out = ndrc->translation_cache;
9387
9388   // Trap writes to any of the pages we compiled
9389   mark_invalid_code(start, slen*4, 0);
9390
9391   /* Pass 10 - Free memory by expiring oldest blocks */
9392
9393   pass10_expire_blocks();
9394
9395 #ifdef ASSEM_PRINT
9396   fflush(stdout);
9397 #endif
9398   stat_inc(stat_bc_direct);
9399   return 0;
9400 }
9401
9402 // vim:shiftwidth=2:expandtab