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