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