drc: don't abort on game crash
[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
33 #include "new_dynarec_config.h"
34 #include "../psxhle.h"
35 #include "../psxinterpreter.h"
36 #include "../gte.h"
37 #include "emu_if.h" // emulator interface
38
39 #define noinline __attribute__((noinline,noclone))
40 #ifndef ARRAY_SIZE
41 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
42 #endif
43 #ifndef min
44 #define min(a, b) ((b) < (a) ? (b) : (a))
45 #endif
46 #ifndef max
47 #define max(a, b) ((b) > (a) ? (b) : (a))
48 #endif
49
50 //#define DISASM
51 //#define ASSEM_PRINT
52 //#define REG_ALLOC_PRINT
53
54 #ifdef ASSEM_PRINT
55 #define assem_debug printf
56 #else
57 #define assem_debug(...)
58 #endif
59 //#define inv_debug printf
60 #define inv_debug(...)
61
62 #ifdef __i386__
63 #include "assem_x86.h"
64 #endif
65 #ifdef __x86_64__
66 #include "assem_x64.h"
67 #endif
68 #ifdef __arm__
69 #include "assem_arm.h"
70 #endif
71 #ifdef __aarch64__
72 #include "assem_arm64.h"
73 #endif
74
75 #define RAM_SIZE 0x200000
76 #define MAXBLOCK 4096
77 #define MAX_OUTPUT_BLOCK_SIZE 262144
78
79 #ifdef VITA
80 // apparently Vita has a 16MB limit, so either we cut tc in half,
81 // or use this hack (it's a hack because tc size was designed to be power-of-2)
82 #define TC_REDUCE_BYTES 4096
83 #else
84 #define TC_REDUCE_BYTES 0
85 #endif
86
87 struct ndrc_mem
88 {
89   u_char translation_cache[(1 << TARGET_SIZE_2) - TC_REDUCE_BYTES];
90   struct
91   {
92     struct tramp_insns ops[2048 / sizeof(struct tramp_insns)];
93     const void *f[2048 / sizeof(void *)];
94   } tramp;
95 };
96
97 #ifdef BASE_ADDR_DYNAMIC
98 static struct ndrc_mem *ndrc;
99 #else
100 static struct ndrc_mem ndrc_ __attribute__((aligned(4096)));
101 static struct ndrc_mem *ndrc = &ndrc_;
102 #endif
103
104 // stubs
105 enum stub_type {
106   CC_STUB = 1,
107   FP_STUB = 2,
108   LOADB_STUB = 3,
109   LOADH_STUB = 4,
110   LOADW_STUB = 5,
111   LOADD_STUB = 6,
112   LOADBU_STUB = 7,
113   LOADHU_STUB = 8,
114   STOREB_STUB = 9,
115   STOREH_STUB = 10,
116   STOREW_STUB = 11,
117   STORED_STUB = 12,
118   STORELR_STUB = 13,
119   INVCODE_STUB = 14,
120 };
121
122 // regmap_pre[i]    - regs before [i] insn starts; dirty things here that
123 //                    don't match .regmap will be written back
124 // [i].regmap_entry - regs that must be set up if someone jumps here
125 // [i].regmap       - regs [i] insn will read/(over)write
126 // branch_regs[i].* - same as above but for branches, takes delay slot into account
127 struct regstat
128 {
129   signed char regmap_entry[HOST_REGS];
130   signed char regmap[HOST_REGS];
131   uint64_t wasdirty;
132   uint64_t dirty;
133   uint64_t u;
134   u_int wasconst;                // before; for example 'lw r2, (r2)' wasconst is true
135   u_int isconst;                 //  ... but isconst is false when r2 is known
136   u_int loadedconst;             // host regs that have constants loaded
137   u_int waswritten;              // MIPS regs that were used as store base before
138 };
139
140 // note: asm depends on this layout
141 struct ll_entry
142 {
143   u_int vaddr;
144   u_int reg_sv_flags;
145   void *addr;
146   struct ll_entry *next;
147 };
148
149 struct ht_entry
150 {
151   u_int vaddr[2];
152   void *tcaddr[2];
153 };
154
155 struct code_stub
156 {
157   enum stub_type type;
158   void *addr;
159   void *retaddr;
160   u_int a;
161   uintptr_t b;
162   uintptr_t c;
163   u_int d;
164   u_int e;
165 };
166
167 struct link_entry
168 {
169   void *addr;
170   u_int target;
171   u_int ext;
172 };
173
174 static struct decoded_insn
175 {
176   u_char itype;
177   u_char opcode;
178   u_char opcode2;
179   u_char rs1;
180   u_char rs2;
181   u_char rt1;
182   u_char rt2;
183   u_char lt1;
184   u_char bt:1;
185   u_char ooo:1;
186   u_char is_ds:1;
187   u_char is_jump:1;
188   u_char is_ujump:1;
189   u_char is_load:1;
190   u_char is_store:1;
191 } dops[MAXBLOCK];
192
193   // used by asm:
194   u_char *out;
195   struct ht_entry hash_table[65536]  __attribute__((aligned(16)));
196   struct ll_entry *jump_in[4096] __attribute__((aligned(16)));
197   struct ll_entry *jump_dirty[4096];
198
199   static struct ll_entry *jump_out[4096];
200   static u_int start;
201   static u_int *source;
202   static char insn[MAXBLOCK][10];
203   static uint64_t gte_rs[MAXBLOCK]; // gte: 32 data and 32 ctl regs
204   static uint64_t gte_rt[MAXBLOCK];
205   static uint64_t gte_unneeded[MAXBLOCK];
206   static u_int smrv[32]; // speculated MIPS register values
207   static u_int smrv_strong; // mask or regs that are likely to have correct values
208   static u_int smrv_weak; // same, but somewhat less likely
209   static u_int smrv_strong_next; // same, but after current insn executes
210   static u_int smrv_weak_next;
211   static int imm[MAXBLOCK];
212   static u_int ba[MAXBLOCK];
213   static uint64_t unneeded_reg[MAXBLOCK];
214   static uint64_t branch_unneeded_reg[MAXBLOCK];
215   // see 'struct regstat' for a description
216   static signed char regmap_pre[MAXBLOCK][HOST_REGS];
217   // contains 'real' consts at [i] insn, but may differ from what's actually
218   // loaded in host reg as 'final' value is always loaded, see get_final_value()
219   static uint32_t current_constmap[HOST_REGS];
220   static uint32_t constmap[MAXBLOCK][HOST_REGS];
221   static struct regstat regs[MAXBLOCK];
222   static struct regstat branch_regs[MAXBLOCK];
223   static signed char minimum_free_regs[MAXBLOCK];
224   static u_int needed_reg[MAXBLOCK];
225   static u_int wont_dirty[MAXBLOCK];
226   static u_int will_dirty[MAXBLOCK];
227   static int ccadj[MAXBLOCK];
228   static int slen;
229   static void *instr_addr[MAXBLOCK];
230   static struct link_entry link_addr[MAXBLOCK];
231   static int linkcount;
232   static struct code_stub stubs[MAXBLOCK*3];
233   static int stubcount;
234   static u_int literals[1024][2];
235   static int literalcount;
236   static int is_delayslot;
237   static char shadow[1048576]  __attribute__((aligned(16)));
238   static void *copy;
239   static int expirep;
240   static u_int stop_after_jal;
241   static u_int f1_hack;
242
243   int new_dynarec_hacks;
244   int new_dynarec_hacks_pergame;
245   int new_dynarec_hacks_old;
246   int new_dynarec_did_compile;
247
248   #define HACK_ENABLED(x) ((new_dynarec_hacks | new_dynarec_hacks_pergame) & (x))
249
250   extern int cycle_count; // ... until end of the timeslice, counts -N -> 0
251   extern int last_count;  // last absolute target, often = next_interupt
252   extern int pcaddr;
253   extern int pending_exception;
254   extern int branch_target;
255   extern uintptr_t ram_offset;
256   extern uintptr_t mini_ht[32][2];
257   extern u_char restore_candidate[512];
258
259   /* registers that may be allocated */
260   /* 1-31 gpr */
261 #define LOREG 32 // lo
262 #define HIREG 33 // hi
263 //#define FSREG 34 // FPU status (FCSR)
264 #define CSREG 35 // Coprocessor status
265 #define CCREG 36 // Cycle count
266 #define INVCP 37 // Pointer to invalid_code
267 //#define MMREG 38 // Pointer to memory_map
268 #define ROREG 39 // ram offset (if rdram!=0x80000000)
269 #define TEMPREG 40
270 #define FTEMP 40 // FPU temporary register
271 #define PTEMP 41 // Prefetch temporary register
272 //#define TLREG 42 // TLB mapping offset
273 #define RHASH 43 // Return address hash
274 #define RHTBL 44 // Return address hash table address
275 #define RTEMP 45 // JR/JALR address register
276 #define MAXREG 45
277 #define AGEN1 46 // Address generation temporary register
278 //#define AGEN2 47 // Address generation temporary register
279 //#define MGEN1 48 // Maptable address generation temporary register
280 //#define MGEN2 49 // Maptable address generation temporary register
281 #define BTREG 50 // Branch target temporary register
282
283   /* instruction types */
284 #define NOP 0     // No operation
285 #define LOAD 1    // Load
286 #define STORE 2   // Store
287 #define LOADLR 3  // Unaligned load
288 #define STORELR 4 // Unaligned store
289 #define MOV 5     // Move
290 #define ALU 6     // Arithmetic/logic
291 #define MULTDIV 7 // Multiply/divide
292 #define SHIFT 8   // Shift by register
293 #define SHIFTIMM 9// Shift by immediate
294 #define IMM16 10  // 16-bit immediate
295 #define RJUMP 11  // Unconditional jump to register
296 #define UJUMP 12  // Unconditional jump
297 #define CJUMP 13  // Conditional branch (BEQ/BNE/BGTZ/BLEZ)
298 #define SJUMP 14  // Conditional branch (regimm format)
299 #define COP0 15   // Coprocessor 0
300 #define COP1 16   // Coprocessor 1
301 #define C1LS 17   // Coprocessor 1 load/store
302 //#define FJUMP 18  // Conditional branch (floating point)
303 //#define FLOAT 19  // Floating point unit
304 //#define FCONV 20  // Convert integer to float
305 //#define FCOMP 21  // Floating point compare (sets FSREG)
306 #define SYSCALL 22// SYSCALL,BREAK
307 #define OTHER 23  // Other
308 #define SPAN 24   // Branch/delay slot spans 2 pages
309 #define NI 25     // Not implemented
310 #define HLECALL 26// PCSX fake opcodes for HLE
311 #define COP2 27   // Coprocessor 2 move
312 #define C2LS 28   // Coprocessor 2 load/store
313 #define C2OP 29   // Coprocessor 2 operation
314 #define INTCALL 30// Call interpreter to handle rare corner cases
315
316   /* branch codes */
317 #define TAKEN 1
318 #define NOTTAKEN 2
319 #define NULLDS 3
320
321 #define DJT_1 (void *)1l // no function, just a label in assem_debug log
322 #define DJT_2 (void *)2l
323
324 // asm linkage
325 int new_recompile_block(u_int addr);
326 void *get_addr_ht(u_int vaddr);
327 void invalidate_block(u_int block);
328 void invalidate_addr(u_int addr);
329 void remove_hash(int vaddr);
330 void dyna_linker();
331 void dyna_linker_ds();
332 void verify_code();
333 void verify_code_ds();
334 void cc_interrupt();
335 void fp_exception();
336 void fp_exception_ds();
337 void jump_syscall   (u_int u0, u_int u1, u_int pc);
338 void jump_syscall_ds(u_int u0, u_int u1, u_int pc);
339 void jump_break   (u_int u0, u_int u1, u_int pc);
340 void jump_break_ds(u_int u0, u_int u1, u_int pc);
341 void jump_to_new_pc();
342 void call_gteStall();
343 void new_dyna_leave();
344
345 // Needed by assembler
346 static void wb_register(signed char r, const signed char regmap[], uint64_t dirty);
347 static void wb_dirtys(const signed char i_regmap[], uint64_t i_dirty);
348 static void wb_needed_dirtys(const signed char i_regmap[], uint64_t i_dirty, int addr);
349 static void load_all_regs(const signed char i_regmap[]);
350 static void load_needed_regs(const signed char i_regmap[], const signed char next_regmap[]);
351 static void load_regs_entry(int t);
352 static void load_all_consts(const signed char regmap[], u_int dirty, int i);
353 static u_int get_host_reglist(const signed char *regmap);
354
355 static int verify_dirty(const u_int *ptr);
356 static int get_final_value(int hr, int i, int *value);
357 static void add_stub(enum stub_type type, void *addr, void *retaddr,
358   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e);
359 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
360   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist);
361 static void add_to_linker(void *addr, u_int target, int ext);
362 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
363   int addr, int *offset_reg, int *addr_reg_override);
364 static void *get_direct_memhandler(void *table, u_int addr,
365   enum stub_type type, uintptr_t *addr_host);
366 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist);
367 static void pass_args(int a0, int a1);
368 static void emit_far_jump(const void *f);
369 static void emit_far_call(const void *f);
370
371 #ifdef VITA
372 #include <psp2/kernel/sysmem.h>
373 static int sceBlock;
374 // note: this interacts with RetroArch's Vita bootstrap code: bootstrap/vita/sbrk.c
375 extern int getVMBlock();
376 int _newlib_vm_size_user = sizeof(*ndrc);
377 #endif
378
379 static void mprotect_w_x(void *start, void *end, int is_x)
380 {
381 #ifdef NO_WRITE_EXEC
382   #if defined(VITA)
383   // *Open* enables write on all memory that was
384   // allocated by sceKernelAllocMemBlockForVM()?
385   if (is_x)
386     sceKernelCloseVMDomain();
387   else
388     sceKernelOpenVMDomain();
389   #else
390   u_long mstart = (u_long)start & ~4095ul;
391   u_long mend = (u_long)end;
392   if (mprotect((void *)mstart, mend - mstart,
393                PROT_READ | (is_x ? PROT_EXEC : PROT_WRITE)) != 0)
394     SysPrintf("mprotect(%c) failed: %s\n", is_x ? 'x' : 'w', strerror(errno));
395   #endif
396 #endif
397 }
398
399 static void start_tcache_write(void *start, void *end)
400 {
401   mprotect_w_x(start, end, 0);
402 }
403
404 static void end_tcache_write(void *start, void *end)
405 {
406 #if defined(__arm__) || defined(__aarch64__)
407   size_t len = (char *)end - (char *)start;
408   #if   defined(__BLACKBERRY_QNX__)
409   msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
410   #elif defined(__MACH__)
411   sys_cache_control(kCacheFunctionPrepareForExecution, start, len);
412   #elif defined(VITA)
413   sceKernelSyncVMDomain(sceBlock, start, len);
414   #elif defined(_3DS)
415   ctr_flush_invalidate_cache();
416   #elif defined(__aarch64__)
417   // as of 2021, __clear_cache() is still broken on arm64
418   // so here is a custom one :(
419   clear_cache_arm64(start, end);
420   #else
421   __clear_cache(start, end);
422   #endif
423   (void)len;
424 #endif
425
426   mprotect_w_x(start, end, 1);
427 }
428
429 static void *start_block(void)
430 {
431   u_char *end = out + MAX_OUTPUT_BLOCK_SIZE;
432   if (end > ndrc->translation_cache + sizeof(ndrc->translation_cache))
433     end = ndrc->translation_cache + sizeof(ndrc->translation_cache);
434   start_tcache_write(out, end);
435   return out;
436 }
437
438 static void end_block(void *start)
439 {
440   end_tcache_write(start, out);
441 }
442
443 // also takes care of w^x mappings when patching code
444 static u_int needs_clear_cache[1<<(TARGET_SIZE_2-17)];
445
446 static void mark_clear_cache(void *target)
447 {
448   uintptr_t offset = (u_char *)target - ndrc->translation_cache;
449   u_int mask = 1u << ((offset >> 12) & 31);
450   if (!(needs_clear_cache[offset >> 17] & mask)) {
451     char *start = (char *)((uintptr_t)target & ~4095l);
452     start_tcache_write(start, start + 4095);
453     needs_clear_cache[offset >> 17] |= mask;
454   }
455 }
456
457 // Clearing the cache is rather slow on ARM Linux, so mark the areas
458 // that need to be cleared, and then only clear these areas once.
459 static void do_clear_cache(void)
460 {
461   int i, j;
462   for (i = 0; i < (1<<(TARGET_SIZE_2-17)); i++)
463   {
464     u_int bitmap = needs_clear_cache[i];
465     if (!bitmap)
466       continue;
467     for (j = 0; j < 32; j++)
468     {
469       u_char *start, *end;
470       if (!(bitmap & (1<<j)))
471         continue;
472
473       start = ndrc->translation_cache + i*131072 + j*4096;
474       end = start + 4095;
475       for (j++; j < 32; j++) {
476         if (!(bitmap & (1<<j)))
477           break;
478         end += 4096;
479       }
480       end_tcache_write(start, end);
481     }
482     needs_clear_cache[i] = 0;
483   }
484 }
485
486 //#define DEBUG_CYCLE_COUNT 1
487
488 #define NO_CYCLE_PENALTY_THR 12
489
490 int cycle_multiplier = CYCLE_MULT_DEFAULT; // 100 for 1.0
491 int cycle_multiplier_override;
492 int cycle_multiplier_old;
493 static int cycle_multiplier_active;
494
495 static int CLOCK_ADJUST(int x)
496 {
497   int m = cycle_multiplier_active;
498   int s = (x >> 31) | 1;
499   return (x * m + s * 50) / 100;
500 }
501
502 static int ds_writes_rjump_rs(int i)
503 {
504   return dops[i].rs1 != 0 && (dops[i].rs1 == dops[i+1].rt1 || dops[i].rs1 == dops[i+1].rt2);
505 }
506
507 static u_int get_page(u_int vaddr)
508 {
509   u_int page=vaddr&~0xe0000000;
510   if (page < 0x1000000)
511     page &= ~0x0e00000; // RAM mirrors
512   page>>=12;
513   if(page>2048) page=2048+(page&2047);
514   return page;
515 }
516
517 // no virtual mem in PCSX
518 static u_int get_vpage(u_int vaddr)
519 {
520   return get_page(vaddr);
521 }
522
523 static struct ht_entry *hash_table_get(u_int vaddr)
524 {
525   return &hash_table[((vaddr>>16)^vaddr)&0xFFFF];
526 }
527
528 static void hash_table_add(struct ht_entry *ht_bin, u_int vaddr, void *tcaddr)
529 {
530   ht_bin->vaddr[1] = ht_bin->vaddr[0];
531   ht_bin->tcaddr[1] = ht_bin->tcaddr[0];
532   ht_bin->vaddr[0] = vaddr;
533   ht_bin->tcaddr[0] = tcaddr;
534 }
535
536 // some messy ari64's code, seems to rely on unsigned 32bit overflow
537 static int doesnt_expire_soon(void *tcaddr)
538 {
539   u_int diff = (u_int)((u_char *)tcaddr - out) << (32-TARGET_SIZE_2);
540   return diff > (u_int)(0x60000000 + (MAX_OUTPUT_BLOCK_SIZE << (32-TARGET_SIZE_2)));
541 }
542
543 // Get address from virtual address
544 // This is called from the recompiled JR/JALR instructions
545 void noinline *get_addr(u_int vaddr)
546 {
547   u_int page=get_page(vaddr);
548   u_int vpage=get_vpage(vaddr);
549   struct ll_entry *head;
550   //printf("TRACE: count=%d next=%d (get_addr %x,page %d)\n",Count,next_interupt,vaddr,page);
551   head=jump_in[page];
552   while(head!=NULL) {
553     if(head->vaddr==vaddr) {
554   //printf("TRACE: count=%d next=%d (get_addr match %x: %p)\n",Count,next_interupt,vaddr,head->addr);
555       hash_table_add(hash_table_get(vaddr), vaddr, head->addr);
556       return head->addr;
557     }
558     head=head->next;
559   }
560   head=jump_dirty[vpage];
561   while(head!=NULL) {
562     if(head->vaddr==vaddr) {
563       //printf("TRACE: count=%d next=%d (get_addr match dirty %x: %p)\n",Count,next_interupt,vaddr,head->addr);
564       // Don't restore blocks which are about to expire from the cache
565       if (doesnt_expire_soon(head->addr))
566       if (verify_dirty(head->addr)) {
567         //printf("restore candidate: %x (%d) d=%d\n",vaddr,page,invalid_code[vaddr>>12]);
568         invalid_code[vaddr>>12]=0;
569         inv_code_start=inv_code_end=~0;
570         if(vpage<2048) {
571           restore_candidate[vpage>>3]|=1<<(vpage&7);
572         }
573         else restore_candidate[page>>3]|=1<<(page&7);
574         struct ht_entry *ht_bin = hash_table_get(vaddr);
575         if (ht_bin->vaddr[0] == vaddr)
576           ht_bin->tcaddr[0] = head->addr; // Replace existing entry
577         else
578           hash_table_add(ht_bin, vaddr, head->addr);
579
580         return head->addr;
581       }
582     }
583     head=head->next;
584   }
585   //printf("TRACE: count=%d next=%d (get_addr no-match %x)\n",Count,next_interupt,vaddr);
586   int r=new_recompile_block(vaddr);
587   if(r==0) return get_addr(vaddr);
588   // generate an address error
589   Status|=2;
590   Cause=(vaddr<<31)|(4<<2);
591   EPC=(vaddr&1)?vaddr-5:vaddr;
592   BadVAddr=(vaddr&~1);
593   return get_addr_ht(0x80000080);
594 }
595 // Look up address in hash table first
596 void *get_addr_ht(u_int vaddr)
597 {
598   //printf("TRACE: count=%d next=%d (get_addr_ht %x)\n",Count,next_interupt,vaddr);
599   const struct ht_entry *ht_bin = hash_table_get(vaddr);
600   if (ht_bin->vaddr[0] == vaddr) return ht_bin->tcaddr[0];
601   if (ht_bin->vaddr[1] == vaddr) return ht_bin->tcaddr[1];
602   return get_addr(vaddr);
603 }
604
605 static void clear_all_regs(signed char regmap[])
606 {
607   memset(regmap, -1, sizeof(regmap[0]) * HOST_REGS);
608 }
609
610 static signed char get_reg(const signed char regmap[],int r)
611 {
612   int hr;
613   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap[hr]==r) return hr;
614   return -1;
615 }
616
617 // Find a register that is available for two consecutive cycles
618 static signed char get_reg2(signed char regmap1[], const signed char regmap2[], int r)
619 {
620   int hr;
621   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap1[hr]==r&&regmap2[hr]==r) return hr;
622   return -1;
623 }
624
625 int count_free_regs(signed char regmap[])
626 {
627   int count=0;
628   int hr;
629   for(hr=0;hr<HOST_REGS;hr++)
630   {
631     if(hr!=EXCLUDE_REG) {
632       if(regmap[hr]<0) count++;
633     }
634   }
635   return count;
636 }
637
638 void dirty_reg(struct regstat *cur,signed char reg)
639 {
640   int hr;
641   if(!reg) return;
642   for (hr=0;hr<HOST_REGS;hr++) {
643     if((cur->regmap[hr]&63)==reg) {
644       cur->dirty|=1<<hr;
645     }
646   }
647 }
648
649 static void set_const(struct regstat *cur, signed char reg, uint32_t value)
650 {
651   int hr;
652   if(!reg) return;
653   for (hr=0;hr<HOST_REGS;hr++) {
654     if(cur->regmap[hr]==reg) {
655       cur->isconst|=1<<hr;
656       current_constmap[hr]=value;
657     }
658   }
659 }
660
661 static void clear_const(struct regstat *cur, signed char reg)
662 {
663   int hr;
664   if(!reg) return;
665   for (hr=0;hr<HOST_REGS;hr++) {
666     if((cur->regmap[hr]&63)==reg) {
667       cur->isconst&=~(1<<hr);
668     }
669   }
670 }
671
672 static int is_const(struct regstat *cur, signed char reg)
673 {
674   int hr;
675   if(reg<0) return 0;
676   if(!reg) return 1;
677   for (hr=0;hr<HOST_REGS;hr++) {
678     if((cur->regmap[hr]&63)==reg) {
679       return (cur->isconst>>hr)&1;
680     }
681   }
682   return 0;
683 }
684
685 static uint32_t get_const(struct regstat *cur, signed char reg)
686 {
687   int hr;
688   if(!reg) return 0;
689   for (hr=0;hr<HOST_REGS;hr++) {
690     if(cur->regmap[hr]==reg) {
691       return current_constmap[hr];
692     }
693   }
694   SysPrintf("Unknown constant in r%d\n",reg);
695   abort();
696 }
697
698 // Least soon needed registers
699 // Look at the next ten instructions and see which registers
700 // will be used.  Try not to reallocate these.
701 void lsn(u_char hsn[], int i, int *preferred_reg)
702 {
703   int j;
704   int b=-1;
705   for(j=0;j<9;j++)
706   {
707     if(i+j>=slen) {
708       j=slen-i-1;
709       break;
710     }
711     if (dops[i+j].is_ujump)
712     {
713       // Don't go past an unconditonal jump
714       j++;
715       break;
716     }
717   }
718   for(;j>=0;j--)
719   {
720     if(dops[i+j].rs1) hsn[dops[i+j].rs1]=j;
721     if(dops[i+j].rs2) hsn[dops[i+j].rs2]=j;
722     if(dops[i+j].rt1) hsn[dops[i+j].rt1]=j;
723     if(dops[i+j].rt2) hsn[dops[i+j].rt2]=j;
724     if(dops[i+j].itype==STORE || dops[i+j].itype==STORELR) {
725       // Stores can allocate zero
726       hsn[dops[i+j].rs1]=j;
727       hsn[dops[i+j].rs2]=j;
728     }
729     if (ram_offset && (dops[i+j].is_load || dops[i+j].is_store))
730       hsn[ROREG] = j;
731     // On some architectures stores need invc_ptr
732     #if defined(HOST_IMM8)
733     if (dops[i+j].is_store)
734       hsn[INVCP] = j;
735     #endif
736     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
737     {
738       hsn[CCREG]=j;
739       b=j;
740     }
741   }
742   if(b>=0)
743   {
744     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
745     {
746       // Follow first branch
747       int t=(ba[i+b]-start)>>2;
748       j=7-b;if(t+j>=slen) j=slen-t-1;
749       for(;j>=0;j--)
750       {
751         if(dops[t+j].rs1) if(hsn[dops[t+j].rs1]>j+b+2) hsn[dops[t+j].rs1]=j+b+2;
752         if(dops[t+j].rs2) if(hsn[dops[t+j].rs2]>j+b+2) hsn[dops[t+j].rs2]=j+b+2;
753         //if(dops[t+j].rt1) if(hsn[dops[t+j].rt1]>j+b+2) hsn[dops[t+j].rt1]=j+b+2;
754         //if(dops[t+j].rt2) if(hsn[dops[t+j].rt2]>j+b+2) hsn[dops[t+j].rt2]=j+b+2;
755       }
756     }
757     // TODO: preferred register based on backward branch
758   }
759   // Delay slot should preferably not overwrite branch conditions or cycle count
760   if (i > 0 && dops[i-1].is_jump) {
761     if(dops[i-1].rs1) if(hsn[dops[i-1].rs1]>1) hsn[dops[i-1].rs1]=1;
762     if(dops[i-1].rs2) if(hsn[dops[i-1].rs2]>1) hsn[dops[i-1].rs2]=1;
763     hsn[CCREG]=1;
764     // ...or hash tables
765     hsn[RHASH]=1;
766     hsn[RHTBL]=1;
767   }
768   // Coprocessor load/store needs FTEMP, even if not declared
769   if(dops[i].itype==C2LS) {
770     hsn[FTEMP]=0;
771   }
772   // Load L/R also uses FTEMP as a temporary register
773   if(dops[i].itype==LOADLR) {
774     hsn[FTEMP]=0;
775   }
776   // Also SWL/SWR/SDL/SDR
777   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) {
778     hsn[FTEMP]=0;
779   }
780   // Don't remove the miniht registers
781   if(dops[i].itype==UJUMP||dops[i].itype==RJUMP)
782   {
783     hsn[RHASH]=0;
784     hsn[RHTBL]=0;
785   }
786 }
787
788 // We only want to allocate registers if we're going to use them again soon
789 int needed_again(int r, int i)
790 {
791   int j;
792   int b=-1;
793   int rn=10;
794
795   if (i > 0 && dops[i-1].is_ujump)
796   {
797     if(ba[i-1]<start || ba[i-1]>start+slen*4-4)
798       return 0; // Don't need any registers if exiting the block
799   }
800   for(j=0;j<9;j++)
801   {
802     if(i+j>=slen) {
803       j=slen-i-1;
804       break;
805     }
806     if (dops[i+j].is_ujump)
807     {
808       // Don't go past an unconditonal jump
809       j++;
810       break;
811     }
812     if(dops[i+j].itype==SYSCALL||dops[i+j].itype==HLECALL||dops[i+j].itype==INTCALL||((source[i+j]&0xfc00003f)==0x0d))
813     {
814       break;
815     }
816   }
817   for(;j>=1;j--)
818   {
819     if(dops[i+j].rs1==r) rn=j;
820     if(dops[i+j].rs2==r) rn=j;
821     if((unneeded_reg[i+j]>>r)&1) rn=10;
822     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
823     {
824       b=j;
825     }
826   }
827   if(rn<10) return 1;
828   (void)b;
829   return 0;
830 }
831
832 // Try to match register allocations at the end of a loop with those
833 // at the beginning
834 int loop_reg(int i, int r, int hr)
835 {
836   int j,k;
837   for(j=0;j<9;j++)
838   {
839     if(i+j>=slen) {
840       j=slen-i-1;
841       break;
842     }
843     if (dops[i+j].is_ujump)
844     {
845       // Don't go past an unconditonal jump
846       j++;
847       break;
848     }
849   }
850   k=0;
851   if(i>0){
852     if(dops[i-1].itype==UJUMP||dops[i-1].itype==CJUMP||dops[i-1].itype==SJUMP)
853       k--;
854   }
855   for(;k<j;k++)
856   {
857     assert(r < 64);
858     if((unneeded_reg[i+k]>>r)&1) return hr;
859     if(i+k>=0&&(dops[i+k].itype==UJUMP||dops[i+k].itype==CJUMP||dops[i+k].itype==SJUMP))
860     {
861       if(ba[i+k]>=start && ba[i+k]<(start+i*4))
862       {
863         int t=(ba[i+k]-start)>>2;
864         int reg=get_reg(regs[t].regmap_entry,r);
865         if(reg>=0) return reg;
866         //reg=get_reg(regs[t+1].regmap_entry,r);
867         //if(reg>=0) return reg;
868       }
869     }
870   }
871   return hr;
872 }
873
874
875 // Allocate every register, preserving source/target regs
876 void alloc_all(struct regstat *cur,int i)
877 {
878   int hr;
879
880   for(hr=0;hr<HOST_REGS;hr++) {
881     if(hr!=EXCLUDE_REG) {
882       if(((cur->regmap[hr]&63)!=dops[i].rs1)&&((cur->regmap[hr]&63)!=dops[i].rs2)&&
883          ((cur->regmap[hr]&63)!=dops[i].rt1)&&((cur->regmap[hr]&63)!=dops[i].rt2))
884       {
885         cur->regmap[hr]=-1;
886         cur->dirty&=~(1<<hr);
887       }
888       // Don't need zeros
889       if((cur->regmap[hr]&63)==0)
890       {
891         cur->regmap[hr]=-1;
892         cur->dirty&=~(1<<hr);
893       }
894     }
895   }
896 }
897
898 #ifndef NDEBUG
899 static int host_tempreg_in_use;
900
901 static void host_tempreg_acquire(void)
902 {
903   assert(!host_tempreg_in_use);
904   host_tempreg_in_use = 1;
905 }
906
907 static void host_tempreg_release(void)
908 {
909   host_tempreg_in_use = 0;
910 }
911 #else
912 static void host_tempreg_acquire(void) {}
913 static void host_tempreg_release(void) {}
914 #endif
915
916 #ifdef ASSEM_PRINT
917 extern void gen_interupt();
918 extern void do_insn_cmp();
919 #define FUNCNAME(f) { f, " " #f }
920 static const struct {
921   void *addr;
922   const char *name;
923 } function_names[] = {
924   FUNCNAME(cc_interrupt),
925   FUNCNAME(gen_interupt),
926   FUNCNAME(get_addr_ht),
927   FUNCNAME(get_addr),
928   FUNCNAME(jump_handler_read8),
929   FUNCNAME(jump_handler_read16),
930   FUNCNAME(jump_handler_read32),
931   FUNCNAME(jump_handler_write8),
932   FUNCNAME(jump_handler_write16),
933   FUNCNAME(jump_handler_write32),
934   FUNCNAME(invalidate_addr),
935   FUNCNAME(jump_to_new_pc),
936   FUNCNAME(jump_break),
937   FUNCNAME(jump_break_ds),
938   FUNCNAME(jump_syscall),
939   FUNCNAME(jump_syscall_ds),
940   FUNCNAME(call_gteStall),
941   FUNCNAME(new_dyna_leave),
942   FUNCNAME(pcsx_mtc0),
943   FUNCNAME(pcsx_mtc0_ds),
944 #ifdef DRC_DBG
945   FUNCNAME(do_insn_cmp),
946 #endif
947 #ifdef __arm__
948   FUNCNAME(verify_code),
949 #endif
950 };
951
952 static const char *func_name(const void *a)
953 {
954   int i;
955   for (i = 0; i < sizeof(function_names)/sizeof(function_names[0]); i++)
956     if (function_names[i].addr == a)
957       return function_names[i].name;
958   return "";
959 }
960 #else
961 #define func_name(x) ""
962 #endif
963
964 #ifdef __i386__
965 #include "assem_x86.c"
966 #endif
967 #ifdef __x86_64__
968 #include "assem_x64.c"
969 #endif
970 #ifdef __arm__
971 #include "assem_arm.c"
972 #endif
973 #ifdef __aarch64__
974 #include "assem_arm64.c"
975 #endif
976
977 static void *get_trampoline(const void *f)
978 {
979   size_t i;
980
981   for (i = 0; i < ARRAY_SIZE(ndrc->tramp.f); i++) {
982     if (ndrc->tramp.f[i] == f || ndrc->tramp.f[i] == NULL)
983       break;
984   }
985   if (i == ARRAY_SIZE(ndrc->tramp.f)) {
986     SysPrintf("trampoline table is full, last func %p\n", f);
987     abort();
988   }
989   if (ndrc->tramp.f[i] == NULL) {
990     start_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
991     ndrc->tramp.f[i] = f;
992     end_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
993   }
994   return &ndrc->tramp.ops[i];
995 }
996
997 static void emit_far_jump(const void *f)
998 {
999   if (can_jump_or_call(f)) {
1000     emit_jmp(f);
1001     return;
1002   }
1003
1004   f = get_trampoline(f);
1005   emit_jmp(f);
1006 }
1007
1008 static void emit_far_call(const void *f)
1009 {
1010   if (can_jump_or_call(f)) {
1011     emit_call(f);
1012     return;
1013   }
1014
1015   f = get_trampoline(f);
1016   emit_call(f);
1017 }
1018
1019 // Add virtual address mapping to linked list
1020 void ll_add(struct ll_entry **head,int vaddr,void *addr)
1021 {
1022   struct ll_entry *new_entry;
1023   new_entry=malloc(sizeof(struct ll_entry));
1024   assert(new_entry!=NULL);
1025   new_entry->vaddr=vaddr;
1026   new_entry->reg_sv_flags=0;
1027   new_entry->addr=addr;
1028   new_entry->next=*head;
1029   *head=new_entry;
1030 }
1031
1032 void ll_add_flags(struct ll_entry **head,int vaddr,u_int reg_sv_flags,void *addr)
1033 {
1034   ll_add(head,vaddr,addr);
1035   (*head)->reg_sv_flags=reg_sv_flags;
1036 }
1037
1038 // Check if an address is already compiled
1039 // but don't return addresses which are about to expire from the cache
1040 void *check_addr(u_int vaddr)
1041 {
1042   struct ht_entry *ht_bin = hash_table_get(vaddr);
1043   size_t i;
1044   for (i = 0; i < ARRAY_SIZE(ht_bin->vaddr); i++) {
1045     if (ht_bin->vaddr[i] == vaddr)
1046       if (doesnt_expire_soon((u_char *)ht_bin->tcaddr[i] - MAX_OUTPUT_BLOCK_SIZE))
1047         if (isclean(ht_bin->tcaddr[i]))
1048           return ht_bin->tcaddr[i];
1049   }
1050   u_int page=get_page(vaddr);
1051   struct ll_entry *head;
1052   head=jump_in[page];
1053   while (head != NULL) {
1054     if (head->vaddr == vaddr) {
1055       if (doesnt_expire_soon(head->addr)) {
1056         // Update existing entry with current address
1057         if (ht_bin->vaddr[0] == vaddr) {
1058           ht_bin->tcaddr[0] = head->addr;
1059           return head->addr;
1060         }
1061         if (ht_bin->vaddr[1] == vaddr) {
1062           ht_bin->tcaddr[1] = head->addr;
1063           return head->addr;
1064         }
1065         // Insert into hash table with low priority.
1066         // Don't evict existing entries, as they are probably
1067         // addresses that are being accessed frequently.
1068         if (ht_bin->vaddr[0] == -1) {
1069           ht_bin->vaddr[0] = vaddr;
1070           ht_bin->tcaddr[0] = head->addr;
1071         }
1072         else if (ht_bin->vaddr[1] == -1) {
1073           ht_bin->vaddr[1] = vaddr;
1074           ht_bin->tcaddr[1] = head->addr;
1075         }
1076         return head->addr;
1077       }
1078     }
1079     head=head->next;
1080   }
1081   return 0;
1082 }
1083
1084 void remove_hash(int vaddr)
1085 {
1086   //printf("remove hash: %x\n",vaddr);
1087   struct ht_entry *ht_bin = hash_table_get(vaddr);
1088   if (ht_bin->vaddr[1] == vaddr) {
1089     ht_bin->vaddr[1] = -1;
1090     ht_bin->tcaddr[1] = NULL;
1091   }
1092   if (ht_bin->vaddr[0] == vaddr) {
1093     ht_bin->vaddr[0] = ht_bin->vaddr[1];
1094     ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
1095     ht_bin->vaddr[1] = -1;
1096     ht_bin->tcaddr[1] = NULL;
1097   }
1098 }
1099
1100 static void ll_remove_matching_addrs(struct ll_entry **head,
1101   uintptr_t base_offs_s, int shift)
1102 {
1103   struct ll_entry *next;
1104   while(*head) {
1105     uintptr_t o1 = (u_char *)(*head)->addr - ndrc->translation_cache;
1106     uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
1107     if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s)
1108     {
1109       inv_debug("EXP: Remove pointer to %p (%x)\n",(*head)->addr,(*head)->vaddr);
1110       remove_hash((*head)->vaddr);
1111       next=(*head)->next;
1112       free(*head);
1113       *head=next;
1114     }
1115     else
1116     {
1117       head=&((*head)->next);
1118     }
1119   }
1120 }
1121
1122 // Remove all entries from linked list
1123 void ll_clear(struct ll_entry **head)
1124 {
1125   struct ll_entry *cur;
1126   struct ll_entry *next;
1127   if((cur=*head)) {
1128     *head=0;
1129     while(cur) {
1130       next=cur->next;
1131       free(cur);
1132       cur=next;
1133     }
1134   }
1135 }
1136
1137 // Dereference the pointers and remove if it matches
1138 static void ll_kill_pointers(struct ll_entry *head,
1139   uintptr_t base_offs_s, int shift)
1140 {
1141   while(head) {
1142     u_char *ptr = get_pointer(head->addr);
1143     uintptr_t o1 = ptr - ndrc->translation_cache;
1144     uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
1145     inv_debug("EXP: Lookup pointer to %p at %p (%x)\n",ptr,head->addr,head->vaddr);
1146     if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s)
1147     {
1148       inv_debug("EXP: Kill pointer at %p (%x)\n",head->addr,head->vaddr);
1149       void *host_addr=find_extjump_insn(head->addr);
1150       mark_clear_cache(host_addr);
1151       set_jump_target(host_addr, head->addr);
1152     }
1153     head=head->next;
1154   }
1155 }
1156
1157 // This is called when we write to a compiled block (see do_invstub)
1158 static void invalidate_page(u_int page)
1159 {
1160   struct ll_entry *head;
1161   struct ll_entry *next;
1162   head=jump_in[page];
1163   jump_in[page]=0;
1164   while(head!=NULL) {
1165     inv_debug("INVALIDATE: %x\n",head->vaddr);
1166     remove_hash(head->vaddr);
1167     next=head->next;
1168     free(head);
1169     head=next;
1170   }
1171   head=jump_out[page];
1172   jump_out[page]=0;
1173   while(head!=NULL) {
1174     inv_debug("INVALIDATE: kill pointer to %x (%p)\n",head->vaddr,head->addr);
1175     void *host_addr=find_extjump_insn(head->addr);
1176     mark_clear_cache(host_addr);
1177     set_jump_target(host_addr, head->addr); // point back to dyna_linker
1178     next=head->next;
1179     free(head);
1180     head=next;
1181   }
1182 }
1183
1184 static void invalidate_block_range(u_int block, u_int first, u_int last)
1185 {
1186   u_int page=get_page(block<<12);
1187   //printf("first=%d last=%d\n",first,last);
1188   invalidate_page(page);
1189   assert(first+5>page); // NB: this assumes MAXBLOCK<=4096 (4 pages)
1190   assert(last<page+5);
1191   // Invalidate the adjacent pages if a block crosses a 4K boundary
1192   while(first<page) {
1193     invalidate_page(first);
1194     first++;
1195   }
1196   for(first=page+1;first<last;first++) {
1197     invalidate_page(first);
1198   }
1199   do_clear_cache();
1200
1201   // Don't trap writes
1202   invalid_code[block]=1;
1203
1204   #ifdef USE_MINI_HT
1205   memset(mini_ht,-1,sizeof(mini_ht));
1206   #endif
1207 }
1208
1209 void invalidate_block(u_int block)
1210 {
1211   u_int page=get_page(block<<12);
1212   u_int vpage=get_vpage(block<<12);
1213   inv_debug("INVALIDATE: %x (%d)\n",block<<12,page);
1214   //inv_debug("invalid_code[block]=%d\n",invalid_code[block]);
1215   u_int first,last;
1216   first=last=page;
1217   struct ll_entry *head;
1218   head=jump_dirty[vpage];
1219   //printf("page=%d vpage=%d\n",page,vpage);
1220   while(head!=NULL) {
1221     if(vpage>2047||(head->vaddr>>12)==block) { // Ignore vaddr hash collision
1222       u_char *start, *end;
1223       get_bounds(head->addr, &start, &end);
1224       //printf("start: %p end: %p\n", start, end);
1225       if (page < 2048 && start >= rdram && end < rdram+RAM_SIZE) {
1226         if (((start-rdram)>>12) <= page && ((end-1-rdram)>>12) >= page) {
1227           if ((((start-rdram)>>12)&2047) < first) first = ((start-rdram)>>12)&2047;
1228           if ((((end-1-rdram)>>12)&2047) > last)  last = ((end-1-rdram)>>12)&2047;
1229         }
1230       }
1231     }
1232     head=head->next;
1233   }
1234   invalidate_block_range(block,first,last);
1235 }
1236
1237 void invalidate_addr(u_int addr)
1238 {
1239   //static int rhits;
1240   // this check is done by the caller
1241   //if (inv_code_start<=addr&&addr<=inv_code_end) { rhits++; return; }
1242   u_int page=get_vpage(addr);
1243   if(page<2048) { // RAM
1244     struct ll_entry *head;
1245     u_int addr_min=~0, addr_max=0;
1246     u_int mask=RAM_SIZE-1;
1247     u_int addr_main=0x80000000|(addr&mask);
1248     int pg1;
1249     inv_code_start=addr_main&~0xfff;
1250     inv_code_end=addr_main|0xfff;
1251     pg1=page;
1252     if (pg1>0) {
1253       // must check previous page too because of spans..
1254       pg1--;
1255       inv_code_start-=0x1000;
1256     }
1257     for(;pg1<=page;pg1++) {
1258       for(head=jump_dirty[pg1];head!=NULL;head=head->next) {
1259         u_char *start_h, *end_h;
1260         u_int start, end;
1261         get_bounds(head->addr, &start_h, &end_h);
1262         start = (uintptr_t)start_h - ram_offset;
1263         end = (uintptr_t)end_h - ram_offset;
1264         if(start<=addr_main&&addr_main<end) {
1265           if(start<addr_min) addr_min=start;
1266           if(end>addr_max) addr_max=end;
1267         }
1268         else if(addr_main<start) {
1269           if(start<inv_code_end)
1270             inv_code_end=start-1;
1271         }
1272         else {
1273           if(end>inv_code_start)
1274             inv_code_start=end;
1275         }
1276       }
1277     }
1278     if (addr_min!=~0) {
1279       inv_debug("INV ADDR: %08x hit %08x-%08x\n", addr, addr_min, addr_max);
1280       inv_code_start=inv_code_end=~0;
1281       invalidate_block_range(addr>>12,(addr_min&mask)>>12,(addr_max&mask)>>12);
1282       return;
1283     }
1284     else {
1285       inv_code_start=(addr&~mask)|(inv_code_start&mask);
1286       inv_code_end=(addr&~mask)|(inv_code_end&mask);
1287       inv_debug("INV ADDR: %08x miss, inv %08x-%08x, sk %d\n", addr, inv_code_start, inv_code_end, 0);
1288       return;
1289     }
1290   }
1291   invalidate_block(addr>>12);
1292 }
1293
1294 // This is called when loading a save state.
1295 // Anything could have changed, so invalidate everything.
1296 void invalidate_all_pages(void)
1297 {
1298   u_int page;
1299   for(page=0;page<4096;page++)
1300     invalidate_page(page);
1301   for(page=0;page<1048576;page++)
1302     if(!invalid_code[page]) {
1303       restore_candidate[(page&2047)>>3]|=1<<(page&7);
1304       restore_candidate[((page&2047)>>3)+256]|=1<<(page&7);
1305     }
1306   #ifdef USE_MINI_HT
1307   memset(mini_ht,-1,sizeof(mini_ht));
1308   #endif
1309   do_clear_cache();
1310 }
1311
1312 static void do_invstub(int n)
1313 {
1314   literal_pool(20);
1315   u_int reglist=stubs[n].a;
1316   set_jump_target(stubs[n].addr, out);
1317   save_regs(reglist);
1318   if(stubs[n].b!=0) emit_mov(stubs[n].b,0);
1319   emit_far_call(invalidate_addr);
1320   restore_regs(reglist);
1321   emit_jmp(stubs[n].retaddr); // return address
1322 }
1323
1324 // Add an entry to jump_out after making a link
1325 // src should point to code by emit_extjump2()
1326 void add_jump_out(u_int vaddr,void *src)
1327 {
1328   u_int page=get_page(vaddr);
1329   inv_debug("add_jump_out: %p -> %x (%d)\n",src,vaddr,page);
1330   check_extjump2(src);
1331   ll_add(jump_out+page,vaddr,src);
1332   //inv_debug("add_jump_out:  to %p\n",get_pointer(src));
1333 }
1334
1335 // If a code block was found to be unmodified (bit was set in
1336 // restore_candidate) and it remains unmodified (bit is clear
1337 // in invalid_code) then move the entries for that 4K page from
1338 // the dirty list to the clean list.
1339 void clean_blocks(u_int page)
1340 {
1341   struct ll_entry *head;
1342   inv_debug("INV: clean_blocks page=%d\n",page);
1343   head=jump_dirty[page];
1344   while(head!=NULL) {
1345     if(!invalid_code[head->vaddr>>12]) {
1346       // Don't restore blocks which are about to expire from the cache
1347       if (doesnt_expire_soon(head->addr)) {
1348         if(verify_dirty(head->addr)) {
1349           u_char *start, *end;
1350           //printf("Possibly Restore %x (%p)\n",head->vaddr, head->addr);
1351           u_int i;
1352           u_int inv=0;
1353           get_bounds(head->addr, &start, &end);
1354           if (start - rdram < RAM_SIZE) {
1355             for (i = (start-rdram+0x80000000)>>12; i <= (end-1-rdram+0x80000000)>>12; i++) {
1356               inv|=invalid_code[i];
1357             }
1358           }
1359           else if((signed int)head->vaddr>=(signed int)0x80000000+RAM_SIZE) {
1360             inv=1;
1361           }
1362           if(!inv) {
1363             void *clean_addr = get_clean_addr(head->addr);
1364             if (doesnt_expire_soon(clean_addr)) {
1365               u_int ppage=page;
1366               inv_debug("INV: Restored %x (%p/%p)\n",head->vaddr, head->addr, clean_addr);
1367               //printf("page=%x, addr=%x\n",page,head->vaddr);
1368               //assert(head->vaddr>>12==(page|0x80000));
1369               ll_add_flags(jump_in+ppage,head->vaddr,head->reg_sv_flags,clean_addr);
1370               struct ht_entry *ht_bin = hash_table_get(head->vaddr);
1371               if (ht_bin->vaddr[0] == head->vaddr)
1372                 ht_bin->tcaddr[0] = clean_addr; // Replace existing entry
1373               if (ht_bin->vaddr[1] == head->vaddr)
1374                 ht_bin->tcaddr[1] = clean_addr; // Replace existing entry
1375             }
1376           }
1377         }
1378       }
1379     }
1380     head=head->next;
1381   }
1382 }
1383
1384 /* Register allocation */
1385
1386 // Note: registers are allocated clean (unmodified state)
1387 // if you intend to modify the register, you must call dirty_reg().
1388 static void alloc_reg(struct regstat *cur,int i,signed char reg)
1389 {
1390   int r,hr;
1391   int preferred_reg = PREFERRED_REG_FIRST
1392     + reg % (PREFERRED_REG_LAST - PREFERRED_REG_FIRST + 1);
1393   if (reg == CCREG) preferred_reg = HOST_CCREG;
1394   if (reg == PTEMP || reg == FTEMP) preferred_reg = 12;
1395   assert(PREFERRED_REG_FIRST != EXCLUDE_REG && EXCLUDE_REG != HOST_REGS);
1396
1397   // Don't allocate unused registers
1398   if((cur->u>>reg)&1) return;
1399
1400   // see if it's already allocated
1401   for(hr=0;hr<HOST_REGS;hr++)
1402   {
1403     if(cur->regmap[hr]==reg) return;
1404   }
1405
1406   // Keep the same mapping if the register was already allocated in a loop
1407   preferred_reg = loop_reg(i,reg,preferred_reg);
1408
1409   // Try to allocate the preferred register
1410   if(cur->regmap[preferred_reg]==-1) {
1411     cur->regmap[preferred_reg]=reg;
1412     cur->dirty&=~(1<<preferred_reg);
1413     cur->isconst&=~(1<<preferred_reg);
1414     return;
1415   }
1416   r=cur->regmap[preferred_reg];
1417   assert(r < 64);
1418   if((cur->u>>r)&1) {
1419     cur->regmap[preferred_reg]=reg;
1420     cur->dirty&=~(1<<preferred_reg);
1421     cur->isconst&=~(1<<preferred_reg);
1422     return;
1423   }
1424
1425   // Clear any unneeded registers
1426   // We try to keep the mapping consistent, if possible, because it
1427   // makes branches easier (especially loops).  So we try to allocate
1428   // first (see above) before removing old mappings.  If this is not
1429   // possible then go ahead and clear out the registers that are no
1430   // longer needed.
1431   for(hr=0;hr<HOST_REGS;hr++)
1432   {
1433     r=cur->regmap[hr];
1434     if(r>=0) {
1435       assert(r < 64);
1436       if((cur->u>>r)&1) {cur->regmap[hr]=-1;break;}
1437     }
1438   }
1439
1440   // Try to allocate any available register, but prefer
1441   // registers that have not been used recently.
1442   if (i > 0) {
1443     for (hr = PREFERRED_REG_FIRST; ; ) {
1444       if (cur->regmap[hr] < 0) {
1445         int oldreg = regs[i-1].regmap[hr];
1446         if (oldreg < 0 || (oldreg != dops[i-1].rs1 && oldreg != dops[i-1].rs2
1447              && oldreg != dops[i-1].rt1 && oldreg != dops[i-1].rt2))
1448         {
1449           cur->regmap[hr]=reg;
1450           cur->dirty&=~(1<<hr);
1451           cur->isconst&=~(1<<hr);
1452           return;
1453         }
1454       }
1455       hr++;
1456       if (hr == EXCLUDE_REG)
1457         hr++;
1458       if (hr == HOST_REGS)
1459         hr = 0;
1460       if (hr == PREFERRED_REG_FIRST)
1461         break;
1462     }
1463   }
1464
1465   // Try to allocate any available register
1466   for (hr = PREFERRED_REG_FIRST; ; ) {
1467     if (cur->regmap[hr] < 0) {
1468       cur->regmap[hr]=reg;
1469       cur->dirty&=~(1<<hr);
1470       cur->isconst&=~(1<<hr);
1471       return;
1472     }
1473     hr++;
1474     if (hr == EXCLUDE_REG)
1475       hr++;
1476     if (hr == HOST_REGS)
1477       hr = 0;
1478     if (hr == PREFERRED_REG_FIRST)
1479       break;
1480   }
1481
1482   // Ok, now we have to evict someone
1483   // Pick a register we hopefully won't need soon
1484   u_char hsn[MAXREG+1];
1485   memset(hsn,10,sizeof(hsn));
1486   int j;
1487   lsn(hsn,i,&preferred_reg);
1488   //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]);
1489   //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]);
1490   if(i>0) {
1491     // Don't evict the cycle count at entry points, otherwise the entry
1492     // stub will have to write it.
1493     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1494     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1495     for(j=10;j>=3;j--)
1496     {
1497       // Alloc preferred register if available
1498       if(hsn[r=cur->regmap[preferred_reg]&63]==j) {
1499         for(hr=0;hr<HOST_REGS;hr++) {
1500           // Evict both parts of a 64-bit register
1501           if((cur->regmap[hr]&63)==r) {
1502             cur->regmap[hr]=-1;
1503             cur->dirty&=~(1<<hr);
1504             cur->isconst&=~(1<<hr);
1505           }
1506         }
1507         cur->regmap[preferred_reg]=reg;
1508         return;
1509       }
1510       for(r=1;r<=MAXREG;r++)
1511       {
1512         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1513           for(hr=0;hr<HOST_REGS;hr++) {
1514             if(hr!=HOST_CCREG||j<hsn[CCREG]) {
1515               if(cur->regmap[hr]==r) {
1516                 cur->regmap[hr]=reg;
1517                 cur->dirty&=~(1<<hr);
1518                 cur->isconst&=~(1<<hr);
1519                 return;
1520               }
1521             }
1522           }
1523         }
1524       }
1525     }
1526   }
1527   for(j=10;j>=0;j--)
1528   {
1529     for(r=1;r<=MAXREG;r++)
1530     {
1531       if(hsn[r]==j) {
1532         for(hr=0;hr<HOST_REGS;hr++) {
1533           if(cur->regmap[hr]==r) {
1534             cur->regmap[hr]=reg;
1535             cur->dirty&=~(1<<hr);
1536             cur->isconst&=~(1<<hr);
1537             return;
1538           }
1539         }
1540       }
1541     }
1542   }
1543   SysPrintf("This shouldn't happen (alloc_reg)");abort();
1544 }
1545
1546 // Allocate a temporary register.  This is done without regard to
1547 // dirty status or whether the register we request is on the unneeded list
1548 // Note: This will only allocate one register, even if called multiple times
1549 static void alloc_reg_temp(struct regstat *cur,int i,signed char reg)
1550 {
1551   int r,hr;
1552   int preferred_reg = -1;
1553
1554   // see if it's already allocated
1555   for(hr=0;hr<HOST_REGS;hr++)
1556   {
1557     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==reg) return;
1558   }
1559
1560   // Try to allocate any available register
1561   for(hr=HOST_REGS-1;hr>=0;hr--) {
1562     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1563       cur->regmap[hr]=reg;
1564       cur->dirty&=~(1<<hr);
1565       cur->isconst&=~(1<<hr);
1566       return;
1567     }
1568   }
1569
1570   // Find an unneeded register
1571   for(hr=HOST_REGS-1;hr>=0;hr--)
1572   {
1573     r=cur->regmap[hr];
1574     if(r>=0) {
1575       assert(r < 64);
1576       if((cur->u>>r)&1) {
1577         if(i==0||((unneeded_reg[i-1]>>r)&1)) {
1578           cur->regmap[hr]=reg;
1579           cur->dirty&=~(1<<hr);
1580           cur->isconst&=~(1<<hr);
1581           return;
1582         }
1583       }
1584     }
1585   }
1586
1587   // Ok, now we have to evict someone
1588   // Pick a register we hopefully won't need soon
1589   // TODO: we might want to follow unconditional jumps here
1590   // TODO: get rid of dupe code and make this into a function
1591   u_char hsn[MAXREG+1];
1592   memset(hsn,10,sizeof(hsn));
1593   int j;
1594   lsn(hsn,i,&preferred_reg);
1595   //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]);
1596   if(i>0) {
1597     // Don't evict the cycle count at entry points, otherwise the entry
1598     // stub will have to write it.
1599     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1600     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1601     for(j=10;j>=3;j--)
1602     {
1603       for(r=1;r<=MAXREG;r++)
1604       {
1605         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1606           for(hr=0;hr<HOST_REGS;hr++) {
1607             if(hr!=HOST_CCREG||hsn[CCREG]>2) {
1608               if(cur->regmap[hr]==r) {
1609                 cur->regmap[hr]=reg;
1610                 cur->dirty&=~(1<<hr);
1611                 cur->isconst&=~(1<<hr);
1612                 return;
1613               }
1614             }
1615           }
1616         }
1617       }
1618     }
1619   }
1620   for(j=10;j>=0;j--)
1621   {
1622     for(r=1;r<=MAXREG;r++)
1623     {
1624       if(hsn[r]==j) {
1625         for(hr=0;hr<HOST_REGS;hr++) {
1626           if(cur->regmap[hr]==r) {
1627             cur->regmap[hr]=reg;
1628             cur->dirty&=~(1<<hr);
1629             cur->isconst&=~(1<<hr);
1630             return;
1631           }
1632         }
1633       }
1634     }
1635   }
1636   SysPrintf("This shouldn't happen");abort();
1637 }
1638
1639 static void mov_alloc(struct regstat *current,int i)
1640 {
1641   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) {
1642     alloc_cc(current,i); // for stalls
1643     dirty_reg(current,CCREG);
1644   }
1645
1646   // Note: Don't need to actually alloc the source registers
1647   //alloc_reg(current,i,dops[i].rs1);
1648   alloc_reg(current,i,dops[i].rt1);
1649
1650   clear_const(current,dops[i].rs1);
1651   clear_const(current,dops[i].rt1);
1652   dirty_reg(current,dops[i].rt1);
1653 }
1654
1655 static void shiftimm_alloc(struct regstat *current,int i)
1656 {
1657   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
1658   {
1659     if(dops[i].rt1) {
1660       if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1661       else dops[i].lt1=dops[i].rs1;
1662       alloc_reg(current,i,dops[i].rt1);
1663       dirty_reg(current,dops[i].rt1);
1664       if(is_const(current,dops[i].rs1)) {
1665         int v=get_const(current,dops[i].rs1);
1666         if(dops[i].opcode2==0x00) set_const(current,dops[i].rt1,v<<imm[i]);
1667         if(dops[i].opcode2==0x02) set_const(current,dops[i].rt1,(u_int)v>>imm[i]);
1668         if(dops[i].opcode2==0x03) set_const(current,dops[i].rt1,v>>imm[i]);
1669       }
1670       else clear_const(current,dops[i].rt1);
1671     }
1672   }
1673   else
1674   {
1675     clear_const(current,dops[i].rs1);
1676     clear_const(current,dops[i].rt1);
1677   }
1678
1679   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
1680   {
1681     assert(0);
1682   }
1683   if(dops[i].opcode2==0x3c) // DSLL32
1684   {
1685     assert(0);
1686   }
1687   if(dops[i].opcode2==0x3e) // DSRL32
1688   {
1689     assert(0);
1690   }
1691   if(dops[i].opcode2==0x3f) // DSRA32
1692   {
1693     assert(0);
1694   }
1695 }
1696
1697 static void shift_alloc(struct regstat *current,int i)
1698 {
1699   if(dops[i].rt1) {
1700     if(dops[i].opcode2<=0x07) // SLLV/SRLV/SRAV
1701     {
1702       if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
1703       if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
1704       alloc_reg(current,i,dops[i].rt1);
1705       if(dops[i].rt1==dops[i].rs2) {
1706         alloc_reg_temp(current,i,-1);
1707         minimum_free_regs[i]=1;
1708       }
1709     } else { // DSLLV/DSRLV/DSRAV
1710       assert(0);
1711     }
1712     clear_const(current,dops[i].rs1);
1713     clear_const(current,dops[i].rs2);
1714     clear_const(current,dops[i].rt1);
1715     dirty_reg(current,dops[i].rt1);
1716   }
1717 }
1718
1719 static void alu_alloc(struct regstat *current,int i)
1720 {
1721   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
1722     if(dops[i].rt1) {
1723       if(dops[i].rs1&&dops[i].rs2) {
1724         alloc_reg(current,i,dops[i].rs1);
1725         alloc_reg(current,i,dops[i].rs2);
1726       }
1727       else {
1728         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1729         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1730       }
1731       alloc_reg(current,i,dops[i].rt1);
1732     }
1733   }
1734   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
1735     if(dops[i].rt1) {
1736       alloc_reg(current,i,dops[i].rs1);
1737       alloc_reg(current,i,dops[i].rs2);
1738       alloc_reg(current,i,dops[i].rt1);
1739     }
1740   }
1741   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
1742     if(dops[i].rt1) {
1743       if(dops[i].rs1&&dops[i].rs2) {
1744         alloc_reg(current,i,dops[i].rs1);
1745         alloc_reg(current,i,dops[i].rs2);
1746       }
1747       else
1748       {
1749         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1750         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1751       }
1752       alloc_reg(current,i,dops[i].rt1);
1753     }
1754   }
1755   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
1756     assert(0);
1757   }
1758   clear_const(current,dops[i].rs1);
1759   clear_const(current,dops[i].rs2);
1760   clear_const(current,dops[i].rt1);
1761   dirty_reg(current,dops[i].rt1);
1762 }
1763
1764 static void imm16_alloc(struct regstat *current,int i)
1765 {
1766   if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1767   else dops[i].lt1=dops[i].rs1;
1768   if(dops[i].rt1) alloc_reg(current,i,dops[i].rt1);
1769   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
1770     assert(0);
1771   }
1772   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
1773     clear_const(current,dops[i].rs1);
1774     clear_const(current,dops[i].rt1);
1775   }
1776   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
1777     if(is_const(current,dops[i].rs1)) {
1778       int v=get_const(current,dops[i].rs1);
1779       if(dops[i].opcode==0x0c) set_const(current,dops[i].rt1,v&imm[i]);
1780       if(dops[i].opcode==0x0d) set_const(current,dops[i].rt1,v|imm[i]);
1781       if(dops[i].opcode==0x0e) set_const(current,dops[i].rt1,v^imm[i]);
1782     }
1783     else clear_const(current,dops[i].rt1);
1784   }
1785   else if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
1786     if(is_const(current,dops[i].rs1)) {
1787       int v=get_const(current,dops[i].rs1);
1788       set_const(current,dops[i].rt1,v+imm[i]);
1789     }
1790     else clear_const(current,dops[i].rt1);
1791   }
1792   else {
1793     set_const(current,dops[i].rt1,imm[i]<<16); // LUI
1794   }
1795   dirty_reg(current,dops[i].rt1);
1796 }
1797
1798 static void load_alloc(struct regstat *current,int i)
1799 {
1800   clear_const(current,dops[i].rt1);
1801   //if(dops[i].rs1!=dops[i].rt1&&needed_again(dops[i].rs1,i)) clear_const(current,dops[i].rs1); // Does this help or hurt?
1802   if(!dops[i].rs1) current->u&=~1LL; // Allow allocating r0 if it's the source register
1803   if (needed_again(dops[i].rs1, i))
1804     alloc_reg(current, i, dops[i].rs1);
1805   if (ram_offset)
1806     alloc_reg(current, i, ROREG);
1807   if(dops[i].rt1&&!((current->u>>dops[i].rt1)&1)) {
1808     alloc_reg(current,i,dops[i].rt1);
1809     assert(get_reg(current->regmap,dops[i].rt1)>=0);
1810     if(dops[i].opcode==0x27||dops[i].opcode==0x37) // LWU/LD
1811     {
1812       assert(0);
1813     }
1814     else if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
1815     {
1816       assert(0);
1817     }
1818     dirty_reg(current,dops[i].rt1);
1819     // LWL/LWR need a temporary register for the old value
1820     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
1821     {
1822       alloc_reg(current,i,FTEMP);
1823       alloc_reg_temp(current,i,-1);
1824       minimum_free_regs[i]=1;
1825     }
1826   }
1827   else
1828   {
1829     // Load to r0 or unneeded register (dummy load)
1830     // but we still need a register to calculate the address
1831     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
1832     {
1833       alloc_reg(current,i,FTEMP); // LWL/LWR need another temporary
1834     }
1835     alloc_reg_temp(current,i,-1);
1836     minimum_free_regs[i]=1;
1837     if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
1838     {
1839       assert(0);
1840     }
1841   }
1842 }
1843
1844 void store_alloc(struct regstat *current,int i)
1845 {
1846   clear_const(current,dops[i].rs2);
1847   if(!(dops[i].rs2)) current->u&=~1LL; // Allow allocating r0 if necessary
1848   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1849   alloc_reg(current,i,dops[i].rs2);
1850   if(dops[i].opcode==0x2c||dops[i].opcode==0x2d||dops[i].opcode==0x3f) { // 64-bit SDL/SDR/SD
1851     assert(0);
1852   }
1853   if (ram_offset)
1854     alloc_reg(current, i, ROREG);
1855   #if defined(HOST_IMM8)
1856   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1857   alloc_reg(current, i, INVCP);
1858   #endif
1859   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) { // SWL/SWL/SDL/SDR
1860     alloc_reg(current,i,FTEMP);
1861   }
1862   // We need a temporary register for address generation
1863   alloc_reg_temp(current,i,-1);
1864   minimum_free_regs[i]=1;
1865 }
1866
1867 void c1ls_alloc(struct regstat *current,int i)
1868 {
1869   clear_const(current,dops[i].rt1);
1870   alloc_reg(current,i,CSREG); // Status
1871 }
1872
1873 void c2ls_alloc(struct regstat *current,int i)
1874 {
1875   clear_const(current,dops[i].rt1);
1876   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1877   alloc_reg(current,i,FTEMP);
1878   if (ram_offset)
1879     alloc_reg(current, i, ROREG);
1880   #if defined(HOST_IMM8)
1881   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1882   if (dops[i].opcode == 0x3a) // SWC2
1883     alloc_reg(current,i,INVCP);
1884   #endif
1885   // We need a temporary register for address generation
1886   alloc_reg_temp(current,i,-1);
1887   minimum_free_regs[i]=1;
1888 }
1889
1890 #ifndef multdiv_alloc
1891 void multdiv_alloc(struct regstat *current,int i)
1892 {
1893   //  case 0x18: MULT
1894   //  case 0x19: MULTU
1895   //  case 0x1A: DIV
1896   //  case 0x1B: DIVU
1897   //  case 0x1C: DMULT
1898   //  case 0x1D: DMULTU
1899   //  case 0x1E: DDIV
1900   //  case 0x1F: DDIVU
1901   clear_const(current,dops[i].rs1);
1902   clear_const(current,dops[i].rs2);
1903   alloc_cc(current,i); // for stalls
1904   if(dops[i].rs1&&dops[i].rs2)
1905   {
1906     if((dops[i].opcode2&4)==0) // 32-bit
1907     {
1908       current->u&=~(1LL<<HIREG);
1909       current->u&=~(1LL<<LOREG);
1910       alloc_reg(current,i,HIREG);
1911       alloc_reg(current,i,LOREG);
1912       alloc_reg(current,i,dops[i].rs1);
1913       alloc_reg(current,i,dops[i].rs2);
1914       dirty_reg(current,HIREG);
1915       dirty_reg(current,LOREG);
1916     }
1917     else // 64-bit
1918     {
1919       assert(0);
1920     }
1921   }
1922   else
1923   {
1924     // Multiply by zero is zero.
1925     // MIPS does not have a divide by zero exception.
1926     // The result is undefined, we return zero.
1927     alloc_reg(current,i,HIREG);
1928     alloc_reg(current,i,LOREG);
1929     dirty_reg(current,HIREG);
1930     dirty_reg(current,LOREG);
1931   }
1932 }
1933 #endif
1934
1935 void cop0_alloc(struct regstat *current,int i)
1936 {
1937   if(dops[i].opcode2==0) // MFC0
1938   {
1939     if(dops[i].rt1) {
1940       clear_const(current,dops[i].rt1);
1941       alloc_all(current,i);
1942       alloc_reg(current,i,dops[i].rt1);
1943       dirty_reg(current,dops[i].rt1);
1944     }
1945   }
1946   else if(dops[i].opcode2==4) // MTC0
1947   {
1948     if(dops[i].rs1){
1949       clear_const(current,dops[i].rs1);
1950       alloc_reg(current,i,dops[i].rs1);
1951       alloc_all(current,i);
1952     }
1953     else {
1954       alloc_all(current,i); // FIXME: Keep r0
1955       current->u&=~1LL;
1956       alloc_reg(current,i,0);
1957     }
1958   }
1959   else
1960   {
1961     // TLBR/TLBWI/TLBWR/TLBP/ERET
1962     assert(dops[i].opcode2==0x10);
1963     alloc_all(current,i);
1964   }
1965   minimum_free_regs[i]=HOST_REGS;
1966 }
1967
1968 static void cop2_alloc(struct regstat *current,int i)
1969 {
1970   if (dops[i].opcode2 < 3) // MFC2/CFC2
1971   {
1972     alloc_cc(current,i); // for stalls
1973     dirty_reg(current,CCREG);
1974     if(dops[i].rt1){
1975       clear_const(current,dops[i].rt1);
1976       alloc_reg(current,i,dops[i].rt1);
1977       dirty_reg(current,dops[i].rt1);
1978     }
1979   }
1980   else if (dops[i].opcode2 > 3) // MTC2/CTC2
1981   {
1982     if(dops[i].rs1){
1983       clear_const(current,dops[i].rs1);
1984       alloc_reg(current,i,dops[i].rs1);
1985     }
1986     else {
1987       current->u&=~1LL;
1988       alloc_reg(current,i,0);
1989     }
1990   }
1991   alloc_reg_temp(current,i,-1);
1992   minimum_free_regs[i]=1;
1993 }
1994
1995 void c2op_alloc(struct regstat *current,int i)
1996 {
1997   alloc_cc(current,i); // for stalls
1998   dirty_reg(current,CCREG);
1999   alloc_reg_temp(current,i,-1);
2000 }
2001
2002 void syscall_alloc(struct regstat *current,int i)
2003 {
2004   alloc_cc(current,i);
2005   dirty_reg(current,CCREG);
2006   alloc_all(current,i);
2007   minimum_free_regs[i]=HOST_REGS;
2008   current->isconst=0;
2009 }
2010
2011 void delayslot_alloc(struct regstat *current,int i)
2012 {
2013   switch(dops[i].itype) {
2014     case UJUMP:
2015     case CJUMP:
2016     case SJUMP:
2017     case RJUMP:
2018     case SYSCALL:
2019     case HLECALL:
2020     case SPAN:
2021       assem_debug("jump in the delay slot.  this shouldn't happen.\n");//abort();
2022       SysPrintf("Disabled speculative precompilation\n");
2023       stop_after_jal=1;
2024       break;
2025     case IMM16:
2026       imm16_alloc(current,i);
2027       break;
2028     case LOAD:
2029     case LOADLR:
2030       load_alloc(current,i);
2031       break;
2032     case STORE:
2033     case STORELR:
2034       store_alloc(current,i);
2035       break;
2036     case ALU:
2037       alu_alloc(current,i);
2038       break;
2039     case SHIFT:
2040       shift_alloc(current,i);
2041       break;
2042     case MULTDIV:
2043       multdiv_alloc(current,i);
2044       break;
2045     case SHIFTIMM:
2046       shiftimm_alloc(current,i);
2047       break;
2048     case MOV:
2049       mov_alloc(current,i);
2050       break;
2051     case COP0:
2052       cop0_alloc(current,i);
2053       break;
2054     case COP1:
2055       break;
2056     case COP2:
2057       cop2_alloc(current,i);
2058       break;
2059     case C1LS:
2060       c1ls_alloc(current,i);
2061       break;
2062     case C2LS:
2063       c2ls_alloc(current,i);
2064       break;
2065     case C2OP:
2066       c2op_alloc(current,i);
2067       break;
2068   }
2069 }
2070
2071 // Special case where a branch and delay slot span two pages in virtual memory
2072 static void pagespan_alloc(struct regstat *current,int i)
2073 {
2074   current->isconst=0;
2075   current->wasconst=0;
2076   regs[i].wasconst=0;
2077   minimum_free_regs[i]=HOST_REGS;
2078   alloc_all(current,i);
2079   alloc_cc(current,i);
2080   dirty_reg(current,CCREG);
2081   if(dops[i].opcode==3) // JAL
2082   {
2083     alloc_reg(current,i,31);
2084     dirty_reg(current,31);
2085   }
2086   if(dops[i].opcode==0&&(dops[i].opcode2&0x3E)==8) // JR/JALR
2087   {
2088     alloc_reg(current,i,dops[i].rs1);
2089     if (dops[i].rt1!=0) {
2090       alloc_reg(current,i,dops[i].rt1);
2091       dirty_reg(current,dops[i].rt1);
2092     }
2093   }
2094   if((dops[i].opcode&0x2E)==4) // BEQ/BNE/BEQL/BNEL
2095   {
2096     if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
2097     if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
2098   }
2099   else
2100   if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ/BLEZL/BGTZL
2101   {
2102     if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
2103   }
2104   //else ...
2105 }
2106
2107 static void add_stub(enum stub_type type, void *addr, void *retaddr,
2108   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e)
2109 {
2110   assert(stubcount < ARRAY_SIZE(stubs));
2111   stubs[stubcount].type = type;
2112   stubs[stubcount].addr = addr;
2113   stubs[stubcount].retaddr = retaddr;
2114   stubs[stubcount].a = a;
2115   stubs[stubcount].b = b;
2116   stubs[stubcount].c = c;
2117   stubs[stubcount].d = d;
2118   stubs[stubcount].e = e;
2119   stubcount++;
2120 }
2121
2122 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
2123   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist)
2124 {
2125   add_stub(type, addr, retaddr, i, addr_reg, (uintptr_t)i_regs, ccadj, reglist);
2126 }
2127
2128 // Write out a single register
2129 static void wb_register(signed char r, const signed char regmap[], uint64_t dirty)
2130 {
2131   int hr;
2132   for(hr=0;hr<HOST_REGS;hr++) {
2133     if(hr!=EXCLUDE_REG) {
2134       if((regmap[hr]&63)==r) {
2135         if((dirty>>hr)&1) {
2136           assert(regmap[hr]<64);
2137           emit_storereg(r,hr);
2138         }
2139       }
2140     }
2141   }
2142 }
2143
2144 static void wb_valid(signed char pre[],signed char entry[],u_int dirty_pre,u_int dirty,uint64_t u)
2145 {
2146   //if(dirty_pre==dirty) return;
2147   int hr,reg;
2148   for(hr=0;hr<HOST_REGS;hr++) {
2149     if(hr!=EXCLUDE_REG) {
2150       reg=pre[hr];
2151       if(((~u)>>(reg&63))&1) {
2152         if(reg>0) {
2153           if(((dirty_pre&~dirty)>>hr)&1) {
2154             if(reg>0&&reg<34) {
2155               emit_storereg(reg,hr);
2156             }
2157             else if(reg>=64) {
2158               assert(0);
2159             }
2160           }
2161         }
2162       }
2163     }
2164   }
2165 }
2166
2167 // trashes r2
2168 static void pass_args(int a0, int a1)
2169 {
2170   if(a0==1&&a1==0) {
2171     // must swap
2172     emit_mov(a0,2); emit_mov(a1,1); emit_mov(2,0);
2173   }
2174   else if(a0!=0&&a1==0) {
2175     emit_mov(a1,1);
2176     if (a0>=0) emit_mov(a0,0);
2177   }
2178   else {
2179     if(a0>=0&&a0!=0) emit_mov(a0,0);
2180     if(a1>=0&&a1!=1) emit_mov(a1,1);
2181   }
2182 }
2183
2184 static void alu_assemble(int i, const struct regstat *i_regs)
2185 {
2186   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
2187     if(dops[i].rt1) {
2188       signed char s1,s2,t;
2189       t=get_reg(i_regs->regmap,dops[i].rt1);
2190       if(t>=0) {
2191         s1=get_reg(i_regs->regmap,dops[i].rs1);
2192         s2=get_reg(i_regs->regmap,dops[i].rs2);
2193         if(dops[i].rs1&&dops[i].rs2) {
2194           assert(s1>=0);
2195           assert(s2>=0);
2196           if(dops[i].opcode2&2) emit_sub(s1,s2,t);
2197           else emit_add(s1,s2,t);
2198         }
2199         else if(dops[i].rs1) {
2200           if(s1>=0) emit_mov(s1,t);
2201           else emit_loadreg(dops[i].rs1,t);
2202         }
2203         else if(dops[i].rs2) {
2204           if(s2>=0) {
2205             if(dops[i].opcode2&2) emit_neg(s2,t);
2206             else emit_mov(s2,t);
2207           }
2208           else {
2209             emit_loadreg(dops[i].rs2,t);
2210             if(dops[i].opcode2&2) emit_neg(t,t);
2211           }
2212         }
2213         else emit_zeroreg(t);
2214       }
2215     }
2216   }
2217   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
2218     assert(0);
2219   }
2220   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
2221     if(dops[i].rt1) {
2222       signed char s1l,s2l,t;
2223       {
2224         t=get_reg(i_regs->regmap,dops[i].rt1);
2225         //assert(t>=0);
2226         if(t>=0) {
2227           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2228           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2229           if(dops[i].rs2==0) // rx<r0
2230           {
2231             if(dops[i].opcode2==0x2a&&dops[i].rs1!=0) { // SLT
2232               assert(s1l>=0);
2233               emit_shrimm(s1l,31,t);
2234             }
2235             else // SLTU (unsigned can not be less than zero, 0<0)
2236               emit_zeroreg(t);
2237           }
2238           else if(dops[i].rs1==0) // r0<rx
2239           {
2240             assert(s2l>=0);
2241             if(dops[i].opcode2==0x2a) // SLT
2242               emit_set_gz32(s2l,t);
2243             else // SLTU (set if not zero)
2244               emit_set_nz32(s2l,t);
2245           }
2246           else{
2247             assert(s1l>=0);assert(s2l>=0);
2248             if(dops[i].opcode2==0x2a) // SLT
2249               emit_set_if_less32(s1l,s2l,t);
2250             else // SLTU
2251               emit_set_if_carry32(s1l,s2l,t);
2252           }
2253         }
2254       }
2255     }
2256   }
2257   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
2258     if(dops[i].rt1) {
2259       signed char s1l,s2l,tl;
2260       tl=get_reg(i_regs->regmap,dops[i].rt1);
2261       {
2262         if(tl>=0) {
2263           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2264           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2265           if(dops[i].rs1&&dops[i].rs2) {
2266             assert(s1l>=0);
2267             assert(s2l>=0);
2268             if(dops[i].opcode2==0x24) { // AND
2269               emit_and(s1l,s2l,tl);
2270             } else
2271             if(dops[i].opcode2==0x25) { // OR
2272               emit_or(s1l,s2l,tl);
2273             } else
2274             if(dops[i].opcode2==0x26) { // XOR
2275               emit_xor(s1l,s2l,tl);
2276             } else
2277             if(dops[i].opcode2==0x27) { // NOR
2278               emit_or(s1l,s2l,tl);
2279               emit_not(tl,tl);
2280             }
2281           }
2282           else
2283           {
2284             if(dops[i].opcode2==0x24) { // AND
2285               emit_zeroreg(tl);
2286             } else
2287             if(dops[i].opcode2==0x25||dops[i].opcode2==0x26) { // OR/XOR
2288               if(dops[i].rs1){
2289                 if(s1l>=0) emit_mov(s1l,tl);
2290                 else emit_loadreg(dops[i].rs1,tl); // CHECK: regmap_entry?
2291               }
2292               else
2293               if(dops[i].rs2){
2294                 if(s2l>=0) emit_mov(s2l,tl);
2295                 else emit_loadreg(dops[i].rs2,tl); // CHECK: regmap_entry?
2296               }
2297               else emit_zeroreg(tl);
2298             } else
2299             if(dops[i].opcode2==0x27) { // NOR
2300               if(dops[i].rs1){
2301                 if(s1l>=0) emit_not(s1l,tl);
2302                 else {
2303                   emit_loadreg(dops[i].rs1,tl);
2304                   emit_not(tl,tl);
2305                 }
2306               }
2307               else
2308               if(dops[i].rs2){
2309                 if(s2l>=0) emit_not(s2l,tl);
2310                 else {
2311                   emit_loadreg(dops[i].rs2,tl);
2312                   emit_not(tl,tl);
2313                 }
2314               }
2315               else emit_movimm(-1,tl);
2316             }
2317           }
2318         }
2319       }
2320     }
2321   }
2322 }
2323
2324 static void imm16_assemble(int i, const struct regstat *i_regs)
2325 {
2326   if (dops[i].opcode==0x0f) { // LUI
2327     if(dops[i].rt1) {
2328       signed char t;
2329       t=get_reg(i_regs->regmap,dops[i].rt1);
2330       //assert(t>=0);
2331       if(t>=0) {
2332         if(!((i_regs->isconst>>t)&1))
2333           emit_movimm(imm[i]<<16,t);
2334       }
2335     }
2336   }
2337   if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
2338     if(dops[i].rt1) {
2339       signed char s,t;
2340       t=get_reg(i_regs->regmap,dops[i].rt1);
2341       s=get_reg(i_regs->regmap,dops[i].rs1);
2342       if(dops[i].rs1) {
2343         //assert(t>=0);
2344         //assert(s>=0);
2345         if(t>=0) {
2346           if(!((i_regs->isconst>>t)&1)) {
2347             if(s<0) {
2348               if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2349               emit_addimm(t,imm[i],t);
2350             }else{
2351               if(!((i_regs->wasconst>>s)&1))
2352                 emit_addimm(s,imm[i],t);
2353               else
2354                 emit_movimm(constmap[i][s]+imm[i],t);
2355             }
2356           }
2357         }
2358       } else {
2359         if(t>=0) {
2360           if(!((i_regs->isconst>>t)&1))
2361             emit_movimm(imm[i],t);
2362         }
2363       }
2364     }
2365   }
2366   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
2367     if(dops[i].rt1) {
2368       signed char sl,tl;
2369       tl=get_reg(i_regs->regmap,dops[i].rt1);
2370       sl=get_reg(i_regs->regmap,dops[i].rs1);
2371       if(tl>=0) {
2372         if(dops[i].rs1) {
2373           assert(sl>=0);
2374           emit_addimm(sl,imm[i],tl);
2375         } else {
2376           emit_movimm(imm[i],tl);
2377         }
2378       }
2379     }
2380   }
2381   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
2382     if(dops[i].rt1) {
2383       //assert(dops[i].rs1!=0); // r0 might be valid, but it's probably a bug
2384       signed char sl,t;
2385       t=get_reg(i_regs->regmap,dops[i].rt1);
2386       sl=get_reg(i_regs->regmap,dops[i].rs1);
2387       //assert(t>=0);
2388       if(t>=0) {
2389         if(dops[i].rs1>0) {
2390             if(dops[i].opcode==0x0a) { // SLTI
2391               if(sl<0) {
2392                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2393                 emit_slti32(t,imm[i],t);
2394               }else{
2395                 emit_slti32(sl,imm[i],t);
2396               }
2397             }
2398             else { // SLTIU
2399               if(sl<0) {
2400                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2401                 emit_sltiu32(t,imm[i],t);
2402               }else{
2403                 emit_sltiu32(sl,imm[i],t);
2404               }
2405             }
2406         }else{
2407           // SLTI(U) with r0 is just stupid,
2408           // nonetheless examples can be found
2409           if(dops[i].opcode==0x0a) // SLTI
2410             if(0<imm[i]) emit_movimm(1,t);
2411             else emit_zeroreg(t);
2412           else // SLTIU
2413           {
2414             if(imm[i]) emit_movimm(1,t);
2415             else emit_zeroreg(t);
2416           }
2417         }
2418       }
2419     }
2420   }
2421   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
2422     if(dops[i].rt1) {
2423       signed char sl,tl;
2424       tl=get_reg(i_regs->regmap,dops[i].rt1);
2425       sl=get_reg(i_regs->regmap,dops[i].rs1);
2426       if(tl>=0 && !((i_regs->isconst>>tl)&1)) {
2427         if(dops[i].opcode==0x0c) //ANDI
2428         {
2429           if(dops[i].rs1) {
2430             if(sl<0) {
2431               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2432               emit_andimm(tl,imm[i],tl);
2433             }else{
2434               if(!((i_regs->wasconst>>sl)&1))
2435                 emit_andimm(sl,imm[i],tl);
2436               else
2437                 emit_movimm(constmap[i][sl]&imm[i],tl);
2438             }
2439           }
2440           else
2441             emit_zeroreg(tl);
2442         }
2443         else
2444         {
2445           if(dops[i].rs1) {
2446             if(sl<0) {
2447               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2448             }
2449             if(dops[i].opcode==0x0d) { // ORI
2450               if(sl<0) {
2451                 emit_orimm(tl,imm[i],tl);
2452               }else{
2453                 if(!((i_regs->wasconst>>sl)&1))
2454                   emit_orimm(sl,imm[i],tl);
2455                 else
2456                   emit_movimm(constmap[i][sl]|imm[i],tl);
2457               }
2458             }
2459             if(dops[i].opcode==0x0e) { // XORI
2460               if(sl<0) {
2461                 emit_xorimm(tl,imm[i],tl);
2462               }else{
2463                 if(!((i_regs->wasconst>>sl)&1))
2464                   emit_xorimm(sl,imm[i],tl);
2465                 else
2466                   emit_movimm(constmap[i][sl]^imm[i],tl);
2467               }
2468             }
2469           }
2470           else {
2471             emit_movimm(imm[i],tl);
2472           }
2473         }
2474       }
2475     }
2476   }
2477 }
2478
2479 static void shiftimm_assemble(int i, const struct regstat *i_regs)
2480 {
2481   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
2482   {
2483     if(dops[i].rt1) {
2484       signed char s,t;
2485       t=get_reg(i_regs->regmap,dops[i].rt1);
2486       s=get_reg(i_regs->regmap,dops[i].rs1);
2487       //assert(t>=0);
2488       if(t>=0&&!((i_regs->isconst>>t)&1)){
2489         if(dops[i].rs1==0)
2490         {
2491           emit_zeroreg(t);
2492         }
2493         else
2494         {
2495           if(s<0&&i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2496           if(imm[i]) {
2497             if(dops[i].opcode2==0) // SLL
2498             {
2499               emit_shlimm(s<0?t:s,imm[i],t);
2500             }
2501             if(dops[i].opcode2==2) // SRL
2502             {
2503               emit_shrimm(s<0?t:s,imm[i],t);
2504             }
2505             if(dops[i].opcode2==3) // SRA
2506             {
2507               emit_sarimm(s<0?t:s,imm[i],t);
2508             }
2509           }else{
2510             // Shift by zero
2511             if(s>=0 && s!=t) emit_mov(s,t);
2512           }
2513         }
2514       }
2515       //emit_storereg(dops[i].rt1,t); //DEBUG
2516     }
2517   }
2518   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
2519   {
2520     assert(0);
2521   }
2522   if(dops[i].opcode2==0x3c) // DSLL32
2523   {
2524     assert(0);
2525   }
2526   if(dops[i].opcode2==0x3e) // DSRL32
2527   {
2528     assert(0);
2529   }
2530   if(dops[i].opcode2==0x3f) // DSRA32
2531   {
2532     assert(0);
2533   }
2534 }
2535
2536 #ifndef shift_assemble
2537 static void shift_assemble(int i, const struct regstat *i_regs)
2538 {
2539   signed char s,t,shift;
2540   if (dops[i].rt1 == 0)
2541     return;
2542   assert(dops[i].opcode2<=0x07); // SLLV/SRLV/SRAV
2543   t = get_reg(i_regs->regmap, dops[i].rt1);
2544   s = get_reg(i_regs->regmap, dops[i].rs1);
2545   shift = get_reg(i_regs->regmap, dops[i].rs2);
2546   if (t < 0)
2547     return;
2548
2549   if(dops[i].rs1==0)
2550     emit_zeroreg(t);
2551   else if(dops[i].rs2==0) {
2552     assert(s>=0);
2553     if(s!=t) emit_mov(s,t);
2554   }
2555   else {
2556     host_tempreg_acquire();
2557     emit_andimm(shift,31,HOST_TEMPREG);
2558     switch(dops[i].opcode2) {
2559     case 4: // SLLV
2560       emit_shl(s,HOST_TEMPREG,t);
2561       break;
2562     case 6: // SRLV
2563       emit_shr(s,HOST_TEMPREG,t);
2564       break;
2565     case 7: // SRAV
2566       emit_sar(s,HOST_TEMPREG,t);
2567       break;
2568     default:
2569       assert(0);
2570     }
2571     host_tempreg_release();
2572   }
2573 }
2574
2575 #endif
2576
2577 enum {
2578   MTYPE_8000 = 0,
2579   MTYPE_8020,
2580   MTYPE_0000,
2581   MTYPE_A000,
2582   MTYPE_1F80,
2583 };
2584
2585 static int get_ptr_mem_type(u_int a)
2586 {
2587   if(a < 0x00200000) {
2588     if(a<0x1000&&((start>>20)==0xbfc||(start>>24)==0xa0))
2589       // return wrong, must use memhandler for BIOS self-test to pass
2590       // 007 does similar stuff from a00 mirror, weird stuff
2591       return MTYPE_8000;
2592     return MTYPE_0000;
2593   }
2594   if(0x1f800000 <= a && a < 0x1f801000)
2595     return MTYPE_1F80;
2596   if(0x80200000 <= a && a < 0x80800000)
2597     return MTYPE_8020;
2598   if(0xa0000000 <= a && a < 0xa0200000)
2599     return MTYPE_A000;
2600   return MTYPE_8000;
2601 }
2602
2603 static int get_ro_reg(const struct regstat *i_regs, int host_tempreg_free)
2604 {
2605   int r = get_reg(i_regs->regmap, ROREG);
2606   if (r < 0 && host_tempreg_free) {
2607     host_tempreg_acquire();
2608     emit_loadreg(ROREG, r = HOST_TEMPREG);
2609   }
2610   if (r < 0)
2611     abort();
2612   return r;
2613 }
2614
2615 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
2616   int addr, int *offset_reg, int *addr_reg_override)
2617 {
2618   void *jaddr = NULL;
2619   int type = 0;
2620   int mr = dops[i].rs1;
2621   *offset_reg = -1;
2622   if(((smrv_strong|smrv_weak)>>mr)&1) {
2623     type=get_ptr_mem_type(smrv[mr]);
2624     //printf("set %08x @%08x r%d %d\n", smrv[mr], start+i*4, mr, type);
2625   }
2626   else {
2627     // use the mirror we are running on
2628     type=get_ptr_mem_type(start);
2629     //printf("set nospec   @%08x r%d %d\n", start+i*4, mr, type);
2630   }
2631
2632   if(type==MTYPE_8020) { // RAM 80200000+ mirror
2633     host_tempreg_acquire();
2634     emit_andimm(addr,~0x00e00000,HOST_TEMPREG);
2635     addr=*addr_reg_override=HOST_TEMPREG;
2636     type=0;
2637   }
2638   else if(type==MTYPE_0000) { // RAM 0 mirror
2639     host_tempreg_acquire();
2640     emit_orimm(addr,0x80000000,HOST_TEMPREG);
2641     addr=*addr_reg_override=HOST_TEMPREG;
2642     type=0;
2643   }
2644   else if(type==MTYPE_A000) { // RAM A mirror
2645     host_tempreg_acquire();
2646     emit_andimm(addr,~0x20000000,HOST_TEMPREG);
2647     addr=*addr_reg_override=HOST_TEMPREG;
2648     type=0;
2649   }
2650   else if(type==MTYPE_1F80) { // scratchpad
2651     if (psxH == (void *)0x1f800000) {
2652       host_tempreg_acquire();
2653       emit_xorimm(addr,0x1f800000,HOST_TEMPREG);
2654       emit_cmpimm(HOST_TEMPREG,0x1000);
2655       host_tempreg_release();
2656       jaddr=out;
2657       emit_jc(0);
2658     }
2659     else {
2660       // do the usual RAM check, jump will go to the right handler
2661       type=0;
2662     }
2663   }
2664
2665   if (type == 0) // need ram check
2666   {
2667     emit_cmpimm(addr,RAM_SIZE);
2668     jaddr = out;
2669     #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
2670     // Hint to branch predictor that the branch is unlikely to be taken
2671     if (dops[i].rs1 >= 28)
2672       emit_jno_unlikely(0);
2673     else
2674     #endif
2675       emit_jno(0);
2676     if (ram_offset != 0)
2677       *offset_reg = get_ro_reg(i_regs, 0);
2678   }
2679
2680   return jaddr;
2681 }
2682
2683 // return memhandler, or get directly accessable address and return 0
2684 static void *get_direct_memhandler(void *table, u_int addr,
2685   enum stub_type type, uintptr_t *addr_host)
2686 {
2687   uintptr_t msb = 1ull << (sizeof(uintptr_t)*8 - 1);
2688   uintptr_t l1, l2 = 0;
2689   l1 = ((uintptr_t *)table)[addr>>12];
2690   if (!(l1 & msb)) {
2691     uintptr_t v = l1 << 1;
2692     *addr_host = v + addr;
2693     return NULL;
2694   }
2695   else {
2696     l1 <<= 1;
2697     if (type == LOADB_STUB || type == LOADBU_STUB || type == STOREB_STUB)
2698       l2 = ((uintptr_t *)l1)[0x1000/4 + 0x1000/2 + (addr&0xfff)];
2699     else if (type == LOADH_STUB || type == LOADHU_STUB || type == STOREH_STUB)
2700       l2 = ((uintptr_t *)l1)[0x1000/4 + (addr&0xfff)/2];
2701     else
2702       l2 = ((uintptr_t *)l1)[(addr&0xfff)/4];
2703     if (!(l2 & msb)) {
2704       uintptr_t v = l2 << 1;
2705       *addr_host = v + (addr&0xfff);
2706       return NULL;
2707     }
2708     return (void *)(l2 << 1);
2709   }
2710 }
2711
2712 static u_int get_host_reglist(const signed char *regmap)
2713 {
2714   u_int reglist = 0, hr;
2715   for (hr = 0; hr < HOST_REGS; hr++) {
2716     if (hr != EXCLUDE_REG && regmap[hr] >= 0)
2717       reglist |= 1 << hr;
2718   }
2719   return reglist;
2720 }
2721
2722 static u_int reglist_exclude(u_int reglist, int r1, int r2)
2723 {
2724   if (r1 >= 0)
2725     reglist &= ~(1u << r1);
2726   if (r2 >= 0)
2727     reglist &= ~(1u << r2);
2728   return reglist;
2729 }
2730
2731 // find a temp caller-saved register not in reglist (so assumed to be free)
2732 static int reglist_find_free(u_int reglist)
2733 {
2734   u_int free_regs = ~reglist & CALLER_SAVE_REGS;
2735   if (free_regs == 0)
2736     return -1;
2737   return __builtin_ctz(free_regs);
2738 }
2739
2740 static void do_load_word(int a, int rt, int offset_reg)
2741 {
2742   if (offset_reg >= 0)
2743     emit_ldr_dualindexed(offset_reg, a, rt);
2744   else
2745     emit_readword_indexed(0, a, rt);
2746 }
2747
2748 static void do_store_word(int a, int ofs, int rt, int offset_reg, int preseve_a)
2749 {
2750   if (offset_reg < 0) {
2751     emit_writeword_indexed(rt, ofs, a);
2752     return;
2753   }
2754   if (ofs != 0)
2755     emit_addimm(a, ofs, a);
2756   emit_str_dualindexed(offset_reg, a, rt);
2757   if (ofs != 0 && preseve_a)
2758     emit_addimm(a, -ofs, a);
2759 }
2760
2761 static void do_store_hword(int a, int ofs, int rt, int offset_reg, int preseve_a)
2762 {
2763   if (offset_reg < 0) {
2764     emit_writehword_indexed(rt, ofs, a);
2765     return;
2766   }
2767   if (ofs != 0)
2768     emit_addimm(a, ofs, a);
2769   emit_strh_dualindexed(offset_reg, a, rt);
2770   if (ofs != 0 && preseve_a)
2771     emit_addimm(a, -ofs, a);
2772 }
2773
2774 static void do_store_byte(int a, int rt, int offset_reg)
2775 {
2776   if (offset_reg >= 0)
2777     emit_strb_dualindexed(offset_reg, a, rt);
2778   else
2779     emit_writebyte_indexed(rt, 0, a);
2780 }
2781
2782 static void load_assemble(int i, const struct regstat *i_regs, int ccadj_)
2783 {
2784   int s,tl,addr;
2785   int offset;
2786   void *jaddr=0;
2787   int memtarget=0,c=0;
2788   int offset_reg = -1;
2789   int fastio_reg_override = -1;
2790   u_int reglist=get_host_reglist(i_regs->regmap);
2791   tl=get_reg(i_regs->regmap,dops[i].rt1);
2792   s=get_reg(i_regs->regmap,dops[i].rs1);
2793   offset=imm[i];
2794   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2795   if(s>=0) {
2796     c=(i_regs->wasconst>>s)&1;
2797     if (c) {
2798       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2799     }
2800   }
2801   //printf("load_assemble: c=%d\n",c);
2802   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2803   // FIXME: Even if the load is a NOP, we should check for pagefaults...
2804   if((tl<0&&(!c||(((u_int)constmap[i][s]+offset)>>16)==0x1f80))
2805     ||dops[i].rt1==0) {
2806       // could be FIFO, must perform the read
2807       // ||dummy read
2808       assem_debug("(forced read)\n");
2809       tl=get_reg(i_regs->regmap,-1);
2810       assert(tl>=0);
2811   }
2812   if(offset||s<0||c) addr=tl;
2813   else addr=s;
2814   //if(tl<0) tl=get_reg(i_regs->regmap,-1);
2815  if(tl>=0) {
2816   //printf("load_assemble: c=%d\n",c);
2817   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2818   assert(tl>=0); // Even if the load is a NOP, we must check for pagefaults and I/O
2819   reglist&=~(1<<tl);
2820   if(!c) {
2821     #ifdef R29_HACK
2822     // Strmnnrmn's speed hack
2823     if(dops[i].rs1!=29||start<0x80001000||start>=0x80000000+RAM_SIZE)
2824     #endif
2825     {
2826       jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
2827                 &offset_reg, &fastio_reg_override);
2828     }
2829   }
2830   else if (ram_offset && memtarget) {
2831     offset_reg = get_ro_reg(i_regs, 0);
2832   }
2833   int dummy=(dops[i].rt1==0)||(tl!=get_reg(i_regs->regmap,dops[i].rt1)); // ignore loads to r0 and unneeded reg
2834   switch (dops[i].opcode) {
2835   case 0x20: // LB
2836     if(!c||memtarget) {
2837       if(!dummy) {
2838         int a = tl;
2839         if (!c) a = addr;
2840         if (fastio_reg_override >= 0)
2841           a = fastio_reg_override;
2842
2843         if (offset_reg >= 0)
2844           emit_ldrsb_dualindexed(offset_reg, a, tl);
2845         else
2846           emit_movsbl_indexed(0, a, tl);
2847       }
2848       if(jaddr)
2849         add_stub_r(LOADB_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2850     }
2851     else
2852       inline_readstub(LOADB_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2853     break;
2854   case 0x21: // LH
2855     if(!c||memtarget) {
2856       if(!dummy) {
2857         int a = tl;
2858         if (!c) a = addr;
2859         if (fastio_reg_override >= 0)
2860           a = fastio_reg_override;
2861         if (offset_reg >= 0)
2862           emit_ldrsh_dualindexed(offset_reg, a, tl);
2863         else
2864           emit_movswl_indexed(0, a, tl);
2865       }
2866       if(jaddr)
2867         add_stub_r(LOADH_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2868     }
2869     else
2870       inline_readstub(LOADH_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2871     break;
2872   case 0x23: // LW
2873     if(!c||memtarget) {
2874       if(!dummy) {
2875         int a = addr;
2876         if (fastio_reg_override >= 0)
2877           a = fastio_reg_override;
2878         do_load_word(a, tl, offset_reg);
2879       }
2880       if(jaddr)
2881         add_stub_r(LOADW_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2882     }
2883     else
2884       inline_readstub(LOADW_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2885     break;
2886   case 0x24: // LBU
2887     if(!c||memtarget) {
2888       if(!dummy) {
2889         int a = tl;
2890         if (!c) a = addr;
2891         if (fastio_reg_override >= 0)
2892           a = fastio_reg_override;
2893
2894         if (offset_reg >= 0)
2895           emit_ldrb_dualindexed(offset_reg, a, tl);
2896         else
2897           emit_movzbl_indexed(0, a, tl);
2898       }
2899       if(jaddr)
2900         add_stub_r(LOADBU_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2901     }
2902     else
2903       inline_readstub(LOADBU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2904     break;
2905   case 0x25: // LHU
2906     if(!c||memtarget) {
2907       if(!dummy) {
2908         int a = tl;
2909         if(!c) a = addr;
2910         if (fastio_reg_override >= 0)
2911           a = fastio_reg_override;
2912         if (offset_reg >= 0)
2913           emit_ldrh_dualindexed(offset_reg, a, tl);
2914         else
2915           emit_movzwl_indexed(0, a, tl);
2916       }
2917       if(jaddr)
2918         add_stub_r(LOADHU_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2919     }
2920     else
2921       inline_readstub(LOADHU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2922     break;
2923   case 0x27: // LWU
2924   case 0x37: // LD
2925   default:
2926     assert(0);
2927   }
2928  }
2929  if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
2930    host_tempreg_release();
2931 }
2932
2933 #ifndef loadlr_assemble
2934 static void loadlr_assemble(int i, const struct regstat *i_regs, int ccadj_)
2935 {
2936   int s,tl,temp,temp2,addr;
2937   int offset;
2938   void *jaddr=0;
2939   int memtarget=0,c=0;
2940   int offset_reg = -1;
2941   int fastio_reg_override = -1;
2942   u_int reglist=get_host_reglist(i_regs->regmap);
2943   tl=get_reg(i_regs->regmap,dops[i].rt1);
2944   s=get_reg(i_regs->regmap,dops[i].rs1);
2945   temp=get_reg(i_regs->regmap,-1);
2946   temp2=get_reg(i_regs->regmap,FTEMP);
2947   addr=get_reg(i_regs->regmap,AGEN1+(i&1));
2948   assert(addr<0);
2949   offset=imm[i];
2950   reglist|=1<<temp;
2951   if(offset||s<0||c) addr=temp2;
2952   else addr=s;
2953   if(s>=0) {
2954     c=(i_regs->wasconst>>s)&1;
2955     if(c) {
2956       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2957     }
2958   }
2959   if(!c) {
2960     emit_shlimm(addr,3,temp);
2961     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
2962       emit_andimm(addr,0xFFFFFFFC,temp2); // LWL/LWR
2963     }else{
2964       emit_andimm(addr,0xFFFFFFF8,temp2); // LDL/LDR
2965     }
2966     jaddr = emit_fastpath_cmp_jump(i, i_regs, temp2,
2967               &offset_reg, &fastio_reg_override);
2968   }
2969   else {
2970     if (ram_offset && memtarget) {
2971       offset_reg = get_ro_reg(i_regs, 0);
2972     }
2973     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
2974       emit_movimm(((constmap[i][s]+offset)<<3)&24,temp); // LWL/LWR
2975     }else{
2976       emit_movimm(((constmap[i][s]+offset)<<3)&56,temp); // LDL/LDR
2977     }
2978   }
2979   if (dops[i].opcode==0x22||dops[i].opcode==0x26) { // LWL/LWR
2980     if(!c||memtarget) {
2981       int a = temp2;
2982       if (fastio_reg_override >= 0)
2983         a = fastio_reg_override;
2984       do_load_word(a, temp2, offset_reg);
2985       if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
2986         host_tempreg_release();
2987       if(jaddr) add_stub_r(LOADW_STUB,jaddr,out,i,temp2,i_regs,ccadj_,reglist);
2988     }
2989     else
2990       inline_readstub(LOADW_STUB,i,(constmap[i][s]+offset)&0xFFFFFFFC,i_regs->regmap,FTEMP,ccadj_,reglist);
2991     if(dops[i].rt1) {
2992       assert(tl>=0);
2993       emit_andimm(temp,24,temp);
2994       if (dops[i].opcode==0x22) // LWL
2995         emit_xorimm(temp,24,temp);
2996       host_tempreg_acquire();
2997       emit_movimm(-1,HOST_TEMPREG);
2998       if (dops[i].opcode==0x26) {
2999         emit_shr(temp2,temp,temp2);
3000         emit_bic_lsr(tl,HOST_TEMPREG,temp,tl);
3001       }else{
3002         emit_shl(temp2,temp,temp2);
3003         emit_bic_lsl(tl,HOST_TEMPREG,temp,tl);
3004       }
3005       host_tempreg_release();
3006       emit_or(temp2,tl,tl);
3007     }
3008     //emit_storereg(dops[i].rt1,tl); // DEBUG
3009   }
3010   if (dops[i].opcode==0x1A||dops[i].opcode==0x1B) { // LDL/LDR
3011     assert(0);
3012   }
3013 }
3014 #endif
3015
3016 static void store_assemble(int i, const struct regstat *i_regs, int ccadj_)
3017 {
3018   int s,tl;
3019   int addr,temp;
3020   int offset;
3021   void *jaddr=0;
3022   enum stub_type type=0;
3023   int memtarget=0,c=0;
3024   int agr=AGEN1+(i&1);
3025   int offset_reg = -1;
3026   int fastio_reg_override = -1;
3027   u_int reglist=get_host_reglist(i_regs->regmap);
3028   tl=get_reg(i_regs->regmap,dops[i].rs2);
3029   s=get_reg(i_regs->regmap,dops[i].rs1);
3030   temp=get_reg(i_regs->regmap,agr);
3031   if(temp<0) temp=get_reg(i_regs->regmap,-1);
3032   offset=imm[i];
3033   if(s>=0) {
3034     c=(i_regs->wasconst>>s)&1;
3035     if(c) {
3036       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3037     }
3038   }
3039   assert(tl>=0);
3040   assert(temp>=0);
3041   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
3042   if(offset||s<0||c) addr=temp;
3043   else addr=s;
3044   if (!c) {
3045     jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
3046               &offset_reg, &fastio_reg_override);
3047   }
3048   else if (ram_offset && memtarget) {
3049     offset_reg = get_ro_reg(i_regs, 0);
3050   }
3051
3052   switch (dops[i].opcode) {
3053   case 0x28: // SB
3054     if(!c||memtarget) {
3055       int a = temp;
3056       if (!c) a = addr;
3057       if (fastio_reg_override >= 0)
3058         a = fastio_reg_override;
3059       do_store_byte(a, tl, offset_reg);
3060     }
3061     type = STOREB_STUB;
3062     break;
3063   case 0x29: // SH
3064     if(!c||memtarget) {
3065       int a = temp;
3066       if (!c) a = addr;
3067       if (fastio_reg_override >= 0)
3068         a = fastio_reg_override;
3069       do_store_hword(a, 0, tl, offset_reg, 1);
3070     }
3071     type = STOREH_STUB;
3072     break;
3073   case 0x2B: // SW
3074     if(!c||memtarget) {
3075       int a = addr;
3076       if (fastio_reg_override >= 0)
3077         a = fastio_reg_override;
3078       do_store_word(a, 0, tl, offset_reg, 1);
3079     }
3080     type = STOREW_STUB;
3081     break;
3082   case 0x3F: // SD
3083   default:
3084     assert(0);
3085   }
3086   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3087     host_tempreg_release();
3088   if(jaddr) {
3089     // PCSX store handlers don't check invcode again
3090     reglist|=1<<addr;
3091     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3092     jaddr=0;
3093   }
3094   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3095     if(!c||memtarget) {
3096       #ifdef DESTRUCTIVE_SHIFT
3097       // The x86 shift operation is 'destructive'; it overwrites the
3098       // source register, so we need to make a copy first and use that.
3099       addr=temp;
3100       #endif
3101       #if defined(HOST_IMM8)
3102       int ir=get_reg(i_regs->regmap,INVCP);
3103       assert(ir>=0);
3104       emit_cmpmem_indexedsr12_reg(ir,addr,1);
3105       #else
3106       emit_cmpmem_indexedsr12_imm(invalid_code,addr,1);
3107       #endif
3108       #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3109       emit_callne(invalidate_addr_reg[addr]);
3110       #else
3111       void *jaddr2 = out;
3112       emit_jne(0);
3113       add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),addr,0,0,0);
3114       #endif
3115     }
3116   }
3117   u_int addr_val=constmap[i][s]+offset;
3118   if(jaddr) {
3119     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3120   } else if(c&&!memtarget) {
3121     inline_writestub(type,i,addr_val,i_regs->regmap,dops[i].rs2,ccadj_,reglist);
3122   }
3123   // basic current block modification detection..
3124   // not looking back as that should be in mips cache already
3125   // (see Spyro2 title->attract mode)
3126   if(c&&start+i*4<addr_val&&addr_val<start+slen*4) {
3127     SysPrintf("write to %08x hits block %08x, pc=%08x\n",addr_val,start,start+i*4);
3128     assert(i_regs->regmap==regs[i].regmap); // not delay slot
3129     if(i_regs->regmap==regs[i].regmap) {
3130       load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3131       wb_dirtys(regs[i].regmap_entry,regs[i].wasdirty);
3132       emit_movimm(start+i*4+4,0);
3133       emit_writeword(0,&pcaddr);
3134       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3135       emit_far_call(get_addr_ht);
3136       emit_jmpreg(0);
3137     }
3138   }
3139 }
3140
3141 static void storelr_assemble(int i, const struct regstat *i_regs, int ccadj_)
3142 {
3143   int s,tl;
3144   int temp;
3145   int offset;
3146   void *jaddr=0;
3147   void *case1, *case23, *case3;
3148   void *done0, *done1, *done2;
3149   int memtarget=0,c=0;
3150   int agr=AGEN1+(i&1);
3151   int offset_reg = -1;
3152   u_int reglist=get_host_reglist(i_regs->regmap);
3153   tl=get_reg(i_regs->regmap,dops[i].rs2);
3154   s=get_reg(i_regs->regmap,dops[i].rs1);
3155   temp=get_reg(i_regs->regmap,agr);
3156   if(temp<0) temp=get_reg(i_regs->regmap,-1);
3157   offset=imm[i];
3158   if(s>=0) {
3159     c=(i_regs->isconst>>s)&1;
3160     if(c) {
3161       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3162     }
3163   }
3164   assert(tl>=0);
3165   assert(temp>=0);
3166   if(!c) {
3167     emit_cmpimm(s<0||offset?temp:s,RAM_SIZE);
3168     if(!offset&&s!=temp) emit_mov(s,temp);
3169     jaddr=out;
3170     emit_jno(0);
3171   }
3172   else
3173   {
3174     if(!memtarget||!dops[i].rs1) {
3175       jaddr=out;
3176       emit_jmp(0);
3177     }
3178   }
3179   if (ram_offset)
3180     offset_reg = get_ro_reg(i_regs, 0);
3181
3182   if (dops[i].opcode==0x2C||dops[i].opcode==0x2D) { // SDL/SDR
3183     assert(0);
3184   }
3185
3186   emit_testimm(temp,2);
3187   case23=out;
3188   emit_jne(0);
3189   emit_testimm(temp,1);
3190   case1=out;
3191   emit_jne(0);
3192   // 0
3193   if (dops[i].opcode == 0x2A) { // SWL
3194     // Write msb into least significant byte
3195     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3196     do_store_byte(temp, tl, offset_reg);
3197     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3198   }
3199   else if (dops[i].opcode == 0x2E) { // SWR
3200     // Write entire word
3201     do_store_word(temp, 0, tl, offset_reg, 1);
3202   }
3203   done0 = out;
3204   emit_jmp(0);
3205   // 1
3206   set_jump_target(case1, out);
3207   if (dops[i].opcode == 0x2A) { // SWL
3208     // Write two msb into two least significant bytes
3209     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3210     do_store_hword(temp, -1, tl, offset_reg, 0);
3211     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3212   }
3213   else if (dops[i].opcode == 0x2E) { // SWR
3214     // Write 3 lsb into three most significant bytes
3215     do_store_byte(temp, tl, offset_reg);
3216     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3217     do_store_hword(temp, 1, tl, offset_reg, 0);
3218     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3219   }
3220   done1=out;
3221   emit_jmp(0);
3222   // 2,3
3223   set_jump_target(case23, out);
3224   emit_testimm(temp,1);
3225   case3 = out;
3226   emit_jne(0);
3227   // 2
3228   if (dops[i].opcode==0x2A) { // SWL
3229     // Write 3 msb into three least significant bytes
3230     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3231     do_store_hword(temp, -2, tl, offset_reg, 1);
3232     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3233     do_store_byte(temp, tl, offset_reg);
3234     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3235   }
3236   else if (dops[i].opcode == 0x2E) { // SWR
3237     // Write two lsb into two most significant bytes
3238     do_store_hword(temp, 0, tl, offset_reg, 1);
3239   }
3240   done2 = out;
3241   emit_jmp(0);
3242   // 3
3243   set_jump_target(case3, out);
3244   if (dops[i].opcode == 0x2A) { // SWL
3245     do_store_word(temp, -3, tl, offset_reg, 0);
3246   }
3247   else if (dops[i].opcode == 0x2E) { // SWR
3248     do_store_byte(temp, tl, offset_reg);
3249   }
3250   set_jump_target(done0, out);
3251   set_jump_target(done1, out);
3252   set_jump_target(done2, out);
3253   if (offset_reg == HOST_TEMPREG)
3254     host_tempreg_release();
3255   if(!c||!memtarget)
3256     add_stub_r(STORELR_STUB,jaddr,out,i,temp,i_regs,ccadj_,reglist);
3257   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3258     #if defined(HOST_IMM8)
3259     int ir=get_reg(i_regs->regmap,INVCP);
3260     assert(ir>=0);
3261     emit_cmpmem_indexedsr12_reg(ir,temp,1);
3262     #else
3263     emit_cmpmem_indexedsr12_imm(invalid_code,temp,1);
3264     #endif
3265     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3266     emit_callne(invalidate_addr_reg[temp]);
3267     #else
3268     void *jaddr2 = out;
3269     emit_jne(0);
3270     add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),temp,0,0,0);
3271     #endif
3272   }
3273 }
3274
3275 static void cop0_assemble(int i, const struct regstat *i_regs, int ccadj_)
3276 {
3277   if(dops[i].opcode2==0) // MFC0
3278   {
3279     signed char t=get_reg(i_regs->regmap,dops[i].rt1);
3280     u_int copr=(source[i]>>11)&0x1f;
3281     //assert(t>=0); // Why does this happen?  OOT is weird
3282     if(t>=0&&dops[i].rt1!=0) {
3283       emit_readword(&reg_cop0[copr],t);
3284     }
3285   }
3286   else if(dops[i].opcode2==4) // MTC0
3287   {
3288     signed char s=get_reg(i_regs->regmap,dops[i].rs1);
3289     char copr=(source[i]>>11)&0x1f;
3290     assert(s>=0);
3291     wb_register(dops[i].rs1,i_regs->regmap,i_regs->dirty);
3292     if(copr==9||copr==11||copr==12||copr==13) {
3293       emit_readword(&last_count,HOST_TEMPREG);
3294       emit_loadreg(CCREG,HOST_CCREG); // TODO: do proper reg alloc
3295       emit_add(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3296       emit_addimm(HOST_CCREG,ccadj_,HOST_CCREG);
3297       emit_writeword(HOST_CCREG,&Count);
3298     }
3299     // What a mess.  The status register (12) can enable interrupts,
3300     // so needs a special case to handle a pending interrupt.
3301     // The interrupt must be taken immediately, because a subsequent
3302     // instruction might disable interrupts again.
3303     if(copr==12||copr==13) {
3304       if (is_delayslot) {
3305         // burn cycles to cause cc_interrupt, which will
3306         // reschedule next_interupt. Relies on CCREG from above.
3307         assem_debug("MTC0 DS %d\n", copr);
3308         emit_writeword(HOST_CCREG,&last_count);
3309         emit_movimm(0,HOST_CCREG);
3310         emit_storereg(CCREG,HOST_CCREG);
3311         emit_loadreg(dops[i].rs1,1);
3312         emit_movimm(copr,0);
3313         emit_far_call(pcsx_mtc0_ds);
3314         emit_loadreg(dops[i].rs1,s);
3315         return;
3316       }
3317       emit_movimm(start+i*4+4,HOST_TEMPREG);
3318       emit_writeword(HOST_TEMPREG,&pcaddr);
3319       emit_movimm(0,HOST_TEMPREG);
3320       emit_writeword(HOST_TEMPREG,&pending_exception);
3321     }
3322     if(s==HOST_CCREG)
3323       emit_loadreg(dops[i].rs1,1);
3324     else if(s!=1)
3325       emit_mov(s,1);
3326     emit_movimm(copr,0);
3327     emit_far_call(pcsx_mtc0);
3328     if(copr==9||copr==11||copr==12||copr==13) {
3329       emit_readword(&Count,HOST_CCREG);
3330       emit_readword(&next_interupt,HOST_TEMPREG);
3331       emit_addimm(HOST_CCREG,-ccadj_,HOST_CCREG);
3332       emit_sub(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3333       emit_writeword(HOST_TEMPREG,&last_count);
3334       emit_storereg(CCREG,HOST_CCREG);
3335     }
3336     if(copr==12||copr==13) {
3337       assert(!is_delayslot);
3338       emit_readword(&pending_exception,14);
3339       emit_test(14,14);
3340       void *jaddr = out;
3341       emit_jeq(0);
3342       emit_readword(&pcaddr, 0);
3343       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3344       emit_far_call(get_addr_ht);
3345       emit_jmpreg(0);
3346       set_jump_target(jaddr, out);
3347     }
3348     emit_loadreg(dops[i].rs1,s);
3349   }
3350   else
3351   {
3352     assert(dops[i].opcode2==0x10);
3353     //if((source[i]&0x3f)==0x10) // RFE
3354     {
3355       emit_readword(&Status,0);
3356       emit_andimm(0,0x3c,1);
3357       emit_andimm(0,~0xf,0);
3358       emit_orrshr_imm(1,2,0);
3359       emit_writeword(0,&Status);
3360     }
3361   }
3362 }
3363
3364 static void cop1_unusable(int i, const struct regstat *i_regs)
3365 {
3366   // XXX: should just just do the exception instead
3367   //if(!cop1_usable)
3368   {
3369     void *jaddr=out;
3370     emit_jmp(0);
3371     add_stub_r(FP_STUB,jaddr,out,i,0,i_regs,is_delayslot,0);
3372   }
3373 }
3374
3375 static void cop1_assemble(int i, const struct regstat *i_regs)
3376 {
3377   cop1_unusable(i, i_regs);
3378 }
3379
3380 static void c1ls_assemble(int i, const struct regstat *i_regs)
3381 {
3382   cop1_unusable(i, i_regs);
3383 }
3384
3385 // FP_STUB
3386 static void do_cop1stub(int n)
3387 {
3388   literal_pool(256);
3389   assem_debug("do_cop1stub %x\n",start+stubs[n].a*4);
3390   set_jump_target(stubs[n].addr, out);
3391   int i=stubs[n].a;
3392 //  int rs=stubs[n].b;
3393   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3394   int ds=stubs[n].d;
3395   if(!ds) {
3396     load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3397     //if(i_regs!=&regs[i]) printf("oops: regs[i]=%x i_regs=%x",(int)&regs[i],(int)i_regs);
3398   }
3399   //else {printf("fp exception in delay slot\n");}
3400   wb_dirtys(i_regs->regmap_entry,i_regs->wasdirty);
3401   if(regs[i].regmap_entry[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
3402   emit_movimm(start+(i-ds)*4,EAX); // Get PC
3403   emit_addimm(HOST_CCREG,ccadj[i],HOST_CCREG); // CHECK: is this right?  There should probably be an extra cycle...
3404   emit_far_jump(ds?fp_exception_ds:fp_exception);
3405 }
3406
3407 static int cop2_is_stalling_op(int i, int *cycles)
3408 {
3409   if (dops[i].opcode == 0x3a) { // SWC2
3410     *cycles = 0;
3411     return 1;
3412   }
3413   if (dops[i].itype == COP2 && (dops[i].opcode2 == 0 || dops[i].opcode2 == 2)) { // MFC2/CFC2
3414     *cycles = 0;
3415     return 1;
3416   }
3417   if (dops[i].itype == C2OP) {
3418     *cycles = gte_cycletab[source[i] & 0x3f];
3419     return 1;
3420   }
3421   // ... what about MTC2/CTC2/LWC2?
3422   return 0;
3423 }
3424
3425 #if 0
3426 static void log_gte_stall(int stall, u_int cycle)
3427 {
3428   if ((u_int)stall <= 44)
3429     printf("x    stall %2d %u\n", stall, cycle + last_count);
3430 }
3431
3432 static void emit_log_gte_stall(int i, int stall, u_int reglist)
3433 {
3434   save_regs(reglist);
3435   if (stall > 0)
3436     emit_movimm(stall, 0);
3437   else
3438     emit_mov(HOST_TEMPREG, 0);
3439   emit_addimm(HOST_CCREG, ccadj[i], 1);
3440   emit_far_call(log_gte_stall);
3441   restore_regs(reglist);
3442 }
3443 #endif
3444
3445 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist)
3446 {
3447   int j = i, other_gte_op_cycles = -1, stall = -MAXBLOCK, cycles_passed;
3448   int rtmp = reglist_find_free(reglist);
3449
3450   if (HACK_ENABLED(NDHACK_NO_STALLS))
3451     return;
3452   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3453     // happens occasionally... cc evicted? Don't bother then
3454     //printf("no cc %08x\n", start + i*4);
3455     return;
3456   }
3457   if (!dops[i].bt) {
3458     for (j = i - 1; j >= 0; j--) {
3459       //if (dops[j].is_ds) break;
3460       if (cop2_is_stalling_op(j, &other_gte_op_cycles) || dops[j].bt)
3461         break;
3462       if (j > 0 && ccadj[j - 1] > ccadj[j])
3463         break;
3464     }
3465     j = max(j, 0);
3466   }
3467   cycles_passed = ccadj[i] - ccadj[j];
3468   if (other_gte_op_cycles >= 0)
3469     stall = other_gte_op_cycles - cycles_passed;
3470   else if (cycles_passed >= 44)
3471     stall = 0; // can't stall
3472   if (stall == -MAXBLOCK && rtmp >= 0) {
3473     // unknown stall, do the expensive runtime check
3474     assem_debug("; cop2_do_stall_check\n");
3475 #if 0 // too slow
3476     save_regs(reglist);
3477     emit_movimm(gte_cycletab[op], 0);
3478     emit_addimm(HOST_CCREG, ccadj[i], 1);
3479     emit_far_call(call_gteStall);
3480     restore_regs(reglist);
3481 #else
3482     host_tempreg_acquire();
3483     emit_readword(&psxRegs.gteBusyCycle, rtmp);
3484     emit_addimm(rtmp, -ccadj[i], rtmp);
3485     emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3486     emit_cmpimm(HOST_TEMPREG, 44);
3487     emit_cmovb_reg(rtmp, HOST_CCREG);
3488     //emit_log_gte_stall(i, 0, reglist);
3489     host_tempreg_release();
3490 #endif
3491   }
3492   else if (stall > 0) {
3493     //emit_log_gte_stall(i, stall, reglist);
3494     emit_addimm(HOST_CCREG, stall, HOST_CCREG);
3495   }
3496
3497   // save gteBusyCycle, if needed
3498   if (gte_cycletab[op] == 0)
3499     return;
3500   other_gte_op_cycles = -1;
3501   for (j = i + 1; j < slen; j++) {
3502     if (cop2_is_stalling_op(j, &other_gte_op_cycles))
3503       break;
3504     if (dops[j].is_jump) {
3505       // check ds
3506       if (j + 1 < slen && cop2_is_stalling_op(j + 1, &other_gte_op_cycles))
3507         j++;
3508       break;
3509     }
3510   }
3511   if (other_gte_op_cycles >= 0)
3512     // will handle stall when assembling that op
3513     return;
3514   cycles_passed = ccadj[min(j, slen -1)] - ccadj[i];
3515   if (cycles_passed >= 44)
3516     return;
3517   assem_debug("; save gteBusyCycle\n");
3518   host_tempreg_acquire();
3519 #if 0
3520   emit_readword(&last_count, HOST_TEMPREG);
3521   emit_add(HOST_TEMPREG, HOST_CCREG, HOST_TEMPREG);
3522   emit_addimm(HOST_TEMPREG, ccadj[i], HOST_TEMPREG);
3523   emit_addimm(HOST_TEMPREG, gte_cycletab[op]), HOST_TEMPREG);
3524   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3525 #else
3526   emit_addimm(HOST_CCREG, ccadj[i] + gte_cycletab[op], HOST_TEMPREG);
3527   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3528 #endif
3529   host_tempreg_release();
3530 }
3531
3532 static int is_mflohi(int i)
3533 {
3534   return (dops[i].itype == MOV && (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG));
3535 }
3536
3537 static int check_multdiv(int i, int *cycles)
3538 {
3539   if (dops[i].itype != MULTDIV)
3540     return 0;
3541   if (dops[i].opcode2 == 0x18 || dops[i].opcode2 == 0x19) // MULT(U)
3542     *cycles = 11; // approx from 7 11 14
3543   else
3544     *cycles = 37;
3545   return 1;
3546 }
3547
3548 static void multdiv_prepare_stall(int i, const struct regstat *i_regs, int ccadj_)
3549 {
3550   int j, found = 0, c = 0;
3551   if (HACK_ENABLED(NDHACK_NO_STALLS))
3552     return;
3553   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3554     // happens occasionally... cc evicted? Don't bother then
3555     return;
3556   }
3557   for (j = i + 1; j < slen; j++) {
3558     if (dops[j].bt)
3559       break;
3560     if ((found = is_mflohi(j)))
3561       break;
3562     if (dops[j].is_jump) {
3563       // check ds
3564       if (j + 1 < slen && (found = is_mflohi(j + 1)))
3565         j++;
3566       break;
3567     }
3568   }
3569   if (found)
3570     // handle all in multdiv_do_stall()
3571     return;
3572   check_multdiv(i, &c);
3573   assert(c > 0);
3574   assem_debug("; muldiv prepare stall %d\n", c);
3575   host_tempreg_acquire();
3576   emit_addimm(HOST_CCREG, ccadj_ + c, HOST_TEMPREG);
3577   emit_writeword(HOST_TEMPREG, &psxRegs.muldivBusyCycle);
3578   host_tempreg_release();
3579 }
3580
3581 static void multdiv_do_stall(int i, const struct regstat *i_regs)
3582 {
3583   int j, known_cycles = 0;
3584   u_int reglist = get_host_reglist(i_regs->regmap);
3585   int rtmp = get_reg(i_regs->regmap, -1);
3586   if (rtmp < 0)
3587     rtmp = reglist_find_free(reglist);
3588   if (HACK_ENABLED(NDHACK_NO_STALLS))
3589     return;
3590   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG || rtmp < 0) {
3591     // happens occasionally... cc evicted? Don't bother then
3592     //printf("no cc/rtmp %08x\n", start + i*4);
3593     return;
3594   }
3595   if (!dops[i].bt) {
3596     for (j = i - 1; j >= 0; j--) {
3597       if (dops[j].is_ds) break;
3598       if (check_multdiv(j, &known_cycles))
3599         break;
3600       if (is_mflohi(j))
3601         // already handled by this op
3602         return;
3603       if (dops[j].bt || (j > 0 && ccadj[j - 1] > ccadj[j]))
3604         break;
3605     }
3606     j = max(j, 0);
3607   }
3608   if (known_cycles > 0) {
3609     known_cycles -= ccadj[i] - ccadj[j];
3610     assem_debug("; muldiv stall resolved %d\n", known_cycles);
3611     if (known_cycles > 0)
3612       emit_addimm(HOST_CCREG, known_cycles, HOST_CCREG);
3613     return;
3614   }
3615   assem_debug("; muldiv stall unresolved\n");
3616   host_tempreg_acquire();
3617   emit_readword(&psxRegs.muldivBusyCycle, rtmp);
3618   emit_addimm(rtmp, -ccadj[i], rtmp);
3619   emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3620   emit_cmpimm(HOST_TEMPREG, 37);
3621   emit_cmovb_reg(rtmp, HOST_CCREG);
3622   //emit_log_gte_stall(i, 0, reglist);
3623   host_tempreg_release();
3624 }
3625
3626 static void cop2_get_dreg(u_int copr,signed char tl,signed char temp)
3627 {
3628   switch (copr) {
3629     case 1:
3630     case 3:
3631     case 5:
3632     case 8:
3633     case 9:
3634     case 10:
3635     case 11:
3636       emit_readword(&reg_cop2d[copr],tl);
3637       emit_signextend16(tl,tl);
3638       emit_writeword(tl,&reg_cop2d[copr]); // hmh
3639       break;
3640     case 7:
3641     case 16:
3642     case 17:
3643     case 18:
3644     case 19:
3645       emit_readword(&reg_cop2d[copr],tl);
3646       emit_andimm(tl,0xffff,tl);
3647       emit_writeword(tl,&reg_cop2d[copr]);
3648       break;
3649     case 15:
3650       emit_readword(&reg_cop2d[14],tl); // SXY2
3651       emit_writeword(tl,&reg_cop2d[copr]);
3652       break;
3653     case 28:
3654     case 29:
3655       c2op_mfc2_29_assemble(tl,temp);
3656       break;
3657     default:
3658       emit_readword(&reg_cop2d[copr],tl);
3659       break;
3660   }
3661 }
3662
3663 static void cop2_put_dreg(u_int copr,signed char sl,signed char temp)
3664 {
3665   switch (copr) {
3666     case 15:
3667       emit_readword(&reg_cop2d[13],temp);  // SXY1
3668       emit_writeword(sl,&reg_cop2d[copr]);
3669       emit_writeword(temp,&reg_cop2d[12]); // SXY0
3670       emit_readword(&reg_cop2d[14],temp);  // SXY2
3671       emit_writeword(sl,&reg_cop2d[14]);
3672       emit_writeword(temp,&reg_cop2d[13]); // SXY1
3673       break;
3674     case 28:
3675       emit_andimm(sl,0x001f,temp);
3676       emit_shlimm(temp,7,temp);
3677       emit_writeword(temp,&reg_cop2d[9]);
3678       emit_andimm(sl,0x03e0,temp);
3679       emit_shlimm(temp,2,temp);
3680       emit_writeword(temp,&reg_cop2d[10]);
3681       emit_andimm(sl,0x7c00,temp);
3682       emit_shrimm(temp,3,temp);
3683       emit_writeword(temp,&reg_cop2d[11]);
3684       emit_writeword(sl,&reg_cop2d[28]);
3685       break;
3686     case 30:
3687       emit_xorsar_imm(sl,sl,31,temp);
3688 #if defined(HAVE_ARMV5) || defined(__aarch64__)
3689       emit_clz(temp,temp);
3690 #else
3691       emit_movs(temp,HOST_TEMPREG);
3692       emit_movimm(0,temp);
3693       emit_jeq((int)out+4*4);
3694       emit_addpl_imm(temp,1,temp);
3695       emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
3696       emit_jns((int)out-2*4);
3697 #endif
3698       emit_writeword(sl,&reg_cop2d[30]);
3699       emit_writeword(temp,&reg_cop2d[31]);
3700       break;
3701     case 31:
3702       break;
3703     default:
3704       emit_writeword(sl,&reg_cop2d[copr]);
3705       break;
3706   }
3707 }
3708
3709 static void c2ls_assemble(int i, const struct regstat *i_regs, int ccadj_)
3710 {
3711   int s,tl;
3712   int ar;
3713   int offset;
3714   int memtarget=0,c=0;
3715   void *jaddr2=NULL;
3716   enum stub_type type;
3717   int agr=AGEN1+(i&1);
3718   int offset_reg = -1;
3719   int fastio_reg_override = -1;
3720   u_int reglist=get_host_reglist(i_regs->regmap);
3721   u_int copr=(source[i]>>16)&0x1f;
3722   s=get_reg(i_regs->regmap,dops[i].rs1);
3723   tl=get_reg(i_regs->regmap,FTEMP);
3724   offset=imm[i];
3725   assert(dops[i].rs1>0);
3726   assert(tl>=0);
3727
3728   if(i_regs->regmap[HOST_CCREG]==CCREG)
3729     reglist&=~(1<<HOST_CCREG);
3730
3731   // get the address
3732   if (dops[i].opcode==0x3a) { // SWC2
3733     ar=get_reg(i_regs->regmap,agr);
3734     if(ar<0) ar=get_reg(i_regs->regmap,-1);
3735     reglist|=1<<ar;
3736   } else { // LWC2
3737     ar=tl;
3738   }
3739   if(s>=0) c=(i_regs->wasconst>>s)&1;
3740   memtarget=c&&(((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE);
3741   if (!offset&&!c&&s>=0) ar=s;
3742   assert(ar>=0);
3743
3744   cop2_do_stall_check(0, i, i_regs, reglist);
3745
3746   if (dops[i].opcode==0x3a) { // SWC2
3747     cop2_get_dreg(copr,tl,-1);
3748     type=STOREW_STUB;
3749   }
3750   else
3751     type=LOADW_STUB;
3752
3753   if(c&&!memtarget) {
3754     jaddr2=out;
3755     emit_jmp(0); // inline_readstub/inline_writestub?
3756   }
3757   else {
3758     if(!c) {
3759       jaddr2 = emit_fastpath_cmp_jump(i, i_regs, ar,
3760                 &offset_reg, &fastio_reg_override);
3761     }
3762     else if (ram_offset && memtarget) {
3763       offset_reg = get_ro_reg(i_regs, 0);
3764     }
3765     switch (dops[i].opcode) {
3766     case 0x32: { // LWC2
3767       int a = ar;
3768       if (fastio_reg_override >= 0)
3769         a = fastio_reg_override;
3770       do_load_word(a, tl, offset_reg);
3771       break;
3772     }
3773     case 0x3a: { // SWC2
3774       #ifdef DESTRUCTIVE_SHIFT
3775       if(!offset&&!c&&s>=0) emit_mov(s,ar);
3776       #endif
3777       int a = ar;
3778       if (fastio_reg_override >= 0)
3779         a = fastio_reg_override;
3780       do_store_word(a, 0, tl, offset_reg, 1);
3781       break;
3782     }
3783     default:
3784       assert(0);
3785     }
3786   }
3787   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3788     host_tempreg_release();
3789   if(jaddr2)
3790     add_stub_r(type,jaddr2,out,i,ar,i_regs,ccadj_,reglist);
3791   if(dops[i].opcode==0x3a) // SWC2
3792   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3793 #if defined(HOST_IMM8)
3794     int ir=get_reg(i_regs->regmap,INVCP);
3795     assert(ir>=0);
3796     emit_cmpmem_indexedsr12_reg(ir,ar,1);
3797 #else
3798     emit_cmpmem_indexedsr12_imm(invalid_code,ar,1);
3799 #endif
3800     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3801     emit_callne(invalidate_addr_reg[ar]);
3802     #else
3803     void *jaddr3 = out;
3804     emit_jne(0);
3805     add_stub(INVCODE_STUB,jaddr3,out,reglist|(1<<HOST_CCREG),ar,0,0,0);
3806     #endif
3807   }
3808   if (dops[i].opcode==0x32) { // LWC2
3809     host_tempreg_acquire();
3810     cop2_put_dreg(copr,tl,HOST_TEMPREG);
3811     host_tempreg_release();
3812   }
3813 }
3814
3815 static void cop2_assemble(int i, const struct regstat *i_regs)
3816 {
3817   u_int copr = (source[i]>>11) & 0x1f;
3818   signed char temp = get_reg(i_regs->regmap, -1);
3819
3820   if (!HACK_ENABLED(NDHACK_NO_STALLS)) {
3821     u_int reglist = reglist_exclude(get_host_reglist(i_regs->regmap), temp, -1);
3822     if (dops[i].opcode2 == 0 || dops[i].opcode2 == 2) { // MFC2/CFC2
3823       signed char tl = get_reg(i_regs->regmap, dops[i].rt1);
3824       reglist = reglist_exclude(reglist, tl, -1);
3825     }
3826     cop2_do_stall_check(0, i, i_regs, reglist);
3827   }
3828   if (dops[i].opcode2==0) { // MFC2
3829     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
3830     if(tl>=0&&dops[i].rt1!=0)
3831       cop2_get_dreg(copr,tl,temp);
3832   }
3833   else if (dops[i].opcode2==4) { // MTC2
3834     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
3835     cop2_put_dreg(copr,sl,temp);
3836   }
3837   else if (dops[i].opcode2==2) // CFC2
3838   {
3839     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
3840     if(tl>=0&&dops[i].rt1!=0)
3841       emit_readword(&reg_cop2c[copr],tl);
3842   }
3843   else if (dops[i].opcode2==6) // CTC2
3844   {
3845     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
3846     switch(copr) {
3847       case 4:
3848       case 12:
3849       case 20:
3850       case 26:
3851       case 27:
3852       case 29:
3853       case 30:
3854         emit_signextend16(sl,temp);
3855         break;
3856       case 31:
3857         c2op_ctc2_31_assemble(sl,temp);
3858         break;
3859       default:
3860         temp=sl;
3861         break;
3862     }
3863     emit_writeword(temp,&reg_cop2c[copr]);
3864     assert(sl>=0);
3865   }
3866 }
3867
3868 static void do_unalignedwritestub(int n)
3869 {
3870   assem_debug("do_unalignedwritestub %x\n",start+stubs[n].a*4);
3871   literal_pool(256);
3872   set_jump_target(stubs[n].addr, out);
3873
3874   int i=stubs[n].a;
3875   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3876   int addr=stubs[n].b;
3877   u_int reglist=stubs[n].e;
3878   signed char *i_regmap=i_regs->regmap;
3879   int temp2=get_reg(i_regmap,FTEMP);
3880   int rt;
3881   rt=get_reg(i_regmap,dops[i].rs2);
3882   assert(rt>=0);
3883   assert(addr>=0);
3884   assert(dops[i].opcode==0x2a||dops[i].opcode==0x2e); // SWL/SWR only implemented
3885   reglist|=(1<<addr);
3886   reglist&=~(1<<temp2);
3887
3888   // don't bother with it and call write handler
3889   save_regs(reglist);
3890   pass_args(addr,rt);
3891   int cc=get_reg(i_regmap,CCREG);
3892   if(cc<0)
3893     emit_loadreg(CCREG,2);
3894   emit_addimm(cc<0?2:cc,(int)stubs[n].d+1,2);
3895   emit_far_call((dops[i].opcode==0x2a?jump_handle_swl:jump_handle_swr));
3896   emit_addimm(0,-((int)stubs[n].d+1),cc<0?2:cc);
3897   if(cc<0)
3898     emit_storereg(CCREG,2);
3899   restore_regs(reglist);
3900   emit_jmp(stubs[n].retaddr); // return address
3901 }
3902
3903 #ifndef multdiv_assemble
3904 void multdiv_assemble(int i,struct regstat *i_regs)
3905 {
3906   printf("Need multdiv_assemble for this architecture.\n");
3907   abort();
3908 }
3909 #endif
3910
3911 static void mov_assemble(int i, const struct regstat *i_regs)
3912 {
3913   //if(dops[i].opcode2==0x10||dops[i].opcode2==0x12) { // MFHI/MFLO
3914   //if(dops[i].opcode2==0x11||dops[i].opcode2==0x13) { // MTHI/MTLO
3915   if(dops[i].rt1) {
3916     signed char sl,tl;
3917     tl=get_reg(i_regs->regmap,dops[i].rt1);
3918     //assert(tl>=0);
3919     if(tl>=0) {
3920       sl=get_reg(i_regs->regmap,dops[i].rs1);
3921       if(sl>=0) emit_mov(sl,tl);
3922       else emit_loadreg(dops[i].rs1,tl);
3923     }
3924   }
3925   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) // MFHI/MFLO
3926     multdiv_do_stall(i, i_regs);
3927 }
3928
3929 // call interpreter, exception handler, things that change pc/regs/cycles ...
3930 static void call_c_cpu_handler(int i, const struct regstat *i_regs, int ccadj_, u_int pc, void *func)
3931 {
3932   signed char ccreg=get_reg(i_regs->regmap,CCREG);
3933   assert(ccreg==HOST_CCREG);
3934   assert(!is_delayslot);
3935   (void)ccreg;
3936
3937   emit_movimm(pc,3); // Get PC
3938   emit_readword(&last_count,2);
3939   emit_writeword(3,&psxRegs.pc);
3940   emit_addimm(HOST_CCREG,ccadj_,HOST_CCREG);
3941   emit_add(2,HOST_CCREG,2);
3942   emit_writeword(2,&psxRegs.cycle);
3943   emit_far_call(func);
3944   emit_far_jump(jump_to_new_pc);
3945 }
3946
3947 static void syscall_assemble(int i, const struct regstat *i_regs, int ccadj_)
3948 {
3949   // 'break' tends to be littered around to catch things like
3950   // division by 0 and is almost never executed, so don't emit much code here
3951   void *func = (dops[i].opcode2 == 0x0C)
3952     ? (is_delayslot ? jump_syscall_ds : jump_syscall)
3953     : (is_delayslot ? jump_break_ds : jump_break);
3954   assert(get_reg(i_regs->regmap, CCREG) == HOST_CCREG);
3955   emit_movimm(start + i*4, 2); // pc
3956   emit_addimm(HOST_CCREG, ccadj_ + CLOCK_ADJUST(1), HOST_CCREG);
3957   emit_far_jump(func);
3958 }
3959
3960 static void hlecall_assemble(int i, const struct regstat *i_regs, int ccadj_)
3961 {
3962   void *hlefunc = psxNULL;
3963   uint32_t hleCode = source[i] & 0x03ffffff;
3964   if (hleCode < ARRAY_SIZE(psxHLEt))
3965     hlefunc = psxHLEt[hleCode];
3966
3967   call_c_cpu_handler(i, i_regs, ccadj_, start + i*4+4, hlefunc);
3968 }
3969
3970 static void intcall_assemble(int i, const struct regstat *i_regs, int ccadj_)
3971 {
3972   call_c_cpu_handler(i, i_regs, ccadj_, start + i*4, execI);
3973 }
3974
3975 static void speculate_mov(int rs,int rt)
3976 {
3977   if(rt!=0) {
3978     smrv_strong_next|=1<<rt;
3979     smrv[rt]=smrv[rs];
3980   }
3981 }
3982
3983 static void speculate_mov_weak(int rs,int rt)
3984 {
3985   if(rt!=0) {
3986     smrv_weak_next|=1<<rt;
3987     smrv[rt]=smrv[rs];
3988   }
3989 }
3990
3991 static void speculate_register_values(int i)
3992 {
3993   if(i==0) {
3994     memcpy(smrv,psxRegs.GPR.r,sizeof(smrv));
3995     // gp,sp are likely to stay the same throughout the block
3996     smrv_strong_next=(1<<28)|(1<<29)|(1<<30);
3997     smrv_weak_next=~smrv_strong_next;
3998     //printf(" llr %08x\n", smrv[4]);
3999   }
4000   smrv_strong=smrv_strong_next;
4001   smrv_weak=smrv_weak_next;
4002   switch(dops[i].itype) {
4003     case ALU:
4004       if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
4005       else if((smrv_strong>>dops[i].rs2)&1) speculate_mov(dops[i].rs2,dops[i].rt1);
4006       else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
4007       else if((smrv_weak>>dops[i].rs2)&1) speculate_mov_weak(dops[i].rs2,dops[i].rt1);
4008       else {
4009         smrv_strong_next&=~(1<<dops[i].rt1);
4010         smrv_weak_next&=~(1<<dops[i].rt1);
4011       }
4012       break;
4013     case SHIFTIMM:
4014       smrv_strong_next&=~(1<<dops[i].rt1);
4015       smrv_weak_next&=~(1<<dops[i].rt1);
4016       // fallthrough
4017     case IMM16:
4018       if(dops[i].rt1&&is_const(&regs[i],dops[i].rt1)) {
4019         int value,hr=get_reg(regs[i].regmap,dops[i].rt1);
4020         if(hr>=0) {
4021           if(get_final_value(hr,i,&value))
4022                smrv[dops[i].rt1]=value;
4023           else smrv[dops[i].rt1]=constmap[i][hr];
4024           smrv_strong_next|=1<<dops[i].rt1;
4025         }
4026       }
4027       else {
4028         if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
4029         else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
4030       }
4031       break;
4032     case LOAD:
4033       if(start<0x2000&&(dops[i].rt1==26||(smrv[dops[i].rt1]>>24)==0xa0)) {
4034         // special case for BIOS
4035         smrv[dops[i].rt1]=0xa0000000;
4036         smrv_strong_next|=1<<dops[i].rt1;
4037         break;
4038       }
4039       // fallthrough
4040     case SHIFT:
4041     case LOADLR:
4042     case MOV:
4043       smrv_strong_next&=~(1<<dops[i].rt1);
4044       smrv_weak_next&=~(1<<dops[i].rt1);
4045       break;
4046     case COP0:
4047     case COP2:
4048       if(dops[i].opcode2==0||dops[i].opcode2==2) { // MFC/CFC
4049         smrv_strong_next&=~(1<<dops[i].rt1);
4050         smrv_weak_next&=~(1<<dops[i].rt1);
4051       }
4052       break;
4053     case C2LS:
4054       if (dops[i].opcode==0x32) { // LWC2
4055         smrv_strong_next&=~(1<<dops[i].rt1);
4056         smrv_weak_next&=~(1<<dops[i].rt1);
4057       }
4058       break;
4059   }
4060 #if 0
4061   int r=4;
4062   printf("x %08x %08x %d %d c %08x %08x\n",smrv[r],start+i*4,
4063     ((smrv_strong>>r)&1),(smrv_weak>>r)&1,regs[i].isconst,regs[i].wasconst);
4064 #endif
4065 }
4066
4067 static void ujump_assemble(int i, const struct regstat *i_regs);
4068 static void rjump_assemble(int i, const struct regstat *i_regs);
4069 static void cjump_assemble(int i, const struct regstat *i_regs);
4070 static void sjump_assemble(int i, const struct regstat *i_regs);
4071 static void pagespan_assemble(int i, const struct regstat *i_regs);
4072
4073 static int assemble(int i, const struct regstat *i_regs, int ccadj_)
4074 {
4075   int ds = 0;
4076   switch (dops[i].itype) {
4077     case ALU:
4078       alu_assemble(i, i_regs);
4079       break;
4080     case IMM16:
4081       imm16_assemble(i, i_regs);
4082       break;
4083     case SHIFT:
4084       shift_assemble(i, i_regs);
4085       break;
4086     case SHIFTIMM:
4087       shiftimm_assemble(i, i_regs);
4088       break;
4089     case LOAD:
4090       load_assemble(i, i_regs, ccadj_);
4091       break;
4092     case LOADLR:
4093       loadlr_assemble(i, i_regs, ccadj_);
4094       break;
4095     case STORE:
4096       store_assemble(i, i_regs, ccadj_);
4097       break;
4098     case STORELR:
4099       storelr_assemble(i, i_regs, ccadj_);
4100       break;
4101     case COP0:
4102       cop0_assemble(i, i_regs, ccadj_);
4103       break;
4104     case COP1:
4105       cop1_assemble(i, i_regs);
4106       break;
4107     case C1LS:
4108       c1ls_assemble(i, i_regs);
4109       break;
4110     case COP2:
4111       cop2_assemble(i, i_regs);
4112       break;
4113     case C2LS:
4114       c2ls_assemble(i, i_regs, ccadj_);
4115       break;
4116     case C2OP:
4117       c2op_assemble(i, i_regs);
4118       break;
4119     case MULTDIV:
4120       multdiv_assemble(i, i_regs);
4121       multdiv_prepare_stall(i, i_regs, ccadj_);
4122       break;
4123     case MOV:
4124       mov_assemble(i, i_regs);
4125       break;
4126     case SYSCALL:
4127       syscall_assemble(i, i_regs, ccadj_);
4128       break;
4129     case HLECALL:
4130       hlecall_assemble(i, i_regs, ccadj_);
4131       break;
4132     case INTCALL:
4133       intcall_assemble(i, i_regs, ccadj_);
4134       break;
4135     case UJUMP:
4136       ujump_assemble(i, i_regs);
4137       ds = 1;
4138       break;
4139     case RJUMP:
4140       rjump_assemble(i, i_regs);
4141       ds = 1;
4142       break;
4143     case CJUMP:
4144       cjump_assemble(i, i_regs);
4145       ds = 1;
4146       break;
4147     case SJUMP:
4148       sjump_assemble(i, i_regs);
4149       ds = 1;
4150       break;
4151     case SPAN:
4152       pagespan_assemble(i, i_regs);
4153       break;
4154     case NOP:
4155     case OTHER:
4156     case NI:
4157       // not handled, just skip
4158       break;
4159     default:
4160       assert(0);
4161   }
4162   return ds;
4163 }
4164
4165 static void ds_assemble(int i, const struct regstat *i_regs)
4166 {
4167   speculate_register_values(i);
4168   is_delayslot = 1;
4169   switch (dops[i].itype) {
4170     case SYSCALL:
4171     case HLECALL:
4172     case INTCALL:
4173     case SPAN:
4174     case UJUMP:
4175     case RJUMP:
4176     case CJUMP:
4177     case SJUMP:
4178       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4179       break;
4180     default:
4181       assemble(i, i_regs, ccadj[i]);
4182   }
4183   is_delayslot = 0;
4184 }
4185
4186 // Is the branch target a valid internal jump?
4187 static int internal_branch(int addr)
4188 {
4189   if(addr&1) return 0; // Indirect (register) jump
4190   if(addr>=start && addr<start+slen*4-4)
4191   {
4192     return 1;
4193   }
4194   return 0;
4195 }
4196
4197 static void wb_invalidate(signed char pre[],signed char entry[],uint64_t dirty,uint64_t u)
4198 {
4199   int hr;
4200   for(hr=0;hr<HOST_REGS;hr++) {
4201     if(hr!=EXCLUDE_REG) {
4202       if(pre[hr]!=entry[hr]) {
4203         if(pre[hr]>=0) {
4204           if((dirty>>hr)&1) {
4205             if(get_reg(entry,pre[hr])<0) {
4206               assert(pre[hr]<64);
4207               if(!((u>>pre[hr])&1))
4208                 emit_storereg(pre[hr],hr);
4209             }
4210           }
4211         }
4212       }
4213     }
4214   }
4215   // Move from one register to another (no writeback)
4216   for(hr=0;hr<HOST_REGS;hr++) {
4217     if(hr!=EXCLUDE_REG) {
4218       if(pre[hr]!=entry[hr]) {
4219         if(pre[hr]>=0&&(pre[hr]&63)<TEMPREG) {
4220           int nr;
4221           if((nr=get_reg(entry,pre[hr]))>=0) {
4222             emit_mov(hr,nr);
4223           }
4224         }
4225       }
4226     }
4227   }
4228 }
4229
4230 // Load the specified registers
4231 // This only loads the registers given as arguments because
4232 // we don't want to load things that will be overwritten
4233 static void load_regs(signed char entry[],signed char regmap[],int rs1,int rs2)
4234 {
4235   int hr;
4236   // Load 32-bit regs
4237   for(hr=0;hr<HOST_REGS;hr++) {
4238     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4239       if(entry[hr]!=regmap[hr]) {
4240         if(regmap[hr]==rs1||regmap[hr]==rs2)
4241         {
4242           if(regmap[hr]==0) {
4243             emit_zeroreg(hr);
4244           }
4245           else
4246           {
4247             emit_loadreg(regmap[hr],hr);
4248           }
4249         }
4250       }
4251     }
4252   }
4253 }
4254
4255 // Load registers prior to the start of a loop
4256 // so that they are not loaded within the loop
4257 static void loop_preload(signed char pre[],signed char entry[])
4258 {
4259   int hr;
4260   for(hr=0;hr<HOST_REGS;hr++) {
4261     if(hr!=EXCLUDE_REG) {
4262       if(pre[hr]!=entry[hr]) {
4263         if(entry[hr]>=0) {
4264           if(get_reg(pre,entry[hr])<0) {
4265             assem_debug("loop preload:\n");
4266             //printf("loop preload: %d\n",hr);
4267             if(entry[hr]==0) {
4268               emit_zeroreg(hr);
4269             }
4270             else if(entry[hr]<TEMPREG)
4271             {
4272               emit_loadreg(entry[hr],hr);
4273             }
4274             else if(entry[hr]-64<TEMPREG)
4275             {
4276               emit_loadreg(entry[hr],hr);
4277             }
4278           }
4279         }
4280       }
4281     }
4282   }
4283 }
4284
4285 // Generate address for load/store instruction
4286 // goes to AGEN for writes, FTEMP for LOADLR and cop1/2 loads
4287 void address_generation(int i, const struct regstat *i_regs, signed char entry[])
4288 {
4289   if (dops[i].is_load || dops[i].is_store) {
4290     int ra=-1;
4291     int agr=AGEN1+(i&1);
4292     if(dops[i].itype==LOAD) {
4293       ra=get_reg(i_regs->regmap,dops[i].rt1);
4294       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4295       assert(ra>=0);
4296     }
4297     if(dops[i].itype==LOADLR) {
4298       ra=get_reg(i_regs->regmap,FTEMP);
4299     }
4300     if(dops[i].itype==STORE||dops[i].itype==STORELR) {
4301       ra=get_reg(i_regs->regmap,agr);
4302       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4303     }
4304     if(dops[i].itype==C2LS) {
4305       if ((dops[i].opcode&0x3b)==0x31||(dops[i].opcode&0x3b)==0x32) // LWC1/LDC1/LWC2/LDC2
4306         ra=get_reg(i_regs->regmap,FTEMP);
4307       else { // SWC1/SDC1/SWC2/SDC2
4308         ra=get_reg(i_regs->regmap,agr);
4309         if(ra<0) ra=get_reg(i_regs->regmap,-1);
4310       }
4311     }
4312     int rs=get_reg(i_regs->regmap,dops[i].rs1);
4313     if(ra>=0) {
4314       int offset=imm[i];
4315       int c=(i_regs->wasconst>>rs)&1;
4316       if(dops[i].rs1==0) {
4317         // Using r0 as a base address
4318         if(!entry||entry[ra]!=agr) {
4319           if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4320             emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4321           }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4322             emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4323           }else{
4324             emit_movimm(offset,ra);
4325           }
4326         } // else did it in the previous cycle
4327       }
4328       else if(rs<0) {
4329         if(!entry||entry[ra]!=dops[i].rs1)
4330           emit_loadreg(dops[i].rs1,ra);
4331         //if(!entry||entry[ra]!=dops[i].rs1)
4332         //  printf("poor load scheduling!\n");
4333       }
4334       else if(c) {
4335         if(dops[i].rs1!=dops[i].rt1||dops[i].itype!=LOAD) {
4336           if(!entry||entry[ra]!=agr) {
4337             if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4338               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4339             }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4340               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4341             }else{
4342               emit_movimm(constmap[i][rs]+offset,ra);
4343               regs[i].loadedconst|=1<<ra;
4344             }
4345           } // else did it in the previous cycle
4346         } // else load_consts already did it
4347       }
4348       if(offset&&!c&&dops[i].rs1) {
4349         if(rs>=0) {
4350           emit_addimm(rs,offset,ra);
4351         }else{
4352           emit_addimm(ra,offset,ra);
4353         }
4354       }
4355     }
4356   }
4357   // Preload constants for next instruction
4358   if (dops[i+1].is_load || dops[i+1].is_store) {
4359     int agr,ra;
4360     // Actual address
4361     agr=AGEN1+((i+1)&1);
4362     ra=get_reg(i_regs->regmap,agr);
4363     if(ra>=0) {
4364       int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
4365       int offset=imm[i+1];
4366       int c=(regs[i+1].wasconst>>rs)&1;
4367       if(c&&(dops[i+1].rs1!=dops[i+1].rt1||dops[i+1].itype!=LOAD)) {
4368         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4369           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4370         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4371           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4372         }else{
4373           emit_movimm(constmap[i+1][rs]+offset,ra);
4374           regs[i+1].loadedconst|=1<<ra;
4375         }
4376       }
4377       else if(dops[i+1].rs1==0) {
4378         // Using r0 as a base address
4379         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4380           emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4381         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4382           emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4383         }else{
4384           emit_movimm(offset,ra);
4385         }
4386       }
4387     }
4388   }
4389 }
4390
4391 static int get_final_value(int hr, int i, int *value)
4392 {
4393   int reg=regs[i].regmap[hr];
4394   while(i<slen-1) {
4395     if(regs[i+1].regmap[hr]!=reg) break;
4396     if(!((regs[i+1].isconst>>hr)&1)) break;
4397     if(dops[i+1].bt) break;
4398     i++;
4399   }
4400   if(i<slen-1) {
4401     if (dops[i].is_jump) {
4402       *value=constmap[i][hr];
4403       return 1;
4404     }
4405     if(!dops[i+1].bt) {
4406       if (dops[i+1].is_jump) {
4407         // Load in delay slot, out-of-order execution
4408         if(dops[i+2].itype==LOAD&&dops[i+2].rs1==reg&&dops[i+2].rt1==reg&&((regs[i+1].wasconst>>hr)&1))
4409         {
4410           // Precompute load address
4411           *value=constmap[i][hr]+imm[i+2];
4412           return 1;
4413         }
4414       }
4415       if(dops[i+1].itype==LOAD&&dops[i+1].rs1==reg&&dops[i+1].rt1==reg)
4416       {
4417         // Precompute load address
4418         *value=constmap[i][hr]+imm[i+1];
4419         //printf("c=%x imm=%lx\n",(long)constmap[i][hr],imm[i+1]);
4420         return 1;
4421       }
4422     }
4423   }
4424   *value=constmap[i][hr];
4425   //printf("c=%lx\n",(long)constmap[i][hr]);
4426   if(i==slen-1) return 1;
4427   assert(reg < 64);
4428   return !((unneeded_reg[i+1]>>reg)&1);
4429 }
4430
4431 // Load registers with known constants
4432 static void load_consts(signed char pre[],signed char regmap[],int i)
4433 {
4434   int hr,hr2;
4435   // propagate loaded constant flags
4436   if(i==0||dops[i].bt)
4437     regs[i].loadedconst=0;
4438   else {
4439     for(hr=0;hr<HOST_REGS;hr++) {
4440       if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((regs[i-1].isconst>>hr)&1)&&pre[hr]==regmap[hr]
4441          &&regmap[hr]==regs[i-1].regmap[hr]&&((regs[i-1].loadedconst>>hr)&1))
4442       {
4443         regs[i].loadedconst|=1<<hr;
4444       }
4445     }
4446   }
4447   // Load 32-bit regs
4448   for(hr=0;hr<HOST_REGS;hr++) {
4449     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4450       //if(entry[hr]!=regmap[hr]) {
4451       if(!((regs[i].loadedconst>>hr)&1)) {
4452         assert(regmap[hr]<64);
4453         if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4454           int value,similar=0;
4455           if(get_final_value(hr,i,&value)) {
4456             // see if some other register has similar value
4457             for(hr2=0;hr2<HOST_REGS;hr2++) {
4458               if(hr2!=EXCLUDE_REG&&((regs[i].loadedconst>>hr2)&1)) {
4459                 if(is_similar_value(value,constmap[i][hr2])) {
4460                   similar=1;
4461                   break;
4462                 }
4463               }
4464             }
4465             if(similar) {
4466               int value2;
4467               if(get_final_value(hr2,i,&value2)) // is this needed?
4468                 emit_movimm_from(value2,hr2,value,hr);
4469               else
4470                 emit_movimm(value,hr);
4471             }
4472             else if(value==0) {
4473               emit_zeroreg(hr);
4474             }
4475             else {
4476               emit_movimm(value,hr);
4477             }
4478           }
4479           regs[i].loadedconst|=1<<hr;
4480         }
4481       }
4482     }
4483   }
4484 }
4485
4486 static void load_all_consts(const signed char regmap[], u_int dirty, int i)
4487 {
4488   int hr;
4489   // Load 32-bit regs
4490   for(hr=0;hr<HOST_REGS;hr++) {
4491     if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((dirty>>hr)&1)) {
4492       assert(regmap[hr] < 64);
4493       if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4494         int value=constmap[i][hr];
4495         if(value==0) {
4496           emit_zeroreg(hr);
4497         }
4498         else {
4499           emit_movimm(value,hr);
4500         }
4501       }
4502     }
4503   }
4504 }
4505
4506 // Write out all dirty registers (except cycle count)
4507 static void wb_dirtys(const signed char i_regmap[], uint64_t i_dirty)
4508 {
4509   int hr;
4510   for(hr=0;hr<HOST_REGS;hr++) {
4511     if(hr!=EXCLUDE_REG) {
4512       if(i_regmap[hr]>0) {
4513         if(i_regmap[hr]!=CCREG) {
4514           if((i_dirty>>hr)&1) {
4515             assert(i_regmap[hr]<64);
4516             emit_storereg(i_regmap[hr],hr);
4517           }
4518         }
4519       }
4520     }
4521   }
4522 }
4523
4524 // Write out dirty registers that we need to reload (pair with load_needed_regs)
4525 // This writes the registers not written by store_regs_bt
4526 static void wb_needed_dirtys(const signed char i_regmap[], uint64_t i_dirty, int addr)
4527 {
4528   int hr;
4529   int t=(addr-start)>>2;
4530   for(hr=0;hr<HOST_REGS;hr++) {
4531     if(hr!=EXCLUDE_REG) {
4532       if(i_regmap[hr]>0) {
4533         if(i_regmap[hr]!=CCREG) {
4534           if(i_regmap[hr]==regs[t].regmap_entry[hr] && ((regs[t].dirty>>hr)&1)) {
4535             if((i_dirty>>hr)&1) {
4536               assert(i_regmap[hr]<64);
4537               emit_storereg(i_regmap[hr],hr);
4538             }
4539           }
4540         }
4541       }
4542     }
4543   }
4544 }
4545
4546 // Load all registers (except cycle count)
4547 static void load_all_regs(const signed char i_regmap[])
4548 {
4549   int hr;
4550   for(hr=0;hr<HOST_REGS;hr++) {
4551     if(hr!=EXCLUDE_REG) {
4552       if(i_regmap[hr]==0) {
4553         emit_zeroreg(hr);
4554       }
4555       else
4556       if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4557       {
4558         emit_loadreg(i_regmap[hr],hr);
4559       }
4560     }
4561   }
4562 }
4563
4564 // Load all current registers also needed by next instruction
4565 static void load_needed_regs(const signed char i_regmap[], const signed char next_regmap[])
4566 {
4567   int hr;
4568   for(hr=0;hr<HOST_REGS;hr++) {
4569     if(hr!=EXCLUDE_REG) {
4570       if(get_reg(next_regmap,i_regmap[hr])>=0) {
4571         if(i_regmap[hr]==0) {
4572           emit_zeroreg(hr);
4573         }
4574         else
4575         if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4576         {
4577           emit_loadreg(i_regmap[hr],hr);
4578         }
4579       }
4580     }
4581   }
4582 }
4583
4584 // Load all regs, storing cycle count if necessary
4585 static void load_regs_entry(int t)
4586 {
4587   int hr;
4588   if(dops[t].is_ds) emit_addimm(HOST_CCREG,CLOCK_ADJUST(1),HOST_CCREG);
4589   else if(ccadj[t]) emit_addimm(HOST_CCREG,-ccadj[t],HOST_CCREG);
4590   if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4591     emit_storereg(CCREG,HOST_CCREG);
4592   }
4593   // Load 32-bit regs
4594   for(hr=0;hr<HOST_REGS;hr++) {
4595     if(regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4596       if(regs[t].regmap_entry[hr]==0) {
4597         emit_zeroreg(hr);
4598       }
4599       else if(regs[t].regmap_entry[hr]!=CCREG)
4600       {
4601         emit_loadreg(regs[t].regmap_entry[hr],hr);
4602       }
4603     }
4604   }
4605 }
4606
4607 // Store dirty registers prior to branch
4608 void store_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4609 {
4610   if(internal_branch(addr))
4611   {
4612     int t=(addr-start)>>2;
4613     int hr;
4614     for(hr=0;hr<HOST_REGS;hr++) {
4615       if(hr!=EXCLUDE_REG) {
4616         if(i_regmap[hr]>0 && i_regmap[hr]!=CCREG) {
4617           if(i_regmap[hr]!=regs[t].regmap_entry[hr] || !((regs[t].dirty>>hr)&1)) {
4618             if((i_dirty>>hr)&1) {
4619               assert(i_regmap[hr]<64);
4620               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4621                 emit_storereg(i_regmap[hr],hr);
4622             }
4623           }
4624         }
4625       }
4626     }
4627   }
4628   else
4629   {
4630     // Branch out of this block, write out all dirty regs
4631     wb_dirtys(i_regmap,i_dirty);
4632   }
4633 }
4634
4635 // Load all needed registers for branch target
4636 static void load_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4637 {
4638   //if(addr>=start && addr<(start+slen*4))
4639   if(internal_branch(addr))
4640   {
4641     int t=(addr-start)>>2;
4642     int hr;
4643     // Store the cycle count before loading something else
4644     if(i_regmap[HOST_CCREG]!=CCREG) {
4645       assert(i_regmap[HOST_CCREG]==-1);
4646     }
4647     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4648       emit_storereg(CCREG,HOST_CCREG);
4649     }
4650     // Load 32-bit regs
4651     for(hr=0;hr<HOST_REGS;hr++) {
4652       if(hr!=EXCLUDE_REG&&regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4653         if(i_regmap[hr]!=regs[t].regmap_entry[hr]) {
4654           if(regs[t].regmap_entry[hr]==0) {
4655             emit_zeroreg(hr);
4656           }
4657           else if(regs[t].regmap_entry[hr]!=CCREG)
4658           {
4659             emit_loadreg(regs[t].regmap_entry[hr],hr);
4660           }
4661         }
4662       }
4663     }
4664   }
4665 }
4666
4667 static int match_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4668 {
4669   if(addr>=start && addr<start+slen*4-4)
4670   {
4671     int t=(addr-start)>>2;
4672     int hr;
4673     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) return 0;
4674     for(hr=0;hr<HOST_REGS;hr++)
4675     {
4676       if(hr!=EXCLUDE_REG)
4677       {
4678         if(i_regmap[hr]!=regs[t].regmap_entry[hr])
4679         {
4680           if(regs[t].regmap_entry[hr]>=0&&(regs[t].regmap_entry[hr]|64)<TEMPREG+64)
4681           {
4682             return 0;
4683           }
4684           else
4685           if((i_dirty>>hr)&1)
4686           {
4687             if(i_regmap[hr]<TEMPREG)
4688             {
4689               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4690                 return 0;
4691             }
4692             else if(i_regmap[hr]>=64&&i_regmap[hr]<TEMPREG+64)
4693             {
4694               assert(0);
4695             }
4696           }
4697         }
4698         else // Same register but is it 32-bit or dirty?
4699         if(i_regmap[hr]>=0)
4700         {
4701           if(!((regs[t].dirty>>hr)&1))
4702           {
4703             if((i_dirty>>hr)&1)
4704             {
4705               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4706               {
4707                 //printf("%x: dirty no match\n",addr);
4708                 return 0;
4709               }
4710             }
4711           }
4712         }
4713       }
4714     }
4715     // Delay slots are not valid branch targets
4716     //if(t>0&&(dops[t-1].is_jump) return 0;
4717     // Delay slots require additional processing, so do not match
4718     if(dops[t].is_ds) return 0;
4719   }
4720   else
4721   {
4722     int hr;
4723     for(hr=0;hr<HOST_REGS;hr++)
4724     {
4725       if(hr!=EXCLUDE_REG)
4726       {
4727         if(i_regmap[hr]>=0)
4728         {
4729           if(hr!=HOST_CCREG||i_regmap[hr]!=CCREG)
4730           {
4731             if((i_dirty>>hr)&1)
4732             {
4733               return 0;
4734             }
4735           }
4736         }
4737       }
4738     }
4739   }
4740   return 1;
4741 }
4742
4743 #ifdef DRC_DBG
4744 static void drc_dbg_emit_do_cmp(int i, int ccadj_)
4745 {
4746   extern void do_insn_cmp();
4747   //extern int cycle;
4748   u_int hr, reglist = get_host_reglist(regs[i].regmap);
4749
4750   assem_debug("//do_insn_cmp %08x\n", start+i*4);
4751   save_regs(reglist);
4752   // write out changed consts to match the interpreter
4753   if (i > 0 && !dops[i].bt) {
4754     for (hr = 0; hr < HOST_REGS; hr++) {
4755       int reg = regs[i].regmap_entry[hr]; // regs[i-1].regmap[hr];
4756       if (hr == EXCLUDE_REG || reg < 0)
4757         continue;
4758       if (!((regs[i-1].isconst >> hr) & 1))
4759         continue;
4760       if (i > 1 && reg == regs[i-2].regmap[hr] && constmap[i-1][hr] == constmap[i-2][hr])
4761         continue;
4762       emit_movimm(constmap[i-1][hr],0);
4763       emit_storereg(reg, 0);
4764     }
4765   }
4766   emit_movimm(start+i*4,0);
4767   emit_writeword(0,&pcaddr);
4768   int cc = get_reg(regs[i].regmap_entry, CCREG);
4769   if (cc < 0)
4770     emit_loadreg(CCREG, cc = 0);
4771   emit_addimm(cc, ccadj_, 0);
4772   emit_writeword(0, &psxRegs.cycle);
4773   emit_far_call(do_insn_cmp);
4774   //emit_readword(&cycle,0);
4775   //emit_addimm(0,2,0);
4776   //emit_writeword(0,&cycle);
4777   (void)get_reg2;
4778   restore_regs(reglist);
4779   assem_debug("\\\\do_insn_cmp\n");
4780 }
4781 #else
4782 #define drc_dbg_emit_do_cmp(x,y)
4783 #endif
4784
4785 // Used when a branch jumps into the delay slot of another branch
4786 static void ds_assemble_entry(int i)
4787 {
4788   int t = (ba[i] - start) >> 2;
4789   int ccadj_ = -CLOCK_ADJUST(1);
4790   if (!instr_addr[t])
4791     instr_addr[t] = out;
4792   assem_debug("Assemble delay slot at %x\n",ba[i]);
4793   assem_debug("<->\n");
4794   drc_dbg_emit_do_cmp(t, ccadj_);
4795   if(regs[t].regmap_entry[HOST_CCREG]==CCREG&&regs[t].regmap[HOST_CCREG]!=CCREG)
4796     wb_register(CCREG,regs[t].regmap_entry,regs[t].wasdirty);
4797   load_regs(regs[t].regmap_entry,regs[t].regmap,dops[t].rs1,dops[t].rs2);
4798   address_generation(t,&regs[t],regs[t].regmap_entry);
4799   if (ram_offset && (dops[t].is_load || dops[t].is_store))
4800     load_regs(regs[t].regmap_entry,regs[t].regmap,ROREG,ROREG);
4801   if (dops[t].is_store)
4802     load_regs(regs[t].regmap_entry,regs[t].regmap,INVCP,INVCP);
4803   is_delayslot=0;
4804   switch (dops[t].itype) {
4805     case SYSCALL:
4806     case HLECALL:
4807     case INTCALL:
4808     case SPAN:
4809     case UJUMP:
4810     case RJUMP:
4811     case CJUMP:
4812     case SJUMP:
4813       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4814       break;
4815     default:
4816       assemble(t, &regs[t], ccadj_);
4817   }
4818   store_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4819   load_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4820   if(internal_branch(ba[i]+4))
4821     assem_debug("branch: internal\n");
4822   else
4823     assem_debug("branch: external\n");
4824   assert(internal_branch(ba[i]+4));
4825   add_to_linker(out,ba[i]+4,internal_branch(ba[i]+4));
4826   emit_jmp(0);
4827 }
4828
4829 static void emit_extjump(void *addr, u_int target)
4830 {
4831   emit_extjump2(addr, target, dyna_linker);
4832 }
4833
4834 static void emit_extjump_ds(void *addr, u_int target)
4835 {
4836   emit_extjump2(addr, target, dyna_linker_ds);
4837 }
4838
4839 // Load 2 immediates optimizing for small code size
4840 static void emit_mov2imm_compact(int imm1,u_int rt1,int imm2,u_int rt2)
4841 {
4842   emit_movimm(imm1,rt1);
4843   emit_movimm_from(imm1,rt1,imm2,rt2);
4844 }
4845
4846 static void do_cc(int i, const signed char i_regmap[], int *adj,
4847   int addr, int taken, int invert)
4848 {
4849   int count, count_plus2;
4850   void *jaddr;
4851   void *idle=NULL;
4852   int t=0;
4853   if(dops[i].itype==RJUMP)
4854   {
4855     *adj=0;
4856   }
4857   //if(ba[i]>=start && ba[i]<(start+slen*4))
4858   if(internal_branch(ba[i]))
4859   {
4860     t=(ba[i]-start)>>2;
4861     if(dops[t].is_ds) *adj=-CLOCK_ADJUST(1); // Branch into delay slot adds an extra cycle
4862     else *adj=ccadj[t];
4863   }
4864   else
4865   {
4866     *adj=0;
4867   }
4868   count = ccadj[i];
4869   count_plus2 = count + CLOCK_ADJUST(2);
4870   if(taken==TAKEN && i==(ba[i]-start)>>2 && source[i+1]==0) {
4871     // Idle loop
4872     if(count&1) emit_addimm_and_set_flags(2*(count+2),HOST_CCREG);
4873     idle=out;
4874     //emit_subfrommem(&idlecount,HOST_CCREG); // Count idle cycles
4875     emit_andimm(HOST_CCREG,3,HOST_CCREG);
4876     jaddr=out;
4877     emit_jmp(0);
4878   }
4879   else if(*adj==0||invert) {
4880     int cycles = count_plus2;
4881     // faster loop HACK
4882 #if 0
4883     if (t&&*adj) {
4884       int rel=t-i;
4885       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
4886         cycles=*adj+count+2-*adj;
4887     }
4888 #endif
4889     emit_addimm_and_set_flags(cycles, HOST_CCREG);
4890     jaddr = out;
4891     emit_jns(0);
4892   }
4893   else
4894   {
4895     emit_cmpimm(HOST_CCREG, -count_plus2);
4896     jaddr = out;
4897     emit_jns(0);
4898   }
4899   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:count_plus2,i,addr,taken,0);
4900 }
4901
4902 static void do_ccstub(int n)
4903 {
4904   literal_pool(256);
4905   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
4906   set_jump_target(stubs[n].addr, out);
4907   int i=stubs[n].b;
4908   if(stubs[n].d==NULLDS) {
4909     // Delay slot instruction is nullified ("likely" branch)
4910     wb_dirtys(regs[i].regmap,regs[i].dirty);
4911   }
4912   else if(stubs[n].d!=TAKEN) {
4913     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
4914   }
4915   else {
4916     if(internal_branch(ba[i]))
4917       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4918   }
4919   if(stubs[n].c!=-1)
4920   {
4921     // Save PC as return address
4922     emit_movimm(stubs[n].c,EAX);
4923     emit_writeword(EAX,&pcaddr);
4924   }
4925   else
4926   {
4927     // Return address depends on which way the branch goes
4928     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
4929     {
4930       int s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
4931       int s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
4932       if(dops[i].rs1==0)
4933       {
4934         s1l=s2l;
4935         s2l=-1;
4936       }
4937       else if(dops[i].rs2==0)
4938       {
4939         s2l=-1;
4940       }
4941       assert(s1l>=0);
4942       #ifdef DESTRUCTIVE_WRITEBACK
4943       if(dops[i].rs1) {
4944         if((branch_regs[i].dirty>>s1l)&&1)
4945           emit_loadreg(dops[i].rs1,s1l);
4946       }
4947       else {
4948         if((branch_regs[i].dirty>>s1l)&1)
4949           emit_loadreg(dops[i].rs2,s1l);
4950       }
4951       if(s2l>=0)
4952         if((branch_regs[i].dirty>>s2l)&1)
4953           emit_loadreg(dops[i].rs2,s2l);
4954       #endif
4955       int hr=0;
4956       int addr=-1,alt=-1,ntaddr=-1;
4957       while(hr<HOST_REGS)
4958       {
4959         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4960            (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4961            (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4962         {
4963           addr=hr++;break;
4964         }
4965         hr++;
4966       }
4967       while(hr<HOST_REGS)
4968       {
4969         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4970            (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4971            (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4972         {
4973           alt=hr++;break;
4974         }
4975         hr++;
4976       }
4977       if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
4978       {
4979         while(hr<HOST_REGS)
4980         {
4981           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4982              (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4983              (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4984           {
4985             ntaddr=hr;break;
4986           }
4987           hr++;
4988         }
4989         assert(hr<HOST_REGS);
4990       }
4991       if((dops[i].opcode&0x2f)==4) // BEQ
4992       {
4993         #ifdef HAVE_CMOV_IMM
4994         if(s2l>=0) emit_cmp(s1l,s2l);
4995         else emit_test(s1l,s1l);
4996         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
4997         #else
4998         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4999         if(s2l>=0) emit_cmp(s1l,s2l);
5000         else emit_test(s1l,s1l);
5001         emit_cmovne_reg(alt,addr);
5002         #endif
5003       }
5004       if((dops[i].opcode&0x2f)==5) // BNE
5005       {
5006         #ifdef HAVE_CMOV_IMM
5007         if(s2l>=0) emit_cmp(s1l,s2l);
5008         else emit_test(s1l,s1l);
5009         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5010         #else
5011         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5012         if(s2l>=0) emit_cmp(s1l,s2l);
5013         else emit_test(s1l,s1l);
5014         emit_cmovne_reg(alt,addr);
5015         #endif
5016       }
5017       if((dops[i].opcode&0x2f)==6) // BLEZ
5018       {
5019         //emit_movimm(ba[i],alt);
5020         //emit_movimm(start+i*4+8,addr);
5021         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5022         emit_cmpimm(s1l,1);
5023         emit_cmovl_reg(alt,addr);
5024       }
5025       if((dops[i].opcode&0x2f)==7) // BGTZ
5026       {
5027         //emit_movimm(ba[i],addr);
5028         //emit_movimm(start+i*4+8,ntaddr);
5029         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5030         emit_cmpimm(s1l,1);
5031         emit_cmovl_reg(ntaddr,addr);
5032       }
5033       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==0) // BLTZ
5034       {
5035         //emit_movimm(ba[i],alt);
5036         //emit_movimm(start+i*4+8,addr);
5037         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5038         emit_test(s1l,s1l);
5039         emit_cmovs_reg(alt,addr);
5040       }
5041       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==1) // BGEZ
5042       {
5043         //emit_movimm(ba[i],addr);
5044         //emit_movimm(start+i*4+8,alt);
5045         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5046         emit_test(s1l,s1l);
5047         emit_cmovs_reg(alt,addr);
5048       }
5049       if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
5050         if(source[i]&0x10000) // BC1T
5051         {
5052           //emit_movimm(ba[i],alt);
5053           //emit_movimm(start+i*4+8,addr);
5054           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5055           emit_testimm(s1l,0x800000);
5056           emit_cmovne_reg(alt,addr);
5057         }
5058         else // BC1F
5059         {
5060           //emit_movimm(ba[i],addr);
5061           //emit_movimm(start+i*4+8,alt);
5062           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5063           emit_testimm(s1l,0x800000);
5064           emit_cmovne_reg(alt,addr);
5065         }
5066       }
5067       emit_writeword(addr,&pcaddr);
5068     }
5069     else
5070     if(dops[i].itype==RJUMP)
5071     {
5072       int r=get_reg(branch_regs[i].regmap,dops[i].rs1);
5073       if (ds_writes_rjump_rs(i)) {
5074         r=get_reg(branch_regs[i].regmap,RTEMP);
5075       }
5076       emit_writeword(r,&pcaddr);
5077     }
5078     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
5079   }
5080   // Update cycle count
5081   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
5082   if(stubs[n].a) emit_addimm(HOST_CCREG,(int)stubs[n].a,HOST_CCREG);
5083   emit_far_call(cc_interrupt);
5084   if(stubs[n].a) emit_addimm(HOST_CCREG,-(int)stubs[n].a,HOST_CCREG);
5085   if(stubs[n].d==TAKEN) {
5086     if(internal_branch(ba[i]))
5087       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
5088     else if(dops[i].itype==RJUMP) {
5089       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
5090         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
5091       else
5092         emit_loadreg(dops[i].rs1,get_reg(branch_regs[i].regmap,dops[i].rs1));
5093     }
5094   }else if(stubs[n].d==NOTTAKEN) {
5095     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
5096     else load_all_regs(branch_regs[i].regmap);
5097   }else if(stubs[n].d==NULLDS) {
5098     // Delay slot instruction is nullified ("likely" branch)
5099     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
5100     else load_all_regs(regs[i].regmap);
5101   }else{
5102     load_all_regs(branch_regs[i].regmap);
5103   }
5104   if (stubs[n].retaddr)
5105     emit_jmp(stubs[n].retaddr);
5106   else
5107     do_jump_vaddr(stubs[n].e);
5108 }
5109
5110 static void add_to_linker(void *addr, u_int target, int ext)
5111 {
5112   assert(linkcount < ARRAY_SIZE(link_addr));
5113   link_addr[linkcount].addr = addr;
5114   link_addr[linkcount].target = target;
5115   link_addr[linkcount].ext = ext;
5116   linkcount++;
5117 }
5118
5119 static void ujump_assemble_write_ra(int i)
5120 {
5121   int rt;
5122   unsigned int return_address;
5123   rt=get_reg(branch_regs[i].regmap,31);
5124   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]);
5125   //assert(rt>=0);
5126   return_address=start+i*4+8;
5127   if(rt>=0) {
5128     #ifdef USE_MINI_HT
5129     if(internal_branch(return_address)&&dops[i+1].rt1!=31) {
5130       int temp=-1; // note: must be ds-safe
5131       #ifdef HOST_TEMPREG
5132       temp=HOST_TEMPREG;
5133       #endif
5134       if(temp>=0) do_miniht_insert(return_address,rt,temp);
5135       else emit_movimm(return_address,rt);
5136     }
5137     else
5138     #endif
5139     {
5140       #ifdef REG_PREFETCH
5141       if(temp>=0)
5142       {
5143         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5144       }
5145       #endif
5146       emit_movimm(return_address,rt); // PC into link register
5147       #ifdef IMM_PREFETCH
5148       emit_prefetch(hash_table_get(return_address));
5149       #endif
5150     }
5151   }
5152 }
5153
5154 static void ujump_assemble(int i, const struct regstat *i_regs)
5155 {
5156   int ra_done=0;
5157   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5158   address_generation(i+1,i_regs,regs[i].regmap_entry);
5159   #ifdef REG_PREFETCH
5160   int temp=get_reg(branch_regs[i].regmap,PTEMP);
5161   if(dops[i].rt1==31&&temp>=0)
5162   {
5163     signed char *i_regmap=i_regs->regmap;
5164     int return_address=start+i*4+8;
5165     if(get_reg(branch_regs[i].regmap,31)>0)
5166     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5167   }
5168   #endif
5169   if(dops[i].rt1==31&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5170     ujump_assemble_write_ra(i); // writeback ra for DS
5171     ra_done=1;
5172   }
5173   ds_assemble(i+1,i_regs);
5174   uint64_t bc_unneeded=branch_regs[i].u;
5175   bc_unneeded|=1|(1LL<<dops[i].rt1);
5176   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5177   load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5178   if(!ra_done&&dops[i].rt1==31)
5179     ujump_assemble_write_ra(i);
5180   int cc,adj;
5181   cc=get_reg(branch_regs[i].regmap,CCREG);
5182   assert(cc==HOST_CCREG);
5183   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5184   #ifdef REG_PREFETCH
5185   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5186   #endif
5187   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5188   if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5189   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5190   if(internal_branch(ba[i]))
5191     assem_debug("branch: internal\n");
5192   else
5193     assem_debug("branch: external\n");
5194   if (internal_branch(ba[i]) && dops[(ba[i]-start)>>2].is_ds) {
5195     ds_assemble_entry(i);
5196   }
5197   else {
5198     add_to_linker(out,ba[i],internal_branch(ba[i]));
5199     emit_jmp(0);
5200   }
5201 }
5202
5203 static void rjump_assemble_write_ra(int i)
5204 {
5205   int rt,return_address;
5206   assert(dops[i+1].rt1!=dops[i].rt1);
5207   assert(dops[i+1].rt2!=dops[i].rt1);
5208   rt=get_reg(branch_regs[i].regmap,dops[i].rt1);
5209   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]);
5210   assert(rt>=0);
5211   return_address=start+i*4+8;
5212   #ifdef REG_PREFETCH
5213   if(temp>=0)
5214   {
5215     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5216   }
5217   #endif
5218   emit_movimm(return_address,rt); // PC into link register
5219   #ifdef IMM_PREFETCH
5220   emit_prefetch(hash_table_get(return_address));
5221   #endif
5222 }
5223
5224 static void rjump_assemble(int i, const struct regstat *i_regs)
5225 {
5226   int temp;
5227   int rs,cc;
5228   int ra_done=0;
5229   rs=get_reg(branch_regs[i].regmap,dops[i].rs1);
5230   assert(rs>=0);
5231   if (ds_writes_rjump_rs(i)) {
5232     // Delay slot abuse, make a copy of the branch address register
5233     temp=get_reg(branch_regs[i].regmap,RTEMP);
5234     assert(temp>=0);
5235     assert(regs[i].regmap[temp]==RTEMP);
5236     emit_mov(rs,temp);
5237     rs=temp;
5238   }
5239   address_generation(i+1,i_regs,regs[i].regmap_entry);
5240   #ifdef REG_PREFETCH
5241   if(dops[i].rt1==31)
5242   {
5243     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
5244       signed char *i_regmap=i_regs->regmap;
5245       int return_address=start+i*4+8;
5246       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5247     }
5248   }
5249   #endif
5250   #ifdef USE_MINI_HT
5251   if(dops[i].rs1==31) {
5252     int rh=get_reg(regs[i].regmap,RHASH);
5253     if(rh>=0) do_preload_rhash(rh);
5254   }
5255   #endif
5256   if(dops[i].rt1!=0&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5257     rjump_assemble_write_ra(i);
5258     ra_done=1;
5259   }
5260   ds_assemble(i+1,i_regs);
5261   uint64_t bc_unneeded=branch_regs[i].u;
5262   bc_unneeded|=1|(1LL<<dops[i].rt1);
5263   bc_unneeded&=~(1LL<<dops[i].rs1);
5264   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5265   load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,CCREG);
5266   if(!ra_done&&dops[i].rt1!=0)
5267     rjump_assemble_write_ra(i);
5268   cc=get_reg(branch_regs[i].regmap,CCREG);
5269   assert(cc==HOST_CCREG);
5270   (void)cc;
5271   #ifdef USE_MINI_HT
5272   int rh=get_reg(branch_regs[i].regmap,RHASH);
5273   int ht=get_reg(branch_regs[i].regmap,RHTBL);
5274   if(dops[i].rs1==31) {
5275     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
5276     do_preload_rhtbl(ht);
5277     do_rhash(rs,rh);
5278   }
5279   #endif
5280   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5281   #ifdef DESTRUCTIVE_WRITEBACK
5282   if((branch_regs[i].dirty>>rs)&1) {
5283     if(dops[i].rs1!=dops[i+1].rt1&&dops[i].rs1!=dops[i+1].rt2) {
5284       emit_loadreg(dops[i].rs1,rs);
5285     }
5286   }
5287   #endif
5288   #ifdef REG_PREFETCH
5289   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5290   #endif
5291   #ifdef USE_MINI_HT
5292   if(dops[i].rs1==31) {
5293     do_miniht_load(ht,rh);
5294   }
5295   #endif
5296   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
5297   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
5298   //assert(adj==0);
5299   emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5300   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
5301   if(dops[i+1].itype==COP0&&(source[i+1]&0x3f)==0x10)
5302     // special case for RFE
5303     emit_jmp(0);
5304   else
5305     emit_jns(0);
5306   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5307   #ifdef USE_MINI_HT
5308   if(dops[i].rs1==31) {
5309     do_miniht_jump(rs,rh,ht);
5310   }
5311   else
5312   #endif
5313   {
5314     do_jump_vaddr(rs);
5315   }
5316   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5317   if(dops[i].rt1!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
5318   #endif
5319 }
5320
5321 static void cjump_assemble(int i, const struct regstat *i_regs)
5322 {
5323   const signed char *i_regmap = i_regs->regmap;
5324   int cc;
5325   int match;
5326   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5327   assem_debug("match=%d\n",match);
5328   int s1l,s2l;
5329   int unconditional=0,nop=0;
5330   int invert=0;
5331   int internal=internal_branch(ba[i]);
5332   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5333   if(!match) invert=1;
5334   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5335   if(i>(ba[i]-start)>>2) invert=1;
5336   #endif
5337   #ifdef __aarch64__
5338   invert=1; // because of near cond. branches
5339   #endif
5340
5341   if(dops[i].ooo) {
5342     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5343     s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
5344   }
5345   else {
5346     s1l=get_reg(i_regmap,dops[i].rs1);
5347     s2l=get_reg(i_regmap,dops[i].rs2);
5348   }
5349   if(dops[i].rs1==0&&dops[i].rs2==0)
5350   {
5351     if(dops[i].opcode&1) nop=1;
5352     else unconditional=1;
5353     //assert(dops[i].opcode!=5);
5354     //assert(dops[i].opcode!=7);
5355     //assert(dops[i].opcode!=0x15);
5356     //assert(dops[i].opcode!=0x17);
5357   }
5358   else if(dops[i].rs1==0)
5359   {
5360     s1l=s2l;
5361     s2l=-1;
5362   }
5363   else if(dops[i].rs2==0)
5364   {
5365     s2l=-1;
5366   }
5367
5368   if(dops[i].ooo) {
5369     // Out of order execution (delay slot first)
5370     //printf("OOOE\n");
5371     address_generation(i+1,i_regs,regs[i].regmap_entry);
5372     ds_assemble(i+1,i_regs);
5373     int adj;
5374     uint64_t bc_unneeded=branch_regs[i].u;
5375     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5376     bc_unneeded|=1;
5377     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5378     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs2);
5379     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5380     cc=get_reg(branch_regs[i].regmap,CCREG);
5381     assert(cc==HOST_CCREG);
5382     if(unconditional)
5383       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5384     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5385     //assem_debug("cycle count (adj)\n");
5386     if(unconditional) {
5387       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5388       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5389         if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5390         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5391         if(internal)
5392           assem_debug("branch: internal\n");
5393         else
5394           assem_debug("branch: external\n");
5395         if (internal && dops[(ba[i]-start)>>2].is_ds) {
5396           ds_assemble_entry(i);
5397         }
5398         else {
5399           add_to_linker(out,ba[i],internal);
5400           emit_jmp(0);
5401         }
5402         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5403         if(((u_int)out)&7) emit_addnop(0);
5404         #endif
5405       }
5406     }
5407     else if(nop) {
5408       emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5409       void *jaddr=out;
5410       emit_jns(0);
5411       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5412     }
5413     else {
5414       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5415       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5416       if(adj&&!invert) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5417
5418       //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]);
5419       assert(s1l>=0);
5420       if(dops[i].opcode==4) // BEQ
5421       {
5422         if(s2l>=0) emit_cmp(s1l,s2l);
5423         else emit_test(s1l,s1l);
5424         if(invert){
5425           nottaken=out;
5426           emit_jne(DJT_1);
5427         }else{
5428           add_to_linker(out,ba[i],internal);
5429           emit_jeq(0);
5430         }
5431       }
5432       if(dops[i].opcode==5) // BNE
5433       {
5434         if(s2l>=0) emit_cmp(s1l,s2l);
5435         else emit_test(s1l,s1l);
5436         if(invert){
5437           nottaken=out;
5438           emit_jeq(DJT_1);
5439         }else{
5440           add_to_linker(out,ba[i],internal);
5441           emit_jne(0);
5442         }
5443       }
5444       if(dops[i].opcode==6) // BLEZ
5445       {
5446         emit_cmpimm(s1l,1);
5447         if(invert){
5448           nottaken=out;
5449           emit_jge(DJT_1);
5450         }else{
5451           add_to_linker(out,ba[i],internal);
5452           emit_jl(0);
5453         }
5454       }
5455       if(dops[i].opcode==7) // BGTZ
5456       {
5457         emit_cmpimm(s1l,1);
5458         if(invert){
5459           nottaken=out;
5460           emit_jl(DJT_1);
5461         }else{
5462           add_to_linker(out,ba[i],internal);
5463           emit_jge(0);
5464         }
5465       }
5466       if(invert) {
5467         if(taken) set_jump_target(taken, out);
5468         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5469         if (match && (!internal || !dops[(ba[i]-start)>>2].is_ds)) {
5470           if(adj) {
5471             emit_addimm(cc,-adj,cc);
5472             add_to_linker(out,ba[i],internal);
5473           }else{
5474             emit_addnop(13);
5475             add_to_linker(out,ba[i],internal*2);
5476           }
5477           emit_jmp(0);
5478         }else
5479         #endif
5480         {
5481           if(adj) emit_addimm(cc,-adj,cc);
5482           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5483           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5484           if(internal)
5485             assem_debug("branch: internal\n");
5486           else
5487             assem_debug("branch: external\n");
5488           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5489             ds_assemble_entry(i);
5490           }
5491           else {
5492             add_to_linker(out,ba[i],internal);
5493             emit_jmp(0);
5494           }
5495         }
5496         set_jump_target(nottaken, out);
5497       }
5498
5499       if(nottaken1) set_jump_target(nottaken1, out);
5500       if(adj) {
5501         if(!invert) emit_addimm(cc,adj,cc);
5502       }
5503     } // (!unconditional)
5504   } // if(ooo)
5505   else
5506   {
5507     // In-order execution (branch first)
5508     void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5509     if(!unconditional&&!nop) {
5510       //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]);
5511       assert(s1l>=0);
5512       if((dops[i].opcode&0x2f)==4) // BEQ
5513       {
5514         if(s2l>=0) emit_cmp(s1l,s2l);
5515         else emit_test(s1l,s1l);
5516         nottaken=out;
5517         emit_jne(DJT_2);
5518       }
5519       if((dops[i].opcode&0x2f)==5) // BNE
5520       {
5521         if(s2l>=0) emit_cmp(s1l,s2l);
5522         else emit_test(s1l,s1l);
5523         nottaken=out;
5524         emit_jeq(DJT_2);
5525       }
5526       if((dops[i].opcode&0x2f)==6) // BLEZ
5527       {
5528         emit_cmpimm(s1l,1);
5529         nottaken=out;
5530         emit_jge(DJT_2);
5531       }
5532       if((dops[i].opcode&0x2f)==7) // BGTZ
5533       {
5534         emit_cmpimm(s1l,1);
5535         nottaken=out;
5536         emit_jl(DJT_2);
5537       }
5538     } // if(!unconditional)
5539     int adj;
5540     uint64_t ds_unneeded=branch_regs[i].u;
5541     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5542     ds_unneeded|=1;
5543     // branch taken
5544     if(!nop) {
5545       if(taken) set_jump_target(taken, out);
5546       assem_debug("1:\n");
5547       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5548       // load regs
5549       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5550       address_generation(i+1,&branch_regs[i],0);
5551       if (ram_offset)
5552         load_regs(regs[i].regmap,branch_regs[i].regmap,ROREG,ROREG);
5553       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5554       ds_assemble(i+1,&branch_regs[i]);
5555       cc=get_reg(branch_regs[i].regmap,CCREG);
5556       if(cc==-1) {
5557         emit_loadreg(CCREG,cc=HOST_CCREG);
5558         // CHECK: Is the following instruction (fall thru) allocated ok?
5559       }
5560       assert(cc==HOST_CCREG);
5561       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5562       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5563       assem_debug("cycle count (adj)\n");
5564       if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5565       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5566       if(internal)
5567         assem_debug("branch: internal\n");
5568       else
5569         assem_debug("branch: external\n");
5570       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5571         ds_assemble_entry(i);
5572       }
5573       else {
5574         add_to_linker(out,ba[i],internal);
5575         emit_jmp(0);
5576       }
5577     }
5578     // branch not taken
5579     if(!unconditional) {
5580       if(nottaken1) set_jump_target(nottaken1, out);
5581       set_jump_target(nottaken, out);
5582       assem_debug("2:\n");
5583       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5584       // load regs
5585       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5586       address_generation(i+1,&branch_regs[i],0);
5587       if (ram_offset)
5588         load_regs(regs[i].regmap,branch_regs[i].regmap,ROREG,ROREG);
5589       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5590       ds_assemble(i+1,&branch_regs[i]);
5591       cc=get_reg(branch_regs[i].regmap,CCREG);
5592       if (cc == -1) {
5593         // Cycle count isn't in a register, temporarily load it then write it out
5594         emit_loadreg(CCREG,HOST_CCREG);
5595         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5596         void *jaddr=out;
5597         emit_jns(0);
5598         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5599         emit_storereg(CCREG,HOST_CCREG);
5600       }
5601       else{
5602         cc=get_reg(i_regmap,CCREG);
5603         assert(cc==HOST_CCREG);
5604         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5605         void *jaddr=out;
5606         emit_jns(0);
5607         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5608       }
5609     }
5610   }
5611 }
5612
5613 static void sjump_assemble(int i, const struct regstat *i_regs)
5614 {
5615   const signed char *i_regmap = i_regs->regmap;
5616   int cc;
5617   int match;
5618   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5619   assem_debug("smatch=%d ooo=%d\n", match, dops[i].ooo);
5620   int s1l;
5621   int unconditional=0,nevertaken=0;
5622   int invert=0;
5623   int internal=internal_branch(ba[i]);
5624   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5625   if(!match) invert=1;
5626   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5627   if(i>(ba[i]-start)>>2) invert=1;
5628   #endif
5629   #ifdef __aarch64__
5630   invert=1; // because of near cond. branches
5631   #endif
5632
5633   //if(dops[i].opcode2>=0x10) return; // FIXME (BxxZAL)
5634   //assert(dops[i].opcode2<0x10||dops[i].rs1==0); // FIXME (BxxZAL)
5635
5636   if(dops[i].ooo) {
5637     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5638   }
5639   else {
5640     s1l=get_reg(i_regmap,dops[i].rs1);
5641   }
5642   if(dops[i].rs1==0)
5643   {
5644     if(dops[i].opcode2&1) unconditional=1;
5645     else nevertaken=1;
5646     // These are never taken (r0 is never less than zero)
5647     //assert(dops[i].opcode2!=0);
5648     //assert(dops[i].opcode2!=2);
5649     //assert(dops[i].opcode2!=0x10);
5650     //assert(dops[i].opcode2!=0x12);
5651   }
5652
5653   if(dops[i].ooo) {
5654     // Out of order execution (delay slot first)
5655     //printf("OOOE\n");
5656     address_generation(i+1,i_regs,regs[i].regmap_entry);
5657     ds_assemble(i+1,i_regs);
5658     int adj;
5659     uint64_t bc_unneeded=branch_regs[i].u;
5660     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5661     bc_unneeded|=1;
5662     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5663     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs1);
5664     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5665     if(dops[i].rt1==31) {
5666       int rt,return_address;
5667       rt=get_reg(branch_regs[i].regmap,31);
5668       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]);
5669       if(rt>=0) {
5670         // Save the PC even if the branch is not taken
5671         return_address=start+i*4+8;
5672         emit_movimm(return_address,rt); // PC into link register
5673         #ifdef IMM_PREFETCH
5674         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5675         #endif
5676       }
5677     }
5678     cc=get_reg(branch_regs[i].regmap,CCREG);
5679     assert(cc==HOST_CCREG);
5680     if(unconditional)
5681       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5682     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5683     assem_debug("cycle count (adj)\n");
5684     if(unconditional) {
5685       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5686       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5687         if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5688         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5689         if(internal)
5690           assem_debug("branch: internal\n");
5691         else
5692           assem_debug("branch: external\n");
5693         if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5694           ds_assemble_entry(i);
5695         }
5696         else {
5697           add_to_linker(out,ba[i],internal);
5698           emit_jmp(0);
5699         }
5700         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5701         if(((u_int)out)&7) emit_addnop(0);
5702         #endif
5703       }
5704     }
5705     else if(nevertaken) {
5706       emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5707       void *jaddr=out;
5708       emit_jns(0);
5709       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5710     }
5711     else {
5712       void *nottaken = NULL;
5713       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5714       if(adj&&!invert) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5715       {
5716         assert(s1l>=0);
5717         if((dops[i].opcode2&0xf)==0) // BLTZ/BLTZAL
5718         {
5719           emit_test(s1l,s1l);
5720           if(invert){
5721             nottaken=out;
5722             emit_jns(DJT_1);
5723           }else{
5724             add_to_linker(out,ba[i],internal);
5725             emit_js(0);
5726           }
5727         }
5728         if((dops[i].opcode2&0xf)==1) // BGEZ/BLTZAL
5729         {
5730           emit_test(s1l,s1l);
5731           if(invert){
5732             nottaken=out;
5733             emit_js(DJT_1);
5734           }else{
5735             add_to_linker(out,ba[i],internal);
5736             emit_jns(0);
5737           }
5738         }
5739       }
5740
5741       if(invert) {
5742         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5743         if (match && (!internal || !dops[(ba[i] - start) >> 2].is_ds)) {
5744           if(adj) {
5745             emit_addimm(cc,-adj,cc);
5746             add_to_linker(out,ba[i],internal);
5747           }else{
5748             emit_addnop(13);
5749             add_to_linker(out,ba[i],internal*2);
5750           }
5751           emit_jmp(0);
5752         }else
5753         #endif
5754         {
5755           if(adj) emit_addimm(cc,-adj,cc);
5756           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
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         set_jump_target(nottaken, out);
5771       }
5772
5773       if(adj) {
5774         if(!invert) emit_addimm(cc,adj,cc);
5775       }
5776     } // (!unconditional)
5777   } // if(ooo)
5778   else
5779   {
5780     // In-order execution (branch first)
5781     //printf("IOE\n");
5782     void *nottaken = NULL;
5783     if(dops[i].rt1==31) {
5784       int rt,return_address;
5785       rt=get_reg(branch_regs[i].regmap,31);
5786       if(rt>=0) {
5787         // Save the PC even if the branch is not taken
5788         return_address=start+i*4+8;
5789         emit_movimm(return_address,rt); // PC into link register
5790         #ifdef IMM_PREFETCH
5791         emit_prefetch(hash_table_get(return_address));
5792         #endif
5793       }
5794     }
5795     if(!unconditional) {
5796       //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]);
5797         assert(s1l>=0);
5798         if((dops[i].opcode2&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5799         {
5800           emit_test(s1l,s1l);
5801           nottaken=out;
5802           emit_jns(DJT_1);
5803         }
5804         if((dops[i].opcode2&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5805         {
5806           emit_test(s1l,s1l);
5807           nottaken=out;
5808           emit_js(DJT_1);
5809         }
5810     } // if(!unconditional)
5811     int adj;
5812     uint64_t ds_unneeded=branch_regs[i].u;
5813     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5814     ds_unneeded|=1;
5815     // branch taken
5816     if(!nevertaken) {
5817       //assem_debug("1:\n");
5818       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5819       // load regs
5820       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5821       address_generation(i+1,&branch_regs[i],0);
5822       if (ram_offset)
5823         load_regs(regs[i].regmap,branch_regs[i].regmap,ROREG,ROREG);
5824       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5825       ds_assemble(i+1,&branch_regs[i]);
5826       cc=get_reg(branch_regs[i].regmap,CCREG);
5827       if(cc==-1) {
5828         emit_loadreg(CCREG,cc=HOST_CCREG);
5829         // CHECK: Is the following instruction (fall thru) allocated ok?
5830       }
5831       assert(cc==HOST_CCREG);
5832       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5833       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5834       assem_debug("cycle count (adj)\n");
5835       if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5836       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5837       if(internal)
5838         assem_debug("branch: internal\n");
5839       else
5840         assem_debug("branch: external\n");
5841       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5842         ds_assemble_entry(i);
5843       }
5844       else {
5845         add_to_linker(out,ba[i],internal);
5846         emit_jmp(0);
5847       }
5848     }
5849     // branch not taken
5850     if(!unconditional) {
5851       set_jump_target(nottaken, out);
5852       assem_debug("1:\n");
5853       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5854       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5855       address_generation(i+1,&branch_regs[i],0);
5856       if (ram_offset)
5857         load_regs(regs[i].regmap,branch_regs[i].regmap,ROREG,ROREG);
5858       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5859       ds_assemble(i+1,&branch_regs[i]);
5860       cc=get_reg(branch_regs[i].regmap,CCREG);
5861       if (cc == -1) {
5862         // Cycle count isn't in a register, temporarily load it then write it out
5863         emit_loadreg(CCREG,HOST_CCREG);
5864         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5865         void *jaddr=out;
5866         emit_jns(0);
5867         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5868         emit_storereg(CCREG,HOST_CCREG);
5869       }
5870       else{
5871         cc=get_reg(i_regmap,CCREG);
5872         assert(cc==HOST_CCREG);
5873         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5874         void *jaddr=out;
5875         emit_jns(0);
5876         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5877       }
5878     }
5879   }
5880 }
5881
5882 static void pagespan_assemble(int i, const struct regstat *i_regs)
5883 {
5884   int s1l=get_reg(i_regs->regmap,dops[i].rs1);
5885   int s2l=get_reg(i_regs->regmap,dops[i].rs2);
5886   void *taken = NULL;
5887   void *nottaken = NULL;
5888   int unconditional=0;
5889   if(dops[i].rs1==0)
5890   {
5891     s1l=s2l;
5892     s2l=-1;
5893   }
5894   else if(dops[i].rs2==0)
5895   {
5896     s2l=-1;
5897   }
5898   int hr=0;
5899   int addr=-1,alt=-1,ntaddr=-1;
5900   if(i_regs->regmap[HOST_BTREG]<0) {addr=HOST_BTREG;}
5901   else {
5902     while(hr<HOST_REGS)
5903     {
5904       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5905          (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5906          (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5907       {
5908         addr=hr++;break;
5909       }
5910       hr++;
5911     }
5912   }
5913   while(hr<HOST_REGS)
5914   {
5915     if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5916        (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5917        (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5918     {
5919       alt=hr++;break;
5920     }
5921     hr++;
5922   }
5923   if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
5924   {
5925     while(hr<HOST_REGS)
5926     {
5927       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5928          (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5929          (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5930       {
5931         ntaddr=hr;break;
5932       }
5933       hr++;
5934     }
5935   }
5936   assert(hr<HOST_REGS);
5937   if((dops[i].opcode&0x2e)==4||dops[i].opcode==0x11) { // BEQ/BNE/BEQL/BNEL/BC1
5938     load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
5939   }
5940   emit_addimm(HOST_CCREG, ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5941   if(dops[i].opcode==2) // J
5942   {
5943     unconditional=1;
5944   }
5945   if(dops[i].opcode==3) // JAL
5946   {
5947     // TODO: mini_ht
5948     int rt=get_reg(i_regs->regmap,31);
5949     emit_movimm(start+i*4+8,rt);
5950     unconditional=1;
5951   }
5952   if(dops[i].opcode==0&&(dops[i].opcode2&0x3E)==8) // JR/JALR
5953   {
5954     emit_mov(s1l,addr);
5955     if(dops[i].opcode2==9) // JALR
5956     {
5957       int rt=get_reg(i_regs->regmap,dops[i].rt1);
5958       emit_movimm(start+i*4+8,rt);
5959     }
5960   }
5961   if((dops[i].opcode&0x3f)==4) // BEQ
5962   {
5963     if(dops[i].rs1==dops[i].rs2)
5964     {
5965       unconditional=1;
5966     }
5967     else
5968     #ifdef HAVE_CMOV_IMM
5969     if(1) {
5970       if(s2l>=0) emit_cmp(s1l,s2l);
5971       else emit_test(s1l,s1l);
5972       emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5973     }
5974     else
5975     #endif
5976     {
5977       assert(s1l>=0);
5978       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5979       if(s2l>=0) emit_cmp(s1l,s2l);
5980       else emit_test(s1l,s1l);
5981       emit_cmovne_reg(alt,addr);
5982     }
5983   }
5984   if((dops[i].opcode&0x3f)==5) // BNE
5985   {
5986     #ifdef HAVE_CMOV_IMM
5987     if(s2l>=0) emit_cmp(s1l,s2l);
5988     else emit_test(s1l,s1l);
5989     emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5990     #else
5991     assert(s1l>=0);
5992     emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5993     if(s2l>=0) emit_cmp(s1l,s2l);
5994     else emit_test(s1l,s1l);
5995     emit_cmovne_reg(alt,addr);
5996     #endif
5997   }
5998   if((dops[i].opcode&0x3f)==0x14) // BEQL
5999   {
6000     if(s2l>=0) emit_cmp(s1l,s2l);
6001     else emit_test(s1l,s1l);
6002     if(nottaken) set_jump_target(nottaken, out);
6003     nottaken=out;
6004     emit_jne(0);
6005   }
6006   if((dops[i].opcode&0x3f)==0x15) // BNEL
6007   {
6008     if(s2l>=0) emit_cmp(s1l,s2l);
6009     else emit_test(s1l,s1l);
6010     nottaken=out;
6011     emit_jeq(0);
6012     if(taken) set_jump_target(taken, out);
6013   }
6014   if((dops[i].opcode&0x3f)==6) // BLEZ
6015   {
6016     emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
6017     emit_cmpimm(s1l,1);
6018     emit_cmovl_reg(alt,addr);
6019   }
6020   if((dops[i].opcode&0x3f)==7) // BGTZ
6021   {
6022     emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
6023     emit_cmpimm(s1l,1);
6024     emit_cmovl_reg(ntaddr,addr);
6025   }
6026   if((dops[i].opcode&0x3f)==0x16) // BLEZL
6027   {
6028     assert((dops[i].opcode&0x3f)!=0x16);
6029   }
6030   if((dops[i].opcode&0x3f)==0x17) // BGTZL
6031   {
6032     assert((dops[i].opcode&0x3f)!=0x17);
6033   }
6034   assert(dops[i].opcode!=1); // BLTZ/BGEZ
6035
6036   //FIXME: Check CSREG
6037   if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
6038     if((source[i]&0x30000)==0) // BC1F
6039     {
6040       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
6041       emit_testimm(s1l,0x800000);
6042       emit_cmovne_reg(alt,addr);
6043     }
6044     if((source[i]&0x30000)==0x10000) // BC1T
6045     {
6046       emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
6047       emit_testimm(s1l,0x800000);
6048       emit_cmovne_reg(alt,addr);
6049     }
6050     if((source[i]&0x30000)==0x20000) // BC1FL
6051     {
6052       emit_testimm(s1l,0x800000);
6053       nottaken=out;
6054       emit_jne(0);
6055     }
6056     if((source[i]&0x30000)==0x30000) // BC1TL
6057     {
6058       emit_testimm(s1l,0x800000);
6059       nottaken=out;
6060       emit_jeq(0);
6061     }
6062   }
6063
6064   assert(i_regs->regmap[HOST_CCREG]==CCREG);
6065   wb_dirtys(regs[i].regmap,regs[i].dirty);
6066   if(unconditional)
6067   {
6068     emit_movimm(ba[i],HOST_BTREG);
6069   }
6070   else if(addr!=HOST_BTREG)
6071   {
6072     emit_mov(addr,HOST_BTREG);
6073   }
6074   void *branch_addr=out;
6075   emit_jmp(0);
6076   int target_addr=start+i*4+5;
6077   void *stub=out;
6078   void *compiled_target_addr=check_addr(target_addr);
6079   emit_extjump_ds(branch_addr, target_addr);
6080   if(compiled_target_addr) {
6081     set_jump_target(branch_addr, compiled_target_addr);
6082     add_jump_out(target_addr,stub);
6083   }
6084   else set_jump_target(branch_addr, stub);
6085 }
6086
6087 // Assemble the delay slot for the above
6088 static void pagespan_ds()
6089 {
6090   assem_debug("initial delay slot:\n");
6091   u_int vaddr=start+1;
6092   u_int page=get_page(vaddr);
6093   u_int vpage=get_vpage(vaddr);
6094   ll_add(jump_dirty+vpage,vaddr,(void *)out);
6095   do_dirty_stub_ds(slen*4);
6096   ll_add(jump_in+page,vaddr,(void *)out);
6097   assert(regs[0].regmap_entry[HOST_CCREG]==CCREG);
6098   if(regs[0].regmap[HOST_CCREG]!=CCREG)
6099     wb_register(CCREG,regs[0].regmap_entry,regs[0].wasdirty);
6100   if(regs[0].regmap[HOST_BTREG]!=BTREG)
6101     emit_writeword(HOST_BTREG,&branch_target);
6102   load_regs(regs[0].regmap_entry,regs[0].regmap,dops[0].rs1,dops[0].rs2);
6103   address_generation(0,&regs[0],regs[0].regmap_entry);
6104   if (ram_offset && (dops[0].is_load || dops[0].is_store))
6105     load_regs(regs[0].regmap_entry,regs[0].regmap,ROREG,ROREG);
6106   if (dops[0].is_store)
6107     load_regs(regs[0].regmap_entry,regs[0].regmap,INVCP,INVCP);
6108   is_delayslot=0;
6109   switch (dops[0].itype) {
6110     case SYSCALL:
6111     case HLECALL:
6112     case INTCALL:
6113     case SPAN:
6114     case UJUMP:
6115     case RJUMP:
6116     case CJUMP:
6117     case SJUMP:
6118       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
6119       break;
6120     default:
6121       assemble(0, &regs[0], 0);
6122   }
6123   int btaddr=get_reg(regs[0].regmap,BTREG);
6124   if(btaddr<0) {
6125     btaddr=get_reg(regs[0].regmap,-1);
6126     emit_readword(&branch_target,btaddr);
6127   }
6128   assert(btaddr!=HOST_CCREG);
6129   if(regs[0].regmap[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
6130 #ifdef HOST_IMM8
6131   host_tempreg_acquire();
6132   emit_movimm(start+4,HOST_TEMPREG);
6133   emit_cmp(btaddr,HOST_TEMPREG);
6134   host_tempreg_release();
6135 #else
6136   emit_cmpimm(btaddr,start+4);
6137 #endif
6138   void *branch = out;
6139   emit_jeq(0);
6140   store_regs_bt(regs[0].regmap,regs[0].dirty,-1);
6141   do_jump_vaddr(btaddr);
6142   set_jump_target(branch, out);
6143   store_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6144   load_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6145 }
6146
6147 static void check_regmap(signed char *regmap)
6148 {
6149 #ifndef NDEBUG
6150   int i,j;
6151   for (i = 0; i < HOST_REGS; i++) {
6152     if (regmap[i] < 0)
6153       continue;
6154     for (j = i + 1; j < HOST_REGS; j++)
6155       assert(regmap[i] != regmap[j]);
6156   }
6157 #endif
6158 }
6159
6160 // Basic liveness analysis for MIPS registers
6161 static void unneeded_registers(int istart,int iend,int r)
6162 {
6163   int i;
6164   uint64_t u,gte_u,b,gte_b;
6165   uint64_t temp_u,temp_gte_u=0;
6166   uint64_t gte_u_unknown=0;
6167   if (HACK_ENABLED(NDHACK_GTE_UNNEEDED))
6168     gte_u_unknown=~0ll;
6169   if(iend==slen-1) {
6170     u=1;
6171     gte_u=gte_u_unknown;
6172   }else{
6173     //u=unneeded_reg[iend+1];
6174     u=1;
6175     gte_u=gte_unneeded[iend+1];
6176   }
6177
6178   for (i=iend;i>=istart;i--)
6179   {
6180     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
6181     if(dops[i].is_jump)
6182     {
6183       // If subroutine call, flag return address as a possible branch target
6184       if(dops[i].rt1==31 && i<slen-2) dops[i+2].bt=1;
6185
6186       if(ba[i]<start || ba[i]>=(start+slen*4))
6187       {
6188         // Branch out of this block, flush all regs
6189         u=1;
6190         gte_u=gte_u_unknown;
6191         branch_unneeded_reg[i]=u;
6192         // Merge in delay slot
6193         u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6194         u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6195         u|=1;
6196         gte_u|=gte_rt[i+1];
6197         gte_u&=~gte_rs[i+1];
6198       }
6199       else
6200       {
6201         // Internal branch, flag target
6202         dops[(ba[i]-start)>>2].bt=1;
6203         if(ba[i]<=start+i*4) {
6204           // Backward branch
6205           if(dops[i].is_ujump)
6206           {
6207             // Unconditional branch
6208             temp_u=1;
6209             temp_gte_u=0;
6210           } else {
6211             // Conditional branch (not taken case)
6212             temp_u=unneeded_reg[i+2];
6213             temp_gte_u&=gte_unneeded[i+2];
6214           }
6215           // Merge in delay slot
6216           temp_u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6217           temp_u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6218           temp_u|=1;
6219           temp_gte_u|=gte_rt[i+1];
6220           temp_gte_u&=~gte_rs[i+1];
6221           temp_u|=(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2);
6222           temp_u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
6223           temp_u|=1;
6224           temp_gte_u|=gte_rt[i];
6225           temp_gte_u&=~gte_rs[i];
6226           unneeded_reg[i]=temp_u;
6227           gte_unneeded[i]=temp_gte_u;
6228           // Only go three levels deep.  This recursion can take an
6229           // excessive amount of time if there are a lot of nested loops.
6230           if(r<2) {
6231             unneeded_registers((ba[i]-start)>>2,i-1,r+1);
6232           }else{
6233             unneeded_reg[(ba[i]-start)>>2]=1;
6234             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
6235           }
6236         } /*else*/ if(1) {
6237           if (dops[i].is_ujump)
6238           {
6239             // Unconditional branch
6240             u=unneeded_reg[(ba[i]-start)>>2];
6241             gte_u=gte_unneeded[(ba[i]-start)>>2];
6242             branch_unneeded_reg[i]=u;
6243             // Merge in delay slot
6244             u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6245             u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6246             u|=1;
6247             gte_u|=gte_rt[i+1];
6248             gte_u&=~gte_rs[i+1];
6249           } else {
6250             // Conditional branch
6251             b=unneeded_reg[(ba[i]-start)>>2];
6252             gte_b=gte_unneeded[(ba[i]-start)>>2];
6253             branch_unneeded_reg[i]=b;
6254             // Branch delay slot
6255             b|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6256             b&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6257             b|=1;
6258             gte_b|=gte_rt[i+1];
6259             gte_b&=~gte_rs[i+1];
6260             u&=b;
6261             gte_u&=gte_b;
6262             if(i<slen-1) {
6263               branch_unneeded_reg[i]&=unneeded_reg[i+2];
6264             } else {
6265               branch_unneeded_reg[i]=1;
6266             }
6267           }
6268         }
6269       }
6270     }
6271     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
6272     {
6273       // SYSCALL instruction (software interrupt)
6274       u=1;
6275     }
6276     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
6277     {
6278       // ERET instruction (return from interrupt)
6279       u=1;
6280     }
6281     //u=1; // DEBUG
6282     // Written registers are unneeded
6283     u|=1LL<<dops[i].rt1;
6284     u|=1LL<<dops[i].rt2;
6285     gte_u|=gte_rt[i];
6286     // Accessed registers are needed
6287     u&=~(1LL<<dops[i].rs1);
6288     u&=~(1LL<<dops[i].rs2);
6289     gte_u&=~gte_rs[i];
6290     if(gte_rs[i]&&dops[i].rt1&&(unneeded_reg[i+1]&(1ll<<dops[i].rt1)))
6291       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
6292     // Source-target dependencies
6293     // R0 is always unneeded
6294     u|=1;
6295     // Save it
6296     unneeded_reg[i]=u;
6297     gte_unneeded[i]=gte_u;
6298     /*
6299     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
6300     printf("U:");
6301     int r;
6302     for(r=1;r<=CCREG;r++) {
6303       if((unneeded_reg[i]>>r)&1) {
6304         if(r==HIREG) printf(" HI");
6305         else if(r==LOREG) printf(" LO");
6306         else printf(" r%d",r);
6307       }
6308     }
6309     printf("\n");
6310     */
6311   }
6312 }
6313
6314 // Write back dirty registers as soon as we will no longer modify them,
6315 // so that we don't end up with lots of writes at the branches.
6316 void clean_registers(int istart,int iend,int wr)
6317 {
6318   int i;
6319   int r;
6320   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
6321   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
6322   if(iend==slen-1) {
6323     will_dirty_i=will_dirty_next=0;
6324     wont_dirty_i=wont_dirty_next=0;
6325   }else{
6326     will_dirty_i=will_dirty_next=will_dirty[iend+1];
6327     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
6328   }
6329   for (i=iend;i>=istart;i--)
6330   {
6331     if(dops[i].is_jump)
6332     {
6333       if(ba[i]<start || ba[i]>=(start+slen*4))
6334       {
6335         // Branch out of this block, flush all regs
6336         if (dops[i].is_ujump)
6337         {
6338           // Unconditional branch
6339           will_dirty_i=0;
6340           wont_dirty_i=0;
6341           // Merge in delay slot (will dirty)
6342           for(r=0;r<HOST_REGS;r++) {
6343             if(r!=EXCLUDE_REG) {
6344               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6345               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6346               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6347               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6348               if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6349               if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6350               if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6351               if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6352               if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6353               if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6354               if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6355               if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6356               if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6357               if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6358             }
6359           }
6360         }
6361         else
6362         {
6363           // Conditional branch
6364           will_dirty_i=0;
6365           wont_dirty_i=wont_dirty_next;
6366           // Merge in delay slot (will dirty)
6367           for(r=0;r<HOST_REGS;r++) {
6368             if(r!=EXCLUDE_REG) {
6369               if (1) { // !dops[i].likely) {
6370                 // Might not dirty if likely branch is not taken
6371                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6372                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6373                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6374                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6375                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6376                 if(branch_regs[i].regmap[r]==0) will_dirty_i&=~(1<<r);
6377                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6378                 //if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6379                 //if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6380                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6381                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6382                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6383                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6384                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6385               }
6386             }
6387           }
6388         }
6389         // Merge in delay slot (wont dirty)
6390         for(r=0;r<HOST_REGS;r++) {
6391           if(r!=EXCLUDE_REG) {
6392             if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6393             if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6394             if((regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6395             if((regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6396             if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6397             if((branch_regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6398             if((branch_regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6399             if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6400             if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6401             if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6402           }
6403         }
6404         if(wr) {
6405           #ifndef DESTRUCTIVE_WRITEBACK
6406           branch_regs[i].dirty&=wont_dirty_i;
6407           #endif
6408           branch_regs[i].dirty|=will_dirty_i;
6409         }
6410       }
6411       else
6412       {
6413         // Internal branch
6414         if(ba[i]<=start+i*4) {
6415           // Backward branch
6416           if (dops[i].is_ujump)
6417           {
6418             // Unconditional branch
6419             temp_will_dirty=0;
6420             temp_wont_dirty=0;
6421             // Merge in delay slot (will dirty)
6422             for(r=0;r<HOST_REGS;r++) {
6423               if(r!=EXCLUDE_REG) {
6424                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6425                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6426                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6427                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6428                 if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6429                 if(branch_regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6430                 if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6431                 if((regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6432                 if((regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6433                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6434                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6435                 if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6436                 if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6437                 if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6438               }
6439             }
6440           } else {
6441             // Conditional branch (not taken case)
6442             temp_will_dirty=will_dirty_next;
6443             temp_wont_dirty=wont_dirty_next;
6444             // Merge in delay slot (will dirty)
6445             for(r=0;r<HOST_REGS;r++) {
6446               if(r!=EXCLUDE_REG) {
6447                 if (1) { // !dops[i].likely) {
6448                   // Will not dirty if likely branch is not taken
6449                   if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6450                   if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6451                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6452                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6453                   if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6454                   if(branch_regs[i].regmap[r]==0) temp_will_dirty&=~(1<<r);
6455                   if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6456                   //if((regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6457                   //if((regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6458                   if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6459                   if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6460                   if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6461                   if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6462                   if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6463                 }
6464               }
6465             }
6466           }
6467           // Merge in delay slot (wont dirty)
6468           for(r=0;r<HOST_REGS;r++) {
6469             if(r!=EXCLUDE_REG) {
6470               if((regs[i].regmap[r]&63)==dops[i].rt1) temp_wont_dirty|=1<<r;
6471               if((regs[i].regmap[r]&63)==dops[i].rt2) temp_wont_dirty|=1<<r;
6472               if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_wont_dirty|=1<<r;
6473               if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_wont_dirty|=1<<r;
6474               if(regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6475               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_wont_dirty|=1<<r;
6476               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_wont_dirty|=1<<r;
6477               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_wont_dirty|=1<<r;
6478               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_wont_dirty|=1<<r;
6479               if(branch_regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6480             }
6481           }
6482           // Deal with changed mappings
6483           if(i<iend) {
6484             for(r=0;r<HOST_REGS;r++) {
6485               if(r!=EXCLUDE_REG) {
6486                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
6487                   temp_will_dirty&=~(1<<r);
6488                   temp_wont_dirty&=~(1<<r);
6489                   if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6490                     temp_will_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6491                     temp_wont_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6492                   } else {
6493                     temp_will_dirty|=1<<r;
6494                     temp_wont_dirty|=1<<r;
6495                   }
6496                 }
6497               }
6498             }
6499           }
6500           if(wr) {
6501             will_dirty[i]=temp_will_dirty;
6502             wont_dirty[i]=temp_wont_dirty;
6503             clean_registers((ba[i]-start)>>2,i-1,0);
6504           }else{
6505             // Limit recursion.  It can take an excessive amount
6506             // of time if there are a lot of nested loops.
6507             will_dirty[(ba[i]-start)>>2]=0;
6508             wont_dirty[(ba[i]-start)>>2]=-1;
6509           }
6510         }
6511         /*else*/ if(1)
6512         {
6513           if (dops[i].is_ujump)
6514           {
6515             // Unconditional branch
6516             will_dirty_i=0;
6517             wont_dirty_i=0;
6518           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6519             for(r=0;r<HOST_REGS;r++) {
6520               if(r!=EXCLUDE_REG) {
6521                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6522                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
6523                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6524                 }
6525                 if(branch_regs[i].regmap[r]>=0) {
6526                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6527                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6528                 }
6529               }
6530             }
6531           //}
6532             // Merge in delay slot
6533             for(r=0;r<HOST_REGS;r++) {
6534               if(r!=EXCLUDE_REG) {
6535                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6536                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6537                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6538                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6539                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6540                 if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6541                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6542                 if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6543                 if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6544                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6545                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6546                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6547                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6548                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6549               }
6550             }
6551           } else {
6552             // Conditional branch
6553             will_dirty_i=will_dirty_next;
6554             wont_dirty_i=wont_dirty_next;
6555           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6556             for(r=0;r<HOST_REGS;r++) {
6557               if(r!=EXCLUDE_REG) {
6558                 signed char target_reg=branch_regs[i].regmap[r];
6559                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6560                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6561                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6562                 }
6563                 else if(target_reg>=0) {
6564                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6565                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6566                 }
6567               }
6568             }
6569           //}
6570             // Merge in delay slot
6571             for(r=0;r<HOST_REGS;r++) {
6572               if(r!=EXCLUDE_REG) {
6573                 if (1) { // !dops[i].likely) {
6574                   // Might not dirty if likely branch is not taken
6575                   if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6576                   if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6577                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6578                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6579                   if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6580                   if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6581                   if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6582                   //if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6583                   //if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6584                   if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6585                   if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6586                   if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6587                   if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6588                   if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6589                 }
6590               }
6591             }
6592           }
6593           // Merge in delay slot (won't dirty)
6594           for(r=0;r<HOST_REGS;r++) {
6595             if(r!=EXCLUDE_REG) {
6596               if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6597               if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6598               if((regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6599               if((regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6600               if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6601               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6602               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6603               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6604               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6605               if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6606             }
6607           }
6608           if(wr) {
6609             #ifndef DESTRUCTIVE_WRITEBACK
6610             branch_regs[i].dirty&=wont_dirty_i;
6611             #endif
6612             branch_regs[i].dirty|=will_dirty_i;
6613           }
6614         }
6615       }
6616     }
6617     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
6618     {
6619       // SYSCALL instruction (software interrupt)
6620       will_dirty_i=0;
6621       wont_dirty_i=0;
6622     }
6623     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
6624     {
6625       // ERET instruction (return from interrupt)
6626       will_dirty_i=0;
6627       wont_dirty_i=0;
6628     }
6629     will_dirty_next=will_dirty_i;
6630     wont_dirty_next=wont_dirty_i;
6631     for(r=0;r<HOST_REGS;r++) {
6632       if(r!=EXCLUDE_REG) {
6633         if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6634         if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6635         if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6636         if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6637         if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6638         if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6639         if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6640         if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6641         if(i>istart) {
6642           if (!dops[i].is_jump)
6643           {
6644             // Don't store a register immediately after writing it,
6645             // may prevent dual-issue.
6646             if((regs[i].regmap[r]&63)==dops[i-1].rt1) wont_dirty_i|=1<<r;
6647             if((regs[i].regmap[r]&63)==dops[i-1].rt2) wont_dirty_i|=1<<r;
6648           }
6649         }
6650       }
6651     }
6652     // Save it
6653     will_dirty[i]=will_dirty_i;
6654     wont_dirty[i]=wont_dirty_i;
6655     // Mark registers that won't be dirtied as not dirty
6656     if(wr) {
6657         regs[i].dirty|=will_dirty_i;
6658         #ifndef DESTRUCTIVE_WRITEBACK
6659         regs[i].dirty&=wont_dirty_i;
6660         if(dops[i].is_jump)
6661         {
6662           if (i < iend-1 && !dops[i].is_ujump) {
6663             for(r=0;r<HOST_REGS;r++) {
6664               if(r!=EXCLUDE_REG) {
6665                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
6666                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
6667                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6668               }
6669             }
6670           }
6671         }
6672         else
6673         {
6674           if(i<iend) {
6675             for(r=0;r<HOST_REGS;r++) {
6676               if(r!=EXCLUDE_REG) {
6677                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
6678                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
6679                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6680               }
6681             }
6682           }
6683         }
6684         #endif
6685       //}
6686     }
6687     // Deal with changed mappings
6688     temp_will_dirty=will_dirty_i;
6689     temp_wont_dirty=wont_dirty_i;
6690     for(r=0;r<HOST_REGS;r++) {
6691       if(r!=EXCLUDE_REG) {
6692         int nr;
6693         if(regs[i].regmap[r]==regmap_pre[i][r]) {
6694           if(wr) {
6695             #ifndef DESTRUCTIVE_WRITEBACK
6696             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6697             #endif
6698             regs[i].wasdirty|=will_dirty_i&(1<<r);
6699           }
6700         }
6701         else if(regmap_pre[i][r]>=0&&(nr=get_reg(regs[i].regmap,regmap_pre[i][r]))>=0) {
6702           // Register moved to a different register
6703           will_dirty_i&=~(1<<r);
6704           wont_dirty_i&=~(1<<r);
6705           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
6706           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
6707           if(wr) {
6708             #ifndef DESTRUCTIVE_WRITEBACK
6709             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6710             #endif
6711             regs[i].wasdirty|=will_dirty_i&(1<<r);
6712           }
6713         }
6714         else {
6715           will_dirty_i&=~(1<<r);
6716           wont_dirty_i&=~(1<<r);
6717           if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6718             will_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6719             wont_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6720           } else {
6721             wont_dirty_i|=1<<r;
6722             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
6723           }
6724         }
6725       }
6726     }
6727   }
6728 }
6729
6730 #ifdef DISASM
6731 #include <inttypes.h>
6732 void print_regmap(const char *name, const signed char *regmap)
6733 {
6734   char buf[5];
6735   int i, l;
6736   fputs(name, stdout);
6737   for (i = 0; i < HOST_REGS; i++) {
6738     l = 0;
6739     if (regmap[i] >= 0)
6740       l = snprintf(buf, sizeof(buf), "$%d", regmap[i]);
6741     for (; l < 3; l++)
6742       buf[l] = ' ';
6743     buf[l] = 0;
6744     printf(" r%d=%s", i, buf);
6745   }
6746   fputs("\n", stdout);
6747 }
6748
6749   /* disassembly */
6750 void disassemble_inst(int i)
6751 {
6752     if (dops[i].bt) printf("*"); else printf(" ");
6753     switch(dops[i].itype) {
6754       case UJUMP:
6755         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6756       case CJUMP:
6757         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;
6758       case SJUMP:
6759         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;
6760       case RJUMP:
6761         if (dops[i].opcode==0x9&&dops[i].rt1!=31)
6762           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1);
6763         else
6764           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6765         break;
6766       case SPAN:
6767         printf (" %x: %s (pagespan) r%d,r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2,ba[i]);break;
6768       case IMM16:
6769         if(dops[i].opcode==0xf) //LUI
6770           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],dops[i].rt1,imm[i]&0xffff);
6771         else
6772           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6773         break;
6774       case LOAD:
6775       case LOADLR:
6776         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6777         break;
6778       case STORE:
6779       case STORELR:
6780         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rs2,dops[i].rs1,imm[i]);
6781         break;
6782       case ALU:
6783       case SHIFT:
6784         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,dops[i].rs2);
6785         break;
6786       case MULTDIV:
6787         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2);
6788         break;
6789       case SHIFTIMM:
6790         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6791         break;
6792       case MOV:
6793         if((dops[i].opcode2&0x1d)==0x10)
6794           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rt1);
6795         else if((dops[i].opcode2&0x1d)==0x11)
6796           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6797         else
6798           printf (" %x: %s\n",start+i*4,insn[i]);
6799         break;
6800       case COP0:
6801         if(dops[i].opcode2==0)
6802           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC0
6803         else if(dops[i].opcode2==4)
6804           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC0
6805         else printf (" %x: %s\n",start+i*4,insn[i]);
6806         break;
6807       case COP1:
6808         if(dops[i].opcode2<3)
6809           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC1
6810         else if(dops[i].opcode2>3)
6811           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC1
6812         else printf (" %x: %s\n",start+i*4,insn[i]);
6813         break;
6814       case COP2:
6815         if(dops[i].opcode2<3)
6816           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC2
6817         else if(dops[i].opcode2>3)
6818           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC2
6819         else printf (" %x: %s\n",start+i*4,insn[i]);
6820         break;
6821       case C1LS:
6822         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6823         break;
6824       case C2LS:
6825         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6826         break;
6827       case INTCALL:
6828         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6829         break;
6830       default:
6831         //printf (" %s %8x\n",insn[i],source[i]);
6832         printf (" %x: %s\n",start+i*4,insn[i]);
6833     }
6834     return;
6835     printf("D: %"PRIu64"  WD: %"PRIu64"  U: %"PRIu64"\n",
6836       regs[i].dirty, regs[i].wasdirty, unneeded_reg[i]);
6837     print_regmap("pre:   ", regmap_pre[i]);
6838     print_regmap("entry: ", regs[i].regmap_entry);
6839     print_regmap("map:   ", regs[i].regmap);
6840     if (dops[i].is_jump) {
6841       print_regmap("bentry:", branch_regs[i].regmap_entry);
6842       print_regmap("bmap:  ", branch_regs[i].regmap);
6843     }
6844 }
6845 #else
6846 static void disassemble_inst(int i) {}
6847 #endif // DISASM
6848
6849 #define DRC_TEST_VAL 0x74657374
6850
6851 static void new_dynarec_test(void)
6852 {
6853   int (*testfunc)(void);
6854   void *beginning;
6855   int ret[2];
6856   size_t i;
6857
6858   // check structure linkage
6859   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6860   {
6861     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6862   }
6863
6864   SysPrintf("testing if we can run recompiled code @%p...\n", out);
6865   ((volatile u_int *)out)[0]++; // make cache dirty
6866
6867   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6868     out = ndrc->translation_cache;
6869     beginning = start_block();
6870     emit_movimm(DRC_TEST_VAL + i, 0); // test
6871     emit_ret();
6872     literal_pool(0);
6873     end_block(beginning);
6874     testfunc = beginning;
6875     ret[i] = testfunc();
6876   }
6877
6878   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6879     SysPrintf("test passed.\n");
6880   else
6881     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6882   out = ndrc->translation_cache;
6883 }
6884
6885 // clear the state completely, instead of just marking
6886 // things invalid like invalidate_all_pages() does
6887 void new_dynarec_clear_full(void)
6888 {
6889   int n;
6890   out = ndrc->translation_cache;
6891   memset(invalid_code,1,sizeof(invalid_code));
6892   memset(hash_table,0xff,sizeof(hash_table));
6893   memset(mini_ht,-1,sizeof(mini_ht));
6894   memset(restore_candidate,0,sizeof(restore_candidate));
6895   memset(shadow,0,sizeof(shadow));
6896   copy=shadow;
6897   expirep=16384; // Expiry pointer, +2 blocks
6898   pending_exception=0;
6899   literalcount=0;
6900   stop_after_jal=0;
6901   inv_code_start=inv_code_end=~0;
6902   hack_addr=0;
6903   f1_hack=0;
6904   // TLB
6905   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6906   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6907   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6908
6909   cycle_multiplier_old = cycle_multiplier;
6910   new_dynarec_hacks_old = new_dynarec_hacks;
6911 }
6912
6913 void new_dynarec_init(void)
6914 {
6915   SysPrintf("Init new dynarec, ndrc size %x\n", (int)sizeof(*ndrc));
6916
6917 #ifdef _3DS
6918   check_rosalina();
6919 #endif
6920 #ifdef BASE_ADDR_DYNAMIC
6921   #ifdef VITA
6922   sceBlock = getVMBlock(); //sceKernelAllocMemBlockForVM("code", sizeof(*ndrc));
6923   if (sceBlock <= 0)
6924     SysPrintf("sceKernelAllocMemBlockForVM failed: %x\n", sceBlock);
6925   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6926   if (ret < 0)
6927     SysPrintf("sceKernelGetMemBlockBase failed: %x\n", ret);
6928   sceKernelOpenVMDomain();
6929   sceClibPrintf("translation_cache = 0x%08lx\n ", (long)ndrc->translation_cache);
6930   #elif defined(_MSC_VER)
6931   ndrc = VirtualAlloc(NULL, sizeof(*ndrc), MEM_COMMIT | MEM_RESERVE,
6932     PAGE_EXECUTE_READWRITE);
6933   #else
6934   uintptr_t desired_addr = 0;
6935   #ifdef __ELF__
6936   extern char _end;
6937   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6938   #endif
6939   ndrc = mmap((void *)desired_addr, sizeof(*ndrc),
6940             PROT_READ | PROT_WRITE | PROT_EXEC,
6941             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
6942   if (ndrc == MAP_FAILED) {
6943     SysPrintf("mmap() failed: %s\n", strerror(errno));
6944     abort();
6945   }
6946   #endif
6947 #else
6948   #ifndef NO_WRITE_EXEC
6949   // not all systems allow execute in data segment by default
6950   // size must be 4K aligned for 3DS?
6951   if (mprotect(ndrc, sizeof(*ndrc),
6952                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6953     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6954   #endif
6955 #endif
6956   out = ndrc->translation_cache;
6957   cycle_multiplier=200;
6958   new_dynarec_clear_full();
6959 #ifdef HOST_IMM8
6960   // Copy this into local area so we don't have to put it in every literal pool
6961   invc_ptr=invalid_code;
6962 #endif
6963   arch_init();
6964   new_dynarec_test();
6965   ram_offset=(uintptr_t)rdram-0x80000000;
6966   if (ram_offset!=0)
6967     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6968 }
6969
6970 void new_dynarec_cleanup(void)
6971 {
6972   int n;
6973 #ifdef BASE_ADDR_DYNAMIC
6974   #ifdef VITA
6975   // sceBlock is managed by retroarch's bootstrap code
6976   //sceKernelFreeMemBlock(sceBlock);
6977   //sceBlock = -1;
6978   #else
6979   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6980     SysPrintf("munmap() failed\n");
6981   #endif
6982 #endif
6983   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6984   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6985   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6986   #ifdef ROM_COPY
6987   if (munmap (ROM_COPY, 67108864) < 0) {SysPrintf("munmap() failed\n");}
6988   #endif
6989 }
6990
6991 static u_int *get_source_start(u_int addr, u_int *limit)
6992 {
6993   if (addr < 0x00200000 ||
6994     (0xa0000000 <= addr && addr < 0xa0200000))
6995   {
6996     // used for BIOS calls mostly?
6997     *limit = (addr&0xa0000000)|0x00200000;
6998     return (u_int *)(rdram + (addr&0x1fffff));
6999   }
7000   else if (!Config.HLE && (
7001     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
7002     (0xbfc00000 <= addr && addr < 0xbfc80000)))
7003   {
7004     // BIOS. The multiplier should be much higher as it's uncached 8bit mem,
7005     // but timings in PCSX are too tied to the interpreter's BIAS
7006     if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
7007       cycle_multiplier_active = 200;
7008
7009     *limit = (addr & 0xfff00000) | 0x80000;
7010     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
7011   }
7012   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
7013     *limit = (addr & 0x80600000) + 0x00200000;
7014     return (u_int *)(rdram + (addr&0x1fffff));
7015   }
7016   return NULL;
7017 }
7018
7019 static u_int scan_for_ret(u_int addr)
7020 {
7021   u_int limit = 0;
7022   u_int *mem;
7023
7024   mem = get_source_start(addr, &limit);
7025   if (mem == NULL)
7026     return addr;
7027
7028   if (limit > addr + 0x1000)
7029     limit = addr + 0x1000;
7030   for (; addr < limit; addr += 4, mem++) {
7031     if (*mem == 0x03e00008) // jr $ra
7032       return addr + 8;
7033   }
7034   return addr;
7035 }
7036
7037 struct savestate_block {
7038   uint32_t addr;
7039   uint32_t regflags;
7040 };
7041
7042 static int addr_cmp(const void *p1_, const void *p2_)
7043 {
7044   const struct savestate_block *p1 = p1_, *p2 = p2_;
7045   return p1->addr - p2->addr;
7046 }
7047
7048 int new_dynarec_save_blocks(void *save, int size)
7049 {
7050   struct savestate_block *blocks = save;
7051   int maxcount = size / sizeof(blocks[0]);
7052   struct savestate_block tmp_blocks[1024];
7053   struct ll_entry *head;
7054   int p, s, d, o, bcnt;
7055   u_int addr;
7056
7057   o = 0;
7058   for (p = 0; p < ARRAY_SIZE(jump_in); p++) {
7059     bcnt = 0;
7060     for (head = jump_in[p]; head != NULL; head = head->next) {
7061       tmp_blocks[bcnt].addr = head->vaddr;
7062       tmp_blocks[bcnt].regflags = head->reg_sv_flags;
7063       bcnt++;
7064     }
7065     if (bcnt < 1)
7066       continue;
7067     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
7068
7069     addr = tmp_blocks[0].addr;
7070     for (s = d = 0; s < bcnt; s++) {
7071       if (tmp_blocks[s].addr < addr)
7072         continue;
7073       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
7074         tmp_blocks[d++] = tmp_blocks[s];
7075       addr = scan_for_ret(tmp_blocks[s].addr);
7076     }
7077
7078     if (o + d > maxcount)
7079       d = maxcount - o;
7080     memcpy(&blocks[o], tmp_blocks, d * sizeof(blocks[0]));
7081     o += d;
7082   }
7083
7084   return o * sizeof(blocks[0]);
7085 }
7086
7087 void new_dynarec_load_blocks(const void *save, int size)
7088 {
7089   const struct savestate_block *blocks = save;
7090   int count = size / sizeof(blocks[0]);
7091   u_int regs_save[32];
7092   uint32_t f;
7093   int i, b;
7094
7095   get_addr(psxRegs.pc);
7096
7097   // change GPRs for speculation to at least partially work..
7098   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
7099   for (i = 1; i < 32; i++)
7100     psxRegs.GPR.r[i] = 0x80000000;
7101
7102   for (b = 0; b < count; b++) {
7103     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
7104       if (f & 1)
7105         psxRegs.GPR.r[i] = 0x1f800000;
7106     }
7107
7108     get_addr(blocks[b].addr);
7109
7110     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
7111       if (f & 1)
7112         psxRegs.GPR.r[i] = 0x80000000;
7113     }
7114   }
7115
7116   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
7117 }
7118
7119 static int apply_hacks(void)
7120 {
7121   int i;
7122   if (HACK_ENABLED(NDHACK_NO_COMPAT_HACKS))
7123     return 0;
7124   /* special hack(s) */
7125   for (i = 0; i < slen - 4; i++)
7126   {
7127     // lui a4, 0xf200; jal <rcnt_read>; addu a0, 2; slti v0, 28224
7128     if (source[i] == 0x3c04f200 && dops[i+1].itype == UJUMP
7129         && source[i+2] == 0x34840002 && dops[i+3].opcode == 0x0a
7130         && imm[i+3] == 0x6e40 && dops[i+3].rs1 == 2)
7131     {
7132       SysPrintf("PE2 hack @%08x\n", start + (i+3)*4);
7133       dops[i + 3].itype = NOP;
7134     }
7135   }
7136   i = slen;
7137   if (i > 10 && source[i-1] == 0 && source[i-2] == 0x03e00008
7138       && source[i-4] == 0x8fbf0018 && source[i-6] == 0x00c0f809
7139       && dops[i-7].itype == STORE)
7140   {
7141     i = i-8;
7142     if (dops[i].itype == IMM16)
7143       i--;
7144     // swl r2, 15(r6); swr r2, 12(r6); sw r6, *; jalr r6
7145     if (dops[i].itype == STORELR && dops[i].rs1 == 6
7146       && dops[i-1].itype == STORELR && dops[i-1].rs1 == 6)
7147     {
7148       SysPrintf("F1 hack from %08x, old dst %08x\n", start, hack_addr);
7149       f1_hack = 1;
7150       return 1;
7151     }
7152   }
7153   return 0;
7154 }
7155
7156 int new_recompile_block(u_int addr)
7157 {
7158   u_int pagelimit = 0;
7159   u_int state_rflags = 0;
7160   int i;
7161
7162   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
7163   //printf("TRACE: count=%d next=%d (compile %x)\n",Count,next_interupt,addr);
7164   //if(debug)
7165   //printf("fpu mapping=%x enabled=%x\n",(Status & 0x04000000)>>26,(Status & 0x20000000)>>29);
7166
7167   // this is just for speculation
7168   for (i = 1; i < 32; i++) {
7169     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
7170       state_rflags |= 1 << i;
7171   }
7172
7173   start = (u_int)addr&~3;
7174   //assert(((u_int)addr&1)==0); // start-in-delay-slot flag
7175   new_dynarec_did_compile=1;
7176   if (Config.HLE && start == 0x80001000) // hlecall
7177   {
7178     // XXX: is this enough? Maybe check hleSoftCall?
7179     void *beginning=start_block();
7180     u_int page=get_page(start);
7181
7182     invalid_code[start>>12]=0;
7183     emit_movimm(start,0);
7184     emit_writeword(0,&pcaddr);
7185     emit_far_jump(new_dyna_leave);
7186     literal_pool(0);
7187     end_block(beginning);
7188     ll_add_flags(jump_in+page,start,state_rflags,(void *)beginning);
7189     return 0;
7190   }
7191   else if (f1_hack && hack_addr == 0) {
7192     void *beginning = start_block();
7193     u_int page = get_page(start);
7194     emit_movimm(start, 0);
7195     emit_writeword(0, &hack_addr);
7196     emit_readword(&psxRegs.GPR.n.sp, 0);
7197     emit_readptr(&mem_rtab, 1);
7198     emit_shrimm(0, 12, 2);
7199     emit_readptr_dualindexedx_ptrlen(1, 2, 1);
7200     emit_addimm(0, 0x18, 0);
7201     emit_adds_ptr(1, 1, 1);
7202     emit_ldr_dualindexed(1, 0, 0);
7203     emit_writeword(0, &psxRegs.GPR.r[26]); // lw k0, 0x18(sp)
7204     emit_far_call(get_addr_ht);
7205     emit_jmpreg(0); // jr k0
7206     literal_pool(0);
7207     end_block(beginning);
7208
7209     ll_add_flags(jump_in + page, start, state_rflags, beginning);
7210     SysPrintf("F1 hack to   %08x\n", start);
7211     return 0;
7212   }
7213
7214   cycle_multiplier_active = cycle_multiplier_override && cycle_multiplier == CYCLE_MULT_DEFAULT
7215     ? cycle_multiplier_override : cycle_multiplier;
7216
7217   source = get_source_start(start, &pagelimit);
7218   if (source == NULL) {
7219     if (addr != hack_addr) {
7220       SysPrintf("Compile at bogus memory address: %08x\n", addr);
7221       hack_addr = addr;
7222     }
7223     //abort();
7224     return -1;
7225   }
7226
7227   /* Pass 1: disassemble */
7228   /* Pass 2: register dependencies, branch targets */
7229   /* Pass 3: register allocation */
7230   /* Pass 4: branch dependencies */
7231   /* Pass 5: pre-alloc */
7232   /* Pass 6: optimize clean/dirty state */
7233   /* Pass 7: flag 32-bit registers */
7234   /* Pass 8: assembly */
7235   /* Pass 9: linker */
7236   /* Pass 10: garbage collection / free memory */
7237
7238   int j;
7239   int done = 0, ni_count = 0;
7240   unsigned int type,op,op2;
7241
7242   //printf("addr = %x source = %x %x\n", addr,source,source[0]);
7243
7244   /* Pass 1 disassembly */
7245
7246   for (i = 0; !done; i++)
7247   {
7248     memset(&dops[i], 0, sizeof(dops[i]));
7249     op2=0;
7250     minimum_free_regs[i]=0;
7251     dops[i].opcode=op=source[i]>>26;
7252     switch(op)
7253     {
7254       case 0x00: strcpy(insn[i],"special"); type=NI;
7255         op2=source[i]&0x3f;
7256         switch(op2)
7257         {
7258           case 0x00: strcpy(insn[i],"SLL"); type=SHIFTIMM; break;
7259           case 0x02: strcpy(insn[i],"SRL"); type=SHIFTIMM; break;
7260           case 0x03: strcpy(insn[i],"SRA"); type=SHIFTIMM; break;
7261           case 0x04: strcpy(insn[i],"SLLV"); type=SHIFT; break;
7262           case 0x06: strcpy(insn[i],"SRLV"); type=SHIFT; break;
7263           case 0x07: strcpy(insn[i],"SRAV"); type=SHIFT; break;
7264           case 0x08: strcpy(insn[i],"JR"); type=RJUMP; break;
7265           case 0x09: strcpy(insn[i],"JALR"); type=RJUMP; break;
7266           case 0x0C: strcpy(insn[i],"SYSCALL"); type=SYSCALL; break;
7267           case 0x0D: strcpy(insn[i],"BREAK"); type=SYSCALL; break;
7268           case 0x0F: strcpy(insn[i],"SYNC"); type=OTHER; break;
7269           case 0x10: strcpy(insn[i],"MFHI"); type=MOV; break;
7270           case 0x11: strcpy(insn[i],"MTHI"); type=MOV; break;
7271           case 0x12: strcpy(insn[i],"MFLO"); type=MOV; break;
7272           case 0x13: strcpy(insn[i],"MTLO"); type=MOV; break;
7273           case 0x18: strcpy(insn[i],"MULT"); type=MULTDIV; break;
7274           case 0x19: strcpy(insn[i],"MULTU"); type=MULTDIV; break;
7275           case 0x1A: strcpy(insn[i],"DIV"); type=MULTDIV; break;
7276           case 0x1B: strcpy(insn[i],"DIVU"); type=MULTDIV; break;
7277           case 0x20: strcpy(insn[i],"ADD"); type=ALU; break;
7278           case 0x21: strcpy(insn[i],"ADDU"); type=ALU; break;
7279           case 0x22: strcpy(insn[i],"SUB"); type=ALU; break;
7280           case 0x23: strcpy(insn[i],"SUBU"); type=ALU; break;
7281           case 0x24: strcpy(insn[i],"AND"); type=ALU; break;
7282           case 0x25: strcpy(insn[i],"OR"); type=ALU; break;
7283           case 0x26: strcpy(insn[i],"XOR"); type=ALU; break;
7284           case 0x27: strcpy(insn[i],"NOR"); type=ALU; break;
7285           case 0x2A: strcpy(insn[i],"SLT"); type=ALU; break;
7286           case 0x2B: strcpy(insn[i],"SLTU"); type=ALU; break;
7287           case 0x30: strcpy(insn[i],"TGE"); type=NI; break;
7288           case 0x31: strcpy(insn[i],"TGEU"); type=NI; break;
7289           case 0x32: strcpy(insn[i],"TLT"); type=NI; break;
7290           case 0x33: strcpy(insn[i],"TLTU"); type=NI; break;
7291           case 0x34: strcpy(insn[i],"TEQ"); type=NI; break;
7292           case 0x36: strcpy(insn[i],"TNE"); type=NI; break;
7293 #if 0
7294           case 0x14: strcpy(insn[i],"DSLLV"); type=SHIFT; break;
7295           case 0x16: strcpy(insn[i],"DSRLV"); type=SHIFT; break;
7296           case 0x17: strcpy(insn[i],"DSRAV"); type=SHIFT; break;
7297           case 0x1C: strcpy(insn[i],"DMULT"); type=MULTDIV; break;
7298           case 0x1D: strcpy(insn[i],"DMULTU"); type=MULTDIV; break;
7299           case 0x1E: strcpy(insn[i],"DDIV"); type=MULTDIV; break;
7300           case 0x1F: strcpy(insn[i],"DDIVU"); type=MULTDIV; break;
7301           case 0x2C: strcpy(insn[i],"DADD"); type=ALU; break;
7302           case 0x2D: strcpy(insn[i],"DADDU"); type=ALU; break;
7303           case 0x2E: strcpy(insn[i],"DSUB"); type=ALU; break;
7304           case 0x2F: strcpy(insn[i],"DSUBU"); type=ALU; break;
7305           case 0x38: strcpy(insn[i],"DSLL"); type=SHIFTIMM; break;
7306           case 0x3A: strcpy(insn[i],"DSRL"); type=SHIFTIMM; break;
7307           case 0x3B: strcpy(insn[i],"DSRA"); type=SHIFTIMM; break;
7308           case 0x3C: strcpy(insn[i],"DSLL32"); type=SHIFTIMM; break;
7309           case 0x3E: strcpy(insn[i],"DSRL32"); type=SHIFTIMM; break;
7310           case 0x3F: strcpy(insn[i],"DSRA32"); type=SHIFTIMM; break;
7311 #endif
7312         }
7313         break;
7314       case 0x01: strcpy(insn[i],"regimm"); type=NI;
7315         op2=(source[i]>>16)&0x1f;
7316         switch(op2)
7317         {
7318           case 0x00: strcpy(insn[i],"BLTZ"); type=SJUMP; break;
7319           case 0x01: strcpy(insn[i],"BGEZ"); type=SJUMP; break;
7320           //case 0x02: strcpy(insn[i],"BLTZL"); type=SJUMP; break;
7321           //case 0x03: strcpy(insn[i],"BGEZL"); type=SJUMP; break;
7322           //case 0x08: strcpy(insn[i],"TGEI"); type=NI; break;
7323           //case 0x09: strcpy(insn[i],"TGEIU"); type=NI; break;
7324           //case 0x0A: strcpy(insn[i],"TLTI"); type=NI; break;
7325           //case 0x0B: strcpy(insn[i],"TLTIU"); type=NI; break;
7326           //case 0x0C: strcpy(insn[i],"TEQI"); type=NI; break;
7327           //case 0x0E: strcpy(insn[i],"TNEI"); type=NI; break;
7328           case 0x10: strcpy(insn[i],"BLTZAL"); type=SJUMP; break;
7329           case 0x11: strcpy(insn[i],"BGEZAL"); type=SJUMP; break;
7330           //case 0x12: strcpy(insn[i],"BLTZALL"); type=SJUMP; break;
7331           //case 0x13: strcpy(insn[i],"BGEZALL"); type=SJUMP; break;
7332         }
7333         break;
7334       case 0x02: strcpy(insn[i],"J"); type=UJUMP; break;
7335       case 0x03: strcpy(insn[i],"JAL"); type=UJUMP; break;
7336       case 0x04: strcpy(insn[i],"BEQ"); type=CJUMP; break;
7337       case 0x05: strcpy(insn[i],"BNE"); type=CJUMP; break;
7338       case 0x06: strcpy(insn[i],"BLEZ"); type=CJUMP; break;
7339       case 0x07: strcpy(insn[i],"BGTZ"); type=CJUMP; break;
7340       case 0x08: strcpy(insn[i],"ADDI"); type=IMM16; break;
7341       case 0x09: strcpy(insn[i],"ADDIU"); type=IMM16; break;
7342       case 0x0A: strcpy(insn[i],"SLTI"); type=IMM16; break;
7343       case 0x0B: strcpy(insn[i],"SLTIU"); type=IMM16; break;
7344       case 0x0C: strcpy(insn[i],"ANDI"); type=IMM16; break;
7345       case 0x0D: strcpy(insn[i],"ORI"); type=IMM16; break;
7346       case 0x0E: strcpy(insn[i],"XORI"); type=IMM16; break;
7347       case 0x0F: strcpy(insn[i],"LUI"); type=IMM16; break;
7348       case 0x10: strcpy(insn[i],"cop0"); type=NI;
7349         op2=(source[i]>>21)&0x1f;
7350         switch(op2)
7351         {
7352           case 0x00: strcpy(insn[i],"MFC0"); type=COP0; break;
7353           case 0x02: strcpy(insn[i],"CFC0"); type=COP0; break;
7354           case 0x04: strcpy(insn[i],"MTC0"); type=COP0; break;
7355           case 0x06: strcpy(insn[i],"CTC0"); type=COP0; break;
7356           case 0x10: strcpy(insn[i],"RFE"); type=COP0; break;
7357         }
7358         break;
7359       case 0x11: strcpy(insn[i],"cop1"); type=COP1;
7360         op2=(source[i]>>21)&0x1f;
7361         break;
7362 #if 0
7363       case 0x14: strcpy(insn[i],"BEQL"); type=CJUMP; break;
7364       case 0x15: strcpy(insn[i],"BNEL"); type=CJUMP; break;
7365       case 0x16: strcpy(insn[i],"BLEZL"); type=CJUMP; break;
7366       case 0x17: strcpy(insn[i],"BGTZL"); type=CJUMP; break;
7367       case 0x18: strcpy(insn[i],"DADDI"); type=IMM16; break;
7368       case 0x19: strcpy(insn[i],"DADDIU"); type=IMM16; break;
7369       case 0x1A: strcpy(insn[i],"LDL"); type=LOADLR; break;
7370       case 0x1B: strcpy(insn[i],"LDR"); type=LOADLR; break;
7371 #endif
7372       case 0x20: strcpy(insn[i],"LB"); type=LOAD; break;
7373       case 0x21: strcpy(insn[i],"LH"); type=LOAD; break;
7374       case 0x22: strcpy(insn[i],"LWL"); type=LOADLR; break;
7375       case 0x23: strcpy(insn[i],"LW"); type=LOAD; break;
7376       case 0x24: strcpy(insn[i],"LBU"); type=LOAD; break;
7377       case 0x25: strcpy(insn[i],"LHU"); type=LOAD; break;
7378       case 0x26: strcpy(insn[i],"LWR"); type=LOADLR; break;
7379 #if 0
7380       case 0x27: strcpy(insn[i],"LWU"); type=LOAD; break;
7381 #endif
7382       case 0x28: strcpy(insn[i],"SB"); type=STORE; break;
7383       case 0x29: strcpy(insn[i],"SH"); type=STORE; break;
7384       case 0x2A: strcpy(insn[i],"SWL"); type=STORELR; break;
7385       case 0x2B: strcpy(insn[i],"SW"); type=STORE; break;
7386 #if 0
7387       case 0x2C: strcpy(insn[i],"SDL"); type=STORELR; break;
7388       case 0x2D: strcpy(insn[i],"SDR"); type=STORELR; break;
7389 #endif
7390       case 0x2E: strcpy(insn[i],"SWR"); type=STORELR; break;
7391       case 0x2F: strcpy(insn[i],"CACHE"); type=NOP; break;
7392       case 0x30: strcpy(insn[i],"LL"); type=NI; break;
7393       case 0x31: strcpy(insn[i],"LWC1"); type=C1LS; break;
7394 #if 0
7395       case 0x34: strcpy(insn[i],"LLD"); type=NI; break;
7396       case 0x35: strcpy(insn[i],"LDC1"); type=C1LS; break;
7397       case 0x37: strcpy(insn[i],"LD"); type=LOAD; break;
7398 #endif
7399       case 0x38: strcpy(insn[i],"SC"); type=NI; break;
7400       case 0x39: strcpy(insn[i],"SWC1"); type=C1LS; break;
7401 #if 0
7402       case 0x3C: strcpy(insn[i],"SCD"); type=NI; break;
7403       case 0x3D: strcpy(insn[i],"SDC1"); type=C1LS; break;
7404       case 0x3F: strcpy(insn[i],"SD"); type=STORE; break;
7405 #endif
7406       case 0x12: strcpy(insn[i],"COP2"); type=NI;
7407         op2=(source[i]>>21)&0x1f;
7408         //if (op2 & 0x10)
7409         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
7410           if (gte_handlers[source[i]&0x3f]!=NULL) {
7411             if (gte_regnames[source[i]&0x3f]!=NULL)
7412               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
7413             else
7414               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
7415             type=C2OP;
7416           }
7417         }
7418         else switch(op2)
7419         {
7420           case 0x00: strcpy(insn[i],"MFC2"); type=COP2; break;
7421           case 0x02: strcpy(insn[i],"CFC2"); type=COP2; break;
7422           case 0x04: strcpy(insn[i],"MTC2"); type=COP2; break;
7423           case 0x06: strcpy(insn[i],"CTC2"); type=COP2; break;
7424         }
7425         break;
7426       case 0x32: strcpy(insn[i],"LWC2"); type=C2LS; break;
7427       case 0x3A: strcpy(insn[i],"SWC2"); type=C2LS; break;
7428       case 0x3B: strcpy(insn[i],"HLECALL"); type=HLECALL; break;
7429       default: strcpy(insn[i],"???"); type=NI;
7430         SysPrintf("NI %08x @%08x (%08x)\n", source[i], addr + i*4, addr);
7431         break;
7432     }
7433     dops[i].itype=type;
7434     dops[i].opcode2=op2;
7435     /* Get registers/immediates */
7436     dops[i].lt1=0;
7437     gte_rs[i]=gte_rt[i]=0;
7438     switch(type) {
7439       case LOAD:
7440         dops[i].rs1=(source[i]>>21)&0x1f;
7441         dops[i].rs2=0;
7442         dops[i].rt1=(source[i]>>16)&0x1f;
7443         dops[i].rt2=0;
7444         imm[i]=(short)source[i];
7445         break;
7446       case STORE:
7447       case STORELR:
7448         dops[i].rs1=(source[i]>>21)&0x1f;
7449         dops[i].rs2=(source[i]>>16)&0x1f;
7450         dops[i].rt1=0;
7451         dops[i].rt2=0;
7452         imm[i]=(short)source[i];
7453         break;
7454       case LOADLR:
7455         // LWL/LWR only load part of the register,
7456         // therefore the target register must be treated as a source too
7457         dops[i].rs1=(source[i]>>21)&0x1f;
7458         dops[i].rs2=(source[i]>>16)&0x1f;
7459         dops[i].rt1=(source[i]>>16)&0x1f;
7460         dops[i].rt2=0;
7461         imm[i]=(short)source[i];
7462         break;
7463       case IMM16:
7464         if (op==0x0f) dops[i].rs1=0; // LUI instruction has no source register
7465         else dops[i].rs1=(source[i]>>21)&0x1f;
7466         dops[i].rs2=0;
7467         dops[i].rt1=(source[i]>>16)&0x1f;
7468         dops[i].rt2=0;
7469         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
7470           imm[i]=(unsigned short)source[i];
7471         }else{
7472           imm[i]=(short)source[i];
7473         }
7474         break;
7475       case UJUMP:
7476         dops[i].rs1=0;
7477         dops[i].rs2=0;
7478         dops[i].rt1=0;
7479         dops[i].rt2=0;
7480         // The JAL instruction writes to r31.
7481         if (op&1) {
7482           dops[i].rt1=31;
7483         }
7484         dops[i].rs2=CCREG;
7485         break;
7486       case RJUMP:
7487         dops[i].rs1=(source[i]>>21)&0x1f;
7488         dops[i].rs2=0;
7489         dops[i].rt1=0;
7490         dops[i].rt2=0;
7491         // The JALR instruction writes to rd.
7492         if (op2&1) {
7493           dops[i].rt1=(source[i]>>11)&0x1f;
7494         }
7495         dops[i].rs2=CCREG;
7496         break;
7497       case CJUMP:
7498         dops[i].rs1=(source[i]>>21)&0x1f;
7499         dops[i].rs2=(source[i]>>16)&0x1f;
7500         dops[i].rt1=0;
7501         dops[i].rt2=0;
7502         if(op&2) { // BGTZ/BLEZ
7503           dops[i].rs2=0;
7504         }
7505         break;
7506       case SJUMP:
7507         dops[i].rs1=(source[i]>>21)&0x1f;
7508         dops[i].rs2=CCREG;
7509         dops[i].rt1=0;
7510         dops[i].rt2=0;
7511         if(op2&0x10) { // BxxAL
7512           dops[i].rt1=31;
7513           // NOTE: If the branch is not taken, r31 is still overwritten
7514         }
7515         break;
7516       case ALU:
7517         dops[i].rs1=(source[i]>>21)&0x1f; // source
7518         dops[i].rs2=(source[i]>>16)&0x1f; // subtract amount
7519         dops[i].rt1=(source[i]>>11)&0x1f; // destination
7520         dops[i].rt2=0;
7521         break;
7522       case MULTDIV:
7523         dops[i].rs1=(source[i]>>21)&0x1f; // source
7524         dops[i].rs2=(source[i]>>16)&0x1f; // divisor
7525         dops[i].rt1=HIREG;
7526         dops[i].rt2=LOREG;
7527         break;
7528       case MOV:
7529         dops[i].rs1=0;
7530         dops[i].rs2=0;
7531         dops[i].rt1=0;
7532         dops[i].rt2=0;
7533         if(op2==0x10) dops[i].rs1=HIREG; // MFHI
7534         if(op2==0x11) dops[i].rt1=HIREG; // MTHI
7535         if(op2==0x12) dops[i].rs1=LOREG; // MFLO
7536         if(op2==0x13) dops[i].rt1=LOREG; // MTLO
7537         if((op2&0x1d)==0x10) dops[i].rt1=(source[i]>>11)&0x1f; // MFxx
7538         if((op2&0x1d)==0x11) dops[i].rs1=(source[i]>>21)&0x1f; // MTxx
7539         break;
7540       case SHIFT:
7541         dops[i].rs1=(source[i]>>16)&0x1f; // target of shift
7542         dops[i].rs2=(source[i]>>21)&0x1f; // shift amount
7543         dops[i].rt1=(source[i]>>11)&0x1f; // destination
7544         dops[i].rt2=0;
7545         break;
7546       case SHIFTIMM:
7547         dops[i].rs1=(source[i]>>16)&0x1f;
7548         dops[i].rs2=0;
7549         dops[i].rt1=(source[i]>>11)&0x1f;
7550         dops[i].rt2=0;
7551         imm[i]=(source[i]>>6)&0x1f;
7552         // DSxx32 instructions
7553         if(op2>=0x3c) imm[i]|=0x20;
7554         break;
7555       case COP0:
7556         dops[i].rs1=0;
7557         dops[i].rs2=0;
7558         dops[i].rt1=0;
7559         dops[i].rt2=0;
7560         if(op2==0||op2==2) dops[i].rt1=(source[i]>>16)&0x1F; // MFC0/CFC0
7561         if(op2==4||op2==6) dops[i].rs1=(source[i]>>16)&0x1F; // MTC0/CTC0
7562         if(op2==4&&((source[i]>>11)&0x1f)==12) dops[i].rt2=CSREG; // Status
7563         if(op2==16) if((source[i]&0x3f)==0x18) dops[i].rs2=CCREG; // ERET
7564         break;
7565       case COP1:
7566         dops[i].rs1=0;
7567         dops[i].rs2=0;
7568         dops[i].rt1=0;
7569         dops[i].rt2=0;
7570         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
7571         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
7572         dops[i].rs2=CSREG;
7573         break;
7574       case COP2:
7575         dops[i].rs1=0;
7576         dops[i].rs2=0;
7577         dops[i].rt1=0;
7578         dops[i].rt2=0;
7579         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC2/CFC2
7580         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC2/CTC2
7581         dops[i].rs2=CSREG;
7582         int gr=(source[i]>>11)&0x1F;
7583         switch(op2)
7584         {
7585           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
7586           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
7587           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
7588           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
7589         }
7590         break;
7591       case C1LS:
7592         dops[i].rs1=(source[i]>>21)&0x1F;
7593         dops[i].rs2=CSREG;
7594         dops[i].rt1=0;
7595         dops[i].rt2=0;
7596         imm[i]=(short)source[i];
7597         break;
7598       case C2LS:
7599         dops[i].rs1=(source[i]>>21)&0x1F;
7600         dops[i].rs2=0;
7601         dops[i].rt1=0;
7602         dops[i].rt2=0;
7603         imm[i]=(short)source[i];
7604         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
7605         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
7606         break;
7607       case C2OP:
7608         dops[i].rs1=0;
7609         dops[i].rs2=0;
7610         dops[i].rt1=0;
7611         dops[i].rt2=0;
7612         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
7613         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
7614         gte_rt[i]|=1ll<<63; // every op changes flags
7615         if((source[i]&0x3f)==GTE_MVMVA) {
7616           int v = (source[i] >> 15) & 3;
7617           gte_rs[i]&=~0xe3fll;
7618           if(v==3) gte_rs[i]|=0xe00ll;
7619           else gte_rs[i]|=3ll<<(v*2);
7620         }
7621         break;
7622       case SYSCALL:
7623       case HLECALL:
7624       case INTCALL:
7625         dops[i].rs1=CCREG;
7626         dops[i].rs2=0;
7627         dops[i].rt1=0;
7628         dops[i].rt2=0;
7629         break;
7630       default:
7631         dops[i].rs1=0;
7632         dops[i].rs2=0;
7633         dops[i].rt1=0;
7634         dops[i].rt2=0;
7635     }
7636     /* Calculate branch target addresses */
7637     if(type==UJUMP)
7638       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
7639     else if(type==CJUMP&&dops[i].rs1==dops[i].rs2&&(op&1))
7640       ba[i]=start+i*4+8; // Ignore never taken branch
7641     else if(type==SJUMP&&dops[i].rs1==0&&!(op2&1))
7642       ba[i]=start+i*4+8; // Ignore never taken branch
7643     else if(type==CJUMP||type==SJUMP)
7644       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
7645     else ba[i]=-1;
7646
7647     /* simplify always (not)taken branches */
7648     if (type == CJUMP && dops[i].rs1 == dops[i].rs2) {
7649       dops[i].rs1 = dops[i].rs2 = 0;
7650       if (!(op & 1)) {
7651         dops[i].itype = type = UJUMP;
7652         dops[i].rs2 = CCREG;
7653       }
7654     }
7655     else if (type == SJUMP && dops[i].rs1 == 0 && (op2 & 1))
7656       dops[i].itype = type = UJUMP;
7657
7658     dops[i].is_jump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP || dops[i].itype == CJUMP || dops[i].itype == SJUMP);
7659     dops[i].is_ujump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP); // || (source[i] >> 16) == 0x1000 // beq r0,r0
7660     dops[i].is_load = (dops[i].itype == LOAD || dops[i].itype == LOADLR || op == 0x32); // LWC2
7661     dops[i].is_store = (dops[i].itype == STORE || dops[i].itype == STORELR || op == 0x3a); // SWC2
7662
7663     /* messy cases to just pass over to the interpreter */
7664     if (i > 0 && dops[i-1].is_jump) {
7665       int do_in_intrp=0;
7666       // branch in delay slot?
7667       if (dops[i].is_jump) {
7668         // don't handle first branch and call interpreter if it's hit
7669         SysPrintf("branch in delay slot @%08x (%08x)\n", addr + i*4, addr);
7670         do_in_intrp=1;
7671       }
7672       // basic load delay detection
7673       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&dops[i].rt1!=0) {
7674         int t=(ba[i-1]-start)/4;
7675         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) {
7676           // jump target wants DS result - potential load delay effect
7677           SysPrintf("load delay @%08x (%08x)\n", addr + i*4, addr);
7678           do_in_intrp=1;
7679           dops[t+1].bt=1; // expected return from interpreter
7680         }
7681         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&&
7682               !(i>=3&&dops[i-3].is_jump)) {
7683           // v0 overwrite like this is a sign of trouble, bail out
7684           SysPrintf("v0 overwrite @%08x (%08x)\n", addr + i*4, addr);
7685           do_in_intrp=1;
7686         }
7687       }
7688       if (do_in_intrp) {
7689         memset(&dops[i-1], 0, sizeof(dops[i-1]));
7690         dops[i-1].itype = INTCALL;
7691         dops[i-1].rs1 = CCREG;
7692         ba[i-1] = -1;
7693         done = 2;
7694         i--; // don't compile the DS
7695       }
7696     }
7697
7698     /* Is this the end of the block? */
7699     if (i > 0 && dops[i-1].is_ujump) {
7700       if(dops[i-1].rt1==0) { // Continue past subroutine call (JAL)
7701         done=2;
7702       }
7703       else {
7704         if(stop_after_jal) done=1;
7705         // Stop on BREAK
7706         if((source[i+1]&0xfc00003f)==0x0d) done=1;
7707       }
7708       // Don't recompile stuff that's already compiled
7709       if(check_addr(start+i*4+4)) done=1;
7710       // Don't get too close to the limit
7711       if(i>MAXBLOCK/2) done=1;
7712     }
7713     if (dops[i].itype == SYSCALL || dops[i].itype == HLECALL || dops[i].itype == INTCALL)
7714       done = stop_after_jal ? 1 : 2;
7715     if (done == 2) {
7716       // Does the block continue due to a branch?
7717       for(j=i-1;j>=0;j--)
7718       {
7719         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
7720         if(ba[j]==start+i*4+4) done=j=0;
7721         if(ba[j]==start+i*4+8) done=j=0;
7722       }
7723     }
7724     //assert(i<MAXBLOCK-1);
7725     if(start+i*4==pagelimit-4) done=1;
7726     assert(start+i*4<pagelimit);
7727     if (i==MAXBLOCK-1) done=1;
7728     // Stop if we're compiling junk
7729     if(dops[i].itype == NI && (++ni_count > 8 || dops[i].opcode == 0x11)) {
7730       done=stop_after_jal=1;
7731       SysPrintf("Disabled speculative precompilation\n");
7732     }
7733   }
7734   slen=i;
7735   if (dops[i-1].is_jump) {
7736     if(start+i*4==pagelimit) {
7737       dops[i-1].itype=SPAN;
7738     }
7739   }
7740   assert(slen>0);
7741
7742   int clear_hack_addr = apply_hacks();
7743
7744   /* Pass 2 - Register dependencies and branch targets */
7745
7746   unneeded_registers(0,slen-1,0);
7747
7748   /* Pass 3 - Register allocation */
7749
7750   struct regstat current; // Current register allocations/status
7751   clear_all_regs(current.regmap_entry);
7752   clear_all_regs(current.regmap);
7753   current.wasdirty = current.dirty = 0;
7754   current.u = unneeded_reg[0];
7755   alloc_reg(&current, 0, CCREG);
7756   dirty_reg(&current, CCREG);
7757   current.wasconst = 0;
7758   current.isconst = 0;
7759   current.loadedconst = 0;
7760   current.waswritten = 0;
7761   int ds=0;
7762   int cc=0;
7763   int hr=-1;
7764
7765   if((u_int)addr&1) {
7766     // First instruction is delay slot
7767     cc=-1;
7768     dops[1].bt=1;
7769     ds=1;
7770     unneeded_reg[0]=1;
7771     current.regmap[HOST_BTREG]=BTREG;
7772   }
7773
7774   for(i=0;i<slen;i++)
7775   {
7776     if(dops[i].bt)
7777     {
7778       int hr;
7779       for(hr=0;hr<HOST_REGS;hr++)
7780       {
7781         // Is this really necessary?
7782         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7783       }
7784       current.isconst=0;
7785       current.waswritten=0;
7786     }
7787
7788     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7789     regs[i].wasconst=current.isconst;
7790     regs[i].wasdirty=current.dirty;
7791     regs[i].dirty=0;
7792     regs[i].u=0;
7793     regs[i].isconst=0;
7794     regs[i].loadedconst=0;
7795     if (!dops[i].is_jump) {
7796       if(i+1<slen) {
7797         current.u=unneeded_reg[i+1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7798         current.u|=1;
7799       } else {
7800         current.u=1;
7801       }
7802     } else {
7803       if(i+1<slen) {
7804         current.u=branch_unneeded_reg[i]&~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7805         current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7806         current.u|=1;
7807       } else {
7808         SysPrintf("oops, branch at end of block with no delay slot @%08x\n", start + i*4);
7809         abort();
7810       }
7811     }
7812     dops[i].is_ds=ds;
7813     if(ds) {
7814       ds=0; // Skip delay slot, already allocated as part of branch
7815       // ...but we need to alloc it in case something jumps here
7816       if(i+1<slen) {
7817         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7818       }else{
7819         current.u=branch_unneeded_reg[i-1];
7820       }
7821       current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7822       current.u|=1;
7823       struct regstat temp;
7824       memcpy(&temp,&current,sizeof(current));
7825       temp.wasdirty=temp.dirty;
7826       // TODO: Take into account unconditional branches, as below
7827       delayslot_alloc(&temp,i);
7828       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7829       regs[i].wasdirty=temp.wasdirty;
7830       regs[i].dirty=temp.dirty;
7831       regs[i].isconst=0;
7832       regs[i].wasconst=0;
7833       current.isconst=0;
7834       // Create entry (branch target) regmap
7835       for(hr=0;hr<HOST_REGS;hr++)
7836       {
7837         int r=temp.regmap[hr];
7838         if(r>=0) {
7839           if(r!=regmap_pre[i][hr]) {
7840             regs[i].regmap_entry[hr]=-1;
7841           }
7842           else
7843           {
7844               assert(r < 64);
7845               if((current.u>>r)&1) {
7846                 regs[i].regmap_entry[hr]=-1;
7847                 regs[i].regmap[hr]=-1;
7848                 //Don't clear regs in the delay slot as the branch might need them
7849                 //current.regmap[hr]=-1;
7850               }else
7851                 regs[i].regmap_entry[hr]=r;
7852           }
7853         } else {
7854           // First instruction expects CCREG to be allocated
7855           if(i==0&&hr==HOST_CCREG)
7856             regs[i].regmap_entry[hr]=CCREG;
7857           else
7858             regs[i].regmap_entry[hr]=-1;
7859         }
7860       }
7861     }
7862     else { // Not delay slot
7863       switch(dops[i].itype) {
7864         case UJUMP:
7865           //current.isconst=0; // DEBUG
7866           //current.wasconst=0; // DEBUG
7867           //regs[i].wasconst=0; // DEBUG
7868           clear_const(&current,dops[i].rt1);
7869           alloc_cc(&current,i);
7870           dirty_reg(&current,CCREG);
7871           if (dops[i].rt1==31) {
7872             alloc_reg(&current,i,31);
7873             dirty_reg(&current,31);
7874             //assert(dops[i+1].rs1!=31&&dops[i+1].rs2!=31);
7875             //assert(dops[i+1].rt1!=dops[i].rt1);
7876             #ifdef REG_PREFETCH
7877             alloc_reg(&current,i,PTEMP);
7878             #endif
7879           }
7880           dops[i].ooo=1;
7881           delayslot_alloc(&current,i+1);
7882           //current.isconst=0; // DEBUG
7883           ds=1;
7884           //printf("i=%d, isconst=%x\n",i,current.isconst);
7885           break;
7886         case RJUMP:
7887           //current.isconst=0;
7888           //current.wasconst=0;
7889           //regs[i].wasconst=0;
7890           clear_const(&current,dops[i].rs1);
7891           clear_const(&current,dops[i].rt1);
7892           alloc_cc(&current,i);
7893           dirty_reg(&current,CCREG);
7894           if (!ds_writes_rjump_rs(i)) {
7895             alloc_reg(&current,i,dops[i].rs1);
7896             if (dops[i].rt1!=0) {
7897               alloc_reg(&current,i,dops[i].rt1);
7898               dirty_reg(&current,dops[i].rt1);
7899               assert(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt1);
7900               assert(dops[i+1].rt1!=dops[i].rt1);
7901               #ifdef REG_PREFETCH
7902               alloc_reg(&current,i,PTEMP);
7903               #endif
7904             }
7905             #ifdef USE_MINI_HT
7906             if(dops[i].rs1==31) { // JALR
7907               alloc_reg(&current,i,RHASH);
7908               alloc_reg(&current,i,RHTBL);
7909             }
7910             #endif
7911             delayslot_alloc(&current,i+1);
7912           } else {
7913             // The delay slot overwrites our source register,
7914             // allocate a temporary register to hold the old value.
7915             current.isconst=0;
7916             current.wasconst=0;
7917             regs[i].wasconst=0;
7918             delayslot_alloc(&current,i+1);
7919             current.isconst=0;
7920             alloc_reg(&current,i,RTEMP);
7921           }
7922           //current.isconst=0; // DEBUG
7923           dops[i].ooo=1;
7924           ds=1;
7925           break;
7926         case CJUMP:
7927           //current.isconst=0;
7928           //current.wasconst=0;
7929           //regs[i].wasconst=0;
7930           clear_const(&current,dops[i].rs1);
7931           clear_const(&current,dops[i].rs2);
7932           if((dops[i].opcode&0x3E)==4) // BEQ/BNE
7933           {
7934             alloc_cc(&current,i);
7935             dirty_reg(&current,CCREG);
7936             if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7937             if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7938             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2))||
7939                (dops[i].rs2&&(dops[i].rs2==dops[i+1].rt1||dops[i].rs2==dops[i+1].rt2))) {
7940               // The delay slot overwrites one of our conditions.
7941               // Allocate the branch condition registers instead.
7942               current.isconst=0;
7943               current.wasconst=0;
7944               regs[i].wasconst=0;
7945               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7946               if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7947             }
7948             else
7949             {
7950               dops[i].ooo=1;
7951               delayslot_alloc(&current,i+1);
7952             }
7953           }
7954           else
7955           if((dops[i].opcode&0x3E)==6) // BLEZ/BGTZ
7956           {
7957             alloc_cc(&current,i);
7958             dirty_reg(&current,CCREG);
7959             alloc_reg(&current,i,dops[i].rs1);
7960             if(dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) {
7961               // The delay slot overwrites one of our conditions.
7962               // Allocate the branch condition registers instead.
7963               current.isconst=0;
7964               current.wasconst=0;
7965               regs[i].wasconst=0;
7966               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7967             }
7968             else
7969             {
7970               dops[i].ooo=1;
7971               delayslot_alloc(&current,i+1);
7972             }
7973           }
7974           else
7975           // Don't alloc the delay slot yet because we might not execute it
7976           if((dops[i].opcode&0x3E)==0x14) // BEQL/BNEL
7977           {
7978             current.isconst=0;
7979             current.wasconst=0;
7980             regs[i].wasconst=0;
7981             alloc_cc(&current,i);
7982             dirty_reg(&current,CCREG);
7983             alloc_reg(&current,i,dops[i].rs1);
7984             alloc_reg(&current,i,dops[i].rs2);
7985           }
7986           else
7987           if((dops[i].opcode&0x3E)==0x16) // BLEZL/BGTZL
7988           {
7989             current.isconst=0;
7990             current.wasconst=0;
7991             regs[i].wasconst=0;
7992             alloc_cc(&current,i);
7993             dirty_reg(&current,CCREG);
7994             alloc_reg(&current,i,dops[i].rs1);
7995           }
7996           ds=1;
7997           //current.isconst=0;
7998           break;
7999         case SJUMP:
8000           //current.isconst=0;
8001           //current.wasconst=0;
8002           //regs[i].wasconst=0;
8003           clear_const(&current,dops[i].rs1);
8004           clear_const(&current,dops[i].rt1);
8005           //if((dops[i].opcode2&0x1E)==0x0) // BLTZ/BGEZ
8006           if((dops[i].opcode2&0x0E)==0x0) // BLTZ/BGEZ
8007           {
8008             alloc_cc(&current,i);
8009             dirty_reg(&current,CCREG);
8010             alloc_reg(&current,i,dops[i].rs1);
8011             if (dops[i].rt1==31) { // BLTZAL/BGEZAL
8012               alloc_reg(&current,i,31);
8013               dirty_reg(&current,31);
8014               //#ifdef REG_PREFETCH
8015               //alloc_reg(&current,i,PTEMP);
8016               //#endif
8017             }
8018             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.
8019                ||(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
8020               // Allocate the branch condition registers instead.
8021               current.isconst=0;
8022               current.wasconst=0;
8023               regs[i].wasconst=0;
8024               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
8025             }
8026             else
8027             {
8028               dops[i].ooo=1;
8029               delayslot_alloc(&current,i+1);
8030             }
8031           }
8032           else
8033           // Don't alloc the delay slot yet because we might not execute it
8034           if((dops[i].opcode2&0x1E)==0x2) // BLTZL/BGEZL
8035           {
8036             current.isconst=0;
8037             current.wasconst=0;
8038             regs[i].wasconst=0;
8039             alloc_cc(&current,i);
8040             dirty_reg(&current,CCREG);
8041             alloc_reg(&current,i,dops[i].rs1);
8042           }
8043           ds=1;
8044           //current.isconst=0;
8045           break;
8046         case IMM16:
8047           imm16_alloc(&current,i);
8048           break;
8049         case LOAD:
8050         case LOADLR:
8051           load_alloc(&current,i);
8052           break;
8053         case STORE:
8054         case STORELR:
8055           store_alloc(&current,i);
8056           break;
8057         case ALU:
8058           alu_alloc(&current,i);
8059           break;
8060         case SHIFT:
8061           shift_alloc(&current,i);
8062           break;
8063         case MULTDIV:
8064           multdiv_alloc(&current,i);
8065           break;
8066         case SHIFTIMM:
8067           shiftimm_alloc(&current,i);
8068           break;
8069         case MOV:
8070           mov_alloc(&current,i);
8071           break;
8072         case COP0:
8073           cop0_alloc(&current,i);
8074           break;
8075         case COP1:
8076           break;
8077         case COP2:
8078           cop2_alloc(&current,i);
8079           break;
8080         case C1LS:
8081           c1ls_alloc(&current,i);
8082           break;
8083         case C2LS:
8084           c2ls_alloc(&current,i);
8085           break;
8086         case C2OP:
8087           c2op_alloc(&current,i);
8088           break;
8089         case SYSCALL:
8090         case HLECALL:
8091         case INTCALL:
8092           syscall_alloc(&current,i);
8093           break;
8094         case SPAN:
8095           pagespan_alloc(&current,i);
8096           break;
8097       }
8098
8099       // Create entry (branch target) regmap
8100       for(hr=0;hr<HOST_REGS;hr++)
8101       {
8102         int r,or;
8103         r=current.regmap[hr];
8104         if(r>=0) {
8105           if(r!=regmap_pre[i][hr]) {
8106             // TODO: delay slot (?)
8107             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
8108             if(or<0||(r&63)>=TEMPREG){
8109               regs[i].regmap_entry[hr]=-1;
8110             }
8111             else
8112             {
8113               // Just move it to a different register
8114               regs[i].regmap_entry[hr]=r;
8115               // If it was dirty before, it's still dirty
8116               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r&63);
8117             }
8118           }
8119           else
8120           {
8121             // Unneeded
8122             if(r==0){
8123               regs[i].regmap_entry[hr]=0;
8124             }
8125             else
8126             {
8127               assert(r<64);
8128               if((current.u>>r)&1) {
8129                 regs[i].regmap_entry[hr]=-1;
8130                 //regs[i].regmap[hr]=-1;
8131                 current.regmap[hr]=-1;
8132               }else
8133                 regs[i].regmap_entry[hr]=r;
8134             }
8135           }
8136         } else {
8137           // Branches expect CCREG to be allocated at the target
8138           if(regmap_pre[i][hr]==CCREG)
8139             regs[i].regmap_entry[hr]=CCREG;
8140           else
8141             regs[i].regmap_entry[hr]=-1;
8142         }
8143       }
8144       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
8145     }
8146
8147     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)
8148       current.waswritten|=1<<dops[i-1].rs1;
8149     current.waswritten&=~(1<<dops[i].rt1);
8150     current.waswritten&=~(1<<dops[i].rt2);
8151     if((dops[i].itype==STORE||dops[i].itype==STORELR||(dops[i].itype==C2LS&&dops[i].opcode==0x3a))&&(u_int)imm[i]>=0x800)
8152       current.waswritten&=~(1<<dops[i].rs1);
8153
8154     /* Branch post-alloc */
8155     if(i>0)
8156     {
8157       current.wasdirty=current.dirty;
8158       switch(dops[i-1].itype) {
8159         case UJUMP:
8160           memcpy(&branch_regs[i-1],&current,sizeof(current));
8161           branch_regs[i-1].isconst=0;
8162           branch_regs[i-1].wasconst=0;
8163           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
8164           alloc_cc(&branch_regs[i-1],i-1);
8165           dirty_reg(&branch_regs[i-1],CCREG);
8166           if(dops[i-1].rt1==31) { // JAL
8167             alloc_reg(&branch_regs[i-1],i-1,31);
8168             dirty_reg(&branch_regs[i-1],31);
8169           }
8170           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8171           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8172           break;
8173         case RJUMP:
8174           memcpy(&branch_regs[i-1],&current,sizeof(current));
8175           branch_regs[i-1].isconst=0;
8176           branch_regs[i-1].wasconst=0;
8177           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
8178           alloc_cc(&branch_regs[i-1],i-1);
8179           dirty_reg(&branch_regs[i-1],CCREG);
8180           alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rs1);
8181           if(dops[i-1].rt1!=0) { // JALR
8182             alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rt1);
8183             dirty_reg(&branch_regs[i-1],dops[i-1].rt1);
8184           }
8185           #ifdef USE_MINI_HT
8186           if(dops[i-1].rs1==31) { // JALR
8187             alloc_reg(&branch_regs[i-1],i-1,RHASH);
8188             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
8189           }
8190           #endif
8191           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8192           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8193           break;
8194         case CJUMP:
8195           if((dops[i-1].opcode&0x3E)==4) // BEQ/BNE
8196           {
8197             alloc_cc(&current,i-1);
8198             dirty_reg(&current,CCREG);
8199             if((dops[i-1].rs1&&(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2))||
8200                (dops[i-1].rs2&&(dops[i-1].rs2==dops[i].rt1||dops[i-1].rs2==dops[i].rt2))) {
8201               // The delay slot overwrote one of our conditions
8202               // Delay slot goes after the test (in order)
8203               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8204               current.u|=1;
8205               delayslot_alloc(&current,i);
8206               current.isconst=0;
8207             }
8208             else
8209             {
8210               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
8211               // Alloc the branch condition registers
8212               if(dops[i-1].rs1) alloc_reg(&current,i-1,dops[i-1].rs1);
8213               if(dops[i-1].rs2) alloc_reg(&current,i-1,dops[i-1].rs2);
8214             }
8215             memcpy(&branch_regs[i-1],&current,sizeof(current));
8216             branch_regs[i-1].isconst=0;
8217             branch_regs[i-1].wasconst=0;
8218             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8219             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8220           }
8221           else
8222           if((dops[i-1].opcode&0x3E)==6) // BLEZ/BGTZ
8223           {
8224             alloc_cc(&current,i-1);
8225             dirty_reg(&current,CCREG);
8226             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
8227               // The delay slot overwrote the branch condition
8228               // Delay slot goes after the test (in order)
8229               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8230               current.u|=1;
8231               delayslot_alloc(&current,i);
8232               current.isconst=0;
8233             }
8234             else
8235             {
8236               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
8237               // Alloc the branch condition register
8238               alloc_reg(&current,i-1,dops[i-1].rs1);
8239             }
8240             memcpy(&branch_regs[i-1],&current,sizeof(current));
8241             branch_regs[i-1].isconst=0;
8242             branch_regs[i-1].wasconst=0;
8243             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8244             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8245           }
8246           else
8247           // Alloc the delay slot in case the branch is taken
8248           if((dops[i-1].opcode&0x3E)==0x14) // BEQL/BNEL
8249           {
8250             memcpy(&branch_regs[i-1],&current,sizeof(current));
8251             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;
8252             alloc_cc(&branch_regs[i-1],i);
8253             dirty_reg(&branch_regs[i-1],CCREG);
8254             delayslot_alloc(&branch_regs[i-1],i);
8255             branch_regs[i-1].isconst=0;
8256             alloc_reg(&current,i,CCREG); // Not taken path
8257             dirty_reg(&current,CCREG);
8258             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8259           }
8260           else
8261           if((dops[i-1].opcode&0x3E)==0x16) // BLEZL/BGTZL
8262           {
8263             memcpy(&branch_regs[i-1],&current,sizeof(current));
8264             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;
8265             alloc_cc(&branch_regs[i-1],i);
8266             dirty_reg(&branch_regs[i-1],CCREG);
8267             delayslot_alloc(&branch_regs[i-1],i);
8268             branch_regs[i-1].isconst=0;
8269             alloc_reg(&current,i,CCREG); // Not taken path
8270             dirty_reg(&current,CCREG);
8271             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8272           }
8273           break;
8274         case SJUMP:
8275           //if((dops[i-1].opcode2&0x1E)==0) // BLTZ/BGEZ
8276           if((dops[i-1].opcode2&0x0E)==0) // BLTZ/BGEZ
8277           {
8278             alloc_cc(&current,i-1);
8279             dirty_reg(&current,CCREG);
8280             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
8281               // The delay slot overwrote the branch condition
8282               // Delay slot goes after the test (in order)
8283               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8284               current.u|=1;
8285               delayslot_alloc(&current,i);
8286               current.isconst=0;
8287             }
8288             else
8289             {
8290               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
8291               // Alloc the branch condition register
8292               alloc_reg(&current,i-1,dops[i-1].rs1);
8293             }
8294             memcpy(&branch_regs[i-1],&current,sizeof(current));
8295             branch_regs[i-1].isconst=0;
8296             branch_regs[i-1].wasconst=0;
8297             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8298             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8299           }
8300           else
8301           // Alloc the delay slot in case the branch is taken
8302           if((dops[i-1].opcode2&0x1E)==2) // BLTZL/BGEZL
8303           {
8304             memcpy(&branch_regs[i-1],&current,sizeof(current));
8305             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;
8306             alloc_cc(&branch_regs[i-1],i);
8307             dirty_reg(&branch_regs[i-1],CCREG);
8308             delayslot_alloc(&branch_regs[i-1],i);
8309             branch_regs[i-1].isconst=0;
8310             alloc_reg(&current,i,CCREG); // Not taken path
8311             dirty_reg(&current,CCREG);
8312             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8313           }
8314           // FIXME: BLTZAL/BGEZAL
8315           if(dops[i-1].opcode2&0x10) { // BxxZAL
8316             alloc_reg(&branch_regs[i-1],i-1,31);
8317             dirty_reg(&branch_regs[i-1],31);
8318           }
8319           break;
8320       }
8321
8322       if (dops[i-1].is_ujump)
8323       {
8324         if(dops[i-1].rt1==31) // JAL/JALR
8325         {
8326           // Subroutine call will return here, don't alloc any registers
8327           current.dirty=0;
8328           clear_all_regs(current.regmap);
8329           alloc_reg(&current,i,CCREG);
8330           dirty_reg(&current,CCREG);
8331         }
8332         else if(i+1<slen)
8333         {
8334           // Internal branch will jump here, match registers to caller
8335           current.dirty=0;
8336           clear_all_regs(current.regmap);
8337           alloc_reg(&current,i,CCREG);
8338           dirty_reg(&current,CCREG);
8339           for(j=i-1;j>=0;j--)
8340           {
8341             if(ba[j]==start+i*4+4) {
8342               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
8343               current.dirty=branch_regs[j].dirty;
8344               break;
8345             }
8346           }
8347           while(j>=0) {
8348             if(ba[j]==start+i*4+4) {
8349               for(hr=0;hr<HOST_REGS;hr++) {
8350                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
8351                   current.regmap[hr]=-1;
8352                 }
8353                 current.dirty&=branch_regs[j].dirty;
8354               }
8355             }
8356             j--;
8357           }
8358         }
8359       }
8360     }
8361
8362     // Count cycles in between branches
8363     ccadj[i] = CLOCK_ADJUST(cc);
8364     if (i > 0 && (dops[i-1].is_jump || dops[i].itype == SYSCALL || dops[i].itype == HLECALL))
8365     {
8366       cc=0;
8367     }
8368 #if !defined(DRC_DBG)
8369     else if(dops[i].itype==C2OP&&gte_cycletab[source[i]&0x3f]>2)
8370     {
8371       // this should really be removed since the real stalls have been implemented,
8372       // but doing so causes sizeable perf regression against the older version
8373       u_int gtec = gte_cycletab[source[i] & 0x3f];
8374       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? gtec/2 : 2;
8375     }
8376     else if(i>1&&dops[i].itype==STORE&&dops[i-1].itype==STORE&&dops[i-2].itype==STORE&&!dops[i].bt)
8377     {
8378       cc+=4;
8379     }
8380     else if(dops[i].itype==C2LS)
8381     {
8382       // same as with C2OP
8383       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? 4 : 2;
8384     }
8385 #endif
8386     else
8387     {
8388       cc++;
8389     }
8390
8391     if(!dops[i].is_ds) {
8392       regs[i].dirty=current.dirty;
8393       regs[i].isconst=current.isconst;
8394       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
8395     }
8396     for(hr=0;hr<HOST_REGS;hr++) {
8397       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
8398         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
8399           regs[i].wasconst&=~(1<<hr);
8400         }
8401       }
8402     }
8403     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
8404     regs[i].waswritten=current.waswritten;
8405   }
8406
8407   /* Pass 4 - Cull unused host registers */
8408
8409   uint64_t nr=0;
8410
8411   for (i=slen-1;i>=0;i--)
8412   {
8413     int hr;
8414     if(dops[i].is_jump)
8415     {
8416       if(ba[i]<start || ba[i]>=(start+slen*4))
8417       {
8418         // Branch out of this block, don't need anything
8419         nr=0;
8420       }
8421       else
8422       {
8423         // Internal branch
8424         // Need whatever matches the target
8425         nr=0;
8426         int t=(ba[i]-start)>>2;
8427         for(hr=0;hr<HOST_REGS;hr++)
8428         {
8429           if(regs[i].regmap_entry[hr]>=0) {
8430             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
8431           }
8432         }
8433       }
8434       // Conditional branch may need registers for following instructions
8435       if (!dops[i].is_ujump)
8436       {
8437         if(i<slen-2) {
8438           nr|=needed_reg[i+2];
8439           for(hr=0;hr<HOST_REGS;hr++)
8440           {
8441             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
8442             //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]);
8443           }
8444         }
8445       }
8446       // Don't need stuff which is overwritten
8447       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8448       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8449       // Merge in delay slot
8450       for(hr=0;hr<HOST_REGS;hr++)
8451       {
8452         if(dops[i+1].rt1&&dops[i+1].rt1==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8453         if(dops[i+1].rt2&&dops[i+1].rt2==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8454         if(dops[i+1].rs1==regmap_pre[i][hr]) nr|=1<<hr;
8455         if(dops[i+1].rs2==regmap_pre[i][hr]) nr|=1<<hr;
8456         if(dops[i+1].rs1==regs[i].regmap_entry[hr]) nr|=1<<hr;
8457         if(dops[i+1].rs2==regs[i].regmap_entry[hr]) nr|=1<<hr;
8458         if(ram_offset && (dops[i+1].is_load || dops[i+1].is_store)) {
8459           if(regmap_pre[i][hr]==ROREG) nr|=1<<hr;
8460           if(regs[i].regmap_entry[hr]==ROREG) nr|=1<<hr;
8461         }
8462         if(dops[i+1].is_store) {
8463           if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8464           if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8465         }
8466       }
8467     }
8468     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
8469     {
8470       // SYSCALL instruction (software interrupt)
8471       nr=0;
8472     }
8473     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
8474     {
8475       // ERET instruction (return from interrupt)
8476       nr=0;
8477     }
8478     else // Non-branch
8479     {
8480       if(i<slen-1) {
8481         for(hr=0;hr<HOST_REGS;hr++) {
8482           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
8483           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
8484           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8485           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8486         }
8487       }
8488     }
8489     for(hr=0;hr<HOST_REGS;hr++)
8490     {
8491       // Overwritten registers are not needed
8492       if(dops[i].rt1&&dops[i].rt1==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8493       if(dops[i].rt2&&dops[i].rt2==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8494       if(FTEMP==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8495       // Source registers are needed
8496       if(dops[i].rs1==regmap_pre[i][hr]) nr|=1<<hr;
8497       if(dops[i].rs2==regmap_pre[i][hr]) nr|=1<<hr;
8498       if(dops[i].rs1==regs[i].regmap_entry[hr]) nr|=1<<hr;
8499       if(dops[i].rs2==regs[i].regmap_entry[hr]) nr|=1<<hr;
8500       if(ram_offset && (dops[i].is_load || dops[i].is_store)) {
8501         if(regmap_pre[i][hr]==ROREG) nr|=1<<hr;
8502         if(regs[i].regmap_entry[hr]==ROREG) nr|=1<<hr;
8503       }
8504       if(dops[i].is_store) {
8505         if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8506         if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8507       }
8508       // Don't store a register immediately after writing it,
8509       // may prevent dual-issue.
8510       // But do so if this is a branch target, otherwise we
8511       // might have to load the register before the branch.
8512       if(i>0&&!dops[i].bt&&((regs[i].wasdirty>>hr)&1)) {
8513         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
8514           if(dops[i-1].rt1==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8515           if(dops[i-1].rt2==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8516         }
8517         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
8518           if(dops[i-1].rt1==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8519           if(dops[i-1].rt2==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8520         }
8521       }
8522     }
8523     // Cycle count is needed at branches.  Assume it is needed at the target too.
8524     if(i==0||dops[i].bt||dops[i].itype==CJUMP||dops[i].itype==SPAN) {
8525       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8526       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8527     }
8528     // Save it
8529     needed_reg[i]=nr;
8530
8531     // Deallocate unneeded registers
8532     for(hr=0;hr<HOST_REGS;hr++)
8533     {
8534       if(!((nr>>hr)&1)) {
8535         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
8536         if(dops[i].is_jump)
8537         {
8538           int map1 = 0, map2 = 0, temp = 0; // or -1 ??
8539           if (dops[i+1].is_load || dops[i+1].is_store)
8540             map1 = ROREG;
8541           if (dops[i+1].is_store)
8542             map2 = INVCP;
8543           if(dops[i+1].itype==LOADLR || dops[i+1].itype==STORELR || dops[i+1].itype==C2LS)
8544             temp = FTEMP;
8545           if((regs[i].regmap[hr]&63)!=dops[i].rs1 && (regs[i].regmap[hr]&63)!=dops[i].rs2 &&
8546              (regs[i].regmap[hr]&63)!=dops[i].rt1 && (regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8547              (regs[i].regmap[hr]&63)!=dops[i+1].rt1 && (regs[i].regmap[hr]&63)!=dops[i+1].rt2 &&
8548              regs[i].regmap[hr]!=dops[i+1].rs1 && regs[i].regmap[hr]!=dops[i+1].rs2 &&
8549              (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=PTEMP &&
8550              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
8551              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
8552              regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2)
8553           {
8554             regs[i].regmap[hr]=-1;
8555             regs[i].isconst&=~(1<<hr);
8556             regs[i].dirty&=~(1<<hr);
8557             regs[i+1].wasdirty&=~(1<<hr);
8558             if((branch_regs[i].regmap[hr]&63)!=dops[i].rs1 && (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 &&
8559                (branch_regs[i].regmap[hr]&63)!=dops[i].rt1 && (branch_regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8560                (branch_regs[i].regmap[hr]&63)!=dops[i+1].rt1 && (branch_regs[i].regmap[hr]&63)!=dops[i+1].rt2 &&
8561                branch_regs[i].regmap[hr]!=dops[i+1].rs1 && branch_regs[i].regmap[hr]!=dops[i+1].rs2 &&
8562                (branch_regs[i].regmap[hr]&63)!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
8563                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
8564                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
8565                branch_regs[i].regmap[hr]!=map1 && branch_regs[i].regmap[hr]!=map2)
8566             {
8567               branch_regs[i].regmap[hr]=-1;
8568               branch_regs[i].regmap_entry[hr]=-1;
8569               if (!dops[i].is_ujump)
8570               {
8571                 if (i < slen-2) {
8572                   regmap_pre[i+2][hr]=-1;
8573                   regs[i+2].wasconst&=~(1<<hr);
8574                 }
8575               }
8576             }
8577           }
8578         }
8579         else
8580         {
8581           // Non-branch
8582           if(i>0)
8583           {
8584             int map1 = -1, map2 = -1, temp=-1;
8585             if (dops[i].is_load || dops[i].is_store)
8586               map1 = ROREG;
8587             if (dops[i].is_store)
8588               map2 = INVCP;
8589             if (dops[i].itype==LOADLR || dops[i].itype==STORELR || dops[i].itype==C2LS)
8590               temp = FTEMP;
8591             if((regs[i].regmap[hr]&63)!=dops[i].rt1 && (regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8592                regs[i].regmap[hr]!=dops[i].rs1 && regs[i].regmap[hr]!=dops[i].rs2 &&
8593                (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2 &&
8594                //(dops[i].itype!=SPAN||regs[i].regmap[hr]!=CCREG)
8595                regs[i].regmap[hr] != CCREG)
8596             {
8597               if(i<slen-1&&!dops[i].is_ds) {
8598                 assert(regs[i].regmap[hr]<64);
8599                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8600                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8601                 {
8602                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8603                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8604                 }
8605                 regmap_pre[i+1][hr]=-1;
8606                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8607                 regs[i+1].wasconst&=~(1<<hr);
8608               }
8609               regs[i].regmap[hr]=-1;
8610               regs[i].isconst&=~(1<<hr);
8611               regs[i].dirty&=~(1<<hr);
8612               regs[i+1].wasdirty&=~(1<<hr);
8613             }
8614           }
8615         }
8616       } // if needed
8617     } // for hr
8618   }
8619
8620   /* Pass 5 - Pre-allocate registers */
8621
8622   // If a register is allocated during a loop, try to allocate it for the
8623   // entire loop, if possible.  This avoids loading/storing registers
8624   // inside of the loop.
8625
8626   signed char f_regmap[HOST_REGS];
8627   clear_all_regs(f_regmap);
8628   for(i=0;i<slen-1;i++)
8629   {
8630     if(dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8631     {
8632       if(ba[i]>=start && ba[i]<(start+i*4))
8633       if(dops[i+1].itype==NOP||dops[i+1].itype==MOV||dops[i+1].itype==ALU
8634       ||dops[i+1].itype==SHIFTIMM||dops[i+1].itype==IMM16||dops[i+1].itype==LOAD
8635       ||dops[i+1].itype==STORE||dops[i+1].itype==STORELR||dops[i+1].itype==C1LS
8636       ||dops[i+1].itype==SHIFT||dops[i+1].itype==COP1
8637       ||dops[i+1].itype==COP2||dops[i+1].itype==C2LS||dops[i+1].itype==C2OP)
8638       {
8639         int t=(ba[i]-start)>>2;
8640         if(t > 0 && !dops[t-1].is_jump) // loop_preload can't handle jumps into delay slots
8641         if(t<2||(dops[t-2].itype!=UJUMP&&dops[t-2].itype!=RJUMP)||dops[t-2].rt1!=31) // call/ret assumes no registers allocated
8642         for(hr=0;hr<HOST_REGS;hr++)
8643         {
8644           if(regs[i].regmap[hr]>=0) {
8645             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8646               // dealloc old register
8647               int n;
8648               for(n=0;n<HOST_REGS;n++)
8649               {
8650                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8651               }
8652               // and alloc new one
8653               f_regmap[hr]=regs[i].regmap[hr];
8654             }
8655           }
8656           if(branch_regs[i].regmap[hr]>=0) {
8657             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8658               // dealloc old register
8659               int n;
8660               for(n=0;n<HOST_REGS;n++)
8661               {
8662                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8663               }
8664               // and alloc new one
8665               f_regmap[hr]=branch_regs[i].regmap[hr];
8666             }
8667           }
8668           if(dops[i].ooo) {
8669             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8670               f_regmap[hr]=branch_regs[i].regmap[hr];
8671           }else{
8672             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8673               f_regmap[hr]=branch_regs[i].regmap[hr];
8674           }
8675           // Avoid dirty->clean transition
8676           #ifdef DESTRUCTIVE_WRITEBACK
8677           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;
8678           #endif
8679           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8680           // case above, however it's always a good idea.  We can't hoist the
8681           // load if the register was already allocated, so there's no point
8682           // wasting time analyzing most of these cases.  It only "succeeds"
8683           // when the mapping was different and the load can be replaced with
8684           // a mov, which is of negligible benefit.  So such cases are
8685           // skipped below.
8686           if(f_regmap[hr]>0) {
8687             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8688               int r=f_regmap[hr];
8689               for(j=t;j<=i;j++)
8690               {
8691                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8692                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8693                 assert(r < 64);
8694                 if(regs[j].regmap[hr]==f_regmap[hr]&&(f_regmap[hr]&63)<TEMPREG) {
8695                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8696                   int k;
8697                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8698                     if(get_reg(regs[i].regmap,f_regmap[hr])>=0) break;
8699                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8700                     k=i;
8701                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8702                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8703                         //printf("no free regs for store %x\n",start+(k-1)*4);
8704                         break;
8705                       }
8706                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8707                         //printf("no-match due to different register\n");
8708                         break;
8709                       }
8710                       if (dops[k-2].is_jump) {
8711                         //printf("no-match due to branch\n");
8712                         break;
8713                       }
8714                       // call/ret fast path assumes no registers allocated
8715                       if(k>2&&(dops[k-3].itype==UJUMP||dops[k-3].itype==RJUMP)&&dops[k-3].rt1==31) {
8716                         break;
8717                       }
8718                       k--;
8719                     }
8720                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8721                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8722                       while(k<i) {
8723                         regs[k].regmap_entry[hr]=f_regmap[hr];
8724                         regs[k].regmap[hr]=f_regmap[hr];
8725                         regmap_pre[k+1][hr]=f_regmap[hr];
8726                         regs[k].wasdirty&=~(1<<hr);
8727                         regs[k].dirty&=~(1<<hr);
8728                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8729                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8730                         regs[k].wasconst&=~(1<<hr);
8731                         regs[k].isconst&=~(1<<hr);
8732                         k++;
8733                       }
8734                     }
8735                     else {
8736                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8737                       break;
8738                     }
8739                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8740                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8741                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8742                       regs[i].regmap_entry[hr]=f_regmap[hr];
8743                       regs[i].regmap[hr]=f_regmap[hr];
8744                       regs[i].wasdirty&=~(1<<hr);
8745                       regs[i].dirty&=~(1<<hr);
8746                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8747                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8748                       regs[i].wasconst&=~(1<<hr);
8749                       regs[i].isconst&=~(1<<hr);
8750                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8751                       branch_regs[i].wasdirty&=~(1<<hr);
8752                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8753                       branch_regs[i].regmap[hr]=f_regmap[hr];
8754                       branch_regs[i].dirty&=~(1<<hr);
8755                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8756                       branch_regs[i].wasconst&=~(1<<hr);
8757                       branch_regs[i].isconst&=~(1<<hr);
8758                       if (!dops[i].is_ujump) {
8759                         regmap_pre[i+2][hr]=f_regmap[hr];
8760                         regs[i+2].wasdirty&=~(1<<hr);
8761                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8762                       }
8763                     }
8764                   }
8765                   for(k=t;k<j;k++) {
8766                     // Alloc register clean at beginning of loop,
8767                     // but may dirty it in pass 6
8768                     regs[k].regmap_entry[hr]=f_regmap[hr];
8769                     regs[k].regmap[hr]=f_regmap[hr];
8770                     regs[k].dirty&=~(1<<hr);
8771                     regs[k].wasconst&=~(1<<hr);
8772                     regs[k].isconst&=~(1<<hr);
8773                     if (dops[k].is_jump) {
8774                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8775                       branch_regs[k].regmap[hr]=f_regmap[hr];
8776                       branch_regs[k].dirty&=~(1<<hr);
8777                       branch_regs[k].wasconst&=~(1<<hr);
8778                       branch_regs[k].isconst&=~(1<<hr);
8779                       if (!dops[k].is_ujump) {
8780                         regmap_pre[k+2][hr]=f_regmap[hr];
8781                         regs[k+2].wasdirty&=~(1<<hr);
8782                       }
8783                     }
8784                     else
8785                     {
8786                       regmap_pre[k+1][hr]=f_regmap[hr];
8787                       regs[k+1].wasdirty&=~(1<<hr);
8788                     }
8789                   }
8790                   if(regs[j].regmap[hr]==f_regmap[hr])
8791                     regs[j].regmap_entry[hr]=f_regmap[hr];
8792                   break;
8793                 }
8794                 if(j==i) break;
8795                 if(regs[j].regmap[hr]>=0)
8796                   break;
8797                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8798                   //printf("no-match due to different register\n");
8799                   break;
8800                 }
8801                 if (dops[j].is_ujump)
8802                 {
8803                   // Stop on unconditional branch
8804                   break;
8805                 }
8806                 if(dops[j].itype==CJUMP||dops[j].itype==SJUMP)
8807                 {
8808                   if(dops[j].ooo) {
8809                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8810                       break;
8811                   }else{
8812                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8813                       break;
8814                   }
8815                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8816                     //printf("no-match due to different register (branch)\n");
8817                     break;
8818                   }
8819                 }
8820                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8821                   //printf("No free regs for store %x\n",start+j*4);
8822                   break;
8823                 }
8824                 assert(f_regmap[hr]<64);
8825               }
8826             }
8827           }
8828         }
8829       }
8830     }else{
8831       // Non branch or undetermined branch target
8832       for(hr=0;hr<HOST_REGS;hr++)
8833       {
8834         if(hr!=EXCLUDE_REG) {
8835           if(regs[i].regmap[hr]>=0) {
8836             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8837               // dealloc old register
8838               int n;
8839               for(n=0;n<HOST_REGS;n++)
8840               {
8841                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8842               }
8843               // and alloc new one
8844               f_regmap[hr]=regs[i].regmap[hr];
8845             }
8846           }
8847         }
8848       }
8849       // Try to restore cycle count at branch targets
8850       if(dops[i].bt) {
8851         for(j=i;j<slen-1;j++) {
8852           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8853           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8854             //printf("no free regs for store %x\n",start+j*4);
8855             break;
8856           }
8857         }
8858         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8859           int k=i;
8860           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8861           while(k<j) {
8862             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8863             regs[k].regmap[HOST_CCREG]=CCREG;
8864             regmap_pre[k+1][HOST_CCREG]=CCREG;
8865             regs[k+1].wasdirty|=1<<HOST_CCREG;
8866             regs[k].dirty|=1<<HOST_CCREG;
8867             regs[k].wasconst&=~(1<<HOST_CCREG);
8868             regs[k].isconst&=~(1<<HOST_CCREG);
8869             k++;
8870           }
8871           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8872         }
8873         // Work backwards from the branch target
8874         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8875         {
8876           //printf("Extend backwards\n");
8877           int k;
8878           k=i;
8879           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8880             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8881               //printf("no free regs for store %x\n",start+(k-1)*4);
8882               break;
8883             }
8884             k--;
8885           }
8886           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8887             //printf("Extend CC, %x ->\n",start+k*4);
8888             while(k<=i) {
8889               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8890               regs[k].regmap[HOST_CCREG]=CCREG;
8891               regmap_pre[k+1][HOST_CCREG]=CCREG;
8892               regs[k+1].wasdirty|=1<<HOST_CCREG;
8893               regs[k].dirty|=1<<HOST_CCREG;
8894               regs[k].wasconst&=~(1<<HOST_CCREG);
8895               regs[k].isconst&=~(1<<HOST_CCREG);
8896               k++;
8897             }
8898           }
8899           else {
8900             //printf("Fail Extend CC, %x ->\n",start+k*4);
8901           }
8902         }
8903       }
8904       if(dops[i].itype!=STORE&&dops[i].itype!=STORELR&&dops[i].itype!=C1LS&&dops[i].itype!=SHIFT&&
8905          dops[i].itype!=NOP&&dops[i].itype!=MOV&&dops[i].itype!=ALU&&dops[i].itype!=SHIFTIMM&&
8906          dops[i].itype!=IMM16&&dops[i].itype!=LOAD&&dops[i].itype!=COP1)
8907       {
8908         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8909       }
8910     }
8911   }
8912
8913   // This allocates registers (if possible) one instruction prior
8914   // to use, which can avoid a load-use penalty on certain CPUs.
8915   for(i=0;i<slen-1;i++)
8916   {
8917     if (!i || !dops[i-1].is_jump)
8918     {
8919       if(!dops[i+1].bt)
8920       {
8921         if(dops[i].itype==ALU||dops[i].itype==MOV||dops[i].itype==LOAD||dops[i].itype==SHIFTIMM||dops[i].itype==IMM16
8922            ||((dops[i].itype==COP1||dops[i].itype==COP2)&&dops[i].opcode2<3))
8923         {
8924           if(dops[i+1].rs1) {
8925             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs1))>=0)
8926             {
8927               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8928               {
8929                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8930                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8931                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8932                 regs[i].isconst&=~(1<<hr);
8933                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8934                 constmap[i][hr]=constmap[i+1][hr];
8935                 regs[i+1].wasdirty&=~(1<<hr);
8936                 regs[i].dirty&=~(1<<hr);
8937               }
8938             }
8939           }
8940           if(dops[i+1].rs2) {
8941             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs2))>=0)
8942             {
8943               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8944               {
8945                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8946                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8947                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8948                 regs[i].isconst&=~(1<<hr);
8949                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8950                 constmap[i][hr]=constmap[i+1][hr];
8951                 regs[i+1].wasdirty&=~(1<<hr);
8952                 regs[i].dirty&=~(1<<hr);
8953               }
8954             }
8955           }
8956           // Preload target address for load instruction (non-constant)
8957           if(dops[i+1].itype==LOAD&&dops[i+1].rs1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8958             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8959             {
8960               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8961               {
8962                 regs[i].regmap[hr]=dops[i+1].rs1;
8963                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8964                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8965                 regs[i].isconst&=~(1<<hr);
8966                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8967                 constmap[i][hr]=constmap[i+1][hr];
8968                 regs[i+1].wasdirty&=~(1<<hr);
8969                 regs[i].dirty&=~(1<<hr);
8970               }
8971             }
8972           }
8973           // Load source into target register
8974           if(dops[i+1].lt1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8975             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8976             {
8977               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8978               {
8979                 regs[i].regmap[hr]=dops[i+1].rs1;
8980                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8981                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8982                 regs[i].isconst&=~(1<<hr);
8983                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8984                 constmap[i][hr]=constmap[i+1][hr];
8985                 regs[i+1].wasdirty&=~(1<<hr);
8986                 regs[i].dirty&=~(1<<hr);
8987               }
8988             }
8989           }
8990           // Address for store instruction (non-constant)
8991           if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR
8992              ||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8993             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8994               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8995               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8996               else {
8997                 regs[i+1].regmap[hr]=AGEN1+((i+1)&1);
8998                 regs[i+1].isconst&=~(1<<hr);
8999               }
9000               assert(hr>=0);
9001               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
9002               {
9003                 regs[i].regmap[hr]=dops[i+1].rs1;
9004                 regmap_pre[i+1][hr]=dops[i+1].rs1;
9005                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
9006                 regs[i].isconst&=~(1<<hr);
9007                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
9008                 constmap[i][hr]=constmap[i+1][hr];
9009                 regs[i+1].wasdirty&=~(1<<hr);
9010                 regs[i].dirty&=~(1<<hr);
9011               }
9012             }
9013           }
9014           if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
9015             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
9016               int nr;
9017               hr=get_reg(regs[i+1].regmap,FTEMP);
9018               assert(hr>=0);
9019               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
9020               {
9021                 regs[i].regmap[hr]=dops[i+1].rs1;
9022                 regmap_pre[i+1][hr]=dops[i+1].rs1;
9023                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
9024                 regs[i].isconst&=~(1<<hr);
9025                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
9026                 constmap[i][hr]=constmap[i+1][hr];
9027                 regs[i+1].wasdirty&=~(1<<hr);
9028                 regs[i].dirty&=~(1<<hr);
9029               }
9030               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
9031               {
9032                 // move it to another register
9033                 regs[i+1].regmap[hr]=-1;
9034                 regmap_pre[i+2][hr]=-1;
9035                 regs[i+1].regmap[nr]=FTEMP;
9036                 regmap_pre[i+2][nr]=FTEMP;
9037                 regs[i].regmap[nr]=dops[i+1].rs1;
9038                 regmap_pre[i+1][nr]=dops[i+1].rs1;
9039                 regs[i+1].regmap_entry[nr]=dops[i+1].rs1;
9040                 regs[i].isconst&=~(1<<nr);
9041                 regs[i+1].isconst&=~(1<<nr);
9042                 regs[i].dirty&=~(1<<nr);
9043                 regs[i+1].wasdirty&=~(1<<nr);
9044                 regs[i+1].dirty&=~(1<<nr);
9045                 regs[i+2].wasdirty&=~(1<<nr);
9046               }
9047             }
9048           }
9049           if(dops[i+1].itype==LOAD||dops[i+1].itype==LOADLR||dops[i+1].itype==STORE||dops[i+1].itype==STORELR/*||dops[i+1].itype==C1LS||||dops[i+1].itype==C2LS*/) {
9050             if(dops[i+1].itype==LOAD)
9051               hr=get_reg(regs[i+1].regmap,dops[i+1].rt1);
9052             if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
9053               hr=get_reg(regs[i+1].regmap,FTEMP);
9054             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
9055               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
9056               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
9057             }
9058             if(hr>=0&&regs[i].regmap[hr]<0) {
9059               int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
9060               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
9061                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
9062                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
9063                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
9064                 regs[i].isconst&=~(1<<hr);
9065                 regs[i+1].wasdirty&=~(1<<hr);
9066                 regs[i].dirty&=~(1<<hr);
9067               }
9068             }
9069           }
9070         }
9071       }
9072     }
9073   }
9074
9075   /* Pass 6 - Optimize clean/dirty state */
9076   clean_registers(0,slen-1,1);
9077
9078   /* Pass 7 - Identify 32-bit registers */
9079   for (i=slen-1;i>=0;i--)
9080   {
9081     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
9082     {
9083       // Conditional branch
9084       if((source[i]>>16)!=0x1000&&i<slen-2) {
9085         // Mark this address as a branch target since it may be called
9086         // upon return from interrupt
9087         dops[i+2].bt=1;
9088       }
9089     }
9090   }
9091
9092   if(dops[slen-1].itype==SPAN) {
9093     dops[slen-1].bt=1; // Mark as a branch target so instruction can restart after exception
9094   }
9095
9096 #ifdef REG_ALLOC_PRINT
9097   /* Debug/disassembly */
9098   for(i=0;i<slen;i++)
9099   {
9100     printf("U:");
9101     int r;
9102     for(r=1;r<=CCREG;r++) {
9103       if((unneeded_reg[i]>>r)&1) {
9104         if(r==HIREG) printf(" HI");
9105         else if(r==LOREG) printf(" LO");
9106         else printf(" r%d",r);
9107       }
9108     }
9109     printf("\n");
9110     #if defined(__i386__) || defined(__x86_64__)
9111     printf("pre: eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",regmap_pre[i][0],regmap_pre[i][1],regmap_pre[i][2],regmap_pre[i][3],regmap_pre[i][5],regmap_pre[i][6],regmap_pre[i][7]);
9112     #endif
9113     #ifdef __arm__
9114     printf("pre: r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d\n",regmap_pre[i][0],regmap_pre[i][1],regmap_pre[i][2],regmap_pre[i][3],regmap_pre[i][4],regmap_pre[i][5],regmap_pre[i][6],regmap_pre[i][7],regmap_pre[i][8],regmap_pre[i][9],regmap_pre[i][10],regmap_pre[i][12]);
9115     #endif
9116     #if defined(__i386__) || defined(__x86_64__)
9117     printf("needs: ");
9118     if(needed_reg[i]&1) printf("eax ");
9119     if((needed_reg[i]>>1)&1) printf("ecx ");
9120     if((needed_reg[i]>>2)&1) printf("edx ");
9121     if((needed_reg[i]>>3)&1) printf("ebx ");
9122     if((needed_reg[i]>>5)&1) printf("ebp ");
9123     if((needed_reg[i]>>6)&1) printf("esi ");
9124     if((needed_reg[i]>>7)&1) printf("edi ");
9125     printf("\n");
9126     printf("entry: eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",regs[i].regmap_entry[0],regs[i].regmap_entry[1],regs[i].regmap_entry[2],regs[i].regmap_entry[3],regs[i].regmap_entry[5],regs[i].regmap_entry[6],regs[i].regmap_entry[7]);
9127     printf("dirty: ");
9128     if(regs[i].wasdirty&1) printf("eax ");
9129     if((regs[i].wasdirty>>1)&1) printf("ecx ");
9130     if((regs[i].wasdirty>>2)&1) printf("edx ");
9131     if((regs[i].wasdirty>>3)&1) printf("ebx ");
9132     if((regs[i].wasdirty>>5)&1) printf("ebp ");
9133     if((regs[i].wasdirty>>6)&1) printf("esi ");
9134     if((regs[i].wasdirty>>7)&1) printf("edi ");
9135     #endif
9136     #ifdef __arm__
9137     printf("entry: r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d\n",regs[i].regmap_entry[0],regs[i].regmap_entry[1],regs[i].regmap_entry[2],regs[i].regmap_entry[3],regs[i].regmap_entry[4],regs[i].regmap_entry[5],regs[i].regmap_entry[6],regs[i].regmap_entry[7],regs[i].regmap_entry[8],regs[i].regmap_entry[9],regs[i].regmap_entry[10],regs[i].regmap_entry[12]);
9138     printf("dirty: ");
9139     if(regs[i].wasdirty&1) printf("r0 ");
9140     if((regs[i].wasdirty>>1)&1) printf("r1 ");
9141     if((regs[i].wasdirty>>2)&1) printf("r2 ");
9142     if((regs[i].wasdirty>>3)&1) printf("r3 ");
9143     if((regs[i].wasdirty>>4)&1) printf("r4 ");
9144     if((regs[i].wasdirty>>5)&1) printf("r5 ");
9145     if((regs[i].wasdirty>>6)&1) printf("r6 ");
9146     if((regs[i].wasdirty>>7)&1) printf("r7 ");
9147     if((regs[i].wasdirty>>8)&1) printf("r8 ");
9148     if((regs[i].wasdirty>>9)&1) printf("r9 ");
9149     if((regs[i].wasdirty>>10)&1) printf("r10 ");
9150     if((regs[i].wasdirty>>12)&1) printf("r12 ");
9151     #endif
9152     printf("\n");
9153     disassemble_inst(i);
9154     //printf ("ccadj[%d] = %d\n",i,ccadj[i]);
9155     #if defined(__i386__) || defined(__x86_64__)
9156     printf("eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d dirty: ",regs[i].regmap[0],regs[i].regmap[1],regs[i].regmap[2],regs[i].regmap[3],regs[i].regmap[5],regs[i].regmap[6],regs[i].regmap[7]);
9157     if(regs[i].dirty&1) printf("eax ");
9158     if((regs[i].dirty>>1)&1) printf("ecx ");
9159     if((regs[i].dirty>>2)&1) printf("edx ");
9160     if((regs[i].dirty>>3)&1) printf("ebx ");
9161     if((regs[i].dirty>>5)&1) printf("ebp ");
9162     if((regs[i].dirty>>6)&1) printf("esi ");
9163     if((regs[i].dirty>>7)&1) printf("edi ");
9164     #endif
9165     #ifdef __arm__
9166     printf("r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d dirty: ",regs[i].regmap[0],regs[i].regmap[1],regs[i].regmap[2],regs[i].regmap[3],regs[i].regmap[4],regs[i].regmap[5],regs[i].regmap[6],regs[i].regmap[7],regs[i].regmap[8],regs[i].regmap[9],regs[i].regmap[10],regs[i].regmap[12]);
9167     if(regs[i].dirty&1) printf("r0 ");
9168     if((regs[i].dirty>>1)&1) printf("r1 ");
9169     if((regs[i].dirty>>2)&1) printf("r2 ");
9170     if((regs[i].dirty>>3)&1) printf("r3 ");
9171     if((regs[i].dirty>>4)&1) printf("r4 ");
9172     if((regs[i].dirty>>5)&1) printf("r5 ");
9173     if((regs[i].dirty>>6)&1) printf("r6 ");
9174     if((regs[i].dirty>>7)&1) printf("r7 ");
9175     if((regs[i].dirty>>8)&1) printf("r8 ");
9176     if((regs[i].dirty>>9)&1) printf("r9 ");
9177     if((regs[i].dirty>>10)&1) printf("r10 ");
9178     if((regs[i].dirty>>12)&1) printf("r12 ");
9179     #endif
9180     printf("\n");
9181     if(regs[i].isconst) {
9182       printf("constants: ");
9183       #if defined(__i386__) || defined(__x86_64__)
9184       if(regs[i].isconst&1) printf("eax=%x ",(u_int)constmap[i][0]);
9185       if((regs[i].isconst>>1)&1) printf("ecx=%x ",(u_int)constmap[i][1]);
9186       if((regs[i].isconst>>2)&1) printf("edx=%x ",(u_int)constmap[i][2]);
9187       if((regs[i].isconst>>3)&1) printf("ebx=%x ",(u_int)constmap[i][3]);
9188       if((regs[i].isconst>>5)&1) printf("ebp=%x ",(u_int)constmap[i][5]);
9189       if((regs[i].isconst>>6)&1) printf("esi=%x ",(u_int)constmap[i][6]);
9190       if((regs[i].isconst>>7)&1) printf("edi=%x ",(u_int)constmap[i][7]);
9191       #endif
9192       #if defined(__arm__) || defined(__aarch64__)
9193       int r;
9194       for (r = 0; r < ARRAY_SIZE(constmap[i]); r++)
9195         if ((regs[i].isconst >> r) & 1)
9196           printf(" r%d=%x", r, (u_int)constmap[i][r]);
9197       #endif
9198       printf("\n");
9199     }
9200     if(dops[i].is_jump) {
9201       #if defined(__i386__) || defined(__x86_64__)
9202       printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d dirty: ",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]);
9203       if(branch_regs[i].dirty&1) printf("eax ");
9204       if((branch_regs[i].dirty>>1)&1) printf("ecx ");
9205       if((branch_regs[i].dirty>>2)&1) printf("edx ");
9206       if((branch_regs[i].dirty>>3)&1) printf("ebx ");
9207       if((branch_regs[i].dirty>>5)&1) printf("ebp ");
9208       if((branch_regs[i].dirty>>6)&1) printf("esi ");
9209       if((branch_regs[i].dirty>>7)&1) printf("edi ");
9210       #endif
9211       #ifdef __arm__
9212       printf("branch(%d): r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d dirty: ",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[4],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7],branch_regs[i].regmap[8],branch_regs[i].regmap[9],branch_regs[i].regmap[10],branch_regs[i].regmap[12]);
9213       if(branch_regs[i].dirty&1) printf("r0 ");
9214       if((branch_regs[i].dirty>>1)&1) printf("r1 ");
9215       if((branch_regs[i].dirty>>2)&1) printf("r2 ");
9216       if((branch_regs[i].dirty>>3)&1) printf("r3 ");
9217       if((branch_regs[i].dirty>>4)&1) printf("r4 ");
9218       if((branch_regs[i].dirty>>5)&1) printf("r5 ");
9219       if((branch_regs[i].dirty>>6)&1) printf("r6 ");
9220       if((branch_regs[i].dirty>>7)&1) printf("r7 ");
9221       if((branch_regs[i].dirty>>8)&1) printf("r8 ");
9222       if((branch_regs[i].dirty>>9)&1) printf("r9 ");
9223       if((branch_regs[i].dirty>>10)&1) printf("r10 ");
9224       if((branch_regs[i].dirty>>12)&1) printf("r12 ");
9225       #endif
9226     }
9227   }
9228 #endif // REG_ALLOC_PRINT
9229
9230   /* Pass 8 - Assembly */
9231   linkcount=0;stubcount=0;
9232   ds=0;is_delayslot=0;
9233   u_int dirty_pre=0;
9234   void *beginning=start_block();
9235   if((u_int)addr&1) {
9236     ds=1;
9237     pagespan_ds();
9238   }
9239   void *instr_addr0_override = NULL;
9240
9241   if (start == 0x80030000) {
9242     // nasty hack for the fastbios thing
9243     // override block entry to this code
9244     instr_addr0_override = out;
9245     emit_movimm(start,0);
9246     // abuse io address var as a flag that we
9247     // have already returned here once
9248     emit_readword(&address,1);
9249     emit_writeword(0,&pcaddr);
9250     emit_writeword(0,&address);
9251     emit_cmp(0,1);
9252     #ifdef __aarch64__
9253     emit_jeq(out + 4*2);
9254     emit_far_jump(new_dyna_leave);
9255     #else
9256     emit_jne(new_dyna_leave);
9257     #endif
9258   }
9259   for(i=0;i<slen;i++)
9260   {
9261     check_regmap(regmap_pre[i]);
9262     check_regmap(regs[i].regmap_entry);
9263     check_regmap(regs[i].regmap);
9264     //if(ds) printf("ds: ");
9265     disassemble_inst(i);
9266     if(ds) {
9267       ds=0; // Skip delay slot
9268       if(dops[i].bt) assem_debug("OOPS - branch into delay slot\n");
9269       instr_addr[i] = NULL;
9270     } else {
9271       speculate_register_values(i);
9272       #ifndef DESTRUCTIVE_WRITEBACK
9273       if (i < 2 || !dops[i-2].is_ujump)
9274       {
9275         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
9276       }
9277       if((dops[i].itype==CJUMP||dops[i].itype==SJUMP)) {
9278         dirty_pre=branch_regs[i].dirty;
9279       }else{
9280         dirty_pre=regs[i].dirty;
9281       }
9282       #endif
9283       // write back
9284       if (i < 2 || !dops[i-2].is_ujump)
9285       {
9286         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
9287         loop_preload(regmap_pre[i],regs[i].regmap_entry);
9288       }
9289       // branch target entry point
9290       instr_addr[i] = out;
9291       assem_debug("<->\n");
9292       drc_dbg_emit_do_cmp(i, ccadj[i]);
9293       if (clear_hack_addr) {
9294         emit_movimm(0, 0);
9295         emit_writeword(0, &hack_addr);
9296         clear_hack_addr = 0;
9297       }
9298
9299       // load regs
9300       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
9301         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
9302       load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i].rs1,dops[i].rs2);
9303       address_generation(i,&regs[i],regs[i].regmap_entry);
9304       load_consts(regmap_pre[i],regs[i].regmap,i);
9305       if(dops[i].is_jump)
9306       {
9307         // Load the delay slot registers if necessary
9308         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))
9309           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9310         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))
9311           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9312         if (ram_offset && (dops[i+1].is_load || dops[i+1].is_store))
9313           load_regs(regs[i].regmap_entry,regs[i].regmap,ROREG,ROREG);
9314         if (dops[i+1].is_store)
9315           load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9316       }
9317       else if(i+1<slen)
9318       {
9319         // Preload registers for following instruction
9320         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2)
9321           if(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs1!=dops[i].rt2)
9322             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9323         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2)
9324           if(dops[i+1].rs2!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt2)
9325             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9326       }
9327       // TODO: if(is_ooo(i)) address_generation(i+1);
9328       if (!dops[i].is_jump || dops[i].itype == CJUMP)
9329         load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
9330       if (ram_offset && (dops[i].is_load || dops[i].is_store))
9331         load_regs(regs[i].regmap_entry,regs[i].regmap,ROREG,ROREG);
9332       if (dops[i].is_store)
9333         load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9334
9335       ds = assemble(i, &regs[i], ccadj[i]);
9336
9337       if (dops[i].is_ujump)
9338         literal_pool(1024);
9339       else
9340         literal_pool_jumpover(256);
9341     }
9342   }
9343
9344   assert(slen > 0);
9345   if (slen > 0 && dops[slen-1].itype == INTCALL) {
9346     // no ending needed for this block since INTCALL never returns
9347   }
9348   // If the block did not end with an unconditional branch,
9349   // add a jump to the next instruction.
9350   else if (i > 1) {
9351     if (!dops[i-2].is_ujump && dops[i-1].itype != SPAN) {
9352       assert(!dops[i-1].is_jump);
9353       assert(i==slen);
9354       if(dops[i-2].itype!=CJUMP&&dops[i-2].itype!=SJUMP) {
9355         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9356         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9357           emit_loadreg(CCREG,HOST_CCREG);
9358         emit_addimm(HOST_CCREG, ccadj[i-1] + CLOCK_ADJUST(1), HOST_CCREG);
9359       }
9360       else
9361       {
9362         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
9363         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
9364       }
9365       add_to_linker(out,start+i*4,0);
9366       emit_jmp(0);
9367     }
9368   }
9369   else
9370   {
9371     assert(i>0);
9372     assert(!dops[i-1].is_jump);
9373     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9374     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9375       emit_loadreg(CCREG,HOST_CCREG);
9376     emit_addimm(HOST_CCREG, ccadj[i-1] + CLOCK_ADJUST(1), HOST_CCREG);
9377     add_to_linker(out,start+i*4,0);
9378     emit_jmp(0);
9379   }
9380
9381   // TODO: delay slot stubs?
9382   // Stubs
9383   for(i=0;i<stubcount;i++)
9384   {
9385     switch(stubs[i].type)
9386     {
9387       case LOADB_STUB:
9388       case LOADH_STUB:
9389       case LOADW_STUB:
9390       case LOADD_STUB:
9391       case LOADBU_STUB:
9392       case LOADHU_STUB:
9393         do_readstub(i);break;
9394       case STOREB_STUB:
9395       case STOREH_STUB:
9396       case STOREW_STUB:
9397       case STORED_STUB:
9398         do_writestub(i);break;
9399       case CC_STUB:
9400         do_ccstub(i);break;
9401       case INVCODE_STUB:
9402         do_invstub(i);break;
9403       case FP_STUB:
9404         do_cop1stub(i);break;
9405       case STORELR_STUB:
9406         do_unalignedwritestub(i);break;
9407     }
9408   }
9409
9410   if (instr_addr0_override)
9411     instr_addr[0] = instr_addr0_override;
9412
9413   /* Pass 9 - Linker */
9414   for(i=0;i<linkcount;i++)
9415   {
9416     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9417     literal_pool(64);
9418     if (!link_addr[i].ext)
9419     {
9420       void *stub = out;
9421       void *addr = check_addr(link_addr[i].target);
9422       emit_extjump(link_addr[i].addr, link_addr[i].target);
9423       if (addr) {
9424         set_jump_target(link_addr[i].addr, addr);
9425         add_jump_out(link_addr[i].target,stub);
9426       }
9427       else
9428         set_jump_target(link_addr[i].addr, stub);
9429     }
9430     else
9431     {
9432       // Internal branch
9433       int target=(link_addr[i].target-start)>>2;
9434       assert(target>=0&&target<slen);
9435       assert(instr_addr[target]);
9436       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9437       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9438       //#else
9439       set_jump_target(link_addr[i].addr, instr_addr[target]);
9440       //#endif
9441     }
9442   }
9443
9444   u_int source_len = slen*4;
9445   if (dops[slen-1].itype == INTCALL && source_len > 4)
9446     // no need to treat the last instruction as compiled
9447     // as interpreter fully handles it
9448     source_len -= 4;
9449
9450   if ((u_char *)copy + source_len > (u_char *)shadow + sizeof(shadow))
9451     copy = shadow;
9452
9453   // External Branch Targets (jump_in)
9454   for(i=0;i<slen;i++)
9455   {
9456     if(dops[i].bt||i==0)
9457     {
9458       if(instr_addr[i]) // TODO - delay slots (=null)
9459       {
9460         u_int vaddr=start+i*4;
9461         u_int page=get_page(vaddr);
9462         u_int vpage=get_vpage(vaddr);
9463         literal_pool(256);
9464         {
9465           assem_debug("%p (%d) <- %8x\n",instr_addr[i],i,start+i*4);
9466           assem_debug("jump_in: %x\n",start+i*4);
9467           ll_add(jump_dirty+vpage,vaddr,out);
9468           void *entry_point = do_dirty_stub(i, source_len);
9469           ll_add_flags(jump_in+page,vaddr,state_rflags,entry_point);
9470           // If there was an existing entry in the hash table,
9471           // replace it with the new address.
9472           // Don't add new entries.  We'll insert the
9473           // ones that actually get used in check_addr().
9474           struct ht_entry *ht_bin = hash_table_get(vaddr);
9475           if (ht_bin->vaddr[0] == vaddr)
9476             ht_bin->tcaddr[0] = entry_point;
9477           if (ht_bin->vaddr[1] == vaddr)
9478             ht_bin->tcaddr[1] = entry_point;
9479         }
9480       }
9481     }
9482   }
9483   // Write out the literal pool if necessary
9484   literal_pool(0);
9485   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9486   // Align code
9487   if(((u_int)out)&7) emit_addnop(13);
9488   #endif
9489   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9490   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9491   memcpy(copy, source, source_len);
9492   copy += source_len;
9493
9494   end_block(beginning);
9495
9496   // If we're within 256K of the end of the buffer,
9497   // start over from the beginning. (Is 256K enough?)
9498   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9499     out = ndrc->translation_cache;
9500
9501   // Trap writes to any of the pages we compiled
9502   for(i=start>>12;i<=(start+slen*4)>>12;i++) {
9503     invalid_code[i]=0;
9504   }
9505   inv_code_start=inv_code_end=~0;
9506
9507   // for PCSX we need to mark all mirrors too
9508   if(get_page(start)<(RAM_SIZE>>12))
9509     for(i=start>>12;i<=(start+slen*4)>>12;i++)
9510       invalid_code[((u_int)0x00000000>>12)|(i&0x1ff)]=
9511       invalid_code[((u_int)0x80000000>>12)|(i&0x1ff)]=
9512       invalid_code[((u_int)0xa0000000>>12)|(i&0x1ff)]=0;
9513
9514   /* Pass 10 - Free memory by expiring oldest blocks */
9515
9516   int end=(((out-ndrc->translation_cache)>>(TARGET_SIZE_2-16))+16384)&65535;
9517   while(expirep!=end)
9518   {
9519     int shift=TARGET_SIZE_2-3; // Divide into 8 blocks
9520     uintptr_t base_offs = ((uintptr_t)(expirep >> 13) << shift); // Base offset of this block
9521     uintptr_t base_offs_s = base_offs >> shift;
9522     inv_debug("EXP: Phase %d\n",expirep);
9523     switch((expirep>>11)&3)
9524     {
9525       case 0:
9526         // Clear jump_in and jump_dirty
9527         ll_remove_matching_addrs(jump_in+(expirep&2047),base_offs_s,shift);
9528         ll_remove_matching_addrs(jump_dirty+(expirep&2047),base_offs_s,shift);
9529         ll_remove_matching_addrs(jump_in+2048+(expirep&2047),base_offs_s,shift);
9530         ll_remove_matching_addrs(jump_dirty+2048+(expirep&2047),base_offs_s,shift);
9531         break;
9532       case 1:
9533         // Clear pointers
9534         ll_kill_pointers(jump_out[expirep&2047],base_offs_s,shift);
9535         ll_kill_pointers(jump_out[(expirep&2047)+2048],base_offs_s,shift);
9536         break;
9537       case 2:
9538         // Clear hash table
9539         for(i=0;i<32;i++) {
9540           struct ht_entry *ht_bin = &hash_table[((expirep&2047)<<5)+i];
9541           uintptr_t o1 = (u_char *)ht_bin->tcaddr[1] - ndrc->translation_cache;
9542           uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
9543           if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s) {
9544             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[1],ht_bin->tcaddr[1]);
9545             ht_bin->vaddr[1] = -1;
9546             ht_bin->tcaddr[1] = NULL;
9547           }
9548           o1 = (u_char *)ht_bin->tcaddr[0] - ndrc->translation_cache;
9549           o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
9550           if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s) {
9551             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[0],ht_bin->tcaddr[0]);
9552             ht_bin->vaddr[0] = ht_bin->vaddr[1];
9553             ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
9554             ht_bin->vaddr[1] = -1;
9555             ht_bin->tcaddr[1] = NULL;
9556           }
9557         }
9558         break;
9559       case 3:
9560         // Clear jump_out
9561         if((expirep&2047)==0)
9562           do_clear_cache();
9563         ll_remove_matching_addrs(jump_out+(expirep&2047),base_offs_s,shift);
9564         ll_remove_matching_addrs(jump_out+2048+(expirep&2047),base_offs_s,shift);
9565         break;
9566     }
9567     expirep=(expirep+1)&65535;
9568   }
9569 #ifdef ASSEM_PRINT
9570   fflush(stdout);
9571 #endif
9572   return 0;
9573 }
9574
9575 // vim:shiftwidth=2:expandtab