72f18bff13dc018a283f694046cc93587b50054c
[pcsx_rearmed.git] / libpcsxcore / new_dynarec / new_dynarec.c
1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  *   Mupen64plus - new_dynarec.c                                           *
3  *   Copyright (C) 2009-2011 Ari64                                         *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
19  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
20
21 #include <stdlib.h>
22 #include <stdint.h> //include for uint64_t
23 #include <assert.h>
24 #include <errno.h>
25 #include <sys/mman.h>
26 #ifdef __MACH__
27 #include <libkern/OSCacheControl.h>
28 #endif
29 #ifdef _3DS
30 #include <3ds_utils.h>
31 #endif
32 #ifdef VITA
33 #include <psp2/kernel/sysmem.h>
34 static int sceBlock;
35 #endif
36
37 #include "new_dynarec_config.h"
38 #include "../psxhle.h"
39 #include "../psxinterpreter.h"
40 #include "../gte.h"
41 #include "emu_if.h" // emulator interface
42
43 #define noinline __attribute__((noinline,noclone))
44 #ifndef ARRAY_SIZE
45 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
46 #endif
47 #ifndef min
48 #define min(a, b) ((b) < (a) ? (b) : (a))
49 #endif
50 #ifndef max
51 #define max(a, b) ((b) > (a) ? (b) : (a))
52 #endif
53
54 //#define DISASM
55 //#define ASSEM_PRINT
56
57 #ifdef ASSEM_PRINT
58 #define assem_debug printf
59 #else
60 #define assem_debug(...)
61 #endif
62 //#define inv_debug printf
63 #define inv_debug(...)
64
65 #ifdef __i386__
66 #include "assem_x86.h"
67 #endif
68 #ifdef __x86_64__
69 #include "assem_x64.h"
70 #endif
71 #ifdef __arm__
72 #include "assem_arm.h"
73 #endif
74 #ifdef __aarch64__
75 #include "assem_arm64.h"
76 #endif
77
78 #define RAM_SIZE 0x200000
79 #define MAXBLOCK 4096
80 #define MAX_OUTPUT_BLOCK_SIZE 262144
81
82 struct ndrc_mem
83 {
84   u_char translation_cache[1 << TARGET_SIZE_2];
85   struct
86   {
87     struct tramp_insns ops[2048 / sizeof(struct tramp_insns)];
88     const void *f[2048 / sizeof(void *)];
89   } tramp;
90 };
91
92 #ifdef BASE_ADDR_DYNAMIC
93 static struct ndrc_mem *ndrc;
94 #else
95 static struct ndrc_mem ndrc_ __attribute__((aligned(4096)));
96 static struct ndrc_mem *ndrc = &ndrc_;
97 #endif
98
99 // stubs
100 enum stub_type {
101   CC_STUB = 1,
102   FP_STUB = 2,
103   LOADB_STUB = 3,
104   LOADH_STUB = 4,
105   LOADW_STUB = 5,
106   LOADD_STUB = 6,
107   LOADBU_STUB = 7,
108   LOADHU_STUB = 8,
109   STOREB_STUB = 9,
110   STOREH_STUB = 10,
111   STOREW_STUB = 11,
112   STORED_STUB = 12,
113   STORELR_STUB = 13,
114   INVCODE_STUB = 14,
115 };
116
117 struct regstat
118 {
119   signed char regmap_entry[HOST_REGS];
120   signed char regmap[HOST_REGS];
121   uint64_t wasdirty;
122   uint64_t dirty;
123   uint64_t u;
124   u_int wasconst;
125   u_int isconst;
126   u_int loadedconst;             // host regs that have constants loaded
127   u_int waswritten;              // MIPS regs that were used as store base before
128 };
129
130 // note: asm depends on this layout
131 struct ll_entry
132 {
133   u_int vaddr;
134   u_int reg_sv_flags;
135   void *addr;
136   struct ll_entry *next;
137 };
138
139 struct ht_entry
140 {
141   u_int vaddr[2];
142   void *tcaddr[2];
143 };
144
145 struct code_stub
146 {
147   enum stub_type type;
148   void *addr;
149   void *retaddr;
150   u_int a;
151   uintptr_t b;
152   uintptr_t c;
153   u_int d;
154   u_int e;
155 };
156
157 struct link_entry
158 {
159   void *addr;
160   u_int target;
161   u_int ext;
162 };
163
164 static struct decoded_insn
165 {
166   u_char itype;
167   u_char opcode;
168   u_char opcode2;
169   u_char rs1;
170   u_char rs2;
171   u_char rt1;
172   u_char rt2;
173   u_char lt1;
174   u_char bt:1;
175   u_char likely:1;
176   u_char ooo:1;
177   u_char is_ds:1;
178 } dops[MAXBLOCK];
179
180   // used by asm:
181   u_char *out;
182   struct ht_entry hash_table[65536]  __attribute__((aligned(16)));
183   struct ll_entry *jump_in[4096] __attribute__((aligned(16)));
184   struct ll_entry *jump_dirty[4096];
185
186   static struct ll_entry *jump_out[4096];
187   static u_int start;
188   static u_int *source;
189   static char insn[MAXBLOCK][10];
190   static uint64_t gte_rs[MAXBLOCK]; // gte: 32 data and 32 ctl regs
191   static uint64_t gte_rt[MAXBLOCK];
192   static uint64_t gte_unneeded[MAXBLOCK];
193   static u_int smrv[32]; // speculated MIPS register values
194   static u_int smrv_strong; // mask or regs that are likely to have correct values
195   static u_int smrv_weak; // same, but somewhat less likely
196   static u_int smrv_strong_next; // same, but after current insn executes
197   static u_int smrv_weak_next;
198   static int imm[MAXBLOCK];
199   static u_int ba[MAXBLOCK];
200   static uint64_t unneeded_reg[MAXBLOCK];
201   static uint64_t branch_unneeded_reg[MAXBLOCK];
202   static signed char regmap_pre[MAXBLOCK][HOST_REGS]; // pre-instruction i?
203   // contains 'real' consts at [i] insn, but may differ from what's actually
204   // loaded in host reg as 'final' value is always loaded, see get_final_value()
205   static uint32_t current_constmap[HOST_REGS];
206   static uint32_t constmap[MAXBLOCK][HOST_REGS];
207   static struct regstat regs[MAXBLOCK];
208   static struct regstat branch_regs[MAXBLOCK];
209   static signed char minimum_free_regs[MAXBLOCK];
210   static u_int needed_reg[MAXBLOCK];
211   static u_int wont_dirty[MAXBLOCK];
212   static u_int will_dirty[MAXBLOCK];
213   static int ccadj[MAXBLOCK];
214   static int slen;
215   static void *instr_addr[MAXBLOCK];
216   static struct link_entry link_addr[MAXBLOCK];
217   static int linkcount;
218   static struct code_stub stubs[MAXBLOCK*3];
219   static int stubcount;
220   static u_int literals[1024][2];
221   static int literalcount;
222   static int is_delayslot;
223   static char shadow[1048576]  __attribute__((aligned(16)));
224   static void *copy;
225   static int expirep;
226   static u_int stop_after_jal;
227 #ifndef RAM_FIXED
228   static uintptr_t ram_offset;
229 #else
230   static const uintptr_t ram_offset=0;
231 #endif
232
233   int new_dynarec_hacks;
234   int new_dynarec_hacks_pergame;
235   int new_dynarec_hacks_old;
236   int new_dynarec_did_compile;
237
238   #define HACK_ENABLED(x) ((new_dynarec_hacks | new_dynarec_hacks_pergame) & (x))
239
240   extern int cycle_count; // ... until end of the timeslice, counts -N -> 0
241   extern int last_count;  // last absolute target, often = next_interupt
242   extern int pcaddr;
243   extern int pending_exception;
244   extern int branch_target;
245   extern uintptr_t mini_ht[32][2];
246   extern u_char restore_candidate[512];
247
248   /* registers that may be allocated */
249   /* 1-31 gpr */
250 #define LOREG 32 // lo
251 #define HIREG 33 // hi
252 //#define FSREG 34 // FPU status (FCSR)
253 #define CSREG 35 // Coprocessor status
254 #define CCREG 36 // Cycle count
255 #define INVCP 37 // Pointer to invalid_code
256 //#define MMREG 38 // Pointer to memory_map
257 //#define ROREG 39 // ram offset (if rdram!=0x80000000)
258 #define TEMPREG 40
259 #define FTEMP 40 // FPU temporary register
260 #define PTEMP 41 // Prefetch temporary register
261 //#define TLREG 42 // TLB mapping offset
262 #define RHASH 43 // Return address hash
263 #define RHTBL 44 // Return address hash table address
264 #define RTEMP 45 // JR/JALR address register
265 #define MAXREG 45
266 #define AGEN1 46 // Address generation temporary register
267 //#define AGEN2 47 // Address generation temporary register
268 //#define MGEN1 48 // Maptable address generation temporary register
269 //#define MGEN2 49 // Maptable address generation temporary register
270 #define BTREG 50 // Branch target temporary register
271
272   /* instruction types */
273 #define NOP 0     // No operation
274 #define LOAD 1    // Load
275 #define STORE 2   // Store
276 #define LOADLR 3  // Unaligned load
277 #define STORELR 4 // Unaligned store
278 #define MOV 5     // Move
279 #define ALU 6     // Arithmetic/logic
280 #define MULTDIV 7 // Multiply/divide
281 #define SHIFT 8   // Shift by register
282 #define SHIFTIMM 9// Shift by immediate
283 #define IMM16 10  // 16-bit immediate
284 #define RJUMP 11  // Unconditional jump to register
285 #define UJUMP 12  // Unconditional jump
286 #define CJUMP 13  // Conditional branch (BEQ/BNE/BGTZ/BLEZ)
287 #define SJUMP 14  // Conditional branch (regimm format)
288 #define COP0 15   // Coprocessor 0
289 #define COP1 16   // Coprocessor 1
290 #define C1LS 17   // Coprocessor 1 load/store
291 //#define FJUMP 18  // Conditional branch (floating point)
292 //#define FLOAT 19  // Floating point unit
293 //#define FCONV 20  // Convert integer to float
294 //#define FCOMP 21  // Floating point compare (sets FSREG)
295 #define SYSCALL 22// SYSCALL
296 #define OTHER 23  // Other
297 #define SPAN 24   // Branch/delay slot spans 2 pages
298 #define NI 25     // Not implemented
299 #define HLECALL 26// PCSX fake opcodes for HLE
300 #define COP2 27   // Coprocessor 2 move
301 #define C2LS 28   // Coprocessor 2 load/store
302 #define C2OP 29   // Coprocessor 2 operation
303 #define INTCALL 30// Call interpreter to handle rare corner cases
304
305   /* branch codes */
306 #define TAKEN 1
307 #define NOTTAKEN 2
308 #define NULLDS 3
309
310 #define DJT_1 (void *)1l // no function, just a label in assem_debug log
311 #define DJT_2 (void *)2l
312
313 // asm linkage
314 int new_recompile_block(u_int addr);
315 void *get_addr_ht(u_int vaddr);
316 void invalidate_block(u_int block);
317 void invalidate_addr(u_int addr);
318 void remove_hash(int vaddr);
319 void dyna_linker();
320 void dyna_linker_ds();
321 void verify_code();
322 void verify_code_ds();
323 void cc_interrupt();
324 void fp_exception();
325 void fp_exception_ds();
326 void jump_to_new_pc();
327 void call_gteStall();
328 void new_dyna_leave();
329
330 // Needed by assembler
331 static void wb_register(signed char r,signed char regmap[],uint64_t dirty);
332 static void wb_dirtys(signed char i_regmap[],uint64_t i_dirty);
333 static void wb_needed_dirtys(signed char i_regmap[],uint64_t i_dirty,int addr);
334 static void load_all_regs(signed char i_regmap[]);
335 static void load_needed_regs(signed char i_regmap[],signed char next_regmap[]);
336 static void load_regs_entry(int t);
337 static void load_all_consts(signed char regmap[],u_int dirty,int i);
338 static u_int get_host_reglist(const signed char *regmap);
339
340 static int verify_dirty(const u_int *ptr);
341 static int get_final_value(int hr, int i, int *value);
342 static void add_stub(enum stub_type type, void *addr, void *retaddr,
343   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e);
344 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
345   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist);
346 static void add_to_linker(void *addr, u_int target, int ext);
347 static void *emit_fastpath_cmp_jump(int i,int addr,int *addr_reg_override);
348 static void *get_direct_memhandler(void *table, u_int addr,
349   enum stub_type type, uintptr_t *addr_host);
350 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist);
351 static void pass_args(int a0, int a1);
352 static void emit_far_jump(const void *f);
353 static void emit_far_call(const void *f);
354
355 static void mprotect_w_x(void *start, void *end, int is_x)
356 {
357 #ifdef NO_WRITE_EXEC
358   #if defined(VITA)
359   // *Open* enables write on all memory that was
360   // allocated by sceKernelAllocMemBlockForVM()?
361   if (is_x)
362     sceKernelCloseVMDomain();
363   else
364     sceKernelOpenVMDomain();
365   #else
366   u_long mstart = (u_long)start & ~4095ul;
367   u_long mend = (u_long)end;
368   if (mprotect((void *)mstart, mend - mstart,
369                PROT_READ | (is_x ? PROT_EXEC : PROT_WRITE)) != 0)
370     SysPrintf("mprotect(%c) failed: %s\n", is_x ? 'x' : 'w', strerror(errno));
371   #endif
372 #endif
373 }
374
375 static void start_tcache_write(void *start, void *end)
376 {
377   mprotect_w_x(start, end, 0);
378 }
379
380 static void end_tcache_write(void *start, void *end)
381 {
382 #if defined(__arm__) || defined(__aarch64__)
383   size_t len = (char *)end - (char *)start;
384   #if   defined(__BLACKBERRY_QNX__)
385   msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
386   #elif defined(__MACH__)
387   sys_cache_control(kCacheFunctionPrepareForExecution, start, len);
388   #elif defined(VITA)
389   sceKernelSyncVMDomain(sceBlock, start, len);
390   #elif defined(_3DS)
391   ctr_flush_invalidate_cache();
392   #elif defined(__aarch64__)
393   // as of 2021, __clear_cache() is still broken on arm64
394   // so here is a custom one :(
395   clear_cache_arm64(start, end);
396   #else
397   __clear_cache(start, end);
398   #endif
399   (void)len;
400 #endif
401
402   mprotect_w_x(start, end, 1);
403 }
404
405 static void *start_block(void)
406 {
407   u_char *end = out + MAX_OUTPUT_BLOCK_SIZE;
408   if (end > ndrc->translation_cache + sizeof(ndrc->translation_cache))
409     end = ndrc->translation_cache + sizeof(ndrc->translation_cache);
410   start_tcache_write(out, end);
411   return out;
412 }
413
414 static void end_block(void *start)
415 {
416   end_tcache_write(start, out);
417 }
418
419 // also takes care of w^x mappings when patching code
420 static u_int needs_clear_cache[1<<(TARGET_SIZE_2-17)];
421
422 static void mark_clear_cache(void *target)
423 {
424   uintptr_t offset = (u_char *)target - ndrc->translation_cache;
425   u_int mask = 1u << ((offset >> 12) & 31);
426   if (!(needs_clear_cache[offset >> 17] & mask)) {
427     char *start = (char *)((uintptr_t)target & ~4095l);
428     start_tcache_write(start, start + 4095);
429     needs_clear_cache[offset >> 17] |= mask;
430   }
431 }
432
433 // Clearing the cache is rather slow on ARM Linux, so mark the areas
434 // that need to be cleared, and then only clear these areas once.
435 static void do_clear_cache(void)
436 {
437   int i, j;
438   for (i = 0; i < (1<<(TARGET_SIZE_2-17)); i++)
439   {
440     u_int bitmap = needs_clear_cache[i];
441     if (!bitmap)
442       continue;
443     for (j = 0; j < 32; j++)
444     {
445       u_char *start, *end;
446       if (!(bitmap & (1<<j)))
447         continue;
448
449       start = ndrc->translation_cache + i*131072 + j*4096;
450       end = start + 4095;
451       for (j++; j < 32; j++) {
452         if (!(bitmap & (1<<j)))
453           break;
454         end += 4096;
455       }
456       end_tcache_write(start, end);
457     }
458     needs_clear_cache[i] = 0;
459   }
460 }
461
462 //#define DEBUG_CYCLE_COUNT 1
463
464 #define NO_CYCLE_PENALTY_THR 12
465
466 int cycle_multiplier; // 100 for 1.0
467 int cycle_multiplier_override;
468 int cycle_multiplier_old;
469
470 static int CLOCK_ADJUST(int x)
471 {
472   int m = cycle_multiplier_override
473         ? cycle_multiplier_override : cycle_multiplier;
474   int s=(x>>31)|1;
475   return (x * m + s * 50) / 100;
476 }
477
478 // is the op an unconditional jump?
479 static int is_ujump(int i)
480 {
481   return dops[i].itype == UJUMP || dops[i].itype == RJUMP
482     || (source[i] >> 16) == 0x1000; // beq r0, r0, offset // b offset
483 }
484
485 static int is_jump(int i)
486 {
487   return dops[i].itype == RJUMP || dops[i].itype == UJUMP || dops[i].itype == CJUMP || dops[i].itype == SJUMP;
488 }
489
490 static int ds_writes_rjump_rs(int i)
491 {
492   return dops[i].rs1 != 0 && (dops[i].rs1 == dops[i+1].rt1 || dops[i].rs1 == dops[i+1].rt2);
493 }
494
495 static u_int get_page(u_int vaddr)
496 {
497   u_int page=vaddr&~0xe0000000;
498   if (page < 0x1000000)
499     page &= ~0x0e00000; // RAM mirrors
500   page>>=12;
501   if(page>2048) page=2048+(page&2047);
502   return page;
503 }
504
505 // no virtual mem in PCSX
506 static u_int get_vpage(u_int vaddr)
507 {
508   return get_page(vaddr);
509 }
510
511 static struct ht_entry *hash_table_get(u_int vaddr)
512 {
513   return &hash_table[((vaddr>>16)^vaddr)&0xFFFF];
514 }
515
516 static void hash_table_add(struct ht_entry *ht_bin, u_int vaddr, void *tcaddr)
517 {
518   ht_bin->vaddr[1] = ht_bin->vaddr[0];
519   ht_bin->tcaddr[1] = ht_bin->tcaddr[0];
520   ht_bin->vaddr[0] = vaddr;
521   ht_bin->tcaddr[0] = tcaddr;
522 }
523
524 // some messy ari64's code, seems to rely on unsigned 32bit overflow
525 static int doesnt_expire_soon(void *tcaddr)
526 {
527   u_int diff = (u_int)((u_char *)tcaddr - out) << (32-TARGET_SIZE_2);
528   return diff > (u_int)(0x60000000 + (MAX_OUTPUT_BLOCK_SIZE << (32-TARGET_SIZE_2)));
529 }
530
531 // Get address from virtual address
532 // This is called from the recompiled JR/JALR instructions
533 void noinline *get_addr(u_int vaddr)
534 {
535   u_int page=get_page(vaddr);
536   u_int vpage=get_vpage(vaddr);
537   struct ll_entry *head;
538   //printf("TRACE: count=%d next=%d (get_addr %x,page %d)\n",Count,next_interupt,vaddr,page);
539   head=jump_in[page];
540   while(head!=NULL) {
541     if(head->vaddr==vaddr) {
542   //printf("TRACE: count=%d next=%d (get_addr match %x: %p)\n",Count,next_interupt,vaddr,head->addr);
543       hash_table_add(hash_table_get(vaddr), vaddr, head->addr);
544       return head->addr;
545     }
546     head=head->next;
547   }
548   head=jump_dirty[vpage];
549   while(head!=NULL) {
550     if(head->vaddr==vaddr) {
551       //printf("TRACE: count=%d next=%d (get_addr match dirty %x: %p)\n",Count,next_interupt,vaddr,head->addr);
552       // Don't restore blocks which are about to expire from the cache
553       if (doesnt_expire_soon(head->addr))
554       if (verify_dirty(head->addr)) {
555         //printf("restore candidate: %x (%d) d=%d\n",vaddr,page,invalid_code[vaddr>>12]);
556         invalid_code[vaddr>>12]=0;
557         inv_code_start=inv_code_end=~0;
558         if(vpage<2048) {
559           restore_candidate[vpage>>3]|=1<<(vpage&7);
560         }
561         else restore_candidate[page>>3]|=1<<(page&7);
562         struct ht_entry *ht_bin = hash_table_get(vaddr);
563         if (ht_bin->vaddr[0] == vaddr)
564           ht_bin->tcaddr[0] = head->addr; // Replace existing entry
565         else
566           hash_table_add(ht_bin, vaddr, head->addr);
567
568         return head->addr;
569       }
570     }
571     head=head->next;
572   }
573   //printf("TRACE: count=%d next=%d (get_addr no-match %x)\n",Count,next_interupt,vaddr);
574   int r=new_recompile_block(vaddr);
575   if(r==0) return get_addr(vaddr);
576   // Execute in unmapped page, generate pagefault execption
577   Status|=2;
578   Cause=(vaddr<<31)|0x8;
579   EPC=(vaddr&1)?vaddr-5:vaddr;
580   BadVAddr=(vaddr&~1);
581   Context=(Context&0xFF80000F)|((BadVAddr>>9)&0x007FFFF0);
582   EntryHi=BadVAddr&0xFFFFE000;
583   return get_addr_ht(0x80000000);
584 }
585 // Look up address in hash table first
586 void *get_addr_ht(u_int vaddr)
587 {
588   //printf("TRACE: count=%d next=%d (get_addr_ht %x)\n",Count,next_interupt,vaddr);
589   const struct ht_entry *ht_bin = hash_table_get(vaddr);
590   if (ht_bin->vaddr[0] == vaddr) return ht_bin->tcaddr[0];
591   if (ht_bin->vaddr[1] == vaddr) return ht_bin->tcaddr[1];
592   return get_addr(vaddr);
593 }
594
595 void clear_all_regs(signed char regmap[])
596 {
597   int hr;
598   for (hr=0;hr<HOST_REGS;hr++) regmap[hr]=-1;
599 }
600
601 static signed char get_reg(const signed char regmap[],int r)
602 {
603   int hr;
604   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap[hr]==r) return hr;
605   return -1;
606 }
607
608 // Find a register that is available for two consecutive cycles
609 static signed char get_reg2(signed char regmap1[], const signed char regmap2[], int r)
610 {
611   int hr;
612   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap1[hr]==r&&regmap2[hr]==r) return hr;
613   return -1;
614 }
615
616 int count_free_regs(signed char regmap[])
617 {
618   int count=0;
619   int hr;
620   for(hr=0;hr<HOST_REGS;hr++)
621   {
622     if(hr!=EXCLUDE_REG) {
623       if(regmap[hr]<0) count++;
624     }
625   }
626   return count;
627 }
628
629 void dirty_reg(struct regstat *cur,signed char reg)
630 {
631   int hr;
632   if(!reg) return;
633   for (hr=0;hr<HOST_REGS;hr++) {
634     if((cur->regmap[hr]&63)==reg) {
635       cur->dirty|=1<<hr;
636     }
637   }
638 }
639
640 static void set_const(struct regstat *cur, signed char reg, uint32_t value)
641 {
642   int hr;
643   if(!reg) return;
644   for (hr=0;hr<HOST_REGS;hr++) {
645     if(cur->regmap[hr]==reg) {
646       cur->isconst|=1<<hr;
647       current_constmap[hr]=value;
648     }
649   }
650 }
651
652 static void clear_const(struct regstat *cur, signed char reg)
653 {
654   int hr;
655   if(!reg) return;
656   for (hr=0;hr<HOST_REGS;hr++) {
657     if((cur->regmap[hr]&63)==reg) {
658       cur->isconst&=~(1<<hr);
659     }
660   }
661 }
662
663 static int is_const(struct regstat *cur, signed char reg)
664 {
665   int hr;
666   if(reg<0) return 0;
667   if(!reg) return 1;
668   for (hr=0;hr<HOST_REGS;hr++) {
669     if((cur->regmap[hr]&63)==reg) {
670       return (cur->isconst>>hr)&1;
671     }
672   }
673   return 0;
674 }
675
676 static uint32_t get_const(struct regstat *cur, signed char reg)
677 {
678   int hr;
679   if(!reg) return 0;
680   for (hr=0;hr<HOST_REGS;hr++) {
681     if(cur->regmap[hr]==reg) {
682       return current_constmap[hr];
683     }
684   }
685   SysPrintf("Unknown constant in r%d\n",reg);
686   abort();
687 }
688
689 // Least soon needed registers
690 // Look at the next ten instructions and see which registers
691 // will be used.  Try not to reallocate these.
692 void lsn(u_char hsn[], int i, int *preferred_reg)
693 {
694   int j;
695   int b=-1;
696   for(j=0;j<9;j++)
697   {
698     if(i+j>=slen) {
699       j=slen-i-1;
700       break;
701     }
702     if (is_ujump(i+j))
703     {
704       // Don't go past an unconditonal jump
705       j++;
706       break;
707     }
708   }
709   for(;j>=0;j--)
710   {
711     if(dops[i+j].rs1) hsn[dops[i+j].rs1]=j;
712     if(dops[i+j].rs2) hsn[dops[i+j].rs2]=j;
713     if(dops[i+j].rt1) hsn[dops[i+j].rt1]=j;
714     if(dops[i+j].rt2) hsn[dops[i+j].rt2]=j;
715     if(dops[i+j].itype==STORE || dops[i+j].itype==STORELR) {
716       // Stores can allocate zero
717       hsn[dops[i+j].rs1]=j;
718       hsn[dops[i+j].rs2]=j;
719     }
720     // On some architectures stores need invc_ptr
721     #if defined(HOST_IMM8)
722     if(dops[i+j].itype==STORE || dops[i+j].itype==STORELR || (dops[i+j].opcode&0x3b)==0x39 || (dops[i+j].opcode&0x3b)==0x3a) {
723       hsn[INVCP]=j;
724     }
725     #endif
726     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
727     {
728       hsn[CCREG]=j;
729       b=j;
730     }
731   }
732   if(b>=0)
733   {
734     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
735     {
736       // Follow first branch
737       int t=(ba[i+b]-start)>>2;
738       j=7-b;if(t+j>=slen) j=slen-t-1;
739       for(;j>=0;j--)
740       {
741         if(dops[t+j].rs1) if(hsn[dops[t+j].rs1]>j+b+2) hsn[dops[t+j].rs1]=j+b+2;
742         if(dops[t+j].rs2) if(hsn[dops[t+j].rs2]>j+b+2) hsn[dops[t+j].rs2]=j+b+2;
743         //if(dops[t+j].rt1) if(hsn[dops[t+j].rt1]>j+b+2) hsn[dops[t+j].rt1]=j+b+2;
744         //if(dops[t+j].rt2) if(hsn[dops[t+j].rt2]>j+b+2) hsn[dops[t+j].rt2]=j+b+2;
745       }
746     }
747     // TODO: preferred register based on backward branch
748   }
749   // Delay slot should preferably not overwrite branch conditions or cycle count
750   if (i > 0 && is_jump(i-1)) {
751     if(dops[i-1].rs1) if(hsn[dops[i-1].rs1]>1) hsn[dops[i-1].rs1]=1;
752     if(dops[i-1].rs2) if(hsn[dops[i-1].rs2]>1) hsn[dops[i-1].rs2]=1;
753     hsn[CCREG]=1;
754     // ...or hash tables
755     hsn[RHASH]=1;
756     hsn[RHTBL]=1;
757   }
758   // Coprocessor load/store needs FTEMP, even if not declared
759   if(dops[i].itype==C1LS||dops[i].itype==C2LS) {
760     hsn[FTEMP]=0;
761   }
762   // Load L/R also uses FTEMP as a temporary register
763   if(dops[i].itype==LOADLR) {
764     hsn[FTEMP]=0;
765   }
766   // Also SWL/SWR/SDL/SDR
767   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) {
768     hsn[FTEMP]=0;
769   }
770   // Don't remove the miniht registers
771   if(dops[i].itype==UJUMP||dops[i].itype==RJUMP)
772   {
773     hsn[RHASH]=0;
774     hsn[RHTBL]=0;
775   }
776 }
777
778 // We only want to allocate registers if we're going to use them again soon
779 int needed_again(int r, int i)
780 {
781   int j;
782   int b=-1;
783   int rn=10;
784
785   if (i > 0 && is_ujump(i-1))
786   {
787     if(ba[i-1]<start || ba[i-1]>start+slen*4-4)
788       return 0; // Don't need any registers if exiting the block
789   }
790   for(j=0;j<9;j++)
791   {
792     if(i+j>=slen) {
793       j=slen-i-1;
794       break;
795     }
796     if (is_ujump(i+j))
797     {
798       // Don't go past an unconditonal jump
799       j++;
800       break;
801     }
802     if(dops[i+j].itype==SYSCALL||dops[i+j].itype==HLECALL||dops[i+j].itype==INTCALL||((source[i+j]&0xfc00003f)==0x0d))
803     {
804       break;
805     }
806   }
807   for(;j>=1;j--)
808   {
809     if(dops[i+j].rs1==r) rn=j;
810     if(dops[i+j].rs2==r) rn=j;
811     if((unneeded_reg[i+j]>>r)&1) rn=10;
812     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
813     {
814       b=j;
815     }
816   }
817   if(rn<10) return 1;
818   (void)b;
819   return 0;
820 }
821
822 // Try to match register allocations at the end of a loop with those
823 // at the beginning
824 int loop_reg(int i, int r, int hr)
825 {
826   int j,k;
827   for(j=0;j<9;j++)
828   {
829     if(i+j>=slen) {
830       j=slen-i-1;
831       break;
832     }
833     if (is_ujump(i+j))
834     {
835       // Don't go past an unconditonal jump
836       j++;
837       break;
838     }
839   }
840   k=0;
841   if(i>0){
842     if(dops[i-1].itype==UJUMP||dops[i-1].itype==CJUMP||dops[i-1].itype==SJUMP)
843       k--;
844   }
845   for(;k<j;k++)
846   {
847     assert(r < 64);
848     if((unneeded_reg[i+k]>>r)&1) return hr;
849     if(i+k>=0&&(dops[i+k].itype==UJUMP||dops[i+k].itype==CJUMP||dops[i+k].itype==SJUMP))
850     {
851       if(ba[i+k]>=start && ba[i+k]<(start+i*4))
852       {
853         int t=(ba[i+k]-start)>>2;
854         int reg=get_reg(regs[t].regmap_entry,r);
855         if(reg>=0) return reg;
856         //reg=get_reg(regs[t+1].regmap_entry,r);
857         //if(reg>=0) return reg;
858       }
859     }
860   }
861   return hr;
862 }
863
864
865 // Allocate every register, preserving source/target regs
866 void alloc_all(struct regstat *cur,int i)
867 {
868   int hr;
869
870   for(hr=0;hr<HOST_REGS;hr++) {
871     if(hr!=EXCLUDE_REG) {
872       if(((cur->regmap[hr]&63)!=dops[i].rs1)&&((cur->regmap[hr]&63)!=dops[i].rs2)&&
873          ((cur->regmap[hr]&63)!=dops[i].rt1)&&((cur->regmap[hr]&63)!=dops[i].rt2))
874       {
875         cur->regmap[hr]=-1;
876         cur->dirty&=~(1<<hr);
877       }
878       // Don't need zeros
879       if((cur->regmap[hr]&63)==0)
880       {
881         cur->regmap[hr]=-1;
882         cur->dirty&=~(1<<hr);
883       }
884     }
885   }
886 }
887
888 #ifndef NDEBUG
889 static int host_tempreg_in_use;
890
891 static void host_tempreg_acquire(void)
892 {
893   assert(!host_tempreg_in_use);
894   host_tempreg_in_use = 1;
895 }
896
897 static void host_tempreg_release(void)
898 {
899   host_tempreg_in_use = 0;
900 }
901 #else
902 static void host_tempreg_acquire(void) {}
903 static void host_tempreg_release(void) {}
904 #endif
905
906 #ifdef ASSEM_PRINT
907 extern void gen_interupt();
908 extern void do_insn_cmp();
909 #define FUNCNAME(f) { f, " " #f }
910 static const struct {
911   void *addr;
912   const char *name;
913 } function_names[] = {
914   FUNCNAME(cc_interrupt),
915   FUNCNAME(gen_interupt),
916   FUNCNAME(get_addr_ht),
917   FUNCNAME(get_addr),
918   FUNCNAME(jump_handler_read8),
919   FUNCNAME(jump_handler_read16),
920   FUNCNAME(jump_handler_read32),
921   FUNCNAME(jump_handler_write8),
922   FUNCNAME(jump_handler_write16),
923   FUNCNAME(jump_handler_write32),
924   FUNCNAME(invalidate_addr),
925   FUNCNAME(jump_to_new_pc),
926   FUNCNAME(call_gteStall),
927   FUNCNAME(new_dyna_leave),
928   FUNCNAME(pcsx_mtc0),
929   FUNCNAME(pcsx_mtc0_ds),
930 #ifdef DRC_DBG
931   FUNCNAME(do_insn_cmp),
932 #endif
933 #ifdef __arm__
934   FUNCNAME(verify_code),
935 #endif
936 };
937
938 static const char *func_name(const void *a)
939 {
940   int i;
941   for (i = 0; i < sizeof(function_names)/sizeof(function_names[0]); i++)
942     if (function_names[i].addr == a)
943       return function_names[i].name;
944   return "";
945 }
946 #else
947 #define func_name(x) ""
948 #endif
949
950 #ifdef __i386__
951 #include "assem_x86.c"
952 #endif
953 #ifdef __x86_64__
954 #include "assem_x64.c"
955 #endif
956 #ifdef __arm__
957 #include "assem_arm.c"
958 #endif
959 #ifdef __aarch64__
960 #include "assem_arm64.c"
961 #endif
962
963 static void *get_trampoline(const void *f)
964 {
965   size_t i;
966
967   for (i = 0; i < ARRAY_SIZE(ndrc->tramp.f); i++) {
968     if (ndrc->tramp.f[i] == f || ndrc->tramp.f[i] == NULL)
969       break;
970   }
971   if (i == ARRAY_SIZE(ndrc->tramp.f)) {
972     SysPrintf("trampoline table is full, last func %p\n", f);
973     abort();
974   }
975   if (ndrc->tramp.f[i] == NULL) {
976     start_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
977     ndrc->tramp.f[i] = f;
978     end_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
979   }
980   return &ndrc->tramp.ops[i];
981 }
982
983 static void emit_far_jump(const void *f)
984 {
985   if (can_jump_or_call(f)) {
986     emit_jmp(f);
987     return;
988   }
989
990   f = get_trampoline(f);
991   emit_jmp(f);
992 }
993
994 static void emit_far_call(const void *f)
995 {
996   if (can_jump_or_call(f)) {
997     emit_call(f);
998     return;
999   }
1000
1001   f = get_trampoline(f);
1002   emit_call(f);
1003 }
1004
1005 // Add virtual address mapping to linked list
1006 void ll_add(struct ll_entry **head,int vaddr,void *addr)
1007 {
1008   struct ll_entry *new_entry;
1009   new_entry=malloc(sizeof(struct ll_entry));
1010   assert(new_entry!=NULL);
1011   new_entry->vaddr=vaddr;
1012   new_entry->reg_sv_flags=0;
1013   new_entry->addr=addr;
1014   new_entry->next=*head;
1015   *head=new_entry;
1016 }
1017
1018 void ll_add_flags(struct ll_entry **head,int vaddr,u_int reg_sv_flags,void *addr)
1019 {
1020   ll_add(head,vaddr,addr);
1021   (*head)->reg_sv_flags=reg_sv_flags;
1022 }
1023
1024 // Check if an address is already compiled
1025 // but don't return addresses which are about to expire from the cache
1026 void *check_addr(u_int vaddr)
1027 {
1028   struct ht_entry *ht_bin = hash_table_get(vaddr);
1029   size_t i;
1030   for (i = 0; i < ARRAY_SIZE(ht_bin->vaddr); i++) {
1031     if (ht_bin->vaddr[i] == vaddr)
1032       if (doesnt_expire_soon((u_char *)ht_bin->tcaddr[i] - MAX_OUTPUT_BLOCK_SIZE))
1033         if (isclean(ht_bin->tcaddr[i]))
1034           return ht_bin->tcaddr[i];
1035   }
1036   u_int page=get_page(vaddr);
1037   struct ll_entry *head;
1038   head=jump_in[page];
1039   while (head != NULL) {
1040     if (head->vaddr == vaddr) {
1041       if (doesnt_expire_soon(head->addr)) {
1042         // Update existing entry with current address
1043         if (ht_bin->vaddr[0] == vaddr) {
1044           ht_bin->tcaddr[0] = head->addr;
1045           return head->addr;
1046         }
1047         if (ht_bin->vaddr[1] == vaddr) {
1048           ht_bin->tcaddr[1] = head->addr;
1049           return head->addr;
1050         }
1051         // Insert into hash table with low priority.
1052         // Don't evict existing entries, as they are probably
1053         // addresses that are being accessed frequently.
1054         if (ht_bin->vaddr[0] == -1) {
1055           ht_bin->vaddr[0] = vaddr;
1056           ht_bin->tcaddr[0] = head->addr;
1057         }
1058         else if (ht_bin->vaddr[1] == -1) {
1059           ht_bin->vaddr[1] = vaddr;
1060           ht_bin->tcaddr[1] = head->addr;
1061         }
1062         return head->addr;
1063       }
1064     }
1065     head=head->next;
1066   }
1067   return 0;
1068 }
1069
1070 void remove_hash(int vaddr)
1071 {
1072   //printf("remove hash: %x\n",vaddr);
1073   struct ht_entry *ht_bin = hash_table_get(vaddr);
1074   if (ht_bin->vaddr[1] == vaddr) {
1075     ht_bin->vaddr[1] = -1;
1076     ht_bin->tcaddr[1] = NULL;
1077   }
1078   if (ht_bin->vaddr[0] == vaddr) {
1079     ht_bin->vaddr[0] = ht_bin->vaddr[1];
1080     ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
1081     ht_bin->vaddr[1] = -1;
1082     ht_bin->tcaddr[1] = NULL;
1083   }
1084 }
1085
1086 static void ll_remove_matching_addrs(struct ll_entry **head,
1087   uintptr_t base_offs_s, int shift)
1088 {
1089   struct ll_entry *next;
1090   while(*head) {
1091     uintptr_t o1 = (u_char *)(*head)->addr - ndrc->translation_cache;
1092     uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
1093     if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s)
1094     {
1095       inv_debug("EXP: Remove pointer to %p (%x)\n",(*head)->addr,(*head)->vaddr);
1096       remove_hash((*head)->vaddr);
1097       next=(*head)->next;
1098       free(*head);
1099       *head=next;
1100     }
1101     else
1102     {
1103       head=&((*head)->next);
1104     }
1105   }
1106 }
1107
1108 // Remove all entries from linked list
1109 void ll_clear(struct ll_entry **head)
1110 {
1111   struct ll_entry *cur;
1112   struct ll_entry *next;
1113   if((cur=*head)) {
1114     *head=0;
1115     while(cur) {
1116       next=cur->next;
1117       free(cur);
1118       cur=next;
1119     }
1120   }
1121 }
1122
1123 // Dereference the pointers and remove if it matches
1124 static void ll_kill_pointers(struct ll_entry *head,
1125   uintptr_t base_offs_s, int shift)
1126 {
1127   while(head) {
1128     u_char *ptr = get_pointer(head->addr);
1129     uintptr_t o1 = ptr - ndrc->translation_cache;
1130     uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
1131     inv_debug("EXP: Lookup pointer to %p at %p (%x)\n",ptr,head->addr,head->vaddr);
1132     if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s)
1133     {
1134       inv_debug("EXP: Kill pointer at %p (%x)\n",head->addr,head->vaddr);
1135       void *host_addr=find_extjump_insn(head->addr);
1136       mark_clear_cache(host_addr);
1137       set_jump_target(host_addr, head->addr);
1138     }
1139     head=head->next;
1140   }
1141 }
1142
1143 // This is called when we write to a compiled block (see do_invstub)
1144 static void invalidate_page(u_int page)
1145 {
1146   struct ll_entry *head;
1147   struct ll_entry *next;
1148   head=jump_in[page];
1149   jump_in[page]=0;
1150   while(head!=NULL) {
1151     inv_debug("INVALIDATE: %x\n",head->vaddr);
1152     remove_hash(head->vaddr);
1153     next=head->next;
1154     free(head);
1155     head=next;
1156   }
1157   head=jump_out[page];
1158   jump_out[page]=0;
1159   while(head!=NULL) {
1160     inv_debug("INVALIDATE: kill pointer to %x (%p)\n",head->vaddr,head->addr);
1161     void *host_addr=find_extjump_insn(head->addr);
1162     mark_clear_cache(host_addr);
1163     set_jump_target(host_addr, head->addr); // point back to dyna_linker
1164     next=head->next;
1165     free(head);
1166     head=next;
1167   }
1168 }
1169
1170 static void invalidate_block_range(u_int block, u_int first, u_int last)
1171 {
1172   u_int page=get_page(block<<12);
1173   //printf("first=%d last=%d\n",first,last);
1174   invalidate_page(page);
1175   assert(first+5>page); // NB: this assumes MAXBLOCK<=4096 (4 pages)
1176   assert(last<page+5);
1177   // Invalidate the adjacent pages if a block crosses a 4K boundary
1178   while(first<page) {
1179     invalidate_page(first);
1180     first++;
1181   }
1182   for(first=page+1;first<last;first++) {
1183     invalidate_page(first);
1184   }
1185   do_clear_cache();
1186
1187   // Don't trap writes
1188   invalid_code[block]=1;
1189
1190   #ifdef USE_MINI_HT
1191   memset(mini_ht,-1,sizeof(mini_ht));
1192   #endif
1193 }
1194
1195 void invalidate_block(u_int block)
1196 {
1197   u_int page=get_page(block<<12);
1198   u_int vpage=get_vpage(block<<12);
1199   inv_debug("INVALIDATE: %x (%d)\n",block<<12,page);
1200   //inv_debug("invalid_code[block]=%d\n",invalid_code[block]);
1201   u_int first,last;
1202   first=last=page;
1203   struct ll_entry *head;
1204   head=jump_dirty[vpage];
1205   //printf("page=%d vpage=%d\n",page,vpage);
1206   while(head!=NULL) {
1207     if(vpage>2047||(head->vaddr>>12)==block) { // Ignore vaddr hash collision
1208       u_char *start, *end;
1209       get_bounds(head->addr, &start, &end);
1210       //printf("start: %p end: %p\n", start, end);
1211       if (page < 2048 && start >= rdram && end < rdram+RAM_SIZE) {
1212         if (((start-rdram)>>12) <= page && ((end-1-rdram)>>12) >= page) {
1213           if ((((start-rdram)>>12)&2047) < first) first = ((start-rdram)>>12)&2047;
1214           if ((((end-1-rdram)>>12)&2047) > last)  last = ((end-1-rdram)>>12)&2047;
1215         }
1216       }
1217     }
1218     head=head->next;
1219   }
1220   invalidate_block_range(block,first,last);
1221 }
1222
1223 void invalidate_addr(u_int addr)
1224 {
1225   //static int rhits;
1226   // this check is done by the caller
1227   //if (inv_code_start<=addr&&addr<=inv_code_end) { rhits++; return; }
1228   u_int page=get_vpage(addr);
1229   if(page<2048) { // RAM
1230     struct ll_entry *head;
1231     u_int addr_min=~0, addr_max=0;
1232     u_int mask=RAM_SIZE-1;
1233     u_int addr_main=0x80000000|(addr&mask);
1234     int pg1;
1235     inv_code_start=addr_main&~0xfff;
1236     inv_code_end=addr_main|0xfff;
1237     pg1=page;
1238     if (pg1>0) {
1239       // must check previous page too because of spans..
1240       pg1--;
1241       inv_code_start-=0x1000;
1242     }
1243     for(;pg1<=page;pg1++) {
1244       for(head=jump_dirty[pg1];head!=NULL;head=head->next) {
1245         u_char *start_h, *end_h;
1246         u_int start, end;
1247         get_bounds(head->addr, &start_h, &end_h);
1248         start = (uintptr_t)start_h - ram_offset;
1249         end = (uintptr_t)end_h - ram_offset;
1250         if(start<=addr_main&&addr_main<end) {
1251           if(start<addr_min) addr_min=start;
1252           if(end>addr_max) addr_max=end;
1253         }
1254         else if(addr_main<start) {
1255           if(start<inv_code_end)
1256             inv_code_end=start-1;
1257         }
1258         else {
1259           if(end>inv_code_start)
1260             inv_code_start=end;
1261         }
1262       }
1263     }
1264     if (addr_min!=~0) {
1265       inv_debug("INV ADDR: %08x hit %08x-%08x\n", addr, addr_min, addr_max);
1266       inv_code_start=inv_code_end=~0;
1267       invalidate_block_range(addr>>12,(addr_min&mask)>>12,(addr_max&mask)>>12);
1268       return;
1269     }
1270     else {
1271       inv_code_start=(addr&~mask)|(inv_code_start&mask);
1272       inv_code_end=(addr&~mask)|(inv_code_end&mask);
1273       inv_debug("INV ADDR: %08x miss, inv %08x-%08x, sk %d\n", addr, inv_code_start, inv_code_end, 0);
1274       return;
1275     }
1276   }
1277   invalidate_block(addr>>12);
1278 }
1279
1280 // This is called when loading a save state.
1281 // Anything could have changed, so invalidate everything.
1282 void invalidate_all_pages(void)
1283 {
1284   u_int page;
1285   for(page=0;page<4096;page++)
1286     invalidate_page(page);
1287   for(page=0;page<1048576;page++)
1288     if(!invalid_code[page]) {
1289       restore_candidate[(page&2047)>>3]|=1<<(page&7);
1290       restore_candidate[((page&2047)>>3)+256]|=1<<(page&7);
1291     }
1292   #ifdef USE_MINI_HT
1293   memset(mini_ht,-1,sizeof(mini_ht));
1294   #endif
1295   do_clear_cache();
1296 }
1297
1298 static void do_invstub(int n)
1299 {
1300   literal_pool(20);
1301   u_int reglist=stubs[n].a;
1302   set_jump_target(stubs[n].addr, out);
1303   save_regs(reglist);
1304   if(stubs[n].b!=0) emit_mov(stubs[n].b,0);
1305   emit_far_call(invalidate_addr);
1306   restore_regs(reglist);
1307   emit_jmp(stubs[n].retaddr); // return address
1308 }
1309
1310 // Add an entry to jump_out after making a link
1311 // src should point to code by emit_extjump2()
1312 void add_jump_out(u_int vaddr,void *src)
1313 {
1314   u_int page=get_page(vaddr);
1315   inv_debug("add_jump_out: %p -> %x (%d)\n",src,vaddr,page);
1316   check_extjump2(src);
1317   ll_add(jump_out+page,vaddr,src);
1318   //inv_debug("add_jump_out:  to %p\n",get_pointer(src));
1319 }
1320
1321 // If a code block was found to be unmodified (bit was set in
1322 // restore_candidate) and it remains unmodified (bit is clear
1323 // in invalid_code) then move the entries for that 4K page from
1324 // the dirty list to the clean list.
1325 void clean_blocks(u_int page)
1326 {
1327   struct ll_entry *head;
1328   inv_debug("INV: clean_blocks page=%d\n",page);
1329   head=jump_dirty[page];
1330   while(head!=NULL) {
1331     if(!invalid_code[head->vaddr>>12]) {
1332       // Don't restore blocks which are about to expire from the cache
1333       if (doesnt_expire_soon(head->addr)) {
1334         if(verify_dirty(head->addr)) {
1335           u_char *start, *end;
1336           //printf("Possibly Restore %x (%p)\n",head->vaddr, head->addr);
1337           u_int i;
1338           u_int inv=0;
1339           get_bounds(head->addr, &start, &end);
1340           if (start - rdram < RAM_SIZE) {
1341             for (i = (start-rdram+0x80000000)>>12; i <= (end-1-rdram+0x80000000)>>12; i++) {
1342               inv|=invalid_code[i];
1343             }
1344           }
1345           else if((signed int)head->vaddr>=(signed int)0x80000000+RAM_SIZE) {
1346             inv=1;
1347           }
1348           if(!inv) {
1349             void *clean_addr = get_clean_addr(head->addr);
1350             if (doesnt_expire_soon(clean_addr)) {
1351               u_int ppage=page;
1352               inv_debug("INV: Restored %x (%p/%p)\n",head->vaddr, head->addr, clean_addr);
1353               //printf("page=%x, addr=%x\n",page,head->vaddr);
1354               //assert(head->vaddr>>12==(page|0x80000));
1355               ll_add_flags(jump_in+ppage,head->vaddr,head->reg_sv_flags,clean_addr);
1356               struct ht_entry *ht_bin = hash_table_get(head->vaddr);
1357               if (ht_bin->vaddr[0] == head->vaddr)
1358                 ht_bin->tcaddr[0] = clean_addr; // Replace existing entry
1359               if (ht_bin->vaddr[1] == head->vaddr)
1360                 ht_bin->tcaddr[1] = clean_addr; // Replace existing entry
1361             }
1362           }
1363         }
1364       }
1365     }
1366     head=head->next;
1367   }
1368 }
1369
1370 /* Register allocation */
1371
1372 // Note: registers are allocated clean (unmodified state)
1373 // if you intend to modify the register, you must call dirty_reg().
1374 static void alloc_reg(struct regstat *cur,int i,signed char reg)
1375 {
1376   int r,hr;
1377   int preferred_reg = (reg&7);
1378   if(reg==CCREG) preferred_reg=HOST_CCREG;
1379   if(reg==PTEMP||reg==FTEMP) preferred_reg=12;
1380
1381   // Don't allocate unused registers
1382   if((cur->u>>reg)&1) return;
1383
1384   // see if it's already allocated
1385   for(hr=0;hr<HOST_REGS;hr++)
1386   {
1387     if(cur->regmap[hr]==reg) return;
1388   }
1389
1390   // Keep the same mapping if the register was already allocated in a loop
1391   preferred_reg = loop_reg(i,reg,preferred_reg);
1392
1393   // Try to allocate the preferred register
1394   if(cur->regmap[preferred_reg]==-1) {
1395     cur->regmap[preferred_reg]=reg;
1396     cur->dirty&=~(1<<preferred_reg);
1397     cur->isconst&=~(1<<preferred_reg);
1398     return;
1399   }
1400   r=cur->regmap[preferred_reg];
1401   assert(r < 64);
1402   if((cur->u>>r)&1) {
1403     cur->regmap[preferred_reg]=reg;
1404     cur->dirty&=~(1<<preferred_reg);
1405     cur->isconst&=~(1<<preferred_reg);
1406     return;
1407   }
1408
1409   // Clear any unneeded registers
1410   // We try to keep the mapping consistent, if possible, because it
1411   // makes branches easier (especially loops).  So we try to allocate
1412   // first (see above) before removing old mappings.  If this is not
1413   // possible then go ahead and clear out the registers that are no
1414   // longer needed.
1415   for(hr=0;hr<HOST_REGS;hr++)
1416   {
1417     r=cur->regmap[hr];
1418     if(r>=0) {
1419       assert(r < 64);
1420       if((cur->u>>r)&1) {cur->regmap[hr]=-1;break;}
1421     }
1422   }
1423   // Try to allocate any available register, but prefer
1424   // registers that have not been used recently.
1425   if(i>0) {
1426     for(hr=0;hr<HOST_REGS;hr++) {
1427       if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1428         if(regs[i-1].regmap[hr]!=dops[i-1].rs1&&regs[i-1].regmap[hr]!=dops[i-1].rs2&&regs[i-1].regmap[hr]!=dops[i-1].rt1&&regs[i-1].regmap[hr]!=dops[i-1].rt2) {
1429           cur->regmap[hr]=reg;
1430           cur->dirty&=~(1<<hr);
1431           cur->isconst&=~(1<<hr);
1432           return;
1433         }
1434       }
1435     }
1436   }
1437   // Try to allocate any available register
1438   for(hr=0;hr<HOST_REGS;hr++) {
1439     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1440       cur->regmap[hr]=reg;
1441       cur->dirty&=~(1<<hr);
1442       cur->isconst&=~(1<<hr);
1443       return;
1444     }
1445   }
1446
1447   // Ok, now we have to evict someone
1448   // Pick a register we hopefully won't need soon
1449   u_char hsn[MAXREG+1];
1450   memset(hsn,10,sizeof(hsn));
1451   int j;
1452   lsn(hsn,i,&preferred_reg);
1453   //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]);
1454   //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]);
1455   if(i>0) {
1456     // Don't evict the cycle count at entry points, otherwise the entry
1457     // stub will have to write it.
1458     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1459     if(i>1&&hsn[CCREG]>2&&(dops[i-2].itype==RJUMP||dops[i-2].itype==UJUMP||dops[i-2].itype==CJUMP||dops[i-2].itype==SJUMP)) hsn[CCREG]=2;
1460     for(j=10;j>=3;j--)
1461     {
1462       // Alloc preferred register if available
1463       if(hsn[r=cur->regmap[preferred_reg]&63]==j) {
1464         for(hr=0;hr<HOST_REGS;hr++) {
1465           // Evict both parts of a 64-bit register
1466           if((cur->regmap[hr]&63)==r) {
1467             cur->regmap[hr]=-1;
1468             cur->dirty&=~(1<<hr);
1469             cur->isconst&=~(1<<hr);
1470           }
1471         }
1472         cur->regmap[preferred_reg]=reg;
1473         return;
1474       }
1475       for(r=1;r<=MAXREG;r++)
1476       {
1477         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1478           for(hr=0;hr<HOST_REGS;hr++) {
1479             if(hr!=HOST_CCREG||j<hsn[CCREG]) {
1480               if(cur->regmap[hr]==r) {
1481                 cur->regmap[hr]=reg;
1482                 cur->dirty&=~(1<<hr);
1483                 cur->isconst&=~(1<<hr);
1484                 return;
1485               }
1486             }
1487           }
1488         }
1489       }
1490     }
1491   }
1492   for(j=10;j>=0;j--)
1493   {
1494     for(r=1;r<=MAXREG;r++)
1495     {
1496       if(hsn[r]==j) {
1497         for(hr=0;hr<HOST_REGS;hr++) {
1498           if(cur->regmap[hr]==r) {
1499             cur->regmap[hr]=reg;
1500             cur->dirty&=~(1<<hr);
1501             cur->isconst&=~(1<<hr);
1502             return;
1503           }
1504         }
1505       }
1506     }
1507   }
1508   SysPrintf("This shouldn't happen (alloc_reg)");abort();
1509 }
1510
1511 // Allocate a temporary register.  This is done without regard to
1512 // dirty status or whether the register we request is on the unneeded list
1513 // Note: This will only allocate one register, even if called multiple times
1514 static void alloc_reg_temp(struct regstat *cur,int i,signed char reg)
1515 {
1516   int r,hr;
1517   int preferred_reg = -1;
1518
1519   // see if it's already allocated
1520   for(hr=0;hr<HOST_REGS;hr++)
1521   {
1522     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==reg) return;
1523   }
1524
1525   // Try to allocate any available register
1526   for(hr=HOST_REGS-1;hr>=0;hr--) {
1527     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1528       cur->regmap[hr]=reg;
1529       cur->dirty&=~(1<<hr);
1530       cur->isconst&=~(1<<hr);
1531       return;
1532     }
1533   }
1534
1535   // Find an unneeded register
1536   for(hr=HOST_REGS-1;hr>=0;hr--)
1537   {
1538     r=cur->regmap[hr];
1539     if(r>=0) {
1540       assert(r < 64);
1541       if((cur->u>>r)&1) {
1542         if(i==0||((unneeded_reg[i-1]>>r)&1)) {
1543           cur->regmap[hr]=reg;
1544           cur->dirty&=~(1<<hr);
1545           cur->isconst&=~(1<<hr);
1546           return;
1547         }
1548       }
1549     }
1550   }
1551
1552   // Ok, now we have to evict someone
1553   // Pick a register we hopefully won't need soon
1554   // TODO: we might want to follow unconditional jumps here
1555   // TODO: get rid of dupe code and make this into a function
1556   u_char hsn[MAXREG+1];
1557   memset(hsn,10,sizeof(hsn));
1558   int j;
1559   lsn(hsn,i,&preferred_reg);
1560   //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]);
1561   if(i>0) {
1562     // Don't evict the cycle count at entry points, otherwise the entry
1563     // stub will have to write it.
1564     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1565     if(i>1&&hsn[CCREG]>2&&(dops[i-2].itype==RJUMP||dops[i-2].itype==UJUMP||dops[i-2].itype==CJUMP||dops[i-2].itype==SJUMP)) hsn[CCREG]=2;
1566     for(j=10;j>=3;j--)
1567     {
1568       for(r=1;r<=MAXREG;r++)
1569       {
1570         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1571           for(hr=0;hr<HOST_REGS;hr++) {
1572             if(hr!=HOST_CCREG||hsn[CCREG]>2) {
1573               if(cur->regmap[hr]==r) {
1574                 cur->regmap[hr]=reg;
1575                 cur->dirty&=~(1<<hr);
1576                 cur->isconst&=~(1<<hr);
1577                 return;
1578               }
1579             }
1580           }
1581         }
1582       }
1583     }
1584   }
1585   for(j=10;j>=0;j--)
1586   {
1587     for(r=1;r<=MAXREG;r++)
1588     {
1589       if(hsn[r]==j) {
1590         for(hr=0;hr<HOST_REGS;hr++) {
1591           if(cur->regmap[hr]==r) {
1592             cur->regmap[hr]=reg;
1593             cur->dirty&=~(1<<hr);
1594             cur->isconst&=~(1<<hr);
1595             return;
1596           }
1597         }
1598       }
1599     }
1600   }
1601   SysPrintf("This shouldn't happen");abort();
1602 }
1603
1604 static void mov_alloc(struct regstat *current,int i)
1605 {
1606   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) {
1607     // logically this is needed but just won't work, no idea why
1608     //alloc_cc(current,i); // for stalls
1609     //dirty_reg(current,CCREG);
1610   }
1611
1612   // Note: Don't need to actually alloc the source registers
1613   //alloc_reg(current,i,dops[i].rs1);
1614   alloc_reg(current,i,dops[i].rt1);
1615
1616   clear_const(current,dops[i].rs1);
1617   clear_const(current,dops[i].rt1);
1618   dirty_reg(current,dops[i].rt1);
1619 }
1620
1621 static void shiftimm_alloc(struct regstat *current,int i)
1622 {
1623   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
1624   {
1625     if(dops[i].rt1) {
1626       if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1627       else dops[i].lt1=dops[i].rs1;
1628       alloc_reg(current,i,dops[i].rt1);
1629       dirty_reg(current,dops[i].rt1);
1630       if(is_const(current,dops[i].rs1)) {
1631         int v=get_const(current,dops[i].rs1);
1632         if(dops[i].opcode2==0x00) set_const(current,dops[i].rt1,v<<imm[i]);
1633         if(dops[i].opcode2==0x02) set_const(current,dops[i].rt1,(u_int)v>>imm[i]);
1634         if(dops[i].opcode2==0x03) set_const(current,dops[i].rt1,v>>imm[i]);
1635       }
1636       else clear_const(current,dops[i].rt1);
1637     }
1638   }
1639   else
1640   {
1641     clear_const(current,dops[i].rs1);
1642     clear_const(current,dops[i].rt1);
1643   }
1644
1645   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
1646   {
1647     assert(0);
1648   }
1649   if(dops[i].opcode2==0x3c) // DSLL32
1650   {
1651     assert(0);
1652   }
1653   if(dops[i].opcode2==0x3e) // DSRL32
1654   {
1655     assert(0);
1656   }
1657   if(dops[i].opcode2==0x3f) // DSRA32
1658   {
1659     assert(0);
1660   }
1661 }
1662
1663 static void shift_alloc(struct regstat *current,int i)
1664 {
1665   if(dops[i].rt1) {
1666     if(dops[i].opcode2<=0x07) // SLLV/SRLV/SRAV
1667     {
1668       if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
1669       if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
1670       alloc_reg(current,i,dops[i].rt1);
1671       if(dops[i].rt1==dops[i].rs2) {
1672         alloc_reg_temp(current,i,-1);
1673         minimum_free_regs[i]=1;
1674       }
1675     } else { // DSLLV/DSRLV/DSRAV
1676       assert(0);
1677     }
1678     clear_const(current,dops[i].rs1);
1679     clear_const(current,dops[i].rs2);
1680     clear_const(current,dops[i].rt1);
1681     dirty_reg(current,dops[i].rt1);
1682   }
1683 }
1684
1685 static void alu_alloc(struct regstat *current,int i)
1686 {
1687   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
1688     if(dops[i].rt1) {
1689       if(dops[i].rs1&&dops[i].rs2) {
1690         alloc_reg(current,i,dops[i].rs1);
1691         alloc_reg(current,i,dops[i].rs2);
1692       }
1693       else {
1694         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1695         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1696       }
1697       alloc_reg(current,i,dops[i].rt1);
1698     }
1699   }
1700   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
1701     if(dops[i].rt1) {
1702       alloc_reg(current,i,dops[i].rs1);
1703       alloc_reg(current,i,dops[i].rs2);
1704       alloc_reg(current,i,dops[i].rt1);
1705     }
1706   }
1707   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
1708     if(dops[i].rt1) {
1709       if(dops[i].rs1&&dops[i].rs2) {
1710         alloc_reg(current,i,dops[i].rs1);
1711         alloc_reg(current,i,dops[i].rs2);
1712       }
1713       else
1714       {
1715         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1716         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1717       }
1718       alloc_reg(current,i,dops[i].rt1);
1719     }
1720   }
1721   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
1722     assert(0);
1723   }
1724   clear_const(current,dops[i].rs1);
1725   clear_const(current,dops[i].rs2);
1726   clear_const(current,dops[i].rt1);
1727   dirty_reg(current,dops[i].rt1);
1728 }
1729
1730 static void imm16_alloc(struct regstat *current,int i)
1731 {
1732   if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1733   else dops[i].lt1=dops[i].rs1;
1734   if(dops[i].rt1) alloc_reg(current,i,dops[i].rt1);
1735   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
1736     assert(0);
1737   }
1738   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
1739     clear_const(current,dops[i].rs1);
1740     clear_const(current,dops[i].rt1);
1741   }
1742   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
1743     if(is_const(current,dops[i].rs1)) {
1744       int v=get_const(current,dops[i].rs1);
1745       if(dops[i].opcode==0x0c) set_const(current,dops[i].rt1,v&imm[i]);
1746       if(dops[i].opcode==0x0d) set_const(current,dops[i].rt1,v|imm[i]);
1747       if(dops[i].opcode==0x0e) set_const(current,dops[i].rt1,v^imm[i]);
1748     }
1749     else clear_const(current,dops[i].rt1);
1750   }
1751   else if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
1752     if(is_const(current,dops[i].rs1)) {
1753       int v=get_const(current,dops[i].rs1);
1754       set_const(current,dops[i].rt1,v+imm[i]);
1755     }
1756     else clear_const(current,dops[i].rt1);
1757   }
1758   else {
1759     set_const(current,dops[i].rt1,imm[i]<<16); // LUI
1760   }
1761   dirty_reg(current,dops[i].rt1);
1762 }
1763
1764 static void load_alloc(struct regstat *current,int i)
1765 {
1766   clear_const(current,dops[i].rt1);
1767   //if(dops[i].rs1!=dops[i].rt1&&needed_again(dops[i].rs1,i)) clear_const(current,dops[i].rs1); // Does this help or hurt?
1768   if(!dops[i].rs1) current->u&=~1LL; // Allow allocating r0 if it's the source register
1769   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1770   if(dops[i].rt1&&!((current->u>>dops[i].rt1)&1)) {
1771     alloc_reg(current,i,dops[i].rt1);
1772     assert(get_reg(current->regmap,dops[i].rt1)>=0);
1773     if(dops[i].opcode==0x27||dops[i].opcode==0x37) // LWU/LD
1774     {
1775       assert(0);
1776     }
1777     else if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
1778     {
1779       assert(0);
1780     }
1781     dirty_reg(current,dops[i].rt1);
1782     // LWL/LWR need a temporary register for the old value
1783     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
1784     {
1785       alloc_reg(current,i,FTEMP);
1786       alloc_reg_temp(current,i,-1);
1787       minimum_free_regs[i]=1;
1788     }
1789   }
1790   else
1791   {
1792     // Load to r0 or unneeded register (dummy load)
1793     // but we still need a register to calculate the address
1794     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
1795     {
1796       alloc_reg(current,i,FTEMP); // LWL/LWR need another temporary
1797     }
1798     alloc_reg_temp(current,i,-1);
1799     minimum_free_regs[i]=1;
1800     if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
1801     {
1802       assert(0);
1803     }
1804   }
1805 }
1806
1807 void store_alloc(struct regstat *current,int i)
1808 {
1809   clear_const(current,dops[i].rs2);
1810   if(!(dops[i].rs2)) current->u&=~1LL; // Allow allocating r0 if necessary
1811   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1812   alloc_reg(current,i,dops[i].rs2);
1813   if(dops[i].opcode==0x2c||dops[i].opcode==0x2d||dops[i].opcode==0x3f) { // 64-bit SDL/SDR/SD
1814     assert(0);
1815   }
1816   #if defined(HOST_IMM8)
1817   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1818   else alloc_reg(current,i,INVCP);
1819   #endif
1820   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) { // SWL/SWL/SDL/SDR
1821     alloc_reg(current,i,FTEMP);
1822   }
1823   // We need a temporary register for address generation
1824   alloc_reg_temp(current,i,-1);
1825   minimum_free_regs[i]=1;
1826 }
1827
1828 void c1ls_alloc(struct regstat *current,int i)
1829 {
1830   //clear_const(current,dops[i].rs1); // FIXME
1831   clear_const(current,dops[i].rt1);
1832   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1833   alloc_reg(current,i,CSREG); // Status
1834   alloc_reg(current,i,FTEMP);
1835   if(dops[i].opcode==0x35||dops[i].opcode==0x3d) { // 64-bit LDC1/SDC1
1836     assert(0);
1837   }
1838   #if defined(HOST_IMM8)
1839   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1840   else if((dops[i].opcode&0x3b)==0x39) // SWC1/SDC1
1841     alloc_reg(current,i,INVCP);
1842   #endif
1843   // We need a temporary register for address generation
1844   alloc_reg_temp(current,i,-1);
1845 }
1846
1847 void c2ls_alloc(struct regstat *current,int i)
1848 {
1849   clear_const(current,dops[i].rt1);
1850   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1851   alloc_reg(current,i,FTEMP);
1852   #if defined(HOST_IMM8)
1853   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1854   if((dops[i].opcode&0x3b)==0x3a) // SWC2/SDC2
1855     alloc_reg(current,i,INVCP);
1856   #endif
1857   // We need a temporary register for address generation
1858   alloc_reg_temp(current,i,-1);
1859   minimum_free_regs[i]=1;
1860 }
1861
1862 #ifndef multdiv_alloc
1863 void multdiv_alloc(struct regstat *current,int i)
1864 {
1865   //  case 0x18: MULT
1866   //  case 0x19: MULTU
1867   //  case 0x1A: DIV
1868   //  case 0x1B: DIVU
1869   //  case 0x1C: DMULT
1870   //  case 0x1D: DMULTU
1871   //  case 0x1E: DDIV
1872   //  case 0x1F: DDIVU
1873   clear_const(current,dops[i].rs1);
1874   clear_const(current,dops[i].rs2);
1875   alloc_cc(current,i); // for stalls
1876   if(dops[i].rs1&&dops[i].rs2)
1877   {
1878     if((dops[i].opcode2&4)==0) // 32-bit
1879     {
1880       current->u&=~(1LL<<HIREG);
1881       current->u&=~(1LL<<LOREG);
1882       alloc_reg(current,i,HIREG);
1883       alloc_reg(current,i,LOREG);
1884       alloc_reg(current,i,dops[i].rs1);
1885       alloc_reg(current,i,dops[i].rs2);
1886       dirty_reg(current,HIREG);
1887       dirty_reg(current,LOREG);
1888     }
1889     else // 64-bit
1890     {
1891       assert(0);
1892     }
1893   }
1894   else
1895   {
1896     // Multiply by zero is zero.
1897     // MIPS does not have a divide by zero exception.
1898     // The result is undefined, we return zero.
1899     alloc_reg(current,i,HIREG);
1900     alloc_reg(current,i,LOREG);
1901     dirty_reg(current,HIREG);
1902     dirty_reg(current,LOREG);
1903   }
1904 }
1905 #endif
1906
1907 void cop0_alloc(struct regstat *current,int i)
1908 {
1909   if(dops[i].opcode2==0) // MFC0
1910   {
1911     if(dops[i].rt1) {
1912       clear_const(current,dops[i].rt1);
1913       alloc_all(current,i);
1914       alloc_reg(current,i,dops[i].rt1);
1915       dirty_reg(current,dops[i].rt1);
1916     }
1917   }
1918   else if(dops[i].opcode2==4) // MTC0
1919   {
1920     if(dops[i].rs1){
1921       clear_const(current,dops[i].rs1);
1922       alloc_reg(current,i,dops[i].rs1);
1923       alloc_all(current,i);
1924     }
1925     else {
1926       alloc_all(current,i); // FIXME: Keep r0
1927       current->u&=~1LL;
1928       alloc_reg(current,i,0);
1929     }
1930   }
1931   else
1932   {
1933     // TLBR/TLBWI/TLBWR/TLBP/ERET
1934     assert(dops[i].opcode2==0x10);
1935     alloc_all(current,i);
1936   }
1937   minimum_free_regs[i]=HOST_REGS;
1938 }
1939
1940 static void cop2_alloc(struct regstat *current,int i)
1941 {
1942   if (dops[i].opcode2 < 3) // MFC2/CFC2
1943   {
1944     alloc_cc(current,i); // for stalls
1945     dirty_reg(current,CCREG);
1946     if(dops[i].rt1){
1947       clear_const(current,dops[i].rt1);
1948       alloc_reg(current,i,dops[i].rt1);
1949       dirty_reg(current,dops[i].rt1);
1950     }
1951   }
1952   else if (dops[i].opcode2 > 3) // MTC2/CTC2
1953   {
1954     if(dops[i].rs1){
1955       clear_const(current,dops[i].rs1);
1956       alloc_reg(current,i,dops[i].rs1);
1957     }
1958     else {
1959       current->u&=~1LL;
1960       alloc_reg(current,i,0);
1961     }
1962   }
1963   alloc_reg_temp(current,i,-1);
1964   minimum_free_regs[i]=1;
1965 }
1966
1967 void c2op_alloc(struct regstat *current,int i)
1968 {
1969   alloc_cc(current,i); // for stalls
1970   dirty_reg(current,CCREG);
1971   alloc_reg_temp(current,i,-1);
1972 }
1973
1974 void syscall_alloc(struct regstat *current,int i)
1975 {
1976   alloc_cc(current,i);
1977   dirty_reg(current,CCREG);
1978   alloc_all(current,i);
1979   minimum_free_regs[i]=HOST_REGS;
1980   current->isconst=0;
1981 }
1982
1983 void delayslot_alloc(struct regstat *current,int i)
1984 {
1985   switch(dops[i].itype) {
1986     case UJUMP:
1987     case CJUMP:
1988     case SJUMP:
1989     case RJUMP:
1990     case SYSCALL:
1991     case HLECALL:
1992     case SPAN:
1993       assem_debug("jump in the delay slot.  this shouldn't happen.\n");//abort();
1994       SysPrintf("Disabled speculative precompilation\n");
1995       stop_after_jal=1;
1996       break;
1997     case IMM16:
1998       imm16_alloc(current,i);
1999       break;
2000     case LOAD:
2001     case LOADLR:
2002       load_alloc(current,i);
2003       break;
2004     case STORE:
2005     case STORELR:
2006       store_alloc(current,i);
2007       break;
2008     case ALU:
2009       alu_alloc(current,i);
2010       break;
2011     case SHIFT:
2012       shift_alloc(current,i);
2013       break;
2014     case MULTDIV:
2015       multdiv_alloc(current,i);
2016       break;
2017     case SHIFTIMM:
2018       shiftimm_alloc(current,i);
2019       break;
2020     case MOV:
2021       mov_alloc(current,i);
2022       break;
2023     case COP0:
2024       cop0_alloc(current,i);
2025       break;
2026     case COP1:
2027       break;
2028     case COP2:
2029       cop2_alloc(current,i);
2030       break;
2031     case C1LS:
2032       c1ls_alloc(current,i);
2033       break;
2034     case C2LS:
2035       c2ls_alloc(current,i);
2036       break;
2037     case C2OP:
2038       c2op_alloc(current,i);
2039       break;
2040   }
2041 }
2042
2043 // Special case where a branch and delay slot span two pages in virtual memory
2044 static void pagespan_alloc(struct regstat *current,int i)
2045 {
2046   current->isconst=0;
2047   current->wasconst=0;
2048   regs[i].wasconst=0;
2049   minimum_free_regs[i]=HOST_REGS;
2050   alloc_all(current,i);
2051   alloc_cc(current,i);
2052   dirty_reg(current,CCREG);
2053   if(dops[i].opcode==3) // JAL
2054   {
2055     alloc_reg(current,i,31);
2056     dirty_reg(current,31);
2057   }
2058   if(dops[i].opcode==0&&(dops[i].opcode2&0x3E)==8) // JR/JALR
2059   {
2060     alloc_reg(current,i,dops[i].rs1);
2061     if (dops[i].rt1!=0) {
2062       alloc_reg(current,i,dops[i].rt1);
2063       dirty_reg(current,dops[i].rt1);
2064     }
2065   }
2066   if((dops[i].opcode&0x2E)==4) // BEQ/BNE/BEQL/BNEL
2067   {
2068     if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
2069     if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
2070   }
2071   else
2072   if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ/BLEZL/BGTZL
2073   {
2074     if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
2075   }
2076   //else ...
2077 }
2078
2079 static void add_stub(enum stub_type type, void *addr, void *retaddr,
2080   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e)
2081 {
2082   assert(stubcount < ARRAY_SIZE(stubs));
2083   stubs[stubcount].type = type;
2084   stubs[stubcount].addr = addr;
2085   stubs[stubcount].retaddr = retaddr;
2086   stubs[stubcount].a = a;
2087   stubs[stubcount].b = b;
2088   stubs[stubcount].c = c;
2089   stubs[stubcount].d = d;
2090   stubs[stubcount].e = e;
2091   stubcount++;
2092 }
2093
2094 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
2095   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist)
2096 {
2097   add_stub(type, addr, retaddr, i, addr_reg, (uintptr_t)i_regs, ccadj, reglist);
2098 }
2099
2100 // Write out a single register
2101 static void wb_register(signed char r,signed char regmap[],uint64_t dirty)
2102 {
2103   int hr;
2104   for(hr=0;hr<HOST_REGS;hr++) {
2105     if(hr!=EXCLUDE_REG) {
2106       if((regmap[hr]&63)==r) {
2107         if((dirty>>hr)&1) {
2108           assert(regmap[hr]<64);
2109           emit_storereg(r,hr);
2110         }
2111       }
2112     }
2113   }
2114 }
2115
2116 static void wb_valid(signed char pre[],signed char entry[],u_int dirty_pre,u_int dirty,uint64_t u)
2117 {
2118   //if(dirty_pre==dirty) return;
2119   int hr,reg;
2120   for(hr=0;hr<HOST_REGS;hr++) {
2121     if(hr!=EXCLUDE_REG) {
2122       reg=pre[hr];
2123       if(((~u)>>(reg&63))&1) {
2124         if(reg>0) {
2125           if(((dirty_pre&~dirty)>>hr)&1) {
2126             if(reg>0&&reg<34) {
2127               emit_storereg(reg,hr);
2128             }
2129             else if(reg>=64) {
2130               assert(0);
2131             }
2132           }
2133         }
2134       }
2135     }
2136   }
2137 }
2138
2139 // trashes r2
2140 static void pass_args(int a0, int a1)
2141 {
2142   if(a0==1&&a1==0) {
2143     // must swap
2144     emit_mov(a0,2); emit_mov(a1,1); emit_mov(2,0);
2145   }
2146   else if(a0!=0&&a1==0) {
2147     emit_mov(a1,1);
2148     if (a0>=0) emit_mov(a0,0);
2149   }
2150   else {
2151     if(a0>=0&&a0!=0) emit_mov(a0,0);
2152     if(a1>=0&&a1!=1) emit_mov(a1,1);
2153   }
2154 }
2155
2156 static void alu_assemble(int i,struct regstat *i_regs)
2157 {
2158   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
2159     if(dops[i].rt1) {
2160       signed char s1,s2,t;
2161       t=get_reg(i_regs->regmap,dops[i].rt1);
2162       if(t>=0) {
2163         s1=get_reg(i_regs->regmap,dops[i].rs1);
2164         s2=get_reg(i_regs->regmap,dops[i].rs2);
2165         if(dops[i].rs1&&dops[i].rs2) {
2166           assert(s1>=0);
2167           assert(s2>=0);
2168           if(dops[i].opcode2&2) emit_sub(s1,s2,t);
2169           else emit_add(s1,s2,t);
2170         }
2171         else if(dops[i].rs1) {
2172           if(s1>=0) emit_mov(s1,t);
2173           else emit_loadreg(dops[i].rs1,t);
2174         }
2175         else if(dops[i].rs2) {
2176           if(s2>=0) {
2177             if(dops[i].opcode2&2) emit_neg(s2,t);
2178             else emit_mov(s2,t);
2179           }
2180           else {
2181             emit_loadreg(dops[i].rs2,t);
2182             if(dops[i].opcode2&2) emit_neg(t,t);
2183           }
2184         }
2185         else emit_zeroreg(t);
2186       }
2187     }
2188   }
2189   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
2190     assert(0);
2191   }
2192   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
2193     if(dops[i].rt1) {
2194       signed char s1l,s2l,t;
2195       {
2196         t=get_reg(i_regs->regmap,dops[i].rt1);
2197         //assert(t>=0);
2198         if(t>=0) {
2199           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2200           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2201           if(dops[i].rs2==0) // rx<r0
2202           {
2203             if(dops[i].opcode2==0x2a&&dops[i].rs1!=0) { // SLT
2204               assert(s1l>=0);
2205               emit_shrimm(s1l,31,t);
2206             }
2207             else // SLTU (unsigned can not be less than zero, 0<0)
2208               emit_zeroreg(t);
2209           }
2210           else if(dops[i].rs1==0) // r0<rx
2211           {
2212             assert(s2l>=0);
2213             if(dops[i].opcode2==0x2a) // SLT
2214               emit_set_gz32(s2l,t);
2215             else // SLTU (set if not zero)
2216               emit_set_nz32(s2l,t);
2217           }
2218           else{
2219             assert(s1l>=0);assert(s2l>=0);
2220             if(dops[i].opcode2==0x2a) // SLT
2221               emit_set_if_less32(s1l,s2l,t);
2222             else // SLTU
2223               emit_set_if_carry32(s1l,s2l,t);
2224           }
2225         }
2226       }
2227     }
2228   }
2229   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
2230     if(dops[i].rt1) {
2231       signed char s1l,s2l,tl;
2232       tl=get_reg(i_regs->regmap,dops[i].rt1);
2233       {
2234         if(tl>=0) {
2235           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2236           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2237           if(dops[i].rs1&&dops[i].rs2) {
2238             assert(s1l>=0);
2239             assert(s2l>=0);
2240             if(dops[i].opcode2==0x24) { // AND
2241               emit_and(s1l,s2l,tl);
2242             } else
2243             if(dops[i].opcode2==0x25) { // OR
2244               emit_or(s1l,s2l,tl);
2245             } else
2246             if(dops[i].opcode2==0x26) { // XOR
2247               emit_xor(s1l,s2l,tl);
2248             } else
2249             if(dops[i].opcode2==0x27) { // NOR
2250               emit_or(s1l,s2l,tl);
2251               emit_not(tl,tl);
2252             }
2253           }
2254           else
2255           {
2256             if(dops[i].opcode2==0x24) { // AND
2257               emit_zeroreg(tl);
2258             } else
2259             if(dops[i].opcode2==0x25||dops[i].opcode2==0x26) { // OR/XOR
2260               if(dops[i].rs1){
2261                 if(s1l>=0) emit_mov(s1l,tl);
2262                 else emit_loadreg(dops[i].rs1,tl); // CHECK: regmap_entry?
2263               }
2264               else
2265               if(dops[i].rs2){
2266                 if(s2l>=0) emit_mov(s2l,tl);
2267                 else emit_loadreg(dops[i].rs2,tl); // CHECK: regmap_entry?
2268               }
2269               else emit_zeroreg(tl);
2270             } else
2271             if(dops[i].opcode2==0x27) { // NOR
2272               if(dops[i].rs1){
2273                 if(s1l>=0) emit_not(s1l,tl);
2274                 else {
2275                   emit_loadreg(dops[i].rs1,tl);
2276                   emit_not(tl,tl);
2277                 }
2278               }
2279               else
2280               if(dops[i].rs2){
2281                 if(s2l>=0) emit_not(s2l,tl);
2282                 else {
2283                   emit_loadreg(dops[i].rs2,tl);
2284                   emit_not(tl,tl);
2285                 }
2286               }
2287               else emit_movimm(-1,tl);
2288             }
2289           }
2290         }
2291       }
2292     }
2293   }
2294 }
2295
2296 void imm16_assemble(int i,struct regstat *i_regs)
2297 {
2298   if (dops[i].opcode==0x0f) { // LUI
2299     if(dops[i].rt1) {
2300       signed char t;
2301       t=get_reg(i_regs->regmap,dops[i].rt1);
2302       //assert(t>=0);
2303       if(t>=0) {
2304         if(!((i_regs->isconst>>t)&1))
2305           emit_movimm(imm[i]<<16,t);
2306       }
2307     }
2308   }
2309   if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
2310     if(dops[i].rt1) {
2311       signed char s,t;
2312       t=get_reg(i_regs->regmap,dops[i].rt1);
2313       s=get_reg(i_regs->regmap,dops[i].rs1);
2314       if(dops[i].rs1) {
2315         //assert(t>=0);
2316         //assert(s>=0);
2317         if(t>=0) {
2318           if(!((i_regs->isconst>>t)&1)) {
2319             if(s<0) {
2320               if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2321               emit_addimm(t,imm[i],t);
2322             }else{
2323               if(!((i_regs->wasconst>>s)&1))
2324                 emit_addimm(s,imm[i],t);
2325               else
2326                 emit_movimm(constmap[i][s]+imm[i],t);
2327             }
2328           }
2329         }
2330       } else {
2331         if(t>=0) {
2332           if(!((i_regs->isconst>>t)&1))
2333             emit_movimm(imm[i],t);
2334         }
2335       }
2336     }
2337   }
2338   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
2339     if(dops[i].rt1) {
2340       signed char sl,tl;
2341       tl=get_reg(i_regs->regmap,dops[i].rt1);
2342       sl=get_reg(i_regs->regmap,dops[i].rs1);
2343       if(tl>=0) {
2344         if(dops[i].rs1) {
2345           assert(sl>=0);
2346           emit_addimm(sl,imm[i],tl);
2347         } else {
2348           emit_movimm(imm[i],tl);
2349         }
2350       }
2351     }
2352   }
2353   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
2354     if(dops[i].rt1) {
2355       //assert(dops[i].rs1!=0); // r0 might be valid, but it's probably a bug
2356       signed char sl,t;
2357       t=get_reg(i_regs->regmap,dops[i].rt1);
2358       sl=get_reg(i_regs->regmap,dops[i].rs1);
2359       //assert(t>=0);
2360       if(t>=0) {
2361         if(dops[i].rs1>0) {
2362             if(dops[i].opcode==0x0a) { // SLTI
2363               if(sl<0) {
2364                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2365                 emit_slti32(t,imm[i],t);
2366               }else{
2367                 emit_slti32(sl,imm[i],t);
2368               }
2369             }
2370             else { // SLTIU
2371               if(sl<0) {
2372                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2373                 emit_sltiu32(t,imm[i],t);
2374               }else{
2375                 emit_sltiu32(sl,imm[i],t);
2376               }
2377             }
2378         }else{
2379           // SLTI(U) with r0 is just stupid,
2380           // nonetheless examples can be found
2381           if(dops[i].opcode==0x0a) // SLTI
2382             if(0<imm[i]) emit_movimm(1,t);
2383             else emit_zeroreg(t);
2384           else // SLTIU
2385           {
2386             if(imm[i]) emit_movimm(1,t);
2387             else emit_zeroreg(t);
2388           }
2389         }
2390       }
2391     }
2392   }
2393   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
2394     if(dops[i].rt1) {
2395       signed char sl,tl;
2396       tl=get_reg(i_regs->regmap,dops[i].rt1);
2397       sl=get_reg(i_regs->regmap,dops[i].rs1);
2398       if(tl>=0 && !((i_regs->isconst>>tl)&1)) {
2399         if(dops[i].opcode==0x0c) //ANDI
2400         {
2401           if(dops[i].rs1) {
2402             if(sl<0) {
2403               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2404               emit_andimm(tl,imm[i],tl);
2405             }else{
2406               if(!((i_regs->wasconst>>sl)&1))
2407                 emit_andimm(sl,imm[i],tl);
2408               else
2409                 emit_movimm(constmap[i][sl]&imm[i],tl);
2410             }
2411           }
2412           else
2413             emit_zeroreg(tl);
2414         }
2415         else
2416         {
2417           if(dops[i].rs1) {
2418             if(sl<0) {
2419               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2420             }
2421             if(dops[i].opcode==0x0d) { // ORI
2422               if(sl<0) {
2423                 emit_orimm(tl,imm[i],tl);
2424               }else{
2425                 if(!((i_regs->wasconst>>sl)&1))
2426                   emit_orimm(sl,imm[i],tl);
2427                 else
2428                   emit_movimm(constmap[i][sl]|imm[i],tl);
2429               }
2430             }
2431             if(dops[i].opcode==0x0e) { // XORI
2432               if(sl<0) {
2433                 emit_xorimm(tl,imm[i],tl);
2434               }else{
2435                 if(!((i_regs->wasconst>>sl)&1))
2436                   emit_xorimm(sl,imm[i],tl);
2437                 else
2438                   emit_movimm(constmap[i][sl]^imm[i],tl);
2439               }
2440             }
2441           }
2442           else {
2443             emit_movimm(imm[i],tl);
2444           }
2445         }
2446       }
2447     }
2448   }
2449 }
2450
2451 void shiftimm_assemble(int i,struct regstat *i_regs)
2452 {
2453   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
2454   {
2455     if(dops[i].rt1) {
2456       signed char s,t;
2457       t=get_reg(i_regs->regmap,dops[i].rt1);
2458       s=get_reg(i_regs->regmap,dops[i].rs1);
2459       //assert(t>=0);
2460       if(t>=0&&!((i_regs->isconst>>t)&1)){
2461         if(dops[i].rs1==0)
2462         {
2463           emit_zeroreg(t);
2464         }
2465         else
2466         {
2467           if(s<0&&i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2468           if(imm[i]) {
2469             if(dops[i].opcode2==0) // SLL
2470             {
2471               emit_shlimm(s<0?t:s,imm[i],t);
2472             }
2473             if(dops[i].opcode2==2) // SRL
2474             {
2475               emit_shrimm(s<0?t:s,imm[i],t);
2476             }
2477             if(dops[i].opcode2==3) // SRA
2478             {
2479               emit_sarimm(s<0?t:s,imm[i],t);
2480             }
2481           }else{
2482             // Shift by zero
2483             if(s>=0 && s!=t) emit_mov(s,t);
2484           }
2485         }
2486       }
2487       //emit_storereg(dops[i].rt1,t); //DEBUG
2488     }
2489   }
2490   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
2491   {
2492     assert(0);
2493   }
2494   if(dops[i].opcode2==0x3c) // DSLL32
2495   {
2496     assert(0);
2497   }
2498   if(dops[i].opcode2==0x3e) // DSRL32
2499   {
2500     assert(0);
2501   }
2502   if(dops[i].opcode2==0x3f) // DSRA32
2503   {
2504     assert(0);
2505   }
2506 }
2507
2508 #ifndef shift_assemble
2509 static void shift_assemble(int i,struct regstat *i_regs)
2510 {
2511   signed char s,t,shift;
2512   if (dops[i].rt1 == 0)
2513     return;
2514   assert(dops[i].opcode2<=0x07); // SLLV/SRLV/SRAV
2515   t = get_reg(i_regs->regmap, dops[i].rt1);
2516   s = get_reg(i_regs->regmap, dops[i].rs1);
2517   shift = get_reg(i_regs->regmap, dops[i].rs2);
2518   if (t < 0)
2519     return;
2520
2521   if(dops[i].rs1==0)
2522     emit_zeroreg(t);
2523   else if(dops[i].rs2==0) {
2524     assert(s>=0);
2525     if(s!=t) emit_mov(s,t);
2526   }
2527   else {
2528     host_tempreg_acquire();
2529     emit_andimm(shift,31,HOST_TEMPREG);
2530     switch(dops[i].opcode2) {
2531     case 4: // SLLV
2532       emit_shl(s,HOST_TEMPREG,t);
2533       break;
2534     case 6: // SRLV
2535       emit_shr(s,HOST_TEMPREG,t);
2536       break;
2537     case 7: // SRAV
2538       emit_sar(s,HOST_TEMPREG,t);
2539       break;
2540     default:
2541       assert(0);
2542     }
2543     host_tempreg_release();
2544   }
2545 }
2546
2547 #endif
2548
2549 enum {
2550   MTYPE_8000 = 0,
2551   MTYPE_8020,
2552   MTYPE_0000,
2553   MTYPE_A000,
2554   MTYPE_1F80,
2555 };
2556
2557 static int get_ptr_mem_type(u_int a)
2558 {
2559   if(a < 0x00200000) {
2560     if(a<0x1000&&((start>>20)==0xbfc||(start>>24)==0xa0))
2561       // return wrong, must use memhandler for BIOS self-test to pass
2562       // 007 does similar stuff from a00 mirror, weird stuff
2563       return MTYPE_8000;
2564     return MTYPE_0000;
2565   }
2566   if(0x1f800000 <= a && a < 0x1f801000)
2567     return MTYPE_1F80;
2568   if(0x80200000 <= a && a < 0x80800000)
2569     return MTYPE_8020;
2570   if(0xa0000000 <= a && a < 0xa0200000)
2571     return MTYPE_A000;
2572   return MTYPE_8000;
2573 }
2574
2575 static void *emit_fastpath_cmp_jump(int i,int addr,int *addr_reg_override)
2576 {
2577   void *jaddr = NULL;
2578   int type=0;
2579   int mr=dops[i].rs1;
2580   if(((smrv_strong|smrv_weak)>>mr)&1) {
2581     type=get_ptr_mem_type(smrv[mr]);
2582     //printf("set %08x @%08x r%d %d\n", smrv[mr], start+i*4, mr, type);
2583   }
2584   else {
2585     // use the mirror we are running on
2586     type=get_ptr_mem_type(start);
2587     //printf("set nospec   @%08x r%d %d\n", start+i*4, mr, type);
2588   }
2589
2590   if(type==MTYPE_8020) { // RAM 80200000+ mirror
2591     host_tempreg_acquire();
2592     emit_andimm(addr,~0x00e00000,HOST_TEMPREG);
2593     addr=*addr_reg_override=HOST_TEMPREG;
2594     type=0;
2595   }
2596   else if(type==MTYPE_0000) { // RAM 0 mirror
2597     host_tempreg_acquire();
2598     emit_orimm(addr,0x80000000,HOST_TEMPREG);
2599     addr=*addr_reg_override=HOST_TEMPREG;
2600     type=0;
2601   }
2602   else if(type==MTYPE_A000) { // RAM A mirror
2603     host_tempreg_acquire();
2604     emit_andimm(addr,~0x20000000,HOST_TEMPREG);
2605     addr=*addr_reg_override=HOST_TEMPREG;
2606     type=0;
2607   }
2608   else if(type==MTYPE_1F80) { // scratchpad
2609     if (psxH == (void *)0x1f800000) {
2610       host_tempreg_acquire();
2611       emit_xorimm(addr,0x1f800000,HOST_TEMPREG);
2612       emit_cmpimm(HOST_TEMPREG,0x1000);
2613       host_tempreg_release();
2614       jaddr=out;
2615       emit_jc(0);
2616     }
2617     else {
2618       // do the usual RAM check, jump will go to the right handler
2619       type=0;
2620     }
2621   }
2622
2623   if(type==0)
2624   {
2625     emit_cmpimm(addr,RAM_SIZE);
2626     jaddr=out;
2627     #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
2628     // Hint to branch predictor that the branch is unlikely to be taken
2629     if(dops[i].rs1>=28)
2630       emit_jno_unlikely(0);
2631     else
2632     #endif
2633       emit_jno(0);
2634     if(ram_offset!=0) {
2635       host_tempreg_acquire();
2636       emit_addimm(addr,ram_offset,HOST_TEMPREG);
2637       addr=*addr_reg_override=HOST_TEMPREG;
2638     }
2639   }
2640
2641   return jaddr;
2642 }
2643
2644 // return memhandler, or get directly accessable address and return 0
2645 static void *get_direct_memhandler(void *table, u_int addr,
2646   enum stub_type type, uintptr_t *addr_host)
2647 {
2648   uintptr_t l1, l2 = 0;
2649   l1 = ((uintptr_t *)table)[addr>>12];
2650   if ((l1 & (1ul << (sizeof(l1)*8-1))) == 0) {
2651     uintptr_t v = l1 << 1;
2652     *addr_host = v + addr;
2653     return NULL;
2654   }
2655   else {
2656     l1 <<= 1;
2657     if (type == LOADB_STUB || type == LOADBU_STUB || type == STOREB_STUB)
2658       l2 = ((uintptr_t *)l1)[0x1000/4 + 0x1000/2 + (addr&0xfff)];
2659     else if (type == LOADH_STUB || type == LOADHU_STUB || type == STOREH_STUB)
2660       l2=((uintptr_t *)l1)[0x1000/4 + (addr&0xfff)/2];
2661     else
2662       l2=((uintptr_t *)l1)[(addr&0xfff)/4];
2663     if ((l2 & (1<<31)) == 0) {
2664       uintptr_t v = l2 << 1;
2665       *addr_host = v + (addr&0xfff);
2666       return NULL;
2667     }
2668     return (void *)(l2 << 1);
2669   }
2670 }
2671
2672 static u_int get_host_reglist(const signed char *regmap)
2673 {
2674   u_int reglist = 0, hr;
2675   for (hr = 0; hr < HOST_REGS; hr++) {
2676     if (hr != EXCLUDE_REG && regmap[hr] >= 0)
2677       reglist |= 1 << hr;
2678   }
2679   return reglist;
2680 }
2681
2682 static u_int reglist_exclude(u_int reglist, int r1, int r2)
2683 {
2684   if (r1 >= 0)
2685     reglist &= ~(1u << r1);
2686   if (r2 >= 0)
2687     reglist &= ~(1u << r2);
2688   return reglist;
2689 }
2690
2691 // find a temp caller-saved register not in reglist (so assumed to be free)
2692 static int reglist_find_free(u_int reglist)
2693 {
2694   u_int free_regs = ~reglist & CALLER_SAVE_REGS;
2695   if (free_regs == 0)
2696     return -1;
2697   return __builtin_ctz(free_regs);
2698 }
2699
2700 static void load_assemble(int i, const struct regstat *i_regs)
2701 {
2702   int s,tl,addr;
2703   int offset;
2704   void *jaddr=0;
2705   int memtarget=0,c=0;
2706   int fastio_reg_override=-1;
2707   u_int reglist=get_host_reglist(i_regs->regmap);
2708   tl=get_reg(i_regs->regmap,dops[i].rt1);
2709   s=get_reg(i_regs->regmap,dops[i].rs1);
2710   offset=imm[i];
2711   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2712   if(s>=0) {
2713     c=(i_regs->wasconst>>s)&1;
2714     if (c) {
2715       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2716     }
2717   }
2718   //printf("load_assemble: c=%d\n",c);
2719   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2720   // FIXME: Even if the load is a NOP, we should check for pagefaults...
2721   if((tl<0&&(!c||(((u_int)constmap[i][s]+offset)>>16)==0x1f80))
2722     ||dops[i].rt1==0) {
2723       // could be FIFO, must perform the read
2724       // ||dummy read
2725       assem_debug("(forced read)\n");
2726       tl=get_reg(i_regs->regmap,-1);
2727       assert(tl>=0);
2728   }
2729   if(offset||s<0||c) addr=tl;
2730   else addr=s;
2731   //if(tl<0) tl=get_reg(i_regs->regmap,-1);
2732  if(tl>=0) {
2733   //printf("load_assemble: c=%d\n",c);
2734   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2735   assert(tl>=0); // Even if the load is a NOP, we must check for pagefaults and I/O
2736   reglist&=~(1<<tl);
2737   if(!c) {
2738     #ifdef R29_HACK
2739     // Strmnnrmn's speed hack
2740     if(dops[i].rs1!=29||start<0x80001000||start>=0x80000000+RAM_SIZE)
2741     #endif
2742     {
2743       jaddr=emit_fastpath_cmp_jump(i,addr,&fastio_reg_override);
2744     }
2745   }
2746   else if(ram_offset&&memtarget) {
2747     host_tempreg_acquire();
2748     emit_addimm(addr,ram_offset,HOST_TEMPREG);
2749     fastio_reg_override=HOST_TEMPREG;
2750   }
2751   int dummy=(dops[i].rt1==0)||(tl!=get_reg(i_regs->regmap,dops[i].rt1)); // ignore loads to r0 and unneeded reg
2752   if (dops[i].opcode==0x20) { // LB
2753     if(!c||memtarget) {
2754       if(!dummy) {
2755         {
2756           int x=0,a=tl;
2757           if(!c) a=addr;
2758           if(fastio_reg_override>=0) a=fastio_reg_override;
2759
2760           emit_movsbl_indexed(x,a,tl);
2761         }
2762       }
2763       if(jaddr)
2764         add_stub_r(LOADB_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2765     }
2766     else
2767       inline_readstub(LOADB_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj[i],reglist);
2768   }
2769   if (dops[i].opcode==0x21) { // LH
2770     if(!c||memtarget) {
2771       if(!dummy) {
2772         int x=0,a=tl;
2773         if(!c) a=addr;
2774         if(fastio_reg_override>=0) a=fastio_reg_override;
2775         emit_movswl_indexed(x,a,tl);
2776       }
2777       if(jaddr)
2778         add_stub_r(LOADH_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2779     }
2780     else
2781       inline_readstub(LOADH_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj[i],reglist);
2782   }
2783   if (dops[i].opcode==0x23) { // LW
2784     if(!c||memtarget) {
2785       if(!dummy) {
2786         int a=addr;
2787         if(fastio_reg_override>=0) a=fastio_reg_override;
2788         emit_readword_indexed(0,a,tl);
2789       }
2790       if(jaddr)
2791         add_stub_r(LOADW_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2792     }
2793     else
2794       inline_readstub(LOADW_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj[i],reglist);
2795   }
2796   if (dops[i].opcode==0x24) { // LBU
2797     if(!c||memtarget) {
2798       if(!dummy) {
2799         int x=0,a=tl;
2800         if(!c) a=addr;
2801         if(fastio_reg_override>=0) a=fastio_reg_override;
2802
2803         emit_movzbl_indexed(x,a,tl);
2804       }
2805       if(jaddr)
2806         add_stub_r(LOADBU_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2807     }
2808     else
2809       inline_readstub(LOADBU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj[i],reglist);
2810   }
2811   if (dops[i].opcode==0x25) { // LHU
2812     if(!c||memtarget) {
2813       if(!dummy) {
2814         int x=0,a=tl;
2815         if(!c) a=addr;
2816         if(fastio_reg_override>=0) a=fastio_reg_override;
2817         emit_movzwl_indexed(x,a,tl);
2818       }
2819       if(jaddr)
2820         add_stub_r(LOADHU_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2821     }
2822     else
2823       inline_readstub(LOADHU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj[i],reglist);
2824   }
2825   if (dops[i].opcode==0x27) { // LWU
2826     assert(0);
2827   }
2828   if (dops[i].opcode==0x37) { // LD
2829     assert(0);
2830   }
2831  }
2832  if (fastio_reg_override == HOST_TEMPREG)
2833    host_tempreg_release();
2834 }
2835
2836 #ifndef loadlr_assemble
2837 static void loadlr_assemble(int i, const struct regstat *i_regs)
2838 {
2839   int s,tl,temp,temp2,addr;
2840   int offset;
2841   void *jaddr=0;
2842   int memtarget=0,c=0;
2843   int fastio_reg_override=-1;
2844   u_int reglist=get_host_reglist(i_regs->regmap);
2845   tl=get_reg(i_regs->regmap,dops[i].rt1);
2846   s=get_reg(i_regs->regmap,dops[i].rs1);
2847   temp=get_reg(i_regs->regmap,-1);
2848   temp2=get_reg(i_regs->regmap,FTEMP);
2849   addr=get_reg(i_regs->regmap,AGEN1+(i&1));
2850   assert(addr<0);
2851   offset=imm[i];
2852   reglist|=1<<temp;
2853   if(offset||s<0||c) addr=temp2;
2854   else addr=s;
2855   if(s>=0) {
2856     c=(i_regs->wasconst>>s)&1;
2857     if(c) {
2858       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2859     }
2860   }
2861   if(!c) {
2862     emit_shlimm(addr,3,temp);
2863     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
2864       emit_andimm(addr,0xFFFFFFFC,temp2); // LWL/LWR
2865     }else{
2866       emit_andimm(addr,0xFFFFFFF8,temp2); // LDL/LDR
2867     }
2868     jaddr=emit_fastpath_cmp_jump(i,temp2,&fastio_reg_override);
2869   }
2870   else {
2871     if(ram_offset&&memtarget) {
2872       host_tempreg_acquire();
2873       emit_addimm(temp2,ram_offset,HOST_TEMPREG);
2874       fastio_reg_override=HOST_TEMPREG;
2875     }
2876     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
2877       emit_movimm(((constmap[i][s]+offset)<<3)&24,temp); // LWL/LWR
2878     }else{
2879       emit_movimm(((constmap[i][s]+offset)<<3)&56,temp); // LDL/LDR
2880     }
2881   }
2882   if (dops[i].opcode==0x22||dops[i].opcode==0x26) { // LWL/LWR
2883     if(!c||memtarget) {
2884       int a=temp2;
2885       if(fastio_reg_override>=0) a=fastio_reg_override;
2886       emit_readword_indexed(0,a,temp2);
2887       if(fastio_reg_override==HOST_TEMPREG) host_tempreg_release();
2888       if(jaddr) add_stub_r(LOADW_STUB,jaddr,out,i,temp2,i_regs,ccadj[i],reglist);
2889     }
2890     else
2891       inline_readstub(LOADW_STUB,i,(constmap[i][s]+offset)&0xFFFFFFFC,i_regs->regmap,FTEMP,ccadj[i],reglist);
2892     if(dops[i].rt1) {
2893       assert(tl>=0);
2894       emit_andimm(temp,24,temp);
2895       if (dops[i].opcode==0x22) // LWL
2896         emit_xorimm(temp,24,temp);
2897       host_tempreg_acquire();
2898       emit_movimm(-1,HOST_TEMPREG);
2899       if (dops[i].opcode==0x26) {
2900         emit_shr(temp2,temp,temp2);
2901         emit_bic_lsr(tl,HOST_TEMPREG,temp,tl);
2902       }else{
2903         emit_shl(temp2,temp,temp2);
2904         emit_bic_lsl(tl,HOST_TEMPREG,temp,tl);
2905       }
2906       host_tempreg_release();
2907       emit_or(temp2,tl,tl);
2908     }
2909     //emit_storereg(dops[i].rt1,tl); // DEBUG
2910   }
2911   if (dops[i].opcode==0x1A||dops[i].opcode==0x1B) { // LDL/LDR
2912     assert(0);
2913   }
2914 }
2915 #endif
2916
2917 void store_assemble(int i, const struct regstat *i_regs)
2918 {
2919   int s,tl;
2920   int addr,temp;
2921   int offset;
2922   void *jaddr=0;
2923   enum stub_type type;
2924   int memtarget=0,c=0;
2925   int agr=AGEN1+(i&1);
2926   int fastio_reg_override=-1;
2927   u_int reglist=get_host_reglist(i_regs->regmap);
2928   tl=get_reg(i_regs->regmap,dops[i].rs2);
2929   s=get_reg(i_regs->regmap,dops[i].rs1);
2930   temp=get_reg(i_regs->regmap,agr);
2931   if(temp<0) temp=get_reg(i_regs->regmap,-1);
2932   offset=imm[i];
2933   if(s>=0) {
2934     c=(i_regs->wasconst>>s)&1;
2935     if(c) {
2936       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2937     }
2938   }
2939   assert(tl>=0);
2940   assert(temp>=0);
2941   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2942   if(offset||s<0||c) addr=temp;
2943   else addr=s;
2944   if(!c) {
2945     jaddr=emit_fastpath_cmp_jump(i,addr,&fastio_reg_override);
2946   }
2947   else if(ram_offset&&memtarget) {
2948     host_tempreg_acquire();
2949     emit_addimm(addr,ram_offset,HOST_TEMPREG);
2950     fastio_reg_override=HOST_TEMPREG;
2951   }
2952
2953   if (dops[i].opcode==0x28) { // SB
2954     if(!c||memtarget) {
2955       int x=0,a=temp;
2956       if(!c) a=addr;
2957       if(fastio_reg_override>=0) a=fastio_reg_override;
2958       emit_writebyte_indexed(tl,x,a);
2959     }
2960     type=STOREB_STUB;
2961   }
2962   if (dops[i].opcode==0x29) { // SH
2963     if(!c||memtarget) {
2964       int x=0,a=temp;
2965       if(!c) a=addr;
2966       if(fastio_reg_override>=0) a=fastio_reg_override;
2967       emit_writehword_indexed(tl,x,a);
2968     }
2969     type=STOREH_STUB;
2970   }
2971   if (dops[i].opcode==0x2B) { // SW
2972     if(!c||memtarget) {
2973       int a=addr;
2974       if(fastio_reg_override>=0) a=fastio_reg_override;
2975       emit_writeword_indexed(tl,0,a);
2976     }
2977     type=STOREW_STUB;
2978   }
2979   if (dops[i].opcode==0x3F) { // SD
2980     assert(0);
2981     type=STORED_STUB;
2982   }
2983   if(fastio_reg_override==HOST_TEMPREG)
2984     host_tempreg_release();
2985   if(jaddr) {
2986     // PCSX store handlers don't check invcode again
2987     reglist|=1<<addr;
2988     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2989     jaddr=0;
2990   }
2991   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
2992     if(!c||memtarget) {
2993       #ifdef DESTRUCTIVE_SHIFT
2994       // The x86 shift operation is 'destructive'; it overwrites the
2995       // source register, so we need to make a copy first and use that.
2996       addr=temp;
2997       #endif
2998       #if defined(HOST_IMM8)
2999       int ir=get_reg(i_regs->regmap,INVCP);
3000       assert(ir>=0);
3001       emit_cmpmem_indexedsr12_reg(ir,addr,1);
3002       #else
3003       emit_cmpmem_indexedsr12_imm(invalid_code,addr,1);
3004       #endif
3005       #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3006       emit_callne(invalidate_addr_reg[addr]);
3007       #else
3008       void *jaddr2 = out;
3009       emit_jne(0);
3010       add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),addr,0,0,0);
3011       #endif
3012     }
3013   }
3014   u_int addr_val=constmap[i][s]+offset;
3015   if(jaddr) {
3016     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
3017   } else if(c&&!memtarget) {
3018     inline_writestub(type,i,addr_val,i_regs->regmap,dops[i].rs2,ccadj[i],reglist);
3019   }
3020   // basic current block modification detection..
3021   // not looking back as that should be in mips cache already
3022   // (see Spyro2 title->attract mode)
3023   if(c&&start+i*4<addr_val&&addr_val<start+slen*4) {
3024     SysPrintf("write to %08x hits block %08x, pc=%08x\n",addr_val,start,start+i*4);
3025     assert(i_regs->regmap==regs[i].regmap); // not delay slot
3026     if(i_regs->regmap==regs[i].regmap) {
3027       load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3028       wb_dirtys(regs[i].regmap_entry,regs[i].wasdirty);
3029       emit_movimm(start+i*4+4,0);
3030       emit_writeword(0,&pcaddr);
3031       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3032       emit_far_call(get_addr_ht);
3033       emit_jmpreg(0);
3034     }
3035   }
3036 }
3037
3038 static void storelr_assemble(int i, const struct regstat *i_regs)
3039 {
3040   int s,tl;
3041   int temp;
3042   int offset;
3043   void *jaddr=0;
3044   void *case1, *case2, *case3;
3045   void *done0, *done1, *done2;
3046   int memtarget=0,c=0;
3047   int agr=AGEN1+(i&1);
3048   u_int reglist=get_host_reglist(i_regs->regmap);
3049   tl=get_reg(i_regs->regmap,dops[i].rs2);
3050   s=get_reg(i_regs->regmap,dops[i].rs1);
3051   temp=get_reg(i_regs->regmap,agr);
3052   if(temp<0) temp=get_reg(i_regs->regmap,-1);
3053   offset=imm[i];
3054   if(s>=0) {
3055     c=(i_regs->isconst>>s)&1;
3056     if(c) {
3057       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3058     }
3059   }
3060   assert(tl>=0);
3061   assert(temp>=0);
3062   if(!c) {
3063     emit_cmpimm(s<0||offset?temp:s,RAM_SIZE);
3064     if(!offset&&s!=temp) emit_mov(s,temp);
3065     jaddr=out;
3066     emit_jno(0);
3067   }
3068   else
3069   {
3070     if(!memtarget||!dops[i].rs1) {
3071       jaddr=out;
3072       emit_jmp(0);
3073     }
3074   }
3075   if(ram_offset)
3076     emit_addimm_no_flags(ram_offset,temp);
3077
3078   if (dops[i].opcode==0x2C||dops[i].opcode==0x2D) { // SDL/SDR
3079     assert(0);
3080   }
3081
3082   emit_xorimm(temp,3,temp);
3083   emit_testimm(temp,2);
3084   case2=out;
3085   emit_jne(0);
3086   emit_testimm(temp,1);
3087   case1=out;
3088   emit_jne(0);
3089   // 0
3090   if (dops[i].opcode==0x2A) { // SWL
3091     emit_writeword_indexed(tl,0,temp);
3092   }
3093   else if (dops[i].opcode==0x2E) { // SWR
3094     emit_writebyte_indexed(tl,3,temp);
3095   }
3096   else
3097     assert(0);
3098   done0=out;
3099   emit_jmp(0);
3100   // 1
3101   set_jump_target(case1, out);
3102   if (dops[i].opcode==0x2A) { // SWL
3103     // Write 3 msb into three least significant bytes
3104     if(dops[i].rs2) emit_rorimm(tl,8,tl);
3105     emit_writehword_indexed(tl,-1,temp);
3106     if(dops[i].rs2) emit_rorimm(tl,16,tl);
3107     emit_writebyte_indexed(tl,1,temp);
3108     if(dops[i].rs2) emit_rorimm(tl,8,tl);
3109   }
3110   else if (dops[i].opcode==0x2E) { // SWR
3111     // Write two lsb into two most significant bytes
3112     emit_writehword_indexed(tl,1,temp);
3113   }
3114   done1=out;
3115   emit_jmp(0);
3116   // 2
3117   set_jump_target(case2, out);
3118   emit_testimm(temp,1);
3119   case3=out;
3120   emit_jne(0);
3121   if (dops[i].opcode==0x2A) { // SWL
3122     // Write two msb into two least significant bytes
3123     if(dops[i].rs2) emit_rorimm(tl,16,tl);
3124     emit_writehword_indexed(tl,-2,temp);
3125     if(dops[i].rs2) emit_rorimm(tl,16,tl);
3126   }
3127   else if (dops[i].opcode==0x2E) { // SWR
3128     // Write 3 lsb into three most significant bytes
3129     emit_writebyte_indexed(tl,-1,temp);
3130     if(dops[i].rs2) emit_rorimm(tl,8,tl);
3131     emit_writehword_indexed(tl,0,temp);
3132     if(dops[i].rs2) emit_rorimm(tl,24,tl);
3133   }
3134   done2=out;
3135   emit_jmp(0);
3136   // 3
3137   set_jump_target(case3, out);
3138   if (dops[i].opcode==0x2A) { // SWL
3139     // Write msb into least significant byte
3140     if(dops[i].rs2) emit_rorimm(tl,24,tl);
3141     emit_writebyte_indexed(tl,-3,temp);
3142     if(dops[i].rs2) emit_rorimm(tl,8,tl);
3143   }
3144   else if (dops[i].opcode==0x2E) { // SWR
3145     // Write entire word
3146     emit_writeword_indexed(tl,-3,temp);
3147   }
3148   set_jump_target(done0, out);
3149   set_jump_target(done1, out);
3150   set_jump_target(done2, out);
3151   if(!c||!memtarget)
3152     add_stub_r(STORELR_STUB,jaddr,out,i,temp,i_regs,ccadj[i],reglist);
3153   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3154     emit_addimm_no_flags(-ram_offset,temp);
3155     #if defined(HOST_IMM8)
3156     int ir=get_reg(i_regs->regmap,INVCP);
3157     assert(ir>=0);
3158     emit_cmpmem_indexedsr12_reg(ir,temp,1);
3159     #else
3160     emit_cmpmem_indexedsr12_imm(invalid_code,temp,1);
3161     #endif
3162     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3163     emit_callne(invalidate_addr_reg[temp]);
3164     #else
3165     void *jaddr2 = out;
3166     emit_jne(0);
3167     add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),temp,0,0,0);
3168     #endif
3169   }
3170 }
3171
3172 static void cop0_assemble(int i,struct regstat *i_regs)
3173 {
3174   if(dops[i].opcode2==0) // MFC0
3175   {
3176     signed char t=get_reg(i_regs->regmap,dops[i].rt1);
3177     u_int copr=(source[i]>>11)&0x1f;
3178     //assert(t>=0); // Why does this happen?  OOT is weird
3179     if(t>=0&&dops[i].rt1!=0) {
3180       emit_readword(&reg_cop0[copr],t);
3181     }
3182   }
3183   else if(dops[i].opcode2==4) // MTC0
3184   {
3185     signed char s=get_reg(i_regs->regmap,dops[i].rs1);
3186     char copr=(source[i]>>11)&0x1f;
3187     assert(s>=0);
3188     wb_register(dops[i].rs1,i_regs->regmap,i_regs->dirty);
3189     if(copr==9||copr==11||copr==12||copr==13) {
3190       emit_readword(&last_count,HOST_TEMPREG);
3191       emit_loadreg(CCREG,HOST_CCREG); // TODO: do proper reg alloc
3192       emit_add(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3193       emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG);
3194       emit_writeword(HOST_CCREG,&Count);
3195     }
3196     // What a mess.  The status register (12) can enable interrupts,
3197     // so needs a special case to handle a pending interrupt.
3198     // The interrupt must be taken immediately, because a subsequent
3199     // instruction might disable interrupts again.
3200     if(copr==12||copr==13) {
3201       if (is_delayslot) {
3202         // burn cycles to cause cc_interrupt, which will
3203         // reschedule next_interupt. Relies on CCREG from above.
3204         assem_debug("MTC0 DS %d\n", copr);
3205         emit_writeword(HOST_CCREG,&last_count);
3206         emit_movimm(0,HOST_CCREG);
3207         emit_storereg(CCREG,HOST_CCREG);
3208         emit_loadreg(dops[i].rs1,1);
3209         emit_movimm(copr,0);
3210         emit_far_call(pcsx_mtc0_ds);
3211         emit_loadreg(dops[i].rs1,s);
3212         return;
3213       }
3214       emit_movimm(start+i*4+4,HOST_TEMPREG);
3215       emit_writeword(HOST_TEMPREG,&pcaddr);
3216       emit_movimm(0,HOST_TEMPREG);
3217       emit_writeword(HOST_TEMPREG,&pending_exception);
3218     }
3219     if(s==HOST_CCREG)
3220       emit_loadreg(dops[i].rs1,1);
3221     else if(s!=1)
3222       emit_mov(s,1);
3223     emit_movimm(copr,0);
3224     emit_far_call(pcsx_mtc0);
3225     if(copr==9||copr==11||copr==12||copr==13) {
3226       emit_readword(&Count,HOST_CCREG);
3227       emit_readword(&next_interupt,HOST_TEMPREG);
3228       emit_addimm(HOST_CCREG,-CLOCK_ADJUST(ccadj[i]),HOST_CCREG);
3229       emit_sub(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3230       emit_writeword(HOST_TEMPREG,&last_count);
3231       emit_storereg(CCREG,HOST_CCREG);
3232     }
3233     if(copr==12||copr==13) {
3234       assert(!is_delayslot);
3235       emit_readword(&pending_exception,14);
3236       emit_test(14,14);
3237       void *jaddr = out;
3238       emit_jeq(0);
3239       emit_readword(&pcaddr, 0);
3240       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3241       emit_far_call(get_addr_ht);
3242       emit_jmpreg(0);
3243       set_jump_target(jaddr, out);
3244     }
3245     emit_loadreg(dops[i].rs1,s);
3246   }
3247   else
3248   {
3249     assert(dops[i].opcode2==0x10);
3250     //if((source[i]&0x3f)==0x10) // RFE
3251     {
3252       emit_readword(&Status,0);
3253       emit_andimm(0,0x3c,1);
3254       emit_andimm(0,~0xf,0);
3255       emit_orrshr_imm(1,2,0);
3256       emit_writeword(0,&Status);
3257     }
3258   }
3259 }
3260
3261 static void cop1_unusable(int i,struct regstat *i_regs)
3262 {
3263   // XXX: should just just do the exception instead
3264   //if(!cop1_usable)
3265   {
3266     void *jaddr=out;
3267     emit_jmp(0);
3268     add_stub_r(FP_STUB,jaddr,out,i,0,i_regs,is_delayslot,0);
3269   }
3270 }
3271
3272 static void cop1_assemble(int i,struct regstat *i_regs)
3273 {
3274   cop1_unusable(i, i_regs);
3275 }
3276
3277 static void c1ls_assemble(int i,struct regstat *i_regs)
3278 {
3279   cop1_unusable(i, i_regs);
3280 }
3281
3282 // FP_STUB
3283 static void do_cop1stub(int n)
3284 {
3285   literal_pool(256);
3286   assem_debug("do_cop1stub %x\n",start+stubs[n].a*4);
3287   set_jump_target(stubs[n].addr, out);
3288   int i=stubs[n].a;
3289 //  int rs=stubs[n].b;
3290   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3291   int ds=stubs[n].d;
3292   if(!ds) {
3293     load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3294     //if(i_regs!=&regs[i]) printf("oops: regs[i]=%x i_regs=%x",(int)&regs[i],(int)i_regs);
3295   }
3296   //else {printf("fp exception in delay slot\n");}
3297   wb_dirtys(i_regs->regmap_entry,i_regs->wasdirty);
3298   if(regs[i].regmap_entry[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
3299   emit_movimm(start+(i-ds)*4,EAX); // Get PC
3300   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG); // CHECK: is this right?  There should probably be an extra cycle...
3301   emit_far_jump(ds?fp_exception_ds:fp_exception);
3302 }
3303
3304 static int cop2_is_stalling_op(int i, int *cycles)
3305 {
3306   if (dops[i].opcode == 0x3a) { // SWC2
3307     *cycles = 0;
3308     return 1;
3309   }
3310   if (dops[i].itype == COP2 && (dops[i].opcode2 == 0 || dops[i].opcode2 == 2)) { // MFC2/CFC2
3311     *cycles = 0;
3312     return 1;
3313   }
3314   if (dops[i].itype == C2OP) {
3315     *cycles = gte_cycletab[source[i] & 0x3f];
3316     return 1;
3317   }
3318   // ... what about MTC2/CTC2/LWC2?
3319   return 0;
3320 }
3321
3322 #if 0
3323 static void log_gte_stall(int stall, u_int cycle)
3324 {
3325   if ((u_int)stall <= 44)
3326     printf("x    stall %2d %u\n", stall, cycle + last_count);
3327 }
3328
3329 static void emit_log_gte_stall(int i, int stall, u_int reglist)
3330 {
3331   save_regs(reglist);
3332   if (stall > 0)
3333     emit_movimm(stall, 0);
3334   else
3335     emit_mov(HOST_TEMPREG, 0);
3336   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]), 1);
3337   emit_far_call(log_gte_stall);
3338   restore_regs(reglist);
3339 }
3340 #endif
3341
3342 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist)
3343 {
3344   int j = i, other_gte_op_cycles = -1, stall = -MAXBLOCK, cycles_passed;
3345   int rtmp = reglist_find_free(reglist);
3346
3347   if (HACK_ENABLED(NDHACK_NO_STALLS))
3348     return;
3349   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3350     // happens occasionally... cc evicted? Don't bother then
3351     //printf("no cc %08x\n", start + i*4);
3352     return;
3353   }
3354   if (!dops[i].bt) {
3355     for (j = i - 1; j >= 0; j--) {
3356       //if (dops[j].is_ds) break;
3357       if (cop2_is_stalling_op(j, &other_gte_op_cycles) || dops[j].bt)
3358         break;
3359     }
3360     j = max(j, 0);
3361   }
3362   cycles_passed = CLOCK_ADJUST(ccadj[i] - ccadj[j]);
3363   if (other_gte_op_cycles >= 0)
3364     stall = other_gte_op_cycles - cycles_passed;
3365   else if (cycles_passed >= 44)
3366     stall = 0; // can't stall
3367   if (stall == -MAXBLOCK && rtmp >= 0) {
3368     // unknown stall, do the expensive runtime check
3369     assem_debug("; cop2_do_stall_check\n");
3370 #if 0 // too slow
3371     save_regs(reglist);
3372     emit_movimm(gte_cycletab[op], 0);
3373     emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]), 1);
3374     emit_far_call(call_gteStall);
3375     restore_regs(reglist);
3376 #else
3377     host_tempreg_acquire();
3378     emit_readword(&psxRegs.gteBusyCycle, rtmp);
3379     emit_addimm(rtmp, -CLOCK_ADJUST(ccadj[i]), rtmp);
3380     emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3381     emit_cmpimm(HOST_TEMPREG, 44);
3382     emit_cmovb_reg(rtmp, HOST_CCREG);
3383     //emit_log_gte_stall(i, 0, reglist);
3384     host_tempreg_release();
3385 #endif
3386   }
3387   else if (stall > 0) {
3388     //emit_log_gte_stall(i, stall, reglist);
3389     emit_addimm(HOST_CCREG, stall, HOST_CCREG);
3390   }
3391
3392   // save gteBusyCycle, if needed
3393   if (gte_cycletab[op] == 0)
3394     return;
3395   other_gte_op_cycles = -1;
3396   for (j = i + 1; j < slen; j++) {
3397     if (cop2_is_stalling_op(j, &other_gte_op_cycles))
3398       break;
3399     if (is_jump(j)) {
3400       // check ds
3401       if (j + 1 < slen && cop2_is_stalling_op(j + 1, &other_gte_op_cycles))
3402         j++;
3403       break;
3404     }
3405   }
3406   if (other_gte_op_cycles >= 0)
3407     // will handle stall when assembling that op
3408     return;
3409   cycles_passed = CLOCK_ADJUST(ccadj[min(j, slen -1)] - ccadj[i]);
3410   if (cycles_passed >= 44)
3411     return;
3412   assem_debug("; save gteBusyCycle\n");
3413   host_tempreg_acquire();
3414 #if 0
3415   emit_readword(&last_count, HOST_TEMPREG);
3416   emit_add(HOST_TEMPREG, HOST_CCREG, HOST_TEMPREG);
3417   emit_addimm(HOST_TEMPREG, CLOCK_ADJUST(ccadj[i]), HOST_TEMPREG);
3418   emit_addimm(HOST_TEMPREG, gte_cycletab[op]), HOST_TEMPREG);
3419   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3420 #else
3421   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]) + gte_cycletab[op], HOST_TEMPREG);
3422   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3423 #endif
3424   host_tempreg_release();
3425 }
3426
3427 static int is_mflohi(int i)
3428 {
3429   return (dops[i].itype == MOV && (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG));
3430 }
3431
3432 static int check_multdiv(int i, int *cycles)
3433 {
3434   if (dops[i].itype != MULTDIV)
3435     return 0;
3436   if (dops[i].opcode2 == 0x18 || dops[i].opcode2 == 0x19) // MULT(U)
3437     *cycles = 11; // approx from 7 11 14
3438   else
3439     *cycles = 37;
3440   return 1;
3441 }
3442
3443 static void multdiv_prepare_stall(int i, const struct regstat *i_regs)
3444 {
3445   int j, found = 0, c = 0;
3446   if (HACK_ENABLED(NDHACK_NO_STALLS))
3447     return;
3448   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3449     // happens occasionally... cc evicted? Don't bother then
3450     return;
3451   }
3452   for (j = i + 1; j < slen; j++) {
3453     if (dops[j].bt)
3454       break;
3455     if ((found = is_mflohi(j)))
3456       break;
3457     if (is_jump(j)) {
3458       // check ds
3459       if (j + 1 < slen && (found = is_mflohi(j + 1)))
3460         j++;
3461       break;
3462     }
3463   }
3464   if (found)
3465     // handle all in multdiv_do_stall()
3466     return;
3467   check_multdiv(i, &c);
3468   assert(c > 0);
3469   assem_debug("; muldiv prepare stall %d\n", c);
3470   host_tempreg_acquire();
3471   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]) + c, HOST_TEMPREG);
3472   emit_writeword(HOST_TEMPREG, &psxRegs.muldivBusyCycle);
3473   host_tempreg_release();
3474 }
3475
3476 static void multdiv_do_stall(int i, const struct regstat *i_regs)
3477 {
3478   int j, known_cycles = 0;
3479   u_int reglist = get_host_reglist(i_regs->regmap);
3480   int rtmp = get_reg(i_regs->regmap, -1);
3481   if (rtmp < 0)
3482     rtmp = reglist_find_free(reglist);
3483   if (HACK_ENABLED(NDHACK_NO_STALLS))
3484     return;
3485   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG || rtmp < 0) {
3486     // happens occasionally... cc evicted? Don't bother then
3487     //printf("no cc/rtmp %08x\n", start + i*4);
3488     return;
3489   }
3490   if (!dops[i].bt) {
3491     for (j = i - 1; j >= 0; j--) {
3492       if (dops[j].is_ds) break;
3493       if (check_multdiv(j, &known_cycles) || dops[j].bt)
3494         break;
3495       if (is_mflohi(j))
3496         // already handled by this op
3497         return;
3498     }
3499     j = max(j, 0);
3500   }
3501   if (known_cycles > 0) {
3502     known_cycles -= CLOCK_ADJUST(ccadj[i] - ccadj[j]);
3503     assem_debug("; muldiv stall resolved %d\n", known_cycles);
3504     if (known_cycles > 0)
3505       emit_addimm(HOST_CCREG, known_cycles, HOST_CCREG);
3506     return;
3507   }
3508   assem_debug("; muldiv stall unresolved\n");
3509   host_tempreg_acquire();
3510   emit_readword(&psxRegs.muldivBusyCycle, rtmp);
3511   emit_addimm(rtmp, -CLOCK_ADJUST(ccadj[i]), rtmp);
3512   emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3513   emit_cmpimm(HOST_TEMPREG, 37);
3514   emit_cmovb_reg(rtmp, HOST_CCREG);
3515   //emit_log_gte_stall(i, 0, reglist);
3516   host_tempreg_release();
3517 }
3518
3519 static void cop2_get_dreg(u_int copr,signed char tl,signed char temp)
3520 {
3521   switch (copr) {
3522     case 1:
3523     case 3:
3524     case 5:
3525     case 8:
3526     case 9:
3527     case 10:
3528     case 11:
3529       emit_readword(&reg_cop2d[copr],tl);
3530       emit_signextend16(tl,tl);
3531       emit_writeword(tl,&reg_cop2d[copr]); // hmh
3532       break;
3533     case 7:
3534     case 16:
3535     case 17:
3536     case 18:
3537     case 19:
3538       emit_readword(&reg_cop2d[copr],tl);
3539       emit_andimm(tl,0xffff,tl);
3540       emit_writeword(tl,&reg_cop2d[copr]);
3541       break;
3542     case 15:
3543       emit_readword(&reg_cop2d[14],tl); // SXY2
3544       emit_writeword(tl,&reg_cop2d[copr]);
3545       break;
3546     case 28:
3547     case 29:
3548       c2op_mfc2_29_assemble(tl,temp);
3549       break;
3550     default:
3551       emit_readword(&reg_cop2d[copr],tl);
3552       break;
3553   }
3554 }
3555
3556 static void cop2_put_dreg(u_int copr,signed char sl,signed char temp)
3557 {
3558   switch (copr) {
3559     case 15:
3560       emit_readword(&reg_cop2d[13],temp);  // SXY1
3561       emit_writeword(sl,&reg_cop2d[copr]);
3562       emit_writeword(temp,&reg_cop2d[12]); // SXY0
3563       emit_readword(&reg_cop2d[14],temp);  // SXY2
3564       emit_writeword(sl,&reg_cop2d[14]);
3565       emit_writeword(temp,&reg_cop2d[13]); // SXY1
3566       break;
3567     case 28:
3568       emit_andimm(sl,0x001f,temp);
3569       emit_shlimm(temp,7,temp);
3570       emit_writeword(temp,&reg_cop2d[9]);
3571       emit_andimm(sl,0x03e0,temp);
3572       emit_shlimm(temp,2,temp);
3573       emit_writeword(temp,&reg_cop2d[10]);
3574       emit_andimm(sl,0x7c00,temp);
3575       emit_shrimm(temp,3,temp);
3576       emit_writeword(temp,&reg_cop2d[11]);
3577       emit_writeword(sl,&reg_cop2d[28]);
3578       break;
3579     case 30:
3580       emit_xorsar_imm(sl,sl,31,temp);
3581 #if defined(HAVE_ARMV5) || defined(__aarch64__)
3582       emit_clz(temp,temp);
3583 #else
3584       emit_movs(temp,HOST_TEMPREG);
3585       emit_movimm(0,temp);
3586       emit_jeq((int)out+4*4);
3587       emit_addpl_imm(temp,1,temp);
3588       emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
3589       emit_jns((int)out-2*4);
3590 #endif
3591       emit_writeword(sl,&reg_cop2d[30]);
3592       emit_writeword(temp,&reg_cop2d[31]);
3593       break;
3594     case 31:
3595       break;
3596     default:
3597       emit_writeword(sl,&reg_cop2d[copr]);
3598       break;
3599   }
3600 }
3601
3602 static void c2ls_assemble(int i, const struct regstat *i_regs)
3603 {
3604   int s,tl;
3605   int ar;
3606   int offset;
3607   int memtarget=0,c=0;
3608   void *jaddr2=NULL;
3609   enum stub_type type;
3610   int agr=AGEN1+(i&1);
3611   int fastio_reg_override=-1;
3612   u_int reglist=get_host_reglist(i_regs->regmap);
3613   u_int copr=(source[i]>>16)&0x1f;
3614   s=get_reg(i_regs->regmap,dops[i].rs1);
3615   tl=get_reg(i_regs->regmap,FTEMP);
3616   offset=imm[i];
3617   assert(dops[i].rs1>0);
3618   assert(tl>=0);
3619
3620   if(i_regs->regmap[HOST_CCREG]==CCREG)
3621     reglist&=~(1<<HOST_CCREG);
3622
3623   // get the address
3624   if (dops[i].opcode==0x3a) { // SWC2
3625     ar=get_reg(i_regs->regmap,agr);
3626     if(ar<0) ar=get_reg(i_regs->regmap,-1);
3627     reglist|=1<<ar;
3628   } else { // LWC2
3629     ar=tl;
3630   }
3631   if(s>=0) c=(i_regs->wasconst>>s)&1;
3632   memtarget=c&&(((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE);
3633   if (!offset&&!c&&s>=0) ar=s;
3634   assert(ar>=0);
3635
3636   cop2_do_stall_check(0, i, i_regs, reglist);
3637
3638   if (dops[i].opcode==0x3a) { // SWC2
3639     cop2_get_dreg(copr,tl,-1);
3640     type=STOREW_STUB;
3641   }
3642   else
3643     type=LOADW_STUB;
3644
3645   if(c&&!memtarget) {
3646     jaddr2=out;
3647     emit_jmp(0); // inline_readstub/inline_writestub?
3648   }
3649   else {
3650     if(!c) {
3651       jaddr2=emit_fastpath_cmp_jump(i,ar,&fastio_reg_override);
3652     }
3653     else if(ram_offset&&memtarget) {
3654       host_tempreg_acquire();
3655       emit_addimm(ar,ram_offset,HOST_TEMPREG);
3656       fastio_reg_override=HOST_TEMPREG;
3657     }
3658     if (dops[i].opcode==0x32) { // LWC2
3659       int a=ar;
3660       if(fastio_reg_override>=0) a=fastio_reg_override;
3661       emit_readword_indexed(0,a,tl);
3662     }
3663     if (dops[i].opcode==0x3a) { // SWC2
3664       #ifdef DESTRUCTIVE_SHIFT
3665       if(!offset&&!c&&s>=0) emit_mov(s,ar);
3666       #endif
3667       int a=ar;
3668       if(fastio_reg_override>=0) a=fastio_reg_override;
3669       emit_writeword_indexed(tl,0,a);
3670     }
3671   }
3672   if(fastio_reg_override==HOST_TEMPREG)
3673     host_tempreg_release();
3674   if(jaddr2)
3675     add_stub_r(type,jaddr2,out,i,ar,i_regs,ccadj[i],reglist);
3676   if(dops[i].opcode==0x3a) // SWC2
3677   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3678 #if defined(HOST_IMM8)
3679     int ir=get_reg(i_regs->regmap,INVCP);
3680     assert(ir>=0);
3681     emit_cmpmem_indexedsr12_reg(ir,ar,1);
3682 #else
3683     emit_cmpmem_indexedsr12_imm(invalid_code,ar,1);
3684 #endif
3685     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3686     emit_callne(invalidate_addr_reg[ar]);
3687     #else
3688     void *jaddr3 = out;
3689     emit_jne(0);
3690     add_stub(INVCODE_STUB,jaddr3,out,reglist|(1<<HOST_CCREG),ar,0,0,0);
3691     #endif
3692   }
3693   if (dops[i].opcode==0x32) { // LWC2
3694     host_tempreg_acquire();
3695     cop2_put_dreg(copr,tl,HOST_TEMPREG);
3696     host_tempreg_release();
3697   }
3698 }
3699
3700 static void cop2_assemble(int i, const struct regstat *i_regs)
3701 {
3702   u_int copr = (source[i]>>11) & 0x1f;
3703   signed char temp = get_reg(i_regs->regmap, -1);
3704
3705   if (!HACK_ENABLED(NDHACK_NO_STALLS)) {
3706     u_int reglist = reglist_exclude(get_host_reglist(i_regs->regmap), temp, -1);
3707     if (dops[i].opcode2 == 0 || dops[i].opcode2 == 2) { // MFC2/CFC2
3708       signed char tl = get_reg(i_regs->regmap, dops[i].rt1);
3709       reglist = reglist_exclude(reglist, tl, -1);
3710     }
3711     cop2_do_stall_check(0, i, i_regs, reglist);
3712   }
3713   if (dops[i].opcode2==0) { // MFC2
3714     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
3715     if(tl>=0&&dops[i].rt1!=0)
3716       cop2_get_dreg(copr,tl,temp);
3717   }
3718   else if (dops[i].opcode2==4) { // MTC2
3719     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
3720     cop2_put_dreg(copr,sl,temp);
3721   }
3722   else if (dops[i].opcode2==2) // CFC2
3723   {
3724     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
3725     if(tl>=0&&dops[i].rt1!=0)
3726       emit_readword(&reg_cop2c[copr],tl);
3727   }
3728   else if (dops[i].opcode2==6) // CTC2
3729   {
3730     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
3731     switch(copr) {
3732       case 4:
3733       case 12:
3734       case 20:
3735       case 26:
3736       case 27:
3737       case 29:
3738       case 30:
3739         emit_signextend16(sl,temp);
3740         break;
3741       case 31:
3742         c2op_ctc2_31_assemble(sl,temp);
3743         break;
3744       default:
3745         temp=sl;
3746         break;
3747     }
3748     emit_writeword(temp,&reg_cop2c[copr]);
3749     assert(sl>=0);
3750   }
3751 }
3752
3753 static void do_unalignedwritestub(int n)
3754 {
3755   assem_debug("do_unalignedwritestub %x\n",start+stubs[n].a*4);
3756   literal_pool(256);
3757   set_jump_target(stubs[n].addr, out);
3758
3759   int i=stubs[n].a;
3760   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3761   int addr=stubs[n].b;
3762   u_int reglist=stubs[n].e;
3763   signed char *i_regmap=i_regs->regmap;
3764   int temp2=get_reg(i_regmap,FTEMP);
3765   int rt;
3766   rt=get_reg(i_regmap,dops[i].rs2);
3767   assert(rt>=0);
3768   assert(addr>=0);
3769   assert(dops[i].opcode==0x2a||dops[i].opcode==0x2e); // SWL/SWR only implemented
3770   reglist|=(1<<addr);
3771   reglist&=~(1<<temp2);
3772
3773   // don't bother with it and call write handler
3774   save_regs(reglist);
3775   pass_args(addr,rt);
3776   int cc=get_reg(i_regmap,CCREG);
3777   if(cc<0)
3778     emit_loadreg(CCREG,2);
3779   emit_addimm(cc<0?2:cc,CLOCK_ADJUST((int)stubs[n].d+1),2);
3780   emit_far_call((dops[i].opcode==0x2a?jump_handle_swl:jump_handle_swr));
3781   emit_addimm(0,-CLOCK_ADJUST((int)stubs[n].d+1),cc<0?2:cc);
3782   if(cc<0)
3783     emit_storereg(CCREG,2);
3784   restore_regs(reglist);
3785   emit_jmp(stubs[n].retaddr); // return address
3786 }
3787
3788 #ifndef multdiv_assemble
3789 void multdiv_assemble(int i,struct regstat *i_regs)
3790 {
3791   printf("Need multdiv_assemble for this architecture.\n");
3792   abort();
3793 }
3794 #endif
3795
3796 static void mov_assemble(int i,struct regstat *i_regs)
3797 {
3798   //if(dops[i].opcode2==0x10||dops[i].opcode2==0x12) { // MFHI/MFLO
3799   //if(dops[i].opcode2==0x11||dops[i].opcode2==0x13) { // MTHI/MTLO
3800   if(dops[i].rt1) {
3801     signed char sl,tl;
3802     tl=get_reg(i_regs->regmap,dops[i].rt1);
3803     //assert(tl>=0);
3804     if(tl>=0) {
3805       sl=get_reg(i_regs->regmap,dops[i].rs1);
3806       if(sl>=0) emit_mov(sl,tl);
3807       else emit_loadreg(dops[i].rs1,tl);
3808     }
3809   }
3810   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) // MFHI/MFLO
3811     multdiv_do_stall(i, i_regs);
3812 }
3813
3814 // call interpreter, exception handler, things that change pc/regs/cycles ...
3815 static void call_c_cpu_handler(int i, const struct regstat *i_regs, u_int pc, void *func)
3816 {
3817   signed char ccreg=get_reg(i_regs->regmap,CCREG);
3818   assert(ccreg==HOST_CCREG);
3819   assert(!is_delayslot);
3820   (void)ccreg;
3821
3822   emit_movimm(pc,3); // Get PC
3823   emit_readword(&last_count,2);
3824   emit_writeword(3,&psxRegs.pc);
3825   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG); // XXX
3826   emit_add(2,HOST_CCREG,2);
3827   emit_writeword(2,&psxRegs.cycle);
3828   emit_far_call(func);
3829   emit_far_jump(jump_to_new_pc);
3830 }
3831
3832 static void syscall_assemble(int i,struct regstat *i_regs)
3833 {
3834   emit_movimm(0x20,0); // cause code
3835   emit_movimm(0,1);    // not in delay slot
3836   call_c_cpu_handler(i,i_regs,start+i*4,psxException);
3837 }
3838
3839 static void hlecall_assemble(int i,struct regstat *i_regs)
3840 {
3841   void *hlefunc = psxNULL;
3842   uint32_t hleCode = source[i] & 0x03ffffff;
3843   if (hleCode < ARRAY_SIZE(psxHLEt))
3844     hlefunc = psxHLEt[hleCode];
3845
3846   call_c_cpu_handler(i,i_regs,start+i*4+4,hlefunc);
3847 }
3848
3849 static void intcall_assemble(int i,struct regstat *i_regs)
3850 {
3851   call_c_cpu_handler(i,i_regs,start+i*4,execI);
3852 }
3853
3854 static void speculate_mov(int rs,int rt)
3855 {
3856   if(rt!=0) {
3857     smrv_strong_next|=1<<rt;
3858     smrv[rt]=smrv[rs];
3859   }
3860 }
3861
3862 static void speculate_mov_weak(int rs,int rt)
3863 {
3864   if(rt!=0) {
3865     smrv_weak_next|=1<<rt;
3866     smrv[rt]=smrv[rs];
3867   }
3868 }
3869
3870 static void speculate_register_values(int i)
3871 {
3872   if(i==0) {
3873     memcpy(smrv,psxRegs.GPR.r,sizeof(smrv));
3874     // gp,sp are likely to stay the same throughout the block
3875     smrv_strong_next=(1<<28)|(1<<29)|(1<<30);
3876     smrv_weak_next=~smrv_strong_next;
3877     //printf(" llr %08x\n", smrv[4]);
3878   }
3879   smrv_strong=smrv_strong_next;
3880   smrv_weak=smrv_weak_next;
3881   switch(dops[i].itype) {
3882     case ALU:
3883       if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
3884       else if((smrv_strong>>dops[i].rs2)&1) speculate_mov(dops[i].rs2,dops[i].rt1);
3885       else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
3886       else if((smrv_weak>>dops[i].rs2)&1) speculate_mov_weak(dops[i].rs2,dops[i].rt1);
3887       else {
3888         smrv_strong_next&=~(1<<dops[i].rt1);
3889         smrv_weak_next&=~(1<<dops[i].rt1);
3890       }
3891       break;
3892     case SHIFTIMM:
3893       smrv_strong_next&=~(1<<dops[i].rt1);
3894       smrv_weak_next&=~(1<<dops[i].rt1);
3895       // fallthrough
3896     case IMM16:
3897       if(dops[i].rt1&&is_const(&regs[i],dops[i].rt1)) {
3898         int value,hr=get_reg(regs[i].regmap,dops[i].rt1);
3899         if(hr>=0) {
3900           if(get_final_value(hr,i,&value))
3901                smrv[dops[i].rt1]=value;
3902           else smrv[dops[i].rt1]=constmap[i][hr];
3903           smrv_strong_next|=1<<dops[i].rt1;
3904         }
3905       }
3906       else {
3907         if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
3908         else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
3909       }
3910       break;
3911     case LOAD:
3912       if(start<0x2000&&(dops[i].rt1==26||(smrv[dops[i].rt1]>>24)==0xa0)) {
3913         // special case for BIOS
3914         smrv[dops[i].rt1]=0xa0000000;
3915         smrv_strong_next|=1<<dops[i].rt1;
3916         break;
3917       }
3918       // fallthrough
3919     case SHIFT:
3920     case LOADLR:
3921     case MOV:
3922       smrv_strong_next&=~(1<<dops[i].rt1);
3923       smrv_weak_next&=~(1<<dops[i].rt1);
3924       break;
3925     case COP0:
3926     case COP2:
3927       if(dops[i].opcode2==0||dops[i].opcode2==2) { // MFC/CFC
3928         smrv_strong_next&=~(1<<dops[i].rt1);
3929         smrv_weak_next&=~(1<<dops[i].rt1);
3930       }
3931       break;
3932     case C2LS:
3933       if (dops[i].opcode==0x32) { // LWC2
3934         smrv_strong_next&=~(1<<dops[i].rt1);
3935         smrv_weak_next&=~(1<<dops[i].rt1);
3936       }
3937       break;
3938   }
3939 #if 0
3940   int r=4;
3941   printf("x %08x %08x %d %d c %08x %08x\n",smrv[r],start+i*4,
3942     ((smrv_strong>>r)&1),(smrv_weak>>r)&1,regs[i].isconst,regs[i].wasconst);
3943 #endif
3944 }
3945
3946 static void ds_assemble(int i,struct regstat *i_regs)
3947 {
3948   speculate_register_values(i);
3949   is_delayslot=1;
3950   switch(dops[i].itype) {
3951     case ALU:
3952       alu_assemble(i,i_regs);break;
3953     case IMM16:
3954       imm16_assemble(i,i_regs);break;
3955     case SHIFT:
3956       shift_assemble(i,i_regs);break;
3957     case SHIFTIMM:
3958       shiftimm_assemble(i,i_regs);break;
3959     case LOAD:
3960       load_assemble(i,i_regs);break;
3961     case LOADLR:
3962       loadlr_assemble(i,i_regs);break;
3963     case STORE:
3964       store_assemble(i,i_regs);break;
3965     case STORELR:
3966       storelr_assemble(i,i_regs);break;
3967     case COP0:
3968       cop0_assemble(i,i_regs);break;
3969     case COP1:
3970       cop1_assemble(i,i_regs);break;
3971     case C1LS:
3972       c1ls_assemble(i,i_regs);break;
3973     case COP2:
3974       cop2_assemble(i,i_regs);break;
3975     case C2LS:
3976       c2ls_assemble(i,i_regs);break;
3977     case C2OP:
3978       c2op_assemble(i,i_regs);break;
3979     case MULTDIV:
3980       multdiv_assemble(i,i_regs);
3981       multdiv_prepare_stall(i,i_regs);
3982       break;
3983     case MOV:
3984       mov_assemble(i,i_regs);break;
3985     case SYSCALL:
3986     case HLECALL:
3987     case INTCALL:
3988     case SPAN:
3989     case UJUMP:
3990     case RJUMP:
3991     case CJUMP:
3992     case SJUMP:
3993       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
3994   }
3995   is_delayslot=0;
3996 }
3997
3998 // Is the branch target a valid internal jump?
3999 static int internal_branch(int addr)
4000 {
4001   if(addr&1) return 0; // Indirect (register) jump
4002   if(addr>=start && addr<start+slen*4-4)
4003   {
4004     return 1;
4005   }
4006   return 0;
4007 }
4008
4009 static void wb_invalidate(signed char pre[],signed char entry[],uint64_t dirty,uint64_t u)
4010 {
4011   int hr;
4012   for(hr=0;hr<HOST_REGS;hr++) {
4013     if(hr!=EXCLUDE_REG) {
4014       if(pre[hr]!=entry[hr]) {
4015         if(pre[hr]>=0) {
4016           if((dirty>>hr)&1) {
4017             if(get_reg(entry,pre[hr])<0) {
4018               assert(pre[hr]<64);
4019               if(!((u>>pre[hr])&1))
4020                 emit_storereg(pre[hr],hr);
4021             }
4022           }
4023         }
4024       }
4025     }
4026   }
4027   // Move from one register to another (no writeback)
4028   for(hr=0;hr<HOST_REGS;hr++) {
4029     if(hr!=EXCLUDE_REG) {
4030       if(pre[hr]!=entry[hr]) {
4031         if(pre[hr]>=0&&(pre[hr]&63)<TEMPREG) {
4032           int nr;
4033           if((nr=get_reg(entry,pre[hr]))>=0) {
4034             emit_mov(hr,nr);
4035           }
4036         }
4037       }
4038     }
4039   }
4040 }
4041
4042 // Load the specified registers
4043 // This only loads the registers given as arguments because
4044 // we don't want to load things that will be overwritten
4045 static void load_regs(signed char entry[],signed char regmap[],int rs1,int rs2)
4046 {
4047   int hr;
4048   // Load 32-bit regs
4049   for(hr=0;hr<HOST_REGS;hr++) {
4050     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4051       if(entry[hr]!=regmap[hr]) {
4052         if(regmap[hr]==rs1||regmap[hr]==rs2)
4053         {
4054           if(regmap[hr]==0) {
4055             emit_zeroreg(hr);
4056           }
4057           else
4058           {
4059             emit_loadreg(regmap[hr],hr);
4060           }
4061         }
4062       }
4063     }
4064   }
4065 }
4066
4067 // Load registers prior to the start of a loop
4068 // so that they are not loaded within the loop
4069 static void loop_preload(signed char pre[],signed char entry[])
4070 {
4071   int hr;
4072   for(hr=0;hr<HOST_REGS;hr++) {
4073     if(hr!=EXCLUDE_REG) {
4074       if(pre[hr]!=entry[hr]) {
4075         if(entry[hr]>=0) {
4076           if(get_reg(pre,entry[hr])<0) {
4077             assem_debug("loop preload:\n");
4078             //printf("loop preload: %d\n",hr);
4079             if(entry[hr]==0) {
4080               emit_zeroreg(hr);
4081             }
4082             else if(entry[hr]<TEMPREG)
4083             {
4084               emit_loadreg(entry[hr],hr);
4085             }
4086             else if(entry[hr]-64<TEMPREG)
4087             {
4088               emit_loadreg(entry[hr],hr);
4089             }
4090           }
4091         }
4092       }
4093     }
4094   }
4095 }
4096
4097 // Generate address for load/store instruction
4098 // goes to AGEN for writes, FTEMP for LOADLR and cop1/2 loads
4099 void address_generation(int i,struct regstat *i_regs,signed char entry[])
4100 {
4101   if(dops[i].itype==LOAD||dops[i].itype==LOADLR||dops[i].itype==STORE||dops[i].itype==STORELR||dops[i].itype==C1LS||dops[i].itype==C2LS) {
4102     int ra=-1;
4103     int agr=AGEN1+(i&1);
4104     if(dops[i].itype==LOAD) {
4105       ra=get_reg(i_regs->regmap,dops[i].rt1);
4106       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4107       assert(ra>=0);
4108     }
4109     if(dops[i].itype==LOADLR) {
4110       ra=get_reg(i_regs->regmap,FTEMP);
4111     }
4112     if(dops[i].itype==STORE||dops[i].itype==STORELR) {
4113       ra=get_reg(i_regs->regmap,agr);
4114       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4115     }
4116     if(dops[i].itype==C1LS||dops[i].itype==C2LS) {
4117       if ((dops[i].opcode&0x3b)==0x31||(dops[i].opcode&0x3b)==0x32) // LWC1/LDC1/LWC2/LDC2
4118         ra=get_reg(i_regs->regmap,FTEMP);
4119       else { // SWC1/SDC1/SWC2/SDC2
4120         ra=get_reg(i_regs->regmap,agr);
4121         if(ra<0) ra=get_reg(i_regs->regmap,-1);
4122       }
4123     }
4124     int rs=get_reg(i_regs->regmap,dops[i].rs1);
4125     if(ra>=0) {
4126       int offset=imm[i];
4127       int c=(i_regs->wasconst>>rs)&1;
4128       if(dops[i].rs1==0) {
4129         // Using r0 as a base address
4130         if(!entry||entry[ra]!=agr) {
4131           if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4132             emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4133           }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4134             emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4135           }else{
4136             emit_movimm(offset,ra);
4137           }
4138         } // else did it in the previous cycle
4139       }
4140       else if(rs<0) {
4141         if(!entry||entry[ra]!=dops[i].rs1)
4142           emit_loadreg(dops[i].rs1,ra);
4143         //if(!entry||entry[ra]!=dops[i].rs1)
4144         //  printf("poor load scheduling!\n");
4145       }
4146       else if(c) {
4147         if(dops[i].rs1!=dops[i].rt1||dops[i].itype!=LOAD) {
4148           if(!entry||entry[ra]!=agr) {
4149             if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4150               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4151             }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4152               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4153             }else{
4154               emit_movimm(constmap[i][rs]+offset,ra);
4155               regs[i].loadedconst|=1<<ra;
4156             }
4157           } // else did it in the previous cycle
4158         } // else load_consts already did it
4159       }
4160       if(offset&&!c&&dops[i].rs1) {
4161         if(rs>=0) {
4162           emit_addimm(rs,offset,ra);
4163         }else{
4164           emit_addimm(ra,offset,ra);
4165         }
4166       }
4167     }
4168   }
4169   // Preload constants for next instruction
4170   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) {
4171     int agr,ra;
4172     // Actual address
4173     agr=AGEN1+((i+1)&1);
4174     ra=get_reg(i_regs->regmap,agr);
4175     if(ra>=0) {
4176       int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
4177       int offset=imm[i+1];
4178       int c=(regs[i+1].wasconst>>rs)&1;
4179       if(c&&(dops[i+1].rs1!=dops[i+1].rt1||dops[i+1].itype!=LOAD)) {
4180         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4181           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4182         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4183           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4184         }else{
4185           emit_movimm(constmap[i+1][rs]+offset,ra);
4186           regs[i+1].loadedconst|=1<<ra;
4187         }
4188       }
4189       else if(dops[i+1].rs1==0) {
4190         // Using r0 as a base address
4191         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4192           emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4193         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4194           emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4195         }else{
4196           emit_movimm(offset,ra);
4197         }
4198       }
4199     }
4200   }
4201 }
4202
4203 static int get_final_value(int hr, int i, int *value)
4204 {
4205   int reg=regs[i].regmap[hr];
4206   while(i<slen-1) {
4207     if(regs[i+1].regmap[hr]!=reg) break;
4208     if(!((regs[i+1].isconst>>hr)&1)) break;
4209     if(dops[i+1].bt) break;
4210     i++;
4211   }
4212   if(i<slen-1) {
4213     if(dops[i].itype==UJUMP||dops[i].itype==RJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP) {
4214       *value=constmap[i][hr];
4215       return 1;
4216     }
4217     if(!dops[i+1].bt) {
4218       if(dops[i+1].itype==UJUMP||dops[i+1].itype==RJUMP||dops[i+1].itype==CJUMP||dops[i+1].itype==SJUMP) {
4219         // Load in delay slot, out-of-order execution
4220         if(dops[i+2].itype==LOAD&&dops[i+2].rs1==reg&&dops[i+2].rt1==reg&&((regs[i+1].wasconst>>hr)&1))
4221         {
4222           // Precompute load address
4223           *value=constmap[i][hr]+imm[i+2];
4224           return 1;
4225         }
4226       }
4227       if(dops[i+1].itype==LOAD&&dops[i+1].rs1==reg&&dops[i+1].rt1==reg)
4228       {
4229         // Precompute load address
4230         *value=constmap[i][hr]+imm[i+1];
4231         //printf("c=%x imm=%lx\n",(long)constmap[i][hr],imm[i+1]);
4232         return 1;
4233       }
4234     }
4235   }
4236   *value=constmap[i][hr];
4237   //printf("c=%lx\n",(long)constmap[i][hr]);
4238   if(i==slen-1) return 1;
4239   assert(reg < 64);
4240   return !((unneeded_reg[i+1]>>reg)&1);
4241 }
4242
4243 // Load registers with known constants
4244 static void load_consts(signed char pre[],signed char regmap[],int i)
4245 {
4246   int hr,hr2;
4247   // propagate loaded constant flags
4248   if(i==0||dops[i].bt)
4249     regs[i].loadedconst=0;
4250   else {
4251     for(hr=0;hr<HOST_REGS;hr++) {
4252       if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((regs[i-1].isconst>>hr)&1)&&pre[hr]==regmap[hr]
4253          &&regmap[hr]==regs[i-1].regmap[hr]&&((regs[i-1].loadedconst>>hr)&1))
4254       {
4255         regs[i].loadedconst|=1<<hr;
4256       }
4257     }
4258   }
4259   // Load 32-bit regs
4260   for(hr=0;hr<HOST_REGS;hr++) {
4261     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4262       //if(entry[hr]!=regmap[hr]) {
4263       if(!((regs[i].loadedconst>>hr)&1)) {
4264         assert(regmap[hr]<64);
4265         if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4266           int value,similar=0;
4267           if(get_final_value(hr,i,&value)) {
4268             // see if some other register has similar value
4269             for(hr2=0;hr2<HOST_REGS;hr2++) {
4270               if(hr2!=EXCLUDE_REG&&((regs[i].loadedconst>>hr2)&1)) {
4271                 if(is_similar_value(value,constmap[i][hr2])) {
4272                   similar=1;
4273                   break;
4274                 }
4275               }
4276             }
4277             if(similar) {
4278               int value2;
4279               if(get_final_value(hr2,i,&value2)) // is this needed?
4280                 emit_movimm_from(value2,hr2,value,hr);
4281               else
4282                 emit_movimm(value,hr);
4283             }
4284             else if(value==0) {
4285               emit_zeroreg(hr);
4286             }
4287             else {
4288               emit_movimm(value,hr);
4289             }
4290           }
4291           regs[i].loadedconst|=1<<hr;
4292         }
4293       }
4294     }
4295   }
4296 }
4297
4298 void load_all_consts(signed char regmap[], u_int dirty, int i)
4299 {
4300   int hr;
4301   // Load 32-bit regs
4302   for(hr=0;hr<HOST_REGS;hr++) {
4303     if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((dirty>>hr)&1)) {
4304       assert(regmap[hr] < 64);
4305       if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4306         int value=constmap[i][hr];
4307         if(value==0) {
4308           emit_zeroreg(hr);
4309         }
4310         else {
4311           emit_movimm(value,hr);
4312         }
4313       }
4314     }
4315   }
4316 }
4317
4318 // Write out all dirty registers (except cycle count)
4319 static void wb_dirtys(signed char i_regmap[],uint64_t i_dirty)
4320 {
4321   int hr;
4322   for(hr=0;hr<HOST_REGS;hr++) {
4323     if(hr!=EXCLUDE_REG) {
4324       if(i_regmap[hr]>0) {
4325         if(i_regmap[hr]!=CCREG) {
4326           if((i_dirty>>hr)&1) {
4327             assert(i_regmap[hr]<64);
4328             emit_storereg(i_regmap[hr],hr);
4329           }
4330         }
4331       }
4332     }
4333   }
4334 }
4335
4336 // Write out dirty registers that we need to reload (pair with load_needed_regs)
4337 // This writes the registers not written by store_regs_bt
4338 void wb_needed_dirtys(signed char i_regmap[],uint64_t i_dirty,int addr)
4339 {
4340   int hr;
4341   int t=(addr-start)>>2;
4342   for(hr=0;hr<HOST_REGS;hr++) {
4343     if(hr!=EXCLUDE_REG) {
4344       if(i_regmap[hr]>0) {
4345         if(i_regmap[hr]!=CCREG) {
4346           if(i_regmap[hr]==regs[t].regmap_entry[hr] && ((regs[t].dirty>>hr)&1)) {
4347             if((i_dirty>>hr)&1) {
4348               assert(i_regmap[hr]<64);
4349               emit_storereg(i_regmap[hr],hr);
4350             }
4351           }
4352         }
4353       }
4354     }
4355   }
4356 }
4357
4358 // Load all registers (except cycle count)
4359 void load_all_regs(signed char i_regmap[])
4360 {
4361   int hr;
4362   for(hr=0;hr<HOST_REGS;hr++) {
4363     if(hr!=EXCLUDE_REG) {
4364       if(i_regmap[hr]==0) {
4365         emit_zeroreg(hr);
4366       }
4367       else
4368       if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4369       {
4370         emit_loadreg(i_regmap[hr],hr);
4371       }
4372     }
4373   }
4374 }
4375
4376 // Load all current registers also needed by next instruction
4377 void load_needed_regs(signed char i_regmap[],signed char next_regmap[])
4378 {
4379   int hr;
4380   for(hr=0;hr<HOST_REGS;hr++) {
4381     if(hr!=EXCLUDE_REG) {
4382       if(get_reg(next_regmap,i_regmap[hr])>=0) {
4383         if(i_regmap[hr]==0) {
4384           emit_zeroreg(hr);
4385         }
4386         else
4387         if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4388         {
4389           emit_loadreg(i_regmap[hr],hr);
4390         }
4391       }
4392     }
4393   }
4394 }
4395
4396 // Load all regs, storing cycle count if necessary
4397 void load_regs_entry(int t)
4398 {
4399   int hr;
4400   if(dops[t].is_ds) emit_addimm(HOST_CCREG,CLOCK_ADJUST(1),HOST_CCREG);
4401   else if(ccadj[t]) emit_addimm(HOST_CCREG,-CLOCK_ADJUST(ccadj[t]),HOST_CCREG);
4402   if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4403     emit_storereg(CCREG,HOST_CCREG);
4404   }
4405   // Load 32-bit regs
4406   for(hr=0;hr<HOST_REGS;hr++) {
4407     if(regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4408       if(regs[t].regmap_entry[hr]==0) {
4409         emit_zeroreg(hr);
4410       }
4411       else if(regs[t].regmap_entry[hr]!=CCREG)
4412       {
4413         emit_loadreg(regs[t].regmap_entry[hr],hr);
4414       }
4415     }
4416   }
4417 }
4418
4419 // Store dirty registers prior to branch
4420 void store_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4421 {
4422   if(internal_branch(addr))
4423   {
4424     int t=(addr-start)>>2;
4425     int hr;
4426     for(hr=0;hr<HOST_REGS;hr++) {
4427       if(hr!=EXCLUDE_REG) {
4428         if(i_regmap[hr]>0 && i_regmap[hr]!=CCREG) {
4429           if(i_regmap[hr]!=regs[t].regmap_entry[hr] || !((regs[t].dirty>>hr)&1)) {
4430             if((i_dirty>>hr)&1) {
4431               assert(i_regmap[hr]<64);
4432               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4433                 emit_storereg(i_regmap[hr],hr);
4434             }
4435           }
4436         }
4437       }
4438     }
4439   }
4440   else
4441   {
4442     // Branch out of this block, write out all dirty regs
4443     wb_dirtys(i_regmap,i_dirty);
4444   }
4445 }
4446
4447 // Load all needed registers for branch target
4448 static void load_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4449 {
4450   //if(addr>=start && addr<(start+slen*4))
4451   if(internal_branch(addr))
4452   {
4453     int t=(addr-start)>>2;
4454     int hr;
4455     // Store the cycle count before loading something else
4456     if(i_regmap[HOST_CCREG]!=CCREG) {
4457       assert(i_regmap[HOST_CCREG]==-1);
4458     }
4459     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4460       emit_storereg(CCREG,HOST_CCREG);
4461     }
4462     // Load 32-bit regs
4463     for(hr=0;hr<HOST_REGS;hr++) {
4464       if(hr!=EXCLUDE_REG&&regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4465         if(i_regmap[hr]!=regs[t].regmap_entry[hr]) {
4466           if(regs[t].regmap_entry[hr]==0) {
4467             emit_zeroreg(hr);
4468           }
4469           else if(regs[t].regmap_entry[hr]!=CCREG)
4470           {
4471             emit_loadreg(regs[t].regmap_entry[hr],hr);
4472           }
4473         }
4474       }
4475     }
4476   }
4477 }
4478
4479 static int match_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4480 {
4481   if(addr>=start && addr<start+slen*4-4)
4482   {
4483     int t=(addr-start)>>2;
4484     int hr;
4485     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) return 0;
4486     for(hr=0;hr<HOST_REGS;hr++)
4487     {
4488       if(hr!=EXCLUDE_REG)
4489       {
4490         if(i_regmap[hr]!=regs[t].regmap_entry[hr])
4491         {
4492           if(regs[t].regmap_entry[hr]>=0&&(regs[t].regmap_entry[hr]|64)<TEMPREG+64)
4493           {
4494             return 0;
4495           }
4496           else
4497           if((i_dirty>>hr)&1)
4498           {
4499             if(i_regmap[hr]<TEMPREG)
4500             {
4501               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4502                 return 0;
4503             }
4504             else if(i_regmap[hr]>=64&&i_regmap[hr]<TEMPREG+64)
4505             {
4506               assert(0);
4507             }
4508           }
4509         }
4510         else // Same register but is it 32-bit or dirty?
4511         if(i_regmap[hr]>=0)
4512         {
4513           if(!((regs[t].dirty>>hr)&1))
4514           {
4515             if((i_dirty>>hr)&1)
4516             {
4517               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4518               {
4519                 //printf("%x: dirty no match\n",addr);
4520                 return 0;
4521               }
4522             }
4523           }
4524         }
4525       }
4526     }
4527     // Delay slots are not valid branch targets
4528     //if(t>0&&(dops[t-1].itype==RJUMP||dops[t-1].itype==UJUMP||dops[t-1].itype==CJUMP||dops[t-1].itype==SJUMP)) return 0;
4529     // Delay slots require additional processing, so do not match
4530     if(dops[t].is_ds) return 0;
4531   }
4532   else
4533   {
4534     int hr;
4535     for(hr=0;hr<HOST_REGS;hr++)
4536     {
4537       if(hr!=EXCLUDE_REG)
4538       {
4539         if(i_regmap[hr]>=0)
4540         {
4541           if(hr!=HOST_CCREG||i_regmap[hr]!=CCREG)
4542           {
4543             if((i_dirty>>hr)&1)
4544             {
4545               return 0;
4546             }
4547           }
4548         }
4549       }
4550     }
4551   }
4552   return 1;
4553 }
4554
4555 #ifdef DRC_DBG
4556 static void drc_dbg_emit_do_cmp(int i)
4557 {
4558   extern void do_insn_cmp();
4559   //extern int cycle;
4560   u_int hr, reglist = get_host_reglist(regs[i].regmap);
4561
4562   assem_debug("//do_insn_cmp %08x\n", start+i*4);
4563   save_regs(reglist);
4564   // write out changed consts to match the interpreter
4565   if (i > 0 && !dops[i].bt) {
4566     for (hr = 0; hr < HOST_REGS; hr++) {
4567       int reg = regs[i-1].regmap[hr];
4568       if (hr == EXCLUDE_REG || reg < 0)
4569         continue;
4570       if (!((regs[i-1].isconst >> hr) & 1))
4571         continue;
4572       if (i > 1 && reg == regs[i-2].regmap[hr] && constmap[i-1][hr] == constmap[i-2][hr])
4573         continue;
4574       emit_movimm(constmap[i-1][hr],0);
4575       emit_storereg(reg, 0);
4576     }
4577   }
4578   emit_movimm(start+i*4,0);
4579   emit_writeword(0,&pcaddr);
4580   emit_far_call(do_insn_cmp);
4581   //emit_readword(&cycle,0);
4582   //emit_addimm(0,2,0);
4583   //emit_writeword(0,&cycle);
4584   (void)get_reg2;
4585   restore_regs(reglist);
4586   assem_debug("\\\\do_insn_cmp\n");
4587 }
4588 #else
4589 #define drc_dbg_emit_do_cmp(x)
4590 #endif
4591
4592 // Used when a branch jumps into the delay slot of another branch
4593 static void ds_assemble_entry(int i)
4594 {
4595   int t=(ba[i]-start)>>2;
4596   if (!instr_addr[t])
4597     instr_addr[t] = out;
4598   assem_debug("Assemble delay slot at %x\n",ba[i]);
4599   assem_debug("<->\n");
4600   drc_dbg_emit_do_cmp(t);
4601   if(regs[t].regmap_entry[HOST_CCREG]==CCREG&&regs[t].regmap[HOST_CCREG]!=CCREG)
4602     wb_register(CCREG,regs[t].regmap_entry,regs[t].wasdirty);
4603   load_regs(regs[t].regmap_entry,regs[t].regmap,dops[t].rs1,dops[t].rs2);
4604   address_generation(t,&regs[t],regs[t].regmap_entry);
4605   if(dops[t].itype==STORE||dops[t].itype==STORELR||(dops[t].opcode&0x3b)==0x39||(dops[t].opcode&0x3b)==0x3a)
4606     load_regs(regs[t].regmap_entry,regs[t].regmap,INVCP,INVCP);
4607   is_delayslot=0;
4608   switch(dops[t].itype) {
4609     case ALU:
4610       alu_assemble(t,&regs[t]);break;
4611     case IMM16:
4612       imm16_assemble(t,&regs[t]);break;
4613     case SHIFT:
4614       shift_assemble(t,&regs[t]);break;
4615     case SHIFTIMM:
4616       shiftimm_assemble(t,&regs[t]);break;
4617     case LOAD:
4618       load_assemble(t,&regs[t]);break;
4619     case LOADLR:
4620       loadlr_assemble(t,&regs[t]);break;
4621     case STORE:
4622       store_assemble(t,&regs[t]);break;
4623     case STORELR:
4624       storelr_assemble(t,&regs[t]);break;
4625     case COP0:
4626       cop0_assemble(t,&regs[t]);break;
4627     case COP1:
4628       cop1_assemble(t,&regs[t]);break;
4629     case C1LS:
4630       c1ls_assemble(t,&regs[t]);break;
4631     case COP2:
4632       cop2_assemble(t,&regs[t]);break;
4633     case C2LS:
4634       c2ls_assemble(t,&regs[t]);break;
4635     case C2OP:
4636       c2op_assemble(t,&regs[t]);break;
4637     case MULTDIV:
4638       multdiv_assemble(t,&regs[t]);
4639       multdiv_prepare_stall(i,&regs[t]);
4640       break;
4641     case MOV:
4642       mov_assemble(t,&regs[t]);break;
4643     case SYSCALL:
4644     case HLECALL:
4645     case INTCALL:
4646     case SPAN:
4647     case UJUMP:
4648     case RJUMP:
4649     case CJUMP:
4650     case SJUMP:
4651       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4652   }
4653   store_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4654   load_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4655   if(internal_branch(ba[i]+4))
4656     assem_debug("branch: internal\n");
4657   else
4658     assem_debug("branch: external\n");
4659   assert(internal_branch(ba[i]+4));
4660   add_to_linker(out,ba[i]+4,internal_branch(ba[i]+4));
4661   emit_jmp(0);
4662 }
4663
4664 static void emit_extjump(void *addr, u_int target)
4665 {
4666   emit_extjump2(addr, target, dyna_linker);
4667 }
4668
4669 static void emit_extjump_ds(void *addr, u_int target)
4670 {
4671   emit_extjump2(addr, target, dyna_linker_ds);
4672 }
4673
4674 // Load 2 immediates optimizing for small code size
4675 static void emit_mov2imm_compact(int imm1,u_int rt1,int imm2,u_int rt2)
4676 {
4677   emit_movimm(imm1,rt1);
4678   emit_movimm_from(imm1,rt1,imm2,rt2);
4679 }
4680
4681 void do_cc(int i,signed char i_regmap[],int *adj,int addr,int taken,int invert)
4682 {
4683   int count;
4684   void *jaddr;
4685   void *idle=NULL;
4686   int t=0;
4687   if(dops[i].itype==RJUMP)
4688   {
4689     *adj=0;
4690   }
4691   //if(ba[i]>=start && ba[i]<(start+slen*4))
4692   if(internal_branch(ba[i]))
4693   {
4694     t=(ba[i]-start)>>2;
4695     if(dops[t].is_ds) *adj=-1; // Branch into delay slot adds an extra cycle
4696     else *adj=ccadj[t];
4697   }
4698   else
4699   {
4700     *adj=0;
4701   }
4702   count=ccadj[i];
4703   if(taken==TAKEN && i==(ba[i]-start)>>2 && source[i+1]==0) {
4704     // Idle loop
4705     if(count&1) emit_addimm_and_set_flags(2*(count+2),HOST_CCREG);
4706     idle=out;
4707     //emit_subfrommem(&idlecount,HOST_CCREG); // Count idle cycles
4708     emit_andimm(HOST_CCREG,3,HOST_CCREG);
4709     jaddr=out;
4710     emit_jmp(0);
4711   }
4712   else if(*adj==0||invert) {
4713     int cycles=CLOCK_ADJUST(count+2);
4714     // faster loop HACK
4715 #if 0
4716     if (t&&*adj) {
4717       int rel=t-i;
4718       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
4719         cycles=CLOCK_ADJUST(*adj)+count+2-*adj;
4720     }
4721 #endif
4722     emit_addimm_and_set_flags(cycles,HOST_CCREG);
4723     jaddr=out;
4724     emit_jns(0);
4725   }
4726   else
4727   {
4728     emit_cmpimm(HOST_CCREG,-CLOCK_ADJUST(count+2));
4729     jaddr=out;
4730     emit_jns(0);
4731   }
4732   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:(count+2),i,addr,taken,0);
4733 }
4734
4735 static void do_ccstub(int n)
4736 {
4737   literal_pool(256);
4738   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
4739   set_jump_target(stubs[n].addr, out);
4740   int i=stubs[n].b;
4741   if(stubs[n].d==NULLDS) {
4742     // Delay slot instruction is nullified ("likely" branch)
4743     wb_dirtys(regs[i].regmap,regs[i].dirty);
4744   }
4745   else if(stubs[n].d!=TAKEN) {
4746     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
4747   }
4748   else {
4749     if(internal_branch(ba[i]))
4750       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4751   }
4752   if(stubs[n].c!=-1)
4753   {
4754     // Save PC as return address
4755     emit_movimm(stubs[n].c,EAX);
4756     emit_writeword(EAX,&pcaddr);
4757   }
4758   else
4759   {
4760     // Return address depends on which way the branch goes
4761     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
4762     {
4763       int s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
4764       int s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
4765       if(dops[i].rs1==0)
4766       {
4767         s1l=s2l;
4768         s2l=-1;
4769       }
4770       else if(dops[i].rs2==0)
4771       {
4772         s2l=-1;
4773       }
4774       assert(s1l>=0);
4775       #ifdef DESTRUCTIVE_WRITEBACK
4776       if(dops[i].rs1) {
4777         if((branch_regs[i].dirty>>s1l)&&1)
4778           emit_loadreg(dops[i].rs1,s1l);
4779       }
4780       else {
4781         if((branch_regs[i].dirty>>s1l)&1)
4782           emit_loadreg(dops[i].rs2,s1l);
4783       }
4784       if(s2l>=0)
4785         if((branch_regs[i].dirty>>s2l)&1)
4786           emit_loadreg(dops[i].rs2,s2l);
4787       #endif
4788       int hr=0;
4789       int addr=-1,alt=-1,ntaddr=-1;
4790       while(hr<HOST_REGS)
4791       {
4792         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4793            (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4794            (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4795         {
4796           addr=hr++;break;
4797         }
4798         hr++;
4799       }
4800       while(hr<HOST_REGS)
4801       {
4802         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4803            (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4804            (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4805         {
4806           alt=hr++;break;
4807         }
4808         hr++;
4809       }
4810       if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
4811       {
4812         while(hr<HOST_REGS)
4813         {
4814           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4815              (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4816              (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4817           {
4818             ntaddr=hr;break;
4819           }
4820           hr++;
4821         }
4822         assert(hr<HOST_REGS);
4823       }
4824       if((dops[i].opcode&0x2f)==4) // BEQ
4825       {
4826         #ifdef HAVE_CMOV_IMM
4827         if(s2l>=0) emit_cmp(s1l,s2l);
4828         else emit_test(s1l,s1l);
4829         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
4830         #else
4831         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4832         if(s2l>=0) emit_cmp(s1l,s2l);
4833         else emit_test(s1l,s1l);
4834         emit_cmovne_reg(alt,addr);
4835         #endif
4836       }
4837       if((dops[i].opcode&0x2f)==5) // BNE
4838       {
4839         #ifdef HAVE_CMOV_IMM
4840         if(s2l>=0) emit_cmp(s1l,s2l);
4841         else emit_test(s1l,s1l);
4842         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
4843         #else
4844         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
4845         if(s2l>=0) emit_cmp(s1l,s2l);
4846         else emit_test(s1l,s1l);
4847         emit_cmovne_reg(alt,addr);
4848         #endif
4849       }
4850       if((dops[i].opcode&0x2f)==6) // BLEZ
4851       {
4852         //emit_movimm(ba[i],alt);
4853         //emit_movimm(start+i*4+8,addr);
4854         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4855         emit_cmpimm(s1l,1);
4856         emit_cmovl_reg(alt,addr);
4857       }
4858       if((dops[i].opcode&0x2f)==7) // BGTZ
4859       {
4860         //emit_movimm(ba[i],addr);
4861         //emit_movimm(start+i*4+8,ntaddr);
4862         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
4863         emit_cmpimm(s1l,1);
4864         emit_cmovl_reg(ntaddr,addr);
4865       }
4866       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==0) // BLTZ
4867       {
4868         //emit_movimm(ba[i],alt);
4869         //emit_movimm(start+i*4+8,addr);
4870         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4871         emit_test(s1l,s1l);
4872         emit_cmovs_reg(alt,addr);
4873       }
4874       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==1) // BGEZ
4875       {
4876         //emit_movimm(ba[i],addr);
4877         //emit_movimm(start+i*4+8,alt);
4878         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4879         emit_test(s1l,s1l);
4880         emit_cmovs_reg(alt,addr);
4881       }
4882       if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
4883         if(source[i]&0x10000) // BC1T
4884         {
4885           //emit_movimm(ba[i],alt);
4886           //emit_movimm(start+i*4+8,addr);
4887           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4888           emit_testimm(s1l,0x800000);
4889           emit_cmovne_reg(alt,addr);
4890         }
4891         else // BC1F
4892         {
4893           //emit_movimm(ba[i],addr);
4894           //emit_movimm(start+i*4+8,alt);
4895           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4896           emit_testimm(s1l,0x800000);
4897           emit_cmovne_reg(alt,addr);
4898         }
4899       }
4900       emit_writeword(addr,&pcaddr);
4901     }
4902     else
4903     if(dops[i].itype==RJUMP)
4904     {
4905       int r=get_reg(branch_regs[i].regmap,dops[i].rs1);
4906       if (ds_writes_rjump_rs(i)) {
4907         r=get_reg(branch_regs[i].regmap,RTEMP);
4908       }
4909       emit_writeword(r,&pcaddr);
4910     }
4911     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
4912   }
4913   // Update cycle count
4914   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
4915   if(stubs[n].a) emit_addimm(HOST_CCREG,CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4916   emit_far_call(cc_interrupt);
4917   if(stubs[n].a) emit_addimm(HOST_CCREG,-CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4918   if(stubs[n].d==TAKEN) {
4919     if(internal_branch(ba[i]))
4920       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
4921     else if(dops[i].itype==RJUMP) {
4922       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
4923         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
4924       else
4925         emit_loadreg(dops[i].rs1,get_reg(branch_regs[i].regmap,dops[i].rs1));
4926     }
4927   }else if(stubs[n].d==NOTTAKEN) {
4928     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
4929     else load_all_regs(branch_regs[i].regmap);
4930   }else if(stubs[n].d==NULLDS) {
4931     // Delay slot instruction is nullified ("likely" branch)
4932     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
4933     else load_all_regs(regs[i].regmap);
4934   }else{
4935     load_all_regs(branch_regs[i].regmap);
4936   }
4937   if (stubs[n].retaddr)
4938     emit_jmp(stubs[n].retaddr);
4939   else
4940     do_jump_vaddr(stubs[n].e);
4941 }
4942
4943 static void add_to_linker(void *addr, u_int target, int ext)
4944 {
4945   assert(linkcount < ARRAY_SIZE(link_addr));
4946   link_addr[linkcount].addr = addr;
4947   link_addr[linkcount].target = target;
4948   link_addr[linkcount].ext = ext;
4949   linkcount++;
4950 }
4951
4952 static void ujump_assemble_write_ra(int i)
4953 {
4954   int rt;
4955   unsigned int return_address;
4956   rt=get_reg(branch_regs[i].regmap,31);
4957   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]);
4958   //assert(rt>=0);
4959   return_address=start+i*4+8;
4960   if(rt>=0) {
4961     #ifdef USE_MINI_HT
4962     if(internal_branch(return_address)&&dops[i+1].rt1!=31) {
4963       int temp=-1; // note: must be ds-safe
4964       #ifdef HOST_TEMPREG
4965       temp=HOST_TEMPREG;
4966       #endif
4967       if(temp>=0) do_miniht_insert(return_address,rt,temp);
4968       else emit_movimm(return_address,rt);
4969     }
4970     else
4971     #endif
4972     {
4973       #ifdef REG_PREFETCH
4974       if(temp>=0)
4975       {
4976         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
4977       }
4978       #endif
4979       emit_movimm(return_address,rt); // PC into link register
4980       #ifdef IMM_PREFETCH
4981       emit_prefetch(hash_table_get(return_address));
4982       #endif
4983     }
4984   }
4985 }
4986
4987 static void ujump_assemble(int i,struct regstat *i_regs)
4988 {
4989   int ra_done=0;
4990   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
4991   address_generation(i+1,i_regs,regs[i].regmap_entry);
4992   #ifdef REG_PREFETCH
4993   int temp=get_reg(branch_regs[i].regmap,PTEMP);
4994   if(dops[i].rt1==31&&temp>=0)
4995   {
4996     signed char *i_regmap=i_regs->regmap;
4997     int return_address=start+i*4+8;
4998     if(get_reg(branch_regs[i].regmap,31)>0)
4999     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5000   }
5001   #endif
5002   if(dops[i].rt1==31&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5003     ujump_assemble_write_ra(i); // writeback ra for DS
5004     ra_done=1;
5005   }
5006   ds_assemble(i+1,i_regs);
5007   uint64_t bc_unneeded=branch_regs[i].u;
5008   bc_unneeded|=1|(1LL<<dops[i].rt1);
5009   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5010   load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5011   if(!ra_done&&dops[i].rt1==31)
5012     ujump_assemble_write_ra(i);
5013   int cc,adj;
5014   cc=get_reg(branch_regs[i].regmap,CCREG);
5015   assert(cc==HOST_CCREG);
5016   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5017   #ifdef REG_PREFETCH
5018   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5019   #endif
5020   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5021   if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5022   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5023   if(internal_branch(ba[i]))
5024     assem_debug("branch: internal\n");
5025   else
5026     assem_debug("branch: external\n");
5027   if (internal_branch(ba[i]) && dops[(ba[i]-start)>>2].is_ds) {
5028     ds_assemble_entry(i);
5029   }
5030   else {
5031     add_to_linker(out,ba[i],internal_branch(ba[i]));
5032     emit_jmp(0);
5033   }
5034 }
5035
5036 static void rjump_assemble_write_ra(int i)
5037 {
5038   int rt,return_address;
5039   assert(dops[i+1].rt1!=dops[i].rt1);
5040   assert(dops[i+1].rt2!=dops[i].rt1);
5041   rt=get_reg(branch_regs[i].regmap,dops[i].rt1);
5042   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]);
5043   assert(rt>=0);
5044   return_address=start+i*4+8;
5045   #ifdef REG_PREFETCH
5046   if(temp>=0)
5047   {
5048     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5049   }
5050   #endif
5051   emit_movimm(return_address,rt); // PC into link register
5052   #ifdef IMM_PREFETCH
5053   emit_prefetch(hash_table_get(return_address));
5054   #endif
5055 }
5056
5057 static void rjump_assemble(int i,struct regstat *i_regs)
5058 {
5059   int temp;
5060   int rs,cc;
5061   int ra_done=0;
5062   rs=get_reg(branch_regs[i].regmap,dops[i].rs1);
5063   assert(rs>=0);
5064   if (ds_writes_rjump_rs(i)) {
5065     // Delay slot abuse, make a copy of the branch address register
5066     temp=get_reg(branch_regs[i].regmap,RTEMP);
5067     assert(temp>=0);
5068     assert(regs[i].regmap[temp]==RTEMP);
5069     emit_mov(rs,temp);
5070     rs=temp;
5071   }
5072   address_generation(i+1,i_regs,regs[i].regmap_entry);
5073   #ifdef REG_PREFETCH
5074   if(dops[i].rt1==31)
5075   {
5076     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
5077       signed char *i_regmap=i_regs->regmap;
5078       int return_address=start+i*4+8;
5079       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5080     }
5081   }
5082   #endif
5083   #ifdef USE_MINI_HT
5084   if(dops[i].rs1==31) {
5085     int rh=get_reg(regs[i].regmap,RHASH);
5086     if(rh>=0) do_preload_rhash(rh);
5087   }
5088   #endif
5089   if(dops[i].rt1!=0&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5090     rjump_assemble_write_ra(i);
5091     ra_done=1;
5092   }
5093   ds_assemble(i+1,i_regs);
5094   uint64_t bc_unneeded=branch_regs[i].u;
5095   bc_unneeded|=1|(1LL<<dops[i].rt1);
5096   bc_unneeded&=~(1LL<<dops[i].rs1);
5097   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5098   load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,CCREG);
5099   if(!ra_done&&dops[i].rt1!=0)
5100     rjump_assemble_write_ra(i);
5101   cc=get_reg(branch_regs[i].regmap,CCREG);
5102   assert(cc==HOST_CCREG);
5103   (void)cc;
5104   #ifdef USE_MINI_HT
5105   int rh=get_reg(branch_regs[i].regmap,RHASH);
5106   int ht=get_reg(branch_regs[i].regmap,RHTBL);
5107   if(dops[i].rs1==31) {
5108     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
5109     do_preload_rhtbl(ht);
5110     do_rhash(rs,rh);
5111   }
5112   #endif
5113   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5114   #ifdef DESTRUCTIVE_WRITEBACK
5115   if((branch_regs[i].dirty>>rs)&1) {
5116     if(dops[i].rs1!=dops[i+1].rt1&&dops[i].rs1!=dops[i+1].rt2) {
5117       emit_loadreg(dops[i].rs1,rs);
5118     }
5119   }
5120   #endif
5121   #ifdef REG_PREFETCH
5122   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5123   #endif
5124   #ifdef USE_MINI_HT
5125   if(dops[i].rs1==31) {
5126     do_miniht_load(ht,rh);
5127   }
5128   #endif
5129   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
5130   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
5131   //assert(adj==0);
5132   emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5133   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
5134   if(dops[i+1].itype==COP0&&(source[i+1]&0x3f)==0x10)
5135     // special case for RFE
5136     emit_jmp(0);
5137   else
5138     emit_jns(0);
5139   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5140   #ifdef USE_MINI_HT
5141   if(dops[i].rs1==31) {
5142     do_miniht_jump(rs,rh,ht);
5143   }
5144   else
5145   #endif
5146   {
5147     do_jump_vaddr(rs);
5148   }
5149   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5150   if(dops[i].rt1!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
5151   #endif
5152 }
5153
5154 static void cjump_assemble(int i,struct regstat *i_regs)
5155 {
5156   signed char *i_regmap=i_regs->regmap;
5157   int cc;
5158   int match;
5159   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5160   assem_debug("match=%d\n",match);
5161   int s1l,s2l;
5162   int unconditional=0,nop=0;
5163   int invert=0;
5164   int internal=internal_branch(ba[i]);
5165   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5166   if(!match) invert=1;
5167   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5168   if(i>(ba[i]-start)>>2) invert=1;
5169   #endif
5170   #ifdef __aarch64__
5171   invert=1; // because of near cond. branches
5172   #endif
5173
5174   if(dops[i].ooo) {
5175     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5176     s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
5177   }
5178   else {
5179     s1l=get_reg(i_regmap,dops[i].rs1);
5180     s2l=get_reg(i_regmap,dops[i].rs2);
5181   }
5182   if(dops[i].rs1==0&&dops[i].rs2==0)
5183   {
5184     if(dops[i].opcode&1) nop=1;
5185     else unconditional=1;
5186     //assert(dops[i].opcode!=5);
5187     //assert(dops[i].opcode!=7);
5188     //assert(dops[i].opcode!=0x15);
5189     //assert(dops[i].opcode!=0x17);
5190   }
5191   else if(dops[i].rs1==0)
5192   {
5193     s1l=s2l;
5194     s2l=-1;
5195   }
5196   else if(dops[i].rs2==0)
5197   {
5198     s2l=-1;
5199   }
5200
5201   if(dops[i].ooo) {
5202     // Out of order execution (delay slot first)
5203     //printf("OOOE\n");
5204     address_generation(i+1,i_regs,regs[i].regmap_entry);
5205     ds_assemble(i+1,i_regs);
5206     int adj;
5207     uint64_t bc_unneeded=branch_regs[i].u;
5208     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5209     bc_unneeded|=1;
5210     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5211     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs2);
5212     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5213     cc=get_reg(branch_regs[i].regmap,CCREG);
5214     assert(cc==HOST_CCREG);
5215     if(unconditional)
5216       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5217     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5218     //assem_debug("cycle count (adj)\n");
5219     if(unconditional) {
5220       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5221       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5222         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5223         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5224         if(internal)
5225           assem_debug("branch: internal\n");
5226         else
5227           assem_debug("branch: external\n");
5228         if (internal && dops[(ba[i]-start)>>2].is_ds) {
5229           ds_assemble_entry(i);
5230         }
5231         else {
5232           add_to_linker(out,ba[i],internal);
5233           emit_jmp(0);
5234         }
5235         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5236         if(((u_int)out)&7) emit_addnop(0);
5237         #endif
5238       }
5239     }
5240     else if(nop) {
5241       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5242       void *jaddr=out;
5243       emit_jns(0);
5244       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5245     }
5246     else {
5247       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5248       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5249       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5250
5251       //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]);
5252       assert(s1l>=0);
5253       if(dops[i].opcode==4) // BEQ
5254       {
5255         if(s2l>=0) emit_cmp(s1l,s2l);
5256         else emit_test(s1l,s1l);
5257         if(invert){
5258           nottaken=out;
5259           emit_jne(DJT_1);
5260         }else{
5261           add_to_linker(out,ba[i],internal);
5262           emit_jeq(0);
5263         }
5264       }
5265       if(dops[i].opcode==5) // BNE
5266       {
5267         if(s2l>=0) emit_cmp(s1l,s2l);
5268         else emit_test(s1l,s1l);
5269         if(invert){
5270           nottaken=out;
5271           emit_jeq(DJT_1);
5272         }else{
5273           add_to_linker(out,ba[i],internal);
5274           emit_jne(0);
5275         }
5276       }
5277       if(dops[i].opcode==6) // BLEZ
5278       {
5279         emit_cmpimm(s1l,1);
5280         if(invert){
5281           nottaken=out;
5282           emit_jge(DJT_1);
5283         }else{
5284           add_to_linker(out,ba[i],internal);
5285           emit_jl(0);
5286         }
5287       }
5288       if(dops[i].opcode==7) // BGTZ
5289       {
5290         emit_cmpimm(s1l,1);
5291         if(invert){
5292           nottaken=out;
5293           emit_jl(DJT_1);
5294         }else{
5295           add_to_linker(out,ba[i],internal);
5296           emit_jge(0);
5297         }
5298       }
5299       if(invert) {
5300         if(taken) set_jump_target(taken, out);
5301         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5302         if (match && (!internal || !dops[(ba[i]-start)>>2].is_ds)) {
5303           if(adj) {
5304             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5305             add_to_linker(out,ba[i],internal);
5306           }else{
5307             emit_addnop(13);
5308             add_to_linker(out,ba[i],internal*2);
5309           }
5310           emit_jmp(0);
5311         }else
5312         #endif
5313         {
5314           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5315           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5316           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5317           if(internal)
5318             assem_debug("branch: internal\n");
5319           else
5320             assem_debug("branch: external\n");
5321           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5322             ds_assemble_entry(i);
5323           }
5324           else {
5325             add_to_linker(out,ba[i],internal);
5326             emit_jmp(0);
5327           }
5328         }
5329         set_jump_target(nottaken, out);
5330       }
5331
5332       if(nottaken1) set_jump_target(nottaken1, out);
5333       if(adj) {
5334         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5335       }
5336     } // (!unconditional)
5337   } // if(ooo)
5338   else
5339   {
5340     // In-order execution (branch first)
5341     //if(dops[i].likely) printf("IOL\n");
5342     //else
5343     //printf("IOE\n");
5344     void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5345     if(!unconditional&&!nop) {
5346       //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]);
5347       assert(s1l>=0);
5348       if((dops[i].opcode&0x2f)==4) // BEQ
5349       {
5350         if(s2l>=0) emit_cmp(s1l,s2l);
5351         else emit_test(s1l,s1l);
5352         nottaken=out;
5353         emit_jne(DJT_2);
5354       }
5355       if((dops[i].opcode&0x2f)==5) // BNE
5356       {
5357         if(s2l>=0) emit_cmp(s1l,s2l);
5358         else emit_test(s1l,s1l);
5359         nottaken=out;
5360         emit_jeq(DJT_2);
5361       }
5362       if((dops[i].opcode&0x2f)==6) // BLEZ
5363       {
5364         emit_cmpimm(s1l,1);
5365         nottaken=out;
5366         emit_jge(DJT_2);
5367       }
5368       if((dops[i].opcode&0x2f)==7) // BGTZ
5369       {
5370         emit_cmpimm(s1l,1);
5371         nottaken=out;
5372         emit_jl(DJT_2);
5373       }
5374     } // if(!unconditional)
5375     int adj;
5376     uint64_t ds_unneeded=branch_regs[i].u;
5377     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5378     ds_unneeded|=1;
5379     // branch taken
5380     if(!nop) {
5381       if(taken) set_jump_target(taken, out);
5382       assem_debug("1:\n");
5383       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5384       // load regs
5385       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5386       address_generation(i+1,&branch_regs[i],0);
5387       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5388       ds_assemble(i+1,&branch_regs[i]);
5389       cc=get_reg(branch_regs[i].regmap,CCREG);
5390       if(cc==-1) {
5391         emit_loadreg(CCREG,cc=HOST_CCREG);
5392         // CHECK: Is the following instruction (fall thru) allocated ok?
5393       }
5394       assert(cc==HOST_CCREG);
5395       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5396       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5397       assem_debug("cycle count (adj)\n");
5398       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5399       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5400       if(internal)
5401         assem_debug("branch: internal\n");
5402       else
5403         assem_debug("branch: external\n");
5404       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5405         ds_assemble_entry(i);
5406       }
5407       else {
5408         add_to_linker(out,ba[i],internal);
5409         emit_jmp(0);
5410       }
5411     }
5412     // branch not taken
5413     if(!unconditional) {
5414       if(nottaken1) set_jump_target(nottaken1, out);
5415       set_jump_target(nottaken, out);
5416       assem_debug("2:\n");
5417       if(!dops[i].likely) {
5418         wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5419         load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5420         address_generation(i+1,&branch_regs[i],0);
5421         load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5422         ds_assemble(i+1,&branch_regs[i]);
5423       }
5424       cc=get_reg(branch_regs[i].regmap,CCREG);
5425       if(cc==-1&&!dops[i].likely) {
5426         // Cycle count isn't in a register, temporarily load it then write it out
5427         emit_loadreg(CCREG,HOST_CCREG);
5428         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5429         void *jaddr=out;
5430         emit_jns(0);
5431         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5432         emit_storereg(CCREG,HOST_CCREG);
5433       }
5434       else{
5435         cc=get_reg(i_regmap,CCREG);
5436         assert(cc==HOST_CCREG);
5437         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5438         void *jaddr=out;
5439         emit_jns(0);
5440         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,dops[i].likely?NULLDS:NOTTAKEN,0);
5441       }
5442     }
5443   }
5444 }
5445
5446 static void sjump_assemble(int i,struct regstat *i_regs)
5447 {
5448   signed char *i_regmap=i_regs->regmap;
5449   int cc;
5450   int match;
5451   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5452   assem_debug("smatch=%d\n",match);
5453   int s1l;
5454   int unconditional=0,nevertaken=0;
5455   int invert=0;
5456   int internal=internal_branch(ba[i]);
5457   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5458   if(!match) invert=1;
5459   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5460   if(i>(ba[i]-start)>>2) invert=1;
5461   #endif
5462   #ifdef __aarch64__
5463   invert=1; // because of near cond. branches
5464   #endif
5465
5466   //if(dops[i].opcode2>=0x10) return; // FIXME (BxxZAL)
5467   //assert(dops[i].opcode2<0x10||dops[i].rs1==0); // FIXME (BxxZAL)
5468
5469   if(dops[i].ooo) {
5470     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5471   }
5472   else {
5473     s1l=get_reg(i_regmap,dops[i].rs1);
5474   }
5475   if(dops[i].rs1==0)
5476   {
5477     if(dops[i].opcode2&1) unconditional=1;
5478     else nevertaken=1;
5479     // These are never taken (r0 is never less than zero)
5480     //assert(dops[i].opcode2!=0);
5481     //assert(dops[i].opcode2!=2);
5482     //assert(dops[i].opcode2!=0x10);
5483     //assert(dops[i].opcode2!=0x12);
5484   }
5485
5486   if(dops[i].ooo) {
5487     // Out of order execution (delay slot first)
5488     //printf("OOOE\n");
5489     address_generation(i+1,i_regs,regs[i].regmap_entry);
5490     ds_assemble(i+1,i_regs);
5491     int adj;
5492     uint64_t bc_unneeded=branch_regs[i].u;
5493     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5494     bc_unneeded|=1;
5495     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5496     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs1);
5497     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5498     if(dops[i].rt1==31) {
5499       int rt,return_address;
5500       rt=get_reg(branch_regs[i].regmap,31);
5501       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]);
5502       if(rt>=0) {
5503         // Save the PC even if the branch is not taken
5504         return_address=start+i*4+8;
5505         emit_movimm(return_address,rt); // PC into link register
5506         #ifdef IMM_PREFETCH
5507         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5508         #endif
5509       }
5510     }
5511     cc=get_reg(branch_regs[i].regmap,CCREG);
5512     assert(cc==HOST_CCREG);
5513     if(unconditional)
5514       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5515     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5516     assem_debug("cycle count (adj)\n");
5517     if(unconditional) {
5518       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5519       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5520         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5521         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5522         if(internal)
5523           assem_debug("branch: internal\n");
5524         else
5525           assem_debug("branch: external\n");
5526         if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5527           ds_assemble_entry(i);
5528         }
5529         else {
5530           add_to_linker(out,ba[i],internal);
5531           emit_jmp(0);
5532         }
5533         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5534         if(((u_int)out)&7) emit_addnop(0);
5535         #endif
5536       }
5537     }
5538     else if(nevertaken) {
5539       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5540       void *jaddr=out;
5541       emit_jns(0);
5542       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5543     }
5544     else {
5545       void *nottaken = NULL;
5546       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5547       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5548       {
5549         assert(s1l>=0);
5550         if((dops[i].opcode2&0xf)==0) // BLTZ/BLTZAL
5551         {
5552           emit_test(s1l,s1l);
5553           if(invert){
5554             nottaken=out;
5555             emit_jns(DJT_1);
5556           }else{
5557             add_to_linker(out,ba[i],internal);
5558             emit_js(0);
5559           }
5560         }
5561         if((dops[i].opcode2&0xf)==1) // BGEZ/BLTZAL
5562         {
5563           emit_test(s1l,s1l);
5564           if(invert){
5565             nottaken=out;
5566             emit_js(DJT_1);
5567           }else{
5568             add_to_linker(out,ba[i],internal);
5569             emit_jns(0);
5570           }
5571         }
5572       }
5573
5574       if(invert) {
5575         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5576         if (match && (!internal || !dops[(ba[i] - start) >> 2].is_ds)) {
5577           if(adj) {
5578             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5579             add_to_linker(out,ba[i],internal);
5580           }else{
5581             emit_addnop(13);
5582             add_to_linker(out,ba[i],internal*2);
5583           }
5584           emit_jmp(0);
5585         }else
5586         #endif
5587         {
5588           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5589           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5590           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5591           if(internal)
5592             assem_debug("branch: internal\n");
5593           else
5594             assem_debug("branch: external\n");
5595           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5596             ds_assemble_entry(i);
5597           }
5598           else {
5599             add_to_linker(out,ba[i],internal);
5600             emit_jmp(0);
5601           }
5602         }
5603         set_jump_target(nottaken, out);
5604       }
5605
5606       if(adj) {
5607         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5608       }
5609     } // (!unconditional)
5610   } // if(ooo)
5611   else
5612   {
5613     // In-order execution (branch first)
5614     //printf("IOE\n");
5615     void *nottaken = NULL;
5616     if(dops[i].rt1==31) {
5617       int rt,return_address;
5618       rt=get_reg(branch_regs[i].regmap,31);
5619       if(rt>=0) {
5620         // Save the PC even if the branch is not taken
5621         return_address=start+i*4+8;
5622         emit_movimm(return_address,rt); // PC into link register
5623         #ifdef IMM_PREFETCH
5624         emit_prefetch(hash_table_get(return_address));
5625         #endif
5626       }
5627     }
5628     if(!unconditional) {
5629       //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]);
5630         assert(s1l>=0);
5631         if((dops[i].opcode2&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5632         {
5633           emit_test(s1l,s1l);
5634           nottaken=out;
5635           emit_jns(DJT_1);
5636         }
5637         if((dops[i].opcode2&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5638         {
5639           emit_test(s1l,s1l);
5640           nottaken=out;
5641           emit_js(DJT_1);
5642         }
5643     } // if(!unconditional)
5644     int adj;
5645     uint64_t ds_unneeded=branch_regs[i].u;
5646     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5647     ds_unneeded|=1;
5648     // branch taken
5649     if(!nevertaken) {
5650       //assem_debug("1:\n");
5651       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5652       // load regs
5653       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5654       address_generation(i+1,&branch_regs[i],0);
5655       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5656       ds_assemble(i+1,&branch_regs[i]);
5657       cc=get_reg(branch_regs[i].regmap,CCREG);
5658       if(cc==-1) {
5659         emit_loadreg(CCREG,cc=HOST_CCREG);
5660         // CHECK: Is the following instruction (fall thru) allocated ok?
5661       }
5662       assert(cc==HOST_CCREG);
5663       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5664       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5665       assem_debug("cycle count (adj)\n");
5666       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5667       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5668       if(internal)
5669         assem_debug("branch: internal\n");
5670       else
5671         assem_debug("branch: external\n");
5672       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5673         ds_assemble_entry(i);
5674       }
5675       else {
5676         add_to_linker(out,ba[i],internal);
5677         emit_jmp(0);
5678       }
5679     }
5680     // branch not taken
5681     if(!unconditional) {
5682       set_jump_target(nottaken, out);
5683       assem_debug("1:\n");
5684       if(!dops[i].likely) {
5685         wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5686         load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5687         address_generation(i+1,&branch_regs[i],0);
5688         load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5689         ds_assemble(i+1,&branch_regs[i]);
5690       }
5691       cc=get_reg(branch_regs[i].regmap,CCREG);
5692       if(cc==-1&&!dops[i].likely) {
5693         // Cycle count isn't in a register, temporarily load it then write it out
5694         emit_loadreg(CCREG,HOST_CCREG);
5695         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5696         void *jaddr=out;
5697         emit_jns(0);
5698         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5699         emit_storereg(CCREG,HOST_CCREG);
5700       }
5701       else{
5702         cc=get_reg(i_regmap,CCREG);
5703         assert(cc==HOST_CCREG);
5704         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5705         void *jaddr=out;
5706         emit_jns(0);
5707         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,dops[i].likely?NULLDS:NOTTAKEN,0);
5708       }
5709     }
5710   }
5711 }
5712
5713 static void pagespan_assemble(int i,struct regstat *i_regs)
5714 {
5715   int s1l=get_reg(i_regs->regmap,dops[i].rs1);
5716   int s2l=get_reg(i_regs->regmap,dops[i].rs2);
5717   void *taken = NULL;
5718   void *nottaken = NULL;
5719   int unconditional=0;
5720   if(dops[i].rs1==0)
5721   {
5722     s1l=s2l;
5723     s2l=-1;
5724   }
5725   else if(dops[i].rs2==0)
5726   {
5727     s2l=-1;
5728   }
5729   int hr=0;
5730   int addr=-1,alt=-1,ntaddr=-1;
5731   if(i_regs->regmap[HOST_BTREG]<0) {addr=HOST_BTREG;}
5732   else {
5733     while(hr<HOST_REGS)
5734     {
5735       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5736          (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5737          (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5738       {
5739         addr=hr++;break;
5740       }
5741       hr++;
5742     }
5743   }
5744   while(hr<HOST_REGS)
5745   {
5746     if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5747        (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5748        (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5749     {
5750       alt=hr++;break;
5751     }
5752     hr++;
5753   }
5754   if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
5755   {
5756     while(hr<HOST_REGS)
5757     {
5758       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5759          (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5760          (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5761       {
5762         ntaddr=hr;break;
5763       }
5764       hr++;
5765     }
5766   }
5767   assert(hr<HOST_REGS);
5768   if((dops[i].opcode&0x2e)==4||dops[i].opcode==0x11) { // BEQ/BNE/BEQL/BNEL/BC1
5769     load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
5770   }
5771   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5772   if(dops[i].opcode==2) // J
5773   {
5774     unconditional=1;
5775   }
5776   if(dops[i].opcode==3) // JAL
5777   {
5778     // TODO: mini_ht
5779     int rt=get_reg(i_regs->regmap,31);
5780     emit_movimm(start+i*4+8,rt);
5781     unconditional=1;
5782   }
5783   if(dops[i].opcode==0&&(dops[i].opcode2&0x3E)==8) // JR/JALR
5784   {
5785     emit_mov(s1l,addr);
5786     if(dops[i].opcode2==9) // JALR
5787     {
5788       int rt=get_reg(i_regs->regmap,dops[i].rt1);
5789       emit_movimm(start+i*4+8,rt);
5790     }
5791   }
5792   if((dops[i].opcode&0x3f)==4) // BEQ
5793   {
5794     if(dops[i].rs1==dops[i].rs2)
5795     {
5796       unconditional=1;
5797     }
5798     else
5799     #ifdef HAVE_CMOV_IMM
5800     if(1) {
5801       if(s2l>=0) emit_cmp(s1l,s2l);
5802       else emit_test(s1l,s1l);
5803       emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5804     }
5805     else
5806     #endif
5807     {
5808       assert(s1l>=0);
5809       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5810       if(s2l>=0) emit_cmp(s1l,s2l);
5811       else emit_test(s1l,s1l);
5812       emit_cmovne_reg(alt,addr);
5813     }
5814   }
5815   if((dops[i].opcode&0x3f)==5) // BNE
5816   {
5817     #ifdef HAVE_CMOV_IMM
5818     if(s2l>=0) emit_cmp(s1l,s2l);
5819     else emit_test(s1l,s1l);
5820     emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5821     #else
5822     assert(s1l>=0);
5823     emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5824     if(s2l>=0) emit_cmp(s1l,s2l);
5825     else emit_test(s1l,s1l);
5826     emit_cmovne_reg(alt,addr);
5827     #endif
5828   }
5829   if((dops[i].opcode&0x3f)==0x14) // BEQL
5830   {
5831     if(s2l>=0) emit_cmp(s1l,s2l);
5832     else emit_test(s1l,s1l);
5833     if(nottaken) set_jump_target(nottaken, out);
5834     nottaken=out;
5835     emit_jne(0);
5836   }
5837   if((dops[i].opcode&0x3f)==0x15) // BNEL
5838   {
5839     if(s2l>=0) emit_cmp(s1l,s2l);
5840     else emit_test(s1l,s1l);
5841     nottaken=out;
5842     emit_jeq(0);
5843     if(taken) set_jump_target(taken, out);
5844   }
5845   if((dops[i].opcode&0x3f)==6) // BLEZ
5846   {
5847     emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5848     emit_cmpimm(s1l,1);
5849     emit_cmovl_reg(alt,addr);
5850   }
5851   if((dops[i].opcode&0x3f)==7) // BGTZ
5852   {
5853     emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5854     emit_cmpimm(s1l,1);
5855     emit_cmovl_reg(ntaddr,addr);
5856   }
5857   if((dops[i].opcode&0x3f)==0x16) // BLEZL
5858   {
5859     assert((dops[i].opcode&0x3f)!=0x16);
5860   }
5861   if((dops[i].opcode&0x3f)==0x17) // BGTZL
5862   {
5863     assert((dops[i].opcode&0x3f)!=0x17);
5864   }
5865   assert(dops[i].opcode!=1); // BLTZ/BGEZ
5866
5867   //FIXME: Check CSREG
5868   if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
5869     if((source[i]&0x30000)==0) // BC1F
5870     {
5871       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5872       emit_testimm(s1l,0x800000);
5873       emit_cmovne_reg(alt,addr);
5874     }
5875     if((source[i]&0x30000)==0x10000) // BC1T
5876     {
5877       emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5878       emit_testimm(s1l,0x800000);
5879       emit_cmovne_reg(alt,addr);
5880     }
5881     if((source[i]&0x30000)==0x20000) // BC1FL
5882     {
5883       emit_testimm(s1l,0x800000);
5884       nottaken=out;
5885       emit_jne(0);
5886     }
5887     if((source[i]&0x30000)==0x30000) // BC1TL
5888     {
5889       emit_testimm(s1l,0x800000);
5890       nottaken=out;
5891       emit_jeq(0);
5892     }
5893   }
5894
5895   assert(i_regs->regmap[HOST_CCREG]==CCREG);
5896   wb_dirtys(regs[i].regmap,regs[i].dirty);
5897   if(dops[i].likely||unconditional)
5898   {
5899     emit_movimm(ba[i],HOST_BTREG);
5900   }
5901   else if(addr!=HOST_BTREG)
5902   {
5903     emit_mov(addr,HOST_BTREG);
5904   }
5905   void *branch_addr=out;
5906   emit_jmp(0);
5907   int target_addr=start+i*4+5;
5908   void *stub=out;
5909   void *compiled_target_addr=check_addr(target_addr);
5910   emit_extjump_ds(branch_addr, target_addr);
5911   if(compiled_target_addr) {
5912     set_jump_target(branch_addr, compiled_target_addr);
5913     add_jump_out(target_addr,stub);
5914   }
5915   else set_jump_target(branch_addr, stub);
5916   if(dops[i].likely) {
5917     // Not-taken path
5918     set_jump_target(nottaken, out);
5919     wb_dirtys(regs[i].regmap,regs[i].dirty);
5920     void *branch_addr=out;
5921     emit_jmp(0);
5922     int target_addr=start+i*4+8;
5923     void *stub=out;
5924     void *compiled_target_addr=check_addr(target_addr);
5925     emit_extjump_ds(branch_addr, target_addr);
5926     if(compiled_target_addr) {
5927       set_jump_target(branch_addr, compiled_target_addr);
5928       add_jump_out(target_addr,stub);
5929     }
5930     else set_jump_target(branch_addr, stub);
5931   }
5932 }
5933
5934 // Assemble the delay slot for the above
5935 static void pagespan_ds()
5936 {
5937   assem_debug("initial delay slot:\n");
5938   u_int vaddr=start+1;
5939   u_int page=get_page(vaddr);
5940   u_int vpage=get_vpage(vaddr);
5941   ll_add(jump_dirty+vpage,vaddr,(void *)out);
5942   do_dirty_stub_ds(slen*4);
5943   ll_add(jump_in+page,vaddr,(void *)out);
5944   assert(regs[0].regmap_entry[HOST_CCREG]==CCREG);
5945   if(regs[0].regmap[HOST_CCREG]!=CCREG)
5946     wb_register(CCREG,regs[0].regmap_entry,regs[0].wasdirty);
5947   if(regs[0].regmap[HOST_BTREG]!=BTREG)
5948     emit_writeword(HOST_BTREG,&branch_target);
5949   load_regs(regs[0].regmap_entry,regs[0].regmap,dops[0].rs1,dops[0].rs2);
5950   address_generation(0,&regs[0],regs[0].regmap_entry);
5951   if(dops[0].itype==STORE||dops[0].itype==STORELR||(dops[0].opcode&0x3b)==0x39||(dops[0].opcode&0x3b)==0x3a)
5952     load_regs(regs[0].regmap_entry,regs[0].regmap,INVCP,INVCP);
5953   is_delayslot=0;
5954   switch(dops[0].itype) {
5955     case ALU:
5956       alu_assemble(0,&regs[0]);break;
5957     case IMM16:
5958       imm16_assemble(0,&regs[0]);break;
5959     case SHIFT:
5960       shift_assemble(0,&regs[0]);break;
5961     case SHIFTIMM:
5962       shiftimm_assemble(0,&regs[0]);break;
5963     case LOAD:
5964       load_assemble(0,&regs[0]);break;
5965     case LOADLR:
5966       loadlr_assemble(0,&regs[0]);break;
5967     case STORE:
5968       store_assemble(0,&regs[0]);break;
5969     case STORELR:
5970       storelr_assemble(0,&regs[0]);break;
5971     case COP0:
5972       cop0_assemble(0,&regs[0]);break;
5973     case COP1:
5974       cop1_assemble(0,&regs[0]);break;
5975     case C1LS:
5976       c1ls_assemble(0,&regs[0]);break;
5977     case COP2:
5978       cop2_assemble(0,&regs[0]);break;
5979     case C2LS:
5980       c2ls_assemble(0,&regs[0]);break;
5981     case C2OP:
5982       c2op_assemble(0,&regs[0]);break;
5983     case MULTDIV:
5984       multdiv_assemble(0,&regs[0]);
5985       multdiv_prepare_stall(0,&regs[0]);
5986       break;
5987     case MOV:
5988       mov_assemble(0,&regs[0]);break;
5989     case SYSCALL:
5990     case HLECALL:
5991     case INTCALL:
5992     case SPAN:
5993     case UJUMP:
5994     case RJUMP:
5995     case CJUMP:
5996     case SJUMP:
5997       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
5998   }
5999   int btaddr=get_reg(regs[0].regmap,BTREG);
6000   if(btaddr<0) {
6001     btaddr=get_reg(regs[0].regmap,-1);
6002     emit_readword(&branch_target,btaddr);
6003   }
6004   assert(btaddr!=HOST_CCREG);
6005   if(regs[0].regmap[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
6006 #ifdef HOST_IMM8
6007   host_tempreg_acquire();
6008   emit_movimm(start+4,HOST_TEMPREG);
6009   emit_cmp(btaddr,HOST_TEMPREG);
6010   host_tempreg_release();
6011 #else
6012   emit_cmpimm(btaddr,start+4);
6013 #endif
6014   void *branch = out;
6015   emit_jeq(0);
6016   store_regs_bt(regs[0].regmap,regs[0].dirty,-1);
6017   do_jump_vaddr(btaddr);
6018   set_jump_target(branch, out);
6019   store_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6020   load_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6021 }
6022
6023 // Basic liveness analysis for MIPS registers
6024 void unneeded_registers(int istart,int iend,int r)
6025 {
6026   int i;
6027   uint64_t u,gte_u,b,gte_b;
6028   uint64_t temp_u,temp_gte_u=0;
6029   uint64_t gte_u_unknown=0;
6030   if (HACK_ENABLED(NDHACK_GTE_UNNEEDED))
6031     gte_u_unknown=~0ll;
6032   if(iend==slen-1) {
6033     u=1;
6034     gte_u=gte_u_unknown;
6035   }else{
6036     //u=unneeded_reg[iend+1];
6037     u=1;
6038     gte_u=gte_unneeded[iend+1];
6039   }
6040
6041   for (i=iend;i>=istart;i--)
6042   {
6043     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
6044     if(dops[i].itype==RJUMP||dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
6045     {
6046       // If subroutine call, flag return address as a possible branch target
6047       if(dops[i].rt1==31 && i<slen-2) dops[i+2].bt=1;
6048
6049       if(ba[i]<start || ba[i]>=(start+slen*4))
6050       {
6051         // Branch out of this block, flush all regs
6052         u=1;
6053         gte_u=gte_u_unknown;
6054         branch_unneeded_reg[i]=u;
6055         // Merge in delay slot
6056         u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6057         u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6058         u|=1;
6059         gte_u|=gte_rt[i+1];
6060         gte_u&=~gte_rs[i+1];
6061         // If branch is "likely" (and conditional)
6062         // then we skip the delay slot on the fall-thru path
6063         if(dops[i].likely) {
6064           if(i<slen-1) {
6065             u&=unneeded_reg[i+2];
6066             gte_u&=gte_unneeded[i+2];
6067           }
6068           else
6069           {
6070             u=1;
6071             gte_u=gte_u_unknown;
6072           }
6073         }
6074       }
6075       else
6076       {
6077         // Internal branch, flag target
6078         dops[(ba[i]-start)>>2].bt=1;
6079         if(ba[i]<=start+i*4) {
6080           // Backward branch
6081           if(is_ujump(i))
6082           {
6083             // Unconditional branch
6084             temp_u=1;
6085             temp_gte_u=0;
6086           } else {
6087             // Conditional branch (not taken case)
6088             temp_u=unneeded_reg[i+2];
6089             temp_gte_u&=gte_unneeded[i+2];
6090           }
6091           // Merge in delay slot
6092           temp_u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6093           temp_u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6094           temp_u|=1;
6095           temp_gte_u|=gte_rt[i+1];
6096           temp_gte_u&=~gte_rs[i+1];
6097           // If branch is "likely" (and conditional)
6098           // then we skip the delay slot on the fall-thru path
6099           if(dops[i].likely) {
6100             if(i<slen-1) {
6101               temp_u&=unneeded_reg[i+2];
6102               temp_gte_u&=gte_unneeded[i+2];
6103             }
6104             else
6105             {
6106               temp_u=1;
6107               temp_gte_u=gte_u_unknown;
6108             }
6109           }
6110           temp_u|=(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2);
6111           temp_u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
6112           temp_u|=1;
6113           temp_gte_u|=gte_rt[i];
6114           temp_gte_u&=~gte_rs[i];
6115           unneeded_reg[i]=temp_u;
6116           gte_unneeded[i]=temp_gte_u;
6117           // Only go three levels deep.  This recursion can take an
6118           // excessive amount of time if there are a lot of nested loops.
6119           if(r<2) {
6120             unneeded_registers((ba[i]-start)>>2,i-1,r+1);
6121           }else{
6122             unneeded_reg[(ba[i]-start)>>2]=1;
6123             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
6124           }
6125         } /*else*/ if(1) {
6126           if (is_ujump(i))
6127           {
6128             // Unconditional branch
6129             u=unneeded_reg[(ba[i]-start)>>2];
6130             gte_u=gte_unneeded[(ba[i]-start)>>2];
6131             branch_unneeded_reg[i]=u;
6132             // Merge in delay slot
6133             u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6134             u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6135             u|=1;
6136             gte_u|=gte_rt[i+1];
6137             gte_u&=~gte_rs[i+1];
6138           } else {
6139             // Conditional branch
6140             b=unneeded_reg[(ba[i]-start)>>2];
6141             gte_b=gte_unneeded[(ba[i]-start)>>2];
6142             branch_unneeded_reg[i]=b;
6143             // Branch delay slot
6144             b|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6145             b&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6146             b|=1;
6147             gte_b|=gte_rt[i+1];
6148             gte_b&=~gte_rs[i+1];
6149             // If branch is "likely" then we skip the
6150             // delay slot on the fall-thru path
6151             if(dops[i].likely) {
6152               u=b;
6153               gte_u=gte_b;
6154               if(i<slen-1) {
6155                 u&=unneeded_reg[i+2];
6156                 gte_u&=gte_unneeded[i+2];
6157               }
6158             } else {
6159               u&=b;
6160               gte_u&=gte_b;
6161             }
6162             if(i<slen-1) {
6163               branch_unneeded_reg[i]&=unneeded_reg[i+2];
6164             } else {
6165               branch_unneeded_reg[i]=1;
6166             }
6167           }
6168         }
6169       }
6170     }
6171     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
6172     {
6173       // SYSCALL instruction (software interrupt)
6174       u=1;
6175     }
6176     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
6177     {
6178       // ERET instruction (return from interrupt)
6179       u=1;
6180     }
6181     //u=1; // DEBUG
6182     // Written registers are unneeded
6183     u|=1LL<<dops[i].rt1;
6184     u|=1LL<<dops[i].rt2;
6185     gte_u|=gte_rt[i];
6186     // Accessed registers are needed
6187     u&=~(1LL<<dops[i].rs1);
6188     u&=~(1LL<<dops[i].rs2);
6189     gte_u&=~gte_rs[i];
6190     if(gte_rs[i]&&dops[i].rt1&&(unneeded_reg[i+1]&(1ll<<dops[i].rt1)))
6191       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
6192     // Source-target dependencies
6193     // R0 is always unneeded
6194     u|=1;
6195     // Save it
6196     unneeded_reg[i]=u;
6197     gte_unneeded[i]=gte_u;
6198     /*
6199     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
6200     printf("U:");
6201     int r;
6202     for(r=1;r<=CCREG;r++) {
6203       if((unneeded_reg[i]>>r)&1) {
6204         if(r==HIREG) printf(" HI");
6205         else if(r==LOREG) printf(" LO");
6206         else printf(" r%d",r);
6207       }
6208     }
6209     printf("\n");
6210     */
6211   }
6212 }
6213
6214 // Write back dirty registers as soon as we will no longer modify them,
6215 // so that we don't end up with lots of writes at the branches.
6216 void clean_registers(int istart,int iend,int wr)
6217 {
6218   int i;
6219   int r;
6220   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
6221   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
6222   if(iend==slen-1) {
6223     will_dirty_i=will_dirty_next=0;
6224     wont_dirty_i=wont_dirty_next=0;
6225   }else{
6226     will_dirty_i=will_dirty_next=will_dirty[iend+1];
6227     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
6228   }
6229   for (i=iend;i>=istart;i--)
6230   {
6231     if(dops[i].itype==RJUMP||dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
6232     {
6233       if(ba[i]<start || ba[i]>=(start+slen*4))
6234       {
6235         // Branch out of this block, flush all regs
6236         if (is_ujump(i))
6237         {
6238           // Unconditional branch
6239           will_dirty_i=0;
6240           wont_dirty_i=0;
6241           // Merge in delay slot (will dirty)
6242           for(r=0;r<HOST_REGS;r++) {
6243             if(r!=EXCLUDE_REG) {
6244               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6245               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6246               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6247               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6248               if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6249               if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6250               if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6251               if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6252               if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6253               if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6254               if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6255               if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6256               if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6257               if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6258             }
6259           }
6260         }
6261         else
6262         {
6263           // Conditional branch
6264           will_dirty_i=0;
6265           wont_dirty_i=wont_dirty_next;
6266           // Merge in delay slot (will dirty)
6267           for(r=0;r<HOST_REGS;r++) {
6268             if(r!=EXCLUDE_REG) {
6269               if(!dops[i].likely) {
6270                 // Might not dirty if likely branch is not taken
6271                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6272                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6273                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6274                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6275                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6276                 if(branch_regs[i].regmap[r]==0) will_dirty_i&=~(1<<r);
6277                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6278                 //if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6279                 //if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6280                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6281                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6282                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6283                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6284                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6285               }
6286             }
6287           }
6288         }
6289         // Merge in delay slot (wont dirty)
6290         for(r=0;r<HOST_REGS;r++) {
6291           if(r!=EXCLUDE_REG) {
6292             if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6293             if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6294             if((regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6295             if((regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6296             if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6297             if((branch_regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6298             if((branch_regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6299             if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6300             if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6301             if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6302           }
6303         }
6304         if(wr) {
6305           #ifndef DESTRUCTIVE_WRITEBACK
6306           branch_regs[i].dirty&=wont_dirty_i;
6307           #endif
6308           branch_regs[i].dirty|=will_dirty_i;
6309         }
6310       }
6311       else
6312       {
6313         // Internal branch
6314         if(ba[i]<=start+i*4) {
6315           // Backward branch
6316           if (is_ujump(i))
6317           {
6318             // Unconditional branch
6319             temp_will_dirty=0;
6320             temp_wont_dirty=0;
6321             // Merge in delay slot (will dirty)
6322             for(r=0;r<HOST_REGS;r++) {
6323               if(r!=EXCLUDE_REG) {
6324                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6325                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6326                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6327                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6328                 if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6329                 if(branch_regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6330                 if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6331                 if((regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6332                 if((regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6333                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6334                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6335                 if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6336                 if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6337                 if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6338               }
6339             }
6340           } else {
6341             // Conditional branch (not taken case)
6342             temp_will_dirty=will_dirty_next;
6343             temp_wont_dirty=wont_dirty_next;
6344             // Merge in delay slot (will dirty)
6345             for(r=0;r<HOST_REGS;r++) {
6346               if(r!=EXCLUDE_REG) {
6347                 if(!dops[i].likely) {
6348                   // Will not dirty if likely branch is not taken
6349                   if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6350                   if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6351                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6352                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6353                   if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6354                   if(branch_regs[i].regmap[r]==0) temp_will_dirty&=~(1<<r);
6355                   if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6356                   //if((regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6357                   //if((regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6358                   if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6359                   if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6360                   if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6361                   if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6362                   if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6363                 }
6364               }
6365             }
6366           }
6367           // Merge in delay slot (wont dirty)
6368           for(r=0;r<HOST_REGS;r++) {
6369             if(r!=EXCLUDE_REG) {
6370               if((regs[i].regmap[r]&63)==dops[i].rt1) temp_wont_dirty|=1<<r;
6371               if((regs[i].regmap[r]&63)==dops[i].rt2) temp_wont_dirty|=1<<r;
6372               if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_wont_dirty|=1<<r;
6373               if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_wont_dirty|=1<<r;
6374               if(regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6375               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_wont_dirty|=1<<r;
6376               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_wont_dirty|=1<<r;
6377               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_wont_dirty|=1<<r;
6378               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_wont_dirty|=1<<r;
6379               if(branch_regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6380             }
6381           }
6382           // Deal with changed mappings
6383           if(i<iend) {
6384             for(r=0;r<HOST_REGS;r++) {
6385               if(r!=EXCLUDE_REG) {
6386                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
6387                   temp_will_dirty&=~(1<<r);
6388                   temp_wont_dirty&=~(1<<r);
6389                   if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6390                     temp_will_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6391                     temp_wont_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6392                   } else {
6393                     temp_will_dirty|=1<<r;
6394                     temp_wont_dirty|=1<<r;
6395                   }
6396                 }
6397               }
6398             }
6399           }
6400           if(wr) {
6401             will_dirty[i]=temp_will_dirty;
6402             wont_dirty[i]=temp_wont_dirty;
6403             clean_registers((ba[i]-start)>>2,i-1,0);
6404           }else{
6405             // Limit recursion.  It can take an excessive amount
6406             // of time if there are a lot of nested loops.
6407             will_dirty[(ba[i]-start)>>2]=0;
6408             wont_dirty[(ba[i]-start)>>2]=-1;
6409           }
6410         }
6411         /*else*/ if(1)
6412         {
6413           if (is_ujump(i))
6414           {
6415             // Unconditional branch
6416             will_dirty_i=0;
6417             wont_dirty_i=0;
6418           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6419             for(r=0;r<HOST_REGS;r++) {
6420               if(r!=EXCLUDE_REG) {
6421                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6422                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
6423                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6424                 }
6425                 if(branch_regs[i].regmap[r]>=0) {
6426                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6427                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6428                 }
6429               }
6430             }
6431           //}
6432             // Merge in delay slot
6433             for(r=0;r<HOST_REGS;r++) {
6434               if(r!=EXCLUDE_REG) {
6435                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6436                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6437                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6438                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6439                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6440                 if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6441                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6442                 if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6443                 if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6444                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6445                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6446                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6447                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6448                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6449               }
6450             }
6451           } else {
6452             // Conditional branch
6453             will_dirty_i=will_dirty_next;
6454             wont_dirty_i=wont_dirty_next;
6455           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6456             for(r=0;r<HOST_REGS;r++) {
6457               if(r!=EXCLUDE_REG) {
6458                 signed char target_reg=branch_regs[i].regmap[r];
6459                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6460                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6461                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6462                 }
6463                 else if(target_reg>=0) {
6464                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6465                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6466                 }
6467               }
6468             }
6469           //}
6470             // Merge in delay slot
6471             for(r=0;r<HOST_REGS;r++) {
6472               if(r!=EXCLUDE_REG) {
6473                 if(!dops[i].likely) {
6474                   // Might not dirty if likely branch is not taken
6475                   if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6476                   if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6477                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6478                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6479                   if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6480                   if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6481                   if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6482                   //if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6483                   //if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6484                   if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6485                   if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6486                   if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6487                   if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6488                   if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6489                 }
6490               }
6491             }
6492           }
6493           // Merge in delay slot (won't dirty)
6494           for(r=0;r<HOST_REGS;r++) {
6495             if(r!=EXCLUDE_REG) {
6496               if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6497               if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6498               if((regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6499               if((regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6500               if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6501               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6502               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6503               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6504               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6505               if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6506             }
6507           }
6508           if(wr) {
6509             #ifndef DESTRUCTIVE_WRITEBACK
6510             branch_regs[i].dirty&=wont_dirty_i;
6511             #endif
6512             branch_regs[i].dirty|=will_dirty_i;
6513           }
6514         }
6515       }
6516     }
6517     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
6518     {
6519       // SYSCALL instruction (software interrupt)
6520       will_dirty_i=0;
6521       wont_dirty_i=0;
6522     }
6523     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
6524     {
6525       // ERET instruction (return from interrupt)
6526       will_dirty_i=0;
6527       wont_dirty_i=0;
6528     }
6529     will_dirty_next=will_dirty_i;
6530     wont_dirty_next=wont_dirty_i;
6531     for(r=0;r<HOST_REGS;r++) {
6532       if(r!=EXCLUDE_REG) {
6533         if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6534         if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6535         if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6536         if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6537         if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6538         if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6539         if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6540         if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6541         if(i>istart) {
6542           if(dops[i].itype!=RJUMP&&dops[i].itype!=UJUMP&&dops[i].itype!=CJUMP&&dops[i].itype!=SJUMP)
6543           {
6544             // Don't store a register immediately after writing it,
6545             // may prevent dual-issue.
6546             if((regs[i].regmap[r]&63)==dops[i-1].rt1) wont_dirty_i|=1<<r;
6547             if((regs[i].regmap[r]&63)==dops[i-1].rt2) wont_dirty_i|=1<<r;
6548           }
6549         }
6550       }
6551     }
6552     // Save it
6553     will_dirty[i]=will_dirty_i;
6554     wont_dirty[i]=wont_dirty_i;
6555     // Mark registers that won't be dirtied as not dirty
6556     if(wr) {
6557         regs[i].dirty|=will_dirty_i;
6558         #ifndef DESTRUCTIVE_WRITEBACK
6559         regs[i].dirty&=wont_dirty_i;
6560         if(dops[i].itype==RJUMP||dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
6561         {
6562           if (i < iend-1 && !is_ujump(i)) {
6563             for(r=0;r<HOST_REGS;r++) {
6564               if(r!=EXCLUDE_REG) {
6565                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
6566                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
6567                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6568               }
6569             }
6570           }
6571         }
6572         else
6573         {
6574           if(i<iend) {
6575             for(r=0;r<HOST_REGS;r++) {
6576               if(r!=EXCLUDE_REG) {
6577                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
6578                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
6579                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6580               }
6581             }
6582           }
6583         }
6584         #endif
6585       //}
6586     }
6587     // Deal with changed mappings
6588     temp_will_dirty=will_dirty_i;
6589     temp_wont_dirty=wont_dirty_i;
6590     for(r=0;r<HOST_REGS;r++) {
6591       if(r!=EXCLUDE_REG) {
6592         int nr;
6593         if(regs[i].regmap[r]==regmap_pre[i][r]) {
6594           if(wr) {
6595             #ifndef DESTRUCTIVE_WRITEBACK
6596             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6597             #endif
6598             regs[i].wasdirty|=will_dirty_i&(1<<r);
6599           }
6600         }
6601         else if(regmap_pre[i][r]>=0&&(nr=get_reg(regs[i].regmap,regmap_pre[i][r]))>=0) {
6602           // Register moved to a different register
6603           will_dirty_i&=~(1<<r);
6604           wont_dirty_i&=~(1<<r);
6605           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
6606           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
6607           if(wr) {
6608             #ifndef DESTRUCTIVE_WRITEBACK
6609             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6610             #endif
6611             regs[i].wasdirty|=will_dirty_i&(1<<r);
6612           }
6613         }
6614         else {
6615           will_dirty_i&=~(1<<r);
6616           wont_dirty_i&=~(1<<r);
6617           if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6618             will_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6619             wont_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6620           } else {
6621             wont_dirty_i|=1<<r;
6622             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
6623           }
6624         }
6625       }
6626     }
6627   }
6628 }
6629
6630 #ifdef DISASM
6631   /* disassembly */
6632 void disassemble_inst(int i)
6633 {
6634     if (dops[i].bt) printf("*"); else printf(" ");
6635     switch(dops[i].itype) {
6636       case UJUMP:
6637         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6638       case CJUMP:
6639         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;
6640       case SJUMP:
6641         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;
6642       case RJUMP:
6643         if (dops[i].opcode==0x9&&dops[i].rt1!=31)
6644           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1);
6645         else
6646           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6647         break;
6648       case SPAN:
6649         printf (" %x: %s (pagespan) r%d,r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2,ba[i]);break;
6650       case IMM16:
6651         if(dops[i].opcode==0xf) //LUI
6652           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],dops[i].rt1,imm[i]&0xffff);
6653         else
6654           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6655         break;
6656       case LOAD:
6657       case LOADLR:
6658         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6659         break;
6660       case STORE:
6661       case STORELR:
6662         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rs2,dops[i].rs1,imm[i]);
6663         break;
6664       case ALU:
6665       case SHIFT:
6666         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,dops[i].rs2);
6667         break;
6668       case MULTDIV:
6669         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2);
6670         break;
6671       case SHIFTIMM:
6672         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6673         break;
6674       case MOV:
6675         if((dops[i].opcode2&0x1d)==0x10)
6676           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rt1);
6677         else if((dops[i].opcode2&0x1d)==0x11)
6678           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6679         else
6680           printf (" %x: %s\n",start+i*4,insn[i]);
6681         break;
6682       case COP0:
6683         if(dops[i].opcode2==0)
6684           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC0
6685         else if(dops[i].opcode2==4)
6686           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC0
6687         else printf (" %x: %s\n",start+i*4,insn[i]);
6688         break;
6689       case COP1:
6690         if(dops[i].opcode2<3)
6691           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC1
6692         else if(dops[i].opcode2>3)
6693           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC1
6694         else printf (" %x: %s\n",start+i*4,insn[i]);
6695         break;
6696       case COP2:
6697         if(dops[i].opcode2<3)
6698           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC2
6699         else if(dops[i].opcode2>3)
6700           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC2
6701         else printf (" %x: %s\n",start+i*4,insn[i]);
6702         break;
6703       case C1LS:
6704         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6705         break;
6706       case C2LS:
6707         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6708         break;
6709       case INTCALL:
6710         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6711         break;
6712       default:
6713         //printf (" %s %8x\n",insn[i],source[i]);
6714         printf (" %x: %s\n",start+i*4,insn[i]);
6715     }
6716 }
6717 #else
6718 static void disassemble_inst(int i) {}
6719 #endif // DISASM
6720
6721 #define DRC_TEST_VAL 0x74657374
6722
6723 static void new_dynarec_test(void)
6724 {
6725   int (*testfunc)(void);
6726   void *beginning;
6727   int ret[2];
6728   size_t i;
6729
6730   // check structure linkage
6731   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6732   {
6733     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6734   }
6735
6736   SysPrintf("testing if we can run recompiled code...\n");
6737   ((volatile u_int *)out)[0]++; // make cache dirty
6738
6739   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6740     out = ndrc->translation_cache;
6741     beginning = start_block();
6742     emit_movimm(DRC_TEST_VAL + i, 0); // test
6743     emit_ret();
6744     literal_pool(0);
6745     end_block(beginning);
6746     testfunc = beginning;
6747     ret[i] = testfunc();
6748   }
6749
6750   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6751     SysPrintf("test passed.\n");
6752   else
6753     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6754   out = ndrc->translation_cache;
6755 }
6756
6757 // clear the state completely, instead of just marking
6758 // things invalid like invalidate_all_pages() does
6759 void new_dynarec_clear_full(void)
6760 {
6761   int n;
6762   out = ndrc->translation_cache;
6763   memset(invalid_code,1,sizeof(invalid_code));
6764   memset(hash_table,0xff,sizeof(hash_table));
6765   memset(mini_ht,-1,sizeof(mini_ht));
6766   memset(restore_candidate,0,sizeof(restore_candidate));
6767   memset(shadow,0,sizeof(shadow));
6768   copy=shadow;
6769   expirep=16384; // Expiry pointer, +2 blocks
6770   pending_exception=0;
6771   literalcount=0;
6772   stop_after_jal=0;
6773   inv_code_start=inv_code_end=~0;
6774   // TLB
6775   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6776   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6777   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6778
6779   cycle_multiplier_old = cycle_multiplier;
6780   new_dynarec_hacks_old = new_dynarec_hacks;
6781 }
6782
6783 void new_dynarec_init(void)
6784 {
6785   SysPrintf("Init new dynarec\n");
6786
6787 #ifdef BASE_ADDR_DYNAMIC
6788   #ifdef VITA
6789   sceBlock = sceKernelAllocMemBlockForVM("code", 1 << TARGET_SIZE_2);
6790   if (sceBlock < 0)
6791     SysPrintf("sceKernelAllocMemBlockForVM failed\n");
6792   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6793   if (ret < 0)
6794     SysPrintf("sceKernelGetMemBlockBase failed\n");
6795   #else
6796   uintptr_t desired_addr = 0;
6797   #ifdef __ELF__
6798   extern char _end;
6799   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6800   #endif
6801   ndrc = mmap((void *)desired_addr, sizeof(*ndrc),
6802             PROT_READ | PROT_WRITE | PROT_EXEC,
6803             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
6804   if (ndrc == MAP_FAILED) {
6805     SysPrintf("mmap() failed: %s\n", strerror(errno));
6806     abort();
6807   }
6808   #endif
6809 #else
6810   #ifndef NO_WRITE_EXEC
6811   // not all systems allow execute in data segment by default
6812   if (mprotect(ndrc, sizeof(ndrc->translation_cache) + sizeof(ndrc->tramp.ops),
6813                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6814     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6815   #endif
6816 #endif
6817   out = ndrc->translation_cache;
6818   cycle_multiplier=200;
6819   new_dynarec_clear_full();
6820 #ifdef HOST_IMM8
6821   // Copy this into local area so we don't have to put it in every literal pool
6822   invc_ptr=invalid_code;
6823 #endif
6824   arch_init();
6825   new_dynarec_test();
6826 #ifndef RAM_FIXED
6827   ram_offset=(uintptr_t)rdram-0x80000000;
6828 #endif
6829   if (ram_offset!=0)
6830     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6831 }
6832
6833 void new_dynarec_cleanup(void)
6834 {
6835   int n;
6836 #ifdef BASE_ADDR_DYNAMIC
6837   #ifdef VITA
6838   sceKernelFreeMemBlock(sceBlock);
6839   sceBlock = -1;
6840   #else
6841   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6842     SysPrintf("munmap() failed\n");
6843   #endif
6844 #endif
6845   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6846   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6847   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6848   #ifdef ROM_COPY
6849   if (munmap (ROM_COPY, 67108864) < 0) {SysPrintf("munmap() failed\n");}
6850   #endif
6851 }
6852
6853 static u_int *get_source_start(u_int addr, u_int *limit)
6854 {
6855   if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6856     cycle_multiplier_override = 0;
6857
6858   if (addr < 0x00200000 ||
6859     (0xa0000000 <= addr && addr < 0xa0200000))
6860   {
6861     // used for BIOS calls mostly?
6862     *limit = (addr&0xa0000000)|0x00200000;
6863     return (u_int *)(rdram + (addr&0x1fffff));
6864   }
6865   else if (!Config.HLE && (
6866     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
6867     (0xbfc00000 <= addr && addr < 0xbfc80000)))
6868   {
6869     // BIOS. The multiplier should be much higher as it's uncached 8bit mem,
6870     // but timings in PCSX are too tied to the interpreter's BIAS
6871     if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6872       cycle_multiplier_override = 200;
6873
6874     *limit = (addr & 0xfff00000) | 0x80000;
6875     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
6876   }
6877   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
6878     *limit = (addr & 0x80600000) + 0x00200000;
6879     return (u_int *)(rdram + (addr&0x1fffff));
6880   }
6881   return NULL;
6882 }
6883
6884 static u_int scan_for_ret(u_int addr)
6885 {
6886   u_int limit = 0;
6887   u_int *mem;
6888
6889   mem = get_source_start(addr, &limit);
6890   if (mem == NULL)
6891     return addr;
6892
6893   if (limit > addr + 0x1000)
6894     limit = addr + 0x1000;
6895   for (; addr < limit; addr += 4, mem++) {
6896     if (*mem == 0x03e00008) // jr $ra
6897       return addr + 8;
6898   }
6899   return addr;
6900 }
6901
6902 struct savestate_block {
6903   uint32_t addr;
6904   uint32_t regflags;
6905 };
6906
6907 static int addr_cmp(const void *p1_, const void *p2_)
6908 {
6909   const struct savestate_block *p1 = p1_, *p2 = p2_;
6910   return p1->addr - p2->addr;
6911 }
6912
6913 int new_dynarec_save_blocks(void *save, int size)
6914 {
6915   struct savestate_block *blocks = save;
6916   int maxcount = size / sizeof(blocks[0]);
6917   struct savestate_block tmp_blocks[1024];
6918   struct ll_entry *head;
6919   int p, s, d, o, bcnt;
6920   u_int addr;
6921
6922   o = 0;
6923   for (p = 0; p < ARRAY_SIZE(jump_in); p++) {
6924     bcnt = 0;
6925     for (head = jump_in[p]; head != NULL; head = head->next) {
6926       tmp_blocks[bcnt].addr = head->vaddr;
6927       tmp_blocks[bcnt].regflags = head->reg_sv_flags;
6928       bcnt++;
6929     }
6930     if (bcnt < 1)
6931       continue;
6932     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
6933
6934     addr = tmp_blocks[0].addr;
6935     for (s = d = 0; s < bcnt; s++) {
6936       if (tmp_blocks[s].addr < addr)
6937         continue;
6938       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
6939         tmp_blocks[d++] = tmp_blocks[s];
6940       addr = scan_for_ret(tmp_blocks[s].addr);
6941     }
6942
6943     if (o + d > maxcount)
6944       d = maxcount - o;
6945     memcpy(&blocks[o], tmp_blocks, d * sizeof(blocks[0]));
6946     o += d;
6947   }
6948
6949   return o * sizeof(blocks[0]);
6950 }
6951
6952 void new_dynarec_load_blocks(const void *save, int size)
6953 {
6954   const struct savestate_block *blocks = save;
6955   int count = size / sizeof(blocks[0]);
6956   u_int regs_save[32];
6957   uint32_t f;
6958   int i, b;
6959
6960   get_addr(psxRegs.pc);
6961
6962   // change GPRs for speculation to at least partially work..
6963   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
6964   for (i = 1; i < 32; i++)
6965     psxRegs.GPR.r[i] = 0x80000000;
6966
6967   for (b = 0; b < count; b++) {
6968     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
6969       if (f & 1)
6970         psxRegs.GPR.r[i] = 0x1f800000;
6971     }
6972
6973     get_addr(blocks[b].addr);
6974
6975     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
6976       if (f & 1)
6977         psxRegs.GPR.r[i] = 0x80000000;
6978     }
6979   }
6980
6981   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
6982 }
6983
6984 int new_recompile_block(u_int addr)
6985 {
6986   u_int pagelimit = 0;
6987   u_int state_rflags = 0;
6988   int i;
6989
6990   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
6991   //printf("TRACE: count=%d next=%d (compile %x)\n",Count,next_interupt,addr);
6992   //if(debug)
6993   //printf("fpu mapping=%x enabled=%x\n",(Status & 0x04000000)>>26,(Status & 0x20000000)>>29);
6994
6995   // this is just for speculation
6996   for (i = 1; i < 32; i++) {
6997     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
6998       state_rflags |= 1 << i;
6999   }
7000
7001   start = (u_int)addr&~3;
7002   //assert(((u_int)addr&1)==0); // start-in-delay-slot flag
7003   new_dynarec_did_compile=1;
7004   if (Config.HLE && start == 0x80001000) // hlecall
7005   {
7006     // XXX: is this enough? Maybe check hleSoftCall?
7007     void *beginning=start_block();
7008     u_int page=get_page(start);
7009
7010     invalid_code[start>>12]=0;
7011     emit_movimm(start,0);
7012     emit_writeword(0,&pcaddr);
7013     emit_far_jump(new_dyna_leave);
7014     literal_pool(0);
7015     end_block(beginning);
7016     ll_add_flags(jump_in+page,start,state_rflags,(void *)beginning);
7017     return 0;
7018   }
7019
7020   source = get_source_start(start, &pagelimit);
7021   if (source == NULL) {
7022     SysPrintf("Compile at bogus memory address: %08x\n", addr);
7023     abort();
7024   }
7025
7026   /* Pass 1: disassemble */
7027   /* Pass 2: register dependencies, branch targets */
7028   /* Pass 3: register allocation */
7029   /* Pass 4: branch dependencies */
7030   /* Pass 5: pre-alloc */
7031   /* Pass 6: optimize clean/dirty state */
7032   /* Pass 7: flag 32-bit registers */
7033   /* Pass 8: assembly */
7034   /* Pass 9: linker */
7035   /* Pass 10: garbage collection / free memory */
7036
7037   int j;
7038   int done=0;
7039   unsigned int type,op,op2;
7040
7041   //printf("addr = %x source = %x %x\n", addr,source,source[0]);
7042
7043   /* Pass 1 disassembly */
7044
7045   for(i=0;!done;i++) {
7046     dops[i].bt=0;
7047     dops[i].likely=0;
7048     dops[i].ooo=0;
7049     op2=0;
7050     minimum_free_regs[i]=0;
7051     dops[i].opcode=op=source[i]>>26;
7052     switch(op)
7053     {
7054       case 0x00: strcpy(insn[i],"special"); type=NI;
7055         op2=source[i]&0x3f;
7056         switch(op2)
7057         {
7058           case 0x00: strcpy(insn[i],"SLL"); type=SHIFTIMM; break;
7059           case 0x02: strcpy(insn[i],"SRL"); type=SHIFTIMM; break;
7060           case 0x03: strcpy(insn[i],"SRA"); type=SHIFTIMM; break;
7061           case 0x04: strcpy(insn[i],"SLLV"); type=SHIFT; break;
7062           case 0x06: strcpy(insn[i],"SRLV"); type=SHIFT; break;
7063           case 0x07: strcpy(insn[i],"SRAV"); type=SHIFT; break;
7064           case 0x08: strcpy(insn[i],"JR"); type=RJUMP; break;
7065           case 0x09: strcpy(insn[i],"JALR"); type=RJUMP; break;
7066           case 0x0C: strcpy(insn[i],"SYSCALL"); type=SYSCALL; break;
7067           case 0x0D: strcpy(insn[i],"BREAK"); type=OTHER; break;
7068           case 0x0F: strcpy(insn[i],"SYNC"); type=OTHER; break;
7069           case 0x10: strcpy(insn[i],"MFHI"); type=MOV; break;
7070           case 0x11: strcpy(insn[i],"MTHI"); type=MOV; break;
7071           case 0x12: strcpy(insn[i],"MFLO"); type=MOV; break;
7072           case 0x13: strcpy(insn[i],"MTLO"); type=MOV; break;
7073           case 0x18: strcpy(insn[i],"MULT"); type=MULTDIV; break;
7074           case 0x19: strcpy(insn[i],"MULTU"); type=MULTDIV; break;
7075           case 0x1A: strcpy(insn[i],"DIV"); type=MULTDIV; break;
7076           case 0x1B: strcpy(insn[i],"DIVU"); type=MULTDIV; break;
7077           case 0x20: strcpy(insn[i],"ADD"); type=ALU; break;
7078           case 0x21: strcpy(insn[i],"ADDU"); type=ALU; break;
7079           case 0x22: strcpy(insn[i],"SUB"); type=ALU; break;
7080           case 0x23: strcpy(insn[i],"SUBU"); type=ALU; break;
7081           case 0x24: strcpy(insn[i],"AND"); type=ALU; break;
7082           case 0x25: strcpy(insn[i],"OR"); type=ALU; break;
7083           case 0x26: strcpy(insn[i],"XOR"); type=ALU; break;
7084           case 0x27: strcpy(insn[i],"NOR"); type=ALU; break;
7085           case 0x2A: strcpy(insn[i],"SLT"); type=ALU; break;
7086           case 0x2B: strcpy(insn[i],"SLTU"); type=ALU; break;
7087           case 0x30: strcpy(insn[i],"TGE"); type=NI; break;
7088           case 0x31: strcpy(insn[i],"TGEU"); type=NI; break;
7089           case 0x32: strcpy(insn[i],"TLT"); type=NI; break;
7090           case 0x33: strcpy(insn[i],"TLTU"); type=NI; break;
7091           case 0x34: strcpy(insn[i],"TEQ"); type=NI; break;
7092           case 0x36: strcpy(insn[i],"TNE"); type=NI; break;
7093 #if 0
7094           case 0x14: strcpy(insn[i],"DSLLV"); type=SHIFT; break;
7095           case 0x16: strcpy(insn[i],"DSRLV"); type=SHIFT; break;
7096           case 0x17: strcpy(insn[i],"DSRAV"); type=SHIFT; break;
7097           case 0x1C: strcpy(insn[i],"DMULT"); type=MULTDIV; break;
7098           case 0x1D: strcpy(insn[i],"DMULTU"); type=MULTDIV; break;
7099           case 0x1E: strcpy(insn[i],"DDIV"); type=MULTDIV; break;
7100           case 0x1F: strcpy(insn[i],"DDIVU"); type=MULTDIV; break;
7101           case 0x2C: strcpy(insn[i],"DADD"); type=ALU; break;
7102           case 0x2D: strcpy(insn[i],"DADDU"); type=ALU; break;
7103           case 0x2E: strcpy(insn[i],"DSUB"); type=ALU; break;
7104           case 0x2F: strcpy(insn[i],"DSUBU"); type=ALU; break;
7105           case 0x38: strcpy(insn[i],"DSLL"); type=SHIFTIMM; break;
7106           case 0x3A: strcpy(insn[i],"DSRL"); type=SHIFTIMM; break;
7107           case 0x3B: strcpy(insn[i],"DSRA"); type=SHIFTIMM; break;
7108           case 0x3C: strcpy(insn[i],"DSLL32"); type=SHIFTIMM; break;
7109           case 0x3E: strcpy(insn[i],"DSRL32"); type=SHIFTIMM; break;
7110           case 0x3F: strcpy(insn[i],"DSRA32"); type=SHIFTIMM; break;
7111 #endif
7112         }
7113         break;
7114       case 0x01: strcpy(insn[i],"regimm"); type=NI;
7115         op2=(source[i]>>16)&0x1f;
7116         switch(op2)
7117         {
7118           case 0x00: strcpy(insn[i],"BLTZ"); type=SJUMP; break;
7119           case 0x01: strcpy(insn[i],"BGEZ"); type=SJUMP; break;
7120           //case 0x02: strcpy(insn[i],"BLTZL"); type=SJUMP; break;
7121           //case 0x03: strcpy(insn[i],"BGEZL"); type=SJUMP; break;
7122           //case 0x08: strcpy(insn[i],"TGEI"); type=NI; break;
7123           //case 0x09: strcpy(insn[i],"TGEIU"); type=NI; break;
7124           //case 0x0A: strcpy(insn[i],"TLTI"); type=NI; break;
7125           //case 0x0B: strcpy(insn[i],"TLTIU"); type=NI; break;
7126           //case 0x0C: strcpy(insn[i],"TEQI"); type=NI; break;
7127           //case 0x0E: strcpy(insn[i],"TNEI"); type=NI; break;
7128           case 0x10: strcpy(insn[i],"BLTZAL"); type=SJUMP; break;
7129           case 0x11: strcpy(insn[i],"BGEZAL"); type=SJUMP; break;
7130           //case 0x12: strcpy(insn[i],"BLTZALL"); type=SJUMP; break;
7131           //case 0x13: strcpy(insn[i],"BGEZALL"); type=SJUMP; break;
7132         }
7133         break;
7134       case 0x02: strcpy(insn[i],"J"); type=UJUMP; break;
7135       case 0x03: strcpy(insn[i],"JAL"); type=UJUMP; break;
7136       case 0x04: strcpy(insn[i],"BEQ"); type=CJUMP; break;
7137       case 0x05: strcpy(insn[i],"BNE"); type=CJUMP; break;
7138       case 0x06: strcpy(insn[i],"BLEZ"); type=CJUMP; break;
7139       case 0x07: strcpy(insn[i],"BGTZ"); type=CJUMP; break;
7140       case 0x08: strcpy(insn[i],"ADDI"); type=IMM16; break;
7141       case 0x09: strcpy(insn[i],"ADDIU"); type=IMM16; break;
7142       case 0x0A: strcpy(insn[i],"SLTI"); type=IMM16; break;
7143       case 0x0B: strcpy(insn[i],"SLTIU"); type=IMM16; break;
7144       case 0x0C: strcpy(insn[i],"ANDI"); type=IMM16; break;
7145       case 0x0D: strcpy(insn[i],"ORI"); type=IMM16; break;
7146       case 0x0E: strcpy(insn[i],"XORI"); type=IMM16; break;
7147       case 0x0F: strcpy(insn[i],"LUI"); type=IMM16; break;
7148       case 0x10: strcpy(insn[i],"cop0"); type=NI;
7149         op2=(source[i]>>21)&0x1f;
7150         switch(op2)
7151         {
7152           case 0x00: strcpy(insn[i],"MFC0"); type=COP0; break;
7153           case 0x02: strcpy(insn[i],"CFC0"); type=COP0; break;
7154           case 0x04: strcpy(insn[i],"MTC0"); type=COP0; break;
7155           case 0x06: strcpy(insn[i],"CTC0"); type=COP0; break;
7156           case 0x10: strcpy(insn[i],"RFE"); type=COP0; break;
7157         }
7158         break;
7159       case 0x11: strcpy(insn[i],"cop1"); type=COP1;
7160         op2=(source[i]>>21)&0x1f;
7161         break;
7162 #if 0
7163       case 0x14: strcpy(insn[i],"BEQL"); type=CJUMP; break;
7164       case 0x15: strcpy(insn[i],"BNEL"); type=CJUMP; break;
7165       case 0x16: strcpy(insn[i],"BLEZL"); type=CJUMP; break;
7166       case 0x17: strcpy(insn[i],"BGTZL"); type=CJUMP; break;
7167       case 0x18: strcpy(insn[i],"DADDI"); type=IMM16; break;
7168       case 0x19: strcpy(insn[i],"DADDIU"); type=IMM16; break;
7169       case 0x1A: strcpy(insn[i],"LDL"); type=LOADLR; break;
7170       case 0x1B: strcpy(insn[i],"LDR"); type=LOADLR; break;
7171 #endif
7172       case 0x20: strcpy(insn[i],"LB"); type=LOAD; break;
7173       case 0x21: strcpy(insn[i],"LH"); type=LOAD; break;
7174       case 0x22: strcpy(insn[i],"LWL"); type=LOADLR; break;
7175       case 0x23: strcpy(insn[i],"LW"); type=LOAD; break;
7176       case 0x24: strcpy(insn[i],"LBU"); type=LOAD; break;
7177       case 0x25: strcpy(insn[i],"LHU"); type=LOAD; break;
7178       case 0x26: strcpy(insn[i],"LWR"); type=LOADLR; break;
7179 #if 0
7180       case 0x27: strcpy(insn[i],"LWU"); type=LOAD; break;
7181 #endif
7182       case 0x28: strcpy(insn[i],"SB"); type=STORE; break;
7183       case 0x29: strcpy(insn[i],"SH"); type=STORE; break;
7184       case 0x2A: strcpy(insn[i],"SWL"); type=STORELR; break;
7185       case 0x2B: strcpy(insn[i],"SW"); type=STORE; break;
7186 #if 0
7187       case 0x2C: strcpy(insn[i],"SDL"); type=STORELR; break;
7188       case 0x2D: strcpy(insn[i],"SDR"); type=STORELR; break;
7189 #endif
7190       case 0x2E: strcpy(insn[i],"SWR"); type=STORELR; break;
7191       case 0x2F: strcpy(insn[i],"CACHE"); type=NOP; break;
7192       case 0x30: strcpy(insn[i],"LL"); type=NI; break;
7193       case 0x31: strcpy(insn[i],"LWC1"); type=C1LS; break;
7194 #if 0
7195       case 0x34: strcpy(insn[i],"LLD"); type=NI; break;
7196       case 0x35: strcpy(insn[i],"LDC1"); type=C1LS; break;
7197       case 0x37: strcpy(insn[i],"LD"); type=LOAD; break;
7198 #endif
7199       case 0x38: strcpy(insn[i],"SC"); type=NI; break;
7200       case 0x39: strcpy(insn[i],"SWC1"); type=C1LS; break;
7201 #if 0
7202       case 0x3C: strcpy(insn[i],"SCD"); type=NI; break;
7203       case 0x3D: strcpy(insn[i],"SDC1"); type=C1LS; break;
7204       case 0x3F: strcpy(insn[i],"SD"); type=STORE; break;
7205 #endif
7206       case 0x12: strcpy(insn[i],"COP2"); type=NI;
7207         op2=(source[i]>>21)&0x1f;
7208         //if (op2 & 0x10)
7209         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
7210           if (gte_handlers[source[i]&0x3f]!=NULL) {
7211             if (gte_regnames[source[i]&0x3f]!=NULL)
7212               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
7213             else
7214               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
7215             type=C2OP;
7216           }
7217         }
7218         else switch(op2)
7219         {
7220           case 0x00: strcpy(insn[i],"MFC2"); type=COP2; break;
7221           case 0x02: strcpy(insn[i],"CFC2"); type=COP2; break;
7222           case 0x04: strcpy(insn[i],"MTC2"); type=COP2; break;
7223           case 0x06: strcpy(insn[i],"CTC2"); type=COP2; break;
7224         }
7225         break;
7226       case 0x32: strcpy(insn[i],"LWC2"); type=C2LS; break;
7227       case 0x3A: strcpy(insn[i],"SWC2"); type=C2LS; break;
7228       case 0x3B: strcpy(insn[i],"HLECALL"); type=HLECALL; break;
7229       default: strcpy(insn[i],"???"); type=NI;
7230         SysPrintf("NI %08x @%08x (%08x)\n", source[i], addr + i*4, addr);
7231         break;
7232     }
7233     dops[i].itype=type;
7234     dops[i].opcode2=op2;
7235     /* Get registers/immediates */
7236     dops[i].lt1=0;
7237     gte_rs[i]=gte_rt[i]=0;
7238     switch(type) {
7239       case LOAD:
7240         dops[i].rs1=(source[i]>>21)&0x1f;
7241         dops[i].rs2=0;
7242         dops[i].rt1=(source[i]>>16)&0x1f;
7243         dops[i].rt2=0;
7244         imm[i]=(short)source[i];
7245         break;
7246       case STORE:
7247       case STORELR:
7248         dops[i].rs1=(source[i]>>21)&0x1f;
7249         dops[i].rs2=(source[i]>>16)&0x1f;
7250         dops[i].rt1=0;
7251         dops[i].rt2=0;
7252         imm[i]=(short)source[i];
7253         break;
7254       case LOADLR:
7255         // LWL/LWR only load part of the register,
7256         // therefore the target register must be treated as a source too
7257         dops[i].rs1=(source[i]>>21)&0x1f;
7258         dops[i].rs2=(source[i]>>16)&0x1f;
7259         dops[i].rt1=(source[i]>>16)&0x1f;
7260         dops[i].rt2=0;
7261         imm[i]=(short)source[i];
7262         break;
7263       case IMM16:
7264         if (op==0x0f) dops[i].rs1=0; // LUI instruction has no source register
7265         else dops[i].rs1=(source[i]>>21)&0x1f;
7266         dops[i].rs2=0;
7267         dops[i].rt1=(source[i]>>16)&0x1f;
7268         dops[i].rt2=0;
7269         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
7270           imm[i]=(unsigned short)source[i];
7271         }else{
7272           imm[i]=(short)source[i];
7273         }
7274         break;
7275       case UJUMP:
7276         dops[i].rs1=0;
7277         dops[i].rs2=0;
7278         dops[i].rt1=0;
7279         dops[i].rt2=0;
7280         // The JAL instruction writes to r31.
7281         if (op&1) {
7282           dops[i].rt1=31;
7283         }
7284         dops[i].rs2=CCREG;
7285         break;
7286       case RJUMP:
7287         dops[i].rs1=(source[i]>>21)&0x1f;
7288         dops[i].rs2=0;
7289         dops[i].rt1=0;
7290         dops[i].rt2=0;
7291         // The JALR instruction writes to rd.
7292         if (op2&1) {
7293           dops[i].rt1=(source[i]>>11)&0x1f;
7294         }
7295         dops[i].rs2=CCREG;
7296         break;
7297       case CJUMP:
7298         dops[i].rs1=(source[i]>>21)&0x1f;
7299         dops[i].rs2=(source[i]>>16)&0x1f;
7300         dops[i].rt1=0;
7301         dops[i].rt2=0;
7302         if(op&2) { // BGTZ/BLEZ
7303           dops[i].rs2=0;
7304         }
7305         dops[i].likely=(op>>4)?1:0;
7306         break;
7307       case SJUMP:
7308         dops[i].rs1=(source[i]>>21)&0x1f;
7309         dops[i].rs2=CCREG;
7310         dops[i].rt1=0;
7311         dops[i].rt2=0;
7312         if(op2&0x10) { // BxxAL
7313           dops[i].rt1=31;
7314           // NOTE: If the branch is not taken, r31 is still overwritten
7315         }
7316         dops[i].likely=(op2&2)?1:0;
7317         break;
7318       case ALU:
7319         dops[i].rs1=(source[i]>>21)&0x1f; // source
7320         dops[i].rs2=(source[i]>>16)&0x1f; // subtract amount
7321         dops[i].rt1=(source[i]>>11)&0x1f; // destination
7322         dops[i].rt2=0;
7323         break;
7324       case MULTDIV:
7325         dops[i].rs1=(source[i]>>21)&0x1f; // source
7326         dops[i].rs2=(source[i]>>16)&0x1f; // divisor
7327         dops[i].rt1=HIREG;
7328         dops[i].rt2=LOREG;
7329         break;
7330       case MOV:
7331         dops[i].rs1=0;
7332         dops[i].rs2=0;
7333         dops[i].rt1=0;
7334         dops[i].rt2=0;
7335         if(op2==0x10) dops[i].rs1=HIREG; // MFHI
7336         if(op2==0x11) dops[i].rt1=HIREG; // MTHI
7337         if(op2==0x12) dops[i].rs1=LOREG; // MFLO
7338         if(op2==0x13) dops[i].rt1=LOREG; // MTLO
7339         if((op2&0x1d)==0x10) dops[i].rt1=(source[i]>>11)&0x1f; // MFxx
7340         if((op2&0x1d)==0x11) dops[i].rs1=(source[i]>>21)&0x1f; // MTxx
7341         break;
7342       case SHIFT:
7343         dops[i].rs1=(source[i]>>16)&0x1f; // target of shift
7344         dops[i].rs2=(source[i]>>21)&0x1f; // shift amount
7345         dops[i].rt1=(source[i]>>11)&0x1f; // destination
7346         dops[i].rt2=0;
7347         break;
7348       case SHIFTIMM:
7349         dops[i].rs1=(source[i]>>16)&0x1f;
7350         dops[i].rs2=0;
7351         dops[i].rt1=(source[i]>>11)&0x1f;
7352         dops[i].rt2=0;
7353         imm[i]=(source[i]>>6)&0x1f;
7354         // DSxx32 instructions
7355         if(op2>=0x3c) imm[i]|=0x20;
7356         break;
7357       case COP0:
7358         dops[i].rs1=0;
7359         dops[i].rs2=0;
7360         dops[i].rt1=0;
7361         dops[i].rt2=0;
7362         if(op2==0||op2==2) dops[i].rt1=(source[i]>>16)&0x1F; // MFC0/CFC0
7363         if(op2==4||op2==6) dops[i].rs1=(source[i]>>16)&0x1F; // MTC0/CTC0
7364         if(op2==4&&((source[i]>>11)&0x1f)==12) dops[i].rt2=CSREG; // Status
7365         if(op2==16) if((source[i]&0x3f)==0x18) dops[i].rs2=CCREG; // ERET
7366         break;
7367       case COP1:
7368         dops[i].rs1=0;
7369         dops[i].rs2=0;
7370         dops[i].rt1=0;
7371         dops[i].rt2=0;
7372         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
7373         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
7374         dops[i].rs2=CSREG;
7375         break;
7376       case COP2:
7377         dops[i].rs1=0;
7378         dops[i].rs2=0;
7379         dops[i].rt1=0;
7380         dops[i].rt2=0;
7381         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC2/CFC2
7382         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC2/CTC2
7383         dops[i].rs2=CSREG;
7384         int gr=(source[i]>>11)&0x1F;
7385         switch(op2)
7386         {
7387           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
7388           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
7389           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
7390           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
7391         }
7392         break;
7393       case C1LS:
7394         dops[i].rs1=(source[i]>>21)&0x1F;
7395         dops[i].rs2=CSREG;
7396         dops[i].rt1=0;
7397         dops[i].rt2=0;
7398         imm[i]=(short)source[i];
7399         break;
7400       case C2LS:
7401         dops[i].rs1=(source[i]>>21)&0x1F;
7402         dops[i].rs2=0;
7403         dops[i].rt1=0;
7404         dops[i].rt2=0;
7405         imm[i]=(short)source[i];
7406         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
7407         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
7408         break;
7409       case C2OP:
7410         dops[i].rs1=0;
7411         dops[i].rs2=0;
7412         dops[i].rt1=0;
7413         dops[i].rt2=0;
7414         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
7415         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
7416         gte_rt[i]|=1ll<<63; // every op changes flags
7417         if((source[i]&0x3f)==GTE_MVMVA) {
7418           int v = (source[i] >> 15) & 3;
7419           gte_rs[i]&=~0xe3fll;
7420           if(v==3) gte_rs[i]|=0xe00ll;
7421           else gte_rs[i]|=3ll<<(v*2);
7422         }
7423         break;
7424       case SYSCALL:
7425       case HLECALL:
7426       case INTCALL:
7427         dops[i].rs1=CCREG;
7428         dops[i].rs2=0;
7429         dops[i].rt1=0;
7430         dops[i].rt2=0;
7431         break;
7432       default:
7433         dops[i].rs1=0;
7434         dops[i].rs2=0;
7435         dops[i].rt1=0;
7436         dops[i].rt2=0;
7437     }
7438     /* Calculate branch target addresses */
7439     if(type==UJUMP)
7440       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
7441     else if(type==CJUMP&&dops[i].rs1==dops[i].rs2&&(op&1))
7442       ba[i]=start+i*4+8; // Ignore never taken branch
7443     else if(type==SJUMP&&dops[i].rs1==0&&!(op2&1))
7444       ba[i]=start+i*4+8; // Ignore never taken branch
7445     else if(type==CJUMP||type==SJUMP)
7446       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
7447     else ba[i]=-1;
7448
7449     /* simplify always (not)taken branches */
7450     if (type == CJUMP && dops[i].rs1 == dops[i].rs2) {
7451       dops[i].rs1 = dops[i].rs2 = 0;
7452       if (!(op & 1)) {
7453         dops[i].itype = type = UJUMP;
7454         dops[i].rs2 = CCREG;
7455       }
7456     }
7457     else if (type == SJUMP && dops[i].rs1 == 0 && (op2 & 1))
7458       dops[i].itype = type = UJUMP;
7459
7460     /* messy cases to just pass over to the interpreter */
7461     if (i > 0 && is_jump(i-1)) {
7462       int do_in_intrp=0;
7463       // branch in delay slot?
7464       if (is_jump(i)) {
7465         // don't handle first branch and call interpreter if it's hit
7466         SysPrintf("branch in delay slot @%08x (%08x)\n", addr + i*4, addr);
7467         do_in_intrp=1;
7468       }
7469       // basic load delay detection
7470       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&dops[i].rt1!=0) {
7471         int t=(ba[i-1]-start)/4;
7472         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) {
7473           // jump target wants DS result - potential load delay effect
7474           SysPrintf("load delay @%08x (%08x)\n", addr + i*4, addr);
7475           do_in_intrp=1;
7476           dops[t+1].bt=1; // expected return from interpreter
7477         }
7478         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&&
7479               !(i>=3&&is_jump(i-3))) {
7480           // v0 overwrite like this is a sign of trouble, bail out
7481           SysPrintf("v0 overwrite @%08x (%08x)\n", addr + i*4, addr);
7482           do_in_intrp=1;
7483         }
7484       }
7485       if(do_in_intrp) {
7486         dops[i-1].rs1=CCREG;
7487         dops[i-1].rs2=dops[i-1].rt1=dops[i-1].rt2=0;
7488         ba[i-1]=-1;
7489         dops[i-1].itype=INTCALL;
7490         done=2;
7491         i--; // don't compile the DS
7492       }
7493     }
7494
7495     /* Is this the end of the block? */
7496     if (i > 0 && is_ujump(i-1)) {
7497       if(dops[i-1].rt1==0) { // Continue past subroutine call (JAL)
7498         done=2;
7499       }
7500       else {
7501         if(stop_after_jal) done=1;
7502         // Stop on BREAK
7503         if((source[i+1]&0xfc00003f)==0x0d) done=1;
7504       }
7505       // Don't recompile stuff that's already compiled
7506       if(check_addr(start+i*4+4)) done=1;
7507       // Don't get too close to the limit
7508       if(i>MAXBLOCK/2) done=1;
7509     }
7510     if(dops[i].itype==SYSCALL&&stop_after_jal) done=1;
7511     if(dops[i].itype==HLECALL||dops[i].itype==INTCALL) done=2;
7512     if(done==2) {
7513       // Does the block continue due to a branch?
7514       for(j=i-1;j>=0;j--)
7515       {
7516         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
7517         if(ba[j]==start+i*4+4) done=j=0;
7518         if(ba[j]==start+i*4+8) done=j=0;
7519       }
7520     }
7521     //assert(i<MAXBLOCK-1);
7522     if(start+i*4==pagelimit-4) done=1;
7523     assert(start+i*4<pagelimit);
7524     if (i==MAXBLOCK-1) done=1;
7525     // Stop if we're compiling junk
7526     if(dops[i].itype==NI&&dops[i].opcode==0x11) {
7527       done=stop_after_jal=1;
7528       SysPrintf("Disabled speculative precompilation\n");
7529     }
7530   }
7531   slen=i;
7532   if(dops[i-1].itype==UJUMP||dops[i-1].itype==CJUMP||dops[i-1].itype==SJUMP||dops[i-1].itype==RJUMP) {
7533     if(start+i*4==pagelimit) {
7534       dops[i-1].itype=SPAN;
7535     }
7536   }
7537   assert(slen>0);
7538
7539   /* Pass 2 - Register dependencies and branch targets */
7540
7541   unneeded_registers(0,slen-1,0);
7542
7543   /* Pass 3 - Register allocation */
7544
7545   struct regstat current; // Current register allocations/status
7546   current.dirty=0;
7547   current.u=unneeded_reg[0];
7548   clear_all_regs(current.regmap);
7549   alloc_reg(&current,0,CCREG);
7550   dirty_reg(&current,CCREG);
7551   current.isconst=0;
7552   current.wasconst=0;
7553   current.waswritten=0;
7554   int ds=0;
7555   int cc=0;
7556   int hr=-1;
7557
7558   if((u_int)addr&1) {
7559     // First instruction is delay slot
7560     cc=-1;
7561     dops[1].bt=1;
7562     ds=1;
7563     unneeded_reg[0]=1;
7564     current.regmap[HOST_BTREG]=BTREG;
7565   }
7566
7567   for(i=0;i<slen;i++)
7568   {
7569     if(dops[i].bt)
7570     {
7571       int hr;
7572       for(hr=0;hr<HOST_REGS;hr++)
7573       {
7574         // Is this really necessary?
7575         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7576       }
7577       current.isconst=0;
7578       current.waswritten=0;
7579     }
7580
7581     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7582     regs[i].wasconst=current.isconst;
7583     regs[i].wasdirty=current.dirty;
7584     regs[i].loadedconst=0;
7585     if(dops[i].itype!=UJUMP&&dops[i].itype!=CJUMP&&dops[i].itype!=SJUMP&&dops[i].itype!=RJUMP) {
7586       if(i+1<slen) {
7587         current.u=unneeded_reg[i+1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7588         current.u|=1;
7589       } else {
7590         current.u=1;
7591       }
7592     } else {
7593       if(i+1<slen) {
7594         current.u=branch_unneeded_reg[i]&~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7595         current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7596         current.u|=1;
7597       } else { SysPrintf("oops, branch at end of block with no delay slot\n");abort(); }
7598     }
7599     dops[i].is_ds=ds;
7600     if(ds) {
7601       ds=0; // Skip delay slot, already allocated as part of branch
7602       // ...but we need to alloc it in case something jumps here
7603       if(i+1<slen) {
7604         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7605       }else{
7606         current.u=branch_unneeded_reg[i-1];
7607       }
7608       current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7609       current.u|=1;
7610       struct regstat temp;
7611       memcpy(&temp,&current,sizeof(current));
7612       temp.wasdirty=temp.dirty;
7613       // TODO: Take into account unconditional branches, as below
7614       delayslot_alloc(&temp,i);
7615       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7616       regs[i].wasdirty=temp.wasdirty;
7617       regs[i].dirty=temp.dirty;
7618       regs[i].isconst=0;
7619       regs[i].wasconst=0;
7620       current.isconst=0;
7621       // Create entry (branch target) regmap
7622       for(hr=0;hr<HOST_REGS;hr++)
7623       {
7624         int r=temp.regmap[hr];
7625         if(r>=0) {
7626           if(r!=regmap_pre[i][hr]) {
7627             regs[i].regmap_entry[hr]=-1;
7628           }
7629           else
7630           {
7631               assert(r < 64);
7632               if((current.u>>r)&1) {
7633                 regs[i].regmap_entry[hr]=-1;
7634                 regs[i].regmap[hr]=-1;
7635                 //Don't clear regs in the delay slot as the branch might need them
7636                 //current.regmap[hr]=-1;
7637               }else
7638                 regs[i].regmap_entry[hr]=r;
7639           }
7640         } else {
7641           // First instruction expects CCREG to be allocated
7642           if(i==0&&hr==HOST_CCREG)
7643             regs[i].regmap_entry[hr]=CCREG;
7644           else
7645             regs[i].regmap_entry[hr]=-1;
7646         }
7647       }
7648     }
7649     else { // Not delay slot
7650       switch(dops[i].itype) {
7651         case UJUMP:
7652           //current.isconst=0; // DEBUG
7653           //current.wasconst=0; // DEBUG
7654           //regs[i].wasconst=0; // DEBUG
7655           clear_const(&current,dops[i].rt1);
7656           alloc_cc(&current,i);
7657           dirty_reg(&current,CCREG);
7658           if (dops[i].rt1==31) {
7659             alloc_reg(&current,i,31);
7660             dirty_reg(&current,31);
7661             //assert(dops[i+1].rs1!=31&&dops[i+1].rs2!=31);
7662             //assert(dops[i+1].rt1!=dops[i].rt1);
7663             #ifdef REG_PREFETCH
7664             alloc_reg(&current,i,PTEMP);
7665             #endif
7666           }
7667           dops[i].ooo=1;
7668           delayslot_alloc(&current,i+1);
7669           //current.isconst=0; // DEBUG
7670           ds=1;
7671           //printf("i=%d, isconst=%x\n",i,current.isconst);
7672           break;
7673         case RJUMP:
7674           //current.isconst=0;
7675           //current.wasconst=0;
7676           //regs[i].wasconst=0;
7677           clear_const(&current,dops[i].rs1);
7678           clear_const(&current,dops[i].rt1);
7679           alloc_cc(&current,i);
7680           dirty_reg(&current,CCREG);
7681           if (!ds_writes_rjump_rs(i)) {
7682             alloc_reg(&current,i,dops[i].rs1);
7683             if (dops[i].rt1!=0) {
7684               alloc_reg(&current,i,dops[i].rt1);
7685               dirty_reg(&current,dops[i].rt1);
7686               assert(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt1);
7687               assert(dops[i+1].rt1!=dops[i].rt1);
7688               #ifdef REG_PREFETCH
7689               alloc_reg(&current,i,PTEMP);
7690               #endif
7691             }
7692             #ifdef USE_MINI_HT
7693             if(dops[i].rs1==31) { // JALR
7694               alloc_reg(&current,i,RHASH);
7695               alloc_reg(&current,i,RHTBL);
7696             }
7697             #endif
7698             delayslot_alloc(&current,i+1);
7699           } else {
7700             // The delay slot overwrites our source register,
7701             // allocate a temporary register to hold the old value.
7702             current.isconst=0;
7703             current.wasconst=0;
7704             regs[i].wasconst=0;
7705             delayslot_alloc(&current,i+1);
7706             current.isconst=0;
7707             alloc_reg(&current,i,RTEMP);
7708           }
7709           //current.isconst=0; // DEBUG
7710           dops[i].ooo=1;
7711           ds=1;
7712           break;
7713         case CJUMP:
7714           //current.isconst=0;
7715           //current.wasconst=0;
7716           //regs[i].wasconst=0;
7717           clear_const(&current,dops[i].rs1);
7718           clear_const(&current,dops[i].rs2);
7719           if((dops[i].opcode&0x3E)==4) // BEQ/BNE
7720           {
7721             alloc_cc(&current,i);
7722             dirty_reg(&current,CCREG);
7723             if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7724             if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7725             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2))||
7726                (dops[i].rs2&&(dops[i].rs2==dops[i+1].rt1||dops[i].rs2==dops[i+1].rt2))) {
7727               // The delay slot overwrites one of our conditions.
7728               // Allocate the branch condition registers instead.
7729               current.isconst=0;
7730               current.wasconst=0;
7731               regs[i].wasconst=0;
7732               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7733               if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7734             }
7735             else
7736             {
7737               dops[i].ooo=1;
7738               delayslot_alloc(&current,i+1);
7739             }
7740           }
7741           else
7742           if((dops[i].opcode&0x3E)==6) // BLEZ/BGTZ
7743           {
7744             alloc_cc(&current,i);
7745             dirty_reg(&current,CCREG);
7746             alloc_reg(&current,i,dops[i].rs1);
7747             if(dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) {
7748               // The delay slot overwrites one of our conditions.
7749               // Allocate the branch condition registers instead.
7750               current.isconst=0;
7751               current.wasconst=0;
7752               regs[i].wasconst=0;
7753               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7754             }
7755             else
7756             {
7757               dops[i].ooo=1;
7758               delayslot_alloc(&current,i+1);
7759             }
7760           }
7761           else
7762           // Don't alloc the delay slot yet because we might not execute it
7763           if((dops[i].opcode&0x3E)==0x14) // BEQL/BNEL
7764           {
7765             current.isconst=0;
7766             current.wasconst=0;
7767             regs[i].wasconst=0;
7768             alloc_cc(&current,i);
7769             dirty_reg(&current,CCREG);
7770             alloc_reg(&current,i,dops[i].rs1);
7771             alloc_reg(&current,i,dops[i].rs2);
7772           }
7773           else
7774           if((dops[i].opcode&0x3E)==0x16) // BLEZL/BGTZL
7775           {
7776             current.isconst=0;
7777             current.wasconst=0;
7778             regs[i].wasconst=0;
7779             alloc_cc(&current,i);
7780             dirty_reg(&current,CCREG);
7781             alloc_reg(&current,i,dops[i].rs1);
7782           }
7783           ds=1;
7784           //current.isconst=0;
7785           break;
7786         case SJUMP:
7787           //current.isconst=0;
7788           //current.wasconst=0;
7789           //regs[i].wasconst=0;
7790           clear_const(&current,dops[i].rs1);
7791           clear_const(&current,dops[i].rt1);
7792           //if((dops[i].opcode2&0x1E)==0x0) // BLTZ/BGEZ
7793           if((dops[i].opcode2&0x0E)==0x0) // BLTZ/BGEZ
7794           {
7795             alloc_cc(&current,i);
7796             dirty_reg(&current,CCREG);
7797             alloc_reg(&current,i,dops[i].rs1);
7798             if (dops[i].rt1==31) { // BLTZAL/BGEZAL
7799               alloc_reg(&current,i,31);
7800               dirty_reg(&current,31);
7801               //#ifdef REG_PREFETCH
7802               //alloc_reg(&current,i,PTEMP);
7803               //#endif
7804             }
7805             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.
7806                ||(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
7807               // Allocate the branch condition registers instead.
7808               current.isconst=0;
7809               current.wasconst=0;
7810               regs[i].wasconst=0;
7811               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7812             }
7813             else
7814             {
7815               dops[i].ooo=1;
7816               delayslot_alloc(&current,i+1);
7817             }
7818           }
7819           else
7820           // Don't alloc the delay slot yet because we might not execute it
7821           if((dops[i].opcode2&0x1E)==0x2) // BLTZL/BGEZL
7822           {
7823             current.isconst=0;
7824             current.wasconst=0;
7825             regs[i].wasconst=0;
7826             alloc_cc(&current,i);
7827             dirty_reg(&current,CCREG);
7828             alloc_reg(&current,i,dops[i].rs1);
7829           }
7830           ds=1;
7831           //current.isconst=0;
7832           break;
7833         case IMM16:
7834           imm16_alloc(&current,i);
7835           break;
7836         case LOAD:
7837         case LOADLR:
7838           load_alloc(&current,i);
7839           break;
7840         case STORE:
7841         case STORELR:
7842           store_alloc(&current,i);
7843           break;
7844         case ALU:
7845           alu_alloc(&current,i);
7846           break;
7847         case SHIFT:
7848           shift_alloc(&current,i);
7849           break;
7850         case MULTDIV:
7851           multdiv_alloc(&current,i);
7852           break;
7853         case SHIFTIMM:
7854           shiftimm_alloc(&current,i);
7855           break;
7856         case MOV:
7857           mov_alloc(&current,i);
7858           break;
7859         case COP0:
7860           cop0_alloc(&current,i);
7861           break;
7862         case COP1:
7863           break;
7864         case COP2:
7865           cop2_alloc(&current,i);
7866           break;
7867         case C1LS:
7868           c1ls_alloc(&current,i);
7869           break;
7870         case C2LS:
7871           c2ls_alloc(&current,i);
7872           break;
7873         case C2OP:
7874           c2op_alloc(&current,i);
7875           break;
7876         case SYSCALL:
7877         case HLECALL:
7878         case INTCALL:
7879           syscall_alloc(&current,i);
7880           break;
7881         case SPAN:
7882           pagespan_alloc(&current,i);
7883           break;
7884       }
7885
7886       // Create entry (branch target) regmap
7887       for(hr=0;hr<HOST_REGS;hr++)
7888       {
7889         int r,or;
7890         r=current.regmap[hr];
7891         if(r>=0) {
7892           if(r!=regmap_pre[i][hr]) {
7893             // TODO: delay slot (?)
7894             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
7895             if(or<0||(r&63)>=TEMPREG){
7896               regs[i].regmap_entry[hr]=-1;
7897             }
7898             else
7899             {
7900               // Just move it to a different register
7901               regs[i].regmap_entry[hr]=r;
7902               // If it was dirty before, it's still dirty
7903               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r&63);
7904             }
7905           }
7906           else
7907           {
7908             // Unneeded
7909             if(r==0){
7910               regs[i].regmap_entry[hr]=0;
7911             }
7912             else
7913             {
7914               assert(r<64);
7915               if((current.u>>r)&1) {
7916                 regs[i].regmap_entry[hr]=-1;
7917                 //regs[i].regmap[hr]=-1;
7918                 current.regmap[hr]=-1;
7919               }else
7920                 regs[i].regmap_entry[hr]=r;
7921             }
7922           }
7923         } else {
7924           // Branches expect CCREG to be allocated at the target
7925           if(regmap_pre[i][hr]==CCREG)
7926             regs[i].regmap_entry[hr]=CCREG;
7927           else
7928             regs[i].regmap_entry[hr]=-1;
7929         }
7930       }
7931       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
7932     }
7933
7934     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)
7935       current.waswritten|=1<<dops[i-1].rs1;
7936     current.waswritten&=~(1<<dops[i].rt1);
7937     current.waswritten&=~(1<<dops[i].rt2);
7938     if((dops[i].itype==STORE||dops[i].itype==STORELR||(dops[i].itype==C2LS&&dops[i].opcode==0x3a))&&(u_int)imm[i]>=0x800)
7939       current.waswritten&=~(1<<dops[i].rs1);
7940
7941     /* Branch post-alloc */
7942     if(i>0)
7943     {
7944       current.wasdirty=current.dirty;
7945       switch(dops[i-1].itype) {
7946         case UJUMP:
7947           memcpy(&branch_regs[i-1],&current,sizeof(current));
7948           branch_regs[i-1].isconst=0;
7949           branch_regs[i-1].wasconst=0;
7950           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7951           alloc_cc(&branch_regs[i-1],i-1);
7952           dirty_reg(&branch_regs[i-1],CCREG);
7953           if(dops[i-1].rt1==31) { // JAL
7954             alloc_reg(&branch_regs[i-1],i-1,31);
7955             dirty_reg(&branch_regs[i-1],31);
7956           }
7957           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7958           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7959           break;
7960         case RJUMP:
7961           memcpy(&branch_regs[i-1],&current,sizeof(current));
7962           branch_regs[i-1].isconst=0;
7963           branch_regs[i-1].wasconst=0;
7964           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7965           alloc_cc(&branch_regs[i-1],i-1);
7966           dirty_reg(&branch_regs[i-1],CCREG);
7967           alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rs1);
7968           if(dops[i-1].rt1!=0) { // JALR
7969             alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rt1);
7970             dirty_reg(&branch_regs[i-1],dops[i-1].rt1);
7971           }
7972           #ifdef USE_MINI_HT
7973           if(dops[i-1].rs1==31) { // JALR
7974             alloc_reg(&branch_regs[i-1],i-1,RHASH);
7975             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
7976           }
7977           #endif
7978           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7979           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7980           break;
7981         case CJUMP:
7982           if((dops[i-1].opcode&0x3E)==4) // BEQ/BNE
7983           {
7984             alloc_cc(&current,i-1);
7985             dirty_reg(&current,CCREG);
7986             if((dops[i-1].rs1&&(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2))||
7987                (dops[i-1].rs2&&(dops[i-1].rs2==dops[i].rt1||dops[i-1].rs2==dops[i].rt2))) {
7988               // The delay slot overwrote one of our conditions
7989               // Delay slot goes after the test (in order)
7990               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7991               current.u|=1;
7992               delayslot_alloc(&current,i);
7993               current.isconst=0;
7994             }
7995             else
7996             {
7997               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7998               // Alloc the branch condition registers
7999               if(dops[i-1].rs1) alloc_reg(&current,i-1,dops[i-1].rs1);
8000               if(dops[i-1].rs2) alloc_reg(&current,i-1,dops[i-1].rs2);
8001             }
8002             memcpy(&branch_regs[i-1],&current,sizeof(current));
8003             branch_regs[i-1].isconst=0;
8004             branch_regs[i-1].wasconst=0;
8005             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8006             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8007           }
8008           else
8009           if((dops[i-1].opcode&0x3E)==6) // BLEZ/BGTZ
8010           {
8011             alloc_cc(&current,i-1);
8012             dirty_reg(&current,CCREG);
8013             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
8014               // The delay slot overwrote the branch condition
8015               // Delay slot goes after the test (in order)
8016               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8017               current.u|=1;
8018               delayslot_alloc(&current,i);
8019               current.isconst=0;
8020             }
8021             else
8022             {
8023               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
8024               // Alloc the branch condition register
8025               alloc_reg(&current,i-1,dops[i-1].rs1);
8026             }
8027             memcpy(&branch_regs[i-1],&current,sizeof(current));
8028             branch_regs[i-1].isconst=0;
8029             branch_regs[i-1].wasconst=0;
8030             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8031             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8032           }
8033           else
8034           // Alloc the delay slot in case the branch is taken
8035           if((dops[i-1].opcode&0x3E)==0x14) // BEQL/BNEL
8036           {
8037             memcpy(&branch_regs[i-1],&current,sizeof(current));
8038             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;
8039             alloc_cc(&branch_regs[i-1],i);
8040             dirty_reg(&branch_regs[i-1],CCREG);
8041             delayslot_alloc(&branch_regs[i-1],i);
8042             branch_regs[i-1].isconst=0;
8043             alloc_reg(&current,i,CCREG); // Not taken path
8044             dirty_reg(&current,CCREG);
8045             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8046           }
8047           else
8048           if((dops[i-1].opcode&0x3E)==0x16) // BLEZL/BGTZL
8049           {
8050             memcpy(&branch_regs[i-1],&current,sizeof(current));
8051             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;
8052             alloc_cc(&branch_regs[i-1],i);
8053             dirty_reg(&branch_regs[i-1],CCREG);
8054             delayslot_alloc(&branch_regs[i-1],i);
8055             branch_regs[i-1].isconst=0;
8056             alloc_reg(&current,i,CCREG); // Not taken path
8057             dirty_reg(&current,CCREG);
8058             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8059           }
8060           break;
8061         case SJUMP:
8062           //if((dops[i-1].opcode2&0x1E)==0) // BLTZ/BGEZ
8063           if((dops[i-1].opcode2&0x0E)==0) // BLTZ/BGEZ
8064           {
8065             alloc_cc(&current,i-1);
8066             dirty_reg(&current,CCREG);
8067             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
8068               // The delay slot overwrote the branch condition
8069               // Delay slot goes after the test (in order)
8070               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8071               current.u|=1;
8072               delayslot_alloc(&current,i);
8073               current.isconst=0;
8074             }
8075             else
8076             {
8077               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
8078               // Alloc the branch condition register
8079               alloc_reg(&current,i-1,dops[i-1].rs1);
8080             }
8081             memcpy(&branch_regs[i-1],&current,sizeof(current));
8082             branch_regs[i-1].isconst=0;
8083             branch_regs[i-1].wasconst=0;
8084             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8085             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8086           }
8087           else
8088           // Alloc the delay slot in case the branch is taken
8089           if((dops[i-1].opcode2&0x1E)==2) // BLTZL/BGEZL
8090           {
8091             memcpy(&branch_regs[i-1],&current,sizeof(current));
8092             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;
8093             alloc_cc(&branch_regs[i-1],i);
8094             dirty_reg(&branch_regs[i-1],CCREG);
8095             delayslot_alloc(&branch_regs[i-1],i);
8096             branch_regs[i-1].isconst=0;
8097             alloc_reg(&current,i,CCREG); // Not taken path
8098             dirty_reg(&current,CCREG);
8099             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8100           }
8101           // FIXME: BLTZAL/BGEZAL
8102           if(dops[i-1].opcode2&0x10) { // BxxZAL
8103             alloc_reg(&branch_regs[i-1],i-1,31);
8104             dirty_reg(&branch_regs[i-1],31);
8105           }
8106           break;
8107       }
8108
8109       if (is_ujump(i-1))
8110       {
8111         if(dops[i-1].rt1==31) // JAL/JALR
8112         {
8113           // Subroutine call will return here, don't alloc any registers
8114           current.dirty=0;
8115           clear_all_regs(current.regmap);
8116           alloc_reg(&current,i,CCREG);
8117           dirty_reg(&current,CCREG);
8118         }
8119         else if(i+1<slen)
8120         {
8121           // Internal branch will jump here, match registers to caller
8122           current.dirty=0;
8123           clear_all_regs(current.regmap);
8124           alloc_reg(&current,i,CCREG);
8125           dirty_reg(&current,CCREG);
8126           for(j=i-1;j>=0;j--)
8127           {
8128             if(ba[j]==start+i*4+4) {
8129               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
8130               current.dirty=branch_regs[j].dirty;
8131               break;
8132             }
8133           }
8134           while(j>=0) {
8135             if(ba[j]==start+i*4+4) {
8136               for(hr=0;hr<HOST_REGS;hr++) {
8137                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
8138                   current.regmap[hr]=-1;
8139                 }
8140                 current.dirty&=branch_regs[j].dirty;
8141               }
8142             }
8143             j--;
8144           }
8145         }
8146       }
8147     }
8148
8149     // Count cycles in between branches
8150     ccadj[i]=cc;
8151     if(i>0&&(dops[i-1].itype==RJUMP||dops[i-1].itype==UJUMP||dops[i-1].itype==CJUMP||dops[i-1].itype==SJUMP||dops[i].itype==SYSCALL||dops[i].itype==HLECALL))
8152     {
8153       cc=0;
8154     }
8155 #if !defined(DRC_DBG)
8156     else if(dops[i].itype==C2OP&&gte_cycletab[source[i]&0x3f]>2)
8157     {
8158       // this should really be removed since the real stalls have been implemented,
8159       // but doing so causes sizeable perf regression against the older version
8160       u_int gtec = gte_cycletab[source[i] & 0x3f];
8161       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? gtec/2 : 2;
8162     }
8163     else if(i>1&&dops[i].itype==STORE&&dops[i-1].itype==STORE&&dops[i-2].itype==STORE&&!dops[i].bt)
8164     {
8165       cc+=4;
8166     }
8167     else if(dops[i].itype==C2LS)
8168     {
8169       // same as with C2OP
8170       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? 4 : 2;
8171     }
8172 #endif
8173     else
8174     {
8175       cc++;
8176     }
8177
8178     if(!dops[i].is_ds) {
8179       regs[i].dirty=current.dirty;
8180       regs[i].isconst=current.isconst;
8181       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
8182     }
8183     for(hr=0;hr<HOST_REGS;hr++) {
8184       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
8185         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
8186           regs[i].wasconst&=~(1<<hr);
8187         }
8188       }
8189     }
8190     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
8191     regs[i].waswritten=current.waswritten;
8192   }
8193
8194   /* Pass 4 - Cull unused host registers */
8195
8196   uint64_t nr=0;
8197
8198   for (i=slen-1;i>=0;i--)
8199   {
8200     int hr;
8201     if(dops[i].itype==RJUMP||dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8202     {
8203       if(ba[i]<start || ba[i]>=(start+slen*4))
8204       {
8205         // Branch out of this block, don't need anything
8206         nr=0;
8207       }
8208       else
8209       {
8210         // Internal branch
8211         // Need whatever matches the target
8212         nr=0;
8213         int t=(ba[i]-start)>>2;
8214         for(hr=0;hr<HOST_REGS;hr++)
8215         {
8216           if(regs[i].regmap_entry[hr]>=0) {
8217             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
8218           }
8219         }
8220       }
8221       // Conditional branch may need registers for following instructions
8222       if (!is_ujump(i))
8223       {
8224         if(i<slen-2) {
8225           nr|=needed_reg[i+2];
8226           for(hr=0;hr<HOST_REGS;hr++)
8227           {
8228             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
8229             //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]);
8230           }
8231         }
8232       }
8233       // Don't need stuff which is overwritten
8234       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8235       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8236       // Merge in delay slot
8237       for(hr=0;hr<HOST_REGS;hr++)
8238       {
8239         if(!dops[i].likely) {
8240           // These are overwritten unless the branch is "likely"
8241           // and the delay slot is nullified if not taken
8242           if(dops[i+1].rt1&&dops[i+1].rt1==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8243           if(dops[i+1].rt2&&dops[i+1].rt2==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8244         }
8245         if(dops[i+1].rs1==regmap_pre[i][hr]) nr|=1<<hr;
8246         if(dops[i+1].rs2==regmap_pre[i][hr]) nr|=1<<hr;
8247         if(dops[i+1].rs1==regs[i].regmap_entry[hr]) nr|=1<<hr;
8248         if(dops[i+1].rs2==regs[i].regmap_entry[hr]) nr|=1<<hr;
8249         if(dops[i+1].itype==STORE || dops[i+1].itype==STORELR || (dops[i+1].opcode&0x3b)==0x39 || (dops[i+1].opcode&0x3b)==0x3a) {
8250           if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8251           if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8252         }
8253       }
8254     }
8255     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
8256     {
8257       // SYSCALL instruction (software interrupt)
8258       nr=0;
8259     }
8260     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
8261     {
8262       // ERET instruction (return from interrupt)
8263       nr=0;
8264     }
8265     else // Non-branch
8266     {
8267       if(i<slen-1) {
8268         for(hr=0;hr<HOST_REGS;hr++) {
8269           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
8270           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
8271           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8272           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8273         }
8274       }
8275     }
8276     for(hr=0;hr<HOST_REGS;hr++)
8277     {
8278       // Overwritten registers are not needed
8279       if(dops[i].rt1&&dops[i].rt1==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8280       if(dops[i].rt2&&dops[i].rt2==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8281       if(FTEMP==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8282       // Source registers are needed
8283       if(dops[i].rs1==regmap_pre[i][hr]) nr|=1<<hr;
8284       if(dops[i].rs2==regmap_pre[i][hr]) nr|=1<<hr;
8285       if(dops[i].rs1==regs[i].regmap_entry[hr]) nr|=1<<hr;
8286       if(dops[i].rs2==regs[i].regmap_entry[hr]) nr|=1<<hr;
8287       if(dops[i].itype==STORE || dops[i].itype==STORELR || (dops[i].opcode&0x3b)==0x39 || (dops[i].opcode&0x3b)==0x3a) {
8288         if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8289         if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8290       }
8291       // Don't store a register immediately after writing it,
8292       // may prevent dual-issue.
8293       // But do so if this is a branch target, otherwise we
8294       // might have to load the register before the branch.
8295       if(i>0&&!dops[i].bt&&((regs[i].wasdirty>>hr)&1)) {
8296         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
8297           if(dops[i-1].rt1==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8298           if(dops[i-1].rt2==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8299         }
8300         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
8301           if(dops[i-1].rt1==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8302           if(dops[i-1].rt2==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8303         }
8304       }
8305     }
8306     // Cycle count is needed at branches.  Assume it is needed at the target too.
8307     if(i==0||dops[i].bt||dops[i].itype==CJUMP||dops[i].itype==SPAN) {
8308       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8309       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8310     }
8311     // Save it
8312     needed_reg[i]=nr;
8313
8314     // Deallocate unneeded registers
8315     for(hr=0;hr<HOST_REGS;hr++)
8316     {
8317       if(!((nr>>hr)&1)) {
8318         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
8319         if((regs[i].regmap[hr]&63)!=dops[i].rs1 && (regs[i].regmap[hr]&63)!=dops[i].rs2 &&
8320            (regs[i].regmap[hr]&63)!=dops[i].rt1 && (regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8321            (regs[i].regmap[hr]&63)!=PTEMP && (regs[i].regmap[hr]&63)!=CCREG)
8322         {
8323           if (!is_ujump(i))
8324           {
8325             if(dops[i].likely) {
8326               regs[i].regmap[hr]=-1;
8327               regs[i].isconst&=~(1<<hr);
8328               if(i<slen-2) {
8329                 regmap_pre[i+2][hr]=-1;
8330                 regs[i+2].wasconst&=~(1<<hr);
8331               }
8332             }
8333           }
8334         }
8335         if(dops[i].itype==RJUMP||dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8336         {
8337           int map=0,temp=0;
8338           if(dops[i+1].itype==STORE || dops[i+1].itype==STORELR ||
8339              (dops[i+1].opcode&0x3b)==0x39 || (dops[i+1].opcode&0x3b)==0x3a) { // SWC1/SDC1 || SWC2/SDC2
8340             map=INVCP;
8341           }
8342           if(dops[i+1].itype==LOADLR || dops[i+1].itype==STORELR ||
8343              dops[i+1].itype==C1LS || dops[i+1].itype==C2LS)
8344             temp=FTEMP;
8345           if((regs[i].regmap[hr]&63)!=dops[i].rs1 && (regs[i].regmap[hr]&63)!=dops[i].rs2 &&
8346              (regs[i].regmap[hr]&63)!=dops[i].rt1 && (regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8347              (regs[i].regmap[hr]&63)!=dops[i+1].rt1 && (regs[i].regmap[hr]&63)!=dops[i+1].rt2 &&
8348              regs[i].regmap[hr]!=dops[i+1].rs1 && regs[i].regmap[hr]!=dops[i+1].rs2 &&
8349              (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=PTEMP &&
8350              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
8351              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
8352              regs[i].regmap[hr]!=map )
8353           {
8354             regs[i].regmap[hr]=-1;
8355             regs[i].isconst&=~(1<<hr);
8356             if((branch_regs[i].regmap[hr]&63)!=dops[i].rs1 && (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 &&
8357                (branch_regs[i].regmap[hr]&63)!=dops[i].rt1 && (branch_regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8358                (branch_regs[i].regmap[hr]&63)!=dops[i+1].rt1 && (branch_regs[i].regmap[hr]&63)!=dops[i+1].rt2 &&
8359                branch_regs[i].regmap[hr]!=dops[i+1].rs1 && branch_regs[i].regmap[hr]!=dops[i+1].rs2 &&
8360                (branch_regs[i].regmap[hr]&63)!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
8361                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
8362                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
8363                branch_regs[i].regmap[hr]!=map)
8364             {
8365               branch_regs[i].regmap[hr]=-1;
8366               branch_regs[i].regmap_entry[hr]=-1;
8367               if (!is_ujump(i))
8368               {
8369                 if(!dops[i].likely&&i<slen-2) {
8370                   regmap_pre[i+2][hr]=-1;
8371                   regs[i+2].wasconst&=~(1<<hr);
8372                 }
8373               }
8374             }
8375           }
8376         }
8377         else
8378         {
8379           // Non-branch
8380           if(i>0)
8381           {
8382             int map=-1,temp=-1;
8383             if(dops[i].itype==STORE || dops[i].itype==STORELR ||
8384                       (dops[i].opcode&0x3b)==0x39 || (dops[i].opcode&0x3b)==0x3a) { // SWC1/SDC1 || SWC2/SDC2
8385               map=INVCP;
8386             }
8387             if(dops[i].itype==LOADLR || dops[i].itype==STORELR ||
8388                dops[i].itype==C1LS || dops[i].itype==C2LS)
8389               temp=FTEMP;
8390             if((regs[i].regmap[hr]&63)!=dops[i].rt1 && (regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8391                regs[i].regmap[hr]!=dops[i].rs1 && regs[i].regmap[hr]!=dops[i].rs2 &&
8392                (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=map &&
8393                (dops[i].itype!=SPAN||regs[i].regmap[hr]!=CCREG))
8394             {
8395               if(i<slen-1&&!dops[i].is_ds) {
8396                 assert(regs[i].regmap[hr]<64);
8397                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8398                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8399                 {
8400                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8401                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8402                 }
8403                 regmap_pre[i+1][hr]=-1;
8404                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8405                 regs[i+1].wasconst&=~(1<<hr);
8406               }
8407               regs[i].regmap[hr]=-1;
8408               regs[i].isconst&=~(1<<hr);
8409             }
8410           }
8411         }
8412       } // if needed
8413     } // for hr
8414   }
8415
8416   /* Pass 5 - Pre-allocate registers */
8417
8418   // If a register is allocated during a loop, try to allocate it for the
8419   // entire loop, if possible.  This avoids loading/storing registers
8420   // inside of the loop.
8421
8422   signed char f_regmap[HOST_REGS];
8423   clear_all_regs(f_regmap);
8424   for(i=0;i<slen-1;i++)
8425   {
8426     if(dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8427     {
8428       if(ba[i]>=start && ba[i]<(start+i*4))
8429       if(dops[i+1].itype==NOP||dops[i+1].itype==MOV||dops[i+1].itype==ALU
8430       ||dops[i+1].itype==SHIFTIMM||dops[i+1].itype==IMM16||dops[i+1].itype==LOAD
8431       ||dops[i+1].itype==STORE||dops[i+1].itype==STORELR||dops[i+1].itype==C1LS
8432       ||dops[i+1].itype==SHIFT||dops[i+1].itype==COP1
8433       ||dops[i+1].itype==COP2||dops[i+1].itype==C2LS||dops[i+1].itype==C2OP)
8434       {
8435         int t=(ba[i]-start)>>2;
8436         if(t>0&&(dops[t-1].itype!=UJUMP&&dops[t-1].itype!=RJUMP&&dops[t-1].itype!=CJUMP&&dops[t-1].itype!=SJUMP)) // loop_preload can't handle jumps into delay slots
8437         if(t<2||(dops[t-2].itype!=UJUMP&&dops[t-2].itype!=RJUMP)||dops[t-2].rt1!=31) // call/ret assumes no registers allocated
8438         for(hr=0;hr<HOST_REGS;hr++)
8439         {
8440           if(regs[i].regmap[hr]>=0) {
8441             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8442               // dealloc old register
8443               int n;
8444               for(n=0;n<HOST_REGS;n++)
8445               {
8446                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8447               }
8448               // and alloc new one
8449               f_regmap[hr]=regs[i].regmap[hr];
8450             }
8451           }
8452           if(branch_regs[i].regmap[hr]>=0) {
8453             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8454               // dealloc old register
8455               int n;
8456               for(n=0;n<HOST_REGS;n++)
8457               {
8458                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8459               }
8460               // and alloc new one
8461               f_regmap[hr]=branch_regs[i].regmap[hr];
8462             }
8463           }
8464           if(dops[i].ooo) {
8465             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8466               f_regmap[hr]=branch_regs[i].regmap[hr];
8467           }else{
8468             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8469               f_regmap[hr]=branch_regs[i].regmap[hr];
8470           }
8471           // Avoid dirty->clean transition
8472           #ifdef DESTRUCTIVE_WRITEBACK
8473           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;
8474           #endif
8475           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8476           // case above, however it's always a good idea.  We can't hoist the
8477           // load if the register was already allocated, so there's no point
8478           // wasting time analyzing most of these cases.  It only "succeeds"
8479           // when the mapping was different and the load can be replaced with
8480           // a mov, which is of negligible benefit.  So such cases are
8481           // skipped below.
8482           if(f_regmap[hr]>0) {
8483             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8484               int r=f_regmap[hr];
8485               for(j=t;j<=i;j++)
8486               {
8487                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8488                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8489                 assert(r < 64);
8490                 if(regs[j].regmap[hr]==f_regmap[hr]&&(f_regmap[hr]&63)<TEMPREG) {
8491                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8492                   int k;
8493                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8494                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8495                     if(r>63) {
8496                       if(get_reg(regs[i].regmap,r&63)<0) break;
8497                       if(get_reg(branch_regs[i].regmap,r&63)<0) break;
8498                     }
8499                     k=i;
8500                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8501                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8502                         //printf("no free regs for store %x\n",start+(k-1)*4);
8503                         break;
8504                       }
8505                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8506                         //printf("no-match due to different register\n");
8507                         break;
8508                       }
8509                       if(dops[k-2].itype==UJUMP||dops[k-2].itype==RJUMP||dops[k-2].itype==CJUMP||dops[k-2].itype==SJUMP) {
8510                         //printf("no-match due to branch\n");
8511                         break;
8512                       }
8513                       // call/ret fast path assumes no registers allocated
8514                       if(k>2&&(dops[k-3].itype==UJUMP||dops[k-3].itype==RJUMP)&&dops[k-3].rt1==31) {
8515                         break;
8516                       }
8517                       assert(r < 64);
8518                       k--;
8519                     }
8520                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8521                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8522                       while(k<i) {
8523                         regs[k].regmap_entry[hr]=f_regmap[hr];
8524                         regs[k].regmap[hr]=f_regmap[hr];
8525                         regmap_pre[k+1][hr]=f_regmap[hr];
8526                         regs[k].wasdirty&=~(1<<hr);
8527                         regs[k].dirty&=~(1<<hr);
8528                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8529                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8530                         regs[k].wasconst&=~(1<<hr);
8531                         regs[k].isconst&=~(1<<hr);
8532                         k++;
8533                       }
8534                     }
8535                     else {
8536                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8537                       break;
8538                     }
8539                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8540                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8541                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8542                       regs[i].regmap_entry[hr]=f_regmap[hr];
8543                       regs[i].regmap[hr]=f_regmap[hr];
8544                       regs[i].wasdirty&=~(1<<hr);
8545                       regs[i].dirty&=~(1<<hr);
8546                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8547                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8548                       regs[i].wasconst&=~(1<<hr);
8549                       regs[i].isconst&=~(1<<hr);
8550                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8551                       branch_regs[i].wasdirty&=~(1<<hr);
8552                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8553                       branch_regs[i].regmap[hr]=f_regmap[hr];
8554                       branch_regs[i].dirty&=~(1<<hr);
8555                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8556                       branch_regs[i].wasconst&=~(1<<hr);
8557                       branch_regs[i].isconst&=~(1<<hr);
8558                       if (!is_ujump(i)) {
8559                         regmap_pre[i+2][hr]=f_regmap[hr];
8560                         regs[i+2].wasdirty&=~(1<<hr);
8561                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8562                       }
8563                     }
8564                   }
8565                   for(k=t;k<j;k++) {
8566                     // Alloc register clean at beginning of loop,
8567                     // but may dirty it in pass 6
8568                     regs[k].regmap_entry[hr]=f_regmap[hr];
8569                     regs[k].regmap[hr]=f_regmap[hr];
8570                     regs[k].dirty&=~(1<<hr);
8571                     regs[k].wasconst&=~(1<<hr);
8572                     regs[k].isconst&=~(1<<hr);
8573                     if(dops[k].itype==UJUMP||dops[k].itype==RJUMP||dops[k].itype==CJUMP||dops[k].itype==SJUMP) {
8574                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8575                       branch_regs[k].regmap[hr]=f_regmap[hr];
8576                       branch_regs[k].dirty&=~(1<<hr);
8577                       branch_regs[k].wasconst&=~(1<<hr);
8578                       branch_regs[k].isconst&=~(1<<hr);
8579                       if (!is_ujump(k)) {
8580                         regmap_pre[k+2][hr]=f_regmap[hr];
8581                         regs[k+2].wasdirty&=~(1<<hr);
8582                       }
8583                     }
8584                     else
8585                     {
8586                       regmap_pre[k+1][hr]=f_regmap[hr];
8587                       regs[k+1].wasdirty&=~(1<<hr);
8588                     }
8589                   }
8590                   if(regs[j].regmap[hr]==f_regmap[hr])
8591                     regs[j].regmap_entry[hr]=f_regmap[hr];
8592                   break;
8593                 }
8594                 if(j==i) break;
8595                 if(regs[j].regmap[hr]>=0)
8596                   break;
8597                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8598                   //printf("no-match due to different register\n");
8599                   break;
8600                 }
8601                 if (is_ujump(j))
8602                 {
8603                   // Stop on unconditional branch
8604                   break;
8605                 }
8606                 if(dops[j].itype==CJUMP||dops[j].itype==SJUMP)
8607                 {
8608                   if(dops[j].ooo) {
8609                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8610                       break;
8611                   }else{
8612                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8613                       break;
8614                   }
8615                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8616                     //printf("no-match due to different register (branch)\n");
8617                     break;
8618                   }
8619                 }
8620                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8621                   //printf("No free regs for store %x\n",start+j*4);
8622                   break;
8623                 }
8624                 assert(f_regmap[hr]<64);
8625               }
8626             }
8627           }
8628         }
8629       }
8630     }else{
8631       // Non branch or undetermined branch target
8632       for(hr=0;hr<HOST_REGS;hr++)
8633       {
8634         if(hr!=EXCLUDE_REG) {
8635           if(regs[i].regmap[hr]>=0) {
8636             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8637               // dealloc old register
8638               int n;
8639               for(n=0;n<HOST_REGS;n++)
8640               {
8641                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8642               }
8643               // and alloc new one
8644               f_regmap[hr]=regs[i].regmap[hr];
8645             }
8646           }
8647         }
8648       }
8649       // Try to restore cycle count at branch targets
8650       if(dops[i].bt) {
8651         for(j=i;j<slen-1;j++) {
8652           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8653           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8654             //printf("no free regs for store %x\n",start+j*4);
8655             break;
8656           }
8657         }
8658         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8659           int k=i;
8660           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8661           while(k<j) {
8662             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8663             regs[k].regmap[HOST_CCREG]=CCREG;
8664             regmap_pre[k+1][HOST_CCREG]=CCREG;
8665             regs[k+1].wasdirty|=1<<HOST_CCREG;
8666             regs[k].dirty|=1<<HOST_CCREG;
8667             regs[k].wasconst&=~(1<<HOST_CCREG);
8668             regs[k].isconst&=~(1<<HOST_CCREG);
8669             k++;
8670           }
8671           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8672         }
8673         // Work backwards from the branch target
8674         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8675         {
8676           //printf("Extend backwards\n");
8677           int k;
8678           k=i;
8679           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8680             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8681               //printf("no free regs for store %x\n",start+(k-1)*4);
8682               break;
8683             }
8684             k--;
8685           }
8686           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8687             //printf("Extend CC, %x ->\n",start+k*4);
8688             while(k<=i) {
8689               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8690               regs[k].regmap[HOST_CCREG]=CCREG;
8691               regmap_pre[k+1][HOST_CCREG]=CCREG;
8692               regs[k+1].wasdirty|=1<<HOST_CCREG;
8693               regs[k].dirty|=1<<HOST_CCREG;
8694               regs[k].wasconst&=~(1<<HOST_CCREG);
8695               regs[k].isconst&=~(1<<HOST_CCREG);
8696               k++;
8697             }
8698           }
8699           else {
8700             //printf("Fail Extend CC, %x ->\n",start+k*4);
8701           }
8702         }
8703       }
8704       if(dops[i].itype!=STORE&&dops[i].itype!=STORELR&&dops[i].itype!=C1LS&&dops[i].itype!=SHIFT&&
8705          dops[i].itype!=NOP&&dops[i].itype!=MOV&&dops[i].itype!=ALU&&dops[i].itype!=SHIFTIMM&&
8706          dops[i].itype!=IMM16&&dops[i].itype!=LOAD&&dops[i].itype!=COP1)
8707       {
8708         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8709       }
8710     }
8711   }
8712
8713   // This allocates registers (if possible) one instruction prior
8714   // to use, which can avoid a load-use penalty on certain CPUs.
8715   for(i=0;i<slen-1;i++)
8716   {
8717     if(!i||(dops[i-1].itype!=UJUMP&&dops[i-1].itype!=CJUMP&&dops[i-1].itype!=SJUMP&&dops[i-1].itype!=RJUMP))
8718     {
8719       if(!dops[i+1].bt)
8720       {
8721         if(dops[i].itype==ALU||dops[i].itype==MOV||dops[i].itype==LOAD||dops[i].itype==SHIFTIMM||dops[i].itype==IMM16
8722            ||((dops[i].itype==COP1||dops[i].itype==COP2)&&dops[i].opcode2<3))
8723         {
8724           if(dops[i+1].rs1) {
8725             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs1))>=0)
8726             {
8727               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8728               {
8729                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8730                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8731                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8732                 regs[i].isconst&=~(1<<hr);
8733                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8734                 constmap[i][hr]=constmap[i+1][hr];
8735                 regs[i+1].wasdirty&=~(1<<hr);
8736                 regs[i].dirty&=~(1<<hr);
8737               }
8738             }
8739           }
8740           if(dops[i+1].rs2) {
8741             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs2))>=0)
8742             {
8743               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8744               {
8745                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8746                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8747                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8748                 regs[i].isconst&=~(1<<hr);
8749                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8750                 constmap[i][hr]=constmap[i+1][hr];
8751                 regs[i+1].wasdirty&=~(1<<hr);
8752                 regs[i].dirty&=~(1<<hr);
8753               }
8754             }
8755           }
8756           // Preload target address for load instruction (non-constant)
8757           if(dops[i+1].itype==LOAD&&dops[i+1].rs1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8758             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8759             {
8760               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8761               {
8762                 regs[i].regmap[hr]=dops[i+1].rs1;
8763                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8764                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8765                 regs[i].isconst&=~(1<<hr);
8766                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8767                 constmap[i][hr]=constmap[i+1][hr];
8768                 regs[i+1].wasdirty&=~(1<<hr);
8769                 regs[i].dirty&=~(1<<hr);
8770               }
8771             }
8772           }
8773           // Load source into target register
8774           if(dops[i+1].lt1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8775             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8776             {
8777               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8778               {
8779                 regs[i].regmap[hr]=dops[i+1].rs1;
8780                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8781                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8782                 regs[i].isconst&=~(1<<hr);
8783                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8784                 constmap[i][hr]=constmap[i+1][hr];
8785                 regs[i+1].wasdirty&=~(1<<hr);
8786                 regs[i].dirty&=~(1<<hr);
8787               }
8788             }
8789           }
8790           // Address for store instruction (non-constant)
8791           if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR
8792              ||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8793             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8794               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8795               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8796               else {regs[i+1].regmap[hr]=AGEN1+((i+1)&1);regs[i+1].isconst&=~(1<<hr);}
8797               assert(hr>=0);
8798               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8799               {
8800                 regs[i].regmap[hr]=dops[i+1].rs1;
8801                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8802                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8803                 regs[i].isconst&=~(1<<hr);
8804                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8805                 constmap[i][hr]=constmap[i+1][hr];
8806                 regs[i+1].wasdirty&=~(1<<hr);
8807                 regs[i].dirty&=~(1<<hr);
8808               }
8809             }
8810           }
8811           if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
8812             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8813               int nr;
8814               hr=get_reg(regs[i+1].regmap,FTEMP);
8815               assert(hr>=0);
8816               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8817               {
8818                 regs[i].regmap[hr]=dops[i+1].rs1;
8819                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8820                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8821                 regs[i].isconst&=~(1<<hr);
8822                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8823                 constmap[i][hr]=constmap[i+1][hr];
8824                 regs[i+1].wasdirty&=~(1<<hr);
8825                 regs[i].dirty&=~(1<<hr);
8826               }
8827               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
8828               {
8829                 // move it to another register
8830                 regs[i+1].regmap[hr]=-1;
8831                 regmap_pre[i+2][hr]=-1;
8832                 regs[i+1].regmap[nr]=FTEMP;
8833                 regmap_pre[i+2][nr]=FTEMP;
8834                 regs[i].regmap[nr]=dops[i+1].rs1;
8835                 regmap_pre[i+1][nr]=dops[i+1].rs1;
8836                 regs[i+1].regmap_entry[nr]=dops[i+1].rs1;
8837                 regs[i].isconst&=~(1<<nr);
8838                 regs[i+1].isconst&=~(1<<nr);
8839                 regs[i].dirty&=~(1<<nr);
8840                 regs[i+1].wasdirty&=~(1<<nr);
8841                 regs[i+1].dirty&=~(1<<nr);
8842                 regs[i+2].wasdirty&=~(1<<nr);
8843               }
8844             }
8845           }
8846           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*/) {
8847             if(dops[i+1].itype==LOAD)
8848               hr=get_reg(regs[i+1].regmap,dops[i+1].rt1);
8849             if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
8850               hr=get_reg(regs[i+1].regmap,FTEMP);
8851             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
8852               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
8853               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8854             }
8855             if(hr>=0&&regs[i].regmap[hr]<0) {
8856               int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
8857               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
8858                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
8859                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
8860                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
8861                 regs[i].isconst&=~(1<<hr);
8862                 regs[i+1].wasdirty&=~(1<<hr);
8863                 regs[i].dirty&=~(1<<hr);
8864               }
8865             }
8866           }
8867         }
8868       }
8869     }
8870   }
8871
8872   /* Pass 6 - Optimize clean/dirty state */
8873   clean_registers(0,slen-1,1);
8874
8875   /* Pass 7 - Identify 32-bit registers */
8876   for (i=slen-1;i>=0;i--)
8877   {
8878     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8879     {
8880       // Conditional branch
8881       if((source[i]>>16)!=0x1000&&i<slen-2) {
8882         // Mark this address as a branch target since it may be called
8883         // upon return from interrupt
8884         dops[i+2].bt=1;
8885       }
8886     }
8887   }
8888
8889   if(dops[slen-1].itype==SPAN) {
8890     dops[slen-1].bt=1; // Mark as a branch target so instruction can restart after exception
8891   }
8892
8893 #ifdef DISASM
8894   /* Debug/disassembly */
8895   for(i=0;i<slen;i++)
8896   {
8897     printf("U:");
8898     int r;
8899     for(r=1;r<=CCREG;r++) {
8900       if((unneeded_reg[i]>>r)&1) {
8901         if(r==HIREG) printf(" HI");
8902         else if(r==LOREG) printf(" LO");
8903         else printf(" r%d",r);
8904       }
8905     }
8906     printf("\n");
8907     #if defined(__i386__) || defined(__x86_64__)
8908     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]);
8909     #endif
8910     #ifdef __arm__
8911     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]);
8912     #endif
8913     #if defined(__i386__) || defined(__x86_64__)
8914     printf("needs: ");
8915     if(needed_reg[i]&1) printf("eax ");
8916     if((needed_reg[i]>>1)&1) printf("ecx ");
8917     if((needed_reg[i]>>2)&1) printf("edx ");
8918     if((needed_reg[i]>>3)&1) printf("ebx ");
8919     if((needed_reg[i]>>5)&1) printf("ebp ");
8920     if((needed_reg[i]>>6)&1) printf("esi ");
8921     if((needed_reg[i]>>7)&1) printf("edi ");
8922     printf("\n");
8923     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]);
8924     printf("dirty: ");
8925     if(regs[i].wasdirty&1) printf("eax ");
8926     if((regs[i].wasdirty>>1)&1) printf("ecx ");
8927     if((regs[i].wasdirty>>2)&1) printf("edx ");
8928     if((regs[i].wasdirty>>3)&1) printf("ebx ");
8929     if((regs[i].wasdirty>>5)&1) printf("ebp ");
8930     if((regs[i].wasdirty>>6)&1) printf("esi ");
8931     if((regs[i].wasdirty>>7)&1) printf("edi ");
8932     #endif
8933     #ifdef __arm__
8934     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]);
8935     printf("dirty: ");
8936     if(regs[i].wasdirty&1) printf("r0 ");
8937     if((regs[i].wasdirty>>1)&1) printf("r1 ");
8938     if((regs[i].wasdirty>>2)&1) printf("r2 ");
8939     if((regs[i].wasdirty>>3)&1) printf("r3 ");
8940     if((regs[i].wasdirty>>4)&1) printf("r4 ");
8941     if((regs[i].wasdirty>>5)&1) printf("r5 ");
8942     if((regs[i].wasdirty>>6)&1) printf("r6 ");
8943     if((regs[i].wasdirty>>7)&1) printf("r7 ");
8944     if((regs[i].wasdirty>>8)&1) printf("r8 ");
8945     if((regs[i].wasdirty>>9)&1) printf("r9 ");
8946     if((regs[i].wasdirty>>10)&1) printf("r10 ");
8947     if((regs[i].wasdirty>>12)&1) printf("r12 ");
8948     #endif
8949     printf("\n");
8950     disassemble_inst(i);
8951     //printf ("ccadj[%d] = %d\n",i,ccadj[i]);
8952     #if defined(__i386__) || defined(__x86_64__)
8953     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]);
8954     if(regs[i].dirty&1) printf("eax ");
8955     if((regs[i].dirty>>1)&1) printf("ecx ");
8956     if((regs[i].dirty>>2)&1) printf("edx ");
8957     if((regs[i].dirty>>3)&1) printf("ebx ");
8958     if((regs[i].dirty>>5)&1) printf("ebp ");
8959     if((regs[i].dirty>>6)&1) printf("esi ");
8960     if((regs[i].dirty>>7)&1) printf("edi ");
8961     #endif
8962     #ifdef __arm__
8963     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]);
8964     if(regs[i].dirty&1) printf("r0 ");
8965     if((regs[i].dirty>>1)&1) printf("r1 ");
8966     if((regs[i].dirty>>2)&1) printf("r2 ");
8967     if((regs[i].dirty>>3)&1) printf("r3 ");
8968     if((regs[i].dirty>>4)&1) printf("r4 ");
8969     if((regs[i].dirty>>5)&1) printf("r5 ");
8970     if((regs[i].dirty>>6)&1) printf("r6 ");
8971     if((regs[i].dirty>>7)&1) printf("r7 ");
8972     if((regs[i].dirty>>8)&1) printf("r8 ");
8973     if((regs[i].dirty>>9)&1) printf("r9 ");
8974     if((regs[i].dirty>>10)&1) printf("r10 ");
8975     if((regs[i].dirty>>12)&1) printf("r12 ");
8976     #endif
8977     printf("\n");
8978     if(regs[i].isconst) {
8979       printf("constants: ");
8980       #if defined(__i386__) || defined(__x86_64__)
8981       if(regs[i].isconst&1) printf("eax=%x ",(u_int)constmap[i][0]);
8982       if((regs[i].isconst>>1)&1) printf("ecx=%x ",(u_int)constmap[i][1]);
8983       if((regs[i].isconst>>2)&1) printf("edx=%x ",(u_int)constmap[i][2]);
8984       if((regs[i].isconst>>3)&1) printf("ebx=%x ",(u_int)constmap[i][3]);
8985       if((regs[i].isconst>>5)&1) printf("ebp=%x ",(u_int)constmap[i][5]);
8986       if((regs[i].isconst>>6)&1) printf("esi=%x ",(u_int)constmap[i][6]);
8987       if((regs[i].isconst>>7)&1) printf("edi=%x ",(u_int)constmap[i][7]);
8988       #endif
8989       #if defined(__arm__) || defined(__aarch64__)
8990       int r;
8991       for (r = 0; r < ARRAY_SIZE(constmap[i]); r++)
8992         if ((regs[i].isconst >> r) & 1)
8993           printf(" r%d=%x", r, (u_int)constmap[i][r]);
8994       #endif
8995       printf("\n");
8996     }
8997     if(dops[i].itype==RJUMP||dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP) {
8998       #if defined(__i386__) || defined(__x86_64__)
8999       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]);
9000       if(branch_regs[i].dirty&1) printf("eax ");
9001       if((branch_regs[i].dirty>>1)&1) printf("ecx ");
9002       if((branch_regs[i].dirty>>2)&1) printf("edx ");
9003       if((branch_regs[i].dirty>>3)&1) printf("ebx ");
9004       if((branch_regs[i].dirty>>5)&1) printf("ebp ");
9005       if((branch_regs[i].dirty>>6)&1) printf("esi ");
9006       if((branch_regs[i].dirty>>7)&1) printf("edi ");
9007       #endif
9008       #ifdef __arm__
9009       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]);
9010       if(branch_regs[i].dirty&1) printf("r0 ");
9011       if((branch_regs[i].dirty>>1)&1) printf("r1 ");
9012       if((branch_regs[i].dirty>>2)&1) printf("r2 ");
9013       if((branch_regs[i].dirty>>3)&1) printf("r3 ");
9014       if((branch_regs[i].dirty>>4)&1) printf("r4 ");
9015       if((branch_regs[i].dirty>>5)&1) printf("r5 ");
9016       if((branch_regs[i].dirty>>6)&1) printf("r6 ");
9017       if((branch_regs[i].dirty>>7)&1) printf("r7 ");
9018       if((branch_regs[i].dirty>>8)&1) printf("r8 ");
9019       if((branch_regs[i].dirty>>9)&1) printf("r9 ");
9020       if((branch_regs[i].dirty>>10)&1) printf("r10 ");
9021       if((branch_regs[i].dirty>>12)&1) printf("r12 ");
9022       #endif
9023     }
9024   }
9025 #endif // DISASM
9026
9027   /* Pass 8 - Assembly */
9028   linkcount=0;stubcount=0;
9029   ds=0;is_delayslot=0;
9030   u_int dirty_pre=0;
9031   void *beginning=start_block();
9032   if((u_int)addr&1) {
9033     ds=1;
9034     pagespan_ds();
9035   }
9036   void *instr_addr0_override = NULL;
9037
9038   if (start == 0x80030000) {
9039     // nasty hack for the fastbios thing
9040     // override block entry to this code
9041     instr_addr0_override = out;
9042     emit_movimm(start,0);
9043     // abuse io address var as a flag that we
9044     // have already returned here once
9045     emit_readword(&address,1);
9046     emit_writeword(0,&pcaddr);
9047     emit_writeword(0,&address);
9048     emit_cmp(0,1);
9049     #ifdef __aarch64__
9050     emit_jeq(out + 4*2);
9051     emit_far_jump(new_dyna_leave);
9052     #else
9053     emit_jne(new_dyna_leave);
9054     #endif
9055   }
9056   for(i=0;i<slen;i++)
9057   {
9058     //if(ds) printf("ds: ");
9059     disassemble_inst(i);
9060     if(ds) {
9061       ds=0; // Skip delay slot
9062       if(dops[i].bt) assem_debug("OOPS - branch into delay slot\n");
9063       instr_addr[i] = NULL;
9064     } else {
9065       speculate_register_values(i);
9066       #ifndef DESTRUCTIVE_WRITEBACK
9067       if (i < 2 || !is_ujump(i-2))
9068       {
9069         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
9070       }
9071       if((dops[i].itype==CJUMP||dops[i].itype==SJUMP)&&!dops[i].likely) {
9072         dirty_pre=branch_regs[i].dirty;
9073       }else{
9074         dirty_pre=regs[i].dirty;
9075       }
9076       #endif
9077       // write back
9078       if (i < 2 || !is_ujump(i-2))
9079       {
9080         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
9081         loop_preload(regmap_pre[i],regs[i].regmap_entry);
9082       }
9083       // branch target entry point
9084       instr_addr[i] = out;
9085       assem_debug("<->\n");
9086       drc_dbg_emit_do_cmp(i);
9087
9088       // load regs
9089       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
9090         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
9091       load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i].rs1,dops[i].rs2);
9092       address_generation(i,&regs[i],regs[i].regmap_entry);
9093       load_consts(regmap_pre[i],regs[i].regmap,i);
9094       if(dops[i].itype==RJUMP||dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
9095       {
9096         // Load the delay slot registers if necessary
9097         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))
9098           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9099         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))
9100           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9101         if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a)
9102           load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9103       }
9104       else if(i+1<slen)
9105       {
9106         // Preload registers for following instruction
9107         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2)
9108           if(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs1!=dops[i].rt2)
9109             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9110         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2)
9111           if(dops[i+1].rs2!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt2)
9112             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9113       }
9114       // TODO: if(is_ooo(i)) address_generation(i+1);
9115       if(dops[i].itype==CJUMP)
9116         load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
9117       if(dops[i].itype==STORE||dops[i].itype==STORELR||(dops[i].opcode&0x3b)==0x39||(dops[i].opcode&0x3b)==0x3a)
9118         load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9119       // assemble
9120       switch(dops[i].itype) {
9121         case ALU:
9122           alu_assemble(i,&regs[i]);break;
9123         case IMM16:
9124           imm16_assemble(i,&regs[i]);break;
9125         case SHIFT:
9126           shift_assemble(i,&regs[i]);break;
9127         case SHIFTIMM:
9128           shiftimm_assemble(i,&regs[i]);break;
9129         case LOAD:
9130           load_assemble(i,&regs[i]);break;
9131         case LOADLR:
9132           loadlr_assemble(i,&regs[i]);break;
9133         case STORE:
9134           store_assemble(i,&regs[i]);break;
9135         case STORELR:
9136           storelr_assemble(i,&regs[i]);break;
9137         case COP0:
9138           cop0_assemble(i,&regs[i]);break;
9139         case COP1:
9140           cop1_assemble(i,&regs[i]);break;
9141         case C1LS:
9142           c1ls_assemble(i,&regs[i]);break;
9143         case COP2:
9144           cop2_assemble(i,&regs[i]);break;
9145         case C2LS:
9146           c2ls_assemble(i,&regs[i]);break;
9147         case C2OP:
9148           c2op_assemble(i,&regs[i]);break;
9149         case MULTDIV:
9150           multdiv_assemble(i,&regs[i]);
9151           multdiv_prepare_stall(i,&regs[i]);
9152           break;
9153         case MOV:
9154           mov_assemble(i,&regs[i]);break;
9155         case SYSCALL:
9156           syscall_assemble(i,&regs[i]);break;
9157         case HLECALL:
9158           hlecall_assemble(i,&regs[i]);break;
9159         case INTCALL:
9160           intcall_assemble(i,&regs[i]);break;
9161         case UJUMP:
9162           ujump_assemble(i,&regs[i]);ds=1;break;
9163         case RJUMP:
9164           rjump_assemble(i,&regs[i]);ds=1;break;
9165         case CJUMP:
9166           cjump_assemble(i,&regs[i]);ds=1;break;
9167         case SJUMP:
9168           sjump_assemble(i,&regs[i]);ds=1;break;
9169         case SPAN:
9170           pagespan_assemble(i,&regs[i]);break;
9171       }
9172       if (is_ujump(i))
9173         literal_pool(1024);
9174       else
9175         literal_pool_jumpover(256);
9176     }
9177   }
9178
9179   assert(slen > 0);
9180   if (slen > 0 && dops[slen-1].itype == INTCALL) {
9181     // no ending needed for this block since INTCALL never returns
9182   }
9183   // If the block did not end with an unconditional branch,
9184   // add a jump to the next instruction.
9185   else if (i > 1) {
9186     if(!is_ujump(i-2)&&dops[i-1].itype!=SPAN) {
9187       assert(dops[i-1].itype!=UJUMP&&dops[i-1].itype!=CJUMP&&dops[i-1].itype!=SJUMP&&dops[i-1].itype!=RJUMP);
9188       assert(i==slen);
9189       if(dops[i-2].itype!=CJUMP&&dops[i-2].itype!=SJUMP) {
9190         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9191         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9192           emit_loadreg(CCREG,HOST_CCREG);
9193         emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
9194       }
9195       else if(!dops[i-2].likely)
9196       {
9197         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
9198         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
9199       }
9200       else
9201       {
9202         store_regs_bt(regs[i-2].regmap,regs[i-2].dirty,start+i*4);
9203         assert(regs[i-2].regmap[HOST_CCREG]==CCREG);
9204       }
9205       add_to_linker(out,start+i*4,0);
9206       emit_jmp(0);
9207     }
9208   }
9209   else
9210   {
9211     assert(i>0);
9212     assert(dops[i-1].itype!=UJUMP&&dops[i-1].itype!=CJUMP&&dops[i-1].itype!=SJUMP&&dops[i-1].itype!=RJUMP);
9213     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9214     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9215       emit_loadreg(CCREG,HOST_CCREG);
9216     emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
9217     add_to_linker(out,start+i*4,0);
9218     emit_jmp(0);
9219   }
9220
9221   // TODO: delay slot stubs?
9222   // Stubs
9223   for(i=0;i<stubcount;i++)
9224   {
9225     switch(stubs[i].type)
9226     {
9227       case LOADB_STUB:
9228       case LOADH_STUB:
9229       case LOADW_STUB:
9230       case LOADD_STUB:
9231       case LOADBU_STUB:
9232       case LOADHU_STUB:
9233         do_readstub(i);break;
9234       case STOREB_STUB:
9235       case STOREH_STUB:
9236       case STOREW_STUB:
9237       case STORED_STUB:
9238         do_writestub(i);break;
9239       case CC_STUB:
9240         do_ccstub(i);break;
9241       case INVCODE_STUB:
9242         do_invstub(i);break;
9243       case FP_STUB:
9244         do_cop1stub(i);break;
9245       case STORELR_STUB:
9246         do_unalignedwritestub(i);break;
9247     }
9248   }
9249
9250   if (instr_addr0_override)
9251     instr_addr[0] = instr_addr0_override;
9252
9253   /* Pass 9 - Linker */
9254   for(i=0;i<linkcount;i++)
9255   {
9256     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9257     literal_pool(64);
9258     if (!link_addr[i].ext)
9259     {
9260       void *stub = out;
9261       void *addr = check_addr(link_addr[i].target);
9262       emit_extjump(link_addr[i].addr, link_addr[i].target);
9263       if (addr) {
9264         set_jump_target(link_addr[i].addr, addr);
9265         add_jump_out(link_addr[i].target,stub);
9266       }
9267       else
9268         set_jump_target(link_addr[i].addr, stub);
9269     }
9270     else
9271     {
9272       // Internal branch
9273       int target=(link_addr[i].target-start)>>2;
9274       assert(target>=0&&target<slen);
9275       assert(instr_addr[target]);
9276       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9277       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9278       //#else
9279       set_jump_target(link_addr[i].addr, instr_addr[target]);
9280       //#endif
9281     }
9282   }
9283
9284   u_int source_len = slen*4;
9285   if (dops[slen-1].itype == INTCALL && source_len > 4)
9286     // no need to treat the last instruction as compiled
9287     // as interpreter fully handles it
9288     source_len -= 4;
9289
9290   if ((u_char *)copy + source_len > (u_char *)shadow + sizeof(shadow))
9291     copy = shadow;
9292
9293   // External Branch Targets (jump_in)
9294   for(i=0;i<slen;i++)
9295   {
9296     if(dops[i].bt||i==0)
9297     {
9298       if(instr_addr[i]) // TODO - delay slots (=null)
9299       {
9300         u_int vaddr=start+i*4;
9301         u_int page=get_page(vaddr);
9302         u_int vpage=get_vpage(vaddr);
9303         literal_pool(256);
9304         {
9305           assem_debug("%p (%d) <- %8x\n",instr_addr[i],i,start+i*4);
9306           assem_debug("jump_in: %x\n",start+i*4);
9307           ll_add(jump_dirty+vpage,vaddr,out);
9308           void *entry_point = do_dirty_stub(i, source_len);
9309           ll_add_flags(jump_in+page,vaddr,state_rflags,entry_point);
9310           // If there was an existing entry in the hash table,
9311           // replace it with the new address.
9312           // Don't add new entries.  We'll insert the
9313           // ones that actually get used in check_addr().
9314           struct ht_entry *ht_bin = hash_table_get(vaddr);
9315           if (ht_bin->vaddr[0] == vaddr)
9316             ht_bin->tcaddr[0] = entry_point;
9317           if (ht_bin->vaddr[1] == vaddr)
9318             ht_bin->tcaddr[1] = entry_point;
9319         }
9320       }
9321     }
9322   }
9323   // Write out the literal pool if necessary
9324   literal_pool(0);
9325   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9326   // Align code
9327   if(((u_int)out)&7) emit_addnop(13);
9328   #endif
9329   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9330   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9331   memcpy(copy, source, source_len);
9332   copy += source_len;
9333
9334   end_block(beginning);
9335
9336   // If we're within 256K of the end of the buffer,
9337   // start over from the beginning. (Is 256K enough?)
9338   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9339     out = ndrc->translation_cache;
9340
9341   // Trap writes to any of the pages we compiled
9342   for(i=start>>12;i<=(start+slen*4)>>12;i++) {
9343     invalid_code[i]=0;
9344   }
9345   inv_code_start=inv_code_end=~0;
9346
9347   // for PCSX we need to mark all mirrors too
9348   if(get_page(start)<(RAM_SIZE>>12))
9349     for(i=start>>12;i<=(start+slen*4)>>12;i++)
9350       invalid_code[((u_int)0x00000000>>12)|(i&0x1ff)]=
9351       invalid_code[((u_int)0x80000000>>12)|(i&0x1ff)]=
9352       invalid_code[((u_int)0xa0000000>>12)|(i&0x1ff)]=0;
9353
9354   /* Pass 10 - Free memory by expiring oldest blocks */
9355
9356   int end=(((out-ndrc->translation_cache)>>(TARGET_SIZE_2-16))+16384)&65535;
9357   while(expirep!=end)
9358   {
9359     int shift=TARGET_SIZE_2-3; // Divide into 8 blocks
9360     uintptr_t base_offs = ((uintptr_t)(expirep >> 13) << shift); // Base offset of this block
9361     uintptr_t base_offs_s = base_offs >> shift;
9362     inv_debug("EXP: Phase %d\n",expirep);
9363     switch((expirep>>11)&3)
9364     {
9365       case 0:
9366         // Clear jump_in and jump_dirty
9367         ll_remove_matching_addrs(jump_in+(expirep&2047),base_offs_s,shift);
9368         ll_remove_matching_addrs(jump_dirty+(expirep&2047),base_offs_s,shift);
9369         ll_remove_matching_addrs(jump_in+2048+(expirep&2047),base_offs_s,shift);
9370         ll_remove_matching_addrs(jump_dirty+2048+(expirep&2047),base_offs_s,shift);
9371         break;
9372       case 1:
9373         // Clear pointers
9374         ll_kill_pointers(jump_out[expirep&2047],base_offs_s,shift);
9375         ll_kill_pointers(jump_out[(expirep&2047)+2048],base_offs_s,shift);
9376         break;
9377       case 2:
9378         // Clear hash table
9379         for(i=0;i<32;i++) {
9380           struct ht_entry *ht_bin = &hash_table[((expirep&2047)<<5)+i];
9381           uintptr_t o1 = (u_char *)ht_bin->tcaddr[1] - ndrc->translation_cache;
9382           uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
9383           if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s) {
9384             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[1],ht_bin->tcaddr[1]);
9385             ht_bin->vaddr[1] = -1;
9386             ht_bin->tcaddr[1] = NULL;
9387           }
9388           o1 = (u_char *)ht_bin->tcaddr[0] - ndrc->translation_cache;
9389           o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
9390           if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s) {
9391             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[0],ht_bin->tcaddr[0]);
9392             ht_bin->vaddr[0] = ht_bin->vaddr[1];
9393             ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
9394             ht_bin->vaddr[1] = -1;
9395             ht_bin->tcaddr[1] = NULL;
9396           }
9397         }
9398         break;
9399       case 3:
9400         // Clear jump_out
9401         if((expirep&2047)==0)
9402           do_clear_cache();
9403         ll_remove_matching_addrs(jump_out+(expirep&2047),base_offs_s,shift);
9404         ll_remove_matching_addrs(jump_out+2048+(expirep&2047),base_offs_s,shift);
9405         break;
9406     }
9407     expirep=(expirep+1)&65535;
9408   }
9409   return 0;
9410 }
9411
9412 // vim:shiftwidth=2:expandtab