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