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