drc: minor adjustments
[pcsx_rearmed.git] / libpcsxcore / new_dynarec / new_dynarec.c
1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  *   Mupen64plus - new_dynarec.c                                           *
3  *   Copyright (C) 2009-2011 Ari64                                         *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
19  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
20
21 #include <stdlib.h>
22 #include <stdint.h> //include for uint64_t
23 #include <assert.h>
24 #include <errno.h>
25 #include <sys/mman.h>
26 #ifdef __MACH__
27 #include <libkern/OSCacheControl.h>
28 #endif
29 #ifdef _3DS
30 #include <3ds_utils.h>
31 #endif
32 #ifdef VITA
33 #include <psp2/kernel/sysmem.h>
34 static int sceBlock;
35 #endif
36
37 #include "new_dynarec_config.h"
38 #include "../psxhle.h"
39 #include "../psxinterpreter.h"
40 #include "../gte.h"
41 #include "emu_if.h" // emulator interface
42
43 #define noinline __attribute__((noinline,noclone))
44 #ifndef ARRAY_SIZE
45 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
46 #endif
47 #ifndef min
48 #define min(a, b) ((b) < (a) ? (b) : (a))
49 #endif
50 #ifndef max
51 #define max(a, b) ((b) > (a) ? (b) : (a))
52 #endif
53
54 //#define DISASM
55 //#define ASSEM_PRINT
56
57 #ifdef ASSEM_PRINT
58 #define assem_debug printf
59 #else
60 #define assem_debug(...)
61 #endif
62 //#define inv_debug printf
63 #define inv_debug(...)
64
65 #ifdef __i386__
66 #include "assem_x86.h"
67 #endif
68 #ifdef __x86_64__
69 #include "assem_x64.h"
70 #endif
71 #ifdef __arm__
72 #include "assem_arm.h"
73 #endif
74 #ifdef __aarch64__
75 #include "assem_arm64.h"
76 #endif
77
78 #define RAM_SIZE 0x200000
79 #define MAXBLOCK 4096
80 #define MAX_OUTPUT_BLOCK_SIZE 262144
81
82 struct ndrc_mem
83 {
84   u_char translation_cache[1 << TARGET_SIZE_2];
85   struct
86   {
87     struct tramp_insns ops[2048 / sizeof(struct tramp_insns)];
88     const void *f[2048 / sizeof(void *)];
89   } tramp;
90 };
91
92 #ifdef BASE_ADDR_DYNAMIC
93 static struct ndrc_mem *ndrc;
94 #else
95 static struct ndrc_mem ndrc_ __attribute__((aligned(4096)));
96 static struct ndrc_mem *ndrc = &ndrc_;
97 #endif
98
99 // stubs
100 enum stub_type {
101   CC_STUB = 1,
102   FP_STUB = 2,
103   LOADB_STUB = 3,
104   LOADH_STUB = 4,
105   LOADW_STUB = 5,
106   LOADD_STUB = 6,
107   LOADBU_STUB = 7,
108   LOADHU_STUB = 8,
109   STOREB_STUB = 9,
110   STOREH_STUB = 10,
111   STOREW_STUB = 11,
112   STORED_STUB = 12,
113   STORELR_STUB = 13,
114   INVCODE_STUB = 14,
115 };
116
117 struct regstat
118 {
119   signed char regmap_entry[HOST_REGS];
120   signed char regmap[HOST_REGS];
121   uint64_t wasdirty;
122   uint64_t dirty;
123   uint64_t u;
124   u_int wasconst;
125   u_int isconst;
126   u_int loadedconst;             // host regs that have constants loaded
127   u_int waswritten;              // MIPS regs that were used as store base before
128 };
129
130 // note: asm depends on this layout
131 struct ll_entry
132 {
133   u_int vaddr;
134   u_int reg_sv_flags;
135   void *addr;
136   struct ll_entry *next;
137 };
138
139 struct ht_entry
140 {
141   u_int vaddr[2];
142   void *tcaddr[2];
143 };
144
145 struct code_stub
146 {
147   enum stub_type type;
148   void *addr;
149   void *retaddr;
150   u_int a;
151   uintptr_t b;
152   uintptr_t c;
153   u_int d;
154   u_int e;
155 };
156
157 struct link_entry
158 {
159   void *addr;
160   u_int target;
161   u_int ext;
162 };
163
164   // used by asm:
165   u_char *out;
166   struct ht_entry hash_table[65536]  __attribute__((aligned(16)));
167   struct ll_entry *jump_in[4096] __attribute__((aligned(16)));
168   struct ll_entry *jump_dirty[4096];
169
170   static struct ll_entry *jump_out[4096];
171   static u_int start;
172   static u_int *source;
173   static char insn[MAXBLOCK][10];
174   static u_char itype[MAXBLOCK];
175   static u_char opcode[MAXBLOCK];
176   static u_char opcode2[MAXBLOCK];
177   static u_char bt[MAXBLOCK];
178   static u_char rs1[MAXBLOCK];
179   static u_char rs2[MAXBLOCK];
180   static u_char rt1[MAXBLOCK];
181   static u_char rt2[MAXBLOCK];
182   static u_char dep1[MAXBLOCK];
183   static u_char dep2[MAXBLOCK];
184   static u_char lt1[MAXBLOCK];
185   static uint64_t gte_rs[MAXBLOCK]; // gte: 32 data and 32 ctl regs
186   static uint64_t gte_rt[MAXBLOCK];
187   static uint64_t gte_unneeded[MAXBLOCK];
188   static u_int smrv[32]; // speculated MIPS register values
189   static u_int smrv_strong; // mask or regs that are likely to have correct values
190   static u_int smrv_weak; // same, but somewhat less likely
191   static u_int smrv_strong_next; // same, but after current insn executes
192   static u_int smrv_weak_next;
193   static int imm[MAXBLOCK];
194   static u_int ba[MAXBLOCK];
195   static char likely[MAXBLOCK];
196   static char is_ds[MAXBLOCK];
197   static char ooo[MAXBLOCK];
198   static uint64_t unneeded_reg[MAXBLOCK];
199   static uint64_t branch_unneeded_reg[MAXBLOCK];
200   static signed char regmap_pre[MAXBLOCK][HOST_REGS]; // pre-instruction i?
201   // contains 'real' consts at [i] insn, but may differ from what's actually
202   // loaded in host reg as 'final' value is always loaded, see get_final_value()
203   static uint32_t current_constmap[HOST_REGS];
204   static uint32_t constmap[MAXBLOCK][HOST_REGS];
205   static struct regstat regs[MAXBLOCK];
206   static struct regstat branch_regs[MAXBLOCK];
207   static signed char minimum_free_regs[MAXBLOCK];
208   static u_int needed_reg[MAXBLOCK];
209   static u_int wont_dirty[MAXBLOCK];
210   static u_int will_dirty[MAXBLOCK];
211   static int ccadj[MAXBLOCK];
212   static int slen;
213   static void *instr_addr[MAXBLOCK];
214   static struct link_entry link_addr[MAXBLOCK];
215   static int linkcount;
216   static struct code_stub stubs[MAXBLOCK*3];
217   static int stubcount;
218   static u_int literals[1024][2];
219   static int literalcount;
220   static int is_delayslot;
221   static char shadow[1048576]  __attribute__((aligned(16)));
222   static void *copy;
223   static int expirep;
224   static u_int stop_after_jal;
225 #ifndef RAM_FIXED
226   static uintptr_t ram_offset;
227 #else
228   static const uintptr_t ram_offset=0;
229 #endif
230
231   int new_dynarec_hacks;
232   int new_dynarec_hacks_pergame;
233   int new_dynarec_hacks_old;
234   int new_dynarec_did_compile;
235
236   #define HACK_ENABLED(x) ((new_dynarec_hacks | new_dynarec_hacks_pergame) & (x))
237
238   extern int cycle_count; // ... until end of the timeslice, counts -N -> 0
239   extern int last_count;  // last absolute target, often = next_interupt
240   extern int pcaddr;
241   extern int pending_exception;
242   extern int branch_target;
243   extern uintptr_t mini_ht[32][2];
244   extern u_char restore_candidate[512];
245
246   /* registers that may be allocated */
247   /* 1-31 gpr */
248 #define LOREG 32 // lo
249 #define HIREG 33 // hi
250 //#define FSREG 34 // FPU status (FCSR)
251 #define CSREG 35 // Coprocessor status
252 #define CCREG 36 // Cycle count
253 #define INVCP 37 // Pointer to invalid_code
254 //#define MMREG 38 // Pointer to memory_map
255 //#define ROREG 39 // ram offset (if rdram!=0x80000000)
256 #define TEMPREG 40
257 #define FTEMP 40 // FPU temporary register
258 #define PTEMP 41 // Prefetch temporary register
259 //#define TLREG 42 // TLB mapping offset
260 #define RHASH 43 // Return address hash
261 #define RHTBL 44 // Return address hash table address
262 #define RTEMP 45 // JR/JALR address register
263 #define MAXREG 45
264 #define AGEN1 46 // Address generation temporary register
265 //#define AGEN2 47 // Address generation temporary register
266 //#define MGEN1 48 // Maptable address generation temporary register
267 //#define MGEN2 49 // Maptable address generation temporary register
268 #define BTREG 50 // Branch target temporary register
269
270   /* instruction types */
271 #define NOP 0     // No operation
272 #define LOAD 1    // Load
273 #define STORE 2   // Store
274 #define LOADLR 3  // Unaligned load
275 #define STORELR 4 // Unaligned store
276 #define MOV 5     // Move
277 #define ALU 6     // Arithmetic/logic
278 #define MULTDIV 7 // Multiply/divide
279 #define SHIFT 8   // Shift by register
280 #define SHIFTIMM 9// Shift by immediate
281 #define IMM16 10  // 16-bit immediate
282 #define RJUMP 11  // Unconditional jump to register
283 #define UJUMP 12  // Unconditional jump
284 #define CJUMP 13  // Conditional branch (BEQ/BNE/BGTZ/BLEZ)
285 #define SJUMP 14  // Conditional branch (regimm format)
286 #define COP0 15   // Coprocessor 0
287 #define COP1 16   // Coprocessor 1
288 #define C1LS 17   // Coprocessor 1 load/store
289 //#define FJUMP 18  // Conditional branch (floating point)
290 //#define FLOAT 19  // Floating point unit
291 //#define FCONV 20  // Convert integer to float
292 //#define FCOMP 21  // Floating point compare (sets FSREG)
293 #define SYSCALL 22// SYSCALL
294 #define OTHER 23  // Other
295 #define SPAN 24   // Branch/delay slot spans 2 pages
296 #define NI 25     // Not implemented
297 #define HLECALL 26// PCSX fake opcodes for HLE
298 #define COP2 27   // Coprocessor 2 move
299 #define C2LS 28   // Coprocessor 2 load/store
300 #define C2OP 29   // Coprocessor 2 operation
301 #define INTCALL 30// Call interpreter to handle rare corner cases
302
303   /* branch codes */
304 #define TAKEN 1
305 #define NOTTAKEN 2
306 #define NULLDS 3
307
308 #define DJT_1 (void *)1l // no function, just a label in assem_debug log
309 #define DJT_2 (void *)2l
310
311 // asm linkage
312 int new_recompile_block(u_int addr);
313 void *get_addr_ht(u_int vaddr);
314 void invalidate_block(u_int block);
315 void invalidate_addr(u_int addr);
316 void remove_hash(int vaddr);
317 void dyna_linker();
318 void dyna_linker_ds();
319 void verify_code();
320 void verify_code_ds();
321 void cc_interrupt();
322 void fp_exception();
323 void fp_exception_ds();
324 void jump_to_new_pc();
325 void call_gteStall();
326 void new_dyna_leave();
327
328 // Needed by assembler
329 static void wb_register(signed char r,signed char regmap[],uint64_t dirty);
330 static void wb_dirtys(signed char i_regmap[],uint64_t i_dirty);
331 static void wb_needed_dirtys(signed char i_regmap[],uint64_t i_dirty,int addr);
332 static void load_all_regs(signed char i_regmap[]);
333 static void load_needed_regs(signed char i_regmap[],signed char next_regmap[]);
334 static void load_regs_entry(int t);
335 static void load_all_consts(signed char regmap[],u_int dirty,int i);
336 static u_int get_host_reglist(const signed char *regmap);
337
338 static int verify_dirty(const u_int *ptr);
339 static int get_final_value(int hr, int i, int *value);
340 static void add_stub(enum stub_type type, void *addr, void *retaddr,
341   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e);
342 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
343   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist);
344 static void add_to_linker(void *addr, u_int target, int ext);
345 static void *emit_fastpath_cmp_jump(int i,int addr,int *addr_reg_override);
346 static void *get_direct_memhandler(void *table, u_int addr,
347   enum stub_type type, uintptr_t *addr_host);
348 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist);
349 static void pass_args(int a0, int a1);
350 static void emit_far_jump(const void *f);
351 static void emit_far_call(const void *f);
352
353 static void mprotect_w_x(void *start, void *end, int is_x)
354 {
355 #ifdef NO_WRITE_EXEC
356   #if defined(VITA)
357   // *Open* enables write on all memory that was
358   // allocated by sceKernelAllocMemBlockForVM()?
359   if (is_x)
360     sceKernelCloseVMDomain();
361   else
362     sceKernelOpenVMDomain();
363   #else
364   u_long mstart = (u_long)start & ~4095ul;
365   u_long mend = (u_long)end;
366   if (mprotect((void *)mstart, mend - mstart,
367                PROT_READ | (is_x ? PROT_EXEC : PROT_WRITE)) != 0)
368     SysPrintf("mprotect(%c) failed: %s\n", is_x ? 'x' : 'w', strerror(errno));
369   #endif
370 #endif
371 }
372
373 static void start_tcache_write(void *start, void *end)
374 {
375   mprotect_w_x(start, end, 0);
376 }
377
378 static void end_tcache_write(void *start, void *end)
379 {
380 #if defined(__arm__) || defined(__aarch64__)
381   size_t len = (char *)end - (char *)start;
382   #if   defined(__BLACKBERRY_QNX__)
383   msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
384   #elif defined(__MACH__)
385   sys_cache_control(kCacheFunctionPrepareForExecution, start, len);
386   #elif defined(VITA)
387   sceKernelSyncVMDomain(sceBlock, start, len);
388   #elif defined(_3DS)
389   ctr_flush_invalidate_cache();
390   #elif defined(__aarch64__)
391   // as of 2021, __clear_cache() is still broken on arm64
392   // so here is a custom one :(
393   clear_cache_arm64(start, end);
394   #else
395   __clear_cache(start, end);
396   #endif
397   (void)len;
398 #endif
399
400   mprotect_w_x(start, end, 1);
401 }
402
403 static void *start_block(void)
404 {
405   u_char *end = out + MAX_OUTPUT_BLOCK_SIZE;
406   if (end > ndrc->translation_cache + sizeof(ndrc->translation_cache))
407     end = ndrc->translation_cache + sizeof(ndrc->translation_cache);
408   start_tcache_write(out, end);
409   return out;
410 }
411
412 static void end_block(void *start)
413 {
414   end_tcache_write(start, out);
415 }
416
417 // also takes care of w^x mappings when patching code
418 static u_int needs_clear_cache[1<<(TARGET_SIZE_2-17)];
419
420 static void mark_clear_cache(void *target)
421 {
422   uintptr_t offset = (u_char *)target - ndrc->translation_cache;
423   u_int mask = 1u << ((offset >> 12) & 31);
424   if (!(needs_clear_cache[offset >> 17] & mask)) {
425     char *start = (char *)((uintptr_t)target & ~4095l);
426     start_tcache_write(start, start + 4095);
427     needs_clear_cache[offset >> 17] |= mask;
428   }
429 }
430
431 // Clearing the cache is rather slow on ARM Linux, so mark the areas
432 // that need to be cleared, and then only clear these areas once.
433 static void do_clear_cache(void)
434 {
435   int i, j;
436   for (i = 0; i < (1<<(TARGET_SIZE_2-17)); i++)
437   {
438     u_int bitmap = needs_clear_cache[i];
439     if (!bitmap)
440       continue;
441     for (j = 0; j < 32; j++)
442     {
443       u_char *start, *end;
444       if (!(bitmap & (1<<j)))
445         continue;
446
447       start = ndrc->translation_cache + i*131072 + j*4096;
448       end = start + 4095;
449       for (j++; j < 32; j++) {
450         if (!(bitmap & (1<<j)))
451           break;
452         end += 4096;
453       }
454       end_tcache_write(start, end);
455     }
456     needs_clear_cache[i] = 0;
457   }
458 }
459
460 //#define DEBUG_CYCLE_COUNT 1
461
462 #define NO_CYCLE_PENALTY_THR 12
463
464 int cycle_multiplier; // 100 for 1.0
465 int cycle_multiplier_override;
466 int cycle_multiplier_old;
467
468 static int CLOCK_ADJUST(int x)
469 {
470   int m = cycle_multiplier_override
471         ? cycle_multiplier_override : cycle_multiplier;
472   int s=(x>>31)|1;
473   return (x * m + s * 50) / 100;
474 }
475
476 // is the op an unconditional jump?
477 static int is_ujump(int i)
478 {
479   return itype[i] == UJUMP || itype[i] == RJUMP
480     || (source[i] >> 16) == 0x1000; // beq r0, r0, offset // b offset
481 }
482
483 static int is_jump(int i)
484 {
485   return itype[i] == RJUMP || itype[i] == UJUMP || itype[i] == CJUMP || itype[i] == SJUMP;
486 }
487
488 static u_int get_page(u_int vaddr)
489 {
490   u_int page=vaddr&~0xe0000000;
491   if (page < 0x1000000)
492     page &= ~0x0e00000; // RAM mirrors
493   page>>=12;
494   if(page>2048) page=2048+(page&2047);
495   return page;
496 }
497
498 // no virtual mem in PCSX
499 static u_int get_vpage(u_int vaddr)
500 {
501   return get_page(vaddr);
502 }
503
504 static struct ht_entry *hash_table_get(u_int vaddr)
505 {
506   return &hash_table[((vaddr>>16)^vaddr)&0xFFFF];
507 }
508
509 static void hash_table_add(struct ht_entry *ht_bin, u_int vaddr, void *tcaddr)
510 {
511   ht_bin->vaddr[1] = ht_bin->vaddr[0];
512   ht_bin->tcaddr[1] = ht_bin->tcaddr[0];
513   ht_bin->vaddr[0] = vaddr;
514   ht_bin->tcaddr[0] = tcaddr;
515 }
516
517 // some messy ari64's code, seems to rely on unsigned 32bit overflow
518 static int doesnt_expire_soon(void *tcaddr)
519 {
520   u_int diff = (u_int)((u_char *)tcaddr - out) << (32-TARGET_SIZE_2);
521   return diff > (u_int)(0x60000000 + (MAX_OUTPUT_BLOCK_SIZE << (32-TARGET_SIZE_2)));
522 }
523
524 // Get address from virtual address
525 // This is called from the recompiled JR/JALR instructions
526 void noinline *get_addr(u_int vaddr)
527 {
528   u_int page=get_page(vaddr);
529   u_int vpage=get_vpage(vaddr);
530   struct ll_entry *head;
531   //printf("TRACE: count=%d next=%d (get_addr %x,page %d)\n",Count,next_interupt,vaddr,page);
532   head=jump_in[page];
533   while(head!=NULL) {
534     if(head->vaddr==vaddr) {
535   //printf("TRACE: count=%d next=%d (get_addr match %x: %p)\n",Count,next_interupt,vaddr,head->addr);
536       hash_table_add(hash_table_get(vaddr), vaddr, head->addr);
537       return head->addr;
538     }
539     head=head->next;
540   }
541   head=jump_dirty[vpage];
542   while(head!=NULL) {
543     if(head->vaddr==vaddr) {
544       //printf("TRACE: count=%d next=%d (get_addr match dirty %x: %p)\n",Count,next_interupt,vaddr,head->addr);
545       // Don't restore blocks which are about to expire from the cache
546       if (doesnt_expire_soon(head->addr))
547       if (verify_dirty(head->addr)) {
548         //printf("restore candidate: %x (%d) d=%d\n",vaddr,page,invalid_code[vaddr>>12]);
549         invalid_code[vaddr>>12]=0;
550         inv_code_start=inv_code_end=~0;
551         if(vpage<2048) {
552           restore_candidate[vpage>>3]|=1<<(vpage&7);
553         }
554         else restore_candidate[page>>3]|=1<<(page&7);
555         struct ht_entry *ht_bin = hash_table_get(vaddr);
556         if (ht_bin->vaddr[0] == vaddr)
557           ht_bin->tcaddr[0] = head->addr; // Replace existing entry
558         else
559           hash_table_add(ht_bin, vaddr, head->addr);
560
561         return head->addr;
562       }
563     }
564     head=head->next;
565   }
566   //printf("TRACE: count=%d next=%d (get_addr no-match %x)\n",Count,next_interupt,vaddr);
567   int r=new_recompile_block(vaddr);
568   if(r==0) return get_addr(vaddr);
569   // Execute in unmapped page, generate pagefault execption
570   Status|=2;
571   Cause=(vaddr<<31)|0x8;
572   EPC=(vaddr&1)?vaddr-5:vaddr;
573   BadVAddr=(vaddr&~1);
574   Context=(Context&0xFF80000F)|((BadVAddr>>9)&0x007FFFF0);
575   EntryHi=BadVAddr&0xFFFFE000;
576   return get_addr_ht(0x80000000);
577 }
578 // Look up address in hash table first
579 void *get_addr_ht(u_int vaddr)
580 {
581   //printf("TRACE: count=%d next=%d (get_addr_ht %x)\n",Count,next_interupt,vaddr);
582   const struct ht_entry *ht_bin = hash_table_get(vaddr);
583   if (ht_bin->vaddr[0] == vaddr) return ht_bin->tcaddr[0];
584   if (ht_bin->vaddr[1] == vaddr) return ht_bin->tcaddr[1];
585   return get_addr(vaddr);
586 }
587
588 void clear_all_regs(signed char regmap[])
589 {
590   int hr;
591   for (hr=0;hr<HOST_REGS;hr++) regmap[hr]=-1;
592 }
593
594 static signed char get_reg(const signed char regmap[],int r)
595 {
596   int hr;
597   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap[hr]==r) return hr;
598   return -1;
599 }
600
601 // Find a register that is available for two consecutive cycles
602 static signed char get_reg2(signed char regmap1[], const signed char regmap2[], int r)
603 {
604   int hr;
605   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap1[hr]==r&&regmap2[hr]==r) return hr;
606   return -1;
607 }
608
609 int count_free_regs(signed char regmap[])
610 {
611   int count=0;
612   int hr;
613   for(hr=0;hr<HOST_REGS;hr++)
614   {
615     if(hr!=EXCLUDE_REG) {
616       if(regmap[hr]<0) count++;
617     }
618   }
619   return count;
620 }
621
622 void dirty_reg(struct regstat *cur,signed char reg)
623 {
624   int hr;
625   if(!reg) return;
626   for (hr=0;hr<HOST_REGS;hr++) {
627     if((cur->regmap[hr]&63)==reg) {
628       cur->dirty|=1<<hr;
629     }
630   }
631 }
632
633 static void set_const(struct regstat *cur, signed char reg, uint32_t value)
634 {
635   int hr;
636   if(!reg) return;
637   for (hr=0;hr<HOST_REGS;hr++) {
638     if(cur->regmap[hr]==reg) {
639       cur->isconst|=1<<hr;
640       current_constmap[hr]=value;
641     }
642   }
643 }
644
645 static void clear_const(struct regstat *cur, signed char reg)
646 {
647   int hr;
648   if(!reg) return;
649   for (hr=0;hr<HOST_REGS;hr++) {
650     if((cur->regmap[hr]&63)==reg) {
651       cur->isconst&=~(1<<hr);
652     }
653   }
654 }
655
656 static int is_const(struct regstat *cur, signed char reg)
657 {
658   int hr;
659   if(reg<0) return 0;
660   if(!reg) return 1;
661   for (hr=0;hr<HOST_REGS;hr++) {
662     if((cur->regmap[hr]&63)==reg) {
663       return (cur->isconst>>hr)&1;
664     }
665   }
666   return 0;
667 }
668
669 static uint32_t get_const(struct regstat *cur, signed char reg)
670 {
671   int hr;
672   if(!reg) return 0;
673   for (hr=0;hr<HOST_REGS;hr++) {
674     if(cur->regmap[hr]==reg) {
675       return current_constmap[hr];
676     }
677   }
678   SysPrintf("Unknown constant in r%d\n",reg);
679   abort();
680 }
681
682 // Least soon needed registers
683 // Look at the next ten instructions and see which registers
684 // will be used.  Try not to reallocate these.
685 void lsn(u_char hsn[], int i, int *preferred_reg)
686 {
687   int j;
688   int b=-1;
689   for(j=0;j<9;j++)
690   {
691     if(i+j>=slen) {
692       j=slen-i-1;
693       break;
694     }
695     if (is_ujump(i+j))
696     {
697       // Don't go past an unconditonal jump
698       j++;
699       break;
700     }
701   }
702   for(;j>=0;j--)
703   {
704     if(rs1[i+j]) hsn[rs1[i+j]]=j;
705     if(rs2[i+j]) hsn[rs2[i+j]]=j;
706     if(rt1[i+j]) hsn[rt1[i+j]]=j;
707     if(rt2[i+j]) hsn[rt2[i+j]]=j;
708     if(itype[i+j]==STORE || itype[i+j]==STORELR) {
709       // Stores can allocate zero
710       hsn[rs1[i+j]]=j;
711       hsn[rs2[i+j]]=j;
712     }
713     // On some architectures stores need invc_ptr
714     #if defined(HOST_IMM8)
715     if(itype[i+j]==STORE || itype[i+j]==STORELR || (opcode[i+j]&0x3b)==0x39 || (opcode[i+j]&0x3b)==0x3a) {
716       hsn[INVCP]=j;
717     }
718     #endif
719     if(i+j>=0&&(itype[i+j]==UJUMP||itype[i+j]==CJUMP||itype[i+j]==SJUMP))
720     {
721       hsn[CCREG]=j;
722       b=j;
723     }
724   }
725   if(b>=0)
726   {
727     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
728     {
729       // Follow first branch
730       int t=(ba[i+b]-start)>>2;
731       j=7-b;if(t+j>=slen) j=slen-t-1;
732       for(;j>=0;j--)
733       {
734         if(rs1[t+j]) if(hsn[rs1[t+j]]>j+b+2) hsn[rs1[t+j]]=j+b+2;
735         if(rs2[t+j]) if(hsn[rs2[t+j]]>j+b+2) hsn[rs2[t+j]]=j+b+2;
736         //if(rt1[t+j]) if(hsn[rt1[t+j]]>j+b+2) hsn[rt1[t+j]]=j+b+2;
737         //if(rt2[t+j]) if(hsn[rt2[t+j]]>j+b+2) hsn[rt2[t+j]]=j+b+2;
738       }
739     }
740     // TODO: preferred register based on backward branch
741   }
742   // Delay slot should preferably not overwrite branch conditions or cycle count
743   if (i > 0 && is_jump(i-1)) {
744     if(rs1[i-1]) if(hsn[rs1[i-1]]>1) hsn[rs1[i-1]]=1;
745     if(rs2[i-1]) if(hsn[rs2[i-1]]>1) hsn[rs2[i-1]]=1;
746     hsn[CCREG]=1;
747     // ...or hash tables
748     hsn[RHASH]=1;
749     hsn[RHTBL]=1;
750   }
751   // Coprocessor load/store needs FTEMP, even if not declared
752   if(itype[i]==C1LS||itype[i]==C2LS) {
753     hsn[FTEMP]=0;
754   }
755   // Load L/R also uses FTEMP as a temporary register
756   if(itype[i]==LOADLR) {
757     hsn[FTEMP]=0;
758   }
759   // Also SWL/SWR/SDL/SDR
760   if(opcode[i]==0x2a||opcode[i]==0x2e||opcode[i]==0x2c||opcode[i]==0x2d) {
761     hsn[FTEMP]=0;
762   }
763   // Don't remove the miniht registers
764   if(itype[i]==UJUMP||itype[i]==RJUMP)
765   {
766     hsn[RHASH]=0;
767     hsn[RHTBL]=0;
768   }
769 }
770
771 // We only want to allocate registers if we're going to use them again soon
772 int needed_again(int r, int i)
773 {
774   int j;
775   int b=-1;
776   int rn=10;
777
778   if (i > 0 && is_ujump(i-1))
779   {
780     if(ba[i-1]<start || ba[i-1]>start+slen*4-4)
781       return 0; // Don't need any registers if exiting the block
782   }
783   for(j=0;j<9;j++)
784   {
785     if(i+j>=slen) {
786       j=slen-i-1;
787       break;
788     }
789     if (is_ujump(i+j))
790     {
791       // Don't go past an unconditonal jump
792       j++;
793       break;
794     }
795     if(itype[i+j]==SYSCALL||itype[i+j]==HLECALL||itype[i+j]==INTCALL||((source[i+j]&0xfc00003f)==0x0d))
796     {
797       break;
798     }
799   }
800   for(;j>=1;j--)
801   {
802     if(rs1[i+j]==r) rn=j;
803     if(rs2[i+j]==r) rn=j;
804     if((unneeded_reg[i+j]>>r)&1) rn=10;
805     if(i+j>=0&&(itype[i+j]==UJUMP||itype[i+j]==CJUMP||itype[i+j]==SJUMP))
806     {
807       b=j;
808     }
809   }
810   /*
811   if(b>=0)
812   {
813     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
814     {
815       // Follow first branch
816       int o=rn;
817       int t=(ba[i+b]-start)>>2;
818       j=7-b;if(t+j>=slen) j=slen-t-1;
819       for(;j>=0;j--)
820       {
821         if(!((unneeded_reg[t+j]>>r)&1)) {
822           if(rs1[t+j]==r) if(rn>j+b+2) rn=j+b+2;
823           if(rs2[t+j]==r) if(rn>j+b+2) rn=j+b+2;
824         }
825         else rn=o;
826       }
827     }
828   }*/
829   if(rn<10) return 1;
830   (void)b;
831   return 0;
832 }
833
834 // Try to match register allocations at the end of a loop with those
835 // at the beginning
836 int loop_reg(int i, int r, int hr)
837 {
838   int j,k;
839   for(j=0;j<9;j++)
840   {
841     if(i+j>=slen) {
842       j=slen-i-1;
843       break;
844     }
845     if (is_ujump(i+j))
846     {
847       // Don't go past an unconditonal jump
848       j++;
849       break;
850     }
851   }
852   k=0;
853   if(i>0){
854     if(itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP)
855       k--;
856   }
857   for(;k<j;k++)
858   {
859     assert(r < 64);
860     if((unneeded_reg[i+k]>>r)&1) return hr;
861     if(i+k>=0&&(itype[i+k]==UJUMP||itype[i+k]==CJUMP||itype[i+k]==SJUMP))
862     {
863       if(ba[i+k]>=start && ba[i+k]<(start+i*4))
864       {
865         int t=(ba[i+k]-start)>>2;
866         int reg=get_reg(regs[t].regmap_entry,r);
867         if(reg>=0) return reg;
868         //reg=get_reg(regs[t+1].regmap_entry,r);
869         //if(reg>=0) return reg;
870       }
871     }
872   }
873   return hr;
874 }
875
876
877 // Allocate every register, preserving source/target regs
878 void alloc_all(struct regstat *cur,int i)
879 {
880   int hr;
881
882   for(hr=0;hr<HOST_REGS;hr++) {
883     if(hr!=EXCLUDE_REG) {
884       if(((cur->regmap[hr]&63)!=rs1[i])&&((cur->regmap[hr]&63)!=rs2[i])&&
885          ((cur->regmap[hr]&63)!=rt1[i])&&((cur->regmap[hr]&63)!=rt2[i]))
886       {
887         cur->regmap[hr]=-1;
888         cur->dirty&=~(1<<hr);
889       }
890       // Don't need zeros
891       if((cur->regmap[hr]&63)==0)
892       {
893         cur->regmap[hr]=-1;
894         cur->dirty&=~(1<<hr);
895       }
896     }
897   }
898 }
899
900 #ifndef NDEBUG
901 static int host_tempreg_in_use;
902
903 static void host_tempreg_acquire(void)
904 {
905   assert(!host_tempreg_in_use);
906   host_tempreg_in_use = 1;
907 }
908
909 static void host_tempreg_release(void)
910 {
911   host_tempreg_in_use = 0;
912 }
913 #else
914 static void host_tempreg_acquire(void) {}
915 static void host_tempreg_release(void) {}
916 #endif
917
918 #ifdef ASSEM_PRINT
919 extern void gen_interupt();
920 extern void do_insn_cmp();
921 #define FUNCNAME(f) { f, " " #f }
922 static const struct {
923   void *addr;
924   const char *name;
925 } function_names[] = {
926   FUNCNAME(cc_interrupt),
927   FUNCNAME(gen_interupt),
928   FUNCNAME(get_addr_ht),
929   FUNCNAME(get_addr),
930   FUNCNAME(jump_handler_read8),
931   FUNCNAME(jump_handler_read16),
932   FUNCNAME(jump_handler_read32),
933   FUNCNAME(jump_handler_write8),
934   FUNCNAME(jump_handler_write16),
935   FUNCNAME(jump_handler_write32),
936   FUNCNAME(invalidate_addr),
937   FUNCNAME(jump_to_new_pc),
938   FUNCNAME(call_gteStall),
939   FUNCNAME(new_dyna_leave),
940   FUNCNAME(pcsx_mtc0),
941   FUNCNAME(pcsx_mtc0_ds),
942 #ifdef DRC_DBG
943   FUNCNAME(do_insn_cmp),
944 #endif
945 #ifdef __arm__
946   FUNCNAME(verify_code),
947 #endif
948 };
949
950 static const char *func_name(const void *a)
951 {
952   int i;
953   for (i = 0; i < sizeof(function_names)/sizeof(function_names[0]); i++)
954     if (function_names[i].addr == a)
955       return function_names[i].name;
956   return "";
957 }
958 #else
959 #define func_name(x) ""
960 #endif
961
962 #ifdef __i386__
963 #include "assem_x86.c"
964 #endif
965 #ifdef __x86_64__
966 #include "assem_x64.c"
967 #endif
968 #ifdef __arm__
969 #include "assem_arm.c"
970 #endif
971 #ifdef __aarch64__
972 #include "assem_arm64.c"
973 #endif
974
975 static void *get_trampoline(const void *f)
976 {
977   size_t i;
978
979   for (i = 0; i < ARRAY_SIZE(ndrc->tramp.f); i++) {
980     if (ndrc->tramp.f[i] == f || ndrc->tramp.f[i] == NULL)
981       break;
982   }
983   if (i == ARRAY_SIZE(ndrc->tramp.f)) {
984     SysPrintf("trampoline table is full, last func %p\n", f);
985     abort();
986   }
987   if (ndrc->tramp.f[i] == NULL) {
988     start_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
989     ndrc->tramp.f[i] = f;
990     end_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
991   }
992   return &ndrc->tramp.ops[i];
993 }
994
995 static void emit_far_jump(const void *f)
996 {
997   if (can_jump_or_call(f)) {
998     emit_jmp(f);
999     return;
1000   }
1001
1002   f = get_trampoline(f);
1003   emit_jmp(f);
1004 }
1005
1006 static void emit_far_call(const void *f)
1007 {
1008   if (can_jump_or_call(f)) {
1009     emit_call(f);
1010     return;
1011   }
1012
1013   f = get_trampoline(f);
1014   emit_call(f);
1015 }
1016
1017 // Add virtual address mapping to linked list
1018 void ll_add(struct ll_entry **head,int vaddr,void *addr)
1019 {
1020   struct ll_entry *new_entry;
1021   new_entry=malloc(sizeof(struct ll_entry));
1022   assert(new_entry!=NULL);
1023   new_entry->vaddr=vaddr;
1024   new_entry->reg_sv_flags=0;
1025   new_entry->addr=addr;
1026   new_entry->next=*head;
1027   *head=new_entry;
1028 }
1029
1030 void ll_add_flags(struct ll_entry **head,int vaddr,u_int reg_sv_flags,void *addr)
1031 {
1032   ll_add(head,vaddr,addr);
1033   (*head)->reg_sv_flags=reg_sv_flags;
1034 }
1035
1036 // Check if an address is already compiled
1037 // but don't return addresses which are about to expire from the cache
1038 void *check_addr(u_int vaddr)
1039 {
1040   struct ht_entry *ht_bin = hash_table_get(vaddr);
1041   size_t i;
1042   for (i = 0; i < ARRAY_SIZE(ht_bin->vaddr); i++) {
1043     if (ht_bin->vaddr[i] == vaddr)
1044       if (doesnt_expire_soon((u_char *)ht_bin->tcaddr[i] - MAX_OUTPUT_BLOCK_SIZE))
1045         if (isclean(ht_bin->tcaddr[i]))
1046           return ht_bin->tcaddr[i];
1047   }
1048   u_int page=get_page(vaddr);
1049   struct ll_entry *head;
1050   head=jump_in[page];
1051   while (head != NULL) {
1052     if (head->vaddr == vaddr) {
1053       if (doesnt_expire_soon(head->addr)) {
1054         // Update existing entry with current address
1055         if (ht_bin->vaddr[0] == vaddr) {
1056           ht_bin->tcaddr[0] = head->addr;
1057           return head->addr;
1058         }
1059         if (ht_bin->vaddr[1] == vaddr) {
1060           ht_bin->tcaddr[1] = head->addr;
1061           return head->addr;
1062         }
1063         // Insert into hash table with low priority.
1064         // Don't evict existing entries, as they are probably
1065         // addresses that are being accessed frequently.
1066         if (ht_bin->vaddr[0] == -1) {
1067           ht_bin->vaddr[0] = vaddr;
1068           ht_bin->tcaddr[0] = head->addr;
1069         }
1070         else if (ht_bin->vaddr[1] == -1) {
1071           ht_bin->vaddr[1] = vaddr;
1072           ht_bin->tcaddr[1] = head->addr;
1073         }
1074         return head->addr;
1075       }
1076     }
1077     head=head->next;
1078   }
1079   return 0;
1080 }
1081
1082 void remove_hash(int vaddr)
1083 {
1084   //printf("remove hash: %x\n",vaddr);
1085   struct ht_entry *ht_bin = hash_table_get(vaddr);
1086   if (ht_bin->vaddr[1] == vaddr) {
1087     ht_bin->vaddr[1] = -1;
1088     ht_bin->tcaddr[1] = NULL;
1089   }
1090   if (ht_bin->vaddr[0] == vaddr) {
1091     ht_bin->vaddr[0] = ht_bin->vaddr[1];
1092     ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
1093     ht_bin->vaddr[1] = -1;
1094     ht_bin->tcaddr[1] = NULL;
1095   }
1096 }
1097
1098 static void ll_remove_matching_addrs(struct ll_entry **head,
1099   uintptr_t base_offs_s, int shift)
1100 {
1101   struct ll_entry *next;
1102   while(*head) {
1103     uintptr_t o1 = (u_char *)(*head)->addr - ndrc->translation_cache;
1104     uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
1105     if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s)
1106     {
1107       inv_debug("EXP: Remove pointer to %p (%x)\n",(*head)->addr,(*head)->vaddr);
1108       remove_hash((*head)->vaddr);
1109       next=(*head)->next;
1110       free(*head);
1111       *head=next;
1112     }
1113     else
1114     {
1115       head=&((*head)->next);
1116     }
1117   }
1118 }
1119
1120 // Remove all entries from linked list
1121 void ll_clear(struct ll_entry **head)
1122 {
1123   struct ll_entry *cur;
1124   struct ll_entry *next;
1125   if((cur=*head)) {
1126     *head=0;
1127     while(cur) {
1128       next=cur->next;
1129       free(cur);
1130       cur=next;
1131     }
1132   }
1133 }
1134
1135 // Dereference the pointers and remove if it matches
1136 static void ll_kill_pointers(struct ll_entry *head,
1137   uintptr_t base_offs_s, int shift)
1138 {
1139   while(head) {
1140     u_char *ptr = get_pointer(head->addr);
1141     uintptr_t o1 = ptr - ndrc->translation_cache;
1142     uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
1143     inv_debug("EXP: Lookup pointer to %p at %p (%x)\n",ptr,head->addr,head->vaddr);
1144     if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s)
1145     {
1146       inv_debug("EXP: Kill pointer at %p (%x)\n",head->addr,head->vaddr);
1147       void *host_addr=find_extjump_insn(head->addr);
1148       mark_clear_cache(host_addr);
1149       set_jump_target(host_addr, head->addr);
1150     }
1151     head=head->next;
1152   }
1153 }
1154
1155 // This is called when we write to a compiled block (see do_invstub)
1156 static void invalidate_page(u_int page)
1157 {
1158   struct ll_entry *head;
1159   struct ll_entry *next;
1160   head=jump_in[page];
1161   jump_in[page]=0;
1162   while(head!=NULL) {
1163     inv_debug("INVALIDATE: %x\n",head->vaddr);
1164     remove_hash(head->vaddr);
1165     next=head->next;
1166     free(head);
1167     head=next;
1168   }
1169   head=jump_out[page];
1170   jump_out[page]=0;
1171   while(head!=NULL) {
1172     inv_debug("INVALIDATE: kill pointer to %x (%p)\n",head->vaddr,head->addr);
1173     void *host_addr=find_extjump_insn(head->addr);
1174     mark_clear_cache(host_addr);
1175     set_jump_target(host_addr, head->addr); // point back to dyna_linker
1176     next=head->next;
1177     free(head);
1178     head=next;
1179   }
1180 }
1181
1182 static void invalidate_block_range(u_int block, u_int first, u_int last)
1183 {
1184   u_int page=get_page(block<<12);
1185   //printf("first=%d last=%d\n",first,last);
1186   invalidate_page(page);
1187   assert(first+5>page); // NB: this assumes MAXBLOCK<=4096 (4 pages)
1188   assert(last<page+5);
1189   // Invalidate the adjacent pages if a block crosses a 4K boundary
1190   while(first<page) {
1191     invalidate_page(first);
1192     first++;
1193   }
1194   for(first=page+1;first<last;first++) {
1195     invalidate_page(first);
1196   }
1197   do_clear_cache();
1198
1199   // Don't trap writes
1200   invalid_code[block]=1;
1201
1202   #ifdef USE_MINI_HT
1203   memset(mini_ht,-1,sizeof(mini_ht));
1204   #endif
1205 }
1206
1207 void invalidate_block(u_int block)
1208 {
1209   u_int page=get_page(block<<12);
1210   u_int vpage=get_vpage(block<<12);
1211   inv_debug("INVALIDATE: %x (%d)\n",block<<12,page);
1212   //inv_debug("invalid_code[block]=%d\n",invalid_code[block]);
1213   u_int first,last;
1214   first=last=page;
1215   struct ll_entry *head;
1216   head=jump_dirty[vpage];
1217   //printf("page=%d vpage=%d\n",page,vpage);
1218   while(head!=NULL) {
1219     if(vpage>2047||(head->vaddr>>12)==block) { // Ignore vaddr hash collision
1220       u_char *start, *end;
1221       get_bounds(head->addr, &start, &end);
1222       //printf("start: %p end: %p\n", start, end);
1223       if (page < 2048 && start >= rdram && end < rdram+RAM_SIZE) {
1224         if (((start-rdram)>>12) <= page && ((end-1-rdram)>>12) >= page) {
1225           if ((((start-rdram)>>12)&2047) < first) first = ((start-rdram)>>12)&2047;
1226           if ((((end-1-rdram)>>12)&2047) > last)  last = ((end-1-rdram)>>12)&2047;
1227         }
1228       }
1229     }
1230     head=head->next;
1231   }
1232   invalidate_block_range(block,first,last);
1233 }
1234
1235 void invalidate_addr(u_int addr)
1236 {
1237   //static int rhits;
1238   // this check is done by the caller
1239   //if (inv_code_start<=addr&&addr<=inv_code_end) { rhits++; return; }
1240   u_int page=get_vpage(addr);
1241   if(page<2048) { // RAM
1242     struct ll_entry *head;
1243     u_int addr_min=~0, addr_max=0;
1244     u_int mask=RAM_SIZE-1;
1245     u_int addr_main=0x80000000|(addr&mask);
1246     int pg1;
1247     inv_code_start=addr_main&~0xfff;
1248     inv_code_end=addr_main|0xfff;
1249     pg1=page;
1250     if (pg1>0) {
1251       // must check previous page too because of spans..
1252       pg1--;
1253       inv_code_start-=0x1000;
1254     }
1255     for(;pg1<=page;pg1++) {
1256       for(head=jump_dirty[pg1];head!=NULL;head=head->next) {
1257         u_char *start_h, *end_h;
1258         u_int start, end;
1259         get_bounds(head->addr, &start_h, &end_h);
1260         start = (uintptr_t)start_h - ram_offset;
1261         end = (uintptr_t)end_h - ram_offset;
1262         if(start<=addr_main&&addr_main<end) {
1263           if(start<addr_min) addr_min=start;
1264           if(end>addr_max) addr_max=end;
1265         }
1266         else if(addr_main<start) {
1267           if(start<inv_code_end)
1268             inv_code_end=start-1;
1269         }
1270         else {
1271           if(end>inv_code_start)
1272             inv_code_start=end;
1273         }
1274       }
1275     }
1276     if (addr_min!=~0) {
1277       inv_debug("INV ADDR: %08x hit %08x-%08x\n", addr, addr_min, addr_max);
1278       inv_code_start=inv_code_end=~0;
1279       invalidate_block_range(addr>>12,(addr_min&mask)>>12,(addr_max&mask)>>12);
1280       return;
1281     }
1282     else {
1283       inv_code_start=(addr&~mask)|(inv_code_start&mask);
1284       inv_code_end=(addr&~mask)|(inv_code_end&mask);
1285       inv_debug("INV ADDR: %08x miss, inv %08x-%08x, sk %d\n", addr, inv_code_start, inv_code_end, 0);
1286       return;
1287     }
1288   }
1289   invalidate_block(addr>>12);
1290 }
1291
1292 // This is called when loading a save state.
1293 // Anything could have changed, so invalidate everything.
1294 void invalidate_all_pages(void)
1295 {
1296   u_int page;
1297   for(page=0;page<4096;page++)
1298     invalidate_page(page);
1299   for(page=0;page<1048576;page++)
1300     if(!invalid_code[page]) {
1301       restore_candidate[(page&2047)>>3]|=1<<(page&7);
1302       restore_candidate[((page&2047)>>3)+256]|=1<<(page&7);
1303     }
1304   #ifdef USE_MINI_HT
1305   memset(mini_ht,-1,sizeof(mini_ht));
1306   #endif
1307   do_clear_cache();
1308 }
1309
1310 static void do_invstub(int n)
1311 {
1312   literal_pool(20);
1313   u_int reglist=stubs[n].a;
1314   set_jump_target(stubs[n].addr, out);
1315   save_regs(reglist);
1316   if(stubs[n].b!=0) emit_mov(stubs[n].b,0);
1317   emit_far_call(invalidate_addr);
1318   restore_regs(reglist);
1319   emit_jmp(stubs[n].retaddr); // return address
1320 }
1321
1322 // Add an entry to jump_out after making a link
1323 // src should point to code by emit_extjump2()
1324 void add_jump_out(u_int vaddr,void *src)
1325 {
1326   u_int page=get_page(vaddr);
1327   inv_debug("add_jump_out: %p -> %x (%d)\n",src,vaddr,page);
1328   check_extjump2(src);
1329   ll_add(jump_out+page,vaddr,src);
1330   //inv_debug("add_jump_out:  to %p\n",get_pointer(src));
1331 }
1332
1333 // If a code block was found to be unmodified (bit was set in
1334 // restore_candidate) and it remains unmodified (bit is clear
1335 // in invalid_code) then move the entries for that 4K page from
1336 // the dirty list to the clean list.
1337 void clean_blocks(u_int page)
1338 {
1339   struct ll_entry *head;
1340   inv_debug("INV: clean_blocks page=%d\n",page);
1341   head=jump_dirty[page];
1342   while(head!=NULL) {
1343     if(!invalid_code[head->vaddr>>12]) {
1344       // Don't restore blocks which are about to expire from the cache
1345       if (doesnt_expire_soon(head->addr)) {
1346         if(verify_dirty(head->addr)) {
1347           u_char *start, *end;
1348           //printf("Possibly Restore %x (%p)\n",head->vaddr, head->addr);
1349           u_int i;
1350           u_int inv=0;
1351           get_bounds(head->addr, &start, &end);
1352           if (start - rdram < RAM_SIZE) {
1353             for (i = (start-rdram+0x80000000)>>12; i <= (end-1-rdram+0x80000000)>>12; i++) {
1354               inv|=invalid_code[i];
1355             }
1356           }
1357           else if((signed int)head->vaddr>=(signed int)0x80000000+RAM_SIZE) {
1358             inv=1;
1359           }
1360           if(!inv) {
1361             void *clean_addr = get_clean_addr(head->addr);
1362             if (doesnt_expire_soon(clean_addr)) {
1363               u_int ppage=page;
1364               inv_debug("INV: Restored %x (%p/%p)\n",head->vaddr, head->addr, clean_addr);
1365               //printf("page=%x, addr=%x\n",page,head->vaddr);
1366               //assert(head->vaddr>>12==(page|0x80000));
1367               ll_add_flags(jump_in+ppage,head->vaddr,head->reg_sv_flags,clean_addr);
1368               struct ht_entry *ht_bin = hash_table_get(head->vaddr);
1369               if (ht_bin->vaddr[0] == head->vaddr)
1370                 ht_bin->tcaddr[0] = clean_addr; // Replace existing entry
1371               if (ht_bin->vaddr[1] == head->vaddr)
1372                 ht_bin->tcaddr[1] = clean_addr; // Replace existing entry
1373             }
1374           }
1375         }
1376       }
1377     }
1378     head=head->next;
1379   }
1380 }
1381
1382 /* Register allocation */
1383
1384 // Note: registers are allocated clean (unmodified state)
1385 // if you intend to modify the register, you must call dirty_reg().
1386 static void alloc_reg(struct regstat *cur,int i,signed char reg)
1387 {
1388   int r,hr;
1389   int preferred_reg = (reg&7);
1390   if(reg==CCREG) preferred_reg=HOST_CCREG;
1391   if(reg==PTEMP||reg==FTEMP) preferred_reg=12;
1392
1393   // Don't allocate unused registers
1394   if((cur->u>>reg)&1) return;
1395
1396   // see if it's already allocated
1397   for(hr=0;hr<HOST_REGS;hr++)
1398   {
1399     if(cur->regmap[hr]==reg) return;
1400   }
1401
1402   // Keep the same mapping if the register was already allocated in a loop
1403   preferred_reg = loop_reg(i,reg,preferred_reg);
1404
1405   // Try to allocate the preferred register
1406   if(cur->regmap[preferred_reg]==-1) {
1407     cur->regmap[preferred_reg]=reg;
1408     cur->dirty&=~(1<<preferred_reg);
1409     cur->isconst&=~(1<<preferred_reg);
1410     return;
1411   }
1412   r=cur->regmap[preferred_reg];
1413   assert(r < 64);
1414   if((cur->u>>r)&1) {
1415     cur->regmap[preferred_reg]=reg;
1416     cur->dirty&=~(1<<preferred_reg);
1417     cur->isconst&=~(1<<preferred_reg);
1418     return;
1419   }
1420
1421   // Clear any unneeded registers
1422   // We try to keep the mapping consistent, if possible, because it
1423   // makes branches easier (especially loops).  So we try to allocate
1424   // first (see above) before removing old mappings.  If this is not
1425   // possible then go ahead and clear out the registers that are no
1426   // longer needed.
1427   for(hr=0;hr<HOST_REGS;hr++)
1428   {
1429     r=cur->regmap[hr];
1430     if(r>=0) {
1431       assert(r < 64);
1432       if((cur->u>>r)&1) {cur->regmap[hr]=-1;break;}
1433     }
1434   }
1435   // Try to allocate any available register, but prefer
1436   // registers that have not been used recently.
1437   if(i>0) {
1438     for(hr=0;hr<HOST_REGS;hr++) {
1439       if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1440         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]) {
1441           cur->regmap[hr]=reg;
1442           cur->dirty&=~(1<<hr);
1443           cur->isconst&=~(1<<hr);
1444           return;
1445         }
1446       }
1447     }
1448   }
1449   // Try to allocate any available register
1450   for(hr=0;hr<HOST_REGS;hr++) {
1451     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1452       cur->regmap[hr]=reg;
1453       cur->dirty&=~(1<<hr);
1454       cur->isconst&=~(1<<hr);
1455       return;
1456     }
1457   }
1458
1459   // Ok, now we have to evict someone
1460   // Pick a register we hopefully won't need soon
1461   u_char hsn[MAXREG+1];
1462   memset(hsn,10,sizeof(hsn));
1463   int j;
1464   lsn(hsn,i,&preferred_reg);
1465   //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]);
1466   //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]);
1467   if(i>0) {
1468     // Don't evict the cycle count at entry points, otherwise the entry
1469     // stub will have to write it.
1470     if(bt[i]&&hsn[CCREG]>2) hsn[CCREG]=2;
1471     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;
1472     for(j=10;j>=3;j--)
1473     {
1474       // Alloc preferred register if available
1475       if(hsn[r=cur->regmap[preferred_reg]&63]==j) {
1476         for(hr=0;hr<HOST_REGS;hr++) {
1477           // Evict both parts of a 64-bit register
1478           if((cur->regmap[hr]&63)==r) {
1479             cur->regmap[hr]=-1;
1480             cur->dirty&=~(1<<hr);
1481             cur->isconst&=~(1<<hr);
1482           }
1483         }
1484         cur->regmap[preferred_reg]=reg;
1485         return;
1486       }
1487       for(r=1;r<=MAXREG;r++)
1488       {
1489         if(hsn[r]==j&&r!=rs1[i-1]&&r!=rs2[i-1]&&r!=rt1[i-1]&&r!=rt2[i-1]) {
1490           for(hr=0;hr<HOST_REGS;hr++) {
1491             if(hr!=HOST_CCREG||j<hsn[CCREG]) {
1492               if(cur->regmap[hr]==r) {
1493                 cur->regmap[hr]=reg;
1494                 cur->dirty&=~(1<<hr);
1495                 cur->isconst&=~(1<<hr);
1496                 return;
1497               }
1498             }
1499           }
1500         }
1501       }
1502     }
1503   }
1504   for(j=10;j>=0;j--)
1505   {
1506     for(r=1;r<=MAXREG;r++)
1507     {
1508       if(hsn[r]==j) {
1509         for(hr=0;hr<HOST_REGS;hr++) {
1510           if(cur->regmap[hr]==r) {
1511             cur->regmap[hr]=reg;
1512             cur->dirty&=~(1<<hr);
1513             cur->isconst&=~(1<<hr);
1514             return;
1515           }
1516         }
1517       }
1518     }
1519   }
1520   SysPrintf("This shouldn't happen (alloc_reg)");abort();
1521 }
1522
1523 // Allocate a temporary register.  This is done without regard to
1524 // dirty status or whether the register we request is on the unneeded list
1525 // Note: This will only allocate one register, even if called multiple times
1526 static void alloc_reg_temp(struct regstat *cur,int i,signed char reg)
1527 {
1528   int r,hr;
1529   int preferred_reg = -1;
1530
1531   // see if it's already allocated
1532   for(hr=0;hr<HOST_REGS;hr++)
1533   {
1534     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==reg) return;
1535   }
1536
1537   // Try to allocate any available register
1538   for(hr=HOST_REGS-1;hr>=0;hr--) {
1539     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1540       cur->regmap[hr]=reg;
1541       cur->dirty&=~(1<<hr);
1542       cur->isconst&=~(1<<hr);
1543       return;
1544     }
1545   }
1546
1547   // Find an unneeded register
1548   for(hr=HOST_REGS-1;hr>=0;hr--)
1549   {
1550     r=cur->regmap[hr];
1551     if(r>=0) {
1552       assert(r < 64);
1553       if((cur->u>>r)&1) {
1554         if(i==0||((unneeded_reg[i-1]>>r)&1)) {
1555           cur->regmap[hr]=reg;
1556           cur->dirty&=~(1<<hr);
1557           cur->isconst&=~(1<<hr);
1558           return;
1559         }
1560       }
1561     }
1562   }
1563
1564   // Ok, now we have to evict someone
1565   // Pick a register we hopefully won't need soon
1566   // TODO: we might want to follow unconditional jumps here
1567   // TODO: get rid of dupe code and make this into a function
1568   u_char hsn[MAXREG+1];
1569   memset(hsn,10,sizeof(hsn));
1570   int j;
1571   lsn(hsn,i,&preferred_reg);
1572   //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]);
1573   if(i>0) {
1574     // Don't evict the cycle count at entry points, otherwise the entry
1575     // stub will have to write it.
1576     if(bt[i]&&hsn[CCREG]>2) hsn[CCREG]=2;
1577     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;
1578     for(j=10;j>=3;j--)
1579     {
1580       for(r=1;r<=MAXREG;r++)
1581       {
1582         if(hsn[r]==j&&r!=rs1[i-1]&&r!=rs2[i-1]&&r!=rt1[i-1]&&r!=rt2[i-1]) {
1583           for(hr=0;hr<HOST_REGS;hr++) {
1584             if(hr!=HOST_CCREG||hsn[CCREG]>2) {
1585               if(cur->regmap[hr]==r) {
1586                 cur->regmap[hr]=reg;
1587                 cur->dirty&=~(1<<hr);
1588                 cur->isconst&=~(1<<hr);
1589                 return;
1590               }
1591             }
1592           }
1593         }
1594       }
1595     }
1596   }
1597   for(j=10;j>=0;j--)
1598   {
1599     for(r=1;r<=MAXREG;r++)
1600     {
1601       if(hsn[r]==j) {
1602         for(hr=0;hr<HOST_REGS;hr++) {
1603           if(cur->regmap[hr]==r) {
1604             cur->regmap[hr]=reg;
1605             cur->dirty&=~(1<<hr);
1606             cur->isconst&=~(1<<hr);
1607             return;
1608           }
1609         }
1610       }
1611     }
1612   }
1613   SysPrintf("This shouldn't happen");abort();
1614 }
1615
1616 static void mov_alloc(struct regstat *current,int i)
1617 {
1618   if (rs1[i] == HIREG || rs1[i] == LOREG) {
1619     // logically this is needed but just won't work, no idea why
1620     //alloc_cc(current,i); // for stalls
1621     //dirty_reg(current,CCREG);
1622   }
1623
1624   // Note: Don't need to actually alloc the source registers
1625   //alloc_reg(current,i,rs1[i]);
1626   alloc_reg(current,i,rt1[i]);
1627
1628   clear_const(current,rs1[i]);
1629   clear_const(current,rt1[i]);
1630   dirty_reg(current,rt1[i]);
1631 }
1632
1633 static void shiftimm_alloc(struct regstat *current,int i)
1634 {
1635   if(opcode2[i]<=0x3) // SLL/SRL/SRA
1636   {
1637     if(rt1[i]) {
1638       if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1639       else lt1[i]=rs1[i];
1640       alloc_reg(current,i,rt1[i]);
1641       dirty_reg(current,rt1[i]);
1642       if(is_const(current,rs1[i])) {
1643         int v=get_const(current,rs1[i]);
1644         if(opcode2[i]==0x00) set_const(current,rt1[i],v<<imm[i]);
1645         if(opcode2[i]==0x02) set_const(current,rt1[i],(u_int)v>>imm[i]);
1646         if(opcode2[i]==0x03) set_const(current,rt1[i],v>>imm[i]);
1647       }
1648       else clear_const(current,rt1[i]);
1649     }
1650   }
1651   else
1652   {
1653     clear_const(current,rs1[i]);
1654     clear_const(current,rt1[i]);
1655   }
1656
1657   if(opcode2[i]>=0x38&&opcode2[i]<=0x3b) // DSLL/DSRL/DSRA
1658   {
1659     assert(0);
1660   }
1661   if(opcode2[i]==0x3c) // DSLL32
1662   {
1663     assert(0);
1664   }
1665   if(opcode2[i]==0x3e) // DSRL32
1666   {
1667     assert(0);
1668   }
1669   if(opcode2[i]==0x3f) // DSRA32
1670   {
1671     assert(0);
1672   }
1673 }
1674
1675 static void shift_alloc(struct regstat *current,int i)
1676 {
1677   if(rt1[i]) {
1678     if(opcode2[i]<=0x07) // SLLV/SRLV/SRAV
1679     {
1680       if(rs1[i]) alloc_reg(current,i,rs1[i]);
1681       if(rs2[i]) alloc_reg(current,i,rs2[i]);
1682       alloc_reg(current,i,rt1[i]);
1683       if(rt1[i]==rs2[i]) {
1684         alloc_reg_temp(current,i,-1);
1685         minimum_free_regs[i]=1;
1686       }
1687     } else { // DSLLV/DSRLV/DSRAV
1688       assert(0);
1689     }
1690     clear_const(current,rs1[i]);
1691     clear_const(current,rs2[i]);
1692     clear_const(current,rt1[i]);
1693     dirty_reg(current,rt1[i]);
1694   }
1695 }
1696
1697 static void alu_alloc(struct regstat *current,int i)
1698 {
1699   if(opcode2[i]>=0x20&&opcode2[i]<=0x23) { // ADD/ADDU/SUB/SUBU
1700     if(rt1[i]) {
1701       if(rs1[i]&&rs2[i]) {
1702         alloc_reg(current,i,rs1[i]);
1703         alloc_reg(current,i,rs2[i]);
1704       }
1705       else {
1706         if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1707         if(rs2[i]&&needed_again(rs2[i],i)) alloc_reg(current,i,rs2[i]);
1708       }
1709       alloc_reg(current,i,rt1[i]);
1710     }
1711   }
1712   if(opcode2[i]==0x2a||opcode2[i]==0x2b) { // SLT/SLTU
1713     if(rt1[i]) {
1714       alloc_reg(current,i,rs1[i]);
1715       alloc_reg(current,i,rs2[i]);
1716       alloc_reg(current,i,rt1[i]);
1717     }
1718   }
1719   if(opcode2[i]>=0x24&&opcode2[i]<=0x27) { // AND/OR/XOR/NOR
1720     if(rt1[i]) {
1721       if(rs1[i]&&rs2[i]) {
1722         alloc_reg(current,i,rs1[i]);
1723         alloc_reg(current,i,rs2[i]);
1724       }
1725       else
1726       {
1727         if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1728         if(rs2[i]&&needed_again(rs2[i],i)) alloc_reg(current,i,rs2[i]);
1729       }
1730       alloc_reg(current,i,rt1[i]);
1731     }
1732   }
1733   if(opcode2[i]>=0x2c&&opcode2[i]<=0x2f) { // DADD/DADDU/DSUB/DSUBU
1734     assert(0);
1735   }
1736   clear_const(current,rs1[i]);
1737   clear_const(current,rs2[i]);
1738   clear_const(current,rt1[i]);
1739   dirty_reg(current,rt1[i]);
1740 }
1741
1742 static void imm16_alloc(struct regstat *current,int i)
1743 {
1744   if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1745   else lt1[i]=rs1[i];
1746   if(rt1[i]) alloc_reg(current,i,rt1[i]);
1747   if(opcode[i]==0x18||opcode[i]==0x19) { // DADDI/DADDIU
1748     assert(0);
1749   }
1750   else if(opcode[i]==0x0a||opcode[i]==0x0b) { // SLTI/SLTIU
1751     clear_const(current,rs1[i]);
1752     clear_const(current,rt1[i]);
1753   }
1754   else if(opcode[i]>=0x0c&&opcode[i]<=0x0e) { // ANDI/ORI/XORI
1755     if(is_const(current,rs1[i])) {
1756       int v=get_const(current,rs1[i]);
1757       if(opcode[i]==0x0c) set_const(current,rt1[i],v&imm[i]);
1758       if(opcode[i]==0x0d) set_const(current,rt1[i],v|imm[i]);
1759       if(opcode[i]==0x0e) set_const(current,rt1[i],v^imm[i]);
1760     }
1761     else clear_const(current,rt1[i]);
1762   }
1763   else if(opcode[i]==0x08||opcode[i]==0x09) { // ADDI/ADDIU
1764     if(is_const(current,rs1[i])) {
1765       int v=get_const(current,rs1[i]);
1766       set_const(current,rt1[i],v+imm[i]);
1767     }
1768     else clear_const(current,rt1[i]);
1769   }
1770   else {
1771     set_const(current,rt1[i],imm[i]<<16); // LUI
1772   }
1773   dirty_reg(current,rt1[i]);
1774 }
1775
1776 static void load_alloc(struct regstat *current,int i)
1777 {
1778   clear_const(current,rt1[i]);
1779   //if(rs1[i]!=rt1[i]&&needed_again(rs1[i],i)) clear_const(current,rs1[i]); // Does this help or hurt?
1780   if(!rs1[i]) current->u&=~1LL; // Allow allocating r0 if it's the source register
1781   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1782   if(rt1[i]&&!((current->u>>rt1[i])&1)) {
1783     alloc_reg(current,i,rt1[i]);
1784     assert(get_reg(current->regmap,rt1[i])>=0);
1785     if(opcode[i]==0x27||opcode[i]==0x37) // LWU/LD
1786     {
1787       assert(0);
1788     }
1789     else if(opcode[i]==0x1A||opcode[i]==0x1B) // LDL/LDR
1790     {
1791       assert(0);
1792     }
1793     dirty_reg(current,rt1[i]);
1794     // LWL/LWR need a temporary register for the old value
1795     if(opcode[i]==0x22||opcode[i]==0x26)
1796     {
1797       alloc_reg(current,i,FTEMP);
1798       alloc_reg_temp(current,i,-1);
1799       minimum_free_regs[i]=1;
1800     }
1801   }
1802   else
1803   {
1804     // Load to r0 or unneeded register (dummy load)
1805     // but we still need a register to calculate the address
1806     if(opcode[i]==0x22||opcode[i]==0x26)
1807     {
1808       alloc_reg(current,i,FTEMP); // LWL/LWR need another temporary
1809     }
1810     alloc_reg_temp(current,i,-1);
1811     minimum_free_regs[i]=1;
1812     if(opcode[i]==0x1A||opcode[i]==0x1B) // LDL/LDR
1813     {
1814       assert(0);
1815     }
1816   }
1817 }
1818
1819 void store_alloc(struct regstat *current,int i)
1820 {
1821   clear_const(current,rs2[i]);
1822   if(!(rs2[i])) current->u&=~1LL; // Allow allocating r0 if necessary
1823   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1824   alloc_reg(current,i,rs2[i]);
1825   if(opcode[i]==0x2c||opcode[i]==0x2d||opcode[i]==0x3f) { // 64-bit SDL/SDR/SD
1826     assert(0);
1827   }
1828   #if defined(HOST_IMM8)
1829   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1830   else alloc_reg(current,i,INVCP);
1831   #endif
1832   if(opcode[i]==0x2a||opcode[i]==0x2e||opcode[i]==0x2c||opcode[i]==0x2d) { // SWL/SWL/SDL/SDR
1833     alloc_reg(current,i,FTEMP);
1834   }
1835   // We need a temporary register for address generation
1836   alloc_reg_temp(current,i,-1);
1837   minimum_free_regs[i]=1;
1838 }
1839
1840 void c1ls_alloc(struct regstat *current,int i)
1841 {
1842   //clear_const(current,rs1[i]); // FIXME
1843   clear_const(current,rt1[i]);
1844   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1845   alloc_reg(current,i,CSREG); // Status
1846   alloc_reg(current,i,FTEMP);
1847   if(opcode[i]==0x35||opcode[i]==0x3d) { // 64-bit LDC1/SDC1
1848     assert(0);
1849   }
1850   #if defined(HOST_IMM8)
1851   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1852   else if((opcode[i]&0x3b)==0x39) // SWC1/SDC1
1853     alloc_reg(current,i,INVCP);
1854   #endif
1855   // We need a temporary register for address generation
1856   alloc_reg_temp(current,i,-1);
1857 }
1858
1859 void c2ls_alloc(struct regstat *current,int i)
1860 {
1861   clear_const(current,rt1[i]);
1862   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1863   alloc_reg(current,i,FTEMP);
1864   #if defined(HOST_IMM8)
1865   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1866   if((opcode[i]&0x3b)==0x3a) // SWC2/SDC2
1867     alloc_reg(current,i,INVCP);
1868   #endif
1869   // We need a temporary register for address generation
1870   alloc_reg_temp(current,i,-1);
1871   minimum_free_regs[i]=1;
1872 }
1873
1874 #ifndef multdiv_alloc
1875 void multdiv_alloc(struct regstat *current,int i)
1876 {
1877   //  case 0x18: MULT
1878   //  case 0x19: MULTU
1879   //  case 0x1A: DIV
1880   //  case 0x1B: DIVU
1881   //  case 0x1C: DMULT
1882   //  case 0x1D: DMULTU
1883   //  case 0x1E: DDIV
1884   //  case 0x1F: DDIVU
1885   clear_const(current,rs1[i]);
1886   clear_const(current,rs2[i]);
1887   alloc_cc(current,i); // for stalls
1888   if(rs1[i]&&rs2[i])
1889   {
1890     if((opcode2[i]&4)==0) // 32-bit
1891     {
1892       current->u&=~(1LL<<HIREG);
1893       current->u&=~(1LL<<LOREG);
1894       alloc_reg(current,i,HIREG);
1895       alloc_reg(current,i,LOREG);
1896       alloc_reg(current,i,rs1[i]);
1897       alloc_reg(current,i,rs2[i]);
1898       dirty_reg(current,HIREG);
1899       dirty_reg(current,LOREG);
1900     }
1901     else // 64-bit
1902     {
1903       assert(0);
1904     }
1905   }
1906   else
1907   {
1908     // Multiply by zero is zero.
1909     // MIPS does not have a divide by zero exception.
1910     // The result is undefined, we return zero.
1911     alloc_reg(current,i,HIREG);
1912     alloc_reg(current,i,LOREG);
1913     dirty_reg(current,HIREG);
1914     dirty_reg(current,LOREG);
1915   }
1916 }
1917 #endif
1918
1919 void cop0_alloc(struct regstat *current,int i)
1920 {
1921   if(opcode2[i]==0) // MFC0
1922   {
1923     if(rt1[i]) {
1924       clear_const(current,rt1[i]);
1925       alloc_all(current,i);
1926       alloc_reg(current,i,rt1[i]);
1927       dirty_reg(current,rt1[i]);
1928     }
1929   }
1930   else if(opcode2[i]==4) // MTC0
1931   {
1932     if(rs1[i]){
1933       clear_const(current,rs1[i]);
1934       alloc_reg(current,i,rs1[i]);
1935       alloc_all(current,i);
1936     }
1937     else {
1938       alloc_all(current,i); // FIXME: Keep r0
1939       current->u&=~1LL;
1940       alloc_reg(current,i,0);
1941     }
1942   }
1943   else
1944   {
1945     // TLBR/TLBWI/TLBWR/TLBP/ERET
1946     assert(opcode2[i]==0x10);
1947     alloc_all(current,i);
1948   }
1949   minimum_free_regs[i]=HOST_REGS;
1950 }
1951
1952 static void cop2_alloc(struct regstat *current,int i)
1953 {
1954   if (opcode2[i] < 3) // MFC2/CFC2
1955   {
1956     alloc_cc(current,i); // for stalls
1957     dirty_reg(current,CCREG);
1958     if(rt1[i]){
1959       clear_const(current,rt1[i]);
1960       alloc_reg(current,i,rt1[i]);
1961       dirty_reg(current,rt1[i]);
1962     }
1963   }
1964   else if (opcode2[i] > 3) // MTC2/CTC2
1965   {
1966     if(rs1[i]){
1967       clear_const(current,rs1[i]);
1968       alloc_reg(current,i,rs1[i]);
1969     }
1970     else {
1971       current->u&=~1LL;
1972       alloc_reg(current,i,0);
1973     }
1974   }
1975   alloc_reg_temp(current,i,-1);
1976   minimum_free_regs[i]=1;
1977 }
1978
1979 void c2op_alloc(struct regstat *current,int i)
1980 {
1981   alloc_cc(current,i); // for stalls
1982   dirty_reg(current,CCREG);
1983   alloc_reg_temp(current,i,-1);
1984 }
1985
1986 void syscall_alloc(struct regstat *current,int i)
1987 {
1988   alloc_cc(current,i);
1989   dirty_reg(current,CCREG);
1990   alloc_all(current,i);
1991   minimum_free_regs[i]=HOST_REGS;
1992   current->isconst=0;
1993 }
1994
1995 void delayslot_alloc(struct regstat *current,int i)
1996 {
1997   switch(itype[i]) {
1998     case UJUMP:
1999     case CJUMP:
2000     case SJUMP:
2001     case RJUMP:
2002     case SYSCALL:
2003     case HLECALL:
2004     case SPAN:
2005       assem_debug("jump in the delay slot.  this shouldn't happen.\n");//abort();
2006       SysPrintf("Disabled speculative precompilation\n");
2007       stop_after_jal=1;
2008       break;
2009     case IMM16:
2010       imm16_alloc(current,i);
2011       break;
2012     case LOAD:
2013     case LOADLR:
2014       load_alloc(current,i);
2015       break;
2016     case STORE:
2017     case STORELR:
2018       store_alloc(current,i);
2019       break;
2020     case ALU:
2021       alu_alloc(current,i);
2022       break;
2023     case SHIFT:
2024       shift_alloc(current,i);
2025       break;
2026     case MULTDIV:
2027       multdiv_alloc(current,i);
2028       break;
2029     case SHIFTIMM:
2030       shiftimm_alloc(current,i);
2031       break;
2032     case MOV:
2033       mov_alloc(current,i);
2034       break;
2035     case COP0:
2036       cop0_alloc(current,i);
2037       break;
2038     case COP1:
2039       break;
2040     case COP2:
2041       cop2_alloc(current,i);
2042       break;
2043     case C1LS:
2044       c1ls_alloc(current,i);
2045       break;
2046     case C2LS:
2047       c2ls_alloc(current,i);
2048       break;
2049     case C2OP:
2050       c2op_alloc(current,i);
2051       break;
2052   }
2053 }
2054
2055 // Special case where a branch and delay slot span two pages in virtual memory
2056 static void pagespan_alloc(struct regstat *current,int i)
2057 {
2058   current->isconst=0;
2059   current->wasconst=0;
2060   regs[i].wasconst=0;
2061   minimum_free_regs[i]=HOST_REGS;
2062   alloc_all(current,i);
2063   alloc_cc(current,i);
2064   dirty_reg(current,CCREG);
2065   if(opcode[i]==3) // JAL
2066   {
2067     alloc_reg(current,i,31);
2068     dirty_reg(current,31);
2069   }
2070   if(opcode[i]==0&&(opcode2[i]&0x3E)==8) // JR/JALR
2071   {
2072     alloc_reg(current,i,rs1[i]);
2073     if (rt1[i]!=0) {
2074       alloc_reg(current,i,rt1[i]);
2075       dirty_reg(current,rt1[i]);
2076     }
2077   }
2078   if((opcode[i]&0x2E)==4) // BEQ/BNE/BEQL/BNEL
2079   {
2080     if(rs1[i]) alloc_reg(current,i,rs1[i]);
2081     if(rs2[i]) alloc_reg(current,i,rs2[i]);
2082   }
2083   else
2084   if((opcode[i]&0x2E)==6) // BLEZ/BGTZ/BLEZL/BGTZL
2085   {
2086     if(rs1[i]) alloc_reg(current,i,rs1[i]);
2087   }
2088   //else ...
2089 }
2090
2091 static void add_stub(enum stub_type type, void *addr, void *retaddr,
2092   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e)
2093 {
2094   assert(stubcount < ARRAY_SIZE(stubs));
2095   stubs[stubcount].type = type;
2096   stubs[stubcount].addr = addr;
2097   stubs[stubcount].retaddr = retaddr;
2098   stubs[stubcount].a = a;
2099   stubs[stubcount].b = b;
2100   stubs[stubcount].c = c;
2101   stubs[stubcount].d = d;
2102   stubs[stubcount].e = e;
2103   stubcount++;
2104 }
2105
2106 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
2107   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist)
2108 {
2109   add_stub(type, addr, retaddr, i, addr_reg, (uintptr_t)i_regs, ccadj, reglist);
2110 }
2111
2112 // Write out a single register
2113 static void wb_register(signed char r,signed char regmap[],uint64_t dirty)
2114 {
2115   int hr;
2116   for(hr=0;hr<HOST_REGS;hr++) {
2117     if(hr!=EXCLUDE_REG) {
2118       if((regmap[hr]&63)==r) {
2119         if((dirty>>hr)&1) {
2120           assert(regmap[hr]<64);
2121           emit_storereg(r,hr);
2122         }
2123       }
2124     }
2125   }
2126 }
2127
2128 static void wb_valid(signed char pre[],signed char entry[],u_int dirty_pre,u_int dirty,uint64_t u)
2129 {
2130   //if(dirty_pre==dirty) return;
2131   int hr,reg;
2132   for(hr=0;hr<HOST_REGS;hr++) {
2133     if(hr!=EXCLUDE_REG) {
2134       reg=pre[hr];
2135       if(((~u)>>(reg&63))&1) {
2136         if(reg>0) {
2137           if(((dirty_pre&~dirty)>>hr)&1) {
2138             if(reg>0&&reg<34) {
2139               emit_storereg(reg,hr);
2140             }
2141             else if(reg>=64) {
2142               assert(0);
2143             }
2144           }
2145         }
2146       }
2147     }
2148   }
2149 }
2150
2151 // trashes r2
2152 static void pass_args(int a0, int a1)
2153 {
2154   if(a0==1&&a1==0) {
2155     // must swap
2156     emit_mov(a0,2); emit_mov(a1,1); emit_mov(2,0);
2157   }
2158   else if(a0!=0&&a1==0) {
2159     emit_mov(a1,1);
2160     if (a0>=0) emit_mov(a0,0);
2161   }
2162   else {
2163     if(a0>=0&&a0!=0) emit_mov(a0,0);
2164     if(a1>=0&&a1!=1) emit_mov(a1,1);
2165   }
2166 }
2167
2168 static void alu_assemble(int i,struct regstat *i_regs)
2169 {
2170   if(opcode2[i]>=0x20&&opcode2[i]<=0x23) { // ADD/ADDU/SUB/SUBU
2171     if(rt1[i]) {
2172       signed char s1,s2,t;
2173       t=get_reg(i_regs->regmap,rt1[i]);
2174       if(t>=0) {
2175         s1=get_reg(i_regs->regmap,rs1[i]);
2176         s2=get_reg(i_regs->regmap,rs2[i]);
2177         if(rs1[i]&&rs2[i]) {
2178           assert(s1>=0);
2179           assert(s2>=0);
2180           if(opcode2[i]&2) emit_sub(s1,s2,t);
2181           else emit_add(s1,s2,t);
2182         }
2183         else if(rs1[i]) {
2184           if(s1>=0) emit_mov(s1,t);
2185           else emit_loadreg(rs1[i],t);
2186         }
2187         else if(rs2[i]) {
2188           if(s2>=0) {
2189             if(opcode2[i]&2) emit_neg(s2,t);
2190             else emit_mov(s2,t);
2191           }
2192           else {
2193             emit_loadreg(rs2[i],t);
2194             if(opcode2[i]&2) emit_neg(t,t);
2195           }
2196         }
2197         else emit_zeroreg(t);
2198       }
2199     }
2200   }
2201   if(opcode2[i]>=0x2c&&opcode2[i]<=0x2f) { // DADD/DADDU/DSUB/DSUBU
2202     assert(0);
2203   }
2204   if(opcode2[i]==0x2a||opcode2[i]==0x2b) { // SLT/SLTU
2205     if(rt1[i]) {
2206       signed char s1l,s2l,t;
2207       {
2208         t=get_reg(i_regs->regmap,rt1[i]);
2209         //assert(t>=0);
2210         if(t>=0) {
2211           s1l=get_reg(i_regs->regmap,rs1[i]);
2212           s2l=get_reg(i_regs->regmap,rs2[i]);
2213           if(rs2[i]==0) // rx<r0
2214           {
2215             if(opcode2[i]==0x2a&&rs1[i]!=0) { // SLT
2216               assert(s1l>=0);
2217               emit_shrimm(s1l,31,t);
2218             }
2219             else // SLTU (unsigned can not be less than zero, 0<0)
2220               emit_zeroreg(t);
2221           }
2222           else if(rs1[i]==0) // r0<rx
2223           {
2224             assert(s2l>=0);
2225             if(opcode2[i]==0x2a) // SLT
2226               emit_set_gz32(s2l,t);
2227             else // SLTU (set if not zero)
2228               emit_set_nz32(s2l,t);
2229           }
2230           else{
2231             assert(s1l>=0);assert(s2l>=0);
2232             if(opcode2[i]==0x2a) // SLT
2233               emit_set_if_less32(s1l,s2l,t);
2234             else // SLTU
2235               emit_set_if_carry32(s1l,s2l,t);
2236           }
2237         }
2238       }
2239     }
2240   }
2241   if(opcode2[i]>=0x24&&opcode2[i]<=0x27) { // AND/OR/XOR/NOR
2242     if(rt1[i]) {
2243       signed char s1l,s2l,tl;
2244       tl=get_reg(i_regs->regmap,rt1[i]);
2245       {
2246         if(tl>=0) {
2247           s1l=get_reg(i_regs->regmap,rs1[i]);
2248           s2l=get_reg(i_regs->regmap,rs2[i]);
2249           if(rs1[i]&&rs2[i]) {
2250             assert(s1l>=0);
2251             assert(s2l>=0);
2252             if(opcode2[i]==0x24) { // AND
2253               emit_and(s1l,s2l,tl);
2254             } else
2255             if(opcode2[i]==0x25) { // OR
2256               emit_or(s1l,s2l,tl);
2257             } else
2258             if(opcode2[i]==0x26) { // XOR
2259               emit_xor(s1l,s2l,tl);
2260             } else
2261             if(opcode2[i]==0x27) { // NOR
2262               emit_or(s1l,s2l,tl);
2263               emit_not(tl,tl);
2264             }
2265           }
2266           else
2267           {
2268             if(opcode2[i]==0x24) { // AND
2269               emit_zeroreg(tl);
2270             } else
2271             if(opcode2[i]==0x25||opcode2[i]==0x26) { // OR/XOR
2272               if(rs1[i]){
2273                 if(s1l>=0) emit_mov(s1l,tl);
2274                 else emit_loadreg(rs1[i],tl); // CHECK: regmap_entry?
2275               }
2276               else
2277               if(rs2[i]){
2278                 if(s2l>=0) emit_mov(s2l,tl);
2279                 else emit_loadreg(rs2[i],tl); // CHECK: regmap_entry?
2280               }
2281               else emit_zeroreg(tl);
2282             } else
2283             if(opcode2[i]==0x27) { // NOR
2284               if(rs1[i]){
2285                 if(s1l>=0) emit_not(s1l,tl);
2286                 else {
2287                   emit_loadreg(rs1[i],tl);
2288                   emit_not(tl,tl);
2289                 }
2290               }
2291               else
2292               if(rs2[i]){
2293                 if(s2l>=0) emit_not(s2l,tl);
2294                 else {
2295                   emit_loadreg(rs2[i],tl);
2296                   emit_not(tl,tl);
2297                 }
2298               }
2299               else emit_movimm(-1,tl);
2300             }
2301           }
2302         }
2303       }
2304     }
2305   }
2306 }
2307
2308 void imm16_assemble(int i,struct regstat *i_regs)
2309 {
2310   if (opcode[i]==0x0f) { // LUI
2311     if(rt1[i]) {
2312       signed char t;
2313       t=get_reg(i_regs->regmap,rt1[i]);
2314       //assert(t>=0);
2315       if(t>=0) {
2316         if(!((i_regs->isconst>>t)&1))
2317           emit_movimm(imm[i]<<16,t);
2318       }
2319     }
2320   }
2321   if(opcode[i]==0x08||opcode[i]==0x09) { // ADDI/ADDIU
2322     if(rt1[i]) {
2323       signed char s,t;
2324       t=get_reg(i_regs->regmap,rt1[i]);
2325       s=get_reg(i_regs->regmap,rs1[i]);
2326       if(rs1[i]) {
2327         //assert(t>=0);
2328         //assert(s>=0);
2329         if(t>=0) {
2330           if(!((i_regs->isconst>>t)&1)) {
2331             if(s<0) {
2332               if(i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2333               emit_addimm(t,imm[i],t);
2334             }else{
2335               if(!((i_regs->wasconst>>s)&1))
2336                 emit_addimm(s,imm[i],t);
2337               else
2338                 emit_movimm(constmap[i][s]+imm[i],t);
2339             }
2340           }
2341         }
2342       } else {
2343         if(t>=0) {
2344           if(!((i_regs->isconst>>t)&1))
2345             emit_movimm(imm[i],t);
2346         }
2347       }
2348     }
2349   }
2350   if(opcode[i]==0x18||opcode[i]==0x19) { // DADDI/DADDIU
2351     if(rt1[i]) {
2352       signed char sl,tl;
2353       tl=get_reg(i_regs->regmap,rt1[i]);
2354       sl=get_reg(i_regs->regmap,rs1[i]);
2355       if(tl>=0) {
2356         if(rs1[i]) {
2357           assert(sl>=0);
2358           emit_addimm(sl,imm[i],tl);
2359         } else {
2360           emit_movimm(imm[i],tl);
2361         }
2362       }
2363     }
2364   }
2365   else if(opcode[i]==0x0a||opcode[i]==0x0b) { // SLTI/SLTIU
2366     if(rt1[i]) {
2367       //assert(rs1[i]!=0); // r0 might be valid, but it's probably a bug
2368       signed char sl,t;
2369       t=get_reg(i_regs->regmap,rt1[i]);
2370       sl=get_reg(i_regs->regmap,rs1[i]);
2371       //assert(t>=0);
2372       if(t>=0) {
2373         if(rs1[i]>0) {
2374             if(opcode[i]==0x0a) { // SLTI
2375               if(sl<0) {
2376                 if(i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2377                 emit_slti32(t,imm[i],t);
2378               }else{
2379                 emit_slti32(sl,imm[i],t);
2380               }
2381             }
2382             else { // SLTIU
2383               if(sl<0) {
2384                 if(i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2385                 emit_sltiu32(t,imm[i],t);
2386               }else{
2387                 emit_sltiu32(sl,imm[i],t);
2388               }
2389             }
2390         }else{
2391           // SLTI(U) with r0 is just stupid,
2392           // nonetheless examples can be found
2393           if(opcode[i]==0x0a) // SLTI
2394             if(0<imm[i]) emit_movimm(1,t);
2395             else emit_zeroreg(t);
2396           else // SLTIU
2397           {
2398             if(imm[i]) emit_movimm(1,t);
2399             else emit_zeroreg(t);
2400           }
2401         }
2402       }
2403     }
2404   }
2405   else if(opcode[i]>=0x0c&&opcode[i]<=0x0e) { // ANDI/ORI/XORI
2406     if(rt1[i]) {
2407       signed char sl,tl;
2408       tl=get_reg(i_regs->regmap,rt1[i]);
2409       sl=get_reg(i_regs->regmap,rs1[i]);
2410       if(tl>=0 && !((i_regs->isconst>>tl)&1)) {
2411         if(opcode[i]==0x0c) //ANDI
2412         {
2413           if(rs1[i]) {
2414             if(sl<0) {
2415               if(i_regs->regmap_entry[tl]!=rs1[i]) emit_loadreg(rs1[i],tl);
2416               emit_andimm(tl,imm[i],tl);
2417             }else{
2418               if(!((i_regs->wasconst>>sl)&1))
2419                 emit_andimm(sl,imm[i],tl);
2420               else
2421                 emit_movimm(constmap[i][sl]&imm[i],tl);
2422             }
2423           }
2424           else
2425             emit_zeroreg(tl);
2426         }
2427         else
2428         {
2429           if(rs1[i]) {
2430             if(sl<0) {
2431               if(i_regs->regmap_entry[tl]!=rs1[i]) emit_loadreg(rs1[i],tl);
2432             }
2433             if(opcode[i]==0x0d) { // ORI
2434               if(sl<0) {
2435                 emit_orimm(tl,imm[i],tl);
2436               }else{
2437                 if(!((i_regs->wasconst>>sl)&1))
2438                   emit_orimm(sl,imm[i],tl);
2439                 else
2440                   emit_movimm(constmap[i][sl]|imm[i],tl);
2441               }
2442             }
2443             if(opcode[i]==0x0e) { // XORI
2444               if(sl<0) {
2445                 emit_xorimm(tl,imm[i],tl);
2446               }else{
2447                 if(!((i_regs->wasconst>>sl)&1))
2448                   emit_xorimm(sl,imm[i],tl);
2449                 else
2450                   emit_movimm(constmap[i][sl]^imm[i],tl);
2451               }
2452             }
2453           }
2454           else {
2455             emit_movimm(imm[i],tl);
2456           }
2457         }
2458       }
2459     }
2460   }
2461 }
2462
2463 void shiftimm_assemble(int i,struct regstat *i_regs)
2464 {
2465   if(opcode2[i]<=0x3) // SLL/SRL/SRA
2466   {
2467     if(rt1[i]) {
2468       signed char s,t;
2469       t=get_reg(i_regs->regmap,rt1[i]);
2470       s=get_reg(i_regs->regmap,rs1[i]);
2471       //assert(t>=0);
2472       if(t>=0&&!((i_regs->isconst>>t)&1)){
2473         if(rs1[i]==0)
2474         {
2475           emit_zeroreg(t);
2476         }
2477         else
2478         {
2479           if(s<0&&i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2480           if(imm[i]) {
2481             if(opcode2[i]==0) // SLL
2482             {
2483               emit_shlimm(s<0?t:s,imm[i],t);
2484             }
2485             if(opcode2[i]==2) // SRL
2486             {
2487               emit_shrimm(s<0?t:s,imm[i],t);
2488             }
2489             if(opcode2[i]==3) // SRA
2490             {
2491               emit_sarimm(s<0?t:s,imm[i],t);
2492             }
2493           }else{
2494             // Shift by zero
2495             if(s>=0 && s!=t) emit_mov(s,t);
2496           }
2497         }
2498       }
2499       //emit_storereg(rt1[i],t); //DEBUG
2500     }
2501   }
2502   if(opcode2[i]>=0x38&&opcode2[i]<=0x3b) // DSLL/DSRL/DSRA
2503   {
2504     assert(0);
2505   }
2506   if(opcode2[i]==0x3c) // DSLL32
2507   {
2508     assert(0);
2509   }
2510   if(opcode2[i]==0x3e) // DSRL32
2511   {
2512     assert(0);
2513   }
2514   if(opcode2[i]==0x3f) // DSRA32
2515   {
2516     assert(0);
2517   }
2518 }
2519
2520 #ifndef shift_assemble
2521 static void shift_assemble(int i,struct regstat *i_regs)
2522 {
2523   signed char s,t,shift;
2524   if (rt1[i] == 0)
2525     return;
2526   assert(opcode2[i]<=0x07); // SLLV/SRLV/SRAV
2527   t = get_reg(i_regs->regmap, rt1[i]);
2528   s = get_reg(i_regs->regmap, rs1[i]);
2529   shift = get_reg(i_regs->regmap, rs2[i]);
2530   if (t < 0)
2531     return;
2532
2533   if(rs1[i]==0)
2534     emit_zeroreg(t);
2535   else if(rs2[i]==0) {
2536     assert(s>=0);
2537     if(s!=t) emit_mov(s,t);
2538   }
2539   else {
2540     host_tempreg_acquire();
2541     emit_andimm(shift,31,HOST_TEMPREG);
2542     switch(opcode2[i]) {
2543     case 4: // SLLV
2544       emit_shl(s,HOST_TEMPREG,t);
2545       break;
2546     case 6: // SRLV
2547       emit_shr(s,HOST_TEMPREG,t);
2548       break;
2549     case 7: // SRAV
2550       emit_sar(s,HOST_TEMPREG,t);
2551       break;
2552     default:
2553       assert(0);
2554     }
2555     host_tempreg_release();
2556   }
2557 }
2558
2559 #endif
2560
2561 enum {
2562   MTYPE_8000 = 0,
2563   MTYPE_8020,
2564   MTYPE_0000,
2565   MTYPE_A000,
2566   MTYPE_1F80,
2567 };
2568
2569 static int get_ptr_mem_type(u_int a)
2570 {
2571   if(a < 0x00200000) {
2572     if(a<0x1000&&((start>>20)==0xbfc||(start>>24)==0xa0))
2573       // return wrong, must use memhandler for BIOS self-test to pass
2574       // 007 does similar stuff from a00 mirror, weird stuff
2575       return MTYPE_8000;
2576     return MTYPE_0000;
2577   }
2578   if(0x1f800000 <= a && a < 0x1f801000)
2579     return MTYPE_1F80;
2580   if(0x80200000 <= a && a < 0x80800000)
2581     return MTYPE_8020;
2582   if(0xa0000000 <= a && a < 0xa0200000)
2583     return MTYPE_A000;
2584   return MTYPE_8000;
2585 }
2586
2587 static void *emit_fastpath_cmp_jump(int i,int addr,int *addr_reg_override)
2588 {
2589   void *jaddr = NULL;
2590   int type=0;
2591   int mr=rs1[i];
2592   if(((smrv_strong|smrv_weak)>>mr)&1) {
2593     type=get_ptr_mem_type(smrv[mr]);
2594     //printf("set %08x @%08x r%d %d\n", smrv[mr], start+i*4, mr, type);
2595   }
2596   else {
2597     // use the mirror we are running on
2598     type=get_ptr_mem_type(start);
2599     //printf("set nospec   @%08x r%d %d\n", start+i*4, mr, type);
2600   }
2601
2602   if(type==MTYPE_8020) { // RAM 80200000+ mirror
2603     host_tempreg_acquire();
2604     emit_andimm(addr,~0x00e00000,HOST_TEMPREG);
2605     addr=*addr_reg_override=HOST_TEMPREG;
2606     type=0;
2607   }
2608   else if(type==MTYPE_0000) { // RAM 0 mirror
2609     host_tempreg_acquire();
2610     emit_orimm(addr,0x80000000,HOST_TEMPREG);
2611     addr=*addr_reg_override=HOST_TEMPREG;
2612     type=0;
2613   }
2614   else if(type==MTYPE_A000) { // RAM A mirror
2615     host_tempreg_acquire();
2616     emit_andimm(addr,~0x20000000,HOST_TEMPREG);
2617     addr=*addr_reg_override=HOST_TEMPREG;
2618     type=0;
2619   }
2620   else if(type==MTYPE_1F80) { // scratchpad
2621     if (psxH == (void *)0x1f800000) {
2622       host_tempreg_acquire();
2623       emit_xorimm(addr,0x1f800000,HOST_TEMPREG);
2624       emit_cmpimm(HOST_TEMPREG,0x1000);
2625       host_tempreg_release();
2626       jaddr=out;
2627       emit_jc(0);
2628     }
2629     else {
2630       // do the usual RAM check, jump will go to the right handler
2631       type=0;
2632     }
2633   }
2634
2635   if(type==0)
2636   {
2637     emit_cmpimm(addr,RAM_SIZE);
2638     jaddr=out;
2639     #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
2640     // Hint to branch predictor that the branch is unlikely to be taken
2641     if(rs1[i]>=28)
2642       emit_jno_unlikely(0);
2643     else
2644     #endif
2645       emit_jno(0);
2646     if(ram_offset!=0) {
2647       host_tempreg_acquire();
2648       emit_addimm(addr,ram_offset,HOST_TEMPREG);
2649       addr=*addr_reg_override=HOST_TEMPREG;
2650     }
2651   }
2652
2653   return jaddr;
2654 }
2655
2656 // return memhandler, or get directly accessable address and return 0
2657 static void *get_direct_memhandler(void *table, u_int addr,
2658   enum stub_type type, uintptr_t *addr_host)
2659 {
2660   uintptr_t l1, l2 = 0;
2661   l1 = ((uintptr_t *)table)[addr>>12];
2662   if ((l1 & (1ul << (sizeof(l1)*8-1))) == 0) {
2663     uintptr_t v = l1 << 1;
2664     *addr_host = v + addr;
2665     return NULL;
2666   }
2667   else {
2668     l1 <<= 1;
2669     if (type == LOADB_STUB || type == LOADBU_STUB || type == STOREB_STUB)
2670       l2 = ((uintptr_t *)l1)[0x1000/4 + 0x1000/2 + (addr&0xfff)];
2671     else if (type == LOADH_STUB || type == LOADHU_STUB || type == STOREH_STUB)
2672       l2=((uintptr_t *)l1)[0x1000/4 + (addr&0xfff)/2];
2673     else
2674       l2=((uintptr_t *)l1)[(addr&0xfff)/4];
2675     if ((l2 & (1<<31)) == 0) {
2676       uintptr_t v = l2 << 1;
2677       *addr_host = v + (addr&0xfff);
2678       return NULL;
2679     }
2680     return (void *)(l2 << 1);
2681   }
2682 }
2683
2684 static u_int get_host_reglist(const signed char *regmap)
2685 {
2686   u_int reglist = 0, hr;
2687   for (hr = 0; hr < HOST_REGS; hr++) {
2688     if (hr != EXCLUDE_REG && regmap[hr] >= 0)
2689       reglist |= 1 << hr;
2690   }
2691   return reglist;
2692 }
2693
2694 static u_int reglist_exclude(u_int reglist, int r1, int r2)
2695 {
2696   if (r1 >= 0)
2697     reglist &= ~(1u << r1);
2698   if (r2 >= 0)
2699     reglist &= ~(1u << r2);
2700   return reglist;
2701 }
2702
2703 // find a temp caller-saved register not in reglist (so assumed to be free)
2704 static int reglist_find_free(u_int reglist)
2705 {
2706   u_int free_regs = ~reglist & CALLER_SAVE_REGS;
2707   if (free_regs == 0)
2708     return -1;
2709   return __builtin_ctz(free_regs);
2710 }
2711
2712 static void load_assemble(int i, const struct regstat *i_regs)
2713 {
2714   int s,tl,addr;
2715   int offset;
2716   void *jaddr=0;
2717   int memtarget=0,c=0;
2718   int fastio_reg_override=-1;
2719   u_int reglist=get_host_reglist(i_regs->regmap);
2720   tl=get_reg(i_regs->regmap,rt1[i]);
2721   s=get_reg(i_regs->regmap,rs1[i]);
2722   offset=imm[i];
2723   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2724   if(s>=0) {
2725     c=(i_regs->wasconst>>s)&1;
2726     if (c) {
2727       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2728     }
2729   }
2730   //printf("load_assemble: c=%d\n",c);
2731   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2732   // FIXME: Even if the load is a NOP, we should check for pagefaults...
2733   if((tl<0&&(!c||(((u_int)constmap[i][s]+offset)>>16)==0x1f80))
2734     ||rt1[i]==0) {
2735       // could be FIFO, must perform the read
2736       // ||dummy read
2737       assem_debug("(forced read)\n");
2738       tl=get_reg(i_regs->regmap,-1);
2739       assert(tl>=0);
2740   }
2741   if(offset||s<0||c) addr=tl;
2742   else addr=s;
2743   //if(tl<0) tl=get_reg(i_regs->regmap,-1);
2744  if(tl>=0) {
2745   //printf("load_assemble: c=%d\n",c);
2746   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2747   assert(tl>=0); // Even if the load is a NOP, we must check for pagefaults and I/O
2748   reglist&=~(1<<tl);
2749   if(!c) {
2750     #ifdef R29_HACK
2751     // Strmnnrmn's speed hack
2752     if(rs1[i]!=29||start<0x80001000||start>=0x80000000+RAM_SIZE)
2753     #endif
2754     {
2755       jaddr=emit_fastpath_cmp_jump(i,addr,&fastio_reg_override);
2756     }
2757   }
2758   else if(ram_offset&&memtarget) {
2759     host_tempreg_acquire();
2760     emit_addimm(addr,ram_offset,HOST_TEMPREG);
2761     fastio_reg_override=HOST_TEMPREG;
2762   }
2763   int dummy=(rt1[i]==0)||(tl!=get_reg(i_regs->regmap,rt1[i])); // ignore loads to r0 and unneeded reg
2764   if (opcode[i]==0x20) { // LB
2765     if(!c||memtarget) {
2766       if(!dummy) {
2767         {
2768           int x=0,a=tl;
2769           if(!c) a=addr;
2770           if(fastio_reg_override>=0) a=fastio_reg_override;
2771
2772           emit_movsbl_indexed(x,a,tl);
2773         }
2774       }
2775       if(jaddr)
2776         add_stub_r(LOADB_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2777     }
2778     else
2779       inline_readstub(LOADB_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2780   }
2781   if (opcode[i]==0x21) { // LH
2782     if(!c||memtarget) {
2783       if(!dummy) {
2784         int x=0,a=tl;
2785         if(!c) a=addr;
2786         if(fastio_reg_override>=0) a=fastio_reg_override;
2787         emit_movswl_indexed(x,a,tl);
2788       }
2789       if(jaddr)
2790         add_stub_r(LOADH_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2791     }
2792     else
2793       inline_readstub(LOADH_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2794   }
2795   if (opcode[i]==0x23) { // LW
2796     if(!c||memtarget) {
2797       if(!dummy) {
2798         int a=addr;
2799         if(fastio_reg_override>=0) a=fastio_reg_override;
2800         emit_readword_indexed(0,a,tl);
2801       }
2802       if(jaddr)
2803         add_stub_r(LOADW_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2804     }
2805     else
2806       inline_readstub(LOADW_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2807   }
2808   if (opcode[i]==0x24) { // LBU
2809     if(!c||memtarget) {
2810       if(!dummy) {
2811         int x=0,a=tl;
2812         if(!c) a=addr;
2813         if(fastio_reg_override>=0) a=fastio_reg_override;
2814
2815         emit_movzbl_indexed(x,a,tl);
2816       }
2817       if(jaddr)
2818         add_stub_r(LOADBU_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2819     }
2820     else
2821       inline_readstub(LOADBU_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2822   }
2823   if (opcode[i]==0x25) { // LHU
2824     if(!c||memtarget) {
2825       if(!dummy) {
2826         int x=0,a=tl;
2827         if(!c) a=addr;
2828         if(fastio_reg_override>=0) a=fastio_reg_override;
2829         emit_movzwl_indexed(x,a,tl);
2830       }
2831       if(jaddr)
2832         add_stub_r(LOADHU_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2833     }
2834     else
2835       inline_readstub(LOADHU_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2836   }
2837   if (opcode[i]==0x27) { // LWU
2838     assert(0);
2839   }
2840   if (opcode[i]==0x37) { // LD
2841     assert(0);
2842   }
2843  }
2844  if (fastio_reg_override == HOST_TEMPREG)
2845    host_tempreg_release();
2846 }
2847
2848 #ifndef loadlr_assemble
2849 static void loadlr_assemble(int i, const struct regstat *i_regs)
2850 {
2851   int s,tl,temp,temp2,addr;
2852   int offset;
2853   void *jaddr=0;
2854   int memtarget=0,c=0;
2855   int fastio_reg_override=-1;
2856   u_int reglist=get_host_reglist(i_regs->regmap);
2857   tl=get_reg(i_regs->regmap,rt1[i]);
2858   s=get_reg(i_regs->regmap,rs1[i]);
2859   temp=get_reg(i_regs->regmap,-1);
2860   temp2=get_reg(i_regs->regmap,FTEMP);
2861   addr=get_reg(i_regs->regmap,AGEN1+(i&1));
2862   assert(addr<0);
2863   offset=imm[i];
2864   reglist|=1<<temp;
2865   if(offset||s<0||c) addr=temp2;
2866   else addr=s;
2867   if(s>=0) {
2868     c=(i_regs->wasconst>>s)&1;
2869     if(c) {
2870       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2871     }
2872   }
2873   if(!c) {
2874     emit_shlimm(addr,3,temp);
2875     if (opcode[i]==0x22||opcode[i]==0x26) {
2876       emit_andimm(addr,0xFFFFFFFC,temp2); // LWL/LWR
2877     }else{
2878       emit_andimm(addr,0xFFFFFFF8,temp2); // LDL/LDR
2879     }
2880     jaddr=emit_fastpath_cmp_jump(i,temp2,&fastio_reg_override);
2881   }
2882   else {
2883     if(ram_offset&&memtarget) {
2884       host_tempreg_acquire();
2885       emit_addimm(temp2,ram_offset,HOST_TEMPREG);
2886       fastio_reg_override=HOST_TEMPREG;
2887     }
2888     if (opcode[i]==0x22||opcode[i]==0x26) {
2889       emit_movimm(((constmap[i][s]+offset)<<3)&24,temp); // LWL/LWR
2890     }else{
2891       emit_movimm(((constmap[i][s]+offset)<<3)&56,temp); // LDL/LDR
2892     }
2893   }
2894   if (opcode[i]==0x22||opcode[i]==0x26) { // LWL/LWR
2895     if(!c||memtarget) {
2896       int a=temp2;
2897       if(fastio_reg_override>=0) a=fastio_reg_override;
2898       emit_readword_indexed(0,a,temp2);
2899       if(fastio_reg_override==HOST_TEMPREG) host_tempreg_release();
2900       if(jaddr) add_stub_r(LOADW_STUB,jaddr,out,i,temp2,i_regs,ccadj[i],reglist);
2901     }
2902     else
2903       inline_readstub(LOADW_STUB,i,(constmap[i][s]+offset)&0xFFFFFFFC,i_regs->regmap,FTEMP,ccadj[i],reglist);
2904     if(rt1[i]) {
2905       assert(tl>=0);
2906       emit_andimm(temp,24,temp);
2907       if (opcode[i]==0x22) // LWL
2908         emit_xorimm(temp,24,temp);
2909       host_tempreg_acquire();
2910       emit_movimm(-1,HOST_TEMPREG);
2911       if (opcode[i]==0x26) {
2912         emit_shr(temp2,temp,temp2);
2913         emit_bic_lsr(tl,HOST_TEMPREG,temp,tl);
2914       }else{
2915         emit_shl(temp2,temp,temp2);
2916         emit_bic_lsl(tl,HOST_TEMPREG,temp,tl);
2917       }
2918       host_tempreg_release();
2919       emit_or(temp2,tl,tl);
2920     }
2921     //emit_storereg(rt1[i],tl); // DEBUG
2922   }
2923   if (opcode[i]==0x1A||opcode[i]==0x1B) { // LDL/LDR
2924     assert(0);
2925   }
2926 }
2927 #endif
2928
2929 void store_assemble(int i, const struct regstat *i_regs)
2930 {
2931   int s,tl;
2932   int addr,temp;
2933   int offset;
2934   void *jaddr=0;
2935   enum stub_type type;
2936   int memtarget=0,c=0;
2937   int agr=AGEN1+(i&1);
2938   int fastio_reg_override=-1;
2939   u_int reglist=get_host_reglist(i_regs->regmap);
2940   tl=get_reg(i_regs->regmap,rs2[i]);
2941   s=get_reg(i_regs->regmap,rs1[i]);
2942   temp=get_reg(i_regs->regmap,agr);
2943   if(temp<0) temp=get_reg(i_regs->regmap,-1);
2944   offset=imm[i];
2945   if(s>=0) {
2946     c=(i_regs->wasconst>>s)&1;
2947     if(c) {
2948       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2949     }
2950   }
2951   assert(tl>=0);
2952   assert(temp>=0);
2953   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2954   if(offset||s<0||c) addr=temp;
2955   else addr=s;
2956   if(!c) {
2957     jaddr=emit_fastpath_cmp_jump(i,addr,&fastio_reg_override);
2958   }
2959   else if(ram_offset&&memtarget) {
2960     host_tempreg_acquire();
2961     emit_addimm(addr,ram_offset,HOST_TEMPREG);
2962     fastio_reg_override=HOST_TEMPREG;
2963   }
2964
2965   if (opcode[i]==0x28) { // SB
2966     if(!c||memtarget) {
2967       int x=0,a=temp;
2968       if(!c) a=addr;
2969       if(fastio_reg_override>=0) a=fastio_reg_override;
2970       emit_writebyte_indexed(tl,x,a);
2971     }
2972     type=STOREB_STUB;
2973   }
2974   if (opcode[i]==0x29) { // SH
2975     if(!c||memtarget) {
2976       int x=0,a=temp;
2977       if(!c) a=addr;
2978       if(fastio_reg_override>=0) a=fastio_reg_override;
2979       emit_writehword_indexed(tl,x,a);
2980     }
2981     type=STOREH_STUB;
2982   }
2983   if (opcode[i]==0x2B) { // SW
2984     if(!c||memtarget) {
2985       int a=addr;
2986       if(fastio_reg_override>=0) a=fastio_reg_override;
2987       emit_writeword_indexed(tl,0,a);
2988     }
2989     type=STOREW_STUB;
2990   }
2991   if (opcode[i]==0x3F) { // SD
2992     assert(0);
2993     type=STORED_STUB;
2994   }
2995   if(fastio_reg_override==HOST_TEMPREG)
2996     host_tempreg_release();
2997   if(jaddr) {
2998     // PCSX store handlers don't check invcode again
2999     reglist|=1<<addr;
3000     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
3001     jaddr=0;
3002   }
3003   if(!(i_regs->waswritten&(1<<rs1[i])) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3004     if(!c||memtarget) {
3005       #ifdef DESTRUCTIVE_SHIFT
3006       // The x86 shift operation is 'destructive'; it overwrites the
3007       // source register, so we need to make a copy first and use that.
3008       addr=temp;
3009       #endif
3010       #if defined(HOST_IMM8)
3011       int ir=get_reg(i_regs->regmap,INVCP);
3012       assert(ir>=0);
3013       emit_cmpmem_indexedsr12_reg(ir,addr,1);
3014       #else
3015       emit_cmpmem_indexedsr12_imm(invalid_code,addr,1);
3016       #endif
3017       #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3018       emit_callne(invalidate_addr_reg[addr]);
3019       #else
3020       void *jaddr2 = out;
3021       emit_jne(0);
3022       add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),addr,0,0,0);
3023       #endif
3024     }
3025   }
3026   u_int addr_val=constmap[i][s]+offset;
3027   if(jaddr) {
3028     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
3029   } else if(c&&!memtarget) {
3030     inline_writestub(type,i,addr_val,i_regs->regmap,rs2[i],ccadj[i],reglist);
3031   }
3032   // basic current block modification detection..
3033   // not looking back as that should be in mips cache already
3034   // (see Spyro2 title->attract mode)
3035   if(c&&start+i*4<addr_val&&addr_val<start+slen*4) {
3036     SysPrintf("write to %08x hits block %08x, pc=%08x\n",addr_val,start,start+i*4);
3037     assert(i_regs->regmap==regs[i].regmap); // not delay slot
3038     if(i_regs->regmap==regs[i].regmap) {
3039       load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3040       wb_dirtys(regs[i].regmap_entry,regs[i].wasdirty);
3041       emit_movimm(start+i*4+4,0);
3042       emit_writeword(0,&pcaddr);
3043       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3044       emit_far_call(get_addr_ht);
3045       emit_jmpreg(0);
3046     }
3047   }
3048 }
3049
3050 static void storelr_assemble(int i, const struct regstat *i_regs)
3051 {
3052   int s,tl;
3053   int temp;
3054   int offset;
3055   void *jaddr=0;
3056   void *case1, *case2, *case3;
3057   void *done0, *done1, *done2;
3058   int memtarget=0,c=0;
3059   int agr=AGEN1+(i&1);
3060   u_int reglist=get_host_reglist(i_regs->regmap);
3061   tl=get_reg(i_regs->regmap,rs2[i]);
3062   s=get_reg(i_regs->regmap,rs1[i]);
3063   temp=get_reg(i_regs->regmap,agr);
3064   if(temp<0) temp=get_reg(i_regs->regmap,-1);
3065   offset=imm[i];
3066   if(s>=0) {
3067     c=(i_regs->isconst>>s)&1;
3068     if(c) {
3069       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3070     }
3071   }
3072   assert(tl>=0);
3073   assert(temp>=0);
3074   if(!c) {
3075     emit_cmpimm(s<0||offset?temp:s,RAM_SIZE);
3076     if(!offset&&s!=temp) emit_mov(s,temp);
3077     jaddr=out;
3078     emit_jno(0);
3079   }
3080   else
3081   {
3082     if(!memtarget||!rs1[i]) {
3083       jaddr=out;
3084       emit_jmp(0);
3085     }
3086   }
3087   if(ram_offset)
3088     emit_addimm_no_flags(ram_offset,temp);
3089
3090   if (opcode[i]==0x2C||opcode[i]==0x2D) { // SDL/SDR
3091     assert(0);
3092   }
3093
3094   emit_xorimm(temp,3,temp);
3095   emit_testimm(temp,2);
3096   case2=out;
3097   emit_jne(0);
3098   emit_testimm(temp,1);
3099   case1=out;
3100   emit_jne(0);
3101   // 0
3102   if (opcode[i]==0x2A) { // SWL
3103     emit_writeword_indexed(tl,0,temp);
3104   }
3105   else if (opcode[i]==0x2E) { // SWR
3106     emit_writebyte_indexed(tl,3,temp);
3107   }
3108   else
3109     assert(0);
3110   done0=out;
3111   emit_jmp(0);
3112   // 1
3113   set_jump_target(case1, out);
3114   if (opcode[i]==0x2A) { // SWL
3115     // Write 3 msb into three least significant bytes
3116     if(rs2[i]) emit_rorimm(tl,8,tl);
3117     emit_writehword_indexed(tl,-1,temp);
3118     if(rs2[i]) emit_rorimm(tl,16,tl);
3119     emit_writebyte_indexed(tl,1,temp);
3120     if(rs2[i]) emit_rorimm(tl,8,tl);
3121   }
3122   else if (opcode[i]==0x2E) { // SWR
3123     // Write two lsb into two most significant bytes
3124     emit_writehword_indexed(tl,1,temp);
3125   }
3126   done1=out;
3127   emit_jmp(0);
3128   // 2
3129   set_jump_target(case2, out);
3130   emit_testimm(temp,1);
3131   case3=out;
3132   emit_jne(0);
3133   if (opcode[i]==0x2A) { // SWL
3134     // Write two msb into two least significant bytes
3135     if(rs2[i]) emit_rorimm(tl,16,tl);
3136     emit_writehword_indexed(tl,-2,temp);
3137     if(rs2[i]) emit_rorimm(tl,16,tl);
3138   }
3139   else if (opcode[i]==0x2E) { // SWR
3140     // Write 3 lsb into three most significant bytes
3141     emit_writebyte_indexed(tl,-1,temp);
3142     if(rs2[i]) emit_rorimm(tl,8,tl);
3143     emit_writehword_indexed(tl,0,temp);
3144     if(rs2[i]) emit_rorimm(tl,24,tl);
3145   }
3146   done2=out;
3147   emit_jmp(0);
3148   // 3
3149   set_jump_target(case3, out);
3150   if (opcode[i]==0x2A) { // SWL
3151     // Write msb into least significant byte
3152     if(rs2[i]) emit_rorimm(tl,24,tl);
3153     emit_writebyte_indexed(tl,-3,temp);
3154     if(rs2[i]) emit_rorimm(tl,8,tl);
3155   }
3156   else if (opcode[i]==0x2E) { // SWR
3157     // Write entire word
3158     emit_writeword_indexed(tl,-3,temp);
3159   }
3160   set_jump_target(done0, out);
3161   set_jump_target(done1, out);
3162   set_jump_target(done2, out);
3163   if(!c||!memtarget)
3164     add_stub_r(STORELR_STUB,jaddr,out,i,temp,i_regs,ccadj[i],reglist);
3165   if(!(i_regs->waswritten&(1<<rs1[i])) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3166     emit_addimm_no_flags(-ram_offset,temp);
3167     #if defined(HOST_IMM8)
3168     int ir=get_reg(i_regs->regmap,INVCP);
3169     assert(ir>=0);
3170     emit_cmpmem_indexedsr12_reg(ir,temp,1);
3171     #else
3172     emit_cmpmem_indexedsr12_imm(invalid_code,temp,1);
3173     #endif
3174     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3175     emit_callne(invalidate_addr_reg[temp]);
3176     #else
3177     void *jaddr2 = out;
3178     emit_jne(0);
3179     add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),temp,0,0,0);
3180     #endif
3181   }
3182 }
3183
3184 static void cop0_assemble(int i,struct regstat *i_regs)
3185 {
3186   if(opcode2[i]==0) // MFC0
3187   {
3188     signed char t=get_reg(i_regs->regmap,rt1[i]);
3189     u_int copr=(source[i]>>11)&0x1f;
3190     //assert(t>=0); // Why does this happen?  OOT is weird
3191     if(t>=0&&rt1[i]!=0) {
3192       emit_readword(&reg_cop0[copr],t);
3193     }
3194   }
3195   else if(opcode2[i]==4) // MTC0
3196   {
3197     signed char s=get_reg(i_regs->regmap,rs1[i]);
3198     char copr=(source[i]>>11)&0x1f;
3199     assert(s>=0);
3200     wb_register(rs1[i],i_regs->regmap,i_regs->dirty);
3201     if(copr==9||copr==11||copr==12||copr==13) {
3202       emit_readword(&last_count,HOST_TEMPREG);
3203       emit_loadreg(CCREG,HOST_CCREG); // TODO: do proper reg alloc
3204       emit_add(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3205       emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG);
3206       emit_writeword(HOST_CCREG,&Count);
3207     }
3208     // What a mess.  The status register (12) can enable interrupts,
3209     // so needs a special case to handle a pending interrupt.
3210     // The interrupt must be taken immediately, because a subsequent
3211     // instruction might disable interrupts again.
3212     if(copr==12||copr==13) {
3213       if (is_delayslot) {
3214         // burn cycles to cause cc_interrupt, which will
3215         // reschedule next_interupt. Relies on CCREG from above.
3216         assem_debug("MTC0 DS %d\n", copr);
3217         emit_writeword(HOST_CCREG,&last_count);
3218         emit_movimm(0,HOST_CCREG);
3219         emit_storereg(CCREG,HOST_CCREG);
3220         emit_loadreg(rs1[i],1);
3221         emit_movimm(copr,0);
3222         emit_far_call(pcsx_mtc0_ds);
3223         emit_loadreg(rs1[i],s);
3224         return;
3225       }
3226       emit_movimm(start+i*4+4,HOST_TEMPREG);
3227       emit_writeword(HOST_TEMPREG,&pcaddr);
3228       emit_movimm(0,HOST_TEMPREG);
3229       emit_writeword(HOST_TEMPREG,&pending_exception);
3230     }
3231     if(s==HOST_CCREG)
3232       emit_loadreg(rs1[i],1);
3233     else if(s!=1)
3234       emit_mov(s,1);
3235     emit_movimm(copr,0);
3236     emit_far_call(pcsx_mtc0);
3237     if(copr==9||copr==11||copr==12||copr==13) {
3238       emit_readword(&Count,HOST_CCREG);
3239       emit_readword(&next_interupt,HOST_TEMPREG);
3240       emit_addimm(HOST_CCREG,-CLOCK_ADJUST(ccadj[i]),HOST_CCREG);
3241       emit_sub(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3242       emit_writeword(HOST_TEMPREG,&last_count);
3243       emit_storereg(CCREG,HOST_CCREG);
3244     }
3245     if(copr==12||copr==13) {
3246       assert(!is_delayslot);
3247       emit_readword(&pending_exception,14);
3248       emit_test(14,14);
3249       void *jaddr = out;
3250       emit_jeq(0);
3251       emit_readword(&pcaddr, 0);
3252       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3253       emit_far_call(get_addr_ht);
3254       emit_jmpreg(0);
3255       set_jump_target(jaddr, out);
3256     }
3257     emit_loadreg(rs1[i],s);
3258   }
3259   else
3260   {
3261     assert(opcode2[i]==0x10);
3262     //if((source[i]&0x3f)==0x10) // RFE
3263     {
3264       emit_readword(&Status,0);
3265       emit_andimm(0,0x3c,1);
3266       emit_andimm(0,~0xf,0);
3267       emit_orrshr_imm(1,2,0);
3268       emit_writeword(0,&Status);
3269     }
3270   }
3271 }
3272
3273 static void cop1_unusable(int i,struct regstat *i_regs)
3274 {
3275   // XXX: should just just do the exception instead
3276   //if(!cop1_usable)
3277   {
3278     void *jaddr=out;
3279     emit_jmp(0);
3280     add_stub_r(FP_STUB,jaddr,out,i,0,i_regs,is_delayslot,0);
3281   }
3282 }
3283
3284 static void cop1_assemble(int i,struct regstat *i_regs)
3285 {
3286   cop1_unusable(i, i_regs);
3287 }
3288
3289 static void c1ls_assemble(int i,struct regstat *i_regs)
3290 {
3291   cop1_unusable(i, i_regs);
3292 }
3293
3294 // FP_STUB
3295 static void do_cop1stub(int n)
3296 {
3297   literal_pool(256);
3298   assem_debug("do_cop1stub %x\n",start+stubs[n].a*4);
3299   set_jump_target(stubs[n].addr, out);
3300   int i=stubs[n].a;
3301 //  int rs=stubs[n].b;
3302   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3303   int ds=stubs[n].d;
3304   if(!ds) {
3305     load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3306     //if(i_regs!=&regs[i]) printf("oops: regs[i]=%x i_regs=%x",(int)&regs[i],(int)i_regs);
3307   }
3308   //else {printf("fp exception in delay slot\n");}
3309   wb_dirtys(i_regs->regmap_entry,i_regs->wasdirty);
3310   if(regs[i].regmap_entry[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
3311   emit_movimm(start+(i-ds)*4,EAX); // Get PC
3312   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG); // CHECK: is this right?  There should probably be an extra cycle...
3313   emit_far_jump(ds?fp_exception_ds:fp_exception);
3314 }
3315
3316 static int cop2_is_stalling_op(int i, int *cycles)
3317 {
3318   if (opcode[i] == 0x3a) { // SWC2
3319     *cycles = 0;
3320     return 1;
3321   }
3322   if (itype[i] == COP2 && (opcode2[i] == 0 || opcode2[i] == 2)) { // MFC2/CFC2
3323     *cycles = 0;
3324     return 1;
3325   }
3326   if (itype[i] == C2OP) {
3327     *cycles = gte_cycletab[source[i] & 0x3f];
3328     return 1;
3329   }
3330   // ... what about MTC2/CTC2/LWC2?
3331   return 0;
3332 }
3333
3334 #if 0
3335 static void log_gte_stall(int stall, u_int cycle)
3336 {
3337   if ((u_int)stall <= 44)
3338     printf("x    stall %2d %u\n", stall, cycle + last_count);
3339 }
3340
3341 static void emit_log_gte_stall(int i, int stall, u_int reglist)
3342 {
3343   save_regs(reglist);
3344   if (stall > 0)
3345     emit_movimm(stall, 0);
3346   else
3347     emit_mov(HOST_TEMPREG, 0);
3348   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]), 1);
3349   emit_far_call(log_gte_stall);
3350   restore_regs(reglist);
3351 }
3352 #endif
3353
3354 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist)
3355 {
3356   int j = i, other_gte_op_cycles = -1, stall = -MAXBLOCK, cycles_passed;
3357   int rtmp = reglist_find_free(reglist);
3358
3359   if (HACK_ENABLED(NDHACK_NO_STALLS))
3360     return;
3361   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3362     // happens occasionally... cc evicted? Don't bother then
3363     //printf("no cc %08x\n", start + i*4);
3364     return;
3365   }
3366   if (!bt[i]) {
3367     for (j = i - 1; j >= 0; j--) {
3368       //if (is_ds[j]) break;
3369       if (cop2_is_stalling_op(j, &other_gte_op_cycles) || bt[j])
3370         break;
3371     }
3372     j = max(j, 0);
3373   }
3374   cycles_passed = CLOCK_ADJUST(ccadj[i] - ccadj[j]);
3375   if (other_gte_op_cycles >= 0)
3376     stall = other_gte_op_cycles - cycles_passed;
3377   else if (cycles_passed >= 44)
3378     stall = 0; // can't stall
3379   if (stall == -MAXBLOCK && rtmp >= 0) {
3380     // unknown stall, do the expensive runtime check
3381     assem_debug("; cop2_do_stall_check\n");
3382 #if 0 // too slow
3383     save_regs(reglist);
3384     emit_movimm(gte_cycletab[op], 0);
3385     emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]), 1);
3386     emit_far_call(call_gteStall);
3387     restore_regs(reglist);
3388 #else
3389     host_tempreg_acquire();
3390     emit_readword(&psxRegs.gteBusyCycle, rtmp);
3391     emit_addimm(rtmp, -CLOCK_ADJUST(ccadj[i]), rtmp);
3392     emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3393     emit_cmpimm(HOST_TEMPREG, 44);
3394     emit_cmovb_reg(rtmp, HOST_CCREG);
3395     //emit_log_gte_stall(i, 0, reglist);
3396     host_tempreg_release();
3397 #endif
3398   }
3399   else if (stall > 0) {
3400     //emit_log_gte_stall(i, stall, reglist);
3401     emit_addimm(HOST_CCREG, stall, HOST_CCREG);
3402   }
3403
3404   // save gteBusyCycle, if needed
3405   if (gte_cycletab[op] == 0)
3406     return;
3407   other_gte_op_cycles = -1;
3408   for (j = i + 1; j < slen; j++) {
3409     if (cop2_is_stalling_op(j, &other_gte_op_cycles))
3410       break;
3411     if (is_jump(j)) {
3412       // check ds
3413       if (j + 1 < slen && cop2_is_stalling_op(j + 1, &other_gte_op_cycles))
3414         j++;
3415       break;
3416     }
3417   }
3418   if (other_gte_op_cycles >= 0)
3419     // will handle stall when assembling that op
3420     return;
3421   cycles_passed = CLOCK_ADJUST(ccadj[min(j, slen -1)] - ccadj[i]);
3422   if (cycles_passed >= 44)
3423     return;
3424   assem_debug("; save gteBusyCycle\n");
3425   host_tempreg_acquire();
3426 #if 0
3427   emit_readword(&last_count, HOST_TEMPREG);
3428   emit_add(HOST_TEMPREG, HOST_CCREG, HOST_TEMPREG);
3429   emit_addimm(HOST_TEMPREG, CLOCK_ADJUST(ccadj[i]), HOST_TEMPREG);
3430   emit_addimm(HOST_TEMPREG, gte_cycletab[op]), HOST_TEMPREG);
3431   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3432 #else
3433   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]) + gte_cycletab[op], HOST_TEMPREG);
3434   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3435 #endif
3436   host_tempreg_release();
3437 }
3438
3439 static int is_mflohi(int i)
3440 {
3441   return (itype[i] == MOV && (rs1[i] == HIREG || rs1[i] == LOREG));
3442 }
3443
3444 static int check_multdiv(int i, int *cycles)
3445 {
3446   if (itype[i] != MULTDIV)
3447     return 0;
3448   if (opcode2[i] == 0x18 || opcode2[i] == 0x19) // MULT(U)
3449     *cycles = 11; // approx from 7 11 14
3450   else
3451     *cycles = 37;
3452   return 1;
3453 }
3454
3455 static void multdiv_prepare_stall(int i, const struct regstat *i_regs)
3456 {
3457   int j, found = 0, c = 0;
3458   if (HACK_ENABLED(NDHACK_NO_STALLS))
3459     return;
3460   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3461     // happens occasionally... cc evicted? Don't bother then
3462     return;
3463   }
3464   for (j = i + 1; j < slen; j++) {
3465     if (bt[j])
3466       break;
3467     if ((found = is_mflohi(j)))
3468       break;
3469     if (is_jump(j)) {
3470       // check ds
3471       if (j + 1 < slen && (found = is_mflohi(j + 1)))
3472         j++;
3473       break;
3474     }
3475   }
3476   if (found)
3477     // handle all in multdiv_do_stall()
3478     return;
3479   check_multdiv(i, &c);
3480   assert(c > 0);
3481   assem_debug("; muldiv prepare stall %d\n", c);
3482   host_tempreg_acquire();
3483   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]) + c, HOST_TEMPREG);
3484   emit_writeword(HOST_TEMPREG, &psxRegs.muldivBusyCycle);
3485   host_tempreg_release();
3486 }
3487
3488 static void multdiv_do_stall(int i, const struct regstat *i_regs)
3489 {
3490   int j, known_cycles = 0;
3491   u_int reglist = get_host_reglist(i_regs->regmap);
3492   int rtmp = get_reg(i_regs->regmap, -1);
3493   if (rtmp < 0)
3494     rtmp = reglist_find_free(reglist);
3495   if (HACK_ENABLED(NDHACK_NO_STALLS))
3496     return;
3497   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG || rtmp < 0) {
3498     // happens occasionally... cc evicted? Don't bother then
3499     //printf("no cc/rtmp %08x\n", start + i*4);
3500     return;
3501   }
3502   if (!bt[i]) {
3503     for (j = i - 1; j >= 0; j--) {
3504       if (is_ds[j]) break;
3505       if (check_multdiv(j, &known_cycles) || bt[j])
3506         break;
3507       if (is_mflohi(j))
3508         // already handled by this op
3509         return;
3510     }
3511     j = max(j, 0);
3512   }
3513   if (known_cycles > 0) {
3514     known_cycles -= CLOCK_ADJUST(ccadj[i] - ccadj[j]);
3515     assem_debug("; muldiv stall resolved %d\n", known_cycles);
3516     if (known_cycles > 0)
3517       emit_addimm(HOST_CCREG, known_cycles, HOST_CCREG);
3518     return;
3519   }
3520   assem_debug("; muldiv stall unresolved\n");
3521   host_tempreg_acquire();
3522   emit_readword(&psxRegs.muldivBusyCycle, rtmp);
3523   emit_addimm(rtmp, -CLOCK_ADJUST(ccadj[i]), rtmp);
3524   emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3525   emit_cmpimm(HOST_TEMPREG, 37);
3526   emit_cmovb_reg(rtmp, HOST_CCREG);
3527   //emit_log_gte_stall(i, 0, reglist);
3528   host_tempreg_release();
3529 }
3530
3531 static void cop2_get_dreg(u_int copr,signed char tl,signed char temp)
3532 {
3533   switch (copr) {
3534     case 1:
3535     case 3:
3536     case 5:
3537     case 8:
3538     case 9:
3539     case 10:
3540     case 11:
3541       emit_readword(&reg_cop2d[copr],tl);
3542       emit_signextend16(tl,tl);
3543       emit_writeword(tl,&reg_cop2d[copr]); // hmh
3544       break;
3545     case 7:
3546     case 16:
3547     case 17:
3548     case 18:
3549     case 19:
3550       emit_readword(&reg_cop2d[copr],tl);
3551       emit_andimm(tl,0xffff,tl);
3552       emit_writeword(tl,&reg_cop2d[copr]);
3553       break;
3554     case 15:
3555       emit_readword(&reg_cop2d[14],tl); // SXY2
3556       emit_writeword(tl,&reg_cop2d[copr]);
3557       break;
3558     case 28:
3559     case 29:
3560       c2op_mfc2_29_assemble(tl,temp);
3561       break;
3562     default:
3563       emit_readword(&reg_cop2d[copr],tl);
3564       break;
3565   }
3566 }
3567
3568 static void cop2_put_dreg(u_int copr,signed char sl,signed char temp)
3569 {
3570   switch (copr) {
3571     case 15:
3572       emit_readword(&reg_cop2d[13],temp);  // SXY1
3573       emit_writeword(sl,&reg_cop2d[copr]);
3574       emit_writeword(temp,&reg_cop2d[12]); // SXY0
3575       emit_readword(&reg_cop2d[14],temp);  // SXY2
3576       emit_writeword(sl,&reg_cop2d[14]);
3577       emit_writeword(temp,&reg_cop2d[13]); // SXY1
3578       break;
3579     case 28:
3580       emit_andimm(sl,0x001f,temp);
3581       emit_shlimm(temp,7,temp);
3582       emit_writeword(temp,&reg_cop2d[9]);
3583       emit_andimm(sl,0x03e0,temp);
3584       emit_shlimm(temp,2,temp);
3585       emit_writeword(temp,&reg_cop2d[10]);
3586       emit_andimm(sl,0x7c00,temp);
3587       emit_shrimm(temp,3,temp);
3588       emit_writeword(temp,&reg_cop2d[11]);
3589       emit_writeword(sl,&reg_cop2d[28]);
3590       break;
3591     case 30:
3592       emit_xorsar_imm(sl,sl,31,temp);
3593 #if defined(HAVE_ARMV5) || defined(__aarch64__)
3594       emit_clz(temp,temp);
3595 #else
3596       emit_movs(temp,HOST_TEMPREG);
3597       emit_movimm(0,temp);
3598       emit_jeq((int)out+4*4);
3599       emit_addpl_imm(temp,1,temp);
3600       emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
3601       emit_jns((int)out-2*4);
3602 #endif
3603       emit_writeword(sl,&reg_cop2d[30]);
3604       emit_writeword(temp,&reg_cop2d[31]);
3605       break;
3606     case 31:
3607       break;
3608     default:
3609       emit_writeword(sl,&reg_cop2d[copr]);
3610       break;
3611   }
3612 }
3613
3614 static void c2ls_assemble(int i, const struct regstat *i_regs)
3615 {
3616   int s,tl;
3617   int ar;
3618   int offset;
3619   int memtarget=0,c=0;
3620   void *jaddr2=NULL;
3621   enum stub_type type;
3622   int agr=AGEN1+(i&1);
3623   int fastio_reg_override=-1;
3624   u_int reglist=get_host_reglist(i_regs->regmap);
3625   u_int copr=(source[i]>>16)&0x1f;
3626   s=get_reg(i_regs->regmap,rs1[i]);
3627   tl=get_reg(i_regs->regmap,FTEMP);
3628   offset=imm[i];
3629   assert(rs1[i]>0);
3630   assert(tl>=0);
3631
3632   if(i_regs->regmap[HOST_CCREG]==CCREG)
3633     reglist&=~(1<<HOST_CCREG);
3634
3635   // get the address
3636   if (opcode[i]==0x3a) { // SWC2
3637     ar=get_reg(i_regs->regmap,agr);
3638     if(ar<0) ar=get_reg(i_regs->regmap,-1);
3639     reglist|=1<<ar;
3640   } else { // LWC2
3641     ar=tl;
3642   }
3643   if(s>=0) c=(i_regs->wasconst>>s)&1;
3644   memtarget=c&&(((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE);
3645   if (!offset&&!c&&s>=0) ar=s;
3646   assert(ar>=0);
3647
3648   cop2_do_stall_check(0, i, i_regs, reglist);
3649
3650   if (opcode[i]==0x3a) { // SWC2
3651     cop2_get_dreg(copr,tl,-1);
3652     type=STOREW_STUB;
3653   }
3654   else
3655     type=LOADW_STUB;
3656
3657   if(c&&!memtarget) {
3658     jaddr2=out;
3659     emit_jmp(0); // inline_readstub/inline_writestub?
3660   }
3661   else {
3662     if(!c) {
3663       jaddr2=emit_fastpath_cmp_jump(i,ar,&fastio_reg_override);
3664     }
3665     else if(ram_offset&&memtarget) {
3666       host_tempreg_acquire();
3667       emit_addimm(ar,ram_offset,HOST_TEMPREG);
3668       fastio_reg_override=HOST_TEMPREG;
3669     }
3670     if (opcode[i]==0x32) { // LWC2
3671       int a=ar;
3672       if(fastio_reg_override>=0) a=fastio_reg_override;
3673       emit_readword_indexed(0,a,tl);
3674     }
3675     if (opcode[i]==0x3a) { // SWC2
3676       #ifdef DESTRUCTIVE_SHIFT
3677       if(!offset&&!c&&s>=0) emit_mov(s,ar);
3678       #endif
3679       int a=ar;
3680       if(fastio_reg_override>=0) a=fastio_reg_override;
3681       emit_writeword_indexed(tl,0,a);
3682     }
3683   }
3684   if(fastio_reg_override==HOST_TEMPREG)
3685     host_tempreg_release();
3686   if(jaddr2)
3687     add_stub_r(type,jaddr2,out,i,ar,i_regs,ccadj[i],reglist);
3688   if(opcode[i]==0x3a) // SWC2
3689   if(!(i_regs->waswritten&(1<<rs1[i])) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3690 #if defined(HOST_IMM8)
3691     int ir=get_reg(i_regs->regmap,INVCP);
3692     assert(ir>=0);
3693     emit_cmpmem_indexedsr12_reg(ir,ar,1);
3694 #else
3695     emit_cmpmem_indexedsr12_imm(invalid_code,ar,1);
3696 #endif
3697     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3698     emit_callne(invalidate_addr_reg[ar]);
3699     #else
3700     void *jaddr3 = out;
3701     emit_jne(0);
3702     add_stub(INVCODE_STUB,jaddr3,out,reglist|(1<<HOST_CCREG),ar,0,0,0);
3703     #endif
3704   }
3705   if (opcode[i]==0x32) { // LWC2
3706     host_tempreg_acquire();
3707     cop2_put_dreg(copr,tl,HOST_TEMPREG);
3708     host_tempreg_release();
3709   }
3710 }
3711
3712 static void cop2_assemble(int i, const struct regstat *i_regs)
3713 {
3714   u_int copr = (source[i]>>11) & 0x1f;
3715   signed char temp = get_reg(i_regs->regmap, -1);
3716
3717   if (!HACK_ENABLED(NDHACK_NO_STALLS)) {
3718     u_int reglist = reglist_exclude(get_host_reglist(i_regs->regmap), temp, -1);
3719     if (opcode2[i] == 0 || opcode2[i] == 2) { // MFC2/CFC2
3720       signed char tl = get_reg(i_regs->regmap, rt1[i]);
3721       reglist = reglist_exclude(reglist, tl, -1);
3722     }
3723     cop2_do_stall_check(0, i, i_regs, reglist);
3724   }
3725   if (opcode2[i]==0) { // MFC2
3726     signed char tl=get_reg(i_regs->regmap,rt1[i]);
3727     if(tl>=0&&rt1[i]!=0)
3728       cop2_get_dreg(copr,tl,temp);
3729   }
3730   else if (opcode2[i]==4) { // MTC2
3731     signed char sl=get_reg(i_regs->regmap,rs1[i]);
3732     cop2_put_dreg(copr,sl,temp);
3733   }
3734   else if (opcode2[i]==2) // CFC2
3735   {
3736     signed char tl=get_reg(i_regs->regmap,rt1[i]);
3737     if(tl>=0&&rt1[i]!=0)
3738       emit_readword(&reg_cop2c[copr],tl);
3739   }
3740   else if (opcode2[i]==6) // CTC2
3741   {
3742     signed char sl=get_reg(i_regs->regmap,rs1[i]);
3743     switch(copr) {
3744       case 4:
3745       case 12:
3746       case 20:
3747       case 26:
3748       case 27:
3749       case 29:
3750       case 30:
3751         emit_signextend16(sl,temp);
3752         break;
3753       case 31:
3754         c2op_ctc2_31_assemble(sl,temp);
3755         break;
3756       default:
3757         temp=sl;
3758         break;
3759     }
3760     emit_writeword(temp,&reg_cop2c[copr]);
3761     assert(sl>=0);
3762   }
3763 }
3764
3765 static void do_unalignedwritestub(int n)
3766 {
3767   assem_debug("do_unalignedwritestub %x\n",start+stubs[n].a*4);
3768   literal_pool(256);
3769   set_jump_target(stubs[n].addr, out);
3770
3771   int i=stubs[n].a;
3772   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3773   int addr=stubs[n].b;
3774   u_int reglist=stubs[n].e;
3775   signed char *i_regmap=i_regs->regmap;
3776   int temp2=get_reg(i_regmap,FTEMP);
3777   int rt;
3778   rt=get_reg(i_regmap,rs2[i]);
3779   assert(rt>=0);
3780   assert(addr>=0);
3781   assert(opcode[i]==0x2a||opcode[i]==0x2e); // SWL/SWR only implemented
3782   reglist|=(1<<addr);
3783   reglist&=~(1<<temp2);
3784
3785 #if 1
3786   // don't bother with it and call write handler
3787   save_regs(reglist);
3788   pass_args(addr,rt);
3789   int cc=get_reg(i_regmap,CCREG);
3790   if(cc<0)
3791     emit_loadreg(CCREG,2);
3792   emit_addimm(cc<0?2:cc,CLOCK_ADJUST((int)stubs[n].d+1),2);
3793   emit_far_call((opcode[i]==0x2a?jump_handle_swl:jump_handle_swr));
3794   emit_addimm(0,-CLOCK_ADJUST((int)stubs[n].d+1),cc<0?2:cc);
3795   if(cc<0)
3796     emit_storereg(CCREG,2);
3797   restore_regs(reglist);
3798   emit_jmp(stubs[n].retaddr); // return address
3799 #else
3800   emit_andimm(addr,0xfffffffc,temp2);
3801   emit_writeword(temp2,&address);
3802
3803   save_regs(reglist);
3804   emit_shrimm(addr,16,1);
3805   int cc=get_reg(i_regmap,CCREG);
3806   if(cc<0) {
3807     emit_loadreg(CCREG,2);
3808   }
3809   emit_movimm((u_int)readmem,0);
3810   emit_addimm(cc<0?2:cc,2*stubs[n].d+2,2);
3811   emit_call((int)&indirect_jump_indexed);
3812   restore_regs(reglist);
3813
3814   emit_readword(&readmem_dword,temp2);
3815   int temp=addr; //hmh
3816   emit_shlimm(addr,3,temp);
3817   emit_andimm(temp,24,temp);
3818   if (opcode[i]==0x2a) // SWL
3819     emit_xorimm(temp,24,temp);
3820   emit_movimm(-1,HOST_TEMPREG);
3821   if (opcode[i]==0x2a) { // SWL
3822     emit_bic_lsr(temp2,HOST_TEMPREG,temp,temp2);
3823     emit_orrshr(rt,temp,temp2);
3824   }else{
3825     emit_bic_lsl(temp2,HOST_TEMPREG,temp,temp2);
3826     emit_orrshl(rt,temp,temp2);
3827   }
3828   emit_readword(&address,addr);
3829   emit_writeword(temp2,&word);
3830   //save_regs(reglist); // don't need to, no state changes
3831   emit_shrimm(addr,16,1);
3832   emit_movimm((u_int)writemem,0);
3833   //emit_call((int)&indirect_jump_indexed);
3834   emit_mov(15,14);
3835   emit_readword_dualindexedx4(0,1,15);
3836   emit_readword(&Count,HOST_TEMPREG);
3837   emit_readword(&next_interupt,2);
3838   emit_addimm(HOST_TEMPREG,-2*stubs[n].d-2,HOST_TEMPREG);
3839   emit_writeword(2,&last_count);
3840   emit_sub(HOST_TEMPREG,2,cc<0?HOST_TEMPREG:cc);
3841   if(cc<0) {
3842     emit_storereg(CCREG,HOST_TEMPREG);
3843   }
3844   restore_regs(reglist);
3845   emit_jmp(stubs[n].retaddr); // return address
3846 #endif
3847 }
3848
3849 #ifndef multdiv_assemble
3850 void multdiv_assemble(int i,struct regstat *i_regs)
3851 {
3852   printf("Need multdiv_assemble for this architecture.\n");
3853   abort();
3854 }
3855 #endif
3856
3857 static void mov_assemble(int i,struct regstat *i_regs)
3858 {
3859   //if(opcode2[i]==0x10||opcode2[i]==0x12) { // MFHI/MFLO
3860   //if(opcode2[i]==0x11||opcode2[i]==0x13) { // MTHI/MTLO
3861   if(rt1[i]) {
3862     signed char sl,tl;
3863     tl=get_reg(i_regs->regmap,rt1[i]);
3864     //assert(tl>=0);
3865     if(tl>=0) {
3866       sl=get_reg(i_regs->regmap,rs1[i]);
3867       if(sl>=0) emit_mov(sl,tl);
3868       else emit_loadreg(rs1[i],tl);
3869     }
3870   }
3871   if (rs1[i] == HIREG || rs1[i] == LOREG) // MFHI/MFLO
3872     multdiv_do_stall(i, i_regs);
3873 }
3874
3875 // call interpreter, exception handler, things that change pc/regs/cycles ...
3876 static void call_c_cpu_handler(int i, const struct regstat *i_regs, u_int pc, void *func)
3877 {
3878   signed char ccreg=get_reg(i_regs->regmap,CCREG);
3879   assert(ccreg==HOST_CCREG);
3880   assert(!is_delayslot);
3881   (void)ccreg;
3882
3883   emit_movimm(pc,3); // Get PC
3884   emit_readword(&last_count,2);
3885   emit_writeword(3,&psxRegs.pc);
3886   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG); // XXX
3887   emit_add(2,HOST_CCREG,2);
3888   emit_writeword(2,&psxRegs.cycle);
3889   emit_far_call(func);
3890   emit_far_jump(jump_to_new_pc);
3891 }
3892
3893 static void syscall_assemble(int i,struct regstat *i_regs)
3894 {
3895   emit_movimm(0x20,0); // cause code
3896   emit_movimm(0,1);    // not in delay slot
3897   call_c_cpu_handler(i,i_regs,start+i*4,psxException);
3898 }
3899
3900 static void hlecall_assemble(int i,struct regstat *i_regs)
3901 {
3902   void *hlefunc = psxNULL;
3903   uint32_t hleCode = source[i] & 0x03ffffff;
3904   if (hleCode < ARRAY_SIZE(psxHLEt))
3905     hlefunc = psxHLEt[hleCode];
3906
3907   call_c_cpu_handler(i,i_regs,start+i*4+4,hlefunc);
3908 }
3909
3910 static void intcall_assemble(int i,struct regstat *i_regs)
3911 {
3912   call_c_cpu_handler(i,i_regs,start+i*4,execI);
3913 }
3914
3915 static void speculate_mov(int rs,int rt)
3916 {
3917   if(rt!=0) {
3918     smrv_strong_next|=1<<rt;
3919     smrv[rt]=smrv[rs];
3920   }
3921 }
3922
3923 static void speculate_mov_weak(int rs,int rt)
3924 {
3925   if(rt!=0) {
3926     smrv_weak_next|=1<<rt;
3927     smrv[rt]=smrv[rs];
3928   }
3929 }
3930
3931 static void speculate_register_values(int i)
3932 {
3933   if(i==0) {
3934     memcpy(smrv,psxRegs.GPR.r,sizeof(smrv));
3935     // gp,sp are likely to stay the same throughout the block
3936     smrv_strong_next=(1<<28)|(1<<29)|(1<<30);
3937     smrv_weak_next=~smrv_strong_next;
3938     //printf(" llr %08x\n", smrv[4]);
3939   }
3940   smrv_strong=smrv_strong_next;
3941   smrv_weak=smrv_weak_next;
3942   switch(itype[i]) {
3943     case ALU:
3944       if     ((smrv_strong>>rs1[i])&1) speculate_mov(rs1[i],rt1[i]);
3945       else if((smrv_strong>>rs2[i])&1) speculate_mov(rs2[i],rt1[i]);
3946       else if((smrv_weak>>rs1[i])&1) speculate_mov_weak(rs1[i],rt1[i]);
3947       else if((smrv_weak>>rs2[i])&1) speculate_mov_weak(rs2[i],rt1[i]);
3948       else {
3949         smrv_strong_next&=~(1<<rt1[i]);
3950         smrv_weak_next&=~(1<<rt1[i]);
3951       }
3952       break;
3953     case SHIFTIMM:
3954       smrv_strong_next&=~(1<<rt1[i]);
3955       smrv_weak_next&=~(1<<rt1[i]);
3956       // fallthrough
3957     case IMM16:
3958       if(rt1[i]&&is_const(&regs[i],rt1[i])) {
3959         int value,hr=get_reg(regs[i].regmap,rt1[i]);
3960         if(hr>=0) {
3961           if(get_final_value(hr,i,&value))
3962                smrv[rt1[i]]=value;
3963           else smrv[rt1[i]]=constmap[i][hr];
3964           smrv_strong_next|=1<<rt1[i];
3965         }
3966       }
3967       else {
3968         if     ((smrv_strong>>rs1[i])&1) speculate_mov(rs1[i],rt1[i]);
3969         else if((smrv_weak>>rs1[i])&1) speculate_mov_weak(rs1[i],rt1[i]);
3970       }
3971       break;
3972     case LOAD:
3973       if(start<0x2000&&(rt1[i]==26||(smrv[rt1[i]]>>24)==0xa0)) {
3974         // special case for BIOS
3975         smrv[rt1[i]]=0xa0000000;
3976         smrv_strong_next|=1<<rt1[i];
3977         break;
3978       }
3979       // fallthrough
3980     case SHIFT:
3981     case LOADLR:
3982     case MOV:
3983       smrv_strong_next&=~(1<<rt1[i]);
3984       smrv_weak_next&=~(1<<rt1[i]);
3985       break;
3986     case COP0:
3987     case COP2:
3988       if(opcode2[i]==0||opcode2[i]==2) { // MFC/CFC
3989         smrv_strong_next&=~(1<<rt1[i]);
3990         smrv_weak_next&=~(1<<rt1[i]);
3991       }
3992       break;
3993     case C2LS:
3994       if (opcode[i]==0x32) { // LWC2
3995         smrv_strong_next&=~(1<<rt1[i]);
3996         smrv_weak_next&=~(1<<rt1[i]);
3997       }
3998       break;
3999   }
4000 #if 0
4001   int r=4;
4002   printf("x %08x %08x %d %d c %08x %08x\n",smrv[r],start+i*4,
4003     ((smrv_strong>>r)&1),(smrv_weak>>r)&1,regs[i].isconst,regs[i].wasconst);
4004 #endif
4005 }
4006
4007 static void ds_assemble(int i,struct regstat *i_regs)
4008 {
4009   speculate_register_values(i);
4010   is_delayslot=1;
4011   switch(itype[i]) {
4012     case ALU:
4013       alu_assemble(i,i_regs);break;
4014     case IMM16:
4015       imm16_assemble(i,i_regs);break;
4016     case SHIFT:
4017       shift_assemble(i,i_regs);break;
4018     case SHIFTIMM:
4019       shiftimm_assemble(i,i_regs);break;
4020     case LOAD:
4021       load_assemble(i,i_regs);break;
4022     case LOADLR:
4023       loadlr_assemble(i,i_regs);break;
4024     case STORE:
4025       store_assemble(i,i_regs);break;
4026     case STORELR:
4027       storelr_assemble(i,i_regs);break;
4028     case COP0:
4029       cop0_assemble(i,i_regs);break;
4030     case COP1:
4031       cop1_assemble(i,i_regs);break;
4032     case C1LS:
4033       c1ls_assemble(i,i_regs);break;
4034     case COP2:
4035       cop2_assemble(i,i_regs);break;
4036     case C2LS:
4037       c2ls_assemble(i,i_regs);break;
4038     case C2OP:
4039       c2op_assemble(i,i_regs);break;
4040     case MULTDIV:
4041       multdiv_assemble(i,i_regs);
4042       multdiv_prepare_stall(i,i_regs);
4043       break;
4044     case MOV:
4045       mov_assemble(i,i_regs);break;
4046     case SYSCALL:
4047     case HLECALL:
4048     case INTCALL:
4049     case SPAN:
4050     case UJUMP:
4051     case RJUMP:
4052     case CJUMP:
4053     case SJUMP:
4054       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4055   }
4056   is_delayslot=0;
4057 }
4058
4059 // Is the branch target a valid internal jump?
4060 static int internal_branch(int addr)
4061 {
4062   if(addr&1) return 0; // Indirect (register) jump
4063   if(addr>=start && addr<start+slen*4-4)
4064   {
4065     return 1;
4066   }
4067   return 0;
4068 }
4069
4070 static void wb_invalidate(signed char pre[],signed char entry[],uint64_t dirty,uint64_t u)
4071 {
4072   int hr;
4073   for(hr=0;hr<HOST_REGS;hr++) {
4074     if(hr!=EXCLUDE_REG) {
4075       if(pre[hr]!=entry[hr]) {
4076         if(pre[hr]>=0) {
4077           if((dirty>>hr)&1) {
4078             if(get_reg(entry,pre[hr])<0) {
4079               assert(pre[hr]<64);
4080               if(!((u>>pre[hr])&1))
4081                 emit_storereg(pre[hr],hr);
4082             }
4083           }
4084         }
4085       }
4086     }
4087   }
4088   // Move from one register to another (no writeback)
4089   for(hr=0;hr<HOST_REGS;hr++) {
4090     if(hr!=EXCLUDE_REG) {
4091       if(pre[hr]!=entry[hr]) {
4092         if(pre[hr]>=0&&(pre[hr]&63)<TEMPREG) {
4093           int nr;
4094           if((nr=get_reg(entry,pre[hr]))>=0) {
4095             emit_mov(hr,nr);
4096           }
4097         }
4098       }
4099     }
4100   }
4101 }
4102
4103 // Load the specified registers
4104 // This only loads the registers given as arguments because
4105 // we don't want to load things that will be overwritten
4106 static void load_regs(signed char entry[],signed char regmap[],int rs1,int rs2)
4107 {
4108   int hr;
4109   // Load 32-bit regs
4110   for(hr=0;hr<HOST_REGS;hr++) {
4111     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4112       if(entry[hr]!=regmap[hr]) {
4113         if(regmap[hr]==rs1||regmap[hr]==rs2)
4114         {
4115           if(regmap[hr]==0) {
4116             emit_zeroreg(hr);
4117           }
4118           else
4119           {
4120             emit_loadreg(regmap[hr],hr);
4121           }
4122         }
4123       }
4124     }
4125   }
4126 }
4127
4128 // Load registers prior to the start of a loop
4129 // so that they are not loaded within the loop
4130 static void loop_preload(signed char pre[],signed char entry[])
4131 {
4132   int hr;
4133   for(hr=0;hr<HOST_REGS;hr++) {
4134     if(hr!=EXCLUDE_REG) {
4135       if(pre[hr]!=entry[hr]) {
4136         if(entry[hr]>=0) {
4137           if(get_reg(pre,entry[hr])<0) {
4138             assem_debug("loop preload:\n");
4139             //printf("loop preload: %d\n",hr);
4140             if(entry[hr]==0) {
4141               emit_zeroreg(hr);
4142             }
4143             else if(entry[hr]<TEMPREG)
4144             {
4145               emit_loadreg(entry[hr],hr);
4146             }
4147             else if(entry[hr]-64<TEMPREG)
4148             {
4149               emit_loadreg(entry[hr],hr);
4150             }
4151           }
4152         }
4153       }
4154     }
4155   }
4156 }
4157
4158 // Generate address for load/store instruction
4159 // goes to AGEN for writes, FTEMP for LOADLR and cop1/2 loads
4160 void address_generation(int i,struct regstat *i_regs,signed char entry[])
4161 {
4162   if(itype[i]==LOAD||itype[i]==LOADLR||itype[i]==STORE||itype[i]==STORELR||itype[i]==C1LS||itype[i]==C2LS) {
4163     int ra=-1;
4164     int agr=AGEN1+(i&1);
4165     if(itype[i]==LOAD) {
4166       ra=get_reg(i_regs->regmap,rt1[i]);
4167       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4168       assert(ra>=0);
4169     }
4170     if(itype[i]==LOADLR) {
4171       ra=get_reg(i_regs->regmap,FTEMP);
4172     }
4173     if(itype[i]==STORE||itype[i]==STORELR) {
4174       ra=get_reg(i_regs->regmap,agr);
4175       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4176     }
4177     if(itype[i]==C1LS||itype[i]==C2LS) {
4178       if ((opcode[i]&0x3b)==0x31||(opcode[i]&0x3b)==0x32) // LWC1/LDC1/LWC2/LDC2
4179         ra=get_reg(i_regs->regmap,FTEMP);
4180       else { // SWC1/SDC1/SWC2/SDC2
4181         ra=get_reg(i_regs->regmap,agr);
4182         if(ra<0) ra=get_reg(i_regs->regmap,-1);
4183       }
4184     }
4185     int rs=get_reg(i_regs->regmap,rs1[i]);
4186     if(ra>=0) {
4187       int offset=imm[i];
4188       int c=(i_regs->wasconst>>rs)&1;
4189       if(rs1[i]==0) {
4190         // Using r0 as a base address
4191         if(!entry||entry[ra]!=agr) {
4192           if (opcode[i]==0x22||opcode[i]==0x26) {
4193             emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4194           }else if (opcode[i]==0x1a||opcode[i]==0x1b) {
4195             emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4196           }else{
4197             emit_movimm(offset,ra);
4198           }
4199         } // else did it in the previous cycle
4200       }
4201       else if(rs<0) {
4202         if(!entry||entry[ra]!=rs1[i])
4203           emit_loadreg(rs1[i],ra);
4204         //if(!entry||entry[ra]!=rs1[i])
4205         //  printf("poor load scheduling!\n");
4206       }
4207       else if(c) {
4208         if(rs1[i]!=rt1[i]||itype[i]!=LOAD) {
4209           if(!entry||entry[ra]!=agr) {
4210             if (opcode[i]==0x22||opcode[i]==0x26) {
4211               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4212             }else if (opcode[i]==0x1a||opcode[i]==0x1b) {
4213               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4214             }else{
4215               emit_movimm(constmap[i][rs]+offset,ra);
4216               regs[i].loadedconst|=1<<ra;
4217             }
4218           } // else did it in the previous cycle
4219         } // else load_consts already did it
4220       }
4221       if(offset&&!c&&rs1[i]) {
4222         if(rs>=0) {
4223           emit_addimm(rs,offset,ra);
4224         }else{
4225           emit_addimm(ra,offset,ra);
4226         }
4227       }
4228     }
4229   }
4230   // Preload constants for next instruction
4231   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) {
4232     int agr,ra;
4233     // Actual address
4234     agr=AGEN1+((i+1)&1);
4235     ra=get_reg(i_regs->regmap,agr);
4236     if(ra>=0) {
4237       int rs=get_reg(regs[i+1].regmap,rs1[i+1]);
4238       int offset=imm[i+1];
4239       int c=(regs[i+1].wasconst>>rs)&1;
4240       if(c&&(rs1[i+1]!=rt1[i+1]||itype[i+1]!=LOAD)) {
4241         if (opcode[i+1]==0x22||opcode[i+1]==0x26) {
4242           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4243         }else if (opcode[i+1]==0x1a||opcode[i+1]==0x1b) {
4244           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4245         }else{
4246           emit_movimm(constmap[i+1][rs]+offset,ra);
4247           regs[i+1].loadedconst|=1<<ra;
4248         }
4249       }
4250       else if(rs1[i+1]==0) {
4251         // Using r0 as a base address
4252         if (opcode[i+1]==0x22||opcode[i+1]==0x26) {
4253           emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4254         }else if (opcode[i+1]==0x1a||opcode[i+1]==0x1b) {
4255           emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4256         }else{
4257           emit_movimm(offset,ra);
4258         }
4259       }
4260     }
4261   }
4262 }
4263
4264 static int get_final_value(int hr, int i, int *value)
4265 {
4266   int reg=regs[i].regmap[hr];
4267   while(i<slen-1) {
4268     if(regs[i+1].regmap[hr]!=reg) break;
4269     if(!((regs[i+1].isconst>>hr)&1)) break;
4270     if(bt[i+1]) break;
4271     i++;
4272   }
4273   if(i<slen-1) {
4274     if(itype[i]==UJUMP||itype[i]==RJUMP||itype[i]==CJUMP||itype[i]==SJUMP) {
4275       *value=constmap[i][hr];
4276       return 1;
4277     }
4278     if(!bt[i+1]) {
4279       if(itype[i+1]==UJUMP||itype[i+1]==RJUMP||itype[i+1]==CJUMP||itype[i+1]==SJUMP) {
4280         // Load in delay slot, out-of-order execution
4281         if(itype[i+2]==LOAD&&rs1[i+2]==reg&&rt1[i+2]==reg&&((regs[i+1].wasconst>>hr)&1))
4282         {
4283           // Precompute load address
4284           *value=constmap[i][hr]+imm[i+2];
4285           return 1;
4286         }
4287       }
4288       if(itype[i+1]==LOAD&&rs1[i+1]==reg&&rt1[i+1]==reg)
4289       {
4290         // Precompute load address
4291         *value=constmap[i][hr]+imm[i+1];
4292         //printf("c=%x imm=%lx\n",(long)constmap[i][hr],imm[i+1]);
4293         return 1;
4294       }
4295     }
4296   }
4297   *value=constmap[i][hr];
4298   //printf("c=%lx\n",(long)constmap[i][hr]);
4299   if(i==slen-1) return 1;
4300   assert(reg < 64);
4301   return !((unneeded_reg[i+1]>>reg)&1);
4302 }
4303
4304 // Load registers with known constants
4305 static void load_consts(signed char pre[],signed char regmap[],int i)
4306 {
4307   int hr,hr2;
4308   // propagate loaded constant flags
4309   if(i==0||bt[i])
4310     regs[i].loadedconst=0;
4311   else {
4312     for(hr=0;hr<HOST_REGS;hr++) {
4313       if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((regs[i-1].isconst>>hr)&1)&&pre[hr]==regmap[hr]
4314          &&regmap[hr]==regs[i-1].regmap[hr]&&((regs[i-1].loadedconst>>hr)&1))
4315       {
4316         regs[i].loadedconst|=1<<hr;
4317       }
4318     }
4319   }
4320   // Load 32-bit regs
4321   for(hr=0;hr<HOST_REGS;hr++) {
4322     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4323       //if(entry[hr]!=regmap[hr]) {
4324       if(!((regs[i].loadedconst>>hr)&1)) {
4325         assert(regmap[hr]<64);
4326         if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4327           int value,similar=0;
4328           if(get_final_value(hr,i,&value)) {
4329             // see if some other register has similar value
4330             for(hr2=0;hr2<HOST_REGS;hr2++) {
4331               if(hr2!=EXCLUDE_REG&&((regs[i].loadedconst>>hr2)&1)) {
4332                 if(is_similar_value(value,constmap[i][hr2])) {
4333                   similar=1;
4334                   break;
4335                 }
4336               }
4337             }
4338             if(similar) {
4339               int value2;
4340               if(get_final_value(hr2,i,&value2)) // is this needed?
4341                 emit_movimm_from(value2,hr2,value,hr);
4342               else
4343                 emit_movimm(value,hr);
4344             }
4345             else if(value==0) {
4346               emit_zeroreg(hr);
4347             }
4348             else {
4349               emit_movimm(value,hr);
4350             }
4351           }
4352           regs[i].loadedconst|=1<<hr;
4353         }
4354       }
4355     }
4356   }
4357 }
4358
4359 void load_all_consts(signed char regmap[], u_int dirty, int i)
4360 {
4361   int hr;
4362   // Load 32-bit regs
4363   for(hr=0;hr<HOST_REGS;hr++) {
4364     if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((dirty>>hr)&1)) {
4365       assert(regmap[hr] < 64);
4366       if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4367         int value=constmap[i][hr];
4368         if(value==0) {
4369           emit_zeroreg(hr);
4370         }
4371         else {
4372           emit_movimm(value,hr);
4373         }
4374       }
4375     }
4376   }
4377 }
4378
4379 // Write out all dirty registers (except cycle count)
4380 static void wb_dirtys(signed char i_regmap[],uint64_t i_dirty)
4381 {
4382   int hr;
4383   for(hr=0;hr<HOST_REGS;hr++) {
4384     if(hr!=EXCLUDE_REG) {
4385       if(i_regmap[hr]>0) {
4386         if(i_regmap[hr]!=CCREG) {
4387           if((i_dirty>>hr)&1) {
4388             assert(i_regmap[hr]<64);
4389             emit_storereg(i_regmap[hr],hr);
4390           }
4391         }
4392       }
4393     }
4394   }
4395 }
4396
4397 // Write out dirty registers that we need to reload (pair with load_needed_regs)
4398 // This writes the registers not written by store_regs_bt
4399 void wb_needed_dirtys(signed char i_regmap[],uint64_t i_dirty,int addr)
4400 {
4401   int hr;
4402   int t=(addr-start)>>2;
4403   for(hr=0;hr<HOST_REGS;hr++) {
4404     if(hr!=EXCLUDE_REG) {
4405       if(i_regmap[hr]>0) {
4406         if(i_regmap[hr]!=CCREG) {
4407           if(i_regmap[hr]==regs[t].regmap_entry[hr] && ((regs[t].dirty>>hr)&1)) {
4408             if((i_dirty>>hr)&1) {
4409               assert(i_regmap[hr]<64);
4410               emit_storereg(i_regmap[hr],hr);
4411             }
4412           }
4413         }
4414       }
4415     }
4416   }
4417 }
4418
4419 // Load all registers (except cycle count)
4420 void load_all_regs(signed char i_regmap[])
4421 {
4422   int hr;
4423   for(hr=0;hr<HOST_REGS;hr++) {
4424     if(hr!=EXCLUDE_REG) {
4425       if(i_regmap[hr]==0) {
4426         emit_zeroreg(hr);
4427       }
4428       else
4429       if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4430       {
4431         emit_loadreg(i_regmap[hr],hr);
4432       }
4433     }
4434   }
4435 }
4436
4437 // Load all current registers also needed by next instruction
4438 void load_needed_regs(signed char i_regmap[],signed char next_regmap[])
4439 {
4440   int hr;
4441   for(hr=0;hr<HOST_REGS;hr++) {
4442     if(hr!=EXCLUDE_REG) {
4443       if(get_reg(next_regmap,i_regmap[hr])>=0) {
4444         if(i_regmap[hr]==0) {
4445           emit_zeroreg(hr);
4446         }
4447         else
4448         if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4449         {
4450           emit_loadreg(i_regmap[hr],hr);
4451         }
4452       }
4453     }
4454   }
4455 }
4456
4457 // Load all regs, storing cycle count if necessary
4458 void load_regs_entry(int t)
4459 {
4460   int hr;
4461   if(is_ds[t]) emit_addimm(HOST_CCREG,CLOCK_ADJUST(1),HOST_CCREG);
4462   else if(ccadj[t]) emit_addimm(HOST_CCREG,-CLOCK_ADJUST(ccadj[t]),HOST_CCREG);
4463   if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4464     emit_storereg(CCREG,HOST_CCREG);
4465   }
4466   // Load 32-bit regs
4467   for(hr=0;hr<HOST_REGS;hr++) {
4468     if(regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4469       if(regs[t].regmap_entry[hr]==0) {
4470         emit_zeroreg(hr);
4471       }
4472       else if(regs[t].regmap_entry[hr]!=CCREG)
4473       {
4474         emit_loadreg(regs[t].regmap_entry[hr],hr);
4475       }
4476     }
4477   }
4478 }
4479
4480 // Store dirty registers prior to branch
4481 void store_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4482 {
4483   if(internal_branch(addr))
4484   {
4485     int t=(addr-start)>>2;
4486     int hr;
4487     for(hr=0;hr<HOST_REGS;hr++) {
4488       if(hr!=EXCLUDE_REG) {
4489         if(i_regmap[hr]>0 && i_regmap[hr]!=CCREG) {
4490           if(i_regmap[hr]!=regs[t].regmap_entry[hr] || !((regs[t].dirty>>hr)&1)) {
4491             if((i_dirty>>hr)&1) {
4492               assert(i_regmap[hr]<64);
4493               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4494                 emit_storereg(i_regmap[hr],hr);
4495             }
4496           }
4497         }
4498       }
4499     }
4500   }
4501   else
4502   {
4503     // Branch out of this block, write out all dirty regs
4504     wb_dirtys(i_regmap,i_dirty);
4505   }
4506 }
4507
4508 // Load all needed registers for branch target
4509 static void load_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4510 {
4511   //if(addr>=start && addr<(start+slen*4))
4512   if(internal_branch(addr))
4513   {
4514     int t=(addr-start)>>2;
4515     int hr;
4516     // Store the cycle count before loading something else
4517     if(i_regmap[HOST_CCREG]!=CCREG) {
4518       assert(i_regmap[HOST_CCREG]==-1);
4519     }
4520     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4521       emit_storereg(CCREG,HOST_CCREG);
4522     }
4523     // Load 32-bit regs
4524     for(hr=0;hr<HOST_REGS;hr++) {
4525       if(hr!=EXCLUDE_REG&&regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4526         if(i_regmap[hr]!=regs[t].regmap_entry[hr]) {
4527           if(regs[t].regmap_entry[hr]==0) {
4528             emit_zeroreg(hr);
4529           }
4530           else if(regs[t].regmap_entry[hr]!=CCREG)
4531           {
4532             emit_loadreg(regs[t].regmap_entry[hr],hr);
4533           }
4534         }
4535       }
4536     }
4537   }
4538 }
4539
4540 static int match_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4541 {
4542   if(addr>=start && addr<start+slen*4-4)
4543   {
4544     int t=(addr-start)>>2;
4545     int hr;
4546     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) return 0;
4547     for(hr=0;hr<HOST_REGS;hr++)
4548     {
4549       if(hr!=EXCLUDE_REG)
4550       {
4551         if(i_regmap[hr]!=regs[t].regmap_entry[hr])
4552         {
4553           if(regs[t].regmap_entry[hr]>=0&&(regs[t].regmap_entry[hr]|64)<TEMPREG+64)
4554           {
4555             return 0;
4556           }
4557           else
4558           if((i_dirty>>hr)&1)
4559           {
4560             if(i_regmap[hr]<TEMPREG)
4561             {
4562               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4563                 return 0;
4564             }
4565             else if(i_regmap[hr]>=64&&i_regmap[hr]<TEMPREG+64)
4566             {
4567               assert(0);
4568             }
4569           }
4570         }
4571         else // Same register but is it 32-bit or dirty?
4572         if(i_regmap[hr]>=0)
4573         {
4574           if(!((regs[t].dirty>>hr)&1))
4575           {
4576             if((i_dirty>>hr)&1)
4577             {
4578               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4579               {
4580                 //printf("%x: dirty no match\n",addr);
4581                 return 0;
4582               }
4583             }
4584           }
4585         }
4586       }
4587     }
4588     // Delay slots are not valid branch targets
4589     //if(t>0&&(itype[t-1]==RJUMP||itype[t-1]==UJUMP||itype[t-1]==CJUMP||itype[t-1]==SJUMP)) return 0;
4590     // Delay slots require additional processing, so do not match
4591     if(is_ds[t]) return 0;
4592   }
4593   else
4594   {
4595     int hr;
4596     for(hr=0;hr<HOST_REGS;hr++)
4597     {
4598       if(hr!=EXCLUDE_REG)
4599       {
4600         if(i_regmap[hr]>=0)
4601         {
4602           if(hr!=HOST_CCREG||i_regmap[hr]!=CCREG)
4603           {
4604             if((i_dirty>>hr)&1)
4605             {
4606               return 0;
4607             }
4608           }
4609         }
4610       }
4611     }
4612   }
4613   return 1;
4614 }
4615
4616 #ifdef DRC_DBG
4617 static void drc_dbg_emit_do_cmp(int i)
4618 {
4619   extern void do_insn_cmp();
4620   //extern int cycle;
4621   u_int hr, reglist = get_host_reglist(regs[i].regmap);
4622
4623   assem_debug("//do_insn_cmp %08x\n", start+i*4);
4624   save_regs(reglist);
4625   // write out changed consts to match the interpreter
4626   if (i > 0 && !bt[i]) {
4627     for (hr = 0; hr < HOST_REGS; hr++) {
4628       int reg = regs[i-1].regmap[hr];
4629       if (hr == EXCLUDE_REG || reg < 0)
4630         continue;
4631       if (!((regs[i-1].isconst >> hr) & 1))
4632         continue;
4633       if (i > 1 && reg == regs[i-2].regmap[hr] && constmap[i-1][hr] == constmap[i-2][hr])
4634         continue;
4635       emit_movimm(constmap[i-1][hr],0);
4636       emit_storereg(reg, 0);
4637     }
4638   }
4639   emit_movimm(start+i*4,0);
4640   emit_writeword(0,&pcaddr);
4641   emit_far_call(do_insn_cmp);
4642   //emit_readword(&cycle,0);
4643   //emit_addimm(0,2,0);
4644   //emit_writeword(0,&cycle);
4645   (void)get_reg2;
4646   restore_regs(reglist);
4647   assem_debug("\\\\do_insn_cmp\n");
4648 }
4649 #else
4650 #define drc_dbg_emit_do_cmp(x)
4651 #endif
4652
4653 // Used when a branch jumps into the delay slot of another branch
4654 static void ds_assemble_entry(int i)
4655 {
4656   int t=(ba[i]-start)>>2;
4657   if (!instr_addr[t])
4658     instr_addr[t] = out;
4659   assem_debug("Assemble delay slot at %x\n",ba[i]);
4660   assem_debug("<->\n");
4661   drc_dbg_emit_do_cmp(t);
4662   if(regs[t].regmap_entry[HOST_CCREG]==CCREG&&regs[t].regmap[HOST_CCREG]!=CCREG)
4663     wb_register(CCREG,regs[t].regmap_entry,regs[t].wasdirty);
4664   load_regs(regs[t].regmap_entry,regs[t].regmap,rs1[t],rs2[t]);
4665   address_generation(t,&regs[t],regs[t].regmap_entry);
4666   if(itype[t]==STORE||itype[t]==STORELR||(opcode[t]&0x3b)==0x39||(opcode[t]&0x3b)==0x3a)
4667     load_regs(regs[t].regmap_entry,regs[t].regmap,INVCP,INVCP);
4668   is_delayslot=0;
4669   switch(itype[t]) {
4670     case ALU:
4671       alu_assemble(t,&regs[t]);break;
4672     case IMM16:
4673       imm16_assemble(t,&regs[t]);break;
4674     case SHIFT:
4675       shift_assemble(t,&regs[t]);break;
4676     case SHIFTIMM:
4677       shiftimm_assemble(t,&regs[t]);break;
4678     case LOAD:
4679       load_assemble(t,&regs[t]);break;
4680     case LOADLR:
4681       loadlr_assemble(t,&regs[t]);break;
4682     case STORE:
4683       store_assemble(t,&regs[t]);break;
4684     case STORELR:
4685       storelr_assemble(t,&regs[t]);break;
4686     case COP0:
4687       cop0_assemble(t,&regs[t]);break;
4688     case COP1:
4689       cop1_assemble(t,&regs[t]);break;
4690     case C1LS:
4691       c1ls_assemble(t,&regs[t]);break;
4692     case COP2:
4693       cop2_assemble(t,&regs[t]);break;
4694     case C2LS:
4695       c2ls_assemble(t,&regs[t]);break;
4696     case C2OP:
4697       c2op_assemble(t,&regs[t]);break;
4698     case MULTDIV:
4699       multdiv_assemble(t,&regs[t]);
4700       multdiv_prepare_stall(i,&regs[t]);
4701       break;
4702     case MOV:
4703       mov_assemble(t,&regs[t]);break;
4704     case SYSCALL:
4705     case HLECALL:
4706     case INTCALL:
4707     case SPAN:
4708     case UJUMP:
4709     case RJUMP:
4710     case CJUMP:
4711     case SJUMP:
4712       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4713   }
4714   store_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4715   load_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4716   if(internal_branch(ba[i]+4))
4717     assem_debug("branch: internal\n");
4718   else
4719     assem_debug("branch: external\n");
4720   assert(internal_branch(ba[i]+4));
4721   add_to_linker(out,ba[i]+4,internal_branch(ba[i]+4));
4722   emit_jmp(0);
4723 }
4724
4725 static void emit_extjump(void *addr, u_int target)
4726 {
4727   emit_extjump2(addr, target, dyna_linker);
4728 }
4729
4730 static void emit_extjump_ds(void *addr, u_int target)
4731 {
4732   emit_extjump2(addr, target, dyna_linker_ds);
4733 }
4734
4735 // Load 2 immediates optimizing for small code size
4736 static void emit_mov2imm_compact(int imm1,u_int rt1,int imm2,u_int rt2)
4737 {
4738   emit_movimm(imm1,rt1);
4739   emit_movimm_from(imm1,rt1,imm2,rt2);
4740 }
4741
4742 void do_cc(int i,signed char i_regmap[],int *adj,int addr,int taken,int invert)
4743 {
4744   int count;
4745   void *jaddr;
4746   void *idle=NULL;
4747   int t=0;
4748   if(itype[i]==RJUMP)
4749   {
4750     *adj=0;
4751   }
4752   //if(ba[i]>=start && ba[i]<(start+slen*4))
4753   if(internal_branch(ba[i]))
4754   {
4755     t=(ba[i]-start)>>2;
4756     if(is_ds[t]) *adj=-1; // Branch into delay slot adds an extra cycle
4757     else *adj=ccadj[t];
4758   }
4759   else
4760   {
4761     *adj=0;
4762   }
4763   count=ccadj[i];
4764   if(taken==TAKEN && i==(ba[i]-start)>>2 && source[i+1]==0) {
4765     // Idle loop
4766     if(count&1) emit_addimm_and_set_flags(2*(count+2),HOST_CCREG);
4767     idle=out;
4768     //emit_subfrommem(&idlecount,HOST_CCREG); // Count idle cycles
4769     emit_andimm(HOST_CCREG,3,HOST_CCREG);
4770     jaddr=out;
4771     emit_jmp(0);
4772   }
4773   else if(*adj==0||invert) {
4774     int cycles=CLOCK_ADJUST(count+2);
4775     // faster loop HACK
4776 #if 0
4777     if (t&&*adj) {
4778       int rel=t-i;
4779       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
4780         cycles=CLOCK_ADJUST(*adj)+count+2-*adj;
4781     }
4782 #endif
4783     emit_addimm_and_set_flags(cycles,HOST_CCREG);
4784     jaddr=out;
4785     emit_jns(0);
4786   }
4787   else
4788   {
4789     emit_cmpimm(HOST_CCREG,-CLOCK_ADJUST(count+2));
4790     jaddr=out;
4791     emit_jns(0);
4792   }
4793   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:(count+2),i,addr,taken,0);
4794 }
4795
4796 static void do_ccstub(int n)
4797 {
4798   literal_pool(256);
4799   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
4800   set_jump_target(stubs[n].addr, out);
4801   int i=stubs[n].b;
4802   if(stubs[n].d==NULLDS) {
4803     // Delay slot instruction is nullified ("likely" branch)
4804     wb_dirtys(regs[i].regmap,regs[i].dirty);
4805   }
4806   else if(stubs[n].d!=TAKEN) {
4807     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
4808   }
4809   else {
4810     if(internal_branch(ba[i]))
4811       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4812   }
4813   if(stubs[n].c!=-1)
4814   {
4815     // Save PC as return address
4816     emit_movimm(stubs[n].c,EAX);
4817     emit_writeword(EAX,&pcaddr);
4818   }
4819   else
4820   {
4821     // Return address depends on which way the branch goes
4822     if(itype[i]==CJUMP||itype[i]==SJUMP)
4823     {
4824       int s1l=get_reg(branch_regs[i].regmap,rs1[i]);
4825       int s2l=get_reg(branch_regs[i].regmap,rs2[i]);
4826       if(rs1[i]==0)
4827       {
4828         s1l=s2l;
4829         s2l=-1;
4830       }
4831       else if(rs2[i]==0)
4832       {
4833         s2l=-1;
4834       }
4835       assert(s1l>=0);
4836       #ifdef DESTRUCTIVE_WRITEBACK
4837       if(rs1[i]) {
4838         if((branch_regs[i].dirty>>s1l)&&1)
4839           emit_loadreg(rs1[i],s1l);
4840       }
4841       else {
4842         if((branch_regs[i].dirty>>s1l)&1)
4843           emit_loadreg(rs2[i],s1l);
4844       }
4845       if(s2l>=0)
4846         if((branch_regs[i].dirty>>s2l)&1)
4847           emit_loadreg(rs2[i],s2l);
4848       #endif
4849       int hr=0;
4850       int addr=-1,alt=-1,ntaddr=-1;
4851       while(hr<HOST_REGS)
4852       {
4853         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4854            (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4855            (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4856         {
4857           addr=hr++;break;
4858         }
4859         hr++;
4860       }
4861       while(hr<HOST_REGS)
4862       {
4863         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4864            (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4865            (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4866         {
4867           alt=hr++;break;
4868         }
4869         hr++;
4870       }
4871       if((opcode[i]&0x2E)==6) // BLEZ/BGTZ needs another register
4872       {
4873         while(hr<HOST_REGS)
4874         {
4875           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4876              (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4877              (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4878           {
4879             ntaddr=hr;break;
4880           }
4881           hr++;
4882         }
4883         assert(hr<HOST_REGS);
4884       }
4885       if((opcode[i]&0x2f)==4) // BEQ
4886       {
4887         #ifdef HAVE_CMOV_IMM
4888         if(s2l>=0) emit_cmp(s1l,s2l);
4889         else emit_test(s1l,s1l);
4890         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
4891         #else
4892         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4893         if(s2l>=0) emit_cmp(s1l,s2l);
4894         else emit_test(s1l,s1l);
4895         emit_cmovne_reg(alt,addr);
4896         #endif
4897       }
4898       if((opcode[i]&0x2f)==5) // BNE
4899       {
4900         #ifdef HAVE_CMOV_IMM
4901         if(s2l>=0) emit_cmp(s1l,s2l);
4902         else emit_test(s1l,s1l);
4903         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
4904         #else
4905         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
4906         if(s2l>=0) emit_cmp(s1l,s2l);
4907         else emit_test(s1l,s1l);
4908         emit_cmovne_reg(alt,addr);
4909         #endif
4910       }
4911       if((opcode[i]&0x2f)==6) // BLEZ
4912       {
4913         //emit_movimm(ba[i],alt);
4914         //emit_movimm(start+i*4+8,addr);
4915         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4916         emit_cmpimm(s1l,1);
4917         emit_cmovl_reg(alt,addr);
4918       }
4919       if((opcode[i]&0x2f)==7) // BGTZ
4920       {
4921         //emit_movimm(ba[i],addr);
4922         //emit_movimm(start+i*4+8,ntaddr);
4923         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
4924         emit_cmpimm(s1l,1);
4925         emit_cmovl_reg(ntaddr,addr);
4926       }
4927       if((opcode[i]==1)&&(opcode2[i]&0x2D)==0) // BLTZ
4928       {
4929         //emit_movimm(ba[i],alt);
4930         //emit_movimm(start+i*4+8,addr);
4931         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4932         emit_test(s1l,s1l);
4933         emit_cmovs_reg(alt,addr);
4934       }
4935       if((opcode[i]==1)&&(opcode2[i]&0x2D)==1) // BGEZ
4936       {
4937         //emit_movimm(ba[i],addr);
4938         //emit_movimm(start+i*4+8,alt);
4939         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4940         emit_test(s1l,s1l);
4941         emit_cmovs_reg(alt,addr);
4942       }
4943       if(opcode[i]==0x11 && opcode2[i]==0x08 ) {
4944         if(source[i]&0x10000) // BC1T
4945         {
4946           //emit_movimm(ba[i],alt);
4947           //emit_movimm(start+i*4+8,addr);
4948           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4949           emit_testimm(s1l,0x800000);
4950           emit_cmovne_reg(alt,addr);
4951         }
4952         else // BC1F
4953         {
4954           //emit_movimm(ba[i],addr);
4955           //emit_movimm(start+i*4+8,alt);
4956           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4957           emit_testimm(s1l,0x800000);
4958           emit_cmovne_reg(alt,addr);
4959         }
4960       }
4961       emit_writeword(addr,&pcaddr);
4962     }
4963     else
4964     if(itype[i]==RJUMP)
4965     {
4966       int r=get_reg(branch_regs[i].regmap,rs1[i]);
4967       if(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]) {
4968         r=get_reg(branch_regs[i].regmap,RTEMP);
4969       }
4970       emit_writeword(r,&pcaddr);
4971     }
4972     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
4973   }
4974   // Update cycle count
4975   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
4976   if(stubs[n].a) emit_addimm(HOST_CCREG,CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4977   emit_far_call(cc_interrupt);
4978   if(stubs[n].a) emit_addimm(HOST_CCREG,-CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4979   if(stubs[n].d==TAKEN) {
4980     if(internal_branch(ba[i]))
4981       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
4982     else if(itype[i]==RJUMP) {
4983       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
4984         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
4985       else
4986         emit_loadreg(rs1[i],get_reg(branch_regs[i].regmap,rs1[i]));
4987     }
4988   }else if(stubs[n].d==NOTTAKEN) {
4989     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
4990     else load_all_regs(branch_regs[i].regmap);
4991   }else if(stubs[n].d==NULLDS) {
4992     // Delay slot instruction is nullified ("likely" branch)
4993     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
4994     else load_all_regs(regs[i].regmap);
4995   }else{
4996     load_all_regs(branch_regs[i].regmap);
4997   }
4998   if (stubs[n].retaddr)
4999     emit_jmp(stubs[n].retaddr);
5000   else
5001     do_jump_vaddr(stubs[n].e);
5002 }
5003
5004 static void add_to_linker(void *addr, u_int target, int ext)
5005 {
5006   assert(linkcount < ARRAY_SIZE(link_addr));
5007   link_addr[linkcount].addr = addr;
5008   link_addr[linkcount].target = target;
5009   link_addr[linkcount].ext = ext;
5010   linkcount++;
5011 }
5012
5013 static void ujump_assemble_write_ra(int i)
5014 {
5015   int rt;
5016   unsigned int return_address;
5017   rt=get_reg(branch_regs[i].regmap,31);
5018   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]);
5019   //assert(rt>=0);
5020   return_address=start+i*4+8;
5021   if(rt>=0) {
5022     #ifdef USE_MINI_HT
5023     if(internal_branch(return_address)&&rt1[i+1]!=31) {
5024       int temp=-1; // note: must be ds-safe
5025       #ifdef HOST_TEMPREG
5026       temp=HOST_TEMPREG;
5027       #endif
5028       if(temp>=0) do_miniht_insert(return_address,rt,temp);
5029       else emit_movimm(return_address,rt);
5030     }
5031     else
5032     #endif
5033     {
5034       #ifdef REG_PREFETCH
5035       if(temp>=0)
5036       {
5037         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5038       }
5039       #endif
5040       emit_movimm(return_address,rt); // PC into link register
5041       #ifdef IMM_PREFETCH
5042       emit_prefetch(hash_table_get(return_address));
5043       #endif
5044     }
5045   }
5046 }
5047
5048 static void ujump_assemble(int i,struct regstat *i_regs)
5049 {
5050   int ra_done=0;
5051   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5052   address_generation(i+1,i_regs,regs[i].regmap_entry);
5053   #ifdef REG_PREFETCH
5054   int temp=get_reg(branch_regs[i].regmap,PTEMP);
5055   if(rt1[i]==31&&temp>=0)
5056   {
5057     signed char *i_regmap=i_regs->regmap;
5058     int return_address=start+i*4+8;
5059     if(get_reg(branch_regs[i].regmap,31)>0)
5060     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5061   }
5062   #endif
5063   if(rt1[i]==31&&(rt1[i]==rs1[i+1]||rt1[i]==rs2[i+1])) {
5064     ujump_assemble_write_ra(i); // writeback ra for DS
5065     ra_done=1;
5066   }
5067   ds_assemble(i+1,i_regs);
5068   uint64_t bc_unneeded=branch_regs[i].u;
5069   bc_unneeded|=1|(1LL<<rt1[i]);
5070   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5071   load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5072   if(!ra_done&&rt1[i]==31)
5073     ujump_assemble_write_ra(i);
5074   int cc,adj;
5075   cc=get_reg(branch_regs[i].regmap,CCREG);
5076   assert(cc==HOST_CCREG);
5077   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5078   #ifdef REG_PREFETCH
5079   if(rt1[i]==31&&temp>=0) emit_prefetchreg(temp);
5080   #endif
5081   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5082   if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5083   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5084   if(internal_branch(ba[i]))
5085     assem_debug("branch: internal\n");
5086   else
5087     assem_debug("branch: external\n");
5088   if(internal_branch(ba[i])&&is_ds[(ba[i]-start)>>2]) {
5089     ds_assemble_entry(i);
5090   }
5091   else {
5092     add_to_linker(out,ba[i],internal_branch(ba[i]));
5093     emit_jmp(0);
5094   }
5095 }
5096
5097 static void rjump_assemble_write_ra(int i)
5098 {
5099   int rt,return_address;
5100   assert(rt1[i+1]!=rt1[i]);
5101   assert(rt2[i+1]!=rt1[i]);
5102   rt=get_reg(branch_regs[i].regmap,rt1[i]);
5103   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]);
5104   assert(rt>=0);
5105   return_address=start+i*4+8;
5106   #ifdef REG_PREFETCH
5107   if(temp>=0)
5108   {
5109     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5110   }
5111   #endif
5112   emit_movimm(return_address,rt); // PC into link register
5113   #ifdef IMM_PREFETCH
5114   emit_prefetch(hash_table_get(return_address));
5115   #endif
5116 }
5117
5118 static void rjump_assemble(int i,struct regstat *i_regs)
5119 {
5120   int temp;
5121   int rs,cc;
5122   int ra_done=0;
5123   rs=get_reg(branch_regs[i].regmap,rs1[i]);
5124   assert(rs>=0);
5125   if(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]) {
5126     // Delay slot abuse, make a copy of the branch address register
5127     temp=get_reg(branch_regs[i].regmap,RTEMP);
5128     assert(temp>=0);
5129     assert(regs[i].regmap[temp]==RTEMP);
5130     emit_mov(rs,temp);
5131     rs=temp;
5132   }
5133   address_generation(i+1,i_regs,regs[i].regmap_entry);
5134   #ifdef REG_PREFETCH
5135   if(rt1[i]==31)
5136   {
5137     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
5138       signed char *i_regmap=i_regs->regmap;
5139       int return_address=start+i*4+8;
5140       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5141     }
5142   }
5143   #endif
5144   #ifdef USE_MINI_HT
5145   if(rs1[i]==31) {
5146     int rh=get_reg(regs[i].regmap,RHASH);
5147     if(rh>=0) do_preload_rhash(rh);
5148   }
5149   #endif
5150   if(rt1[i]!=0&&(rt1[i]==rs1[i+1]||rt1[i]==rs2[i+1])) {
5151     rjump_assemble_write_ra(i);
5152     ra_done=1;
5153   }
5154   ds_assemble(i+1,i_regs);
5155   uint64_t bc_unneeded=branch_regs[i].u;
5156   bc_unneeded|=1|(1LL<<rt1[i]);
5157   bc_unneeded&=~(1LL<<rs1[i]);
5158   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5159   load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],CCREG);
5160   if(!ra_done&&rt1[i]!=0)
5161     rjump_assemble_write_ra(i);
5162   cc=get_reg(branch_regs[i].regmap,CCREG);
5163   assert(cc==HOST_CCREG);
5164   (void)cc;
5165   #ifdef USE_MINI_HT
5166   int rh=get_reg(branch_regs[i].regmap,RHASH);
5167   int ht=get_reg(branch_regs[i].regmap,RHTBL);
5168   if(rs1[i]==31) {
5169     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
5170     do_preload_rhtbl(ht);
5171     do_rhash(rs,rh);
5172   }
5173   #endif
5174   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5175   #ifdef DESTRUCTIVE_WRITEBACK
5176   if((branch_regs[i].dirty>>rs)&1) {
5177     if(rs1[i]!=rt1[i+1]&&rs1[i]!=rt2[i+1]) {
5178       emit_loadreg(rs1[i],rs);
5179     }
5180   }
5181   #endif
5182   #ifdef REG_PREFETCH
5183   if(rt1[i]==31&&temp>=0) emit_prefetchreg(temp);
5184   #endif
5185   #ifdef USE_MINI_HT
5186   if(rs1[i]==31) {
5187     do_miniht_load(ht,rh);
5188   }
5189   #endif
5190   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
5191   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
5192   //assert(adj==0);
5193   emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5194   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
5195   if(itype[i+1]==COP0&&(source[i+1]&0x3f)==0x10)
5196     // special case for RFE
5197     emit_jmp(0);
5198   else
5199     emit_jns(0);
5200   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5201   #ifdef USE_MINI_HT
5202   if(rs1[i]==31) {
5203     do_miniht_jump(rs,rh,ht);
5204   }
5205   else
5206   #endif
5207   {
5208     do_jump_vaddr(rs);
5209   }
5210   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5211   if(rt1[i]!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
5212   #endif
5213 }
5214
5215 static void cjump_assemble(int i,struct regstat *i_regs)
5216 {
5217   signed char *i_regmap=i_regs->regmap;
5218   int cc;
5219   int match;
5220   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5221   assem_debug("match=%d\n",match);
5222   int s1l,s2l;
5223   int unconditional=0,nop=0;
5224   int invert=0;
5225   int internal=internal_branch(ba[i]);
5226   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5227   if(!match) invert=1;
5228   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5229   if(i>(ba[i]-start)>>2) invert=1;
5230   #endif
5231   #ifdef __aarch64__
5232   invert=1; // because of near cond. branches
5233   #endif
5234
5235   if(ooo[i]) {
5236     s1l=get_reg(branch_regs[i].regmap,rs1[i]);
5237     s2l=get_reg(branch_regs[i].regmap,rs2[i]);
5238   }
5239   else {
5240     s1l=get_reg(i_regmap,rs1[i]);
5241     s2l=get_reg(i_regmap,rs2[i]);
5242   }
5243   if(rs1[i]==0&&rs2[i]==0)
5244   {
5245     if(opcode[i]&1) nop=1;
5246     else unconditional=1;
5247     //assert(opcode[i]!=5);
5248     //assert(opcode[i]!=7);
5249     //assert(opcode[i]!=0x15);
5250     //assert(opcode[i]!=0x17);
5251   }
5252   else if(rs1[i]==0)
5253   {
5254     s1l=s2l;
5255     s2l=-1;
5256   }
5257   else if(rs2[i]==0)
5258   {
5259     s2l=-1;
5260   }
5261
5262   if(ooo[i]) {
5263     // Out of order execution (delay slot first)
5264     //printf("OOOE\n");
5265     address_generation(i+1,i_regs,regs[i].regmap_entry);
5266     ds_assemble(i+1,i_regs);
5267     int adj;
5268     uint64_t bc_unneeded=branch_regs[i].u;
5269     bc_unneeded&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
5270     bc_unneeded|=1;
5271     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5272     load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],rs2[i]);
5273     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5274     cc=get_reg(branch_regs[i].regmap,CCREG);
5275     assert(cc==HOST_CCREG);
5276     if(unconditional)
5277       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5278     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5279     //assem_debug("cycle count (adj)\n");
5280     if(unconditional) {
5281       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5282       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5283         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5284         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5285         if(internal)
5286           assem_debug("branch: internal\n");
5287         else
5288           assem_debug("branch: external\n");
5289         if(internal&&is_ds[(ba[i]-start)>>2]) {
5290           ds_assemble_entry(i);
5291         }
5292         else {
5293           add_to_linker(out,ba[i],internal);
5294           emit_jmp(0);
5295         }
5296         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5297         if(((u_int)out)&7) emit_addnop(0);
5298         #endif
5299       }
5300     }
5301     else if(nop) {
5302       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5303       void *jaddr=out;
5304       emit_jns(0);
5305       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5306     }
5307     else {
5308       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5309       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5310       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5311
5312       //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]);
5313       assert(s1l>=0);
5314       if(opcode[i]==4) // BEQ
5315       {
5316         if(s2l>=0) emit_cmp(s1l,s2l);
5317         else emit_test(s1l,s1l);
5318         if(invert){
5319           nottaken=out;
5320           emit_jne(DJT_1);
5321         }else{
5322           add_to_linker(out,ba[i],internal);
5323           emit_jeq(0);
5324         }
5325       }
5326       if(opcode[i]==5) // BNE
5327       {
5328         if(s2l>=0) emit_cmp(s1l,s2l);
5329         else emit_test(s1l,s1l);
5330         if(invert){
5331           nottaken=out;
5332           emit_jeq(DJT_1);
5333         }else{
5334           add_to_linker(out,ba[i],internal);
5335           emit_jne(0);
5336         }
5337       }
5338       if(opcode[i]==6) // BLEZ
5339       {
5340         emit_cmpimm(s1l,1);
5341         if(invert){
5342           nottaken=out;
5343           emit_jge(DJT_1);
5344         }else{
5345           add_to_linker(out,ba[i],internal);
5346           emit_jl(0);
5347         }
5348       }
5349       if(opcode[i]==7) // BGTZ
5350       {
5351         emit_cmpimm(s1l,1);
5352         if(invert){
5353           nottaken=out;
5354           emit_jl(DJT_1);
5355         }else{
5356           add_to_linker(out,ba[i],internal);
5357           emit_jge(0);
5358         }
5359       }
5360       if(invert) {
5361         if(taken) set_jump_target(taken, out);
5362         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5363         if(match&&(!internal||!is_ds[(ba[i]-start)>>2])) {
5364           if(adj) {
5365             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5366             add_to_linker(out,ba[i],internal);
5367           }else{
5368             emit_addnop(13);
5369             add_to_linker(out,ba[i],internal*2);
5370           }
5371           emit_jmp(0);
5372         }else
5373         #endif
5374         {
5375           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5376           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5377           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5378           if(internal)
5379             assem_debug("branch: internal\n");
5380           else
5381             assem_debug("branch: external\n");
5382           if(internal&&is_ds[(ba[i]-start)>>2]) {
5383             ds_assemble_entry(i);
5384           }
5385           else {
5386             add_to_linker(out,ba[i],internal);
5387             emit_jmp(0);
5388           }
5389         }
5390         set_jump_target(nottaken, out);
5391       }
5392
5393       if(nottaken1) set_jump_target(nottaken1, out);
5394       if(adj) {
5395         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5396       }
5397     } // (!unconditional)
5398   } // if(ooo)
5399   else
5400   {
5401     // In-order execution (branch first)
5402     //if(likely[i]) printf("IOL\n");
5403     //else
5404     //printf("IOE\n");
5405     void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5406     if(!unconditional&&!nop) {
5407       //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]);
5408       assert(s1l>=0);
5409       if((opcode[i]&0x2f)==4) // BEQ
5410       {
5411         if(s2l>=0) emit_cmp(s1l,s2l);
5412         else emit_test(s1l,s1l);
5413         nottaken=out;
5414         emit_jne(DJT_2);
5415       }
5416       if((opcode[i]&0x2f)==5) // BNE
5417       {
5418         if(s2l>=0) emit_cmp(s1l,s2l);
5419         else emit_test(s1l,s1l);
5420         nottaken=out;
5421         emit_jeq(DJT_2);
5422       }
5423       if((opcode[i]&0x2f)==6) // BLEZ
5424       {
5425         emit_cmpimm(s1l,1);
5426         nottaken=out;
5427         emit_jge(DJT_2);
5428       }
5429       if((opcode[i]&0x2f)==7) // BGTZ
5430       {
5431         emit_cmpimm(s1l,1);
5432         nottaken=out;
5433         emit_jl(DJT_2);
5434       }
5435     } // if(!unconditional)
5436     int adj;
5437     uint64_t ds_unneeded=branch_regs[i].u;
5438     ds_unneeded&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5439     ds_unneeded|=1;
5440     // branch taken
5441     if(!nop) {
5442       if(taken) set_jump_target(taken, out);
5443       assem_debug("1:\n");
5444       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5445       // load regs
5446       load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5447       address_generation(i+1,&branch_regs[i],0);
5448       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5449       ds_assemble(i+1,&branch_regs[i]);
5450       cc=get_reg(branch_regs[i].regmap,CCREG);
5451       if(cc==-1) {
5452         emit_loadreg(CCREG,cc=HOST_CCREG);
5453         // CHECK: Is the following instruction (fall thru) allocated ok?
5454       }
5455       assert(cc==HOST_CCREG);
5456       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5457       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5458       assem_debug("cycle count (adj)\n");
5459       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5460       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5461       if(internal)
5462         assem_debug("branch: internal\n");
5463       else
5464         assem_debug("branch: external\n");
5465       if(internal&&is_ds[(ba[i]-start)>>2]) {
5466         ds_assemble_entry(i);
5467       }
5468       else {
5469         add_to_linker(out,ba[i],internal);
5470         emit_jmp(0);
5471       }
5472     }
5473     // branch not taken
5474     if(!unconditional) {
5475       if(nottaken1) set_jump_target(nottaken1, out);
5476       set_jump_target(nottaken, out);
5477       assem_debug("2:\n");
5478       if(!likely[i]) {
5479         wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5480         load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5481         address_generation(i+1,&branch_regs[i],0);
5482         load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5483         ds_assemble(i+1,&branch_regs[i]);
5484       }
5485       cc=get_reg(branch_regs[i].regmap,CCREG);
5486       if(cc==-1&&!likely[i]) {
5487         // Cycle count isn't in a register, temporarily load it then write it out
5488         emit_loadreg(CCREG,HOST_CCREG);
5489         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5490         void *jaddr=out;
5491         emit_jns(0);
5492         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5493         emit_storereg(CCREG,HOST_CCREG);
5494       }
5495       else{
5496         cc=get_reg(i_regmap,CCREG);
5497         assert(cc==HOST_CCREG);
5498         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5499         void *jaddr=out;
5500         emit_jns(0);
5501         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,likely[i]?NULLDS:NOTTAKEN,0);
5502       }
5503     }
5504   }
5505 }
5506
5507 static void sjump_assemble(int i,struct regstat *i_regs)
5508 {
5509   signed char *i_regmap=i_regs->regmap;
5510   int cc;
5511   int match;
5512   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5513   assem_debug("smatch=%d\n",match);
5514   int s1l;
5515   int unconditional=0,nevertaken=0;
5516   int invert=0;
5517   int internal=internal_branch(ba[i]);
5518   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5519   if(!match) invert=1;
5520   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5521   if(i>(ba[i]-start)>>2) invert=1;
5522   #endif
5523   #ifdef __aarch64__
5524   invert=1; // because of near cond. branches
5525   #endif
5526
5527   //if(opcode2[i]>=0x10) return; // FIXME (BxxZAL)
5528   //assert(opcode2[i]<0x10||rs1[i]==0); // FIXME (BxxZAL)
5529
5530   if(ooo[i]) {
5531     s1l=get_reg(branch_regs[i].regmap,rs1[i]);
5532   }
5533   else {
5534     s1l=get_reg(i_regmap,rs1[i]);
5535   }
5536   if(rs1[i]==0)
5537   {
5538     if(opcode2[i]&1) unconditional=1;
5539     else nevertaken=1;
5540     // These are never taken (r0 is never less than zero)
5541     //assert(opcode2[i]!=0);
5542     //assert(opcode2[i]!=2);
5543     //assert(opcode2[i]!=0x10);
5544     //assert(opcode2[i]!=0x12);
5545   }
5546
5547   if(ooo[i]) {
5548     // Out of order execution (delay slot first)
5549     //printf("OOOE\n");
5550     address_generation(i+1,i_regs,regs[i].regmap_entry);
5551     ds_assemble(i+1,i_regs);
5552     int adj;
5553     uint64_t bc_unneeded=branch_regs[i].u;
5554     bc_unneeded&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
5555     bc_unneeded|=1;
5556     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5557     load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],rs1[i]);
5558     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5559     if(rt1[i]==31) {
5560       int rt,return_address;
5561       rt=get_reg(branch_regs[i].regmap,31);
5562       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]);
5563       if(rt>=0) {
5564         // Save the PC even if the branch is not taken
5565         return_address=start+i*4+8;
5566         emit_movimm(return_address,rt); // PC into link register
5567         #ifdef IMM_PREFETCH
5568         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5569         #endif
5570       }
5571     }
5572     cc=get_reg(branch_regs[i].regmap,CCREG);
5573     assert(cc==HOST_CCREG);
5574     if(unconditional)
5575       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5576     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5577     assem_debug("cycle count (adj)\n");
5578     if(unconditional) {
5579       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5580       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5581         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5582         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5583         if(internal)
5584           assem_debug("branch: internal\n");
5585         else
5586           assem_debug("branch: external\n");
5587         if(internal&&is_ds[(ba[i]-start)>>2]) {
5588           ds_assemble_entry(i);
5589         }
5590         else {
5591           add_to_linker(out,ba[i],internal);
5592           emit_jmp(0);
5593         }
5594         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5595         if(((u_int)out)&7) emit_addnop(0);
5596         #endif
5597       }
5598     }
5599     else if(nevertaken) {
5600       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5601       void *jaddr=out;
5602       emit_jns(0);
5603       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5604     }
5605     else {
5606       void *nottaken = NULL;
5607       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5608       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5609       {
5610         assert(s1l>=0);
5611         if((opcode2[i]&0xf)==0) // BLTZ/BLTZAL
5612         {
5613           emit_test(s1l,s1l);
5614           if(invert){
5615             nottaken=out;
5616             emit_jns(DJT_1);
5617           }else{
5618             add_to_linker(out,ba[i],internal);
5619             emit_js(0);
5620           }
5621         }
5622         if((opcode2[i]&0xf)==1) // BGEZ/BLTZAL
5623         {
5624           emit_test(s1l,s1l);
5625           if(invert){
5626             nottaken=out;
5627             emit_js(DJT_1);
5628           }else{
5629             add_to_linker(out,ba[i],internal);
5630             emit_jns(0);
5631           }
5632         }
5633       }
5634
5635       if(invert) {
5636         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5637         if(match&&(!internal||!is_ds[(ba[i]-start)>>2])) {
5638           if(adj) {
5639             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5640             add_to_linker(out,ba[i],internal);
5641           }else{
5642             emit_addnop(13);
5643             add_to_linker(out,ba[i],internal*2);
5644           }
5645           emit_jmp(0);
5646         }else
5647         #endif
5648         {
5649           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5650           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5651           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5652           if(internal)
5653             assem_debug("branch: internal\n");
5654           else
5655             assem_debug("branch: external\n");
5656           if(internal&&is_ds[(ba[i]-start)>>2]) {
5657             ds_assemble_entry(i);
5658           }
5659           else {
5660             add_to_linker(out,ba[i],internal);
5661             emit_jmp(0);
5662           }
5663         }
5664         set_jump_target(nottaken, out);
5665       }
5666
5667       if(adj) {
5668         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5669       }
5670     } // (!unconditional)
5671   } // if(ooo)
5672   else
5673   {
5674     // In-order execution (branch first)
5675     //printf("IOE\n");
5676     void *nottaken = NULL;
5677     if(rt1[i]==31) {
5678       int rt,return_address;
5679       rt=get_reg(branch_regs[i].regmap,31);
5680       if(rt>=0) {
5681         // Save the PC even if the branch is not taken
5682         return_address=start+i*4+8;
5683         emit_movimm(return_address,rt); // PC into link register
5684         #ifdef IMM_PREFETCH
5685         emit_prefetch(hash_table_get(return_address));
5686         #endif
5687       }
5688     }
5689     if(!unconditional) {
5690       //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]);
5691         assert(s1l>=0);
5692         if((opcode2[i]&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5693         {
5694           emit_test(s1l,s1l);
5695           nottaken=out;
5696           emit_jns(DJT_1);
5697         }
5698         if((opcode2[i]&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5699         {
5700           emit_test(s1l,s1l);
5701           nottaken=out;
5702           emit_js(DJT_1);
5703         }
5704     } // if(!unconditional)
5705     int adj;
5706     uint64_t ds_unneeded=branch_regs[i].u;
5707     ds_unneeded&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5708     ds_unneeded|=1;
5709     // branch taken
5710     if(!nevertaken) {
5711       //assem_debug("1:\n");
5712       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5713       // load regs
5714       load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5715       address_generation(i+1,&branch_regs[i],0);
5716       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5717       ds_assemble(i+1,&branch_regs[i]);
5718       cc=get_reg(branch_regs[i].regmap,CCREG);
5719       if(cc==-1) {
5720         emit_loadreg(CCREG,cc=HOST_CCREG);
5721         // CHECK: Is the following instruction (fall thru) allocated ok?
5722       }
5723       assert(cc==HOST_CCREG);
5724       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5725       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5726       assem_debug("cycle count (adj)\n");
5727       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5728       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5729       if(internal)
5730         assem_debug("branch: internal\n");
5731       else
5732         assem_debug("branch: external\n");
5733       if(internal&&is_ds[(ba[i]-start)>>2]) {
5734         ds_assemble_entry(i);
5735       }
5736       else {
5737         add_to_linker(out,ba[i],internal);
5738         emit_jmp(0);
5739       }
5740     }
5741     // branch not taken
5742     if(!unconditional) {
5743       set_jump_target(nottaken, out);
5744       assem_debug("1:\n");
5745       if(!likely[i]) {
5746         wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5747         load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5748         address_generation(i+1,&branch_regs[i],0);
5749         load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5750         ds_assemble(i+1,&branch_regs[i]);
5751       }
5752       cc=get_reg(branch_regs[i].regmap,CCREG);
5753       if(cc==-1&&!likely[i]) {
5754         // Cycle count isn't in a register, temporarily load it then write it out
5755         emit_loadreg(CCREG,HOST_CCREG);
5756         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5757         void *jaddr=out;
5758         emit_jns(0);
5759         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5760         emit_storereg(CCREG,HOST_CCREG);
5761       }
5762       else{
5763         cc=get_reg(i_regmap,CCREG);
5764         assert(cc==HOST_CCREG);
5765         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5766         void *jaddr=out;
5767         emit_jns(0);
5768         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,likely[i]?NULLDS:NOTTAKEN,0);
5769       }
5770     }
5771   }
5772 }
5773
5774 static void pagespan_assemble(int i,struct regstat *i_regs)
5775 {
5776   int s1l=get_reg(i_regs->regmap,rs1[i]);
5777   int s2l=get_reg(i_regs->regmap,rs2[i]);
5778   void *taken = NULL;
5779   void *nottaken = NULL;
5780   int unconditional=0;
5781   if(rs1[i]==0)
5782   {
5783     s1l=s2l;
5784     s2l=-1;
5785   }
5786   else if(rs2[i]==0)
5787   {
5788     s2l=-1;
5789   }
5790   int hr=0;
5791   int addr=-1,alt=-1,ntaddr=-1;
5792   if(i_regs->regmap[HOST_BTREG]<0) {addr=HOST_BTREG;}
5793   else {
5794     while(hr<HOST_REGS)
5795     {
5796       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5797          (i_regs->regmap[hr]&63)!=rs1[i] &&
5798          (i_regs->regmap[hr]&63)!=rs2[i] )
5799       {
5800         addr=hr++;break;
5801       }
5802       hr++;
5803     }
5804   }
5805   while(hr<HOST_REGS)
5806   {
5807     if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5808        (i_regs->regmap[hr]&63)!=rs1[i] &&
5809        (i_regs->regmap[hr]&63)!=rs2[i] )
5810     {
5811       alt=hr++;break;
5812     }
5813     hr++;
5814   }
5815   if((opcode[i]&0x2E)==6) // BLEZ/BGTZ needs another register
5816   {
5817     while(hr<HOST_REGS)
5818     {
5819       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5820          (i_regs->regmap[hr]&63)!=rs1[i] &&
5821          (i_regs->regmap[hr]&63)!=rs2[i] )
5822       {
5823         ntaddr=hr;break;
5824       }
5825       hr++;
5826     }
5827   }
5828   assert(hr<HOST_REGS);
5829   if((opcode[i]&0x2e)==4||opcode[i]==0x11) { // BEQ/BNE/BEQL/BNEL/BC1
5830     load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
5831   }
5832   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5833   if(opcode[i]==2) // J
5834   {
5835     unconditional=1;
5836   }
5837   if(opcode[i]==3) // JAL
5838   {
5839     // TODO: mini_ht
5840     int rt=get_reg(i_regs->regmap,31);
5841     emit_movimm(start+i*4+8,rt);
5842     unconditional=1;
5843   }
5844   if(opcode[i]==0&&(opcode2[i]&0x3E)==8) // JR/JALR
5845   {
5846     emit_mov(s1l,addr);
5847     if(opcode2[i]==9) // JALR
5848     {
5849       int rt=get_reg(i_regs->regmap,rt1[i]);
5850       emit_movimm(start+i*4+8,rt);
5851     }
5852   }
5853   if((opcode[i]&0x3f)==4) // BEQ
5854   {
5855     if(rs1[i]==rs2[i])
5856     {
5857       unconditional=1;
5858     }
5859     else
5860     #ifdef HAVE_CMOV_IMM
5861     if(1) {
5862       if(s2l>=0) emit_cmp(s1l,s2l);
5863       else emit_test(s1l,s1l);
5864       emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5865     }
5866     else
5867     #endif
5868     {
5869       assert(s1l>=0);
5870       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5871       if(s2l>=0) emit_cmp(s1l,s2l);
5872       else emit_test(s1l,s1l);
5873       emit_cmovne_reg(alt,addr);
5874     }
5875   }
5876   if((opcode[i]&0x3f)==5) // BNE
5877   {
5878     #ifdef HAVE_CMOV_IMM
5879     if(s2l>=0) emit_cmp(s1l,s2l);
5880     else emit_test(s1l,s1l);
5881     emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5882     #else
5883     assert(s1l>=0);
5884     emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5885     if(s2l>=0) emit_cmp(s1l,s2l);
5886     else emit_test(s1l,s1l);
5887     emit_cmovne_reg(alt,addr);
5888     #endif
5889   }
5890   if((opcode[i]&0x3f)==0x14) // BEQL
5891   {
5892     if(s2l>=0) emit_cmp(s1l,s2l);
5893     else emit_test(s1l,s1l);
5894     if(nottaken) set_jump_target(nottaken, out);
5895     nottaken=out;
5896     emit_jne(0);
5897   }
5898   if((opcode[i]&0x3f)==0x15) // BNEL
5899   {
5900     if(s2l>=0) emit_cmp(s1l,s2l);
5901     else emit_test(s1l,s1l);
5902     nottaken=out;
5903     emit_jeq(0);
5904     if(taken) set_jump_target(taken, out);
5905   }
5906   if((opcode[i]&0x3f)==6) // BLEZ
5907   {
5908     emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5909     emit_cmpimm(s1l,1);
5910     emit_cmovl_reg(alt,addr);
5911   }
5912   if((opcode[i]&0x3f)==7) // BGTZ
5913   {
5914     emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5915     emit_cmpimm(s1l,1);
5916     emit_cmovl_reg(ntaddr,addr);
5917   }
5918   if((opcode[i]&0x3f)==0x16) // BLEZL
5919   {
5920     assert((opcode[i]&0x3f)!=0x16);
5921   }
5922   if((opcode[i]&0x3f)==0x17) // BGTZL
5923   {
5924     assert((opcode[i]&0x3f)!=0x17);
5925   }
5926   assert(opcode[i]!=1); // BLTZ/BGEZ
5927
5928   //FIXME: Check CSREG
5929   if(opcode[i]==0x11 && opcode2[i]==0x08 ) {
5930     if((source[i]&0x30000)==0) // BC1F
5931     {
5932       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5933       emit_testimm(s1l,0x800000);
5934       emit_cmovne_reg(alt,addr);
5935     }
5936     if((source[i]&0x30000)==0x10000) // BC1T
5937     {
5938       emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5939       emit_testimm(s1l,0x800000);
5940       emit_cmovne_reg(alt,addr);
5941     }
5942     if((source[i]&0x30000)==0x20000) // BC1FL
5943     {
5944       emit_testimm(s1l,0x800000);
5945       nottaken=out;
5946       emit_jne(0);
5947     }
5948     if((source[i]&0x30000)==0x30000) // BC1TL
5949     {
5950       emit_testimm(s1l,0x800000);
5951       nottaken=out;
5952       emit_jeq(0);
5953     }
5954   }
5955
5956   assert(i_regs->regmap[HOST_CCREG]==CCREG);
5957   wb_dirtys(regs[i].regmap,regs[i].dirty);
5958   if(likely[i]||unconditional)
5959   {
5960     emit_movimm(ba[i],HOST_BTREG);
5961   }
5962   else if(addr!=HOST_BTREG)
5963   {
5964     emit_mov(addr,HOST_BTREG);
5965   }
5966   void *branch_addr=out;
5967   emit_jmp(0);
5968   int target_addr=start+i*4+5;
5969   void *stub=out;
5970   void *compiled_target_addr=check_addr(target_addr);
5971   emit_extjump_ds(branch_addr, target_addr);
5972   if(compiled_target_addr) {
5973     set_jump_target(branch_addr, compiled_target_addr);
5974     add_jump_out(target_addr,stub);
5975   }
5976   else set_jump_target(branch_addr, stub);
5977   if(likely[i]) {
5978     // Not-taken path
5979     set_jump_target(nottaken, out);
5980     wb_dirtys(regs[i].regmap,regs[i].dirty);
5981     void *branch_addr=out;
5982     emit_jmp(0);
5983     int target_addr=start+i*4+8;
5984     void *stub=out;
5985     void *compiled_target_addr=check_addr(target_addr);
5986     emit_extjump_ds(branch_addr, target_addr);
5987     if(compiled_target_addr) {
5988       set_jump_target(branch_addr, compiled_target_addr);
5989       add_jump_out(target_addr,stub);
5990     }
5991     else set_jump_target(branch_addr, stub);
5992   }
5993 }
5994
5995 // Assemble the delay slot for the above
5996 static void pagespan_ds()
5997 {
5998   assem_debug("initial delay slot:\n");
5999   u_int vaddr=start+1;
6000   u_int page=get_page(vaddr);
6001   u_int vpage=get_vpage(vaddr);
6002   ll_add(jump_dirty+vpage,vaddr,(void *)out);
6003   do_dirty_stub_ds(slen*4);
6004   ll_add(jump_in+page,vaddr,(void *)out);
6005   assert(regs[0].regmap_entry[HOST_CCREG]==CCREG);
6006   if(regs[0].regmap[HOST_CCREG]!=CCREG)
6007     wb_register(CCREG,regs[0].regmap_entry,regs[0].wasdirty);
6008   if(regs[0].regmap[HOST_BTREG]!=BTREG)
6009     emit_writeword(HOST_BTREG,&branch_target);
6010   load_regs(regs[0].regmap_entry,regs[0].regmap,rs1[0],rs2[0]);
6011   address_generation(0,&regs[0],regs[0].regmap_entry);
6012   if(itype[0]==STORE||itype[0]==STORELR||(opcode[0]&0x3b)==0x39||(opcode[0]&0x3b)==0x3a)
6013     load_regs(regs[0].regmap_entry,regs[0].regmap,INVCP,INVCP);
6014   is_delayslot=0;
6015   switch(itype[0]) {
6016     case ALU:
6017       alu_assemble(0,&regs[0]);break;
6018     case IMM16:
6019       imm16_assemble(0,&regs[0]);break;
6020     case SHIFT:
6021       shift_assemble(0,&regs[0]);break;
6022     case SHIFTIMM:
6023       shiftimm_assemble(0,&regs[0]);break;
6024     case LOAD:
6025       load_assemble(0,&regs[0]);break;
6026     case LOADLR:
6027       loadlr_assemble(0,&regs[0]);break;
6028     case STORE:
6029       store_assemble(0,&regs[0]);break;
6030     case STORELR:
6031       storelr_assemble(0,&regs[0]);break;
6032     case COP0:
6033       cop0_assemble(0,&regs[0]);break;
6034     case COP1:
6035       cop1_assemble(0,&regs[0]);break;
6036     case C1LS:
6037       c1ls_assemble(0,&regs[0]);break;
6038     case COP2:
6039       cop2_assemble(0,&regs[0]);break;
6040     case C2LS:
6041       c2ls_assemble(0,&regs[0]);break;
6042     case C2OP:
6043       c2op_assemble(0,&regs[0]);break;
6044     case MULTDIV:
6045       multdiv_assemble(0,&regs[0]);
6046       multdiv_prepare_stall(0,&regs[0]);
6047       break;
6048     case MOV:
6049       mov_assemble(0,&regs[0]);break;
6050     case SYSCALL:
6051     case HLECALL:
6052     case INTCALL:
6053     case SPAN:
6054     case UJUMP:
6055     case RJUMP:
6056     case CJUMP:
6057     case SJUMP:
6058       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
6059   }
6060   int btaddr=get_reg(regs[0].regmap,BTREG);
6061   if(btaddr<0) {
6062     btaddr=get_reg(regs[0].regmap,-1);
6063     emit_readword(&branch_target,btaddr);
6064   }
6065   assert(btaddr!=HOST_CCREG);
6066   if(regs[0].regmap[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
6067 #ifdef HOST_IMM8
6068   host_tempreg_acquire();
6069   emit_movimm(start+4,HOST_TEMPREG);
6070   emit_cmp(btaddr,HOST_TEMPREG);
6071   host_tempreg_release();
6072 #else
6073   emit_cmpimm(btaddr,start+4);
6074 #endif
6075   void *branch = out;
6076   emit_jeq(0);
6077   store_regs_bt(regs[0].regmap,regs[0].dirty,-1);
6078   do_jump_vaddr(btaddr);
6079   set_jump_target(branch, out);
6080   store_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6081   load_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6082 }
6083
6084 // Basic liveness analysis for MIPS registers
6085 void unneeded_registers(int istart,int iend,int r)
6086 {
6087   int i;
6088   uint64_t u,gte_u,b,gte_b;
6089   uint64_t temp_u,temp_gte_u=0;
6090   uint64_t gte_u_unknown=0;
6091   if (HACK_ENABLED(NDHACK_GTE_UNNEEDED))
6092     gte_u_unknown=~0ll;
6093   if(iend==slen-1) {
6094     u=1;
6095     gte_u=gte_u_unknown;
6096   }else{
6097     //u=unneeded_reg[iend+1];
6098     u=1;
6099     gte_u=gte_unneeded[iend+1];
6100   }
6101
6102   for (i=iend;i>=istart;i--)
6103   {
6104     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
6105     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
6106     {
6107       // If subroutine call, flag return address as a possible branch target
6108       if(rt1[i]==31 && i<slen-2) bt[i+2]=1;
6109
6110       if(ba[i]<start || ba[i]>=(start+slen*4))
6111       {
6112         // Branch out of this block, flush all regs
6113         u=1;
6114         gte_u=gte_u_unknown;
6115         branch_unneeded_reg[i]=u;
6116         // Merge in delay slot
6117         u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
6118         u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
6119         u|=1;
6120         gte_u|=gte_rt[i+1];
6121         gte_u&=~gte_rs[i+1];
6122         // If branch is "likely" (and conditional)
6123         // then we skip the delay slot on the fall-thru path
6124         if(likely[i]) {
6125           if(i<slen-1) {
6126             u&=unneeded_reg[i+2];
6127             gte_u&=gte_unneeded[i+2];
6128           }
6129           else
6130           {
6131             u=1;
6132             gte_u=gte_u_unknown;
6133           }
6134         }
6135       }
6136       else
6137       {
6138         // Internal branch, flag target
6139         bt[(ba[i]-start)>>2]=1;
6140         if(ba[i]<=start+i*4) {
6141           // Backward branch
6142           if(is_ujump(i))
6143           {
6144             // Unconditional branch
6145             temp_u=1;
6146             temp_gte_u=0;
6147           } else {
6148             // Conditional branch (not taken case)
6149             temp_u=unneeded_reg[i+2];
6150             temp_gte_u&=gte_unneeded[i+2];
6151           }
6152           // Merge in delay slot
6153           temp_u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
6154           temp_u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
6155           temp_u|=1;
6156           temp_gte_u|=gte_rt[i+1];
6157           temp_gte_u&=~gte_rs[i+1];
6158           // If branch is "likely" (and conditional)
6159           // then we skip the delay slot on the fall-thru path
6160           if(likely[i]) {
6161             if(i<slen-1) {
6162               temp_u&=unneeded_reg[i+2];
6163               temp_gte_u&=gte_unneeded[i+2];
6164             }
6165             else
6166             {
6167               temp_u=1;
6168               temp_gte_u=gte_u_unknown;
6169             }
6170           }
6171           temp_u|=(1LL<<rt1[i])|(1LL<<rt2[i]);
6172           temp_u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
6173           temp_u|=1;
6174           temp_gte_u|=gte_rt[i];
6175           temp_gte_u&=~gte_rs[i];
6176           unneeded_reg[i]=temp_u;
6177           gte_unneeded[i]=temp_gte_u;
6178           // Only go three levels deep.  This recursion can take an
6179           // excessive amount of time if there are a lot of nested loops.
6180           if(r<2) {
6181             unneeded_registers((ba[i]-start)>>2,i-1,r+1);
6182           }else{
6183             unneeded_reg[(ba[i]-start)>>2]=1;
6184             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
6185           }
6186         } /*else*/ if(1) {
6187           if (is_ujump(i))
6188           {
6189             // Unconditional branch
6190             u=unneeded_reg[(ba[i]-start)>>2];
6191             gte_u=gte_unneeded[(ba[i]-start)>>2];
6192             branch_unneeded_reg[i]=u;
6193             // Merge in delay slot
6194             u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
6195             u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
6196             u|=1;
6197             gte_u|=gte_rt[i+1];
6198             gte_u&=~gte_rs[i+1];
6199           } else {
6200             // Conditional branch
6201             b=unneeded_reg[(ba[i]-start)>>2];
6202             gte_b=gte_unneeded[(ba[i]-start)>>2];
6203             branch_unneeded_reg[i]=b;
6204             // Branch delay slot
6205             b|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
6206             b&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
6207             b|=1;
6208             gte_b|=gte_rt[i+1];
6209             gte_b&=~gte_rs[i+1];
6210             // If branch is "likely" then we skip the
6211             // delay slot on the fall-thru path
6212             if(likely[i]) {
6213               u=b;
6214               gte_u=gte_b;
6215               if(i<slen-1) {
6216                 u&=unneeded_reg[i+2];
6217                 gte_u&=gte_unneeded[i+2];
6218               }
6219             } else {
6220               u&=b;
6221               gte_u&=gte_b;
6222             }
6223             if(i<slen-1) {
6224               branch_unneeded_reg[i]&=unneeded_reg[i+2];
6225             } else {
6226               branch_unneeded_reg[i]=1;
6227             }
6228           }
6229         }
6230       }
6231     }
6232     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
6233     {
6234       // SYSCALL instruction (software interrupt)
6235       u=1;
6236     }
6237     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
6238     {
6239       // ERET instruction (return from interrupt)
6240       u=1;
6241     }
6242     //u=1; // DEBUG
6243     // Written registers are unneeded
6244     u|=1LL<<rt1[i];
6245     u|=1LL<<rt2[i];
6246     gte_u|=gte_rt[i];
6247     // Accessed registers are needed
6248     u&=~(1LL<<rs1[i]);
6249     u&=~(1LL<<rs2[i]);
6250     gte_u&=~gte_rs[i];
6251     if(gte_rs[i]&&rt1[i]&&(unneeded_reg[i+1]&(1ll<<rt1[i])))
6252       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
6253     // Source-target dependencies
6254     // R0 is always unneeded
6255     u|=1;
6256     // Save it
6257     unneeded_reg[i]=u;
6258     gte_unneeded[i]=gte_u;
6259     /*
6260     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
6261     printf("U:");
6262     int r;
6263     for(r=1;r<=CCREG;r++) {
6264       if((unneeded_reg[i]>>r)&1) {
6265         if(r==HIREG) printf(" HI");
6266         else if(r==LOREG) printf(" LO");
6267         else printf(" r%d",r);
6268       }
6269     }
6270     printf("\n");
6271     */
6272   }
6273 }
6274
6275 // Write back dirty registers as soon as we will no longer modify them,
6276 // so that we don't end up with lots of writes at the branches.
6277 void clean_registers(int istart,int iend,int wr)
6278 {
6279   int i;
6280   int r;
6281   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
6282   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
6283   if(iend==slen-1) {
6284     will_dirty_i=will_dirty_next=0;
6285     wont_dirty_i=wont_dirty_next=0;
6286   }else{
6287     will_dirty_i=will_dirty_next=will_dirty[iend+1];
6288     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
6289   }
6290   for (i=iend;i>=istart;i--)
6291   {
6292     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
6293     {
6294       if(ba[i]<start || ba[i]>=(start+slen*4))
6295       {
6296         // Branch out of this block, flush all regs
6297         if (is_ujump(i))
6298         {
6299           // Unconditional branch
6300           will_dirty_i=0;
6301           wont_dirty_i=0;
6302           // Merge in delay slot (will dirty)
6303           for(r=0;r<HOST_REGS;r++) {
6304             if(r!=EXCLUDE_REG) {
6305               if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6306               if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6307               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6308               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6309               if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6310               if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6311               if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6312               if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6313               if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6314               if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6315               if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6316               if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6317               if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6318               if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6319             }
6320           }
6321         }
6322         else
6323         {
6324           // Conditional branch
6325           will_dirty_i=0;
6326           wont_dirty_i=wont_dirty_next;
6327           // Merge in delay slot (will dirty)
6328           for(r=0;r<HOST_REGS;r++) {
6329             if(r!=EXCLUDE_REG) {
6330               if(!likely[i]) {
6331                 // Might not dirty if likely branch is not taken
6332                 if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6333                 if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6334                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6335                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6336                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6337                 if(branch_regs[i].regmap[r]==0) will_dirty_i&=~(1<<r);
6338                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6339                 //if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6340                 //if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6341                 if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6342                 if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6343                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6344                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6345                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6346               }
6347             }
6348           }
6349         }
6350         // Merge in delay slot (wont dirty)
6351         for(r=0;r<HOST_REGS;r++) {
6352           if(r!=EXCLUDE_REG) {
6353             if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6354             if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6355             if((regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6356             if((regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6357             if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6358             if((branch_regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6359             if((branch_regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6360             if((branch_regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6361             if((branch_regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6362             if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6363           }
6364         }
6365         if(wr) {
6366           #ifndef DESTRUCTIVE_WRITEBACK
6367           branch_regs[i].dirty&=wont_dirty_i;
6368           #endif
6369           branch_regs[i].dirty|=will_dirty_i;
6370         }
6371       }
6372       else
6373       {
6374         // Internal branch
6375         if(ba[i]<=start+i*4) {
6376           // Backward branch
6377           if (is_ujump(i))
6378           {
6379             // Unconditional branch
6380             temp_will_dirty=0;
6381             temp_wont_dirty=0;
6382             // Merge in delay slot (will dirty)
6383             for(r=0;r<HOST_REGS;r++) {
6384               if(r!=EXCLUDE_REG) {
6385                 if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6386                 if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6387                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6388                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6389                 if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6390                 if(branch_regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6391                 if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6392                 if((regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6393                 if((regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6394                 if((regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6395                 if((regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6396                 if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6397                 if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6398                 if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6399               }
6400             }
6401           } else {
6402             // Conditional branch (not taken case)
6403             temp_will_dirty=will_dirty_next;
6404             temp_wont_dirty=wont_dirty_next;
6405             // Merge in delay slot (will dirty)
6406             for(r=0;r<HOST_REGS;r++) {
6407               if(r!=EXCLUDE_REG) {
6408                 if(!likely[i]) {
6409                   // Will not dirty if likely branch is not taken
6410                   if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6411                   if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6412                   if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6413                   if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6414                   if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6415                   if(branch_regs[i].regmap[r]==0) temp_will_dirty&=~(1<<r);
6416                   if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6417                   //if((regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6418                   //if((regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6419                   if((regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6420                   if((regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6421                   if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6422                   if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6423                   if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6424                 }
6425               }
6426             }
6427           }
6428           // Merge in delay slot (wont dirty)
6429           for(r=0;r<HOST_REGS;r++) {
6430             if(r!=EXCLUDE_REG) {
6431               if((regs[i].regmap[r]&63)==rt1[i]) temp_wont_dirty|=1<<r;
6432               if((regs[i].regmap[r]&63)==rt2[i]) temp_wont_dirty|=1<<r;
6433               if((regs[i].regmap[r]&63)==rt1[i+1]) temp_wont_dirty|=1<<r;
6434               if((regs[i].regmap[r]&63)==rt2[i+1]) temp_wont_dirty|=1<<r;
6435               if(regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6436               if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_wont_dirty|=1<<r;
6437               if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_wont_dirty|=1<<r;
6438               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_wont_dirty|=1<<r;
6439               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_wont_dirty|=1<<r;
6440               if(branch_regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6441             }
6442           }
6443           // Deal with changed mappings
6444           if(i<iend) {
6445             for(r=0;r<HOST_REGS;r++) {
6446               if(r!=EXCLUDE_REG) {
6447                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
6448                   temp_will_dirty&=~(1<<r);
6449                   temp_wont_dirty&=~(1<<r);
6450                   if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6451                     temp_will_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6452                     temp_wont_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6453                   } else {
6454                     temp_will_dirty|=1<<r;
6455                     temp_wont_dirty|=1<<r;
6456                   }
6457                 }
6458               }
6459             }
6460           }
6461           if(wr) {
6462             will_dirty[i]=temp_will_dirty;
6463             wont_dirty[i]=temp_wont_dirty;
6464             clean_registers((ba[i]-start)>>2,i-1,0);
6465           }else{
6466             // Limit recursion.  It can take an excessive amount
6467             // of time if there are a lot of nested loops.
6468             will_dirty[(ba[i]-start)>>2]=0;
6469             wont_dirty[(ba[i]-start)>>2]=-1;
6470           }
6471         }
6472         /*else*/ if(1)
6473         {
6474           if (is_ujump(i))
6475           {
6476             // Unconditional branch
6477             will_dirty_i=0;
6478             wont_dirty_i=0;
6479           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6480             for(r=0;r<HOST_REGS;r++) {
6481               if(r!=EXCLUDE_REG) {
6482                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6483                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
6484                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6485                 }
6486                 if(branch_regs[i].regmap[r]>=0) {
6487                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6488                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6489                 }
6490               }
6491             }
6492           //}
6493             // Merge in delay slot
6494             for(r=0;r<HOST_REGS;r++) {
6495               if(r!=EXCLUDE_REG) {
6496                 if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6497                 if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6498                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6499                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6500                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6501                 if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6502                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6503                 if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6504                 if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6505                 if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6506                 if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6507                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6508                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6509                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6510               }
6511             }
6512           } else {
6513             // Conditional branch
6514             will_dirty_i=will_dirty_next;
6515             wont_dirty_i=wont_dirty_next;
6516           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6517             for(r=0;r<HOST_REGS;r++) {
6518               if(r!=EXCLUDE_REG) {
6519                 signed char target_reg=branch_regs[i].regmap[r];
6520                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6521                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6522                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6523                 }
6524                 else if(target_reg>=0) {
6525                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6526                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6527                 }
6528                 // Treat delay slot as part of branch too
6529                 /*if(regs[i+1].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6530                   will_dirty[i+1]&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6531                   wont_dirty[i+1]|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6532                 }
6533                 else
6534                 {
6535                   will_dirty[i+1]&=~(1<<r);
6536                 }*/
6537               }
6538             }
6539           //}
6540             // Merge in delay slot
6541             for(r=0;r<HOST_REGS;r++) {
6542               if(r!=EXCLUDE_REG) {
6543                 if(!likely[i]) {
6544                   // Might not dirty if likely branch is not taken
6545                   if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6546                   if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6547                   if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6548                   if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6549                   if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6550                   if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6551                   if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6552                   //if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6553                   //if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6554                   if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6555                   if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6556                   if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6557                   if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6558                   if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6559                 }
6560               }
6561             }
6562           }
6563           // Merge in delay slot (won't dirty)
6564           for(r=0;r<HOST_REGS;r++) {
6565             if(r!=EXCLUDE_REG) {
6566               if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6567               if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6568               if((regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6569               if((regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6570               if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6571               if((branch_regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6572               if((branch_regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6573               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6574               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6575               if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6576             }
6577           }
6578           if(wr) {
6579             #ifndef DESTRUCTIVE_WRITEBACK
6580             branch_regs[i].dirty&=wont_dirty_i;
6581             #endif
6582             branch_regs[i].dirty|=will_dirty_i;
6583           }
6584         }
6585       }
6586     }
6587     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
6588     {
6589       // SYSCALL instruction (software interrupt)
6590       will_dirty_i=0;
6591       wont_dirty_i=0;
6592     }
6593     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
6594     {
6595       // ERET instruction (return from interrupt)
6596       will_dirty_i=0;
6597       wont_dirty_i=0;
6598     }
6599     will_dirty_next=will_dirty_i;
6600     wont_dirty_next=wont_dirty_i;
6601     for(r=0;r<HOST_REGS;r++) {
6602       if(r!=EXCLUDE_REG) {
6603         if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6604         if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6605         if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6606         if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6607         if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6608         if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6609         if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6610         if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6611         if(i>istart) {
6612           if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&itype[i]!=CJUMP&&itype[i]!=SJUMP)
6613           {
6614             // Don't store a register immediately after writing it,
6615             // may prevent dual-issue.
6616             if((regs[i].regmap[r]&63)==rt1[i-1]) wont_dirty_i|=1<<r;
6617             if((regs[i].regmap[r]&63)==rt2[i-1]) wont_dirty_i|=1<<r;
6618           }
6619         }
6620       }
6621     }
6622     // Save it
6623     will_dirty[i]=will_dirty_i;
6624     wont_dirty[i]=wont_dirty_i;
6625     // Mark registers that won't be dirtied as not dirty
6626     if(wr) {
6627       /*printf("wr (%d,%d) %x will:",istart,iend,start+i*4);
6628       for(r=0;r<HOST_REGS;r++) {
6629         if((will_dirty_i>>r)&1) {
6630           printf(" r%d",r);
6631         }
6632       }
6633       printf("\n");*/
6634
6635       //if(i==istart||(itype[i-1]!=RJUMP&&itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP)) {
6636         regs[i].dirty|=will_dirty_i;
6637         #ifndef DESTRUCTIVE_WRITEBACK
6638         regs[i].dirty&=wont_dirty_i;
6639         if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
6640         {
6641           if (i < iend-1 && !is_ujump(i)) {
6642             for(r=0;r<HOST_REGS;r++) {
6643               if(r!=EXCLUDE_REG) {
6644                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
6645                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
6646                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6647               }
6648             }
6649           }
6650         }
6651         else
6652         {
6653           if(i<iend) {
6654             for(r=0;r<HOST_REGS;r++) {
6655               if(r!=EXCLUDE_REG) {
6656                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
6657                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
6658                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6659               }
6660             }
6661           }
6662         }
6663         #endif
6664       //}
6665     }
6666     // Deal with changed mappings
6667     temp_will_dirty=will_dirty_i;
6668     temp_wont_dirty=wont_dirty_i;
6669     for(r=0;r<HOST_REGS;r++) {
6670       if(r!=EXCLUDE_REG) {
6671         int nr;
6672         if(regs[i].regmap[r]==regmap_pre[i][r]) {
6673           if(wr) {
6674             #ifndef DESTRUCTIVE_WRITEBACK
6675             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6676             #endif
6677             regs[i].wasdirty|=will_dirty_i&(1<<r);
6678           }
6679         }
6680         else if(regmap_pre[i][r]>=0&&(nr=get_reg(regs[i].regmap,regmap_pre[i][r]))>=0) {
6681           // Register moved to a different register
6682           will_dirty_i&=~(1<<r);
6683           wont_dirty_i&=~(1<<r);
6684           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
6685           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
6686           if(wr) {
6687             #ifndef DESTRUCTIVE_WRITEBACK
6688             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6689             #endif
6690             regs[i].wasdirty|=will_dirty_i&(1<<r);
6691           }
6692         }
6693         else {
6694           will_dirty_i&=~(1<<r);
6695           wont_dirty_i&=~(1<<r);
6696           if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6697             will_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6698             wont_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6699           } else {
6700             wont_dirty_i|=1<<r;
6701             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
6702           }
6703         }
6704       }
6705     }
6706   }
6707 }
6708
6709 #ifdef DISASM
6710   /* disassembly */
6711 void disassemble_inst(int i)
6712 {
6713     if (bt[i]) printf("*"); else printf(" ");
6714     switch(itype[i]) {
6715       case UJUMP:
6716         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6717       case CJUMP:
6718         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;
6719       case SJUMP:
6720         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;
6721       case RJUMP:
6722         if (opcode[i]==0x9&&rt1[i]!=31)
6723           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],rt1[i],rs1[i]);
6724         else
6725           printf (" %x: %s r%d\n",start+i*4,insn[i],rs1[i]);
6726         break;
6727       case SPAN:
6728         printf (" %x: %s (pagespan) r%d,r%d,%8x\n",start+i*4,insn[i],rs1[i],rs2[i],ba[i]);break;
6729       case IMM16:
6730         if(opcode[i]==0xf) //LUI
6731           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],rt1[i],imm[i]&0xffff);
6732         else
6733           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6734         break;
6735       case LOAD:
6736       case LOADLR:
6737         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6738         break;
6739       case STORE:
6740       case STORELR:
6741         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],rs2[i],rs1[i],imm[i]);
6742         break;
6743       case ALU:
6744       case SHIFT:
6745         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],rt1[i],rs1[i],rs2[i]);
6746         break;
6747       case MULTDIV:
6748         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],rs1[i],rs2[i]);
6749         break;
6750       case SHIFTIMM:
6751         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6752         break;
6753       case MOV:
6754         if((opcode2[i]&0x1d)==0x10)
6755           printf (" %x: %s r%d\n",start+i*4,insn[i],rt1[i]);
6756         else if((opcode2[i]&0x1d)==0x11)
6757           printf (" %x: %s r%d\n",start+i*4,insn[i],rs1[i]);
6758         else
6759           printf (" %x: %s\n",start+i*4,insn[i]);
6760         break;
6761       case COP0:
6762         if(opcode2[i]==0)
6763           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC0
6764         else if(opcode2[i]==4)
6765           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC0
6766         else printf (" %x: %s\n",start+i*4,insn[i]);
6767         break;
6768       case COP1:
6769         if(opcode2[i]<3)
6770           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC1
6771         else if(opcode2[i]>3)
6772           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC1
6773         else printf (" %x: %s\n",start+i*4,insn[i]);
6774         break;
6775       case COP2:
6776         if(opcode2[i]<3)
6777           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC2
6778         else if(opcode2[i]>3)
6779           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC2
6780         else printf (" %x: %s\n",start+i*4,insn[i]);
6781         break;
6782       case C1LS:
6783         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,rs1[i],imm[i]);
6784         break;
6785       case C2LS:
6786         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,rs1[i],imm[i]);
6787         break;
6788       case INTCALL:
6789         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6790         break;
6791       default:
6792         //printf (" %s %8x\n",insn[i],source[i]);
6793         printf (" %x: %s\n",start+i*4,insn[i]);
6794     }
6795 }
6796 #else
6797 static void disassemble_inst(int i) {}
6798 #endif // DISASM
6799
6800 #define DRC_TEST_VAL 0x74657374
6801
6802 static void new_dynarec_test(void)
6803 {
6804   int (*testfunc)(void);
6805   void *beginning;
6806   int ret[2];
6807   size_t i;
6808
6809   // check structure linkage
6810   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6811   {
6812     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6813   }
6814
6815   SysPrintf("testing if we can run recompiled code...\n");
6816   ((volatile u_int *)out)[0]++; // make cache dirty
6817
6818   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6819     out = ndrc->translation_cache;
6820     beginning = start_block();
6821     emit_movimm(DRC_TEST_VAL + i, 0); // test
6822     emit_ret();
6823     literal_pool(0);
6824     end_block(beginning);
6825     testfunc = beginning;
6826     ret[i] = testfunc();
6827   }
6828
6829   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6830     SysPrintf("test passed.\n");
6831   else
6832     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6833   out = ndrc->translation_cache;
6834 }
6835
6836 // clear the state completely, instead of just marking
6837 // things invalid like invalidate_all_pages() does
6838 void new_dynarec_clear_full(void)
6839 {
6840   int n;
6841   out = ndrc->translation_cache;
6842   memset(invalid_code,1,sizeof(invalid_code));
6843   memset(hash_table,0xff,sizeof(hash_table));
6844   memset(mini_ht,-1,sizeof(mini_ht));
6845   memset(restore_candidate,0,sizeof(restore_candidate));
6846   memset(shadow,0,sizeof(shadow));
6847   copy=shadow;
6848   expirep=16384; // Expiry pointer, +2 blocks
6849   pending_exception=0;
6850   literalcount=0;
6851   stop_after_jal=0;
6852   inv_code_start=inv_code_end=~0;
6853   // TLB
6854   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6855   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6856   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6857
6858   cycle_multiplier_old = cycle_multiplier;
6859   new_dynarec_hacks_old = new_dynarec_hacks;
6860 }
6861
6862 void new_dynarec_init(void)
6863 {
6864   SysPrintf("Init new dynarec\n");
6865
6866 #ifdef BASE_ADDR_DYNAMIC
6867   #ifdef VITA
6868   sceBlock = sceKernelAllocMemBlockForVM("code", 1 << TARGET_SIZE_2);
6869   if (sceBlock < 0)
6870     SysPrintf("sceKernelAllocMemBlockForVM failed\n");
6871   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6872   if (ret < 0)
6873     SysPrintf("sceKernelGetMemBlockBase failed\n");
6874   #else
6875   uintptr_t desired_addr = 0;
6876   #ifdef __ELF__
6877   extern char _end;
6878   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6879   #endif
6880   ndrc = mmap((void *)desired_addr, sizeof(*ndrc),
6881             PROT_READ | PROT_WRITE | PROT_EXEC,
6882             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
6883   if (ndrc == MAP_FAILED) {
6884     SysPrintf("mmap() failed: %s\n", strerror(errno));
6885     abort();
6886   }
6887   #endif
6888 #else
6889   #ifndef NO_WRITE_EXEC
6890   // not all systems allow execute in data segment by default
6891   if (mprotect(ndrc, sizeof(ndrc->translation_cache) + sizeof(ndrc->tramp.ops),
6892                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6893     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6894   #endif
6895 #endif
6896   out = ndrc->translation_cache;
6897   cycle_multiplier=200;
6898   new_dynarec_clear_full();
6899 #ifdef HOST_IMM8
6900   // Copy this into local area so we don't have to put it in every literal pool
6901   invc_ptr=invalid_code;
6902 #endif
6903   arch_init();
6904   new_dynarec_test();
6905 #ifndef RAM_FIXED
6906   ram_offset=(uintptr_t)rdram-0x80000000;
6907 #endif
6908   if (ram_offset!=0)
6909     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6910 }
6911
6912 void new_dynarec_cleanup(void)
6913 {
6914   int n;
6915 #ifdef BASE_ADDR_DYNAMIC
6916   #ifdef VITA
6917   sceKernelFreeMemBlock(sceBlock);
6918   sceBlock = -1;
6919   #else
6920   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6921     SysPrintf("munmap() failed\n");
6922   #endif
6923 #endif
6924   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6925   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6926   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6927   #ifdef ROM_COPY
6928   if (munmap (ROM_COPY, 67108864) < 0) {SysPrintf("munmap() failed\n");}
6929   #endif
6930 }
6931
6932 static u_int *get_source_start(u_int addr, u_int *limit)
6933 {
6934   if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6935     cycle_multiplier_override = 0;
6936
6937   if (addr < 0x00200000 ||
6938     (0xa0000000 <= addr && addr < 0xa0200000))
6939   {
6940     // used for BIOS calls mostly?
6941     *limit = (addr&0xa0000000)|0x00200000;
6942     return (u_int *)(rdram + (addr&0x1fffff));
6943   }
6944   else if (!Config.HLE && (
6945     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
6946     (0xbfc00000 <= addr && addr < 0xbfc80000)))
6947   {
6948     // BIOS. The multiplier should be much higher as it's uncached 8bit mem,
6949     // but timings in PCSX are too tied to the interpreter's BIAS
6950     if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6951       cycle_multiplier_override = 200;
6952
6953     *limit = (addr & 0xfff00000) | 0x80000;
6954     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
6955   }
6956   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
6957     *limit = (addr & 0x80600000) + 0x00200000;
6958     return (u_int *)(rdram + (addr&0x1fffff));
6959   }
6960   return NULL;
6961 }
6962
6963 static u_int scan_for_ret(u_int addr)
6964 {
6965   u_int limit = 0;
6966   u_int *mem;
6967
6968   mem = get_source_start(addr, &limit);
6969   if (mem == NULL)
6970     return addr;
6971
6972   if (limit > addr + 0x1000)
6973     limit = addr + 0x1000;
6974   for (; addr < limit; addr += 4, mem++) {
6975     if (*mem == 0x03e00008) // jr $ra
6976       return addr + 8;
6977   }
6978   return addr;
6979 }
6980
6981 struct savestate_block {
6982   uint32_t addr;
6983   uint32_t regflags;
6984 };
6985
6986 static int addr_cmp(const void *p1_, const void *p2_)
6987 {
6988   const struct savestate_block *p1 = p1_, *p2 = p2_;
6989   return p1->addr - p2->addr;
6990 }
6991
6992 int new_dynarec_save_blocks(void *save, int size)
6993 {
6994   struct savestate_block *blocks = save;
6995   int maxcount = size / sizeof(blocks[0]);
6996   struct savestate_block tmp_blocks[1024];
6997   struct ll_entry *head;
6998   int p, s, d, o, bcnt;
6999   u_int addr;
7000
7001   o = 0;
7002   for (p = 0; p < ARRAY_SIZE(jump_in); p++) {
7003     bcnt = 0;
7004     for (head = jump_in[p]; head != NULL; head = head->next) {
7005       tmp_blocks[bcnt].addr = head->vaddr;
7006       tmp_blocks[bcnt].regflags = head->reg_sv_flags;
7007       bcnt++;
7008     }
7009     if (bcnt < 1)
7010       continue;
7011     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
7012
7013     addr = tmp_blocks[0].addr;
7014     for (s = d = 0; s < bcnt; s++) {
7015       if (tmp_blocks[s].addr < addr)
7016         continue;
7017       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
7018         tmp_blocks[d++] = tmp_blocks[s];
7019       addr = scan_for_ret(tmp_blocks[s].addr);
7020     }
7021
7022     if (o + d > maxcount)
7023       d = maxcount - o;
7024     memcpy(&blocks[o], tmp_blocks, d * sizeof(blocks[0]));
7025     o += d;
7026   }
7027
7028   return o * sizeof(blocks[0]);
7029 }
7030
7031 void new_dynarec_load_blocks(const void *save, int size)
7032 {
7033   const struct savestate_block *blocks = save;
7034   int count = size / sizeof(blocks[0]);
7035   u_int regs_save[32];
7036   uint32_t f;
7037   int i, b;
7038
7039   get_addr(psxRegs.pc);
7040
7041   // change GPRs for speculation to at least partially work..
7042   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
7043   for (i = 1; i < 32; i++)
7044     psxRegs.GPR.r[i] = 0x80000000;
7045
7046   for (b = 0; b < count; b++) {
7047     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
7048       if (f & 1)
7049         psxRegs.GPR.r[i] = 0x1f800000;
7050     }
7051
7052     get_addr(blocks[b].addr);
7053
7054     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
7055       if (f & 1)
7056         psxRegs.GPR.r[i] = 0x80000000;
7057     }
7058   }
7059
7060   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
7061 }
7062
7063 int new_recompile_block(u_int addr)
7064 {
7065   u_int pagelimit = 0;
7066   u_int state_rflags = 0;
7067   int i;
7068
7069   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
7070   //printf("TRACE: count=%d next=%d (compile %x)\n",Count,next_interupt,addr);
7071   //if(debug)
7072   //printf("fpu mapping=%x enabled=%x\n",(Status & 0x04000000)>>26,(Status & 0x20000000)>>29);
7073
7074   // this is just for speculation
7075   for (i = 1; i < 32; i++) {
7076     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
7077       state_rflags |= 1 << i;
7078   }
7079
7080   start = (u_int)addr&~3;
7081   //assert(((u_int)addr&1)==0); // start-in-delay-slot flag
7082   new_dynarec_did_compile=1;
7083   if (Config.HLE && start == 0x80001000) // hlecall
7084   {
7085     // XXX: is this enough? Maybe check hleSoftCall?
7086     void *beginning=start_block();
7087     u_int page=get_page(start);
7088
7089     invalid_code[start>>12]=0;
7090     emit_movimm(start,0);
7091     emit_writeword(0,&pcaddr);
7092     emit_far_jump(new_dyna_leave);
7093     literal_pool(0);
7094     end_block(beginning);
7095     ll_add_flags(jump_in+page,start,state_rflags,(void *)beginning);
7096     return 0;
7097   }
7098
7099   source = get_source_start(start, &pagelimit);
7100   if (source == NULL) {
7101     SysPrintf("Compile at bogus memory address: %08x\n", addr);
7102     abort();
7103   }
7104
7105   /* Pass 1: disassemble */
7106   /* Pass 2: register dependencies, branch targets */
7107   /* Pass 3: register allocation */
7108   /* Pass 4: branch dependencies */
7109   /* Pass 5: pre-alloc */
7110   /* Pass 6: optimize clean/dirty state */
7111   /* Pass 7: flag 32-bit registers */
7112   /* Pass 8: assembly */
7113   /* Pass 9: linker */
7114   /* Pass 10: garbage collection / free memory */
7115
7116   int j;
7117   int done=0;
7118   unsigned int type,op,op2;
7119
7120   //printf("addr = %x source = %x %x\n", addr,source,source[0]);
7121
7122   /* Pass 1 disassembly */
7123
7124   for(i=0;!done;i++) {
7125     bt[i]=0;likely[i]=0;ooo[i]=0;op2=0;
7126     minimum_free_regs[i]=0;
7127     opcode[i]=op=source[i]>>26;
7128     switch(op)
7129     {
7130       case 0x00: strcpy(insn[i],"special"); type=NI;
7131         op2=source[i]&0x3f;
7132         switch(op2)
7133         {
7134           case 0x00: strcpy(insn[i],"SLL"); type=SHIFTIMM; break;
7135           case 0x02: strcpy(insn[i],"SRL"); type=SHIFTIMM; break;
7136           case 0x03: strcpy(insn[i],"SRA"); type=SHIFTIMM; break;
7137           case 0x04: strcpy(insn[i],"SLLV"); type=SHIFT; break;
7138           case 0x06: strcpy(insn[i],"SRLV"); type=SHIFT; break;
7139           case 0x07: strcpy(insn[i],"SRAV"); type=SHIFT; break;
7140           case 0x08: strcpy(insn[i],"JR"); type=RJUMP; break;
7141           case 0x09: strcpy(insn[i],"JALR"); type=RJUMP; break;
7142           case 0x0C: strcpy(insn[i],"SYSCALL"); type=SYSCALL; break;
7143           case 0x0D: strcpy(insn[i],"BREAK"); type=OTHER; break;
7144           case 0x0F: strcpy(insn[i],"SYNC"); type=OTHER; break;
7145           case 0x10: strcpy(insn[i],"MFHI"); type=MOV; break;
7146           case 0x11: strcpy(insn[i],"MTHI"); type=MOV; break;
7147           case 0x12: strcpy(insn[i],"MFLO"); type=MOV; break;
7148           case 0x13: strcpy(insn[i],"MTLO"); type=MOV; break;
7149           case 0x18: strcpy(insn[i],"MULT"); type=MULTDIV; break;
7150           case 0x19: strcpy(insn[i],"MULTU"); type=MULTDIV; break;
7151           case 0x1A: strcpy(insn[i],"DIV"); type=MULTDIV; break;
7152           case 0x1B: strcpy(insn[i],"DIVU"); type=MULTDIV; break;
7153           case 0x20: strcpy(insn[i],"ADD"); type=ALU; break;
7154           case 0x21: strcpy(insn[i],"ADDU"); type=ALU; break;
7155           case 0x22: strcpy(insn[i],"SUB"); type=ALU; break;
7156           case 0x23: strcpy(insn[i],"SUBU"); type=ALU; break;
7157           case 0x24: strcpy(insn[i],"AND"); type=ALU; break;
7158           case 0x25: strcpy(insn[i],"OR"); type=ALU; break;
7159           case 0x26: strcpy(insn[i],"XOR"); type=ALU; break;
7160           case 0x27: strcpy(insn[i],"NOR"); type=ALU; break;
7161           case 0x2A: strcpy(insn[i],"SLT"); type=ALU; break;
7162           case 0x2B: strcpy(insn[i],"SLTU"); type=ALU; break;
7163           case 0x30: strcpy(insn[i],"TGE"); type=NI; break;
7164           case 0x31: strcpy(insn[i],"TGEU"); type=NI; break;
7165           case 0x32: strcpy(insn[i],"TLT"); type=NI; break;
7166           case 0x33: strcpy(insn[i],"TLTU"); type=NI; break;
7167           case 0x34: strcpy(insn[i],"TEQ"); type=NI; break;
7168           case 0x36: strcpy(insn[i],"TNE"); type=NI; break;
7169 #if 0
7170           case 0x14: strcpy(insn[i],"DSLLV"); type=SHIFT; break;
7171           case 0x16: strcpy(insn[i],"DSRLV"); type=SHIFT; break;
7172           case 0x17: strcpy(insn[i],"DSRAV"); type=SHIFT; break;
7173           case 0x1C: strcpy(insn[i],"DMULT"); type=MULTDIV; break;
7174           case 0x1D: strcpy(insn[i],"DMULTU"); type=MULTDIV; break;
7175           case 0x1E: strcpy(insn[i],"DDIV"); type=MULTDIV; break;
7176           case 0x1F: strcpy(insn[i],"DDIVU"); type=MULTDIV; break;
7177           case 0x2C: strcpy(insn[i],"DADD"); type=ALU; break;
7178           case 0x2D: strcpy(insn[i],"DADDU"); type=ALU; break;
7179           case 0x2E: strcpy(insn[i],"DSUB"); type=ALU; break;
7180           case 0x2F: strcpy(insn[i],"DSUBU"); type=ALU; break;
7181           case 0x38: strcpy(insn[i],"DSLL"); type=SHIFTIMM; break;
7182           case 0x3A: strcpy(insn[i],"DSRL"); type=SHIFTIMM; break;
7183           case 0x3B: strcpy(insn[i],"DSRA"); type=SHIFTIMM; break;
7184           case 0x3C: strcpy(insn[i],"DSLL32"); type=SHIFTIMM; break;
7185           case 0x3E: strcpy(insn[i],"DSRL32"); type=SHIFTIMM; break;
7186           case 0x3F: strcpy(insn[i],"DSRA32"); type=SHIFTIMM; break;
7187 #endif
7188         }
7189         break;
7190       case 0x01: strcpy(insn[i],"regimm"); type=NI;
7191         op2=(source[i]>>16)&0x1f;
7192         switch(op2)
7193         {
7194           case 0x00: strcpy(insn[i],"BLTZ"); type=SJUMP; break;
7195           case 0x01: strcpy(insn[i],"BGEZ"); type=SJUMP; break;
7196           case 0x02: strcpy(insn[i],"BLTZL"); type=SJUMP; break;
7197           case 0x03: strcpy(insn[i],"BGEZL"); type=SJUMP; break;
7198           case 0x08: strcpy(insn[i],"TGEI"); type=NI; break;
7199           case 0x09: strcpy(insn[i],"TGEIU"); type=NI; break;
7200           case 0x0A: strcpy(insn[i],"TLTI"); type=NI; break;
7201           case 0x0B: strcpy(insn[i],"TLTIU"); type=NI; break;
7202           case 0x0C: strcpy(insn[i],"TEQI"); type=NI; break;
7203           case 0x0E: strcpy(insn[i],"TNEI"); type=NI; break;
7204           case 0x10: strcpy(insn[i],"BLTZAL"); type=SJUMP; break;
7205           case 0x11: strcpy(insn[i],"BGEZAL"); type=SJUMP; break;
7206           case 0x12: strcpy(insn[i],"BLTZALL"); type=SJUMP; break;
7207           case 0x13: strcpy(insn[i],"BGEZALL"); type=SJUMP; break;
7208         }
7209         break;
7210       case 0x02: strcpy(insn[i],"J"); type=UJUMP; break;
7211       case 0x03: strcpy(insn[i],"JAL"); type=UJUMP; break;
7212       case 0x04: strcpy(insn[i],"BEQ"); type=CJUMP; break;
7213       case 0x05: strcpy(insn[i],"BNE"); type=CJUMP; break;
7214       case 0x06: strcpy(insn[i],"BLEZ"); type=CJUMP; break;
7215       case 0x07: strcpy(insn[i],"BGTZ"); type=CJUMP; break;
7216       case 0x08: strcpy(insn[i],"ADDI"); type=IMM16; break;
7217       case 0x09: strcpy(insn[i],"ADDIU"); type=IMM16; break;
7218       case 0x0A: strcpy(insn[i],"SLTI"); type=IMM16; break;
7219       case 0x0B: strcpy(insn[i],"SLTIU"); type=IMM16; break;
7220       case 0x0C: strcpy(insn[i],"ANDI"); type=IMM16; break;
7221       case 0x0D: strcpy(insn[i],"ORI"); type=IMM16; break;
7222       case 0x0E: strcpy(insn[i],"XORI"); type=IMM16; break;
7223       case 0x0F: strcpy(insn[i],"LUI"); type=IMM16; break;
7224       case 0x10: strcpy(insn[i],"cop0"); type=NI;
7225         op2=(source[i]>>21)&0x1f;
7226         switch(op2)
7227         {
7228           case 0x00: strcpy(insn[i],"MFC0"); type=COP0; break;
7229           case 0x02: strcpy(insn[i],"CFC0"); type=COP0; break;
7230           case 0x04: strcpy(insn[i],"MTC0"); type=COP0; break;
7231           case 0x06: strcpy(insn[i],"CTC0"); type=COP0; break;
7232           case 0x10: strcpy(insn[i],"RFE"); type=COP0; break;
7233         }
7234         break;
7235       case 0x11: strcpy(insn[i],"cop1"); type=COP1;
7236         op2=(source[i]>>21)&0x1f;
7237         break;
7238 #if 0
7239       case 0x14: strcpy(insn[i],"BEQL"); type=CJUMP; break;
7240       case 0x15: strcpy(insn[i],"BNEL"); type=CJUMP; break;
7241       case 0x16: strcpy(insn[i],"BLEZL"); type=CJUMP; break;
7242       case 0x17: strcpy(insn[i],"BGTZL"); type=CJUMP; break;
7243       case 0x18: strcpy(insn[i],"DADDI"); type=IMM16; break;
7244       case 0x19: strcpy(insn[i],"DADDIU"); type=IMM16; break;
7245       case 0x1A: strcpy(insn[i],"LDL"); type=LOADLR; break;
7246       case 0x1B: strcpy(insn[i],"LDR"); type=LOADLR; break;
7247 #endif
7248       case 0x20: strcpy(insn[i],"LB"); type=LOAD; break;
7249       case 0x21: strcpy(insn[i],"LH"); type=LOAD; break;
7250       case 0x22: strcpy(insn[i],"LWL"); type=LOADLR; break;
7251       case 0x23: strcpy(insn[i],"LW"); type=LOAD; break;
7252       case 0x24: strcpy(insn[i],"LBU"); type=LOAD; break;
7253       case 0x25: strcpy(insn[i],"LHU"); type=LOAD; break;
7254       case 0x26: strcpy(insn[i],"LWR"); type=LOADLR; break;
7255 #if 0
7256       case 0x27: strcpy(insn[i],"LWU"); type=LOAD; break;
7257 #endif
7258       case 0x28: strcpy(insn[i],"SB"); type=STORE; break;
7259       case 0x29: strcpy(insn[i],"SH"); type=STORE; break;
7260       case 0x2A: strcpy(insn[i],"SWL"); type=STORELR; break;
7261       case 0x2B: strcpy(insn[i],"SW"); type=STORE; break;
7262 #if 0
7263       case 0x2C: strcpy(insn[i],"SDL"); type=STORELR; break;
7264       case 0x2D: strcpy(insn[i],"SDR"); type=STORELR; break;
7265 #endif
7266       case 0x2E: strcpy(insn[i],"SWR"); type=STORELR; break;
7267       case 0x2F: strcpy(insn[i],"CACHE"); type=NOP; break;
7268       case 0x30: strcpy(insn[i],"LL"); type=NI; break;
7269       case 0x31: strcpy(insn[i],"LWC1"); type=C1LS; break;
7270 #if 0
7271       case 0x34: strcpy(insn[i],"LLD"); type=NI; break;
7272       case 0x35: strcpy(insn[i],"LDC1"); type=C1LS; break;
7273       case 0x37: strcpy(insn[i],"LD"); type=LOAD; break;
7274 #endif
7275       case 0x38: strcpy(insn[i],"SC"); type=NI; break;
7276       case 0x39: strcpy(insn[i],"SWC1"); type=C1LS; break;
7277 #if 0
7278       case 0x3C: strcpy(insn[i],"SCD"); type=NI; break;
7279       case 0x3D: strcpy(insn[i],"SDC1"); type=C1LS; break;
7280       case 0x3F: strcpy(insn[i],"SD"); type=STORE; break;
7281 #endif
7282       case 0x12: strcpy(insn[i],"COP2"); type=NI;
7283         op2=(source[i]>>21)&0x1f;
7284         //if (op2 & 0x10)
7285         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
7286           if (gte_handlers[source[i]&0x3f]!=NULL) {
7287             if (gte_regnames[source[i]&0x3f]!=NULL)
7288               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
7289             else
7290               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
7291             type=C2OP;
7292           }
7293         }
7294         else switch(op2)
7295         {
7296           case 0x00: strcpy(insn[i],"MFC2"); type=COP2; break;
7297           case 0x02: strcpy(insn[i],"CFC2"); type=COP2; break;
7298           case 0x04: strcpy(insn[i],"MTC2"); type=COP2; break;
7299           case 0x06: strcpy(insn[i],"CTC2"); type=COP2; break;
7300         }
7301         break;
7302       case 0x32: strcpy(insn[i],"LWC2"); type=C2LS; break;
7303       case 0x3A: strcpy(insn[i],"SWC2"); type=C2LS; break;
7304       case 0x3B: strcpy(insn[i],"HLECALL"); type=HLECALL; break;
7305       default: strcpy(insn[i],"???"); type=NI;
7306         SysPrintf("NI %08x @%08x (%08x)\n", source[i], addr + i*4, addr);
7307         break;
7308     }
7309     itype[i]=type;
7310     opcode2[i]=op2;
7311     /* Get registers/immediates */
7312     lt1[i]=0;
7313     dep1[i]=0;
7314     dep2[i]=0;
7315     gte_rs[i]=gte_rt[i]=0;
7316     switch(type) {
7317       case LOAD:
7318         rs1[i]=(source[i]>>21)&0x1f;
7319         rs2[i]=0;
7320         rt1[i]=(source[i]>>16)&0x1f;
7321         rt2[i]=0;
7322         imm[i]=(short)source[i];
7323         break;
7324       case STORE:
7325       case STORELR:
7326         rs1[i]=(source[i]>>21)&0x1f;
7327         rs2[i]=(source[i]>>16)&0x1f;
7328         rt1[i]=0;
7329         rt2[i]=0;
7330         imm[i]=(short)source[i];
7331         break;
7332       case LOADLR:
7333         // LWL/LWR only load part of the register,
7334         // therefore the target register must be treated as a source too
7335         rs1[i]=(source[i]>>21)&0x1f;
7336         rs2[i]=(source[i]>>16)&0x1f;
7337         rt1[i]=(source[i]>>16)&0x1f;
7338         rt2[i]=0;
7339         imm[i]=(short)source[i];
7340         if(op==0x26) dep1[i]=rt1[i]; // LWR
7341         break;
7342       case IMM16:
7343         if (op==0x0f) rs1[i]=0; // LUI instruction has no source register
7344         else rs1[i]=(source[i]>>21)&0x1f;
7345         rs2[i]=0;
7346         rt1[i]=(source[i]>>16)&0x1f;
7347         rt2[i]=0;
7348         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
7349           imm[i]=(unsigned short)source[i];
7350         }else{
7351           imm[i]=(short)source[i];
7352         }
7353         if(op==0x0d||op==0x0e) dep1[i]=rs1[i]; // ORI/XORI
7354         break;
7355       case UJUMP:
7356         rs1[i]=0;
7357         rs2[i]=0;
7358         rt1[i]=0;
7359         rt2[i]=0;
7360         // The JAL instruction writes to r31.
7361         if (op&1) {
7362           rt1[i]=31;
7363         }
7364         rs2[i]=CCREG;
7365         break;
7366       case RJUMP:
7367         rs1[i]=(source[i]>>21)&0x1f;
7368         rs2[i]=0;
7369         rt1[i]=0;
7370         rt2[i]=0;
7371         // The JALR instruction writes to rd.
7372         if (op2&1) {
7373           rt1[i]=(source[i]>>11)&0x1f;
7374         }
7375         rs2[i]=CCREG;
7376         break;
7377       case CJUMP:
7378         rs1[i]=(source[i]>>21)&0x1f;
7379         rs2[i]=(source[i]>>16)&0x1f;
7380         rt1[i]=0;
7381         rt2[i]=0;
7382         if(op&2) { // BGTZ/BLEZ
7383           rs2[i]=0;
7384         }
7385         likely[i]=op>>4;
7386         break;
7387       case SJUMP:
7388         rs1[i]=(source[i]>>21)&0x1f;
7389         rs2[i]=CCREG;
7390         rt1[i]=0;
7391         rt2[i]=0;
7392         if(op2&0x10) { // BxxAL
7393           rt1[i]=31;
7394           // NOTE: If the branch is not taken, r31 is still overwritten
7395         }
7396         likely[i]=(op2&2)>>1;
7397         break;
7398       case ALU:
7399         rs1[i]=(source[i]>>21)&0x1f; // source
7400         rs2[i]=(source[i]>>16)&0x1f; // subtract amount
7401         rt1[i]=(source[i]>>11)&0x1f; // destination
7402         rt2[i]=0;
7403         if(op2>=0x24&&op2<=0x27) { // AND/OR/XOR/NOR
7404           dep1[i]=rs1[i];dep2[i]=rs2[i];
7405         }
7406         else if(op2>=0x2c&&op2<=0x2f) { // DADD/DSUB
7407           dep1[i]=rs1[i];dep2[i]=rs2[i];
7408         }
7409         break;
7410       case MULTDIV:
7411         rs1[i]=(source[i]>>21)&0x1f; // source
7412         rs2[i]=(source[i]>>16)&0x1f; // divisor
7413         rt1[i]=HIREG;
7414         rt2[i]=LOREG;
7415         break;
7416       case MOV:
7417         rs1[i]=0;
7418         rs2[i]=0;
7419         rt1[i]=0;
7420         rt2[i]=0;
7421         if(op2==0x10) rs1[i]=HIREG; // MFHI
7422         if(op2==0x11) rt1[i]=HIREG; // MTHI
7423         if(op2==0x12) rs1[i]=LOREG; // MFLO
7424         if(op2==0x13) rt1[i]=LOREG; // MTLO
7425         if((op2&0x1d)==0x10) rt1[i]=(source[i]>>11)&0x1f; // MFxx
7426         if((op2&0x1d)==0x11) rs1[i]=(source[i]>>21)&0x1f; // MTxx
7427         dep1[i]=rs1[i];
7428         break;
7429       case SHIFT:
7430         rs1[i]=(source[i]>>16)&0x1f; // target of shift
7431         rs2[i]=(source[i]>>21)&0x1f; // shift amount
7432         rt1[i]=(source[i]>>11)&0x1f; // destination
7433         rt2[i]=0;
7434         break;
7435       case SHIFTIMM:
7436         rs1[i]=(source[i]>>16)&0x1f;
7437         rs2[i]=0;
7438         rt1[i]=(source[i]>>11)&0x1f;
7439         rt2[i]=0;
7440         imm[i]=(source[i]>>6)&0x1f;
7441         // DSxx32 instructions
7442         if(op2>=0x3c) imm[i]|=0x20;
7443         break;
7444       case COP0:
7445         rs1[i]=0;
7446         rs2[i]=0;
7447         rt1[i]=0;
7448         rt2[i]=0;
7449         if(op2==0||op2==2) rt1[i]=(source[i]>>16)&0x1F; // MFC0/CFC0
7450         if(op2==4||op2==6) rs1[i]=(source[i]>>16)&0x1F; // MTC0/CTC0
7451         if(op2==4&&((source[i]>>11)&0x1f)==12) rt2[i]=CSREG; // Status
7452         if(op2==16) if((source[i]&0x3f)==0x18) rs2[i]=CCREG; // ERET
7453         break;
7454       case COP1:
7455         rs1[i]=0;
7456         rs2[i]=0;
7457         rt1[i]=0;
7458         rt2[i]=0;
7459         if(op2<3) rt1[i]=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
7460         if(op2>3) rs1[i]=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
7461         rs2[i]=CSREG;
7462         break;
7463       case COP2:
7464         rs1[i]=0;
7465         rs2[i]=0;
7466         rt1[i]=0;
7467         rt2[i]=0;
7468         if(op2<3) rt1[i]=(source[i]>>16)&0x1F; // MFC2/CFC2
7469         if(op2>3) rs1[i]=(source[i]>>16)&0x1F; // MTC2/CTC2
7470         rs2[i]=CSREG;
7471         int gr=(source[i]>>11)&0x1F;
7472         switch(op2)
7473         {
7474           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
7475           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
7476           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
7477           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
7478         }
7479         break;
7480       case C1LS:
7481         rs1[i]=(source[i]>>21)&0x1F;
7482         rs2[i]=CSREG;
7483         rt1[i]=0;
7484         rt2[i]=0;
7485         imm[i]=(short)source[i];
7486         break;
7487       case C2LS:
7488         rs1[i]=(source[i]>>21)&0x1F;
7489         rs2[i]=0;
7490         rt1[i]=0;
7491         rt2[i]=0;
7492         imm[i]=(short)source[i];
7493         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
7494         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
7495         break;
7496       case C2OP:
7497         rs1[i]=0;
7498         rs2[i]=0;
7499         rt1[i]=0;
7500         rt2[i]=0;
7501         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
7502         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
7503         gte_rt[i]|=1ll<<63; // every op changes flags
7504         if((source[i]&0x3f)==GTE_MVMVA) {
7505           int v = (source[i] >> 15) & 3;
7506           gte_rs[i]&=~0xe3fll;
7507           if(v==3) gte_rs[i]|=0xe00ll;
7508           else gte_rs[i]|=3ll<<(v*2);
7509         }
7510         break;
7511       case SYSCALL:
7512       case HLECALL:
7513       case INTCALL:
7514         rs1[i]=CCREG;
7515         rs2[i]=0;
7516         rt1[i]=0;
7517         rt2[i]=0;
7518         break;
7519       default:
7520         rs1[i]=0;
7521         rs2[i]=0;
7522         rt1[i]=0;
7523         rt2[i]=0;
7524     }
7525     /* Calculate branch target addresses */
7526     if(type==UJUMP)
7527       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
7528     else if(type==CJUMP&&rs1[i]==rs2[i]&&(op&1))
7529       ba[i]=start+i*4+8; // Ignore never taken branch
7530     else if(type==SJUMP&&rs1[i]==0&&!(op2&1))
7531       ba[i]=start+i*4+8; // Ignore never taken branch
7532     else if(type==CJUMP||type==SJUMP)
7533       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
7534     else ba[i]=-1;
7535     if (i > 0 && is_jump(i-1)) {
7536       int do_in_intrp=0;
7537       // branch in delay slot?
7538       if(type==RJUMP||type==UJUMP||type==CJUMP||type==SJUMP) {
7539         // don't handle first branch and call interpreter if it's hit
7540         SysPrintf("branch in delay slot @%08x (%08x)\n", addr + i*4, addr);
7541         do_in_intrp=1;
7542       }
7543       // basic load delay detection
7544       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&rt1[i]!=0) {
7545         int t=(ba[i-1]-start)/4;
7546         if(0 <= t && t < i &&(rt1[i]==rs1[t]||rt1[i]==rs2[t])&&itype[t]!=CJUMP&&itype[t]!=SJUMP) {
7547           // jump target wants DS result - potential load delay effect
7548           SysPrintf("load delay @%08x (%08x)\n", addr + i*4, addr);
7549           do_in_intrp=1;
7550           bt[t+1]=1; // expected return from interpreter
7551         }
7552         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&&
7553               !(i>=3&&is_jump(i-3))) {
7554           // v0 overwrite like this is a sign of trouble, bail out
7555           SysPrintf("v0 overwrite @%08x (%08x)\n", addr + i*4, addr);
7556           do_in_intrp=1;
7557         }
7558       }
7559       if(do_in_intrp) {
7560         rs1[i-1]=CCREG;
7561         rs2[i-1]=rt1[i-1]=rt2[i-1]=0;
7562         ba[i-1]=-1;
7563         itype[i-1]=INTCALL;
7564         done=2;
7565         i--; // don't compile the DS
7566       }
7567     }
7568     /* Is this the end of the block? */
7569     if (i > 0 && is_ujump(i-1)) {
7570       if(rt1[i-1]==0) { // Continue past subroutine call (JAL)
7571         done=2;
7572       }
7573       else {
7574         if(stop_after_jal) done=1;
7575         // Stop on BREAK
7576         if((source[i+1]&0xfc00003f)==0x0d) done=1;
7577       }
7578       // Don't recompile stuff that's already compiled
7579       if(check_addr(start+i*4+4)) done=1;
7580       // Don't get too close to the limit
7581       if(i>MAXBLOCK/2) done=1;
7582     }
7583     if(itype[i]==SYSCALL&&stop_after_jal) done=1;
7584     if(itype[i]==HLECALL||itype[i]==INTCALL) done=2;
7585     if(done==2) {
7586       // Does the block continue due to a branch?
7587       for(j=i-1;j>=0;j--)
7588       {
7589         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
7590         if(ba[j]==start+i*4+4) done=j=0;
7591         if(ba[j]==start+i*4+8) done=j=0;
7592       }
7593     }
7594     //assert(i<MAXBLOCK-1);
7595     if(start+i*4==pagelimit-4) done=1;
7596     assert(start+i*4<pagelimit);
7597     if (i==MAXBLOCK-1) done=1;
7598     // Stop if we're compiling junk
7599     if(itype[i]==NI&&opcode[i]==0x11) {
7600       done=stop_after_jal=1;
7601       SysPrintf("Disabled speculative precompilation\n");
7602     }
7603   }
7604   slen=i;
7605   if(itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP||itype[i-1]==RJUMP) {
7606     if(start+i*4==pagelimit) {
7607       itype[i-1]=SPAN;
7608     }
7609   }
7610   assert(slen>0);
7611
7612   /* Pass 2 - Register dependencies and branch targets */
7613
7614   unneeded_registers(0,slen-1,0);
7615
7616   /* Pass 3 - Register allocation */
7617
7618   struct regstat current; // Current register allocations/status
7619   current.dirty=0;
7620   current.u=unneeded_reg[0];
7621   clear_all_regs(current.regmap);
7622   alloc_reg(&current,0,CCREG);
7623   dirty_reg(&current,CCREG);
7624   current.isconst=0;
7625   current.wasconst=0;
7626   current.waswritten=0;
7627   int ds=0;
7628   int cc=0;
7629   int hr=-1;
7630
7631   if((u_int)addr&1) {
7632     // First instruction is delay slot
7633     cc=-1;
7634     bt[1]=1;
7635     ds=1;
7636     unneeded_reg[0]=1;
7637     current.regmap[HOST_BTREG]=BTREG;
7638   }
7639
7640   for(i=0;i<slen;i++)
7641   {
7642     if(bt[i])
7643     {
7644       int hr;
7645       for(hr=0;hr<HOST_REGS;hr++)
7646       {
7647         // Is this really necessary?
7648         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7649       }
7650       current.isconst=0;
7651       current.waswritten=0;
7652     }
7653
7654     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7655     regs[i].wasconst=current.isconst;
7656     regs[i].wasdirty=current.dirty;
7657     regs[i].loadedconst=0;
7658     if(itype[i]!=UJUMP&&itype[i]!=CJUMP&&itype[i]!=SJUMP&&itype[i]!=RJUMP) {
7659       if(i+1<slen) {
7660         current.u=unneeded_reg[i+1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
7661         current.u|=1;
7662       } else {
7663         current.u=1;
7664       }
7665     } else {
7666       if(i+1<slen) {
7667         current.u=branch_unneeded_reg[i]&~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
7668         current.u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
7669         current.u|=1;
7670       } else { SysPrintf("oops, branch at end of block with no delay slot\n");abort(); }
7671     }
7672     is_ds[i]=ds;
7673     if(ds) {
7674       ds=0; // Skip delay slot, already allocated as part of branch
7675       // ...but we need to alloc it in case something jumps here
7676       if(i+1<slen) {
7677         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7678       }else{
7679         current.u=branch_unneeded_reg[i-1];
7680       }
7681       current.u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
7682       current.u|=1;
7683       struct regstat temp;
7684       memcpy(&temp,&current,sizeof(current));
7685       temp.wasdirty=temp.dirty;
7686       // TODO: Take into account unconditional branches, as below
7687       delayslot_alloc(&temp,i);
7688       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7689       regs[i].wasdirty=temp.wasdirty;
7690       regs[i].dirty=temp.dirty;
7691       regs[i].isconst=0;
7692       regs[i].wasconst=0;
7693       current.isconst=0;
7694       // Create entry (branch target) regmap
7695       for(hr=0;hr<HOST_REGS;hr++)
7696       {
7697         int r=temp.regmap[hr];
7698         if(r>=0) {
7699           if(r!=regmap_pre[i][hr]) {
7700             regs[i].regmap_entry[hr]=-1;
7701           }
7702           else
7703           {
7704               assert(r < 64);
7705               if((current.u>>r)&1) {
7706                 regs[i].regmap_entry[hr]=-1;
7707                 regs[i].regmap[hr]=-1;
7708                 //Don't clear regs in the delay slot as the branch might need them
7709                 //current.regmap[hr]=-1;
7710               }else
7711                 regs[i].regmap_entry[hr]=r;
7712           }
7713         } else {
7714           // First instruction expects CCREG to be allocated
7715           if(i==0&&hr==HOST_CCREG)
7716             regs[i].regmap_entry[hr]=CCREG;
7717           else
7718             regs[i].regmap_entry[hr]=-1;
7719         }
7720       }
7721     }
7722     else { // Not delay slot
7723       switch(itype[i]) {
7724         case UJUMP:
7725           //current.isconst=0; // DEBUG
7726           //current.wasconst=0; // DEBUG
7727           //regs[i].wasconst=0; // DEBUG
7728           clear_const(&current,rt1[i]);
7729           alloc_cc(&current,i);
7730           dirty_reg(&current,CCREG);
7731           if (rt1[i]==31) {
7732             alloc_reg(&current,i,31);
7733             dirty_reg(&current,31);
7734             //assert(rs1[i+1]!=31&&rs2[i+1]!=31);
7735             //assert(rt1[i+1]!=rt1[i]);
7736             #ifdef REG_PREFETCH
7737             alloc_reg(&current,i,PTEMP);
7738             #endif
7739           }
7740           ooo[i]=1;
7741           delayslot_alloc(&current,i+1);
7742           //current.isconst=0; // DEBUG
7743           ds=1;
7744           //printf("i=%d, isconst=%x\n",i,current.isconst);
7745           break;
7746         case RJUMP:
7747           //current.isconst=0;
7748           //current.wasconst=0;
7749           //regs[i].wasconst=0;
7750           clear_const(&current,rs1[i]);
7751           clear_const(&current,rt1[i]);
7752           alloc_cc(&current,i);
7753           dirty_reg(&current,CCREG);
7754           if(rs1[i]!=rt1[i+1]&&rs1[i]!=rt2[i+1]) {
7755             alloc_reg(&current,i,rs1[i]);
7756             if (rt1[i]!=0) {
7757               alloc_reg(&current,i,rt1[i]);
7758               dirty_reg(&current,rt1[i]);
7759               assert(rs1[i+1]!=rt1[i]&&rs2[i+1]!=rt1[i]);
7760               assert(rt1[i+1]!=rt1[i]);
7761               #ifdef REG_PREFETCH
7762               alloc_reg(&current,i,PTEMP);
7763               #endif
7764             }
7765             #ifdef USE_MINI_HT
7766             if(rs1[i]==31) { // JALR
7767               alloc_reg(&current,i,RHASH);
7768               alloc_reg(&current,i,RHTBL);
7769             }
7770             #endif
7771             delayslot_alloc(&current,i+1);
7772           } else {
7773             // The delay slot overwrites our source register,
7774             // allocate a temporary register to hold the old value.
7775             current.isconst=0;
7776             current.wasconst=0;
7777             regs[i].wasconst=0;
7778             delayslot_alloc(&current,i+1);
7779             current.isconst=0;
7780             alloc_reg(&current,i,RTEMP);
7781           }
7782           //current.isconst=0; // DEBUG
7783           ooo[i]=1;
7784           ds=1;
7785           break;
7786         case CJUMP:
7787           //current.isconst=0;
7788           //current.wasconst=0;
7789           //regs[i].wasconst=0;
7790           clear_const(&current,rs1[i]);
7791           clear_const(&current,rs2[i]);
7792           if((opcode[i]&0x3E)==4) // BEQ/BNE
7793           {
7794             alloc_cc(&current,i);
7795             dirty_reg(&current,CCREG);
7796             if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7797             if(rs2[i]) alloc_reg(&current,i,rs2[i]);
7798             if((rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]))||
7799                (rs2[i]&&(rs2[i]==rt1[i+1]||rs2[i]==rt2[i+1]))) {
7800               // The delay slot overwrites one of our conditions.
7801               // Allocate the branch condition registers instead.
7802               current.isconst=0;
7803               current.wasconst=0;
7804               regs[i].wasconst=0;
7805               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7806               if(rs2[i]) alloc_reg(&current,i,rs2[i]);
7807             }
7808             else
7809             {
7810               ooo[i]=1;
7811               delayslot_alloc(&current,i+1);
7812             }
7813           }
7814           else
7815           if((opcode[i]&0x3E)==6) // BLEZ/BGTZ
7816           {
7817             alloc_cc(&current,i);
7818             dirty_reg(&current,CCREG);
7819             alloc_reg(&current,i,rs1[i]);
7820             if(rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1])) {
7821               // The delay slot overwrites one of our conditions.
7822               // Allocate the branch condition registers instead.
7823               current.isconst=0;
7824               current.wasconst=0;
7825               regs[i].wasconst=0;
7826               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7827             }
7828             else
7829             {
7830               ooo[i]=1;
7831               delayslot_alloc(&current,i+1);
7832             }
7833           }
7834           else
7835           // Don't alloc the delay slot yet because we might not execute it
7836           if((opcode[i]&0x3E)==0x14) // BEQL/BNEL
7837           {
7838             current.isconst=0;
7839             current.wasconst=0;
7840             regs[i].wasconst=0;
7841             alloc_cc(&current,i);
7842             dirty_reg(&current,CCREG);
7843             alloc_reg(&current,i,rs1[i]);
7844             alloc_reg(&current,i,rs2[i]);
7845           }
7846           else
7847           if((opcode[i]&0x3E)==0x16) // BLEZL/BGTZL
7848           {
7849             current.isconst=0;
7850             current.wasconst=0;
7851             regs[i].wasconst=0;
7852             alloc_cc(&current,i);
7853             dirty_reg(&current,CCREG);
7854             alloc_reg(&current,i,rs1[i]);
7855           }
7856           ds=1;
7857           //current.isconst=0;
7858           break;
7859         case SJUMP:
7860           //current.isconst=0;
7861           //current.wasconst=0;
7862           //regs[i].wasconst=0;
7863           clear_const(&current,rs1[i]);
7864           clear_const(&current,rt1[i]);
7865           //if((opcode2[i]&0x1E)==0x0) // BLTZ/BGEZ
7866           if((opcode2[i]&0x0E)==0x0) // BLTZ/BGEZ
7867           {
7868             alloc_cc(&current,i);
7869             dirty_reg(&current,CCREG);
7870             alloc_reg(&current,i,rs1[i]);
7871             if (rt1[i]==31) { // BLTZAL/BGEZAL
7872               alloc_reg(&current,i,31);
7873               dirty_reg(&current,31);
7874               //#ifdef REG_PREFETCH
7875               //alloc_reg(&current,i,PTEMP);
7876               //#endif
7877             }
7878             if((rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1])) // The delay slot overwrites the branch condition.
7879                ||(rt1[i]==31&&(rs1[i+1]==31||rs2[i+1]==31||rt1[i+1]==31||rt2[i+1]==31))) { // DS touches $ra
7880               // Allocate the branch condition registers instead.
7881               current.isconst=0;
7882               current.wasconst=0;
7883               regs[i].wasconst=0;
7884               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7885             }
7886             else
7887             {
7888               ooo[i]=1;
7889               delayslot_alloc(&current,i+1);
7890             }
7891           }
7892           else
7893           // Don't alloc the delay slot yet because we might not execute it
7894           if((opcode2[i]&0x1E)==0x2) // BLTZL/BGEZL
7895           {
7896             current.isconst=0;
7897             current.wasconst=0;
7898             regs[i].wasconst=0;
7899             alloc_cc(&current,i);
7900             dirty_reg(&current,CCREG);
7901             alloc_reg(&current,i,rs1[i]);
7902           }
7903           ds=1;
7904           //current.isconst=0;
7905           break;
7906         case IMM16:
7907           imm16_alloc(&current,i);
7908           break;
7909         case LOAD:
7910         case LOADLR:
7911           load_alloc(&current,i);
7912           break;
7913         case STORE:
7914         case STORELR:
7915           store_alloc(&current,i);
7916           break;
7917         case ALU:
7918           alu_alloc(&current,i);
7919           break;
7920         case SHIFT:
7921           shift_alloc(&current,i);
7922           break;
7923         case MULTDIV:
7924           multdiv_alloc(&current,i);
7925           break;
7926         case SHIFTIMM:
7927           shiftimm_alloc(&current,i);
7928           break;
7929         case MOV:
7930           mov_alloc(&current,i);
7931           break;
7932         case COP0:
7933           cop0_alloc(&current,i);
7934           break;
7935         case COP1:
7936           break;
7937         case COP2:
7938           cop2_alloc(&current,i);
7939           break;
7940         case C1LS:
7941           c1ls_alloc(&current,i);
7942           break;
7943         case C2LS:
7944           c2ls_alloc(&current,i);
7945           break;
7946         case C2OP:
7947           c2op_alloc(&current,i);
7948           break;
7949         case SYSCALL:
7950         case HLECALL:
7951         case INTCALL:
7952           syscall_alloc(&current,i);
7953           break;
7954         case SPAN:
7955           pagespan_alloc(&current,i);
7956           break;
7957       }
7958
7959       // Create entry (branch target) regmap
7960       for(hr=0;hr<HOST_REGS;hr++)
7961       {
7962         int r,or;
7963         r=current.regmap[hr];
7964         if(r>=0) {
7965           if(r!=regmap_pre[i][hr]) {
7966             // TODO: delay slot (?)
7967             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
7968             if(or<0||(r&63)>=TEMPREG){
7969               regs[i].regmap_entry[hr]=-1;
7970             }
7971             else
7972             {
7973               // Just move it to a different register
7974               regs[i].regmap_entry[hr]=r;
7975               // If it was dirty before, it's still dirty
7976               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r&63);
7977             }
7978           }
7979           else
7980           {
7981             // Unneeded
7982             if(r==0){
7983               regs[i].regmap_entry[hr]=0;
7984             }
7985             else
7986             {
7987               assert(r<64);
7988               if((current.u>>r)&1) {
7989                 regs[i].regmap_entry[hr]=-1;
7990                 //regs[i].regmap[hr]=-1;
7991                 current.regmap[hr]=-1;
7992               }else
7993                 regs[i].regmap_entry[hr]=r;
7994             }
7995           }
7996         } else {
7997           // Branches expect CCREG to be allocated at the target
7998           if(regmap_pre[i][hr]==CCREG)
7999             regs[i].regmap_entry[hr]=CCREG;
8000           else
8001             regs[i].regmap_entry[hr]=-1;
8002         }
8003       }
8004       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
8005     }
8006
8007     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)
8008       current.waswritten|=1<<rs1[i-1];
8009     current.waswritten&=~(1<<rt1[i]);
8010     current.waswritten&=~(1<<rt2[i]);
8011     if((itype[i]==STORE||itype[i]==STORELR||(itype[i]==C2LS&&opcode[i]==0x3a))&&(u_int)imm[i]>=0x800)
8012       current.waswritten&=~(1<<rs1[i]);
8013
8014     /* Branch post-alloc */
8015     if(i>0)
8016     {
8017       current.wasdirty=current.dirty;
8018       switch(itype[i-1]) {
8019         case UJUMP:
8020           memcpy(&branch_regs[i-1],&current,sizeof(current));
8021           branch_regs[i-1].isconst=0;
8022           branch_regs[i-1].wasconst=0;
8023           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
8024           alloc_cc(&branch_regs[i-1],i-1);
8025           dirty_reg(&branch_regs[i-1],CCREG);
8026           if(rt1[i-1]==31) { // JAL
8027             alloc_reg(&branch_regs[i-1],i-1,31);
8028             dirty_reg(&branch_regs[i-1],31);
8029           }
8030           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8031           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8032           break;
8033         case RJUMP:
8034           memcpy(&branch_regs[i-1],&current,sizeof(current));
8035           branch_regs[i-1].isconst=0;
8036           branch_regs[i-1].wasconst=0;
8037           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
8038           alloc_cc(&branch_regs[i-1],i-1);
8039           dirty_reg(&branch_regs[i-1],CCREG);
8040           alloc_reg(&branch_regs[i-1],i-1,rs1[i-1]);
8041           if(rt1[i-1]!=0) { // JALR
8042             alloc_reg(&branch_regs[i-1],i-1,rt1[i-1]);
8043             dirty_reg(&branch_regs[i-1],rt1[i-1]);
8044           }
8045           #ifdef USE_MINI_HT
8046           if(rs1[i-1]==31) { // JALR
8047             alloc_reg(&branch_regs[i-1],i-1,RHASH);
8048             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
8049           }
8050           #endif
8051           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8052           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8053           break;
8054         case CJUMP:
8055           if((opcode[i-1]&0x3E)==4) // BEQ/BNE
8056           {
8057             alloc_cc(&current,i-1);
8058             dirty_reg(&current,CCREG);
8059             if((rs1[i-1]&&(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]))||
8060                (rs2[i-1]&&(rs2[i-1]==rt1[i]||rs2[i-1]==rt2[i]))) {
8061               // The delay slot overwrote one of our conditions
8062               // Delay slot goes after the test (in order)
8063               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
8064               current.u|=1;
8065               delayslot_alloc(&current,i);
8066               current.isconst=0;
8067             }
8068             else
8069             {
8070               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
8071               // Alloc the branch condition registers
8072               if(rs1[i-1]) alloc_reg(&current,i-1,rs1[i-1]);
8073               if(rs2[i-1]) alloc_reg(&current,i-1,rs2[i-1]);
8074             }
8075             memcpy(&branch_regs[i-1],&current,sizeof(current));
8076             branch_regs[i-1].isconst=0;
8077             branch_regs[i-1].wasconst=0;
8078             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8079             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8080           }
8081           else
8082           if((opcode[i-1]&0x3E)==6) // BLEZ/BGTZ
8083           {
8084             alloc_cc(&current,i-1);
8085             dirty_reg(&current,CCREG);
8086             if(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]) {
8087               // The delay slot overwrote the branch condition
8088               // Delay slot goes after the test (in order)
8089               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
8090               current.u|=1;
8091               delayslot_alloc(&current,i);
8092               current.isconst=0;
8093             }
8094             else
8095             {
8096               current.u=branch_unneeded_reg[i-1]&~(1LL<<rs1[i-1]);
8097               // Alloc the branch condition register
8098               alloc_reg(&current,i-1,rs1[i-1]);
8099             }
8100             memcpy(&branch_regs[i-1],&current,sizeof(current));
8101             branch_regs[i-1].isconst=0;
8102             branch_regs[i-1].wasconst=0;
8103             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8104             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8105           }
8106           else
8107           // Alloc the delay slot in case the branch is taken
8108           if((opcode[i-1]&0x3E)==0x14) // BEQL/BNEL
8109           {
8110             memcpy(&branch_regs[i-1],&current,sizeof(current));
8111             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
8112             alloc_cc(&branch_regs[i-1],i);
8113             dirty_reg(&branch_regs[i-1],CCREG);
8114             delayslot_alloc(&branch_regs[i-1],i);
8115             branch_regs[i-1].isconst=0;
8116             alloc_reg(&current,i,CCREG); // Not taken path
8117             dirty_reg(&current,CCREG);
8118             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8119           }
8120           else
8121           if((opcode[i-1]&0x3E)==0x16) // BLEZL/BGTZL
8122           {
8123             memcpy(&branch_regs[i-1],&current,sizeof(current));
8124             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
8125             alloc_cc(&branch_regs[i-1],i);
8126             dirty_reg(&branch_regs[i-1],CCREG);
8127             delayslot_alloc(&branch_regs[i-1],i);
8128             branch_regs[i-1].isconst=0;
8129             alloc_reg(&current,i,CCREG); // Not taken path
8130             dirty_reg(&current,CCREG);
8131             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8132           }
8133           break;
8134         case SJUMP:
8135           //if((opcode2[i-1]&0x1E)==0) // BLTZ/BGEZ
8136           if((opcode2[i-1]&0x0E)==0) // BLTZ/BGEZ
8137           {
8138             alloc_cc(&current,i-1);
8139             dirty_reg(&current,CCREG);
8140             if(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]) {
8141               // The delay slot overwrote the branch condition
8142               // Delay slot goes after the test (in order)
8143               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
8144               current.u|=1;
8145               delayslot_alloc(&current,i);
8146               current.isconst=0;
8147             }
8148             else
8149             {
8150               current.u=branch_unneeded_reg[i-1]&~(1LL<<rs1[i-1]);
8151               // Alloc the branch condition register
8152               alloc_reg(&current,i-1,rs1[i-1]);
8153             }
8154             memcpy(&branch_regs[i-1],&current,sizeof(current));
8155             branch_regs[i-1].isconst=0;
8156             branch_regs[i-1].wasconst=0;
8157             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8158             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8159           }
8160           else
8161           // Alloc the delay slot in case the branch is taken
8162           if((opcode2[i-1]&0x1E)==2) // BLTZL/BGEZL
8163           {
8164             memcpy(&branch_regs[i-1],&current,sizeof(current));
8165             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
8166             alloc_cc(&branch_regs[i-1],i);
8167             dirty_reg(&branch_regs[i-1],CCREG);
8168             delayslot_alloc(&branch_regs[i-1],i);
8169             branch_regs[i-1].isconst=0;
8170             alloc_reg(&current,i,CCREG); // Not taken path
8171             dirty_reg(&current,CCREG);
8172             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8173           }
8174           // FIXME: BLTZAL/BGEZAL
8175           if(opcode2[i-1]&0x10) { // BxxZAL
8176             alloc_reg(&branch_regs[i-1],i-1,31);
8177             dirty_reg(&branch_regs[i-1],31);
8178           }
8179           break;
8180       }
8181
8182       if (is_ujump(i-1))
8183       {
8184         if(rt1[i-1]==31) // JAL/JALR
8185         {
8186           // Subroutine call will return here, don't alloc any registers
8187           current.dirty=0;
8188           clear_all_regs(current.regmap);
8189           alloc_reg(&current,i,CCREG);
8190           dirty_reg(&current,CCREG);
8191         }
8192         else if(i+1<slen)
8193         {
8194           // Internal branch will jump here, match registers to caller
8195           current.dirty=0;
8196           clear_all_regs(current.regmap);
8197           alloc_reg(&current,i,CCREG);
8198           dirty_reg(&current,CCREG);
8199           for(j=i-1;j>=0;j--)
8200           {
8201             if(ba[j]==start+i*4+4) {
8202               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
8203               current.dirty=branch_regs[j].dirty;
8204               break;
8205             }
8206           }
8207           while(j>=0) {
8208             if(ba[j]==start+i*4+4) {
8209               for(hr=0;hr<HOST_REGS;hr++) {
8210                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
8211                   current.regmap[hr]=-1;
8212                 }
8213                 current.dirty&=branch_regs[j].dirty;
8214               }
8215             }
8216             j--;
8217           }
8218         }
8219       }
8220     }
8221
8222     // Count cycles in between branches
8223     ccadj[i]=cc;
8224     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))
8225     {
8226       cc=0;
8227     }
8228 #if !defined(DRC_DBG)
8229     else if(itype[i]==C2OP&&gte_cycletab[source[i]&0x3f]>2)
8230     {
8231       // this should really be removed since the real stalls have been implemented,
8232       // but doing so causes sizeable perf regression against the older version
8233       u_int gtec = gte_cycletab[source[i] & 0x3f];
8234       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? gtec/2 : 2;
8235     }
8236     else if(i>1&&itype[i]==STORE&&itype[i-1]==STORE&&itype[i-2]==STORE&&!bt[i])
8237     {
8238       cc+=4;
8239     }
8240     else if(itype[i]==C2LS)
8241     {
8242       // same as with C2OP
8243       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? 4 : 2;
8244     }
8245 #endif
8246     else
8247     {
8248       cc++;
8249     }
8250
8251     if(!is_ds[i]) {
8252       regs[i].dirty=current.dirty;
8253       regs[i].isconst=current.isconst;
8254       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
8255     }
8256     for(hr=0;hr<HOST_REGS;hr++) {
8257       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
8258         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
8259           regs[i].wasconst&=~(1<<hr);
8260         }
8261       }
8262     }
8263     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
8264     regs[i].waswritten=current.waswritten;
8265   }
8266
8267   /* Pass 4 - Cull unused host registers */
8268
8269   uint64_t nr=0;
8270
8271   for (i=slen-1;i>=0;i--)
8272   {
8273     int hr;
8274     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8275     {
8276       if(ba[i]<start || ba[i]>=(start+slen*4))
8277       {
8278         // Branch out of this block, don't need anything
8279         nr=0;
8280       }
8281       else
8282       {
8283         // Internal branch
8284         // Need whatever matches the target
8285         nr=0;
8286         int t=(ba[i]-start)>>2;
8287         for(hr=0;hr<HOST_REGS;hr++)
8288         {
8289           if(regs[i].regmap_entry[hr]>=0) {
8290             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
8291           }
8292         }
8293       }
8294       // Conditional branch may need registers for following instructions
8295       if (!is_ujump(i))
8296       {
8297         if(i<slen-2) {
8298           nr|=needed_reg[i+2];
8299           for(hr=0;hr<HOST_REGS;hr++)
8300           {
8301             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
8302             //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]);
8303           }
8304         }
8305       }
8306       // Don't need stuff which is overwritten
8307       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8308       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8309       // Merge in delay slot
8310       for(hr=0;hr<HOST_REGS;hr++)
8311       {
8312         if(!likely[i]) {
8313           // These are overwritten unless the branch is "likely"
8314           // and the delay slot is nullified if not taken
8315           if(rt1[i+1]&&rt1[i+1]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8316           if(rt2[i+1]&&rt2[i+1]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8317         }
8318         if(rs1[i+1]==regmap_pre[i][hr]) nr|=1<<hr;
8319         if(rs2[i+1]==regmap_pre[i][hr]) nr|=1<<hr;
8320         if(rs1[i+1]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8321         if(rs2[i+1]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8322         if(itype[i+1]==STORE || itype[i+1]==STORELR || (opcode[i+1]&0x3b)==0x39 || (opcode[i+1]&0x3b)==0x3a) {
8323           if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8324           if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8325         }
8326       }
8327     }
8328     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
8329     {
8330       // SYSCALL instruction (software interrupt)
8331       nr=0;
8332     }
8333     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
8334     {
8335       // ERET instruction (return from interrupt)
8336       nr=0;
8337     }
8338     else // Non-branch
8339     {
8340       if(i<slen-1) {
8341         for(hr=0;hr<HOST_REGS;hr++) {
8342           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
8343           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
8344           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8345           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8346         }
8347       }
8348     }
8349     for(hr=0;hr<HOST_REGS;hr++)
8350     {
8351       // Overwritten registers are not needed
8352       if(rt1[i]&&rt1[i]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8353       if(rt2[i]&&rt2[i]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8354       if(FTEMP==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8355       // Source registers are needed
8356       if(rs1[i]==regmap_pre[i][hr]) nr|=1<<hr;
8357       if(rs2[i]==regmap_pre[i][hr]) nr|=1<<hr;
8358       if(rs1[i]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8359       if(rs2[i]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8360       if(itype[i]==STORE || itype[i]==STORELR || (opcode[i]&0x3b)==0x39 || (opcode[i]&0x3b)==0x3a) {
8361         if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8362         if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8363       }
8364       // Don't store a register immediately after writing it,
8365       // may prevent dual-issue.
8366       // But do so if this is a branch target, otherwise we
8367       // might have to load the register before the branch.
8368       if(i>0&&!bt[i]&&((regs[i].wasdirty>>hr)&1)) {
8369         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
8370           if(rt1[i-1]==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8371           if(rt2[i-1]==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8372         }
8373         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
8374           if(rt1[i-1]==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8375           if(rt2[i-1]==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8376         }
8377       }
8378     }
8379     // Cycle count is needed at branches.  Assume it is needed at the target too.
8380     if(i==0||bt[i]||itype[i]==CJUMP||itype[i]==SPAN) {
8381       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8382       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8383     }
8384     // Save it
8385     needed_reg[i]=nr;
8386
8387     // Deallocate unneeded registers
8388     for(hr=0;hr<HOST_REGS;hr++)
8389     {
8390       if(!((nr>>hr)&1)) {
8391         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
8392         if((regs[i].regmap[hr]&63)!=rs1[i] && (regs[i].regmap[hr]&63)!=rs2[i] &&
8393            (regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8394            (regs[i].regmap[hr]&63)!=PTEMP && (regs[i].regmap[hr]&63)!=CCREG)
8395         {
8396           if (!is_ujump(i))
8397           {
8398             if(likely[i]) {
8399               regs[i].regmap[hr]=-1;
8400               regs[i].isconst&=~(1<<hr);
8401               if(i<slen-2) {
8402                 regmap_pre[i+2][hr]=-1;
8403                 regs[i+2].wasconst&=~(1<<hr);
8404               }
8405             }
8406           }
8407         }
8408         if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8409         {
8410           int map=0,temp=0;
8411           if(itype[i+1]==STORE || itype[i+1]==STORELR ||
8412              (opcode[i+1]&0x3b)==0x39 || (opcode[i+1]&0x3b)==0x3a) { // SWC1/SDC1 || SWC2/SDC2
8413             map=INVCP;
8414           }
8415           if(itype[i+1]==LOADLR || itype[i+1]==STORELR ||
8416              itype[i+1]==C1LS || itype[i+1]==C2LS)
8417             temp=FTEMP;
8418           if((regs[i].regmap[hr]&63)!=rs1[i] && (regs[i].regmap[hr]&63)!=rs2[i] &&
8419              (regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8420              (regs[i].regmap[hr]&63)!=rt1[i+1] && (regs[i].regmap[hr]&63)!=rt2[i+1] &&
8421              regs[i].regmap[hr]!=rs1[i+1] && regs[i].regmap[hr]!=rs2[i+1] &&
8422              (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=PTEMP &&
8423              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
8424              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
8425              regs[i].regmap[hr]!=map )
8426           {
8427             regs[i].regmap[hr]=-1;
8428             regs[i].isconst&=~(1<<hr);
8429             if((branch_regs[i].regmap[hr]&63)!=rs1[i] && (branch_regs[i].regmap[hr]&63)!=rs2[i] &&
8430                (branch_regs[i].regmap[hr]&63)!=rt1[i] && (branch_regs[i].regmap[hr]&63)!=rt2[i] &&
8431                (branch_regs[i].regmap[hr]&63)!=rt1[i+1] && (branch_regs[i].regmap[hr]&63)!=rt2[i+1] &&
8432                branch_regs[i].regmap[hr]!=rs1[i+1] && branch_regs[i].regmap[hr]!=rs2[i+1] &&
8433                (branch_regs[i].regmap[hr]&63)!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
8434                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
8435                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
8436                branch_regs[i].regmap[hr]!=map)
8437             {
8438               branch_regs[i].regmap[hr]=-1;
8439               branch_regs[i].regmap_entry[hr]=-1;
8440               if (!is_ujump(i))
8441               {
8442                 if(!likely[i]&&i<slen-2) {
8443                   regmap_pre[i+2][hr]=-1;
8444                   regs[i+2].wasconst&=~(1<<hr);
8445                 }
8446               }
8447             }
8448           }
8449         }
8450         else
8451         {
8452           // Non-branch
8453           if(i>0)
8454           {
8455             int map=-1,temp=-1;
8456             if(itype[i]==STORE || itype[i]==STORELR ||
8457                       (opcode[i]&0x3b)==0x39 || (opcode[i]&0x3b)==0x3a) { // SWC1/SDC1 || SWC2/SDC2
8458               map=INVCP;
8459             }
8460             if(itype[i]==LOADLR || itype[i]==STORELR ||
8461                itype[i]==C1LS || itype[i]==C2LS)
8462               temp=FTEMP;
8463             if((regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8464                regs[i].regmap[hr]!=rs1[i] && regs[i].regmap[hr]!=rs2[i] &&
8465                (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=map &&
8466                (itype[i]!=SPAN||regs[i].regmap[hr]!=CCREG))
8467             {
8468               if(i<slen-1&&!is_ds[i]) {
8469                 assert(regs[i].regmap[hr]<64);
8470                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8471                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8472                 {
8473                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8474                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8475                 }
8476                 regmap_pre[i+1][hr]=-1;
8477                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8478                 regs[i+1].wasconst&=~(1<<hr);
8479               }
8480               regs[i].regmap[hr]=-1;
8481               regs[i].isconst&=~(1<<hr);
8482             }
8483           }
8484         }
8485       } // if needed
8486     } // for hr
8487   }
8488
8489   /* Pass 5 - Pre-allocate registers */
8490
8491   // If a register is allocated during a loop, try to allocate it for the
8492   // entire loop, if possible.  This avoids loading/storing registers
8493   // inside of the loop.
8494
8495   signed char f_regmap[HOST_REGS];
8496   clear_all_regs(f_regmap);
8497   for(i=0;i<slen-1;i++)
8498   {
8499     if(itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8500     {
8501       if(ba[i]>=start && ba[i]<(start+i*4))
8502       if(itype[i+1]==NOP||itype[i+1]==MOV||itype[i+1]==ALU
8503       ||itype[i+1]==SHIFTIMM||itype[i+1]==IMM16||itype[i+1]==LOAD
8504       ||itype[i+1]==STORE||itype[i+1]==STORELR||itype[i+1]==C1LS
8505       ||itype[i+1]==SHIFT||itype[i+1]==COP1
8506       ||itype[i+1]==COP2||itype[i+1]==C2LS||itype[i+1]==C2OP)
8507       {
8508         int t=(ba[i]-start)>>2;
8509         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
8510         if(t<2||(itype[t-2]!=UJUMP&&itype[t-2]!=RJUMP)||rt1[t-2]!=31) // call/ret assumes no registers allocated
8511         for(hr=0;hr<HOST_REGS;hr++)
8512         {
8513           if(regs[i].regmap[hr]>=0) {
8514             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8515               // dealloc old register
8516               int n;
8517               for(n=0;n<HOST_REGS;n++)
8518               {
8519                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8520               }
8521               // and alloc new one
8522               f_regmap[hr]=regs[i].regmap[hr];
8523             }
8524           }
8525           if(branch_regs[i].regmap[hr]>=0) {
8526             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8527               // dealloc old register
8528               int n;
8529               for(n=0;n<HOST_REGS;n++)
8530               {
8531                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8532               }
8533               // and alloc new one
8534               f_regmap[hr]=branch_regs[i].regmap[hr];
8535             }
8536           }
8537           if(ooo[i]) {
8538             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8539               f_regmap[hr]=branch_regs[i].regmap[hr];
8540           }else{
8541             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8542               f_regmap[hr]=branch_regs[i].regmap[hr];
8543           }
8544           // Avoid dirty->clean transition
8545           #ifdef DESTRUCTIVE_WRITEBACK
8546           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;
8547           #endif
8548           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8549           // case above, however it's always a good idea.  We can't hoist the
8550           // load if the register was already allocated, so there's no point
8551           // wasting time analyzing most of these cases.  It only "succeeds"
8552           // when the mapping was different and the load can be replaced with
8553           // a mov, which is of negligible benefit.  So such cases are
8554           // skipped below.
8555           if(f_regmap[hr]>0) {
8556             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8557               int r=f_regmap[hr];
8558               for(j=t;j<=i;j++)
8559               {
8560                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8561                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8562                 assert(r < 64);
8563                 if(regs[j].regmap[hr]==f_regmap[hr]&&(f_regmap[hr]&63)<TEMPREG) {
8564                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8565                   int k;
8566                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8567                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8568                     if(r>63) {
8569                       if(get_reg(regs[i].regmap,r&63)<0) break;
8570                       if(get_reg(branch_regs[i].regmap,r&63)<0) break;
8571                     }
8572                     k=i;
8573                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8574                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8575                         //printf("no free regs for store %x\n",start+(k-1)*4);
8576                         break;
8577                       }
8578                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8579                         //printf("no-match due to different register\n");
8580                         break;
8581                       }
8582                       if(itype[k-2]==UJUMP||itype[k-2]==RJUMP||itype[k-2]==CJUMP||itype[k-2]==SJUMP) {
8583                         //printf("no-match due to branch\n");
8584                         break;
8585                       }
8586                       // call/ret fast path assumes no registers allocated
8587                       if(k>2&&(itype[k-3]==UJUMP||itype[k-3]==RJUMP)&&rt1[k-3]==31) {
8588                         break;
8589                       }
8590                       assert(r < 64);
8591                       k--;
8592                     }
8593                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8594                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8595                       while(k<i) {
8596                         regs[k].regmap_entry[hr]=f_regmap[hr];
8597                         regs[k].regmap[hr]=f_regmap[hr];
8598                         regmap_pre[k+1][hr]=f_regmap[hr];
8599                         regs[k].wasdirty&=~(1<<hr);
8600                         regs[k].dirty&=~(1<<hr);
8601                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8602                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8603                         regs[k].wasconst&=~(1<<hr);
8604                         regs[k].isconst&=~(1<<hr);
8605                         k++;
8606                       }
8607                     }
8608                     else {
8609                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8610                       break;
8611                     }
8612                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8613                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8614                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8615                       regs[i].regmap_entry[hr]=f_regmap[hr];
8616                       regs[i].regmap[hr]=f_regmap[hr];
8617                       regs[i].wasdirty&=~(1<<hr);
8618                       regs[i].dirty&=~(1<<hr);
8619                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8620                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8621                       regs[i].wasconst&=~(1<<hr);
8622                       regs[i].isconst&=~(1<<hr);
8623                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8624                       branch_regs[i].wasdirty&=~(1<<hr);
8625                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8626                       branch_regs[i].regmap[hr]=f_regmap[hr];
8627                       branch_regs[i].dirty&=~(1<<hr);
8628                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8629                       branch_regs[i].wasconst&=~(1<<hr);
8630                       branch_regs[i].isconst&=~(1<<hr);
8631                       if (!is_ujump(i)) {
8632                         regmap_pre[i+2][hr]=f_regmap[hr];
8633                         regs[i+2].wasdirty&=~(1<<hr);
8634                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8635                       }
8636                     }
8637                   }
8638                   for(k=t;k<j;k++) {
8639                     // Alloc register clean at beginning of loop,
8640                     // but may dirty it in pass 6
8641                     regs[k].regmap_entry[hr]=f_regmap[hr];
8642                     regs[k].regmap[hr]=f_regmap[hr];
8643                     regs[k].dirty&=~(1<<hr);
8644                     regs[k].wasconst&=~(1<<hr);
8645                     regs[k].isconst&=~(1<<hr);
8646                     if(itype[k]==UJUMP||itype[k]==RJUMP||itype[k]==CJUMP||itype[k]==SJUMP) {
8647                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8648                       branch_regs[k].regmap[hr]=f_regmap[hr];
8649                       branch_regs[k].dirty&=~(1<<hr);
8650                       branch_regs[k].wasconst&=~(1<<hr);
8651                       branch_regs[k].isconst&=~(1<<hr);
8652                       if (!is_ujump(k)) {
8653                         regmap_pre[k+2][hr]=f_regmap[hr];
8654                         regs[k+2].wasdirty&=~(1<<hr);
8655                       }
8656                     }
8657                     else
8658                     {
8659                       regmap_pre[k+1][hr]=f_regmap[hr];
8660                       regs[k+1].wasdirty&=~(1<<hr);
8661                     }
8662                   }
8663                   if(regs[j].regmap[hr]==f_regmap[hr])
8664                     regs[j].regmap_entry[hr]=f_regmap[hr];
8665                   break;
8666                 }
8667                 if(j==i) break;
8668                 if(regs[j].regmap[hr]>=0)
8669                   break;
8670                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8671                   //printf("no-match due to different register\n");
8672                   break;
8673                 }
8674                 if (is_ujump(j))
8675                 {
8676                   // Stop on unconditional branch
8677                   break;
8678                 }
8679                 if(itype[j]==CJUMP||itype[j]==SJUMP)
8680                 {
8681                   if(ooo[j]) {
8682                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8683                       break;
8684                   }else{
8685                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8686                       break;
8687                   }
8688                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8689                     //printf("no-match due to different register (branch)\n");
8690                     break;
8691                   }
8692                 }
8693                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8694                   //printf("No free regs for store %x\n",start+j*4);
8695                   break;
8696                 }
8697                 assert(f_regmap[hr]<64);
8698               }
8699             }
8700           }
8701         }
8702       }
8703     }else{
8704       // Non branch or undetermined branch target
8705       for(hr=0;hr<HOST_REGS;hr++)
8706       {
8707         if(hr!=EXCLUDE_REG) {
8708           if(regs[i].regmap[hr]>=0) {
8709             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8710               // dealloc old register
8711               int n;
8712               for(n=0;n<HOST_REGS;n++)
8713               {
8714                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8715               }
8716               // and alloc new one
8717               f_regmap[hr]=regs[i].regmap[hr];
8718             }
8719           }
8720         }
8721       }
8722       // Try to restore cycle count at branch targets
8723       if(bt[i]) {
8724         for(j=i;j<slen-1;j++) {
8725           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8726           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8727             //printf("no free regs for store %x\n",start+j*4);
8728             break;
8729           }
8730         }
8731         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8732           int k=i;
8733           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8734           while(k<j) {
8735             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8736             regs[k].regmap[HOST_CCREG]=CCREG;
8737             regmap_pre[k+1][HOST_CCREG]=CCREG;
8738             regs[k+1].wasdirty|=1<<HOST_CCREG;
8739             regs[k].dirty|=1<<HOST_CCREG;
8740             regs[k].wasconst&=~(1<<HOST_CCREG);
8741             regs[k].isconst&=~(1<<HOST_CCREG);
8742             k++;
8743           }
8744           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8745         }
8746         // Work backwards from the branch target
8747         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8748         {
8749           //printf("Extend backwards\n");
8750           int k;
8751           k=i;
8752           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8753             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8754               //printf("no free regs for store %x\n",start+(k-1)*4);
8755               break;
8756             }
8757             k--;
8758           }
8759           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8760             //printf("Extend CC, %x ->\n",start+k*4);
8761             while(k<=i) {
8762               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8763               regs[k].regmap[HOST_CCREG]=CCREG;
8764               regmap_pre[k+1][HOST_CCREG]=CCREG;
8765               regs[k+1].wasdirty|=1<<HOST_CCREG;
8766               regs[k].dirty|=1<<HOST_CCREG;
8767               regs[k].wasconst&=~(1<<HOST_CCREG);
8768               regs[k].isconst&=~(1<<HOST_CCREG);
8769               k++;
8770             }
8771           }
8772           else {
8773             //printf("Fail Extend CC, %x ->\n",start+k*4);
8774           }
8775         }
8776       }
8777       if(itype[i]!=STORE&&itype[i]!=STORELR&&itype[i]!=C1LS&&itype[i]!=SHIFT&&
8778          itype[i]!=NOP&&itype[i]!=MOV&&itype[i]!=ALU&&itype[i]!=SHIFTIMM&&
8779          itype[i]!=IMM16&&itype[i]!=LOAD&&itype[i]!=COP1)
8780       {
8781         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8782       }
8783     }
8784   }
8785
8786   // This allocates registers (if possible) one instruction prior
8787   // to use, which can avoid a load-use penalty on certain CPUs.
8788   for(i=0;i<slen-1;i++)
8789   {
8790     if(!i||(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP))
8791     {
8792       if(!bt[i+1])
8793       {
8794         if(itype[i]==ALU||itype[i]==MOV||itype[i]==LOAD||itype[i]==SHIFTIMM||itype[i]==IMM16
8795            ||((itype[i]==COP1||itype[i]==COP2)&&opcode2[i]<3))
8796         {
8797           if(rs1[i+1]) {
8798             if((hr=get_reg(regs[i+1].regmap,rs1[i+1]))>=0)
8799             {
8800               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8801               {
8802                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8803                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8804                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8805                 regs[i].isconst&=~(1<<hr);
8806                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8807                 constmap[i][hr]=constmap[i+1][hr];
8808                 regs[i+1].wasdirty&=~(1<<hr);
8809                 regs[i].dirty&=~(1<<hr);
8810               }
8811             }
8812           }
8813           if(rs2[i+1]) {
8814             if((hr=get_reg(regs[i+1].regmap,rs2[i+1]))>=0)
8815             {
8816               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8817               {
8818                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8819                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8820                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8821                 regs[i].isconst&=~(1<<hr);
8822                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8823                 constmap[i][hr]=constmap[i+1][hr];
8824                 regs[i+1].wasdirty&=~(1<<hr);
8825                 regs[i].dirty&=~(1<<hr);
8826               }
8827             }
8828           }
8829           // Preload target address for load instruction (non-constant)
8830           if(itype[i+1]==LOAD&&rs1[i+1]&&get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8831             if((hr=get_reg(regs[i+1].regmap,rt1[i+1]))>=0)
8832             {
8833               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8834               {
8835                 regs[i].regmap[hr]=rs1[i+1];
8836                 regmap_pre[i+1][hr]=rs1[i+1];
8837                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8838                 regs[i].isconst&=~(1<<hr);
8839                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8840                 constmap[i][hr]=constmap[i+1][hr];
8841                 regs[i+1].wasdirty&=~(1<<hr);
8842                 regs[i].dirty&=~(1<<hr);
8843               }
8844             }
8845           }
8846           // Load source into target register
8847           if(lt1[i+1]&&get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8848             if((hr=get_reg(regs[i+1].regmap,rt1[i+1]))>=0)
8849             {
8850               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8851               {
8852                 regs[i].regmap[hr]=rs1[i+1];
8853                 regmap_pre[i+1][hr]=rs1[i+1];
8854                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8855                 regs[i].isconst&=~(1<<hr);
8856                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8857                 constmap[i][hr]=constmap[i+1][hr];
8858                 regs[i+1].wasdirty&=~(1<<hr);
8859                 regs[i].dirty&=~(1<<hr);
8860               }
8861             }
8862           }
8863           // Address for store instruction (non-constant)
8864           if(itype[i+1]==STORE||itype[i+1]==STORELR
8865              ||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8866             if(get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8867               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8868               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8869               else {regs[i+1].regmap[hr]=AGEN1+((i+1)&1);regs[i+1].isconst&=~(1<<hr);}
8870               assert(hr>=0);
8871               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8872               {
8873                 regs[i].regmap[hr]=rs1[i+1];
8874                 regmap_pre[i+1][hr]=rs1[i+1];
8875                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8876                 regs[i].isconst&=~(1<<hr);
8877                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8878                 constmap[i][hr]=constmap[i+1][hr];
8879                 regs[i+1].wasdirty&=~(1<<hr);
8880                 regs[i].dirty&=~(1<<hr);
8881               }
8882             }
8883           }
8884           if(itype[i+1]==LOADLR||(opcode[i+1]&0x3b)==0x31||(opcode[i+1]&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
8885             if(get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8886               int nr;
8887               hr=get_reg(regs[i+1].regmap,FTEMP);
8888               assert(hr>=0);
8889               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8890               {
8891                 regs[i].regmap[hr]=rs1[i+1];
8892                 regmap_pre[i+1][hr]=rs1[i+1];
8893                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8894                 regs[i].isconst&=~(1<<hr);
8895                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8896                 constmap[i][hr]=constmap[i+1][hr];
8897                 regs[i+1].wasdirty&=~(1<<hr);
8898                 regs[i].dirty&=~(1<<hr);
8899               }
8900               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
8901               {
8902                 // move it to another register
8903                 regs[i+1].regmap[hr]=-1;
8904                 regmap_pre[i+2][hr]=-1;
8905                 regs[i+1].regmap[nr]=FTEMP;
8906                 regmap_pre[i+2][nr]=FTEMP;
8907                 regs[i].regmap[nr]=rs1[i+1];
8908                 regmap_pre[i+1][nr]=rs1[i+1];
8909                 regs[i+1].regmap_entry[nr]=rs1[i+1];
8910                 regs[i].isconst&=~(1<<nr);
8911                 regs[i+1].isconst&=~(1<<nr);
8912                 regs[i].dirty&=~(1<<nr);
8913                 regs[i+1].wasdirty&=~(1<<nr);
8914                 regs[i+1].dirty&=~(1<<nr);
8915                 regs[i+2].wasdirty&=~(1<<nr);
8916               }
8917             }
8918           }
8919           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*/) {
8920             if(itype[i+1]==LOAD)
8921               hr=get_reg(regs[i+1].regmap,rt1[i+1]);
8922             if(itype[i+1]==LOADLR||(opcode[i+1]&0x3b)==0x31||(opcode[i+1]&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
8923               hr=get_reg(regs[i+1].regmap,FTEMP);
8924             if(itype[i+1]==STORE||itype[i+1]==STORELR||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a) { // SWC1/SDC1/SWC2/SDC2
8925               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
8926               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8927             }
8928             if(hr>=0&&regs[i].regmap[hr]<0) {
8929               int rs=get_reg(regs[i+1].regmap,rs1[i+1]);
8930               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
8931                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
8932                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
8933                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
8934                 regs[i].isconst&=~(1<<hr);
8935                 regs[i+1].wasdirty&=~(1<<hr);
8936                 regs[i].dirty&=~(1<<hr);
8937               }
8938             }
8939           }
8940         }
8941       }
8942     }
8943   }
8944
8945   /* Pass 6 - Optimize clean/dirty state */
8946   clean_registers(0,slen-1,1);
8947
8948   /* Pass 7 - Identify 32-bit registers */
8949   for (i=slen-1;i>=0;i--)
8950   {
8951     if(itype[i]==CJUMP||itype[i]==SJUMP)
8952     {
8953       // Conditional branch
8954       if((source[i]>>16)!=0x1000&&i<slen-2) {
8955         // Mark this address as a branch target since it may be called
8956         // upon return from interrupt
8957         bt[i+2]=1;
8958       }
8959     }
8960   }
8961
8962   if(itype[slen-1]==SPAN) {
8963     bt[slen-1]=1; // Mark as a branch target so instruction can restart after exception
8964   }
8965
8966 #ifdef DISASM
8967   /* Debug/disassembly */
8968   for(i=0;i<slen;i++)
8969   {
8970     printf("U:");
8971     int r;
8972     for(r=1;r<=CCREG;r++) {
8973       if((unneeded_reg[i]>>r)&1) {
8974         if(r==HIREG) printf(" HI");
8975         else if(r==LOREG) printf(" LO");
8976         else printf(" r%d",r);
8977       }
8978     }
8979     printf("\n");
8980     #if defined(__i386__) || defined(__x86_64__)
8981     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]);
8982     #endif
8983     #ifdef __arm__
8984     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]);
8985     #endif
8986     #if defined(__i386__) || defined(__x86_64__)
8987     printf("needs: ");
8988     if(needed_reg[i]&1) printf("eax ");
8989     if((needed_reg[i]>>1)&1) printf("ecx ");
8990     if((needed_reg[i]>>2)&1) printf("edx ");
8991     if((needed_reg[i]>>3)&1) printf("ebx ");
8992     if((needed_reg[i]>>5)&1) printf("ebp ");
8993     if((needed_reg[i]>>6)&1) printf("esi ");
8994     if((needed_reg[i]>>7)&1) printf("edi ");
8995     printf("\n");
8996     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]);
8997     printf("dirty: ");
8998     if(regs[i].wasdirty&1) printf("eax ");
8999     if((regs[i].wasdirty>>1)&1) printf("ecx ");
9000     if((regs[i].wasdirty>>2)&1) printf("edx ");
9001     if((regs[i].wasdirty>>3)&1) printf("ebx ");
9002     if((regs[i].wasdirty>>5)&1) printf("ebp ");
9003     if((regs[i].wasdirty>>6)&1) printf("esi ");
9004     if((regs[i].wasdirty>>7)&1) printf("edi ");
9005     #endif
9006     #ifdef __arm__
9007     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]);
9008     printf("dirty: ");
9009     if(regs[i].wasdirty&1) printf("r0 ");
9010     if((regs[i].wasdirty>>1)&1) printf("r1 ");
9011     if((regs[i].wasdirty>>2)&1) printf("r2 ");
9012     if((regs[i].wasdirty>>3)&1) printf("r3 ");
9013     if((regs[i].wasdirty>>4)&1) printf("r4 ");
9014     if((regs[i].wasdirty>>5)&1) printf("r5 ");
9015     if((regs[i].wasdirty>>6)&1) printf("r6 ");
9016     if((regs[i].wasdirty>>7)&1) printf("r7 ");
9017     if((regs[i].wasdirty>>8)&1) printf("r8 ");
9018     if((regs[i].wasdirty>>9)&1) printf("r9 ");
9019     if((regs[i].wasdirty>>10)&1) printf("r10 ");
9020     if((regs[i].wasdirty>>12)&1) printf("r12 ");
9021     #endif
9022     printf("\n");
9023     disassemble_inst(i);
9024     //printf ("ccadj[%d] = %d\n",i,ccadj[i]);
9025     #if defined(__i386__) || defined(__x86_64__)
9026     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]);
9027     if(regs[i].dirty&1) printf("eax ");
9028     if((regs[i].dirty>>1)&1) printf("ecx ");
9029     if((regs[i].dirty>>2)&1) printf("edx ");
9030     if((regs[i].dirty>>3)&1) printf("ebx ");
9031     if((regs[i].dirty>>5)&1) printf("ebp ");
9032     if((regs[i].dirty>>6)&1) printf("esi ");
9033     if((regs[i].dirty>>7)&1) printf("edi ");
9034     #endif
9035     #ifdef __arm__
9036     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]);
9037     if(regs[i].dirty&1) printf("r0 ");
9038     if((regs[i].dirty>>1)&1) printf("r1 ");
9039     if((regs[i].dirty>>2)&1) printf("r2 ");
9040     if((regs[i].dirty>>3)&1) printf("r3 ");
9041     if((regs[i].dirty>>4)&1) printf("r4 ");
9042     if((regs[i].dirty>>5)&1) printf("r5 ");
9043     if((regs[i].dirty>>6)&1) printf("r6 ");
9044     if((regs[i].dirty>>7)&1) printf("r7 ");
9045     if((regs[i].dirty>>8)&1) printf("r8 ");
9046     if((regs[i].dirty>>9)&1) printf("r9 ");
9047     if((regs[i].dirty>>10)&1) printf("r10 ");
9048     if((regs[i].dirty>>12)&1) printf("r12 ");
9049     #endif
9050     printf("\n");
9051     if(regs[i].isconst) {
9052       printf("constants: ");
9053       #if defined(__i386__) || defined(__x86_64__)
9054       if(regs[i].isconst&1) printf("eax=%x ",(u_int)constmap[i][0]);
9055       if((regs[i].isconst>>1)&1) printf("ecx=%x ",(u_int)constmap[i][1]);
9056       if((regs[i].isconst>>2)&1) printf("edx=%x ",(u_int)constmap[i][2]);
9057       if((regs[i].isconst>>3)&1) printf("ebx=%x ",(u_int)constmap[i][3]);
9058       if((regs[i].isconst>>5)&1) printf("ebp=%x ",(u_int)constmap[i][5]);
9059       if((regs[i].isconst>>6)&1) printf("esi=%x ",(u_int)constmap[i][6]);
9060       if((regs[i].isconst>>7)&1) printf("edi=%x ",(u_int)constmap[i][7]);
9061       #endif
9062       #if defined(__arm__) || defined(__aarch64__)
9063       int r;
9064       for (r = 0; r < ARRAY_SIZE(constmap[i]); r++)
9065         if ((regs[i].isconst >> r) & 1)
9066           printf(" r%d=%x", r, (u_int)constmap[i][r]);
9067       #endif
9068       printf("\n");
9069     }
9070     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP) {
9071       #if defined(__i386__) || defined(__x86_64__)
9072       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]);
9073       if(branch_regs[i].dirty&1) printf("eax ");
9074       if((branch_regs[i].dirty>>1)&1) printf("ecx ");
9075       if((branch_regs[i].dirty>>2)&1) printf("edx ");
9076       if((branch_regs[i].dirty>>3)&1) printf("ebx ");
9077       if((branch_regs[i].dirty>>5)&1) printf("ebp ");
9078       if((branch_regs[i].dirty>>6)&1) printf("esi ");
9079       if((branch_regs[i].dirty>>7)&1) printf("edi ");
9080       #endif
9081       #ifdef __arm__
9082       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]);
9083       if(branch_regs[i].dirty&1) printf("r0 ");
9084       if((branch_regs[i].dirty>>1)&1) printf("r1 ");
9085       if((branch_regs[i].dirty>>2)&1) printf("r2 ");
9086       if((branch_regs[i].dirty>>3)&1) printf("r3 ");
9087       if((branch_regs[i].dirty>>4)&1) printf("r4 ");
9088       if((branch_regs[i].dirty>>5)&1) printf("r5 ");
9089       if((branch_regs[i].dirty>>6)&1) printf("r6 ");
9090       if((branch_regs[i].dirty>>7)&1) printf("r7 ");
9091       if((branch_regs[i].dirty>>8)&1) printf("r8 ");
9092       if((branch_regs[i].dirty>>9)&1) printf("r9 ");
9093       if((branch_regs[i].dirty>>10)&1) printf("r10 ");
9094       if((branch_regs[i].dirty>>12)&1) printf("r12 ");
9095       #endif
9096     }
9097   }
9098 #endif // DISASM
9099
9100   /* Pass 8 - Assembly */
9101   linkcount=0;stubcount=0;
9102   ds=0;is_delayslot=0;
9103   u_int dirty_pre=0;
9104   void *beginning=start_block();
9105   if((u_int)addr&1) {
9106     ds=1;
9107     pagespan_ds();
9108   }
9109   void *instr_addr0_override = NULL;
9110
9111   if (start == 0x80030000) {
9112     // nasty hack for the fastbios thing
9113     // override block entry to this code
9114     instr_addr0_override = out;
9115     emit_movimm(start,0);
9116     // abuse io address var as a flag that we
9117     // have already returned here once
9118     emit_readword(&address,1);
9119     emit_writeword(0,&pcaddr);
9120     emit_writeword(0,&address);
9121     emit_cmp(0,1);
9122     #ifdef __aarch64__
9123     emit_jeq(out + 4*2);
9124     emit_far_jump(new_dyna_leave);
9125     #else
9126     emit_jne(new_dyna_leave);
9127     #endif
9128   }
9129   for(i=0;i<slen;i++)
9130   {
9131     //if(ds) printf("ds: ");
9132     disassemble_inst(i);
9133     if(ds) {
9134       ds=0; // Skip delay slot
9135       if(bt[i]) assem_debug("OOPS - branch into delay slot\n");
9136       instr_addr[i] = NULL;
9137     } else {
9138       speculate_register_values(i);
9139       #ifndef DESTRUCTIVE_WRITEBACK
9140       if (i < 2 || !is_ujump(i-2))
9141       {
9142         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
9143       }
9144       if((itype[i]==CJUMP||itype[i]==SJUMP)&&!likely[i]) {
9145         dirty_pre=branch_regs[i].dirty;
9146       }else{
9147         dirty_pre=regs[i].dirty;
9148       }
9149       #endif
9150       // write back
9151       if (i < 2 || !is_ujump(i-2))
9152       {
9153         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
9154         loop_preload(regmap_pre[i],regs[i].regmap_entry);
9155       }
9156       // branch target entry point
9157       instr_addr[i] = out;
9158       assem_debug("<->\n");
9159       drc_dbg_emit_do_cmp(i);
9160
9161       // load regs
9162       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
9163         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
9164       load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i],rs2[i]);
9165       address_generation(i,&regs[i],regs[i].regmap_entry);
9166       load_consts(regmap_pre[i],regs[i].regmap,i);
9167       if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
9168       {
9169         // Load the delay slot registers if necessary
9170         if(rs1[i+1]!=rs1[i]&&rs1[i+1]!=rs2[i]&&(rs1[i+1]!=rt1[i]||rt1[i]==0))
9171           load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i+1],rs1[i+1]);
9172         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))
9173           load_regs(regs[i].regmap_entry,regs[i].regmap,rs2[i+1],rs2[i+1]);
9174         if(itype[i+1]==STORE||itype[i+1]==STORELR||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a)
9175           load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9176       }
9177       else if(i+1<slen)
9178       {
9179         // Preload registers for following instruction
9180         if(rs1[i+1]!=rs1[i]&&rs1[i+1]!=rs2[i])
9181           if(rs1[i+1]!=rt1[i]&&rs1[i+1]!=rt2[i])
9182             load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i+1],rs1[i+1]);
9183         if(rs2[i+1]!=rs1[i+1]&&rs2[i+1]!=rs1[i]&&rs2[i+1]!=rs2[i])
9184           if(rs2[i+1]!=rt1[i]&&rs2[i+1]!=rt2[i])
9185             load_regs(regs[i].regmap_entry,regs[i].regmap,rs2[i+1],rs2[i+1]);
9186       }
9187       // TODO: if(is_ooo(i)) address_generation(i+1);
9188       if(itype[i]==CJUMP)
9189         load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
9190       if(itype[i]==STORE||itype[i]==STORELR||(opcode[i]&0x3b)==0x39||(opcode[i]&0x3b)==0x3a)
9191         load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9192       // assemble
9193       switch(itype[i]) {
9194         case ALU:
9195           alu_assemble(i,&regs[i]);break;
9196         case IMM16:
9197           imm16_assemble(i,&regs[i]);break;
9198         case SHIFT:
9199           shift_assemble(i,&regs[i]);break;
9200         case SHIFTIMM:
9201           shiftimm_assemble(i,&regs[i]);break;
9202         case LOAD:
9203           load_assemble(i,&regs[i]);break;
9204         case LOADLR:
9205           loadlr_assemble(i,&regs[i]);break;
9206         case STORE:
9207           store_assemble(i,&regs[i]);break;
9208         case STORELR:
9209           storelr_assemble(i,&regs[i]);break;
9210         case COP0:
9211           cop0_assemble(i,&regs[i]);break;
9212         case COP1:
9213           cop1_assemble(i,&regs[i]);break;
9214         case C1LS:
9215           c1ls_assemble(i,&regs[i]);break;
9216         case COP2:
9217           cop2_assemble(i,&regs[i]);break;
9218         case C2LS:
9219           c2ls_assemble(i,&regs[i]);break;
9220         case C2OP:
9221           c2op_assemble(i,&regs[i]);break;
9222         case MULTDIV:
9223           multdiv_assemble(i,&regs[i]);
9224           multdiv_prepare_stall(i,&regs[i]);
9225           break;
9226         case MOV:
9227           mov_assemble(i,&regs[i]);break;
9228         case SYSCALL:
9229           syscall_assemble(i,&regs[i]);break;
9230         case HLECALL:
9231           hlecall_assemble(i,&regs[i]);break;
9232         case INTCALL:
9233           intcall_assemble(i,&regs[i]);break;
9234         case UJUMP:
9235           ujump_assemble(i,&regs[i]);ds=1;break;
9236         case RJUMP:
9237           rjump_assemble(i,&regs[i]);ds=1;break;
9238         case CJUMP:
9239           cjump_assemble(i,&regs[i]);ds=1;break;
9240         case SJUMP:
9241           sjump_assemble(i,&regs[i]);ds=1;break;
9242         case SPAN:
9243           pagespan_assemble(i,&regs[i]);break;
9244       }
9245       if (is_ujump(i))
9246         literal_pool(1024);
9247       else
9248         literal_pool_jumpover(256);
9249     }
9250   }
9251
9252   assert(slen > 0);
9253   if (itype[slen-1] == INTCALL) {
9254     // no ending needed for this block since INTCALL never returns
9255   }
9256   // If the block did not end with an unconditional branch,
9257   // add a jump to the next instruction.
9258   else if (i > 1) {
9259     if(!is_ujump(i-2)&&itype[i-1]!=SPAN) {
9260       assert(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP);
9261       assert(i==slen);
9262       if(itype[i-2]!=CJUMP&&itype[i-2]!=SJUMP) {
9263         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9264         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9265           emit_loadreg(CCREG,HOST_CCREG);
9266         emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
9267       }
9268       else if(!likely[i-2])
9269       {
9270         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
9271         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
9272       }
9273       else
9274       {
9275         store_regs_bt(regs[i-2].regmap,regs[i-2].dirty,start+i*4);
9276         assert(regs[i-2].regmap[HOST_CCREG]==CCREG);
9277       }
9278       add_to_linker(out,start+i*4,0);
9279       emit_jmp(0);
9280     }
9281   }
9282   else
9283   {
9284     assert(i>0);
9285     assert(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP);
9286     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9287     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9288       emit_loadreg(CCREG,HOST_CCREG);
9289     emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
9290     add_to_linker(out,start+i*4,0);
9291     emit_jmp(0);
9292   }
9293
9294   // TODO: delay slot stubs?
9295   // Stubs
9296   for(i=0;i<stubcount;i++)
9297   {
9298     switch(stubs[i].type)
9299     {
9300       case LOADB_STUB:
9301       case LOADH_STUB:
9302       case LOADW_STUB:
9303       case LOADD_STUB:
9304       case LOADBU_STUB:
9305       case LOADHU_STUB:
9306         do_readstub(i);break;
9307       case STOREB_STUB:
9308       case STOREH_STUB:
9309       case STOREW_STUB:
9310       case STORED_STUB:
9311         do_writestub(i);break;
9312       case CC_STUB:
9313         do_ccstub(i);break;
9314       case INVCODE_STUB:
9315         do_invstub(i);break;
9316       case FP_STUB:
9317         do_cop1stub(i);break;
9318       case STORELR_STUB:
9319         do_unalignedwritestub(i);break;
9320     }
9321   }
9322
9323   if (instr_addr0_override)
9324     instr_addr[0] = instr_addr0_override;
9325
9326   /* Pass 9 - Linker */
9327   for(i=0;i<linkcount;i++)
9328   {
9329     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9330     literal_pool(64);
9331     if (!link_addr[i].ext)
9332     {
9333       void *stub = out;
9334       void *addr = check_addr(link_addr[i].target);
9335       emit_extjump(link_addr[i].addr, link_addr[i].target);
9336       if (addr) {
9337         set_jump_target(link_addr[i].addr, addr);
9338         add_jump_out(link_addr[i].target,stub);
9339       }
9340       else
9341         set_jump_target(link_addr[i].addr, stub);
9342     }
9343     else
9344     {
9345       // Internal branch
9346       int target=(link_addr[i].target-start)>>2;
9347       assert(target>=0&&target<slen);
9348       assert(instr_addr[target]);
9349       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9350       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9351       //#else
9352       set_jump_target(link_addr[i].addr, instr_addr[target]);
9353       //#endif
9354     }
9355   }
9356
9357   u_int source_len = slen*4;
9358   if (itype[slen-1] == INTCALL && source_len > 4)
9359     // no need to treat the last instruction as compiled
9360     // as interpreter fully handles it
9361     source_len -= 4;
9362
9363   if ((u_char *)copy + source_len > (u_char *)shadow + sizeof(shadow))
9364     copy = shadow;
9365
9366   // External Branch Targets (jump_in)
9367   for(i=0;i<slen;i++)
9368   {
9369     if(bt[i]||i==0)
9370     {
9371       if(instr_addr[i]) // TODO - delay slots (=null)
9372       {
9373         u_int vaddr=start+i*4;
9374         u_int page=get_page(vaddr);
9375         u_int vpage=get_vpage(vaddr);
9376         literal_pool(256);
9377         {
9378           assem_debug("%p (%d) <- %8x\n",instr_addr[i],i,start+i*4);
9379           assem_debug("jump_in: %x\n",start+i*4);
9380           ll_add(jump_dirty+vpage,vaddr,out);
9381           void *entry_point = do_dirty_stub(i, source_len);
9382           ll_add_flags(jump_in+page,vaddr,state_rflags,entry_point);
9383           // If there was an existing entry in the hash table,
9384           // replace it with the new address.
9385           // Don't add new entries.  We'll insert the
9386           // ones that actually get used in check_addr().
9387           struct ht_entry *ht_bin = hash_table_get(vaddr);
9388           if (ht_bin->vaddr[0] == vaddr)
9389             ht_bin->tcaddr[0] = entry_point;
9390           if (ht_bin->vaddr[1] == vaddr)
9391             ht_bin->tcaddr[1] = entry_point;
9392         }
9393       }
9394     }
9395   }
9396   // Write out the literal pool if necessary
9397   literal_pool(0);
9398   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9399   // Align code
9400   if(((u_int)out)&7) emit_addnop(13);
9401   #endif
9402   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9403   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9404   memcpy(copy, source, source_len);
9405   copy += source_len;
9406
9407   end_block(beginning);
9408
9409   // If we're within 256K of the end of the buffer,
9410   // start over from the beginning. (Is 256K enough?)
9411   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9412     out = ndrc->translation_cache;
9413
9414   // Trap writes to any of the pages we compiled
9415   for(i=start>>12;i<=(start+slen*4)>>12;i++) {
9416     invalid_code[i]=0;
9417   }
9418   inv_code_start=inv_code_end=~0;
9419
9420   // for PCSX we need to mark all mirrors too
9421   if(get_page(start)<(RAM_SIZE>>12))
9422     for(i=start>>12;i<=(start+slen*4)>>12;i++)
9423       invalid_code[((u_int)0x00000000>>12)|(i&0x1ff)]=
9424       invalid_code[((u_int)0x80000000>>12)|(i&0x1ff)]=
9425       invalid_code[((u_int)0xa0000000>>12)|(i&0x1ff)]=0;
9426
9427   /* Pass 10 - Free memory by expiring oldest blocks */
9428
9429   int end=(((out-ndrc->translation_cache)>>(TARGET_SIZE_2-16))+16384)&65535;
9430   while(expirep!=end)
9431   {
9432     int shift=TARGET_SIZE_2-3; // Divide into 8 blocks
9433     uintptr_t base_offs = ((uintptr_t)(expirep >> 13) << shift); // Base offset of this block
9434     uintptr_t base_offs_s = base_offs >> shift;
9435     inv_debug("EXP: Phase %d\n",expirep);
9436     switch((expirep>>11)&3)
9437     {
9438       case 0:
9439         // Clear jump_in and jump_dirty
9440         ll_remove_matching_addrs(jump_in+(expirep&2047),base_offs_s,shift);
9441         ll_remove_matching_addrs(jump_dirty+(expirep&2047),base_offs_s,shift);
9442         ll_remove_matching_addrs(jump_in+2048+(expirep&2047),base_offs_s,shift);
9443         ll_remove_matching_addrs(jump_dirty+2048+(expirep&2047),base_offs_s,shift);
9444         break;
9445       case 1:
9446         // Clear pointers
9447         ll_kill_pointers(jump_out[expirep&2047],base_offs_s,shift);
9448         ll_kill_pointers(jump_out[(expirep&2047)+2048],base_offs_s,shift);
9449         break;
9450       case 2:
9451         // Clear hash table
9452         for(i=0;i<32;i++) {
9453           struct ht_entry *ht_bin = &hash_table[((expirep&2047)<<5)+i];
9454           uintptr_t o1 = (u_char *)ht_bin->tcaddr[1] - ndrc->translation_cache;
9455           uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
9456           if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s) {
9457             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[1],ht_bin->tcaddr[1]);
9458             ht_bin->vaddr[1] = -1;
9459             ht_bin->tcaddr[1] = NULL;
9460           }
9461           o1 = (u_char *)ht_bin->tcaddr[0] - ndrc->translation_cache;
9462           o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
9463           if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s) {
9464             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[0],ht_bin->tcaddr[0]);
9465             ht_bin->vaddr[0] = ht_bin->vaddr[1];
9466             ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
9467             ht_bin->vaddr[1] = -1;
9468             ht_bin->tcaddr[1] = NULL;
9469           }
9470         }
9471         break;
9472       case 3:
9473         // Clear jump_out
9474         if((expirep&2047)==0)
9475           do_clear_cache();
9476         ll_remove_matching_addrs(jump_out+(expirep&2047),base_offs_s,shift);
9477         ll_remove_matching_addrs(jump_out+2048+(expirep&2047),base_offs_s,shift);
9478         break;
9479     }
9480     expirep=(expirep+1)&65535;
9481   }
9482   return 0;
9483 }
9484
9485 // vim:shiftwidth=2:expandtab