921a2ed18836d5f64e20d4bdc4ae15153bd42d05
[pcsx_rearmed.git] / libpcsxcore / new_dynarec / new_dynarec.c
1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  *   Mupen64plus - new_dynarec.c                                           *
3  *   Copyright (C) 2009-2011 Ari64                                         *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
19  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
20
21 #include <stdlib.h>
22 #include <stdint.h> //include for uint64_t
23 #include <assert.h>
24 #include <errno.h>
25 #include <sys/mman.h>
26 #ifdef __MACH__
27 #include <libkern/OSCacheControl.h>
28 #endif
29 #ifdef _3DS
30 #include <3ds_utils.h>
31 #endif
32 #ifdef VITA
33 #include <psp2/kernel/sysmem.h>
34 static int sceBlock;
35 #endif
36
37 #include "new_dynarec_config.h"
38 #include "../psxhle.h"
39 #include "../psxinterpreter.h"
40 #include "../gte.h"
41 #include "emu_if.h" // emulator interface
42
43 #define noinline __attribute__((noinline,noclone))
44 #ifndef ARRAY_SIZE
45 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
46 #endif
47 #ifndef min
48 #define min(a, b) ((b) < (a) ? (b) : (a))
49 #endif
50 #ifndef max
51 #define max(a, b) ((b) > (a) ? (b) : (a))
52 #endif
53
54 //#define DISASM
55 //#define ASSEM_PRINT
56
57 #ifdef ASSEM_PRINT
58 #define assem_debug printf
59 #else
60 #define assem_debug(...)
61 #endif
62 //#define inv_debug printf
63 #define inv_debug(...)
64
65 #ifdef __i386__
66 #include "assem_x86.h"
67 #endif
68 #ifdef __x86_64__
69 #include "assem_x64.h"
70 #endif
71 #ifdef __arm__
72 #include "assem_arm.h"
73 #endif
74 #ifdef __aarch64__
75 #include "assem_arm64.h"
76 #endif
77
78 #define RAM_SIZE 0x200000
79 #define MAXBLOCK 4096
80 #define MAX_OUTPUT_BLOCK_SIZE 262144
81
82 struct ndrc_mem
83 {
84   u_char translation_cache[1 << TARGET_SIZE_2];
85   struct
86   {
87     struct tramp_insns ops[2048 / sizeof(struct tramp_insns)];
88     const void *f[2048 / sizeof(void *)];
89   } tramp;
90 };
91
92 #ifdef BASE_ADDR_DYNAMIC
93 static struct ndrc_mem *ndrc;
94 #else
95 static struct ndrc_mem ndrc_ __attribute__((aligned(4096)));
96 static struct ndrc_mem *ndrc = &ndrc_;
97 #endif
98
99 // stubs
100 enum stub_type {
101   CC_STUB = 1,
102   FP_STUB = 2,
103   LOADB_STUB = 3,
104   LOADH_STUB = 4,
105   LOADW_STUB = 5,
106   LOADD_STUB = 6,
107   LOADBU_STUB = 7,
108   LOADHU_STUB = 8,
109   STOREB_STUB = 9,
110   STOREH_STUB = 10,
111   STOREW_STUB = 11,
112   STORED_STUB = 12,
113   STORELR_STUB = 13,
114   INVCODE_STUB = 14,
115 };
116
117 struct regstat
118 {
119   signed char regmap_entry[HOST_REGS];
120   signed char regmap[HOST_REGS];
121   uint64_t wasdirty;
122   uint64_t dirty;
123   uint64_t u;
124   u_int wasconst;
125   u_int isconst;
126   u_int loadedconst;             // host regs that have constants loaded
127   u_int waswritten;              // MIPS regs that were used as store base before
128 };
129
130 // note: asm depends on this layout
131 struct ll_entry
132 {
133   u_int vaddr;
134   u_int reg_sv_flags;
135   void *addr;
136   struct ll_entry *next;
137 };
138
139 struct ht_entry
140 {
141   u_int vaddr[2];
142   void *tcaddr[2];
143 };
144
145 struct code_stub
146 {
147   enum stub_type type;
148   void *addr;
149   void *retaddr;
150   u_int a;
151   uintptr_t b;
152   uintptr_t c;
153   u_int d;
154   u_int e;
155 };
156
157 struct link_entry
158 {
159   void *addr;
160   u_int target;
161   u_int ext;
162 };
163
164 static struct decoded_insn
165 {
166   u_char itype;
167   u_char opcode;
168   u_char opcode2;
169   u_char rs1;
170   u_char rs2;
171   u_char rt1;
172   u_char rt2;
173   u_char lt1;
174   u_char bt:1;
175   u_char ooo:1;
176   u_char is_ds:1;
177   u_char is_jump:1;
178   u_char is_ujump:1;
179   u_char is_load:1;
180   u_char is_store:1;
181 } dops[MAXBLOCK];
182
183   // used by asm:
184   u_char *out;
185   struct ht_entry hash_table[65536]  __attribute__((aligned(16)));
186   struct ll_entry *jump_in[4096] __attribute__((aligned(16)));
187   struct ll_entry *jump_dirty[4096];
188
189   static struct ll_entry *jump_out[4096];
190   static u_int start;
191   static u_int *source;
192   static char insn[MAXBLOCK][10];
193   static uint64_t gte_rs[MAXBLOCK]; // gte: 32 data and 32 ctl regs
194   static uint64_t gte_rt[MAXBLOCK];
195   static uint64_t gte_unneeded[MAXBLOCK];
196   static u_int smrv[32]; // speculated MIPS register values
197   static u_int smrv_strong; // mask or regs that are likely to have correct values
198   static u_int smrv_weak; // same, but somewhat less likely
199   static u_int smrv_strong_next; // same, but after current insn executes
200   static u_int smrv_weak_next;
201   static int imm[MAXBLOCK];
202   static u_int ba[MAXBLOCK];
203   static uint64_t unneeded_reg[MAXBLOCK];
204   static uint64_t branch_unneeded_reg[MAXBLOCK];
205   static signed char regmap_pre[MAXBLOCK][HOST_REGS]; // pre-instruction i?
206   // contains 'real' consts at [i] insn, but may differ from what's actually
207   // loaded in host reg as 'final' value is always loaded, see get_final_value()
208   static uint32_t current_constmap[HOST_REGS];
209   static uint32_t constmap[MAXBLOCK][HOST_REGS];
210   static struct regstat regs[MAXBLOCK];
211   static struct regstat branch_regs[MAXBLOCK];
212   static signed char minimum_free_regs[MAXBLOCK];
213   static u_int needed_reg[MAXBLOCK];
214   static u_int wont_dirty[MAXBLOCK];
215   static u_int will_dirty[MAXBLOCK];
216   static int ccadj[MAXBLOCK];
217   static int slen;
218   static void *instr_addr[MAXBLOCK];
219   static struct link_entry link_addr[MAXBLOCK];
220   static int linkcount;
221   static struct code_stub stubs[MAXBLOCK*3];
222   static int stubcount;
223   static u_int literals[1024][2];
224   static int literalcount;
225   static int is_delayslot;
226   static char shadow[1048576]  __attribute__((aligned(16)));
227   static void *copy;
228   static int expirep;
229   static u_int stop_after_jal;
230   static u_int f1_hack; // 0 - off, ~0 - capture address, else addr
231
232   int new_dynarec_hacks;
233   int new_dynarec_hacks_pergame;
234   int new_dynarec_hacks_old;
235   int new_dynarec_did_compile;
236
237   #define HACK_ENABLED(x) ((new_dynarec_hacks | new_dynarec_hacks_pergame) & (x))
238
239   extern int cycle_count; // ... until end of the timeslice, counts -N -> 0
240   extern int last_count;  // last absolute target, often = next_interupt
241   extern int pcaddr;
242   extern int pending_exception;
243   extern int branch_target;
244   extern uintptr_t ram_offset;
245   extern uintptr_t mini_ht[32][2];
246   extern u_char restore_candidate[512];
247
248   /* registers that may be allocated */
249   /* 1-31 gpr */
250 #define LOREG 32 // lo
251 #define HIREG 33 // hi
252 //#define FSREG 34 // FPU status (FCSR)
253 #define CSREG 35 // Coprocessor status
254 #define CCREG 36 // Cycle count
255 #define INVCP 37 // Pointer to invalid_code
256 //#define MMREG 38 // Pointer to memory_map
257 #define ROREG 39 // ram offset (if rdram!=0x80000000)
258 #define TEMPREG 40
259 #define FTEMP 40 // FPU temporary register
260 #define PTEMP 41 // Prefetch temporary register
261 //#define TLREG 42 // TLB mapping offset
262 #define RHASH 43 // Return address hash
263 #define RHTBL 44 // Return address hash table address
264 #define RTEMP 45 // JR/JALR address register
265 #define MAXREG 45
266 #define AGEN1 46 // Address generation temporary register
267 //#define AGEN2 47 // Address generation temporary register
268 //#define MGEN1 48 // Maptable address generation temporary register
269 //#define MGEN2 49 // Maptable address generation temporary register
270 #define BTREG 50 // Branch target temporary register
271
272   /* instruction types */
273 #define NOP 0     // No operation
274 #define LOAD 1    // Load
275 #define STORE 2   // Store
276 #define LOADLR 3  // Unaligned load
277 #define STORELR 4 // Unaligned store
278 #define MOV 5     // Move
279 #define ALU 6     // Arithmetic/logic
280 #define MULTDIV 7 // Multiply/divide
281 #define SHIFT 8   // Shift by register
282 #define SHIFTIMM 9// Shift by immediate
283 #define IMM16 10  // 16-bit immediate
284 #define RJUMP 11  // Unconditional jump to register
285 #define UJUMP 12  // Unconditional jump
286 #define CJUMP 13  // Conditional branch (BEQ/BNE/BGTZ/BLEZ)
287 #define SJUMP 14  // Conditional branch (regimm format)
288 #define COP0 15   // Coprocessor 0
289 #define COP1 16   // Coprocessor 1
290 #define C1LS 17   // Coprocessor 1 load/store
291 //#define FJUMP 18  // Conditional branch (floating point)
292 //#define FLOAT 19  // Floating point unit
293 //#define FCONV 20  // Convert integer to float
294 //#define FCOMP 21  // Floating point compare (sets FSREG)
295 #define SYSCALL 22// SYSCALL
296 #define OTHER 23  // Other
297 #define SPAN 24   // Branch/delay slot spans 2 pages
298 #define NI 25     // Not implemented
299 #define HLECALL 26// PCSX fake opcodes for HLE
300 #define COP2 27   // Coprocessor 2 move
301 #define C2LS 28   // Coprocessor 2 load/store
302 #define C2OP 29   // Coprocessor 2 operation
303 #define INTCALL 30// Call interpreter to handle rare corner cases
304
305   /* branch codes */
306 #define TAKEN 1
307 #define NOTTAKEN 2
308 #define NULLDS 3
309
310 #define DJT_1 (void *)1l // no function, just a label in assem_debug log
311 #define DJT_2 (void *)2l
312
313 // asm linkage
314 int new_recompile_block(u_int addr);
315 void *get_addr_ht(u_int vaddr);
316 void invalidate_block(u_int block);
317 void invalidate_addr(u_int addr);
318 void remove_hash(int vaddr);
319 void dyna_linker();
320 void dyna_linker_ds();
321 void verify_code();
322 void verify_code_ds();
323 void cc_interrupt();
324 void fp_exception();
325 void fp_exception_ds();
326 void jump_to_new_pc();
327 void call_gteStall();
328 void new_dyna_leave();
329
330 // Needed by assembler
331 static void wb_register(signed char r,signed char regmap[],uint64_t dirty);
332 static void wb_dirtys(signed char i_regmap[],uint64_t i_dirty);
333 static void wb_needed_dirtys(signed char i_regmap[],uint64_t i_dirty,int addr);
334 static void load_all_regs(signed char i_regmap[]);
335 static void load_needed_regs(signed char i_regmap[],signed char next_regmap[]);
336 static void load_regs_entry(int t);
337 static void load_all_consts(signed char regmap[],u_int dirty,int i);
338 static u_int get_host_reglist(const signed char *regmap);
339
340 static int verify_dirty(const u_int *ptr);
341 static int get_final_value(int hr, int i, int *value);
342 static void add_stub(enum stub_type type, void *addr, void *retaddr,
343   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e);
344 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
345   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist);
346 static void add_to_linker(void *addr, u_int target, int ext);
347 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
348   int addr, int *offset_reg, int *addr_reg_override);
349 static void *get_direct_memhandler(void *table, u_int addr,
350   enum stub_type type, uintptr_t *addr_host);
351 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist);
352 static void pass_args(int a0, int a1);
353 static void emit_far_jump(const void *f);
354 static void emit_far_call(const void *f);
355
356 static void mprotect_w_x(void *start, void *end, int is_x)
357 {
358 #ifdef NO_WRITE_EXEC
359   #if defined(VITA)
360   // *Open* enables write on all memory that was
361   // allocated by sceKernelAllocMemBlockForVM()?
362   if (is_x)
363     sceKernelCloseVMDomain();
364   else
365     sceKernelOpenVMDomain();
366   #else
367   u_long mstart = (u_long)start & ~4095ul;
368   u_long mend = (u_long)end;
369   if (mprotect((void *)mstart, mend - mstart,
370                PROT_READ | (is_x ? PROT_EXEC : PROT_WRITE)) != 0)
371     SysPrintf("mprotect(%c) failed: %s\n", is_x ? 'x' : 'w', strerror(errno));
372   #endif
373 #endif
374 }
375
376 static void start_tcache_write(void *start, void *end)
377 {
378   mprotect_w_x(start, end, 0);
379 }
380
381 static void end_tcache_write(void *start, void *end)
382 {
383 #if defined(__arm__) || defined(__aarch64__)
384   size_t len = (char *)end - (char *)start;
385   #if   defined(__BLACKBERRY_QNX__)
386   msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
387   #elif defined(__MACH__)
388   sys_cache_control(kCacheFunctionPrepareForExecution, start, len);
389   #elif defined(VITA)
390   sceKernelSyncVMDomain(sceBlock, start, len);
391   #elif defined(_3DS)
392   ctr_flush_invalidate_cache();
393   #elif defined(__aarch64__)
394   // as of 2021, __clear_cache() is still broken on arm64
395   // so here is a custom one :(
396   clear_cache_arm64(start, end);
397   #else
398   __clear_cache(start, end);
399   #endif
400   (void)len;
401 #endif
402
403   mprotect_w_x(start, end, 1);
404 }
405
406 static void *start_block(void)
407 {
408   u_char *end = out + MAX_OUTPUT_BLOCK_SIZE;
409   if (end > ndrc->translation_cache + sizeof(ndrc->translation_cache))
410     end = ndrc->translation_cache + sizeof(ndrc->translation_cache);
411   start_tcache_write(out, end);
412   return out;
413 }
414
415 static void end_block(void *start)
416 {
417   end_tcache_write(start, out);
418 }
419
420 // also takes care of w^x mappings when patching code
421 static u_int needs_clear_cache[1<<(TARGET_SIZE_2-17)];
422
423 static void mark_clear_cache(void *target)
424 {
425   uintptr_t offset = (u_char *)target - ndrc->translation_cache;
426   u_int mask = 1u << ((offset >> 12) & 31);
427   if (!(needs_clear_cache[offset >> 17] & mask)) {
428     char *start = (char *)((uintptr_t)target & ~4095l);
429     start_tcache_write(start, start + 4095);
430     needs_clear_cache[offset >> 17] |= mask;
431   }
432 }
433
434 // Clearing the cache is rather slow on ARM Linux, so mark the areas
435 // that need to be cleared, and then only clear these areas once.
436 static void do_clear_cache(void)
437 {
438   int i, j;
439   for (i = 0; i < (1<<(TARGET_SIZE_2-17)); i++)
440   {
441     u_int bitmap = needs_clear_cache[i];
442     if (!bitmap)
443       continue;
444     for (j = 0; j < 32; j++)
445     {
446       u_char *start, *end;
447       if (!(bitmap & (1<<j)))
448         continue;
449
450       start = ndrc->translation_cache + i*131072 + j*4096;
451       end = start + 4095;
452       for (j++; j < 32; j++) {
453         if (!(bitmap & (1<<j)))
454           break;
455         end += 4096;
456       }
457       end_tcache_write(start, end);
458     }
459     needs_clear_cache[i] = 0;
460   }
461 }
462
463 //#define DEBUG_CYCLE_COUNT 1
464
465 #define NO_CYCLE_PENALTY_THR 12
466
467 int cycle_multiplier = CYCLE_MULT_DEFAULT; // 100 for 1.0
468 int cycle_multiplier_override;
469 int cycle_multiplier_old;
470
471 static int CLOCK_ADJUST(int x)
472 {
473   int m = cycle_multiplier_override && cycle_multiplier == CYCLE_MULT_DEFAULT
474         ? cycle_multiplier_override : cycle_multiplier;
475   int s=(x>>31)|1;
476   return (x * m + s * 50) / 100;
477 }
478
479 static int ds_writes_rjump_rs(int i)
480 {
481   return dops[i].rs1 != 0 && (dops[i].rs1 == dops[i+1].rt1 || dops[i].rs1 == dops[i+1].rt2);
482 }
483
484 static u_int get_page(u_int vaddr)
485 {
486   u_int page=vaddr&~0xe0000000;
487   if (page < 0x1000000)
488     page &= ~0x0e00000; // RAM mirrors
489   page>>=12;
490   if(page>2048) page=2048+(page&2047);
491   return page;
492 }
493
494 // no virtual mem in PCSX
495 static u_int get_vpage(u_int vaddr)
496 {
497   return get_page(vaddr);
498 }
499
500 static struct ht_entry *hash_table_get(u_int vaddr)
501 {
502   return &hash_table[((vaddr>>16)^vaddr)&0xFFFF];
503 }
504
505 static void hash_table_add(struct ht_entry *ht_bin, u_int vaddr, void *tcaddr)
506 {
507   ht_bin->vaddr[1] = ht_bin->vaddr[0];
508   ht_bin->tcaddr[1] = ht_bin->tcaddr[0];
509   ht_bin->vaddr[0] = vaddr;
510   ht_bin->tcaddr[0] = tcaddr;
511 }
512
513 // some messy ari64's code, seems to rely on unsigned 32bit overflow
514 static int doesnt_expire_soon(void *tcaddr)
515 {
516   u_int diff = (u_int)((u_char *)tcaddr - out) << (32-TARGET_SIZE_2);
517   return diff > (u_int)(0x60000000 + (MAX_OUTPUT_BLOCK_SIZE << (32-TARGET_SIZE_2)));
518 }
519
520 // Get address from virtual address
521 // This is called from the recompiled JR/JALR instructions
522 void noinline *get_addr(u_int vaddr)
523 {
524   u_int page=get_page(vaddr);
525   u_int vpage=get_vpage(vaddr);
526   struct ll_entry *head;
527   //printf("TRACE: count=%d next=%d (get_addr %x,page %d)\n",Count,next_interupt,vaddr,page);
528   head=jump_in[page];
529   while(head!=NULL) {
530     if(head->vaddr==vaddr) {
531   //printf("TRACE: count=%d next=%d (get_addr match %x: %p)\n",Count,next_interupt,vaddr,head->addr);
532       hash_table_add(hash_table_get(vaddr), vaddr, head->addr);
533       return head->addr;
534     }
535     head=head->next;
536   }
537   head=jump_dirty[vpage];
538   while(head!=NULL) {
539     if(head->vaddr==vaddr) {
540       //printf("TRACE: count=%d next=%d (get_addr match dirty %x: %p)\n",Count,next_interupt,vaddr,head->addr);
541       // Don't restore blocks which are about to expire from the cache
542       if (doesnt_expire_soon(head->addr))
543       if (verify_dirty(head->addr)) {
544         //printf("restore candidate: %x (%d) d=%d\n",vaddr,page,invalid_code[vaddr>>12]);
545         invalid_code[vaddr>>12]=0;
546         inv_code_start=inv_code_end=~0;
547         if(vpage<2048) {
548           restore_candidate[vpage>>3]|=1<<(vpage&7);
549         }
550         else restore_candidate[page>>3]|=1<<(page&7);
551         struct ht_entry *ht_bin = hash_table_get(vaddr);
552         if (ht_bin->vaddr[0] == vaddr)
553           ht_bin->tcaddr[0] = head->addr; // Replace existing entry
554         else
555           hash_table_add(ht_bin, vaddr, head->addr);
556
557         return head->addr;
558       }
559     }
560     head=head->next;
561   }
562   //printf("TRACE: count=%d next=%d (get_addr no-match %x)\n",Count,next_interupt,vaddr);
563   int r=new_recompile_block(vaddr);
564   if(r==0) return get_addr(vaddr);
565   // Execute in unmapped page, generate pagefault execption
566   Status|=2;
567   Cause=(vaddr<<31)|0x8;
568   EPC=(vaddr&1)?vaddr-5:vaddr;
569   BadVAddr=(vaddr&~1);
570   Context=(Context&0xFF80000F)|((BadVAddr>>9)&0x007FFFF0);
571   EntryHi=BadVAddr&0xFFFFE000;
572   return get_addr_ht(0x80000000);
573 }
574 // Look up address in hash table first
575 void *get_addr_ht(u_int vaddr)
576 {
577   //printf("TRACE: count=%d next=%d (get_addr_ht %x)\n",Count,next_interupt,vaddr);
578   const struct ht_entry *ht_bin = hash_table_get(vaddr);
579   if (ht_bin->vaddr[0] == vaddr) return ht_bin->tcaddr[0];
580   if (ht_bin->vaddr[1] == vaddr) return ht_bin->tcaddr[1];
581   return get_addr(vaddr);
582 }
583
584 void clear_all_regs(signed char regmap[])
585 {
586   int hr;
587   for (hr=0;hr<HOST_REGS;hr++) regmap[hr]=-1;
588 }
589
590 static signed char get_reg(const signed char regmap[],int r)
591 {
592   int hr;
593   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap[hr]==r) return hr;
594   return -1;
595 }
596
597 // Find a register that is available for two consecutive cycles
598 static signed char get_reg2(signed char regmap1[], const signed char regmap2[], int r)
599 {
600   int hr;
601   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap1[hr]==r&&regmap2[hr]==r) return hr;
602   return -1;
603 }
604
605 int count_free_regs(signed char regmap[])
606 {
607   int count=0;
608   int hr;
609   for(hr=0;hr<HOST_REGS;hr++)
610   {
611     if(hr!=EXCLUDE_REG) {
612       if(regmap[hr]<0) count++;
613     }
614   }
615   return count;
616 }
617
618 void dirty_reg(struct regstat *cur,signed char reg)
619 {
620   int hr;
621   if(!reg) return;
622   for (hr=0;hr<HOST_REGS;hr++) {
623     if((cur->regmap[hr]&63)==reg) {
624       cur->dirty|=1<<hr;
625     }
626   }
627 }
628
629 static void set_const(struct regstat *cur, signed char reg, uint32_t value)
630 {
631   int hr;
632   if(!reg) return;
633   for (hr=0;hr<HOST_REGS;hr++) {
634     if(cur->regmap[hr]==reg) {
635       cur->isconst|=1<<hr;
636       current_constmap[hr]=value;
637     }
638   }
639 }
640
641 static void clear_const(struct regstat *cur, signed char reg)
642 {
643   int hr;
644   if(!reg) return;
645   for (hr=0;hr<HOST_REGS;hr++) {
646     if((cur->regmap[hr]&63)==reg) {
647       cur->isconst&=~(1<<hr);
648     }
649   }
650 }
651
652 static int is_const(struct regstat *cur, signed char reg)
653 {
654   int hr;
655   if(reg<0) return 0;
656   if(!reg) return 1;
657   for (hr=0;hr<HOST_REGS;hr++) {
658     if((cur->regmap[hr]&63)==reg) {
659       return (cur->isconst>>hr)&1;
660     }
661   }
662   return 0;
663 }
664
665 static uint32_t get_const(struct regstat *cur, signed char reg)
666 {
667   int hr;
668   if(!reg) return 0;
669   for (hr=0;hr<HOST_REGS;hr++) {
670     if(cur->regmap[hr]==reg) {
671       return current_constmap[hr];
672     }
673   }
674   SysPrintf("Unknown constant in r%d\n",reg);
675   abort();
676 }
677
678 // Least soon needed registers
679 // Look at the next ten instructions and see which registers
680 // will be used.  Try not to reallocate these.
681 void lsn(u_char hsn[], int i, int *preferred_reg)
682 {
683   int j;
684   int b=-1;
685   for(j=0;j<9;j++)
686   {
687     if(i+j>=slen) {
688       j=slen-i-1;
689       break;
690     }
691     if (dops[i+j].is_ujump)
692     {
693       // Don't go past an unconditonal jump
694       j++;
695       break;
696     }
697   }
698   for(;j>=0;j--)
699   {
700     if(dops[i+j].rs1) hsn[dops[i+j].rs1]=j;
701     if(dops[i+j].rs2) hsn[dops[i+j].rs2]=j;
702     if(dops[i+j].rt1) hsn[dops[i+j].rt1]=j;
703     if(dops[i+j].rt2) hsn[dops[i+j].rt2]=j;
704     if(dops[i+j].itype==STORE || dops[i+j].itype==STORELR) {
705       // Stores can allocate zero
706       hsn[dops[i+j].rs1]=j;
707       hsn[dops[i+j].rs2]=j;
708     }
709     if (ram_offset && (dops[i+j].is_load || dops[i+j].is_store))
710       hsn[ROREG] = j;
711     // On some architectures stores need invc_ptr
712     #if defined(HOST_IMM8)
713     if (dops[i+j].is_store)
714       hsn[INVCP] = j;
715     #endif
716     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
717     {
718       hsn[CCREG]=j;
719       b=j;
720     }
721   }
722   if(b>=0)
723   {
724     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
725     {
726       // Follow first branch
727       int t=(ba[i+b]-start)>>2;
728       j=7-b;if(t+j>=slen) j=slen-t-1;
729       for(;j>=0;j--)
730       {
731         if(dops[t+j].rs1) if(hsn[dops[t+j].rs1]>j+b+2) hsn[dops[t+j].rs1]=j+b+2;
732         if(dops[t+j].rs2) if(hsn[dops[t+j].rs2]>j+b+2) hsn[dops[t+j].rs2]=j+b+2;
733         //if(dops[t+j].rt1) if(hsn[dops[t+j].rt1]>j+b+2) hsn[dops[t+j].rt1]=j+b+2;
734         //if(dops[t+j].rt2) if(hsn[dops[t+j].rt2]>j+b+2) hsn[dops[t+j].rt2]=j+b+2;
735       }
736     }
737     // TODO: preferred register based on backward branch
738   }
739   // Delay slot should preferably not overwrite branch conditions or cycle count
740   if (i > 0 && dops[i-1].is_jump) {
741     if(dops[i-1].rs1) if(hsn[dops[i-1].rs1]>1) hsn[dops[i-1].rs1]=1;
742     if(dops[i-1].rs2) if(hsn[dops[i-1].rs2]>1) hsn[dops[i-1].rs2]=1;
743     hsn[CCREG]=1;
744     // ...or hash tables
745     hsn[RHASH]=1;
746     hsn[RHTBL]=1;
747   }
748   // Coprocessor load/store needs FTEMP, even if not declared
749   if(dops[i].itype==C2LS) {
750     hsn[FTEMP]=0;
751   }
752   // Load L/R also uses FTEMP as a temporary register
753   if(dops[i].itype==LOADLR) {
754     hsn[FTEMP]=0;
755   }
756   // Also SWL/SWR/SDL/SDR
757   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) {
758     hsn[FTEMP]=0;
759   }
760   // Don't remove the miniht registers
761   if(dops[i].itype==UJUMP||dops[i].itype==RJUMP)
762   {
763     hsn[RHASH]=0;
764     hsn[RHTBL]=0;
765   }
766 }
767
768 // We only want to allocate registers if we're going to use them again soon
769 int needed_again(int r, int i)
770 {
771   int j;
772   int b=-1;
773   int rn=10;
774
775   if (i > 0 && dops[i-1].is_ujump)
776   {
777     if(ba[i-1]<start || ba[i-1]>start+slen*4-4)
778       return 0; // Don't need any registers if exiting the block
779   }
780   for(j=0;j<9;j++)
781   {
782     if(i+j>=slen) {
783       j=slen-i-1;
784       break;
785     }
786     if (dops[i+j].is_ujump)
787     {
788       // Don't go past an unconditonal jump
789       j++;
790       break;
791     }
792     if(dops[i+j].itype==SYSCALL||dops[i+j].itype==HLECALL||dops[i+j].itype==INTCALL||((source[i+j]&0xfc00003f)==0x0d))
793     {
794       break;
795     }
796   }
797   for(;j>=1;j--)
798   {
799     if(dops[i+j].rs1==r) rn=j;
800     if(dops[i+j].rs2==r) rn=j;
801     if((unneeded_reg[i+j]>>r)&1) rn=10;
802     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
803     {
804       b=j;
805     }
806   }
807   if(rn<10) return 1;
808   (void)b;
809   return 0;
810 }
811
812 // Try to match register allocations at the end of a loop with those
813 // at the beginning
814 int loop_reg(int i, int r, int hr)
815 {
816   int j,k;
817   for(j=0;j<9;j++)
818   {
819     if(i+j>=slen) {
820       j=slen-i-1;
821       break;
822     }
823     if (dops[i+j].is_ujump)
824     {
825       // Don't go past an unconditonal jump
826       j++;
827       break;
828     }
829   }
830   k=0;
831   if(i>0){
832     if(dops[i-1].itype==UJUMP||dops[i-1].itype==CJUMP||dops[i-1].itype==SJUMP)
833       k--;
834   }
835   for(;k<j;k++)
836   {
837     assert(r < 64);
838     if((unneeded_reg[i+k]>>r)&1) return hr;
839     if(i+k>=0&&(dops[i+k].itype==UJUMP||dops[i+k].itype==CJUMP||dops[i+k].itype==SJUMP))
840     {
841       if(ba[i+k]>=start && ba[i+k]<(start+i*4))
842       {
843         int t=(ba[i+k]-start)>>2;
844         int reg=get_reg(regs[t].regmap_entry,r);
845         if(reg>=0) return reg;
846         //reg=get_reg(regs[t+1].regmap_entry,r);
847         //if(reg>=0) return reg;
848       }
849     }
850   }
851   return hr;
852 }
853
854
855 // Allocate every register, preserving source/target regs
856 void alloc_all(struct regstat *cur,int i)
857 {
858   int hr;
859
860   for(hr=0;hr<HOST_REGS;hr++) {
861     if(hr!=EXCLUDE_REG) {
862       if(((cur->regmap[hr]&63)!=dops[i].rs1)&&((cur->regmap[hr]&63)!=dops[i].rs2)&&
863          ((cur->regmap[hr]&63)!=dops[i].rt1)&&((cur->regmap[hr]&63)!=dops[i].rt2))
864       {
865         cur->regmap[hr]=-1;
866         cur->dirty&=~(1<<hr);
867       }
868       // Don't need zeros
869       if((cur->regmap[hr]&63)==0)
870       {
871         cur->regmap[hr]=-1;
872         cur->dirty&=~(1<<hr);
873       }
874     }
875   }
876 }
877
878 #ifndef NDEBUG
879 static int host_tempreg_in_use;
880
881 static void host_tempreg_acquire(void)
882 {
883   assert(!host_tempreg_in_use);
884   host_tempreg_in_use = 1;
885 }
886
887 static void host_tempreg_release(void)
888 {
889   host_tempreg_in_use = 0;
890 }
891 #else
892 static void host_tempreg_acquire(void) {}
893 static void host_tempreg_release(void) {}
894 #endif
895
896 #ifdef ASSEM_PRINT
897 extern void gen_interupt();
898 extern void do_insn_cmp();
899 #define FUNCNAME(f) { f, " " #f }
900 static const struct {
901   void *addr;
902   const char *name;
903 } function_names[] = {
904   FUNCNAME(cc_interrupt),
905   FUNCNAME(gen_interupt),
906   FUNCNAME(get_addr_ht),
907   FUNCNAME(get_addr),
908   FUNCNAME(jump_handler_read8),
909   FUNCNAME(jump_handler_read16),
910   FUNCNAME(jump_handler_read32),
911   FUNCNAME(jump_handler_write8),
912   FUNCNAME(jump_handler_write16),
913   FUNCNAME(jump_handler_write32),
914   FUNCNAME(invalidate_addr),
915   FUNCNAME(jump_to_new_pc),
916   FUNCNAME(call_gteStall),
917   FUNCNAME(new_dyna_leave),
918   FUNCNAME(pcsx_mtc0),
919   FUNCNAME(pcsx_mtc0_ds),
920 #ifdef DRC_DBG
921   FUNCNAME(do_insn_cmp),
922 #endif
923 #ifdef __arm__
924   FUNCNAME(verify_code),
925 #endif
926 };
927
928 static const char *func_name(const void *a)
929 {
930   int i;
931   for (i = 0; i < sizeof(function_names)/sizeof(function_names[0]); i++)
932     if (function_names[i].addr == a)
933       return function_names[i].name;
934   return "";
935 }
936 #else
937 #define func_name(x) ""
938 #endif
939
940 #ifdef __i386__
941 #include "assem_x86.c"
942 #endif
943 #ifdef __x86_64__
944 #include "assem_x64.c"
945 #endif
946 #ifdef __arm__
947 #include "assem_arm.c"
948 #endif
949 #ifdef __aarch64__
950 #include "assem_arm64.c"
951 #endif
952
953 static void *get_trampoline(const void *f)
954 {
955   size_t i;
956
957   for (i = 0; i < ARRAY_SIZE(ndrc->tramp.f); i++) {
958     if (ndrc->tramp.f[i] == f || ndrc->tramp.f[i] == NULL)
959       break;
960   }
961   if (i == ARRAY_SIZE(ndrc->tramp.f)) {
962     SysPrintf("trampoline table is full, last func %p\n", f);
963     abort();
964   }
965   if (ndrc->tramp.f[i] == NULL) {
966     start_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
967     ndrc->tramp.f[i] = f;
968     end_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
969   }
970   return &ndrc->tramp.ops[i];
971 }
972
973 static void emit_far_jump(const void *f)
974 {
975   if (can_jump_or_call(f)) {
976     emit_jmp(f);
977     return;
978   }
979
980   f = get_trampoline(f);
981   emit_jmp(f);
982 }
983
984 static void emit_far_call(const void *f)
985 {
986   if (can_jump_or_call(f)) {
987     emit_call(f);
988     return;
989   }
990
991   f = get_trampoline(f);
992   emit_call(f);
993 }
994
995 // Add virtual address mapping to linked list
996 void ll_add(struct ll_entry **head,int vaddr,void *addr)
997 {
998   struct ll_entry *new_entry;
999   new_entry=malloc(sizeof(struct ll_entry));
1000   assert(new_entry!=NULL);
1001   new_entry->vaddr=vaddr;
1002   new_entry->reg_sv_flags=0;
1003   new_entry->addr=addr;
1004   new_entry->next=*head;
1005   *head=new_entry;
1006 }
1007
1008 void ll_add_flags(struct ll_entry **head,int vaddr,u_int reg_sv_flags,void *addr)
1009 {
1010   ll_add(head,vaddr,addr);
1011   (*head)->reg_sv_flags=reg_sv_flags;
1012 }
1013
1014 // Check if an address is already compiled
1015 // but don't return addresses which are about to expire from the cache
1016 void *check_addr(u_int vaddr)
1017 {
1018   struct ht_entry *ht_bin = hash_table_get(vaddr);
1019   size_t i;
1020   for (i = 0; i < ARRAY_SIZE(ht_bin->vaddr); i++) {
1021     if (ht_bin->vaddr[i] == vaddr)
1022       if (doesnt_expire_soon((u_char *)ht_bin->tcaddr[i] - MAX_OUTPUT_BLOCK_SIZE))
1023         if (isclean(ht_bin->tcaddr[i]))
1024           return ht_bin->tcaddr[i];
1025   }
1026   u_int page=get_page(vaddr);
1027   struct ll_entry *head;
1028   head=jump_in[page];
1029   while (head != NULL) {
1030     if (head->vaddr == vaddr) {
1031       if (doesnt_expire_soon(head->addr)) {
1032         // Update existing entry with current address
1033         if (ht_bin->vaddr[0] == vaddr) {
1034           ht_bin->tcaddr[0] = head->addr;
1035           return head->addr;
1036         }
1037         if (ht_bin->vaddr[1] == vaddr) {
1038           ht_bin->tcaddr[1] = head->addr;
1039           return head->addr;
1040         }
1041         // Insert into hash table with low priority.
1042         // Don't evict existing entries, as they are probably
1043         // addresses that are being accessed frequently.
1044         if (ht_bin->vaddr[0] == -1) {
1045           ht_bin->vaddr[0] = vaddr;
1046           ht_bin->tcaddr[0] = head->addr;
1047         }
1048         else if (ht_bin->vaddr[1] == -1) {
1049           ht_bin->vaddr[1] = vaddr;
1050           ht_bin->tcaddr[1] = head->addr;
1051         }
1052         return head->addr;
1053       }
1054     }
1055     head=head->next;
1056   }
1057   return 0;
1058 }
1059
1060 void remove_hash(int vaddr)
1061 {
1062   //printf("remove hash: %x\n",vaddr);
1063   struct ht_entry *ht_bin = hash_table_get(vaddr);
1064   if (ht_bin->vaddr[1] == vaddr) {
1065     ht_bin->vaddr[1] = -1;
1066     ht_bin->tcaddr[1] = NULL;
1067   }
1068   if (ht_bin->vaddr[0] == vaddr) {
1069     ht_bin->vaddr[0] = ht_bin->vaddr[1];
1070     ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
1071     ht_bin->vaddr[1] = -1;
1072     ht_bin->tcaddr[1] = NULL;
1073   }
1074 }
1075
1076 static void ll_remove_matching_addrs(struct ll_entry **head,
1077   uintptr_t base_offs_s, int shift)
1078 {
1079   struct ll_entry *next;
1080   while(*head) {
1081     uintptr_t o1 = (u_char *)(*head)->addr - ndrc->translation_cache;
1082     uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
1083     if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s)
1084     {
1085       inv_debug("EXP: Remove pointer to %p (%x)\n",(*head)->addr,(*head)->vaddr);
1086       remove_hash((*head)->vaddr);
1087       next=(*head)->next;
1088       free(*head);
1089       *head=next;
1090     }
1091     else
1092     {
1093       head=&((*head)->next);
1094     }
1095   }
1096 }
1097
1098 // Remove all entries from linked list
1099 void ll_clear(struct ll_entry **head)
1100 {
1101   struct ll_entry *cur;
1102   struct ll_entry *next;
1103   if((cur=*head)) {
1104     *head=0;
1105     while(cur) {
1106       next=cur->next;
1107       free(cur);
1108       cur=next;
1109     }
1110   }
1111 }
1112
1113 // Dereference the pointers and remove if it matches
1114 static void ll_kill_pointers(struct ll_entry *head,
1115   uintptr_t base_offs_s, int shift)
1116 {
1117   while(head) {
1118     u_char *ptr = get_pointer(head->addr);
1119     uintptr_t o1 = ptr - ndrc->translation_cache;
1120     uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
1121     inv_debug("EXP: Lookup pointer to %p at %p (%x)\n",ptr,head->addr,head->vaddr);
1122     if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s)
1123     {
1124       inv_debug("EXP: Kill pointer at %p (%x)\n",head->addr,head->vaddr);
1125       void *host_addr=find_extjump_insn(head->addr);
1126       mark_clear_cache(host_addr);
1127       set_jump_target(host_addr, head->addr);
1128     }
1129     head=head->next;
1130   }
1131 }
1132
1133 // This is called when we write to a compiled block (see do_invstub)
1134 static void invalidate_page(u_int page)
1135 {
1136   struct ll_entry *head;
1137   struct ll_entry *next;
1138   head=jump_in[page];
1139   jump_in[page]=0;
1140   while(head!=NULL) {
1141     inv_debug("INVALIDATE: %x\n",head->vaddr);
1142     remove_hash(head->vaddr);
1143     next=head->next;
1144     free(head);
1145     head=next;
1146   }
1147   head=jump_out[page];
1148   jump_out[page]=0;
1149   while(head!=NULL) {
1150     inv_debug("INVALIDATE: kill pointer to %x (%p)\n",head->vaddr,head->addr);
1151     void *host_addr=find_extjump_insn(head->addr);
1152     mark_clear_cache(host_addr);
1153     set_jump_target(host_addr, head->addr); // point back to dyna_linker
1154     next=head->next;
1155     free(head);
1156     head=next;
1157   }
1158 }
1159
1160 static void invalidate_block_range(u_int block, u_int first, u_int last)
1161 {
1162   u_int page=get_page(block<<12);
1163   //printf("first=%d last=%d\n",first,last);
1164   invalidate_page(page);
1165   assert(first+5>page); // NB: this assumes MAXBLOCK<=4096 (4 pages)
1166   assert(last<page+5);
1167   // Invalidate the adjacent pages if a block crosses a 4K boundary
1168   while(first<page) {
1169     invalidate_page(first);
1170     first++;
1171   }
1172   for(first=page+1;first<last;first++) {
1173     invalidate_page(first);
1174   }
1175   do_clear_cache();
1176
1177   // Don't trap writes
1178   invalid_code[block]=1;
1179
1180   #ifdef USE_MINI_HT
1181   memset(mini_ht,-1,sizeof(mini_ht));
1182   #endif
1183 }
1184
1185 void invalidate_block(u_int block)
1186 {
1187   u_int page=get_page(block<<12);
1188   u_int vpage=get_vpage(block<<12);
1189   inv_debug("INVALIDATE: %x (%d)\n",block<<12,page);
1190   //inv_debug("invalid_code[block]=%d\n",invalid_code[block]);
1191   u_int first,last;
1192   first=last=page;
1193   struct ll_entry *head;
1194   head=jump_dirty[vpage];
1195   //printf("page=%d vpage=%d\n",page,vpage);
1196   while(head!=NULL) {
1197     if(vpage>2047||(head->vaddr>>12)==block) { // Ignore vaddr hash collision
1198       u_char *start, *end;
1199       get_bounds(head->addr, &start, &end);
1200       //printf("start: %p end: %p\n", start, end);
1201       if (page < 2048 && start >= rdram && end < rdram+RAM_SIZE) {
1202         if (((start-rdram)>>12) <= page && ((end-1-rdram)>>12) >= page) {
1203           if ((((start-rdram)>>12)&2047) < first) first = ((start-rdram)>>12)&2047;
1204           if ((((end-1-rdram)>>12)&2047) > last)  last = ((end-1-rdram)>>12)&2047;
1205         }
1206       }
1207     }
1208     head=head->next;
1209   }
1210   invalidate_block_range(block,first,last);
1211 }
1212
1213 void invalidate_addr(u_int addr)
1214 {
1215   //static int rhits;
1216   // this check is done by the caller
1217   //if (inv_code_start<=addr&&addr<=inv_code_end) { rhits++; return; }
1218   u_int page=get_vpage(addr);
1219   if(page<2048) { // RAM
1220     struct ll_entry *head;
1221     u_int addr_min=~0, addr_max=0;
1222     u_int mask=RAM_SIZE-1;
1223     u_int addr_main=0x80000000|(addr&mask);
1224     int pg1;
1225     inv_code_start=addr_main&~0xfff;
1226     inv_code_end=addr_main|0xfff;
1227     pg1=page;
1228     if (pg1>0) {
1229       // must check previous page too because of spans..
1230       pg1--;
1231       inv_code_start-=0x1000;
1232     }
1233     for(;pg1<=page;pg1++) {
1234       for(head=jump_dirty[pg1];head!=NULL;head=head->next) {
1235         u_char *start_h, *end_h;
1236         u_int start, end;
1237         get_bounds(head->addr, &start_h, &end_h);
1238         start = (uintptr_t)start_h - ram_offset;
1239         end = (uintptr_t)end_h - ram_offset;
1240         if(start<=addr_main&&addr_main<end) {
1241           if(start<addr_min) addr_min=start;
1242           if(end>addr_max) addr_max=end;
1243         }
1244         else if(addr_main<start) {
1245           if(start<inv_code_end)
1246             inv_code_end=start-1;
1247         }
1248         else {
1249           if(end>inv_code_start)
1250             inv_code_start=end;
1251         }
1252       }
1253     }
1254     if (addr_min!=~0) {
1255       inv_debug("INV ADDR: %08x hit %08x-%08x\n", addr, addr_min, addr_max);
1256       inv_code_start=inv_code_end=~0;
1257       invalidate_block_range(addr>>12,(addr_min&mask)>>12,(addr_max&mask)>>12);
1258       return;
1259     }
1260     else {
1261       inv_code_start=(addr&~mask)|(inv_code_start&mask);
1262       inv_code_end=(addr&~mask)|(inv_code_end&mask);
1263       inv_debug("INV ADDR: %08x miss, inv %08x-%08x, sk %d\n", addr, inv_code_start, inv_code_end, 0);
1264       return;
1265     }
1266   }
1267   invalidate_block(addr>>12);
1268 }
1269
1270 // This is called when loading a save state.
1271 // Anything could have changed, so invalidate everything.
1272 void invalidate_all_pages(void)
1273 {
1274   u_int page;
1275   for(page=0;page<4096;page++)
1276     invalidate_page(page);
1277   for(page=0;page<1048576;page++)
1278     if(!invalid_code[page]) {
1279       restore_candidate[(page&2047)>>3]|=1<<(page&7);
1280       restore_candidate[((page&2047)>>3)+256]|=1<<(page&7);
1281     }
1282   #ifdef USE_MINI_HT
1283   memset(mini_ht,-1,sizeof(mini_ht));
1284   #endif
1285   do_clear_cache();
1286 }
1287
1288 static void do_invstub(int n)
1289 {
1290   literal_pool(20);
1291   u_int reglist=stubs[n].a;
1292   set_jump_target(stubs[n].addr, out);
1293   save_regs(reglist);
1294   if(stubs[n].b!=0) emit_mov(stubs[n].b,0);
1295   emit_far_call(invalidate_addr);
1296   restore_regs(reglist);
1297   emit_jmp(stubs[n].retaddr); // return address
1298 }
1299
1300 // Add an entry to jump_out after making a link
1301 // src should point to code by emit_extjump2()
1302 void add_jump_out(u_int vaddr,void *src)
1303 {
1304   u_int page=get_page(vaddr);
1305   inv_debug("add_jump_out: %p -> %x (%d)\n",src,vaddr,page);
1306   check_extjump2(src);
1307   ll_add(jump_out+page,vaddr,src);
1308   //inv_debug("add_jump_out:  to %p\n",get_pointer(src));
1309 }
1310
1311 // If a code block was found to be unmodified (bit was set in
1312 // restore_candidate) and it remains unmodified (bit is clear
1313 // in invalid_code) then move the entries for that 4K page from
1314 // the dirty list to the clean list.
1315 void clean_blocks(u_int page)
1316 {
1317   struct ll_entry *head;
1318   inv_debug("INV: clean_blocks page=%d\n",page);
1319   head=jump_dirty[page];
1320   while(head!=NULL) {
1321     if(!invalid_code[head->vaddr>>12]) {
1322       // Don't restore blocks which are about to expire from the cache
1323       if (doesnt_expire_soon(head->addr)) {
1324         if(verify_dirty(head->addr)) {
1325           u_char *start, *end;
1326           //printf("Possibly Restore %x (%p)\n",head->vaddr, head->addr);
1327           u_int i;
1328           u_int inv=0;
1329           get_bounds(head->addr, &start, &end);
1330           if (start - rdram < RAM_SIZE) {
1331             for (i = (start-rdram+0x80000000)>>12; i <= (end-1-rdram+0x80000000)>>12; i++) {
1332               inv|=invalid_code[i];
1333             }
1334           }
1335           else if((signed int)head->vaddr>=(signed int)0x80000000+RAM_SIZE) {
1336             inv=1;
1337           }
1338           if(!inv) {
1339             void *clean_addr = get_clean_addr(head->addr);
1340             if (doesnt_expire_soon(clean_addr)) {
1341               u_int ppage=page;
1342               inv_debug("INV: Restored %x (%p/%p)\n",head->vaddr, head->addr, clean_addr);
1343               //printf("page=%x, addr=%x\n",page,head->vaddr);
1344               //assert(head->vaddr>>12==(page|0x80000));
1345               ll_add_flags(jump_in+ppage,head->vaddr,head->reg_sv_flags,clean_addr);
1346               struct ht_entry *ht_bin = hash_table_get(head->vaddr);
1347               if (ht_bin->vaddr[0] == head->vaddr)
1348                 ht_bin->tcaddr[0] = clean_addr; // Replace existing entry
1349               if (ht_bin->vaddr[1] == head->vaddr)
1350                 ht_bin->tcaddr[1] = clean_addr; // Replace existing entry
1351             }
1352           }
1353         }
1354       }
1355     }
1356     head=head->next;
1357   }
1358 }
1359
1360 /* Register allocation */
1361
1362 // Note: registers are allocated clean (unmodified state)
1363 // if you intend to modify the register, you must call dirty_reg().
1364 static void alloc_reg(struct regstat *cur,int i,signed char reg)
1365 {
1366   int r,hr;
1367   int preferred_reg = (reg&7);
1368   if(reg==CCREG) preferred_reg=HOST_CCREG;
1369   if(reg==PTEMP||reg==FTEMP) preferred_reg=12;
1370
1371   // Don't allocate unused registers
1372   if((cur->u>>reg)&1) return;
1373
1374   // see if it's already allocated
1375   for(hr=0;hr<HOST_REGS;hr++)
1376   {
1377     if(cur->regmap[hr]==reg) return;
1378   }
1379
1380   // Keep the same mapping if the register was already allocated in a loop
1381   preferred_reg = loop_reg(i,reg,preferred_reg);
1382
1383   // Try to allocate the preferred register
1384   if(cur->regmap[preferred_reg]==-1) {
1385     cur->regmap[preferred_reg]=reg;
1386     cur->dirty&=~(1<<preferred_reg);
1387     cur->isconst&=~(1<<preferred_reg);
1388     return;
1389   }
1390   r=cur->regmap[preferred_reg];
1391   assert(r < 64);
1392   if((cur->u>>r)&1) {
1393     cur->regmap[preferred_reg]=reg;
1394     cur->dirty&=~(1<<preferred_reg);
1395     cur->isconst&=~(1<<preferred_reg);
1396     return;
1397   }
1398
1399   // Clear any unneeded registers
1400   // We try to keep the mapping consistent, if possible, because it
1401   // makes branches easier (especially loops).  So we try to allocate
1402   // first (see above) before removing old mappings.  If this is not
1403   // possible then go ahead and clear out the registers that are no
1404   // longer needed.
1405   for(hr=0;hr<HOST_REGS;hr++)
1406   {
1407     r=cur->regmap[hr];
1408     if(r>=0) {
1409       assert(r < 64);
1410       if((cur->u>>r)&1) {cur->regmap[hr]=-1;break;}
1411     }
1412   }
1413   // Try to allocate any available register, but prefer
1414   // registers that have not been used recently.
1415   if(i>0) {
1416     for(hr=0;hr<HOST_REGS;hr++) {
1417       if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1418         if(regs[i-1].regmap[hr]!=dops[i-1].rs1&&regs[i-1].regmap[hr]!=dops[i-1].rs2&&regs[i-1].regmap[hr]!=dops[i-1].rt1&&regs[i-1].regmap[hr]!=dops[i-1].rt2) {
1419           cur->regmap[hr]=reg;
1420           cur->dirty&=~(1<<hr);
1421           cur->isconst&=~(1<<hr);
1422           return;
1423         }
1424       }
1425     }
1426   }
1427   // Try to allocate any available register
1428   for(hr=0;hr<HOST_REGS;hr++) {
1429     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1430       cur->regmap[hr]=reg;
1431       cur->dirty&=~(1<<hr);
1432       cur->isconst&=~(1<<hr);
1433       return;
1434     }
1435   }
1436
1437   // Ok, now we have to evict someone
1438   // Pick a register we hopefully won't need soon
1439   u_char hsn[MAXREG+1];
1440   memset(hsn,10,sizeof(hsn));
1441   int j;
1442   lsn(hsn,i,&preferred_reg);
1443   //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]);
1444   //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]);
1445   if(i>0) {
1446     // Don't evict the cycle count at entry points, otherwise the entry
1447     // stub will have to write it.
1448     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1449     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1450     for(j=10;j>=3;j--)
1451     {
1452       // Alloc preferred register if available
1453       if(hsn[r=cur->regmap[preferred_reg]&63]==j) {
1454         for(hr=0;hr<HOST_REGS;hr++) {
1455           // Evict both parts of a 64-bit register
1456           if((cur->regmap[hr]&63)==r) {
1457             cur->regmap[hr]=-1;
1458             cur->dirty&=~(1<<hr);
1459             cur->isconst&=~(1<<hr);
1460           }
1461         }
1462         cur->regmap[preferred_reg]=reg;
1463         return;
1464       }
1465       for(r=1;r<=MAXREG;r++)
1466       {
1467         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1468           for(hr=0;hr<HOST_REGS;hr++) {
1469             if(hr!=HOST_CCREG||j<hsn[CCREG]) {
1470               if(cur->regmap[hr]==r) {
1471                 cur->regmap[hr]=reg;
1472                 cur->dirty&=~(1<<hr);
1473                 cur->isconst&=~(1<<hr);
1474                 return;
1475               }
1476             }
1477           }
1478         }
1479       }
1480     }
1481   }
1482   for(j=10;j>=0;j--)
1483   {
1484     for(r=1;r<=MAXREG;r++)
1485     {
1486       if(hsn[r]==j) {
1487         for(hr=0;hr<HOST_REGS;hr++) {
1488           if(cur->regmap[hr]==r) {
1489             cur->regmap[hr]=reg;
1490             cur->dirty&=~(1<<hr);
1491             cur->isconst&=~(1<<hr);
1492             return;
1493           }
1494         }
1495       }
1496     }
1497   }
1498   SysPrintf("This shouldn't happen (alloc_reg)");abort();
1499 }
1500
1501 // Allocate a temporary register.  This is done without regard to
1502 // dirty status or whether the register we request is on the unneeded list
1503 // Note: This will only allocate one register, even if called multiple times
1504 static void alloc_reg_temp(struct regstat *cur,int i,signed char reg)
1505 {
1506   int r,hr;
1507   int preferred_reg = -1;
1508
1509   // see if it's already allocated
1510   for(hr=0;hr<HOST_REGS;hr++)
1511   {
1512     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==reg) return;
1513   }
1514
1515   // Try to allocate any available register
1516   for(hr=HOST_REGS-1;hr>=0;hr--) {
1517     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1518       cur->regmap[hr]=reg;
1519       cur->dirty&=~(1<<hr);
1520       cur->isconst&=~(1<<hr);
1521       return;
1522     }
1523   }
1524
1525   // Find an unneeded register
1526   for(hr=HOST_REGS-1;hr>=0;hr--)
1527   {
1528     r=cur->regmap[hr];
1529     if(r>=0) {
1530       assert(r < 64);
1531       if((cur->u>>r)&1) {
1532         if(i==0||((unneeded_reg[i-1]>>r)&1)) {
1533           cur->regmap[hr]=reg;
1534           cur->dirty&=~(1<<hr);
1535           cur->isconst&=~(1<<hr);
1536           return;
1537         }
1538       }
1539     }
1540   }
1541
1542   // Ok, now we have to evict someone
1543   // Pick a register we hopefully won't need soon
1544   // TODO: we might want to follow unconditional jumps here
1545   // TODO: get rid of dupe code and make this into a function
1546   u_char hsn[MAXREG+1];
1547   memset(hsn,10,sizeof(hsn));
1548   int j;
1549   lsn(hsn,i,&preferred_reg);
1550   //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]);
1551   if(i>0) {
1552     // Don't evict the cycle count at entry points, otherwise the entry
1553     // stub will have to write it.
1554     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1555     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1556     for(j=10;j>=3;j--)
1557     {
1558       for(r=1;r<=MAXREG;r++)
1559       {
1560         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1561           for(hr=0;hr<HOST_REGS;hr++) {
1562             if(hr!=HOST_CCREG||hsn[CCREG]>2) {
1563               if(cur->regmap[hr]==r) {
1564                 cur->regmap[hr]=reg;
1565                 cur->dirty&=~(1<<hr);
1566                 cur->isconst&=~(1<<hr);
1567                 return;
1568               }
1569             }
1570           }
1571         }
1572       }
1573     }
1574   }
1575   for(j=10;j>=0;j--)
1576   {
1577     for(r=1;r<=MAXREG;r++)
1578     {
1579       if(hsn[r]==j) {
1580         for(hr=0;hr<HOST_REGS;hr++) {
1581           if(cur->regmap[hr]==r) {
1582             cur->regmap[hr]=reg;
1583             cur->dirty&=~(1<<hr);
1584             cur->isconst&=~(1<<hr);
1585             return;
1586           }
1587         }
1588       }
1589     }
1590   }
1591   SysPrintf("This shouldn't happen");abort();
1592 }
1593
1594 static void mov_alloc(struct regstat *current,int i)
1595 {
1596   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) {
1597     // logically this is needed but just won't work, no idea why
1598     //alloc_cc(current,i); // for stalls
1599     //dirty_reg(current,CCREG);
1600   }
1601
1602   // Note: Don't need to actually alloc the source registers
1603   //alloc_reg(current,i,dops[i].rs1);
1604   alloc_reg(current,i,dops[i].rt1);
1605
1606   clear_const(current,dops[i].rs1);
1607   clear_const(current,dops[i].rt1);
1608   dirty_reg(current,dops[i].rt1);
1609 }
1610
1611 static void shiftimm_alloc(struct regstat *current,int i)
1612 {
1613   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
1614   {
1615     if(dops[i].rt1) {
1616       if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1617       else dops[i].lt1=dops[i].rs1;
1618       alloc_reg(current,i,dops[i].rt1);
1619       dirty_reg(current,dops[i].rt1);
1620       if(is_const(current,dops[i].rs1)) {
1621         int v=get_const(current,dops[i].rs1);
1622         if(dops[i].opcode2==0x00) set_const(current,dops[i].rt1,v<<imm[i]);
1623         if(dops[i].opcode2==0x02) set_const(current,dops[i].rt1,(u_int)v>>imm[i]);
1624         if(dops[i].opcode2==0x03) set_const(current,dops[i].rt1,v>>imm[i]);
1625       }
1626       else clear_const(current,dops[i].rt1);
1627     }
1628   }
1629   else
1630   {
1631     clear_const(current,dops[i].rs1);
1632     clear_const(current,dops[i].rt1);
1633   }
1634
1635   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
1636   {
1637     assert(0);
1638   }
1639   if(dops[i].opcode2==0x3c) // DSLL32
1640   {
1641     assert(0);
1642   }
1643   if(dops[i].opcode2==0x3e) // DSRL32
1644   {
1645     assert(0);
1646   }
1647   if(dops[i].opcode2==0x3f) // DSRA32
1648   {
1649     assert(0);
1650   }
1651 }
1652
1653 static void shift_alloc(struct regstat *current,int i)
1654 {
1655   if(dops[i].rt1) {
1656     if(dops[i].opcode2<=0x07) // SLLV/SRLV/SRAV
1657     {
1658       if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
1659       if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
1660       alloc_reg(current,i,dops[i].rt1);
1661       if(dops[i].rt1==dops[i].rs2) {
1662         alloc_reg_temp(current,i,-1);
1663         minimum_free_regs[i]=1;
1664       }
1665     } else { // DSLLV/DSRLV/DSRAV
1666       assert(0);
1667     }
1668     clear_const(current,dops[i].rs1);
1669     clear_const(current,dops[i].rs2);
1670     clear_const(current,dops[i].rt1);
1671     dirty_reg(current,dops[i].rt1);
1672   }
1673 }
1674
1675 static void alu_alloc(struct regstat *current,int i)
1676 {
1677   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
1678     if(dops[i].rt1) {
1679       if(dops[i].rs1&&dops[i].rs2) {
1680         alloc_reg(current,i,dops[i].rs1);
1681         alloc_reg(current,i,dops[i].rs2);
1682       }
1683       else {
1684         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1685         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1686       }
1687       alloc_reg(current,i,dops[i].rt1);
1688     }
1689   }
1690   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
1691     if(dops[i].rt1) {
1692       alloc_reg(current,i,dops[i].rs1);
1693       alloc_reg(current,i,dops[i].rs2);
1694       alloc_reg(current,i,dops[i].rt1);
1695     }
1696   }
1697   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
1698     if(dops[i].rt1) {
1699       if(dops[i].rs1&&dops[i].rs2) {
1700         alloc_reg(current,i,dops[i].rs1);
1701         alloc_reg(current,i,dops[i].rs2);
1702       }
1703       else
1704       {
1705         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1706         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1707       }
1708       alloc_reg(current,i,dops[i].rt1);
1709     }
1710   }
1711   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
1712     assert(0);
1713   }
1714   clear_const(current,dops[i].rs1);
1715   clear_const(current,dops[i].rs2);
1716   clear_const(current,dops[i].rt1);
1717   dirty_reg(current,dops[i].rt1);
1718 }
1719
1720 static void imm16_alloc(struct regstat *current,int i)
1721 {
1722   if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1723   else dops[i].lt1=dops[i].rs1;
1724   if(dops[i].rt1) alloc_reg(current,i,dops[i].rt1);
1725   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
1726     assert(0);
1727   }
1728   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
1729     clear_const(current,dops[i].rs1);
1730     clear_const(current,dops[i].rt1);
1731   }
1732   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
1733     if(is_const(current,dops[i].rs1)) {
1734       int v=get_const(current,dops[i].rs1);
1735       if(dops[i].opcode==0x0c) set_const(current,dops[i].rt1,v&imm[i]);
1736       if(dops[i].opcode==0x0d) set_const(current,dops[i].rt1,v|imm[i]);
1737       if(dops[i].opcode==0x0e) set_const(current,dops[i].rt1,v^imm[i]);
1738     }
1739     else clear_const(current,dops[i].rt1);
1740   }
1741   else if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
1742     if(is_const(current,dops[i].rs1)) {
1743       int v=get_const(current,dops[i].rs1);
1744       set_const(current,dops[i].rt1,v+imm[i]);
1745     }
1746     else clear_const(current,dops[i].rt1);
1747   }
1748   else {
1749     set_const(current,dops[i].rt1,imm[i]<<16); // LUI
1750   }
1751   dirty_reg(current,dops[i].rt1);
1752 }
1753
1754 static void load_alloc(struct regstat *current,int i)
1755 {
1756   clear_const(current,dops[i].rt1);
1757   //if(dops[i].rs1!=dops[i].rt1&&needed_again(dops[i].rs1,i)) clear_const(current,dops[i].rs1); // Does this help or hurt?
1758   if(!dops[i].rs1) current->u&=~1LL; // Allow allocating r0 if it's the source register
1759   if (needed_again(dops[i].rs1, i))
1760     alloc_reg(current, i, dops[i].rs1);
1761   if (ram_offset)
1762     alloc_reg(current, i, ROREG);
1763   if(dops[i].rt1&&!((current->u>>dops[i].rt1)&1)) {
1764     alloc_reg(current,i,dops[i].rt1);
1765     assert(get_reg(current->regmap,dops[i].rt1)>=0);
1766     if(dops[i].opcode==0x27||dops[i].opcode==0x37) // LWU/LD
1767     {
1768       assert(0);
1769     }
1770     else if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
1771     {
1772       assert(0);
1773     }
1774     dirty_reg(current,dops[i].rt1);
1775     // LWL/LWR need a temporary register for the old value
1776     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
1777     {
1778       alloc_reg(current,i,FTEMP);
1779       alloc_reg_temp(current,i,-1);
1780       minimum_free_regs[i]=1;
1781     }
1782   }
1783   else
1784   {
1785     // Load to r0 or unneeded register (dummy load)
1786     // but we still need a register to calculate the address
1787     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
1788     {
1789       alloc_reg(current,i,FTEMP); // LWL/LWR need another temporary
1790     }
1791     alloc_reg_temp(current,i,-1);
1792     minimum_free_regs[i]=1;
1793     if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
1794     {
1795       assert(0);
1796     }
1797   }
1798 }
1799
1800 void store_alloc(struct regstat *current,int i)
1801 {
1802   clear_const(current,dops[i].rs2);
1803   if(!(dops[i].rs2)) current->u&=~1LL; // Allow allocating r0 if necessary
1804   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1805   alloc_reg(current,i,dops[i].rs2);
1806   if(dops[i].opcode==0x2c||dops[i].opcode==0x2d||dops[i].opcode==0x3f) { // 64-bit SDL/SDR/SD
1807     assert(0);
1808   }
1809   if (ram_offset)
1810     alloc_reg(current, i, ROREG);
1811   #if defined(HOST_IMM8)
1812   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1813   alloc_reg(current, i, INVCP);
1814   #endif
1815   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) { // SWL/SWL/SDL/SDR
1816     alloc_reg(current,i,FTEMP);
1817   }
1818   // We need a temporary register for address generation
1819   alloc_reg_temp(current,i,-1);
1820   minimum_free_regs[i]=1;
1821 }
1822
1823 void c1ls_alloc(struct regstat *current,int i)
1824 {
1825   clear_const(current,dops[i].rt1);
1826   alloc_reg(current,i,CSREG); // Status
1827 }
1828
1829 void c2ls_alloc(struct regstat *current,int i)
1830 {
1831   clear_const(current,dops[i].rt1);
1832   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1833   alloc_reg(current,i,FTEMP);
1834   if (ram_offset)
1835     alloc_reg(current, i, ROREG);
1836   #if defined(HOST_IMM8)
1837   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1838   if (dops[i].opcode == 0x3a) // SWC2
1839     alloc_reg(current,i,INVCP);
1840   #endif
1841   // We need a temporary register for address generation
1842   alloc_reg_temp(current,i,-1);
1843   minimum_free_regs[i]=1;
1844 }
1845
1846 #ifndef multdiv_alloc
1847 void multdiv_alloc(struct regstat *current,int i)
1848 {
1849   //  case 0x18: MULT
1850   //  case 0x19: MULTU
1851   //  case 0x1A: DIV
1852   //  case 0x1B: DIVU
1853   //  case 0x1C: DMULT
1854   //  case 0x1D: DMULTU
1855   //  case 0x1E: DDIV
1856   //  case 0x1F: DDIVU
1857   clear_const(current,dops[i].rs1);
1858   clear_const(current,dops[i].rs2);
1859   alloc_cc(current,i); // for stalls
1860   if(dops[i].rs1&&dops[i].rs2)
1861   {
1862     if((dops[i].opcode2&4)==0) // 32-bit
1863     {
1864       current->u&=~(1LL<<HIREG);
1865       current->u&=~(1LL<<LOREG);
1866       alloc_reg(current,i,HIREG);
1867       alloc_reg(current,i,LOREG);
1868       alloc_reg(current,i,dops[i].rs1);
1869       alloc_reg(current,i,dops[i].rs2);
1870       dirty_reg(current,HIREG);
1871       dirty_reg(current,LOREG);
1872     }
1873     else // 64-bit
1874     {
1875       assert(0);
1876     }
1877   }
1878   else
1879   {
1880     // Multiply by zero is zero.
1881     // MIPS does not have a divide by zero exception.
1882     // The result is undefined, we return zero.
1883     alloc_reg(current,i,HIREG);
1884     alloc_reg(current,i,LOREG);
1885     dirty_reg(current,HIREG);
1886     dirty_reg(current,LOREG);
1887   }
1888 }
1889 #endif
1890
1891 void cop0_alloc(struct regstat *current,int i)
1892 {
1893   if(dops[i].opcode2==0) // MFC0
1894   {
1895     if(dops[i].rt1) {
1896       clear_const(current,dops[i].rt1);
1897       alloc_all(current,i);
1898       alloc_reg(current,i,dops[i].rt1);
1899       dirty_reg(current,dops[i].rt1);
1900     }
1901   }
1902   else if(dops[i].opcode2==4) // MTC0
1903   {
1904     if(dops[i].rs1){
1905       clear_const(current,dops[i].rs1);
1906       alloc_reg(current,i,dops[i].rs1);
1907       alloc_all(current,i);
1908     }
1909     else {
1910       alloc_all(current,i); // FIXME: Keep r0
1911       current->u&=~1LL;
1912       alloc_reg(current,i,0);
1913     }
1914   }
1915   else
1916   {
1917     // TLBR/TLBWI/TLBWR/TLBP/ERET
1918     assert(dops[i].opcode2==0x10);
1919     alloc_all(current,i);
1920   }
1921   minimum_free_regs[i]=HOST_REGS;
1922 }
1923
1924 static void cop2_alloc(struct regstat *current,int i)
1925 {
1926   if (dops[i].opcode2 < 3) // MFC2/CFC2
1927   {
1928     alloc_cc(current,i); // for stalls
1929     dirty_reg(current,CCREG);
1930     if(dops[i].rt1){
1931       clear_const(current,dops[i].rt1);
1932       alloc_reg(current,i,dops[i].rt1);
1933       dirty_reg(current,dops[i].rt1);
1934     }
1935   }
1936   else if (dops[i].opcode2 > 3) // MTC2/CTC2
1937   {
1938     if(dops[i].rs1){
1939       clear_const(current,dops[i].rs1);
1940       alloc_reg(current,i,dops[i].rs1);
1941     }
1942     else {
1943       current->u&=~1LL;
1944       alloc_reg(current,i,0);
1945     }
1946   }
1947   alloc_reg_temp(current,i,-1);
1948   minimum_free_regs[i]=1;
1949 }
1950
1951 void c2op_alloc(struct regstat *current,int i)
1952 {
1953   alloc_cc(current,i); // for stalls
1954   dirty_reg(current,CCREG);
1955   alloc_reg_temp(current,i,-1);
1956 }
1957
1958 void syscall_alloc(struct regstat *current,int i)
1959 {
1960   alloc_cc(current,i);
1961   dirty_reg(current,CCREG);
1962   alloc_all(current,i);
1963   minimum_free_regs[i]=HOST_REGS;
1964   current->isconst=0;
1965 }
1966
1967 void delayslot_alloc(struct regstat *current,int i)
1968 {
1969   switch(dops[i].itype) {
1970     case UJUMP:
1971     case CJUMP:
1972     case SJUMP:
1973     case RJUMP:
1974     case SYSCALL:
1975     case HLECALL:
1976     case SPAN:
1977       assem_debug("jump in the delay slot.  this shouldn't happen.\n");//abort();
1978       SysPrintf("Disabled speculative precompilation\n");
1979       stop_after_jal=1;
1980       break;
1981     case IMM16:
1982       imm16_alloc(current,i);
1983       break;
1984     case LOAD:
1985     case LOADLR:
1986       load_alloc(current,i);
1987       break;
1988     case STORE:
1989     case STORELR:
1990       store_alloc(current,i);
1991       break;
1992     case ALU:
1993       alu_alloc(current,i);
1994       break;
1995     case SHIFT:
1996       shift_alloc(current,i);
1997       break;
1998     case MULTDIV:
1999       multdiv_alloc(current,i);
2000       break;
2001     case SHIFTIMM:
2002       shiftimm_alloc(current,i);
2003       break;
2004     case MOV:
2005       mov_alloc(current,i);
2006       break;
2007     case COP0:
2008       cop0_alloc(current,i);
2009       break;
2010     case COP1:
2011       break;
2012     case COP2:
2013       cop2_alloc(current,i);
2014       break;
2015     case C1LS:
2016       c1ls_alloc(current,i);
2017       break;
2018     case C2LS:
2019       c2ls_alloc(current,i);
2020       break;
2021     case C2OP:
2022       c2op_alloc(current,i);
2023       break;
2024   }
2025 }
2026
2027 // Special case where a branch and delay slot span two pages in virtual memory
2028 static void pagespan_alloc(struct regstat *current,int i)
2029 {
2030   current->isconst=0;
2031   current->wasconst=0;
2032   regs[i].wasconst=0;
2033   minimum_free_regs[i]=HOST_REGS;
2034   alloc_all(current,i);
2035   alloc_cc(current,i);
2036   dirty_reg(current,CCREG);
2037   if(dops[i].opcode==3) // JAL
2038   {
2039     alloc_reg(current,i,31);
2040     dirty_reg(current,31);
2041   }
2042   if(dops[i].opcode==0&&(dops[i].opcode2&0x3E)==8) // JR/JALR
2043   {
2044     alloc_reg(current,i,dops[i].rs1);
2045     if (dops[i].rt1!=0) {
2046       alloc_reg(current,i,dops[i].rt1);
2047       dirty_reg(current,dops[i].rt1);
2048     }
2049   }
2050   if((dops[i].opcode&0x2E)==4) // BEQ/BNE/BEQL/BNEL
2051   {
2052     if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
2053     if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
2054   }
2055   else
2056   if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ/BLEZL/BGTZL
2057   {
2058     if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
2059   }
2060   //else ...
2061 }
2062
2063 static void add_stub(enum stub_type type, void *addr, void *retaddr,
2064   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e)
2065 {
2066   assert(stubcount < ARRAY_SIZE(stubs));
2067   stubs[stubcount].type = type;
2068   stubs[stubcount].addr = addr;
2069   stubs[stubcount].retaddr = retaddr;
2070   stubs[stubcount].a = a;
2071   stubs[stubcount].b = b;
2072   stubs[stubcount].c = c;
2073   stubs[stubcount].d = d;
2074   stubs[stubcount].e = e;
2075   stubcount++;
2076 }
2077
2078 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
2079   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist)
2080 {
2081   add_stub(type, addr, retaddr, i, addr_reg, (uintptr_t)i_regs, ccadj, reglist);
2082 }
2083
2084 // Write out a single register
2085 static void wb_register(signed char r,signed char regmap[],uint64_t dirty)
2086 {
2087   int hr;
2088   for(hr=0;hr<HOST_REGS;hr++) {
2089     if(hr!=EXCLUDE_REG) {
2090       if((regmap[hr]&63)==r) {
2091         if((dirty>>hr)&1) {
2092           assert(regmap[hr]<64);
2093           emit_storereg(r,hr);
2094         }
2095       }
2096     }
2097   }
2098 }
2099
2100 static void wb_valid(signed char pre[],signed char entry[],u_int dirty_pre,u_int dirty,uint64_t u)
2101 {
2102   //if(dirty_pre==dirty) return;
2103   int hr,reg;
2104   for(hr=0;hr<HOST_REGS;hr++) {
2105     if(hr!=EXCLUDE_REG) {
2106       reg=pre[hr];
2107       if(((~u)>>(reg&63))&1) {
2108         if(reg>0) {
2109           if(((dirty_pre&~dirty)>>hr)&1) {
2110             if(reg>0&&reg<34) {
2111               emit_storereg(reg,hr);
2112             }
2113             else if(reg>=64) {
2114               assert(0);
2115             }
2116           }
2117         }
2118       }
2119     }
2120   }
2121 }
2122
2123 // trashes r2
2124 static void pass_args(int a0, int a1)
2125 {
2126   if(a0==1&&a1==0) {
2127     // must swap
2128     emit_mov(a0,2); emit_mov(a1,1); emit_mov(2,0);
2129   }
2130   else if(a0!=0&&a1==0) {
2131     emit_mov(a1,1);
2132     if (a0>=0) emit_mov(a0,0);
2133   }
2134   else {
2135     if(a0>=0&&a0!=0) emit_mov(a0,0);
2136     if(a1>=0&&a1!=1) emit_mov(a1,1);
2137   }
2138 }
2139
2140 static void alu_assemble(int i,struct regstat *i_regs)
2141 {
2142   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
2143     if(dops[i].rt1) {
2144       signed char s1,s2,t;
2145       t=get_reg(i_regs->regmap,dops[i].rt1);
2146       if(t>=0) {
2147         s1=get_reg(i_regs->regmap,dops[i].rs1);
2148         s2=get_reg(i_regs->regmap,dops[i].rs2);
2149         if(dops[i].rs1&&dops[i].rs2) {
2150           assert(s1>=0);
2151           assert(s2>=0);
2152           if(dops[i].opcode2&2) emit_sub(s1,s2,t);
2153           else emit_add(s1,s2,t);
2154         }
2155         else if(dops[i].rs1) {
2156           if(s1>=0) emit_mov(s1,t);
2157           else emit_loadreg(dops[i].rs1,t);
2158         }
2159         else if(dops[i].rs2) {
2160           if(s2>=0) {
2161             if(dops[i].opcode2&2) emit_neg(s2,t);
2162             else emit_mov(s2,t);
2163           }
2164           else {
2165             emit_loadreg(dops[i].rs2,t);
2166             if(dops[i].opcode2&2) emit_neg(t,t);
2167           }
2168         }
2169         else emit_zeroreg(t);
2170       }
2171     }
2172   }
2173   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
2174     assert(0);
2175   }
2176   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
2177     if(dops[i].rt1) {
2178       signed char s1l,s2l,t;
2179       {
2180         t=get_reg(i_regs->regmap,dops[i].rt1);
2181         //assert(t>=0);
2182         if(t>=0) {
2183           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2184           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2185           if(dops[i].rs2==0) // rx<r0
2186           {
2187             if(dops[i].opcode2==0x2a&&dops[i].rs1!=0) { // SLT
2188               assert(s1l>=0);
2189               emit_shrimm(s1l,31,t);
2190             }
2191             else // SLTU (unsigned can not be less than zero, 0<0)
2192               emit_zeroreg(t);
2193           }
2194           else if(dops[i].rs1==0) // r0<rx
2195           {
2196             assert(s2l>=0);
2197             if(dops[i].opcode2==0x2a) // SLT
2198               emit_set_gz32(s2l,t);
2199             else // SLTU (set if not zero)
2200               emit_set_nz32(s2l,t);
2201           }
2202           else{
2203             assert(s1l>=0);assert(s2l>=0);
2204             if(dops[i].opcode2==0x2a) // SLT
2205               emit_set_if_less32(s1l,s2l,t);
2206             else // SLTU
2207               emit_set_if_carry32(s1l,s2l,t);
2208           }
2209         }
2210       }
2211     }
2212   }
2213   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
2214     if(dops[i].rt1) {
2215       signed char s1l,s2l,tl;
2216       tl=get_reg(i_regs->regmap,dops[i].rt1);
2217       {
2218         if(tl>=0) {
2219           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2220           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2221           if(dops[i].rs1&&dops[i].rs2) {
2222             assert(s1l>=0);
2223             assert(s2l>=0);
2224             if(dops[i].opcode2==0x24) { // AND
2225               emit_and(s1l,s2l,tl);
2226             } else
2227             if(dops[i].opcode2==0x25) { // OR
2228               emit_or(s1l,s2l,tl);
2229             } else
2230             if(dops[i].opcode2==0x26) { // XOR
2231               emit_xor(s1l,s2l,tl);
2232             } else
2233             if(dops[i].opcode2==0x27) { // NOR
2234               emit_or(s1l,s2l,tl);
2235               emit_not(tl,tl);
2236             }
2237           }
2238           else
2239           {
2240             if(dops[i].opcode2==0x24) { // AND
2241               emit_zeroreg(tl);
2242             } else
2243             if(dops[i].opcode2==0x25||dops[i].opcode2==0x26) { // OR/XOR
2244               if(dops[i].rs1){
2245                 if(s1l>=0) emit_mov(s1l,tl);
2246                 else emit_loadreg(dops[i].rs1,tl); // CHECK: regmap_entry?
2247               }
2248               else
2249               if(dops[i].rs2){
2250                 if(s2l>=0) emit_mov(s2l,tl);
2251                 else emit_loadreg(dops[i].rs2,tl); // CHECK: regmap_entry?
2252               }
2253               else emit_zeroreg(tl);
2254             } else
2255             if(dops[i].opcode2==0x27) { // NOR
2256               if(dops[i].rs1){
2257                 if(s1l>=0) emit_not(s1l,tl);
2258                 else {
2259                   emit_loadreg(dops[i].rs1,tl);
2260                   emit_not(tl,tl);
2261                 }
2262               }
2263               else
2264               if(dops[i].rs2){
2265                 if(s2l>=0) emit_not(s2l,tl);
2266                 else {
2267                   emit_loadreg(dops[i].rs2,tl);
2268                   emit_not(tl,tl);
2269                 }
2270               }
2271               else emit_movimm(-1,tl);
2272             }
2273           }
2274         }
2275       }
2276     }
2277   }
2278 }
2279
2280 void imm16_assemble(int i,struct regstat *i_regs)
2281 {
2282   if (dops[i].opcode==0x0f) { // LUI
2283     if(dops[i].rt1) {
2284       signed char t;
2285       t=get_reg(i_regs->regmap,dops[i].rt1);
2286       //assert(t>=0);
2287       if(t>=0) {
2288         if(!((i_regs->isconst>>t)&1))
2289           emit_movimm(imm[i]<<16,t);
2290       }
2291     }
2292   }
2293   if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
2294     if(dops[i].rt1) {
2295       signed char s,t;
2296       t=get_reg(i_regs->regmap,dops[i].rt1);
2297       s=get_reg(i_regs->regmap,dops[i].rs1);
2298       if(dops[i].rs1) {
2299         //assert(t>=0);
2300         //assert(s>=0);
2301         if(t>=0) {
2302           if(!((i_regs->isconst>>t)&1)) {
2303             if(s<0) {
2304               if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2305               emit_addimm(t,imm[i],t);
2306             }else{
2307               if(!((i_regs->wasconst>>s)&1))
2308                 emit_addimm(s,imm[i],t);
2309               else
2310                 emit_movimm(constmap[i][s]+imm[i],t);
2311             }
2312           }
2313         }
2314       } else {
2315         if(t>=0) {
2316           if(!((i_regs->isconst>>t)&1))
2317             emit_movimm(imm[i],t);
2318         }
2319       }
2320     }
2321   }
2322   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
2323     if(dops[i].rt1) {
2324       signed char sl,tl;
2325       tl=get_reg(i_regs->regmap,dops[i].rt1);
2326       sl=get_reg(i_regs->regmap,dops[i].rs1);
2327       if(tl>=0) {
2328         if(dops[i].rs1) {
2329           assert(sl>=0);
2330           emit_addimm(sl,imm[i],tl);
2331         } else {
2332           emit_movimm(imm[i],tl);
2333         }
2334       }
2335     }
2336   }
2337   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
2338     if(dops[i].rt1) {
2339       //assert(dops[i].rs1!=0); // r0 might be valid, but it's probably a bug
2340       signed char sl,t;
2341       t=get_reg(i_regs->regmap,dops[i].rt1);
2342       sl=get_reg(i_regs->regmap,dops[i].rs1);
2343       //assert(t>=0);
2344       if(t>=0) {
2345         if(dops[i].rs1>0) {
2346             if(dops[i].opcode==0x0a) { // SLTI
2347               if(sl<0) {
2348                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2349                 emit_slti32(t,imm[i],t);
2350               }else{
2351                 emit_slti32(sl,imm[i],t);
2352               }
2353             }
2354             else { // SLTIU
2355               if(sl<0) {
2356                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2357                 emit_sltiu32(t,imm[i],t);
2358               }else{
2359                 emit_sltiu32(sl,imm[i],t);
2360               }
2361             }
2362         }else{
2363           // SLTI(U) with r0 is just stupid,
2364           // nonetheless examples can be found
2365           if(dops[i].opcode==0x0a) // SLTI
2366             if(0<imm[i]) emit_movimm(1,t);
2367             else emit_zeroreg(t);
2368           else // SLTIU
2369           {
2370             if(imm[i]) emit_movimm(1,t);
2371             else emit_zeroreg(t);
2372           }
2373         }
2374       }
2375     }
2376   }
2377   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
2378     if(dops[i].rt1) {
2379       signed char sl,tl;
2380       tl=get_reg(i_regs->regmap,dops[i].rt1);
2381       sl=get_reg(i_regs->regmap,dops[i].rs1);
2382       if(tl>=0 && !((i_regs->isconst>>tl)&1)) {
2383         if(dops[i].opcode==0x0c) //ANDI
2384         {
2385           if(dops[i].rs1) {
2386             if(sl<0) {
2387               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2388               emit_andimm(tl,imm[i],tl);
2389             }else{
2390               if(!((i_regs->wasconst>>sl)&1))
2391                 emit_andimm(sl,imm[i],tl);
2392               else
2393                 emit_movimm(constmap[i][sl]&imm[i],tl);
2394             }
2395           }
2396           else
2397             emit_zeroreg(tl);
2398         }
2399         else
2400         {
2401           if(dops[i].rs1) {
2402             if(sl<0) {
2403               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2404             }
2405             if(dops[i].opcode==0x0d) { // ORI
2406               if(sl<0) {
2407                 emit_orimm(tl,imm[i],tl);
2408               }else{
2409                 if(!((i_regs->wasconst>>sl)&1))
2410                   emit_orimm(sl,imm[i],tl);
2411                 else
2412                   emit_movimm(constmap[i][sl]|imm[i],tl);
2413               }
2414             }
2415             if(dops[i].opcode==0x0e) { // XORI
2416               if(sl<0) {
2417                 emit_xorimm(tl,imm[i],tl);
2418               }else{
2419                 if(!((i_regs->wasconst>>sl)&1))
2420                   emit_xorimm(sl,imm[i],tl);
2421                 else
2422                   emit_movimm(constmap[i][sl]^imm[i],tl);
2423               }
2424             }
2425           }
2426           else {
2427             emit_movimm(imm[i],tl);
2428           }
2429         }
2430       }
2431     }
2432   }
2433 }
2434
2435 void shiftimm_assemble(int i,struct regstat *i_regs)
2436 {
2437   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
2438   {
2439     if(dops[i].rt1) {
2440       signed char s,t;
2441       t=get_reg(i_regs->regmap,dops[i].rt1);
2442       s=get_reg(i_regs->regmap,dops[i].rs1);
2443       //assert(t>=0);
2444       if(t>=0&&!((i_regs->isconst>>t)&1)){
2445         if(dops[i].rs1==0)
2446         {
2447           emit_zeroreg(t);
2448         }
2449         else
2450         {
2451           if(s<0&&i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2452           if(imm[i]) {
2453             if(dops[i].opcode2==0) // SLL
2454             {
2455               emit_shlimm(s<0?t:s,imm[i],t);
2456             }
2457             if(dops[i].opcode2==2) // SRL
2458             {
2459               emit_shrimm(s<0?t:s,imm[i],t);
2460             }
2461             if(dops[i].opcode2==3) // SRA
2462             {
2463               emit_sarimm(s<0?t:s,imm[i],t);
2464             }
2465           }else{
2466             // Shift by zero
2467             if(s>=0 && s!=t) emit_mov(s,t);
2468           }
2469         }
2470       }
2471       //emit_storereg(dops[i].rt1,t); //DEBUG
2472     }
2473   }
2474   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
2475   {
2476     assert(0);
2477   }
2478   if(dops[i].opcode2==0x3c) // DSLL32
2479   {
2480     assert(0);
2481   }
2482   if(dops[i].opcode2==0x3e) // DSRL32
2483   {
2484     assert(0);
2485   }
2486   if(dops[i].opcode2==0x3f) // DSRA32
2487   {
2488     assert(0);
2489   }
2490 }
2491
2492 #ifndef shift_assemble
2493 static void shift_assemble(int i,struct regstat *i_regs)
2494 {
2495   signed char s,t,shift;
2496   if (dops[i].rt1 == 0)
2497     return;
2498   assert(dops[i].opcode2<=0x07); // SLLV/SRLV/SRAV
2499   t = get_reg(i_regs->regmap, dops[i].rt1);
2500   s = get_reg(i_regs->regmap, dops[i].rs1);
2501   shift = get_reg(i_regs->regmap, dops[i].rs2);
2502   if (t < 0)
2503     return;
2504
2505   if(dops[i].rs1==0)
2506     emit_zeroreg(t);
2507   else if(dops[i].rs2==0) {
2508     assert(s>=0);
2509     if(s!=t) emit_mov(s,t);
2510   }
2511   else {
2512     host_tempreg_acquire();
2513     emit_andimm(shift,31,HOST_TEMPREG);
2514     switch(dops[i].opcode2) {
2515     case 4: // SLLV
2516       emit_shl(s,HOST_TEMPREG,t);
2517       break;
2518     case 6: // SRLV
2519       emit_shr(s,HOST_TEMPREG,t);
2520       break;
2521     case 7: // SRAV
2522       emit_sar(s,HOST_TEMPREG,t);
2523       break;
2524     default:
2525       assert(0);
2526     }
2527     host_tempreg_release();
2528   }
2529 }
2530
2531 #endif
2532
2533 enum {
2534   MTYPE_8000 = 0,
2535   MTYPE_8020,
2536   MTYPE_0000,
2537   MTYPE_A000,
2538   MTYPE_1F80,
2539 };
2540
2541 static int get_ptr_mem_type(u_int a)
2542 {
2543   if(a < 0x00200000) {
2544     if(a<0x1000&&((start>>20)==0xbfc||(start>>24)==0xa0))
2545       // return wrong, must use memhandler for BIOS self-test to pass
2546       // 007 does similar stuff from a00 mirror, weird stuff
2547       return MTYPE_8000;
2548     return MTYPE_0000;
2549   }
2550   if(0x1f800000 <= a && a < 0x1f801000)
2551     return MTYPE_1F80;
2552   if(0x80200000 <= a && a < 0x80800000)
2553     return MTYPE_8020;
2554   if(0xa0000000 <= a && a < 0xa0200000)
2555     return MTYPE_A000;
2556   return MTYPE_8000;
2557 }
2558
2559 static int get_ro_reg(const struct regstat *i_regs, int host_tempreg_free)
2560 {
2561   int r = get_reg(i_regs->regmap, ROREG);
2562   if (r < 0 && host_tempreg_free) {
2563     host_tempreg_acquire();
2564     emit_loadreg(ROREG, r = HOST_TEMPREG);
2565   }
2566   if (r < 0)
2567     abort();
2568   return r;
2569 }
2570
2571 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
2572   int addr, int *offset_reg, int *addr_reg_override)
2573 {
2574   void *jaddr = NULL;
2575   int type = 0;
2576   int mr = dops[i].rs1;
2577   *offset_reg = -1;
2578   if(((smrv_strong|smrv_weak)>>mr)&1) {
2579     type=get_ptr_mem_type(smrv[mr]);
2580     //printf("set %08x @%08x r%d %d\n", smrv[mr], start+i*4, mr, type);
2581   }
2582   else {
2583     // use the mirror we are running on
2584     type=get_ptr_mem_type(start);
2585     //printf("set nospec   @%08x r%d %d\n", start+i*4, mr, type);
2586   }
2587
2588   if(type==MTYPE_8020) { // RAM 80200000+ mirror
2589     host_tempreg_acquire();
2590     emit_andimm(addr,~0x00e00000,HOST_TEMPREG);
2591     addr=*addr_reg_override=HOST_TEMPREG;
2592     type=0;
2593   }
2594   else if(type==MTYPE_0000) { // RAM 0 mirror
2595     host_tempreg_acquire();
2596     emit_orimm(addr,0x80000000,HOST_TEMPREG);
2597     addr=*addr_reg_override=HOST_TEMPREG;
2598     type=0;
2599   }
2600   else if(type==MTYPE_A000) { // RAM A mirror
2601     host_tempreg_acquire();
2602     emit_andimm(addr,~0x20000000,HOST_TEMPREG);
2603     addr=*addr_reg_override=HOST_TEMPREG;
2604     type=0;
2605   }
2606   else if(type==MTYPE_1F80) { // scratchpad
2607     if (psxH == (void *)0x1f800000) {
2608       host_tempreg_acquire();
2609       emit_xorimm(addr,0x1f800000,HOST_TEMPREG);
2610       emit_cmpimm(HOST_TEMPREG,0x1000);
2611       host_tempreg_release();
2612       jaddr=out;
2613       emit_jc(0);
2614     }
2615     else {
2616       // do the usual RAM check, jump will go to the right handler
2617       type=0;
2618     }
2619   }
2620
2621   if (type == 0) // need ram check
2622   {
2623     emit_cmpimm(addr,RAM_SIZE);
2624     jaddr = out;
2625     #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
2626     // Hint to branch predictor that the branch is unlikely to be taken
2627     if (dops[i].rs1 >= 28)
2628       emit_jno_unlikely(0);
2629     else
2630     #endif
2631       emit_jno(0);
2632     if (ram_offset != 0)
2633       *offset_reg = get_ro_reg(i_regs, 0);
2634   }
2635
2636   return jaddr;
2637 }
2638
2639 // return memhandler, or get directly accessable address and return 0
2640 static void *get_direct_memhandler(void *table, u_int addr,
2641   enum stub_type type, uintptr_t *addr_host)
2642 {
2643   uintptr_t msb = 1ull << (sizeof(uintptr_t)*8 - 1);
2644   uintptr_t l1, l2 = 0;
2645   l1 = ((uintptr_t *)table)[addr>>12];
2646   if (!(l1 & msb)) {
2647     uintptr_t v = l1 << 1;
2648     *addr_host = v + addr;
2649     return NULL;
2650   }
2651   else {
2652     l1 <<= 1;
2653     if (type == LOADB_STUB || type == LOADBU_STUB || type == STOREB_STUB)
2654       l2 = ((uintptr_t *)l1)[0x1000/4 + 0x1000/2 + (addr&0xfff)];
2655     else if (type == LOADH_STUB || type == LOADHU_STUB || type == STOREH_STUB)
2656       l2 = ((uintptr_t *)l1)[0x1000/4 + (addr&0xfff)/2];
2657     else
2658       l2 = ((uintptr_t *)l1)[(addr&0xfff)/4];
2659     if (!(l2 & msb)) {
2660       uintptr_t v = l2 << 1;
2661       *addr_host = v + (addr&0xfff);
2662       return NULL;
2663     }
2664     return (void *)(l2 << 1);
2665   }
2666 }
2667
2668 static u_int get_host_reglist(const signed char *regmap)
2669 {
2670   u_int reglist = 0, hr;
2671   for (hr = 0; hr < HOST_REGS; hr++) {
2672     if (hr != EXCLUDE_REG && regmap[hr] >= 0)
2673       reglist |= 1 << hr;
2674   }
2675   return reglist;
2676 }
2677
2678 static u_int reglist_exclude(u_int reglist, int r1, int r2)
2679 {
2680   if (r1 >= 0)
2681     reglist &= ~(1u << r1);
2682   if (r2 >= 0)
2683     reglist &= ~(1u << r2);
2684   return reglist;
2685 }
2686
2687 // find a temp caller-saved register not in reglist (so assumed to be free)
2688 static int reglist_find_free(u_int reglist)
2689 {
2690   u_int free_regs = ~reglist & CALLER_SAVE_REGS;
2691   if (free_regs == 0)
2692     return -1;
2693   return __builtin_ctz(free_regs);
2694 }
2695
2696 static void do_load_word(int a, int rt, int offset_reg)
2697 {
2698   if (offset_reg >= 0)
2699     emit_ldr_dualindexed(offset_reg, a, rt);
2700   else
2701     emit_readword_indexed(0, a, rt);
2702 }
2703
2704 static void do_store_word(int a, int ofs, int rt, int offset_reg, int preseve_a)
2705 {
2706   if (offset_reg < 0) {
2707     emit_writeword_indexed(rt, ofs, a);
2708     return;
2709   }
2710   if (ofs != 0)
2711     emit_addimm(a, ofs, a);
2712   emit_str_dualindexed(offset_reg, a, rt);
2713   if (ofs != 0 && preseve_a)
2714     emit_addimm(a, -ofs, a);
2715 }
2716
2717 static void do_store_hword(int a, int ofs, int rt, int offset_reg, int preseve_a)
2718 {
2719   if (offset_reg < 0) {
2720     emit_writehword_indexed(rt, ofs, a);
2721     return;
2722   }
2723   if (ofs != 0)
2724     emit_addimm(a, ofs, a);
2725   emit_strh_dualindexed(offset_reg, a, rt);
2726   if (ofs != 0 && preseve_a)
2727     emit_addimm(a, -ofs, a);
2728 }
2729
2730 static void do_store_byte(int a, int rt, int offset_reg)
2731 {
2732   if (offset_reg >= 0)
2733     emit_strb_dualindexed(offset_reg, a, rt);
2734   else
2735     emit_writebyte_indexed(rt, 0, a);
2736 }
2737
2738 static void load_assemble(int i, const struct regstat *i_regs)
2739 {
2740   int s,tl,addr;
2741   int offset;
2742   void *jaddr=0;
2743   int memtarget=0,c=0;
2744   int offset_reg = -1;
2745   int fastio_reg_override = -1;
2746   u_int reglist=get_host_reglist(i_regs->regmap);
2747   tl=get_reg(i_regs->regmap,dops[i].rt1);
2748   s=get_reg(i_regs->regmap,dops[i].rs1);
2749   offset=imm[i];
2750   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2751   if(s>=0) {
2752     c=(i_regs->wasconst>>s)&1;
2753     if (c) {
2754       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2755     }
2756   }
2757   //printf("load_assemble: c=%d\n",c);
2758   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2759   // FIXME: Even if the load is a NOP, we should check for pagefaults...
2760   if((tl<0&&(!c||(((u_int)constmap[i][s]+offset)>>16)==0x1f80))
2761     ||dops[i].rt1==0) {
2762       // could be FIFO, must perform the read
2763       // ||dummy read
2764       assem_debug("(forced read)\n");
2765       tl=get_reg(i_regs->regmap,-1);
2766       assert(tl>=0);
2767   }
2768   if(offset||s<0||c) addr=tl;
2769   else addr=s;
2770   //if(tl<0) tl=get_reg(i_regs->regmap,-1);
2771  if(tl>=0) {
2772   //printf("load_assemble: c=%d\n",c);
2773   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2774   assert(tl>=0); // Even if the load is a NOP, we must check for pagefaults and I/O
2775   reglist&=~(1<<tl);
2776   if(!c) {
2777     #ifdef R29_HACK
2778     // Strmnnrmn's speed hack
2779     if(dops[i].rs1!=29||start<0x80001000||start>=0x80000000+RAM_SIZE)
2780     #endif
2781     {
2782       jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
2783                 &offset_reg, &fastio_reg_override);
2784     }
2785   }
2786   else if (ram_offset && memtarget) {
2787     offset_reg = get_ro_reg(i_regs, 0);
2788   }
2789   int dummy=(dops[i].rt1==0)||(tl!=get_reg(i_regs->regmap,dops[i].rt1)); // ignore loads to r0 and unneeded reg
2790   switch (dops[i].opcode) {
2791   case 0x20: // LB
2792     if(!c||memtarget) {
2793       if(!dummy) {
2794         int a = tl;
2795         if (!c) a = addr;
2796         if (fastio_reg_override >= 0)
2797           a = fastio_reg_override;
2798
2799         if (offset_reg >= 0)
2800           emit_ldrsb_dualindexed(offset_reg, a, tl);
2801         else
2802           emit_movsbl_indexed(0, a, tl);
2803       }
2804       if(jaddr)
2805         add_stub_r(LOADB_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2806     }
2807     else
2808       inline_readstub(LOADB_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj[i],reglist);
2809     break;
2810   case 0x21: // LH
2811     if(!c||memtarget) {
2812       if(!dummy) {
2813         int a = tl;
2814         if (!c) a = addr;
2815         if (fastio_reg_override >= 0)
2816           a = fastio_reg_override;
2817         if (offset_reg >= 0)
2818           emit_ldrsh_dualindexed(offset_reg, a, tl);
2819         else
2820           emit_movswl_indexed(0, a, tl);
2821       }
2822       if(jaddr)
2823         add_stub_r(LOADH_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2824     }
2825     else
2826       inline_readstub(LOADH_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj[i],reglist);
2827     break;
2828   case 0x23: // LW
2829     if(!c||memtarget) {
2830       if(!dummy) {
2831         int a = addr;
2832         if (fastio_reg_override >= 0)
2833           a = fastio_reg_override;
2834         do_load_word(a, tl, offset_reg);
2835       }
2836       if(jaddr)
2837         add_stub_r(LOADW_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2838     }
2839     else
2840       inline_readstub(LOADW_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj[i],reglist);
2841     break;
2842   case 0x24: // LBU
2843     if(!c||memtarget) {
2844       if(!dummy) {
2845         int a = tl;
2846         if (!c) a = addr;
2847         if (fastio_reg_override >= 0)
2848           a = fastio_reg_override;
2849
2850         if (offset_reg >= 0)
2851           emit_ldrb_dualindexed(offset_reg, a, tl);
2852         else
2853           emit_movzbl_indexed(0, a, tl);
2854       }
2855       if(jaddr)
2856         add_stub_r(LOADBU_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2857     }
2858     else
2859       inline_readstub(LOADBU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj[i],reglist);
2860     break;
2861   case 0x25: // LHU
2862     if(!c||memtarget) {
2863       if(!dummy) {
2864         int a = tl;
2865         if(!c) a = addr;
2866         if (fastio_reg_override >= 0)
2867           a = fastio_reg_override;
2868         if (offset_reg >= 0)
2869           emit_ldrh_dualindexed(offset_reg, a, tl);
2870         else
2871           emit_movzwl_indexed(0, a, tl);
2872       }
2873       if(jaddr)
2874         add_stub_r(LOADHU_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2875     }
2876     else
2877       inline_readstub(LOADHU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj[i],reglist);
2878     break;
2879   case 0x27: // LWU
2880   case 0x37: // LD
2881   default:
2882     assert(0);
2883   }
2884  }
2885  if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
2886    host_tempreg_release();
2887 }
2888
2889 #ifndef loadlr_assemble
2890 static void loadlr_assemble(int i, const struct regstat *i_regs)
2891 {
2892   int s,tl,temp,temp2,addr;
2893   int offset;
2894   void *jaddr=0;
2895   int memtarget=0,c=0;
2896   int offset_reg = -1;
2897   int fastio_reg_override = -1;
2898   u_int reglist=get_host_reglist(i_regs->regmap);
2899   tl=get_reg(i_regs->regmap,dops[i].rt1);
2900   s=get_reg(i_regs->regmap,dops[i].rs1);
2901   temp=get_reg(i_regs->regmap,-1);
2902   temp2=get_reg(i_regs->regmap,FTEMP);
2903   addr=get_reg(i_regs->regmap,AGEN1+(i&1));
2904   assert(addr<0);
2905   offset=imm[i];
2906   reglist|=1<<temp;
2907   if(offset||s<0||c) addr=temp2;
2908   else addr=s;
2909   if(s>=0) {
2910     c=(i_regs->wasconst>>s)&1;
2911     if(c) {
2912       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2913     }
2914   }
2915   if(!c) {
2916     emit_shlimm(addr,3,temp);
2917     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
2918       emit_andimm(addr,0xFFFFFFFC,temp2); // LWL/LWR
2919     }else{
2920       emit_andimm(addr,0xFFFFFFF8,temp2); // LDL/LDR
2921     }
2922     jaddr = emit_fastpath_cmp_jump(i, i_regs, temp2,
2923               &offset_reg, &fastio_reg_override);
2924   }
2925   else {
2926     if (ram_offset && memtarget) {
2927       offset_reg = get_ro_reg(i_regs, 0);
2928     }
2929     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
2930       emit_movimm(((constmap[i][s]+offset)<<3)&24,temp); // LWL/LWR
2931     }else{
2932       emit_movimm(((constmap[i][s]+offset)<<3)&56,temp); // LDL/LDR
2933     }
2934   }
2935   if (dops[i].opcode==0x22||dops[i].opcode==0x26) { // LWL/LWR
2936     if(!c||memtarget) {
2937       int a = temp2;
2938       if (fastio_reg_override >= 0)
2939         a = fastio_reg_override;
2940       do_load_word(a, temp2, offset_reg);
2941       if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
2942         host_tempreg_release();
2943       if(jaddr) add_stub_r(LOADW_STUB,jaddr,out,i,temp2,i_regs,ccadj[i],reglist);
2944     }
2945     else
2946       inline_readstub(LOADW_STUB,i,(constmap[i][s]+offset)&0xFFFFFFFC,i_regs->regmap,FTEMP,ccadj[i],reglist);
2947     if(dops[i].rt1) {
2948       assert(tl>=0);
2949       emit_andimm(temp,24,temp);
2950       if (dops[i].opcode==0x22) // LWL
2951         emit_xorimm(temp,24,temp);
2952       host_tempreg_acquire();
2953       emit_movimm(-1,HOST_TEMPREG);
2954       if (dops[i].opcode==0x26) {
2955         emit_shr(temp2,temp,temp2);
2956         emit_bic_lsr(tl,HOST_TEMPREG,temp,tl);
2957       }else{
2958         emit_shl(temp2,temp,temp2);
2959         emit_bic_lsl(tl,HOST_TEMPREG,temp,tl);
2960       }
2961       host_tempreg_release();
2962       emit_or(temp2,tl,tl);
2963     }
2964     //emit_storereg(dops[i].rt1,tl); // DEBUG
2965   }
2966   if (dops[i].opcode==0x1A||dops[i].opcode==0x1B) { // LDL/LDR
2967     assert(0);
2968   }
2969 }
2970 #endif
2971
2972 static void store_assemble(int i, const struct regstat *i_regs)
2973 {
2974   int s,tl;
2975   int addr,temp;
2976   int offset;
2977   void *jaddr=0;
2978   enum stub_type type=0;
2979   int memtarget=0,c=0;
2980   int agr=AGEN1+(i&1);
2981   int offset_reg = -1;
2982   int fastio_reg_override = -1;
2983   u_int reglist=get_host_reglist(i_regs->regmap);
2984   tl=get_reg(i_regs->regmap,dops[i].rs2);
2985   s=get_reg(i_regs->regmap,dops[i].rs1);
2986   temp=get_reg(i_regs->regmap,agr);
2987   if(temp<0) temp=get_reg(i_regs->regmap,-1);
2988   offset=imm[i];
2989   if(s>=0) {
2990     c=(i_regs->wasconst>>s)&1;
2991     if(c) {
2992       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2993     }
2994   }
2995   assert(tl>=0);
2996   assert(temp>=0);
2997   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2998   if(offset||s<0||c) addr=temp;
2999   else addr=s;
3000   if (!c) {
3001     jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
3002               &offset_reg, &fastio_reg_override);
3003   }
3004   else if (ram_offset && memtarget) {
3005     offset_reg = get_ro_reg(i_regs, 0);
3006   }
3007
3008   switch (dops[i].opcode) {
3009   case 0x28: // SB
3010     if(!c||memtarget) {
3011       int a = temp;
3012       if (!c) a = addr;
3013       if (fastio_reg_override >= 0)
3014         a = fastio_reg_override;
3015       do_store_byte(a, tl, offset_reg);
3016     }
3017     type = STOREB_STUB;
3018     break;
3019   case 0x29: // SH
3020     if(!c||memtarget) {
3021       int a = temp;
3022       if (!c) a = addr;
3023       if (fastio_reg_override >= 0)
3024         a = fastio_reg_override;
3025       do_store_hword(a, 0, tl, offset_reg, 1);
3026     }
3027     type = STOREH_STUB;
3028     break;
3029   case 0x2B: // SW
3030     if(!c||memtarget) {
3031       int a = addr;
3032       if (fastio_reg_override >= 0)
3033         a = fastio_reg_override;
3034       do_store_word(a, 0, tl, offset_reg, 1);
3035     }
3036     type = STOREW_STUB;
3037     break;
3038   case 0x3F: // SD
3039   default:
3040     assert(0);
3041   }
3042   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3043     host_tempreg_release();
3044   if(jaddr) {
3045     // PCSX store handlers don't check invcode again
3046     reglist|=1<<addr;
3047     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
3048     jaddr=0;
3049   }
3050   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3051     if(!c||memtarget) {
3052       #ifdef DESTRUCTIVE_SHIFT
3053       // The x86 shift operation is 'destructive'; it overwrites the
3054       // source register, so we need to make a copy first and use that.
3055       addr=temp;
3056       #endif
3057       #if defined(HOST_IMM8)
3058       int ir=get_reg(i_regs->regmap,INVCP);
3059       assert(ir>=0);
3060       emit_cmpmem_indexedsr12_reg(ir,addr,1);
3061       #else
3062       emit_cmpmem_indexedsr12_imm(invalid_code,addr,1);
3063       #endif
3064       #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3065       emit_callne(invalidate_addr_reg[addr]);
3066       #else
3067       void *jaddr2 = out;
3068       emit_jne(0);
3069       add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),addr,0,0,0);
3070       #endif
3071     }
3072   }
3073   u_int addr_val=constmap[i][s]+offset;
3074   if(jaddr) {
3075     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
3076   } else if(c&&!memtarget) {
3077     inline_writestub(type,i,addr_val,i_regs->regmap,dops[i].rs2,ccadj[i],reglist);
3078   }
3079   // basic current block modification detection..
3080   // not looking back as that should be in mips cache already
3081   // (see Spyro2 title->attract mode)
3082   if(c&&start+i*4<addr_val&&addr_val<start+slen*4) {
3083     SysPrintf("write to %08x hits block %08x, pc=%08x\n",addr_val,start,start+i*4);
3084     assert(i_regs->regmap==regs[i].regmap); // not delay slot
3085     if(i_regs->regmap==regs[i].regmap) {
3086       load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3087       wb_dirtys(regs[i].regmap_entry,regs[i].wasdirty);
3088       emit_movimm(start+i*4+4,0);
3089       emit_writeword(0,&pcaddr);
3090       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3091       emit_far_call(get_addr_ht);
3092       emit_jmpreg(0);
3093     }
3094   }
3095 }
3096
3097 static void storelr_assemble(int i, const struct regstat *i_regs)
3098 {
3099   int s,tl;
3100   int temp;
3101   int offset;
3102   void *jaddr=0;
3103   void *case1, *case23, *case3;
3104   void *done0, *done1, *done2;
3105   int memtarget=0,c=0;
3106   int agr=AGEN1+(i&1);
3107   int offset_reg = -1;
3108   u_int reglist=get_host_reglist(i_regs->regmap);
3109   tl=get_reg(i_regs->regmap,dops[i].rs2);
3110   s=get_reg(i_regs->regmap,dops[i].rs1);
3111   temp=get_reg(i_regs->regmap,agr);
3112   if(temp<0) temp=get_reg(i_regs->regmap,-1);
3113   offset=imm[i];
3114   if(s>=0) {
3115     c=(i_regs->isconst>>s)&1;
3116     if(c) {
3117       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3118     }
3119   }
3120   assert(tl>=0);
3121   assert(temp>=0);
3122   if(!c) {
3123     emit_cmpimm(s<0||offset?temp:s,RAM_SIZE);
3124     if(!offset&&s!=temp) emit_mov(s,temp);
3125     jaddr=out;
3126     emit_jno(0);
3127   }
3128   else
3129   {
3130     if(!memtarget||!dops[i].rs1) {
3131       jaddr=out;
3132       emit_jmp(0);
3133     }
3134   }
3135   if (ram_offset)
3136     offset_reg = get_ro_reg(i_regs, 0);
3137
3138   if (dops[i].opcode==0x2C||dops[i].opcode==0x2D) { // SDL/SDR
3139     assert(0);
3140   }
3141
3142   emit_testimm(temp,2);
3143   case23=out;
3144   emit_jne(0);
3145   emit_testimm(temp,1);
3146   case1=out;
3147   emit_jne(0);
3148   // 0
3149   if (dops[i].opcode == 0x2A) { // SWL
3150     // Write msb into least significant byte
3151     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3152     do_store_byte(temp, tl, offset_reg);
3153     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3154   }
3155   else if (dops[i].opcode == 0x2E) { // SWR
3156     // Write entire word
3157     do_store_word(temp, 0, tl, offset_reg, 1);
3158   }
3159   done0 = out;
3160   emit_jmp(0);
3161   // 1
3162   set_jump_target(case1, out);
3163   if (dops[i].opcode == 0x2A) { // SWL
3164     // Write two msb into two least significant bytes
3165     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3166     do_store_hword(temp, -1, tl, offset_reg, 0);
3167     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3168   }
3169   else if (dops[i].opcode == 0x2E) { // SWR
3170     // Write 3 lsb into three most significant bytes
3171     do_store_byte(temp, tl, offset_reg);
3172     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3173     do_store_hword(temp, 1, tl, offset_reg, 0);
3174     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3175   }
3176   done1=out;
3177   emit_jmp(0);
3178   // 2,3
3179   set_jump_target(case23, out);
3180   emit_testimm(temp,1);
3181   case3 = out;
3182   emit_jne(0);
3183   // 2
3184   if (dops[i].opcode==0x2A) { // SWL
3185     // Write 3 msb into three least significant bytes
3186     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3187     do_store_hword(temp, -2, tl, offset_reg, 1);
3188     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3189     do_store_byte(temp, tl, offset_reg);
3190     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3191   }
3192   else if (dops[i].opcode == 0x2E) { // SWR
3193     // Write two lsb into two most significant bytes
3194     do_store_hword(temp, 0, tl, offset_reg, 1);
3195   }
3196   done2 = out;
3197   emit_jmp(0);
3198   // 3
3199   set_jump_target(case3, out);
3200   if (dops[i].opcode == 0x2A) { // SWL
3201     do_store_word(temp, -3, tl, offset_reg, 0);
3202   }
3203   else if (dops[i].opcode == 0x2E) { // SWR
3204     do_store_byte(temp, tl, offset_reg);
3205   }
3206   set_jump_target(done0, out);
3207   set_jump_target(done1, out);
3208   set_jump_target(done2, out);
3209   if (offset_reg == HOST_TEMPREG)
3210     host_tempreg_release();
3211   if(!c||!memtarget)
3212     add_stub_r(STORELR_STUB,jaddr,out,i,temp,i_regs,ccadj[i],reglist);
3213   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3214     #if defined(HOST_IMM8)
3215     int ir=get_reg(i_regs->regmap,INVCP);
3216     assert(ir>=0);
3217     emit_cmpmem_indexedsr12_reg(ir,temp,1);
3218     #else
3219     emit_cmpmem_indexedsr12_imm(invalid_code,temp,1);
3220     #endif
3221     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3222     emit_callne(invalidate_addr_reg[temp]);
3223     #else
3224     void *jaddr2 = out;
3225     emit_jne(0);
3226     add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),temp,0,0,0);
3227     #endif
3228   }
3229 }
3230
3231 static void cop0_assemble(int i,struct regstat *i_regs)
3232 {
3233   if(dops[i].opcode2==0) // MFC0
3234   {
3235     signed char t=get_reg(i_regs->regmap,dops[i].rt1);
3236     u_int copr=(source[i]>>11)&0x1f;
3237     //assert(t>=0); // Why does this happen?  OOT is weird
3238     if(t>=0&&dops[i].rt1!=0) {
3239       emit_readword(&reg_cop0[copr],t);
3240     }
3241   }
3242   else if(dops[i].opcode2==4) // MTC0
3243   {
3244     signed char s=get_reg(i_regs->regmap,dops[i].rs1);
3245     char copr=(source[i]>>11)&0x1f;
3246     assert(s>=0);
3247     wb_register(dops[i].rs1,i_regs->regmap,i_regs->dirty);
3248     if(copr==9||copr==11||copr==12||copr==13) {
3249       emit_readword(&last_count,HOST_TEMPREG);
3250       emit_loadreg(CCREG,HOST_CCREG); // TODO: do proper reg alloc
3251       emit_add(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3252       emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG);
3253       emit_writeword(HOST_CCREG,&Count);
3254     }
3255     // What a mess.  The status register (12) can enable interrupts,
3256     // so needs a special case to handle a pending interrupt.
3257     // The interrupt must be taken immediately, because a subsequent
3258     // instruction might disable interrupts again.
3259     if(copr==12||copr==13) {
3260       if (is_delayslot) {
3261         // burn cycles to cause cc_interrupt, which will
3262         // reschedule next_interupt. Relies on CCREG from above.
3263         assem_debug("MTC0 DS %d\n", copr);
3264         emit_writeword(HOST_CCREG,&last_count);
3265         emit_movimm(0,HOST_CCREG);
3266         emit_storereg(CCREG,HOST_CCREG);
3267         emit_loadreg(dops[i].rs1,1);
3268         emit_movimm(copr,0);
3269         emit_far_call(pcsx_mtc0_ds);
3270         emit_loadreg(dops[i].rs1,s);
3271         return;
3272       }
3273       emit_movimm(start+i*4+4,HOST_TEMPREG);
3274       emit_writeword(HOST_TEMPREG,&pcaddr);
3275       emit_movimm(0,HOST_TEMPREG);
3276       emit_writeword(HOST_TEMPREG,&pending_exception);
3277     }
3278     if(s==HOST_CCREG)
3279       emit_loadreg(dops[i].rs1,1);
3280     else if(s!=1)
3281       emit_mov(s,1);
3282     emit_movimm(copr,0);
3283     emit_far_call(pcsx_mtc0);
3284     if(copr==9||copr==11||copr==12||copr==13) {
3285       emit_readword(&Count,HOST_CCREG);
3286       emit_readword(&next_interupt,HOST_TEMPREG);
3287       emit_addimm(HOST_CCREG,-CLOCK_ADJUST(ccadj[i]),HOST_CCREG);
3288       emit_sub(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3289       emit_writeword(HOST_TEMPREG,&last_count);
3290       emit_storereg(CCREG,HOST_CCREG);
3291     }
3292     if(copr==12||copr==13) {
3293       assert(!is_delayslot);
3294       emit_readword(&pending_exception,14);
3295       emit_test(14,14);
3296       void *jaddr = out;
3297       emit_jeq(0);
3298       emit_readword(&pcaddr, 0);
3299       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3300       emit_far_call(get_addr_ht);
3301       emit_jmpreg(0);
3302       set_jump_target(jaddr, out);
3303     }
3304     emit_loadreg(dops[i].rs1,s);
3305   }
3306   else
3307   {
3308     assert(dops[i].opcode2==0x10);
3309     //if((source[i]&0x3f)==0x10) // RFE
3310     {
3311       emit_readword(&Status,0);
3312       emit_andimm(0,0x3c,1);
3313       emit_andimm(0,~0xf,0);
3314       emit_orrshr_imm(1,2,0);
3315       emit_writeword(0,&Status);
3316     }
3317   }
3318 }
3319
3320 static void cop1_unusable(int i,struct regstat *i_regs)
3321 {
3322   // XXX: should just just do the exception instead
3323   //if(!cop1_usable)
3324   {
3325     void *jaddr=out;
3326     emit_jmp(0);
3327     add_stub_r(FP_STUB,jaddr,out,i,0,i_regs,is_delayslot,0);
3328   }
3329 }
3330
3331 static void cop1_assemble(int i,struct regstat *i_regs)
3332 {
3333   cop1_unusable(i, i_regs);
3334 }
3335
3336 static void c1ls_assemble(int i,struct regstat *i_regs)
3337 {
3338   cop1_unusable(i, i_regs);
3339 }
3340
3341 // FP_STUB
3342 static void do_cop1stub(int n)
3343 {
3344   literal_pool(256);
3345   assem_debug("do_cop1stub %x\n",start+stubs[n].a*4);
3346   set_jump_target(stubs[n].addr, out);
3347   int i=stubs[n].a;
3348 //  int rs=stubs[n].b;
3349   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3350   int ds=stubs[n].d;
3351   if(!ds) {
3352     load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3353     //if(i_regs!=&regs[i]) printf("oops: regs[i]=%x i_regs=%x",(int)&regs[i],(int)i_regs);
3354   }
3355   //else {printf("fp exception in delay slot\n");}
3356   wb_dirtys(i_regs->regmap_entry,i_regs->wasdirty);
3357   if(regs[i].regmap_entry[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
3358   emit_movimm(start+(i-ds)*4,EAX); // Get PC
3359   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG); // CHECK: is this right?  There should probably be an extra cycle...
3360   emit_far_jump(ds?fp_exception_ds:fp_exception);
3361 }
3362
3363 static int cop2_is_stalling_op(int i, int *cycles)
3364 {
3365   if (dops[i].opcode == 0x3a) { // SWC2
3366     *cycles = 0;
3367     return 1;
3368   }
3369   if (dops[i].itype == COP2 && (dops[i].opcode2 == 0 || dops[i].opcode2 == 2)) { // MFC2/CFC2
3370     *cycles = 0;
3371     return 1;
3372   }
3373   if (dops[i].itype == C2OP) {
3374     *cycles = gte_cycletab[source[i] & 0x3f];
3375     return 1;
3376   }
3377   // ... what about MTC2/CTC2/LWC2?
3378   return 0;
3379 }
3380
3381 #if 0
3382 static void log_gte_stall(int stall, u_int cycle)
3383 {
3384   if ((u_int)stall <= 44)
3385     printf("x    stall %2d %u\n", stall, cycle + last_count);
3386 }
3387
3388 static void emit_log_gte_stall(int i, int stall, u_int reglist)
3389 {
3390   save_regs(reglist);
3391   if (stall > 0)
3392     emit_movimm(stall, 0);
3393   else
3394     emit_mov(HOST_TEMPREG, 0);
3395   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]), 1);
3396   emit_far_call(log_gte_stall);
3397   restore_regs(reglist);
3398 }
3399 #endif
3400
3401 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist)
3402 {
3403   int j = i, other_gte_op_cycles = -1, stall = -MAXBLOCK, cycles_passed;
3404   int rtmp = reglist_find_free(reglist);
3405
3406   if (HACK_ENABLED(NDHACK_NO_STALLS))
3407     return;
3408   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3409     // happens occasionally... cc evicted? Don't bother then
3410     //printf("no cc %08x\n", start + i*4);
3411     return;
3412   }
3413   if (!dops[i].bt) {
3414     for (j = i - 1; j >= 0; j--) {
3415       //if (dops[j].is_ds) break;
3416       if (cop2_is_stalling_op(j, &other_gte_op_cycles) || dops[j].bt)
3417         break;
3418     }
3419     j = max(j, 0);
3420   }
3421   cycles_passed = CLOCK_ADJUST(ccadj[i] - ccadj[j]);
3422   if (other_gte_op_cycles >= 0)
3423     stall = other_gte_op_cycles - cycles_passed;
3424   else if (cycles_passed >= 44)
3425     stall = 0; // can't stall
3426   if (stall == -MAXBLOCK && rtmp >= 0) {
3427     // unknown stall, do the expensive runtime check
3428     assem_debug("; cop2_do_stall_check\n");
3429 #if 0 // too slow
3430     save_regs(reglist);
3431     emit_movimm(gte_cycletab[op], 0);
3432     emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]), 1);
3433     emit_far_call(call_gteStall);
3434     restore_regs(reglist);
3435 #else
3436     host_tempreg_acquire();
3437     emit_readword(&psxRegs.gteBusyCycle, rtmp);
3438     emit_addimm(rtmp, -CLOCK_ADJUST(ccadj[i]), rtmp);
3439     emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3440     emit_cmpimm(HOST_TEMPREG, 44);
3441     emit_cmovb_reg(rtmp, HOST_CCREG);
3442     //emit_log_gte_stall(i, 0, reglist);
3443     host_tempreg_release();
3444 #endif
3445   }
3446   else if (stall > 0) {
3447     //emit_log_gte_stall(i, stall, reglist);
3448     emit_addimm(HOST_CCREG, stall, HOST_CCREG);
3449   }
3450
3451   // save gteBusyCycle, if needed
3452   if (gte_cycletab[op] == 0)
3453     return;
3454   other_gte_op_cycles = -1;
3455   for (j = i + 1; j < slen; j++) {
3456     if (cop2_is_stalling_op(j, &other_gte_op_cycles))
3457       break;
3458     if (dops[j].is_jump) {
3459       // check ds
3460       if (j + 1 < slen && cop2_is_stalling_op(j + 1, &other_gte_op_cycles))
3461         j++;
3462       break;
3463     }
3464   }
3465   if (other_gte_op_cycles >= 0)
3466     // will handle stall when assembling that op
3467     return;
3468   cycles_passed = CLOCK_ADJUST(ccadj[min(j, slen -1)] - ccadj[i]);
3469   if (cycles_passed >= 44)
3470     return;
3471   assem_debug("; save gteBusyCycle\n");
3472   host_tempreg_acquire();
3473 #if 0
3474   emit_readword(&last_count, HOST_TEMPREG);
3475   emit_add(HOST_TEMPREG, HOST_CCREG, HOST_TEMPREG);
3476   emit_addimm(HOST_TEMPREG, CLOCK_ADJUST(ccadj[i]), HOST_TEMPREG);
3477   emit_addimm(HOST_TEMPREG, gte_cycletab[op]), HOST_TEMPREG);
3478   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3479 #else
3480   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]) + gte_cycletab[op], HOST_TEMPREG);
3481   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3482 #endif
3483   host_tempreg_release();
3484 }
3485
3486 static int is_mflohi(int i)
3487 {
3488   return (dops[i].itype == MOV && (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG));
3489 }
3490
3491 static int check_multdiv(int i, int *cycles)
3492 {
3493   if (dops[i].itype != MULTDIV)
3494     return 0;
3495   if (dops[i].opcode2 == 0x18 || dops[i].opcode2 == 0x19) // MULT(U)
3496     *cycles = 11; // approx from 7 11 14
3497   else
3498     *cycles = 37;
3499   return 1;
3500 }
3501
3502 static void multdiv_prepare_stall(int i, const struct regstat *i_regs)
3503 {
3504   int j, found = 0, c = 0;
3505   if (HACK_ENABLED(NDHACK_NO_STALLS))
3506     return;
3507   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3508     // happens occasionally... cc evicted? Don't bother then
3509     return;
3510   }
3511   for (j = i + 1; j < slen; j++) {
3512     if (dops[j].bt)
3513       break;
3514     if ((found = is_mflohi(j)))
3515       break;
3516     if (dops[j].is_jump) {
3517       // check ds
3518       if (j + 1 < slen && (found = is_mflohi(j + 1)))
3519         j++;
3520       break;
3521     }
3522   }
3523   if (found)
3524     // handle all in multdiv_do_stall()
3525     return;
3526   check_multdiv(i, &c);
3527   assert(c > 0);
3528   assem_debug("; muldiv prepare stall %d\n", c);
3529   host_tempreg_acquire();
3530   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]) + c, HOST_TEMPREG);
3531   emit_writeword(HOST_TEMPREG, &psxRegs.muldivBusyCycle);
3532   host_tempreg_release();
3533 }
3534
3535 static void multdiv_do_stall(int i, const struct regstat *i_regs)
3536 {
3537   int j, known_cycles = 0;
3538   u_int reglist = get_host_reglist(i_regs->regmap);
3539   int rtmp = get_reg(i_regs->regmap, -1);
3540   if (rtmp < 0)
3541     rtmp = reglist_find_free(reglist);
3542   if (HACK_ENABLED(NDHACK_NO_STALLS))
3543     return;
3544   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG || rtmp < 0) {
3545     // happens occasionally... cc evicted? Don't bother then
3546     //printf("no cc/rtmp %08x\n", start + i*4);
3547     return;
3548   }
3549   if (!dops[i].bt) {
3550     for (j = i - 1; j >= 0; j--) {
3551       if (dops[j].is_ds) break;
3552       if (check_multdiv(j, &known_cycles) || dops[j].bt)
3553         break;
3554       if (is_mflohi(j))
3555         // already handled by this op
3556         return;
3557     }
3558     j = max(j, 0);
3559   }
3560   if (known_cycles > 0) {
3561     known_cycles -= CLOCK_ADJUST(ccadj[i] - ccadj[j]);
3562     assem_debug("; muldiv stall resolved %d\n", known_cycles);
3563     if (known_cycles > 0)
3564       emit_addimm(HOST_CCREG, known_cycles, HOST_CCREG);
3565     return;
3566   }
3567   assem_debug("; muldiv stall unresolved\n");
3568   host_tempreg_acquire();
3569   emit_readword(&psxRegs.muldivBusyCycle, rtmp);
3570   emit_addimm(rtmp, -CLOCK_ADJUST(ccadj[i]), rtmp);
3571   emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3572   emit_cmpimm(HOST_TEMPREG, 37);
3573   emit_cmovb_reg(rtmp, HOST_CCREG);
3574   //emit_log_gte_stall(i, 0, reglist);
3575   host_tempreg_release();
3576 }
3577
3578 static void cop2_get_dreg(u_int copr,signed char tl,signed char temp)
3579 {
3580   switch (copr) {
3581     case 1:
3582     case 3:
3583     case 5:
3584     case 8:
3585     case 9:
3586     case 10:
3587     case 11:
3588       emit_readword(&reg_cop2d[copr],tl);
3589       emit_signextend16(tl,tl);
3590       emit_writeword(tl,&reg_cop2d[copr]); // hmh
3591       break;
3592     case 7:
3593     case 16:
3594     case 17:
3595     case 18:
3596     case 19:
3597       emit_readword(&reg_cop2d[copr],tl);
3598       emit_andimm(tl,0xffff,tl);
3599       emit_writeword(tl,&reg_cop2d[copr]);
3600       break;
3601     case 15:
3602       emit_readword(&reg_cop2d[14],tl); // SXY2
3603       emit_writeword(tl,&reg_cop2d[copr]);
3604       break;
3605     case 28:
3606     case 29:
3607       c2op_mfc2_29_assemble(tl,temp);
3608       break;
3609     default:
3610       emit_readword(&reg_cop2d[copr],tl);
3611       break;
3612   }
3613 }
3614
3615 static void cop2_put_dreg(u_int copr,signed char sl,signed char temp)
3616 {
3617   switch (copr) {
3618     case 15:
3619       emit_readword(&reg_cop2d[13],temp);  // SXY1
3620       emit_writeword(sl,&reg_cop2d[copr]);
3621       emit_writeword(temp,&reg_cop2d[12]); // SXY0
3622       emit_readword(&reg_cop2d[14],temp);  // SXY2
3623       emit_writeword(sl,&reg_cop2d[14]);
3624       emit_writeword(temp,&reg_cop2d[13]); // SXY1
3625       break;
3626     case 28:
3627       emit_andimm(sl,0x001f,temp);
3628       emit_shlimm(temp,7,temp);
3629       emit_writeword(temp,&reg_cop2d[9]);
3630       emit_andimm(sl,0x03e0,temp);
3631       emit_shlimm(temp,2,temp);
3632       emit_writeword(temp,&reg_cop2d[10]);
3633       emit_andimm(sl,0x7c00,temp);
3634       emit_shrimm(temp,3,temp);
3635       emit_writeword(temp,&reg_cop2d[11]);
3636       emit_writeword(sl,&reg_cop2d[28]);
3637       break;
3638     case 30:
3639       emit_xorsar_imm(sl,sl,31,temp);
3640 #if defined(HAVE_ARMV5) || defined(__aarch64__)
3641       emit_clz(temp,temp);
3642 #else
3643       emit_movs(temp,HOST_TEMPREG);
3644       emit_movimm(0,temp);
3645       emit_jeq((int)out+4*4);
3646       emit_addpl_imm(temp,1,temp);
3647       emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
3648       emit_jns((int)out-2*4);
3649 #endif
3650       emit_writeword(sl,&reg_cop2d[30]);
3651       emit_writeword(temp,&reg_cop2d[31]);
3652       break;
3653     case 31:
3654       break;
3655     default:
3656       emit_writeword(sl,&reg_cop2d[copr]);
3657       break;
3658   }
3659 }
3660
3661 static void c2ls_assemble(int i, const struct regstat *i_regs)
3662 {
3663   int s,tl;
3664   int ar;
3665   int offset;
3666   int memtarget=0,c=0;
3667   void *jaddr2=NULL;
3668   enum stub_type type;
3669   int agr=AGEN1+(i&1);
3670   int offset_reg = -1;
3671   int fastio_reg_override = -1;
3672   u_int reglist=get_host_reglist(i_regs->regmap);
3673   u_int copr=(source[i]>>16)&0x1f;
3674   s=get_reg(i_regs->regmap,dops[i].rs1);
3675   tl=get_reg(i_regs->regmap,FTEMP);
3676   offset=imm[i];
3677   assert(dops[i].rs1>0);
3678   assert(tl>=0);
3679
3680   if(i_regs->regmap[HOST_CCREG]==CCREG)
3681     reglist&=~(1<<HOST_CCREG);
3682
3683   // get the address
3684   if (dops[i].opcode==0x3a) { // SWC2
3685     ar=get_reg(i_regs->regmap,agr);
3686     if(ar<0) ar=get_reg(i_regs->regmap,-1);
3687     reglist|=1<<ar;
3688   } else { // LWC2
3689     ar=tl;
3690   }
3691   if(s>=0) c=(i_regs->wasconst>>s)&1;
3692   memtarget=c&&(((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE);
3693   if (!offset&&!c&&s>=0) ar=s;
3694   assert(ar>=0);
3695
3696   cop2_do_stall_check(0, i, i_regs, reglist);
3697
3698   if (dops[i].opcode==0x3a) { // SWC2
3699     cop2_get_dreg(copr,tl,-1);
3700     type=STOREW_STUB;
3701   }
3702   else
3703     type=LOADW_STUB;
3704
3705   if(c&&!memtarget) {
3706     jaddr2=out;
3707     emit_jmp(0); // inline_readstub/inline_writestub?
3708   }
3709   else {
3710     if(!c) {
3711       jaddr2 = emit_fastpath_cmp_jump(i, i_regs, ar,
3712                 &offset_reg, &fastio_reg_override);
3713     }
3714     else if (ram_offset && memtarget) {
3715       offset_reg = get_ro_reg(i_regs, 0);
3716     }
3717     switch (dops[i].opcode) {
3718     case 0x32: { // LWC2
3719       int a = ar;
3720       if (fastio_reg_override >= 0)
3721         a = fastio_reg_override;
3722       do_load_word(a, tl, offset_reg);
3723       break;
3724     }
3725     case 0x3a: { // SWC2
3726       #ifdef DESTRUCTIVE_SHIFT
3727       if(!offset&&!c&&s>=0) emit_mov(s,ar);
3728       #endif
3729       int a = ar;
3730       if (fastio_reg_override >= 0)
3731         a = fastio_reg_override;
3732       do_store_word(a, 0, tl, offset_reg, 1);
3733       break;
3734     }
3735     default:
3736       assert(0);
3737     }
3738   }
3739   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3740     host_tempreg_release();
3741   if(jaddr2)
3742     add_stub_r(type,jaddr2,out,i,ar,i_regs,ccadj[i],reglist);
3743   if(dops[i].opcode==0x3a) // SWC2
3744   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3745 #if defined(HOST_IMM8)
3746     int ir=get_reg(i_regs->regmap,INVCP);
3747     assert(ir>=0);
3748     emit_cmpmem_indexedsr12_reg(ir,ar,1);
3749 #else
3750     emit_cmpmem_indexedsr12_imm(invalid_code,ar,1);
3751 #endif
3752     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3753     emit_callne(invalidate_addr_reg[ar]);
3754     #else
3755     void *jaddr3 = out;
3756     emit_jne(0);
3757     add_stub(INVCODE_STUB,jaddr3,out,reglist|(1<<HOST_CCREG),ar,0,0,0);
3758     #endif
3759   }
3760   if (dops[i].opcode==0x32) { // LWC2
3761     host_tempreg_acquire();
3762     cop2_put_dreg(copr,tl,HOST_TEMPREG);
3763     host_tempreg_release();
3764   }
3765 }
3766
3767 static void cop2_assemble(int i, const struct regstat *i_regs)
3768 {
3769   u_int copr = (source[i]>>11) & 0x1f;
3770   signed char temp = get_reg(i_regs->regmap, -1);
3771
3772   if (!HACK_ENABLED(NDHACK_NO_STALLS)) {
3773     u_int reglist = reglist_exclude(get_host_reglist(i_regs->regmap), temp, -1);
3774     if (dops[i].opcode2 == 0 || dops[i].opcode2 == 2) { // MFC2/CFC2
3775       signed char tl = get_reg(i_regs->regmap, dops[i].rt1);
3776       reglist = reglist_exclude(reglist, tl, -1);
3777     }
3778     cop2_do_stall_check(0, i, i_regs, reglist);
3779   }
3780   if (dops[i].opcode2==0) { // MFC2
3781     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
3782     if(tl>=0&&dops[i].rt1!=0)
3783       cop2_get_dreg(copr,tl,temp);
3784   }
3785   else if (dops[i].opcode2==4) { // MTC2
3786     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
3787     cop2_put_dreg(copr,sl,temp);
3788   }
3789   else if (dops[i].opcode2==2) // CFC2
3790   {
3791     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
3792     if(tl>=0&&dops[i].rt1!=0)
3793       emit_readword(&reg_cop2c[copr],tl);
3794   }
3795   else if (dops[i].opcode2==6) // CTC2
3796   {
3797     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
3798     switch(copr) {
3799       case 4:
3800       case 12:
3801       case 20:
3802       case 26:
3803       case 27:
3804       case 29:
3805       case 30:
3806         emit_signextend16(sl,temp);
3807         break;
3808       case 31:
3809         c2op_ctc2_31_assemble(sl,temp);
3810         break;
3811       default:
3812         temp=sl;
3813         break;
3814     }
3815     emit_writeword(temp,&reg_cop2c[copr]);
3816     assert(sl>=0);
3817   }
3818 }
3819
3820 static void do_unalignedwritestub(int n)
3821 {
3822   assem_debug("do_unalignedwritestub %x\n",start+stubs[n].a*4);
3823   literal_pool(256);
3824   set_jump_target(stubs[n].addr, out);
3825
3826   int i=stubs[n].a;
3827   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3828   int addr=stubs[n].b;
3829   u_int reglist=stubs[n].e;
3830   signed char *i_regmap=i_regs->regmap;
3831   int temp2=get_reg(i_regmap,FTEMP);
3832   int rt;
3833   rt=get_reg(i_regmap,dops[i].rs2);
3834   assert(rt>=0);
3835   assert(addr>=0);
3836   assert(dops[i].opcode==0x2a||dops[i].opcode==0x2e); // SWL/SWR only implemented
3837   reglist|=(1<<addr);
3838   reglist&=~(1<<temp2);
3839
3840   // don't bother with it and call write handler
3841   save_regs(reglist);
3842   pass_args(addr,rt);
3843   int cc=get_reg(i_regmap,CCREG);
3844   if(cc<0)
3845     emit_loadreg(CCREG,2);
3846   emit_addimm(cc<0?2:cc,CLOCK_ADJUST((int)stubs[n].d+1),2);
3847   emit_far_call((dops[i].opcode==0x2a?jump_handle_swl:jump_handle_swr));
3848   emit_addimm(0,-CLOCK_ADJUST((int)stubs[n].d+1),cc<0?2:cc);
3849   if(cc<0)
3850     emit_storereg(CCREG,2);
3851   restore_regs(reglist);
3852   emit_jmp(stubs[n].retaddr); // return address
3853 }
3854
3855 #ifndef multdiv_assemble
3856 void multdiv_assemble(int i,struct regstat *i_regs)
3857 {
3858   printf("Need multdiv_assemble for this architecture.\n");
3859   abort();
3860 }
3861 #endif
3862
3863 static void mov_assemble(int i,struct regstat *i_regs)
3864 {
3865   //if(dops[i].opcode2==0x10||dops[i].opcode2==0x12) { // MFHI/MFLO
3866   //if(dops[i].opcode2==0x11||dops[i].opcode2==0x13) { // MTHI/MTLO
3867   if(dops[i].rt1) {
3868     signed char sl,tl;
3869     tl=get_reg(i_regs->regmap,dops[i].rt1);
3870     //assert(tl>=0);
3871     if(tl>=0) {
3872       sl=get_reg(i_regs->regmap,dops[i].rs1);
3873       if(sl>=0) emit_mov(sl,tl);
3874       else emit_loadreg(dops[i].rs1,tl);
3875     }
3876   }
3877   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) // MFHI/MFLO
3878     multdiv_do_stall(i, i_regs);
3879 }
3880
3881 // call interpreter, exception handler, things that change pc/regs/cycles ...
3882 static void call_c_cpu_handler(int i, const struct regstat *i_regs, u_int pc, void *func)
3883 {
3884   signed char ccreg=get_reg(i_regs->regmap,CCREG);
3885   assert(ccreg==HOST_CCREG);
3886   assert(!is_delayslot);
3887   (void)ccreg;
3888
3889   emit_movimm(pc,3); // Get PC
3890   emit_readword(&last_count,2);
3891   emit_writeword(3,&psxRegs.pc);
3892   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG); // XXX
3893   emit_add(2,HOST_CCREG,2);
3894   emit_writeword(2,&psxRegs.cycle);
3895   emit_far_call(func);
3896   emit_far_jump(jump_to_new_pc);
3897 }
3898
3899 static void syscall_assemble(int i,struct regstat *i_regs)
3900 {
3901   emit_movimm(0x20,0); // cause code
3902   emit_movimm(0,1);    // not in delay slot
3903   call_c_cpu_handler(i,i_regs,start+i*4,psxException);
3904 }
3905
3906 static void hlecall_assemble(int i,struct regstat *i_regs)
3907 {
3908   void *hlefunc = psxNULL;
3909   uint32_t hleCode = source[i] & 0x03ffffff;
3910   if (hleCode < ARRAY_SIZE(psxHLEt))
3911     hlefunc = psxHLEt[hleCode];
3912
3913   call_c_cpu_handler(i,i_regs,start+i*4+4,hlefunc);
3914 }
3915
3916 static void intcall_assemble(int i,struct regstat *i_regs)
3917 {
3918   call_c_cpu_handler(i,i_regs,start+i*4,execI);
3919 }
3920
3921 static void speculate_mov(int rs,int rt)
3922 {
3923   if(rt!=0) {
3924     smrv_strong_next|=1<<rt;
3925     smrv[rt]=smrv[rs];
3926   }
3927 }
3928
3929 static void speculate_mov_weak(int rs,int rt)
3930 {
3931   if(rt!=0) {
3932     smrv_weak_next|=1<<rt;
3933     smrv[rt]=smrv[rs];
3934   }
3935 }
3936
3937 static void speculate_register_values(int i)
3938 {
3939   if(i==0) {
3940     memcpy(smrv,psxRegs.GPR.r,sizeof(smrv));
3941     // gp,sp are likely to stay the same throughout the block
3942     smrv_strong_next=(1<<28)|(1<<29)|(1<<30);
3943     smrv_weak_next=~smrv_strong_next;
3944     //printf(" llr %08x\n", smrv[4]);
3945   }
3946   smrv_strong=smrv_strong_next;
3947   smrv_weak=smrv_weak_next;
3948   switch(dops[i].itype) {
3949     case ALU:
3950       if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
3951       else if((smrv_strong>>dops[i].rs2)&1) speculate_mov(dops[i].rs2,dops[i].rt1);
3952       else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
3953       else if((smrv_weak>>dops[i].rs2)&1) speculate_mov_weak(dops[i].rs2,dops[i].rt1);
3954       else {
3955         smrv_strong_next&=~(1<<dops[i].rt1);
3956         smrv_weak_next&=~(1<<dops[i].rt1);
3957       }
3958       break;
3959     case SHIFTIMM:
3960       smrv_strong_next&=~(1<<dops[i].rt1);
3961       smrv_weak_next&=~(1<<dops[i].rt1);
3962       // fallthrough
3963     case IMM16:
3964       if(dops[i].rt1&&is_const(&regs[i],dops[i].rt1)) {
3965         int value,hr=get_reg(regs[i].regmap,dops[i].rt1);
3966         if(hr>=0) {
3967           if(get_final_value(hr,i,&value))
3968                smrv[dops[i].rt1]=value;
3969           else smrv[dops[i].rt1]=constmap[i][hr];
3970           smrv_strong_next|=1<<dops[i].rt1;
3971         }
3972       }
3973       else {
3974         if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
3975         else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
3976       }
3977       break;
3978     case LOAD:
3979       if(start<0x2000&&(dops[i].rt1==26||(smrv[dops[i].rt1]>>24)==0xa0)) {
3980         // special case for BIOS
3981         smrv[dops[i].rt1]=0xa0000000;
3982         smrv_strong_next|=1<<dops[i].rt1;
3983         break;
3984       }
3985       // fallthrough
3986     case SHIFT:
3987     case LOADLR:
3988     case MOV:
3989       smrv_strong_next&=~(1<<dops[i].rt1);
3990       smrv_weak_next&=~(1<<dops[i].rt1);
3991       break;
3992     case COP0:
3993     case COP2:
3994       if(dops[i].opcode2==0||dops[i].opcode2==2) { // MFC/CFC
3995         smrv_strong_next&=~(1<<dops[i].rt1);
3996         smrv_weak_next&=~(1<<dops[i].rt1);
3997       }
3998       break;
3999     case C2LS:
4000       if (dops[i].opcode==0x32) { // LWC2
4001         smrv_strong_next&=~(1<<dops[i].rt1);
4002         smrv_weak_next&=~(1<<dops[i].rt1);
4003       }
4004       break;
4005   }
4006 #if 0
4007   int r=4;
4008   printf("x %08x %08x %d %d c %08x %08x\n",smrv[r],start+i*4,
4009     ((smrv_strong>>r)&1),(smrv_weak>>r)&1,regs[i].isconst,regs[i].wasconst);
4010 #endif
4011 }
4012
4013 static void ds_assemble(int i,struct regstat *i_regs)
4014 {
4015   speculate_register_values(i);
4016   is_delayslot=1;
4017   switch(dops[i].itype) {
4018     case ALU:
4019       alu_assemble(i,i_regs);break;
4020     case IMM16:
4021       imm16_assemble(i,i_regs);break;
4022     case SHIFT:
4023       shift_assemble(i,i_regs);break;
4024     case SHIFTIMM:
4025       shiftimm_assemble(i,i_regs);break;
4026     case LOAD:
4027       load_assemble(i,i_regs);break;
4028     case LOADLR:
4029       loadlr_assemble(i,i_regs);break;
4030     case STORE:
4031       store_assemble(i,i_regs);break;
4032     case STORELR:
4033       storelr_assemble(i,i_regs);break;
4034     case COP0:
4035       cop0_assemble(i,i_regs);break;
4036     case COP1:
4037       cop1_assemble(i,i_regs);break;
4038     case C1LS:
4039       c1ls_assemble(i,i_regs);break;
4040     case COP2:
4041       cop2_assemble(i,i_regs);break;
4042     case C2LS:
4043       c2ls_assemble(i,i_regs);break;
4044     case C2OP:
4045       c2op_assemble(i,i_regs);break;
4046     case MULTDIV:
4047       multdiv_assemble(i,i_regs);
4048       multdiv_prepare_stall(i,i_regs);
4049       break;
4050     case MOV:
4051       mov_assemble(i,i_regs);break;
4052     case SYSCALL:
4053     case HLECALL:
4054     case INTCALL:
4055     case SPAN:
4056     case UJUMP:
4057     case RJUMP:
4058     case CJUMP:
4059     case SJUMP:
4060       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4061   }
4062   is_delayslot=0;
4063 }
4064
4065 // Is the branch target a valid internal jump?
4066 static int internal_branch(int addr)
4067 {
4068   if(addr&1) return 0; // Indirect (register) jump
4069   if(addr>=start && addr<start+slen*4-4)
4070   {
4071     return 1;
4072   }
4073   return 0;
4074 }
4075
4076 static void wb_invalidate(signed char pre[],signed char entry[],uint64_t dirty,uint64_t u)
4077 {
4078   int hr;
4079   for(hr=0;hr<HOST_REGS;hr++) {
4080     if(hr!=EXCLUDE_REG) {
4081       if(pre[hr]!=entry[hr]) {
4082         if(pre[hr]>=0) {
4083           if((dirty>>hr)&1) {
4084             if(get_reg(entry,pre[hr])<0) {
4085               assert(pre[hr]<64);
4086               if(!((u>>pre[hr])&1))
4087                 emit_storereg(pre[hr],hr);
4088             }
4089           }
4090         }
4091       }
4092     }
4093   }
4094   // Move from one register to another (no writeback)
4095   for(hr=0;hr<HOST_REGS;hr++) {
4096     if(hr!=EXCLUDE_REG) {
4097       if(pre[hr]!=entry[hr]) {
4098         if(pre[hr]>=0&&(pre[hr]&63)<TEMPREG) {
4099           int nr;
4100           if((nr=get_reg(entry,pre[hr]))>=0) {
4101             emit_mov(hr,nr);
4102           }
4103         }
4104       }
4105     }
4106   }
4107 }
4108
4109 // Load the specified registers
4110 // This only loads the registers given as arguments because
4111 // we don't want to load things that will be overwritten
4112 static void load_regs(signed char entry[],signed char regmap[],int rs1,int rs2)
4113 {
4114   int hr;
4115   // Load 32-bit regs
4116   for(hr=0;hr<HOST_REGS;hr++) {
4117     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4118       if(entry[hr]!=regmap[hr]) {
4119         if(regmap[hr]==rs1||regmap[hr]==rs2)
4120         {
4121           if(regmap[hr]==0) {
4122             emit_zeroreg(hr);
4123           }
4124           else
4125           {
4126             emit_loadreg(regmap[hr],hr);
4127           }
4128         }
4129       }
4130     }
4131   }
4132 }
4133
4134 // Load registers prior to the start of a loop
4135 // so that they are not loaded within the loop
4136 static void loop_preload(signed char pre[],signed char entry[])
4137 {
4138   int hr;
4139   for(hr=0;hr<HOST_REGS;hr++) {
4140     if(hr!=EXCLUDE_REG) {
4141       if(pre[hr]!=entry[hr]) {
4142         if(entry[hr]>=0) {
4143           if(get_reg(pre,entry[hr])<0) {
4144             assem_debug("loop preload:\n");
4145             //printf("loop preload: %d\n",hr);
4146             if(entry[hr]==0) {
4147               emit_zeroreg(hr);
4148             }
4149             else if(entry[hr]<TEMPREG)
4150             {
4151               emit_loadreg(entry[hr],hr);
4152             }
4153             else if(entry[hr]-64<TEMPREG)
4154             {
4155               emit_loadreg(entry[hr],hr);
4156             }
4157           }
4158         }
4159       }
4160     }
4161   }
4162 }
4163
4164 // Generate address for load/store instruction
4165 // goes to AGEN for writes, FTEMP for LOADLR and cop1/2 loads
4166 void address_generation(int i,struct regstat *i_regs,signed char entry[])
4167 {
4168   if (dops[i].is_load || dops[i].is_store) {
4169     int ra=-1;
4170     int agr=AGEN1+(i&1);
4171     if(dops[i].itype==LOAD) {
4172       ra=get_reg(i_regs->regmap,dops[i].rt1);
4173       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4174       assert(ra>=0);
4175     }
4176     if(dops[i].itype==LOADLR) {
4177       ra=get_reg(i_regs->regmap,FTEMP);
4178     }
4179     if(dops[i].itype==STORE||dops[i].itype==STORELR) {
4180       ra=get_reg(i_regs->regmap,agr);
4181       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4182     }
4183     if(dops[i].itype==C2LS) {
4184       if ((dops[i].opcode&0x3b)==0x31||(dops[i].opcode&0x3b)==0x32) // LWC1/LDC1/LWC2/LDC2
4185         ra=get_reg(i_regs->regmap,FTEMP);
4186       else { // SWC1/SDC1/SWC2/SDC2
4187         ra=get_reg(i_regs->regmap,agr);
4188         if(ra<0) ra=get_reg(i_regs->regmap,-1);
4189       }
4190     }
4191     int rs=get_reg(i_regs->regmap,dops[i].rs1);
4192     if(ra>=0) {
4193       int offset=imm[i];
4194       int c=(i_regs->wasconst>>rs)&1;
4195       if(dops[i].rs1==0) {
4196         // Using r0 as a base address
4197         if(!entry||entry[ra]!=agr) {
4198           if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4199             emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4200           }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4201             emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4202           }else{
4203             emit_movimm(offset,ra);
4204           }
4205         } // else did it in the previous cycle
4206       }
4207       else if(rs<0) {
4208         if(!entry||entry[ra]!=dops[i].rs1)
4209           emit_loadreg(dops[i].rs1,ra);
4210         //if(!entry||entry[ra]!=dops[i].rs1)
4211         //  printf("poor load scheduling!\n");
4212       }
4213       else if(c) {
4214         if(dops[i].rs1!=dops[i].rt1||dops[i].itype!=LOAD) {
4215           if(!entry||entry[ra]!=agr) {
4216             if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4217               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4218             }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4219               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4220             }else{
4221               emit_movimm(constmap[i][rs]+offset,ra);
4222               regs[i].loadedconst|=1<<ra;
4223             }
4224           } // else did it in the previous cycle
4225         } // else load_consts already did it
4226       }
4227       if(offset&&!c&&dops[i].rs1) {
4228         if(rs>=0) {
4229           emit_addimm(rs,offset,ra);
4230         }else{
4231           emit_addimm(ra,offset,ra);
4232         }
4233       }
4234     }
4235   }
4236   // Preload constants for next instruction
4237   if (dops[i+1].is_load || dops[i+1].is_store) {
4238     int agr,ra;
4239     // Actual address
4240     agr=AGEN1+((i+1)&1);
4241     ra=get_reg(i_regs->regmap,agr);
4242     if(ra>=0) {
4243       int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
4244       int offset=imm[i+1];
4245       int c=(regs[i+1].wasconst>>rs)&1;
4246       if(c&&(dops[i+1].rs1!=dops[i+1].rt1||dops[i+1].itype!=LOAD)) {
4247         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4248           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4249         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4250           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4251         }else{
4252           emit_movimm(constmap[i+1][rs]+offset,ra);
4253           regs[i+1].loadedconst|=1<<ra;
4254         }
4255       }
4256       else if(dops[i+1].rs1==0) {
4257         // Using r0 as a base address
4258         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4259           emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4260         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4261           emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4262         }else{
4263           emit_movimm(offset,ra);
4264         }
4265       }
4266     }
4267   }
4268 }
4269
4270 static int get_final_value(int hr, int i, int *value)
4271 {
4272   int reg=regs[i].regmap[hr];
4273   while(i<slen-1) {
4274     if(regs[i+1].regmap[hr]!=reg) break;
4275     if(!((regs[i+1].isconst>>hr)&1)) break;
4276     if(dops[i+1].bt) break;
4277     i++;
4278   }
4279   if(i<slen-1) {
4280     if (dops[i].is_jump) {
4281       *value=constmap[i][hr];
4282       return 1;
4283     }
4284     if(!dops[i+1].bt) {
4285       if (dops[i+1].is_jump) {
4286         // Load in delay slot, out-of-order execution
4287         if(dops[i+2].itype==LOAD&&dops[i+2].rs1==reg&&dops[i+2].rt1==reg&&((regs[i+1].wasconst>>hr)&1))
4288         {
4289           // Precompute load address
4290           *value=constmap[i][hr]+imm[i+2];
4291           return 1;
4292         }
4293       }
4294       if(dops[i+1].itype==LOAD&&dops[i+1].rs1==reg&&dops[i+1].rt1==reg)
4295       {
4296         // Precompute load address
4297         *value=constmap[i][hr]+imm[i+1];
4298         //printf("c=%x imm=%lx\n",(long)constmap[i][hr],imm[i+1]);
4299         return 1;
4300       }
4301     }
4302   }
4303   *value=constmap[i][hr];
4304   //printf("c=%lx\n",(long)constmap[i][hr]);
4305   if(i==slen-1) return 1;
4306   assert(reg < 64);
4307   return !((unneeded_reg[i+1]>>reg)&1);
4308 }
4309
4310 // Load registers with known constants
4311 static void load_consts(signed char pre[],signed char regmap[],int i)
4312 {
4313   int hr,hr2;
4314   // propagate loaded constant flags
4315   if(i==0||dops[i].bt)
4316     regs[i].loadedconst=0;
4317   else {
4318     for(hr=0;hr<HOST_REGS;hr++) {
4319       if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((regs[i-1].isconst>>hr)&1)&&pre[hr]==regmap[hr]
4320          &&regmap[hr]==regs[i-1].regmap[hr]&&((regs[i-1].loadedconst>>hr)&1))
4321       {
4322         regs[i].loadedconst|=1<<hr;
4323       }
4324     }
4325   }
4326   // Load 32-bit regs
4327   for(hr=0;hr<HOST_REGS;hr++) {
4328     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4329       //if(entry[hr]!=regmap[hr]) {
4330       if(!((regs[i].loadedconst>>hr)&1)) {
4331         assert(regmap[hr]<64);
4332         if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4333           int value,similar=0;
4334           if(get_final_value(hr,i,&value)) {
4335             // see if some other register has similar value
4336             for(hr2=0;hr2<HOST_REGS;hr2++) {
4337               if(hr2!=EXCLUDE_REG&&((regs[i].loadedconst>>hr2)&1)) {
4338                 if(is_similar_value(value,constmap[i][hr2])) {
4339                   similar=1;
4340                   break;
4341                 }
4342               }
4343             }
4344             if(similar) {
4345               int value2;
4346               if(get_final_value(hr2,i,&value2)) // is this needed?
4347                 emit_movimm_from(value2,hr2,value,hr);
4348               else
4349                 emit_movimm(value,hr);
4350             }
4351             else if(value==0) {
4352               emit_zeroreg(hr);
4353             }
4354             else {
4355               emit_movimm(value,hr);
4356             }
4357           }
4358           regs[i].loadedconst|=1<<hr;
4359         }
4360       }
4361     }
4362   }
4363 }
4364
4365 void load_all_consts(signed char regmap[], u_int dirty, int i)
4366 {
4367   int hr;
4368   // Load 32-bit regs
4369   for(hr=0;hr<HOST_REGS;hr++) {
4370     if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((dirty>>hr)&1)) {
4371       assert(regmap[hr] < 64);
4372       if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4373         int value=constmap[i][hr];
4374         if(value==0) {
4375           emit_zeroreg(hr);
4376         }
4377         else {
4378           emit_movimm(value,hr);
4379         }
4380       }
4381     }
4382   }
4383 }
4384
4385 // Write out all dirty registers (except cycle count)
4386 static void wb_dirtys(signed char i_regmap[],uint64_t i_dirty)
4387 {
4388   int hr;
4389   for(hr=0;hr<HOST_REGS;hr++) {
4390     if(hr!=EXCLUDE_REG) {
4391       if(i_regmap[hr]>0) {
4392         if(i_regmap[hr]!=CCREG) {
4393           if((i_dirty>>hr)&1) {
4394             assert(i_regmap[hr]<64);
4395             emit_storereg(i_regmap[hr],hr);
4396           }
4397         }
4398       }
4399     }
4400   }
4401 }
4402
4403 // Write out dirty registers that we need to reload (pair with load_needed_regs)
4404 // This writes the registers not written by store_regs_bt
4405 void wb_needed_dirtys(signed char i_regmap[],uint64_t i_dirty,int addr)
4406 {
4407   int hr;
4408   int t=(addr-start)>>2;
4409   for(hr=0;hr<HOST_REGS;hr++) {
4410     if(hr!=EXCLUDE_REG) {
4411       if(i_regmap[hr]>0) {
4412         if(i_regmap[hr]!=CCREG) {
4413           if(i_regmap[hr]==regs[t].regmap_entry[hr] && ((regs[t].dirty>>hr)&1)) {
4414             if((i_dirty>>hr)&1) {
4415               assert(i_regmap[hr]<64);
4416               emit_storereg(i_regmap[hr],hr);
4417             }
4418           }
4419         }
4420       }
4421     }
4422   }
4423 }
4424
4425 // Load all registers (except cycle count)
4426 void load_all_regs(signed char i_regmap[])
4427 {
4428   int hr;
4429   for(hr=0;hr<HOST_REGS;hr++) {
4430     if(hr!=EXCLUDE_REG) {
4431       if(i_regmap[hr]==0) {
4432         emit_zeroreg(hr);
4433       }
4434       else
4435       if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4436       {
4437         emit_loadreg(i_regmap[hr],hr);
4438       }
4439     }
4440   }
4441 }
4442
4443 // Load all current registers also needed by next instruction
4444 void load_needed_regs(signed char i_regmap[],signed char next_regmap[])
4445 {
4446   int hr;
4447   for(hr=0;hr<HOST_REGS;hr++) {
4448     if(hr!=EXCLUDE_REG) {
4449       if(get_reg(next_regmap,i_regmap[hr])>=0) {
4450         if(i_regmap[hr]==0) {
4451           emit_zeroreg(hr);
4452         }
4453         else
4454         if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4455         {
4456           emit_loadreg(i_regmap[hr],hr);
4457         }
4458       }
4459     }
4460   }
4461 }
4462
4463 // Load all regs, storing cycle count if necessary
4464 void load_regs_entry(int t)
4465 {
4466   int hr;
4467   if(dops[t].is_ds) emit_addimm(HOST_CCREG,CLOCK_ADJUST(1),HOST_CCREG);
4468   else if(ccadj[t]) emit_addimm(HOST_CCREG,-CLOCK_ADJUST(ccadj[t]),HOST_CCREG);
4469   if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4470     emit_storereg(CCREG,HOST_CCREG);
4471   }
4472   // Load 32-bit regs
4473   for(hr=0;hr<HOST_REGS;hr++) {
4474     if(regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4475       if(regs[t].regmap_entry[hr]==0) {
4476         emit_zeroreg(hr);
4477       }
4478       else if(regs[t].regmap_entry[hr]!=CCREG)
4479       {
4480         emit_loadreg(regs[t].regmap_entry[hr],hr);
4481       }
4482     }
4483   }
4484 }
4485
4486 // Store dirty registers prior to branch
4487 void store_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4488 {
4489   if(internal_branch(addr))
4490   {
4491     int t=(addr-start)>>2;
4492     int hr;
4493     for(hr=0;hr<HOST_REGS;hr++) {
4494       if(hr!=EXCLUDE_REG) {
4495         if(i_regmap[hr]>0 && i_regmap[hr]!=CCREG) {
4496           if(i_regmap[hr]!=regs[t].regmap_entry[hr] || !((regs[t].dirty>>hr)&1)) {
4497             if((i_dirty>>hr)&1) {
4498               assert(i_regmap[hr]<64);
4499               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4500                 emit_storereg(i_regmap[hr],hr);
4501             }
4502           }
4503         }
4504       }
4505     }
4506   }
4507   else
4508   {
4509     // Branch out of this block, write out all dirty regs
4510     wb_dirtys(i_regmap,i_dirty);
4511   }
4512 }
4513
4514 // Load all needed registers for branch target
4515 static void load_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4516 {
4517   //if(addr>=start && addr<(start+slen*4))
4518   if(internal_branch(addr))
4519   {
4520     int t=(addr-start)>>2;
4521     int hr;
4522     // Store the cycle count before loading something else
4523     if(i_regmap[HOST_CCREG]!=CCREG) {
4524       assert(i_regmap[HOST_CCREG]==-1);
4525     }
4526     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4527       emit_storereg(CCREG,HOST_CCREG);
4528     }
4529     // Load 32-bit regs
4530     for(hr=0;hr<HOST_REGS;hr++) {
4531       if(hr!=EXCLUDE_REG&&regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4532         if(i_regmap[hr]!=regs[t].regmap_entry[hr]) {
4533           if(regs[t].regmap_entry[hr]==0) {
4534             emit_zeroreg(hr);
4535           }
4536           else if(regs[t].regmap_entry[hr]!=CCREG)
4537           {
4538             emit_loadreg(regs[t].regmap_entry[hr],hr);
4539           }
4540         }
4541       }
4542     }
4543   }
4544 }
4545
4546 static int match_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4547 {
4548   if(addr>=start && addr<start+slen*4-4)
4549   {
4550     int t=(addr-start)>>2;
4551     int hr;
4552     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) return 0;
4553     for(hr=0;hr<HOST_REGS;hr++)
4554     {
4555       if(hr!=EXCLUDE_REG)
4556       {
4557         if(i_regmap[hr]!=regs[t].regmap_entry[hr])
4558         {
4559           if(regs[t].regmap_entry[hr]>=0&&(regs[t].regmap_entry[hr]|64)<TEMPREG+64)
4560           {
4561             return 0;
4562           }
4563           else
4564           if((i_dirty>>hr)&1)
4565           {
4566             if(i_regmap[hr]<TEMPREG)
4567             {
4568               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4569                 return 0;
4570             }
4571             else if(i_regmap[hr]>=64&&i_regmap[hr]<TEMPREG+64)
4572             {
4573               assert(0);
4574             }
4575           }
4576         }
4577         else // Same register but is it 32-bit or dirty?
4578         if(i_regmap[hr]>=0)
4579         {
4580           if(!((regs[t].dirty>>hr)&1))
4581           {
4582             if((i_dirty>>hr)&1)
4583             {
4584               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4585               {
4586                 //printf("%x: dirty no match\n",addr);
4587                 return 0;
4588               }
4589             }
4590           }
4591         }
4592       }
4593     }
4594     // Delay slots are not valid branch targets
4595     //if(t>0&&(dops[t-1].is_jump) return 0;
4596     // Delay slots require additional processing, so do not match
4597     if(dops[t].is_ds) return 0;
4598   }
4599   else
4600   {
4601     int hr;
4602     for(hr=0;hr<HOST_REGS;hr++)
4603     {
4604       if(hr!=EXCLUDE_REG)
4605       {
4606         if(i_regmap[hr]>=0)
4607         {
4608           if(hr!=HOST_CCREG||i_regmap[hr]!=CCREG)
4609           {
4610             if((i_dirty>>hr)&1)
4611             {
4612               return 0;
4613             }
4614           }
4615         }
4616       }
4617     }
4618   }
4619   return 1;
4620 }
4621
4622 #ifdef DRC_DBG
4623 static void drc_dbg_emit_do_cmp(int i)
4624 {
4625   extern void do_insn_cmp();
4626   //extern int cycle;
4627   u_int hr, reglist = get_host_reglist(regs[i].regmap);
4628
4629   assem_debug("//do_insn_cmp %08x\n", start+i*4);
4630   save_regs(reglist);
4631   // write out changed consts to match the interpreter
4632   if (i > 0 && !dops[i].bt) {
4633     for (hr = 0; hr < HOST_REGS; hr++) {
4634       int reg = regs[i-1].regmap[hr];
4635       if (hr == EXCLUDE_REG || reg < 0)
4636         continue;
4637       if (!((regs[i-1].isconst >> hr) & 1))
4638         continue;
4639       if (i > 1 && reg == regs[i-2].regmap[hr] && constmap[i-1][hr] == constmap[i-2][hr])
4640         continue;
4641       emit_movimm(constmap[i-1][hr],0);
4642       emit_storereg(reg, 0);
4643     }
4644   }
4645   emit_movimm(start+i*4,0);
4646   emit_writeword(0,&pcaddr);
4647   emit_far_call(do_insn_cmp);
4648   //emit_readword(&cycle,0);
4649   //emit_addimm(0,2,0);
4650   //emit_writeword(0,&cycle);
4651   (void)get_reg2;
4652   restore_regs(reglist);
4653   assem_debug("\\\\do_insn_cmp\n");
4654 }
4655 #else
4656 #define drc_dbg_emit_do_cmp(x)
4657 #endif
4658
4659 // Used when a branch jumps into the delay slot of another branch
4660 static void ds_assemble_entry(int i)
4661 {
4662   int t=(ba[i]-start)>>2;
4663   if (!instr_addr[t])
4664     instr_addr[t] = out;
4665   assem_debug("Assemble delay slot at %x\n",ba[i]);
4666   assem_debug("<->\n");
4667   drc_dbg_emit_do_cmp(t);
4668   if(regs[t].regmap_entry[HOST_CCREG]==CCREG&&regs[t].regmap[HOST_CCREG]!=CCREG)
4669     wb_register(CCREG,regs[t].regmap_entry,regs[t].wasdirty);
4670   load_regs(regs[t].regmap_entry,regs[t].regmap,dops[t].rs1,dops[t].rs2);
4671   address_generation(t,&regs[t],regs[t].regmap_entry);
4672   if (ram_offset && (dops[t].is_load || dops[t].is_store))
4673     load_regs(regs[t].regmap_entry,regs[t].regmap,ROREG,ROREG);
4674   if (dops[t].is_store)
4675     load_regs(regs[t].regmap_entry,regs[t].regmap,INVCP,INVCP);
4676   is_delayslot=0;
4677   switch(dops[t].itype) {
4678     case ALU:
4679       alu_assemble(t,&regs[t]);break;
4680     case IMM16:
4681       imm16_assemble(t,&regs[t]);break;
4682     case SHIFT:
4683       shift_assemble(t,&regs[t]);break;
4684     case SHIFTIMM:
4685       shiftimm_assemble(t,&regs[t]);break;
4686     case LOAD:
4687       load_assemble(t,&regs[t]);break;
4688     case LOADLR:
4689       loadlr_assemble(t,&regs[t]);break;
4690     case STORE:
4691       store_assemble(t,&regs[t]);break;
4692     case STORELR:
4693       storelr_assemble(t,&regs[t]);break;
4694     case COP0:
4695       cop0_assemble(t,&regs[t]);break;
4696     case COP1:
4697       cop1_assemble(t,&regs[t]);break;
4698     case C1LS:
4699       c1ls_assemble(t,&regs[t]);break;
4700     case COP2:
4701       cop2_assemble(t,&regs[t]);break;
4702     case C2LS:
4703       c2ls_assemble(t,&regs[t]);break;
4704     case C2OP:
4705       c2op_assemble(t,&regs[t]);break;
4706     case MULTDIV:
4707       multdiv_assemble(t,&regs[t]);
4708       multdiv_prepare_stall(i,&regs[t]);
4709       break;
4710     case MOV:
4711       mov_assemble(t,&regs[t]);break;
4712     case SYSCALL:
4713     case HLECALL:
4714     case INTCALL:
4715     case SPAN:
4716     case UJUMP:
4717     case RJUMP:
4718     case CJUMP:
4719     case SJUMP:
4720       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4721   }
4722   store_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4723   load_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4724   if(internal_branch(ba[i]+4))
4725     assem_debug("branch: internal\n");
4726   else
4727     assem_debug("branch: external\n");
4728   assert(internal_branch(ba[i]+4));
4729   add_to_linker(out,ba[i]+4,internal_branch(ba[i]+4));
4730   emit_jmp(0);
4731 }
4732
4733 static void emit_extjump(void *addr, u_int target)
4734 {
4735   emit_extjump2(addr, target, dyna_linker);
4736 }
4737
4738 static void emit_extjump_ds(void *addr, u_int target)
4739 {
4740   emit_extjump2(addr, target, dyna_linker_ds);
4741 }
4742
4743 // Load 2 immediates optimizing for small code size
4744 static void emit_mov2imm_compact(int imm1,u_int rt1,int imm2,u_int rt2)
4745 {
4746   emit_movimm(imm1,rt1);
4747   emit_movimm_from(imm1,rt1,imm2,rt2);
4748 }
4749
4750 void do_cc(int i,signed char i_regmap[],int *adj,int addr,int taken,int invert)
4751 {
4752   int count;
4753   void *jaddr;
4754   void *idle=NULL;
4755   int t=0;
4756   if(dops[i].itype==RJUMP)
4757   {
4758     *adj=0;
4759   }
4760   //if(ba[i]>=start && ba[i]<(start+slen*4))
4761   if(internal_branch(ba[i]))
4762   {
4763     t=(ba[i]-start)>>2;
4764     if(dops[t].is_ds) *adj=-1; // Branch into delay slot adds an extra cycle
4765     else *adj=ccadj[t];
4766   }
4767   else
4768   {
4769     *adj=0;
4770   }
4771   count=ccadj[i];
4772   if(taken==TAKEN && i==(ba[i]-start)>>2 && source[i+1]==0) {
4773     // Idle loop
4774     if(count&1) emit_addimm_and_set_flags(2*(count+2),HOST_CCREG);
4775     idle=out;
4776     //emit_subfrommem(&idlecount,HOST_CCREG); // Count idle cycles
4777     emit_andimm(HOST_CCREG,3,HOST_CCREG);
4778     jaddr=out;
4779     emit_jmp(0);
4780   }
4781   else if(*adj==0||invert) {
4782     int cycles=CLOCK_ADJUST(count+2);
4783     // faster loop HACK
4784 #if 0
4785     if (t&&*adj) {
4786       int rel=t-i;
4787       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
4788         cycles=CLOCK_ADJUST(*adj)+count+2-*adj;
4789     }
4790 #endif
4791     emit_addimm_and_set_flags(cycles,HOST_CCREG);
4792     jaddr=out;
4793     emit_jns(0);
4794   }
4795   else
4796   {
4797     emit_cmpimm(HOST_CCREG,-CLOCK_ADJUST(count+2));
4798     jaddr=out;
4799     emit_jns(0);
4800   }
4801   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:(count+2),i,addr,taken,0);
4802 }
4803
4804 static void do_ccstub(int n)
4805 {
4806   literal_pool(256);
4807   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
4808   set_jump_target(stubs[n].addr, out);
4809   int i=stubs[n].b;
4810   if(stubs[n].d==NULLDS) {
4811     // Delay slot instruction is nullified ("likely" branch)
4812     wb_dirtys(regs[i].regmap,regs[i].dirty);
4813   }
4814   else if(stubs[n].d!=TAKEN) {
4815     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
4816   }
4817   else {
4818     if(internal_branch(ba[i]))
4819       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4820   }
4821   if(stubs[n].c!=-1)
4822   {
4823     // Save PC as return address
4824     emit_movimm(stubs[n].c,EAX);
4825     emit_writeword(EAX,&pcaddr);
4826   }
4827   else
4828   {
4829     // Return address depends on which way the branch goes
4830     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
4831     {
4832       int s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
4833       int s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
4834       if(dops[i].rs1==0)
4835       {
4836         s1l=s2l;
4837         s2l=-1;
4838       }
4839       else if(dops[i].rs2==0)
4840       {
4841         s2l=-1;
4842       }
4843       assert(s1l>=0);
4844       #ifdef DESTRUCTIVE_WRITEBACK
4845       if(dops[i].rs1) {
4846         if((branch_regs[i].dirty>>s1l)&&1)
4847           emit_loadreg(dops[i].rs1,s1l);
4848       }
4849       else {
4850         if((branch_regs[i].dirty>>s1l)&1)
4851           emit_loadreg(dops[i].rs2,s1l);
4852       }
4853       if(s2l>=0)
4854         if((branch_regs[i].dirty>>s2l)&1)
4855           emit_loadreg(dops[i].rs2,s2l);
4856       #endif
4857       int hr=0;
4858       int addr=-1,alt=-1,ntaddr=-1;
4859       while(hr<HOST_REGS)
4860       {
4861         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4862            (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4863            (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4864         {
4865           addr=hr++;break;
4866         }
4867         hr++;
4868       }
4869       while(hr<HOST_REGS)
4870       {
4871         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4872            (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4873            (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4874         {
4875           alt=hr++;break;
4876         }
4877         hr++;
4878       }
4879       if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
4880       {
4881         while(hr<HOST_REGS)
4882         {
4883           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4884              (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4885              (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4886           {
4887             ntaddr=hr;break;
4888           }
4889           hr++;
4890         }
4891         assert(hr<HOST_REGS);
4892       }
4893       if((dops[i].opcode&0x2f)==4) // BEQ
4894       {
4895         #ifdef HAVE_CMOV_IMM
4896         if(s2l>=0) emit_cmp(s1l,s2l);
4897         else emit_test(s1l,s1l);
4898         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
4899         #else
4900         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4901         if(s2l>=0) emit_cmp(s1l,s2l);
4902         else emit_test(s1l,s1l);
4903         emit_cmovne_reg(alt,addr);
4904         #endif
4905       }
4906       if((dops[i].opcode&0x2f)==5) // BNE
4907       {
4908         #ifdef HAVE_CMOV_IMM
4909         if(s2l>=0) emit_cmp(s1l,s2l);
4910         else emit_test(s1l,s1l);
4911         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
4912         #else
4913         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
4914         if(s2l>=0) emit_cmp(s1l,s2l);
4915         else emit_test(s1l,s1l);
4916         emit_cmovne_reg(alt,addr);
4917         #endif
4918       }
4919       if((dops[i].opcode&0x2f)==6) // BLEZ
4920       {
4921         //emit_movimm(ba[i],alt);
4922         //emit_movimm(start+i*4+8,addr);
4923         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4924         emit_cmpimm(s1l,1);
4925         emit_cmovl_reg(alt,addr);
4926       }
4927       if((dops[i].opcode&0x2f)==7) // BGTZ
4928       {
4929         //emit_movimm(ba[i],addr);
4930         //emit_movimm(start+i*4+8,ntaddr);
4931         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
4932         emit_cmpimm(s1l,1);
4933         emit_cmovl_reg(ntaddr,addr);
4934       }
4935       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==0) // BLTZ
4936       {
4937         //emit_movimm(ba[i],alt);
4938         //emit_movimm(start+i*4+8,addr);
4939         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4940         emit_test(s1l,s1l);
4941         emit_cmovs_reg(alt,addr);
4942       }
4943       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==1) // BGEZ
4944       {
4945         //emit_movimm(ba[i],addr);
4946         //emit_movimm(start+i*4+8,alt);
4947         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4948         emit_test(s1l,s1l);
4949         emit_cmovs_reg(alt,addr);
4950       }
4951       if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
4952         if(source[i]&0x10000) // BC1T
4953         {
4954           //emit_movimm(ba[i],alt);
4955           //emit_movimm(start+i*4+8,addr);
4956           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4957           emit_testimm(s1l,0x800000);
4958           emit_cmovne_reg(alt,addr);
4959         }
4960         else // BC1F
4961         {
4962           //emit_movimm(ba[i],addr);
4963           //emit_movimm(start+i*4+8,alt);
4964           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4965           emit_testimm(s1l,0x800000);
4966           emit_cmovne_reg(alt,addr);
4967         }
4968       }
4969       emit_writeword(addr,&pcaddr);
4970     }
4971     else
4972     if(dops[i].itype==RJUMP)
4973     {
4974       int r=get_reg(branch_regs[i].regmap,dops[i].rs1);
4975       if (ds_writes_rjump_rs(i)) {
4976         r=get_reg(branch_regs[i].regmap,RTEMP);
4977       }
4978       emit_writeword(r,&pcaddr);
4979     }
4980     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
4981   }
4982   // Update cycle count
4983   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
4984   if(stubs[n].a) emit_addimm(HOST_CCREG,CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4985   emit_far_call(cc_interrupt);
4986   if(stubs[n].a) emit_addimm(HOST_CCREG,-CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4987   if(stubs[n].d==TAKEN) {
4988     if(internal_branch(ba[i]))
4989       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
4990     else if(dops[i].itype==RJUMP) {
4991       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
4992         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
4993       else
4994         emit_loadreg(dops[i].rs1,get_reg(branch_regs[i].regmap,dops[i].rs1));
4995     }
4996   }else if(stubs[n].d==NOTTAKEN) {
4997     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
4998     else load_all_regs(branch_regs[i].regmap);
4999   }else if(stubs[n].d==NULLDS) {
5000     // Delay slot instruction is nullified ("likely" branch)
5001     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
5002     else load_all_regs(regs[i].regmap);
5003   }else{
5004     load_all_regs(branch_regs[i].regmap);
5005   }
5006   if (stubs[n].retaddr)
5007     emit_jmp(stubs[n].retaddr);
5008   else
5009     do_jump_vaddr(stubs[n].e);
5010 }
5011
5012 static void add_to_linker(void *addr, u_int target, int ext)
5013 {
5014   assert(linkcount < ARRAY_SIZE(link_addr));
5015   link_addr[linkcount].addr = addr;
5016   link_addr[linkcount].target = target;
5017   link_addr[linkcount].ext = ext;
5018   linkcount++;
5019 }
5020
5021 static void ujump_assemble_write_ra(int i)
5022 {
5023   int rt;
5024   unsigned int return_address;
5025   rt=get_reg(branch_regs[i].regmap,31);
5026   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]);
5027   //assert(rt>=0);
5028   return_address=start+i*4+8;
5029   if(rt>=0) {
5030     #ifdef USE_MINI_HT
5031     if(internal_branch(return_address)&&dops[i+1].rt1!=31) {
5032       int temp=-1; // note: must be ds-safe
5033       #ifdef HOST_TEMPREG
5034       temp=HOST_TEMPREG;
5035       #endif
5036       if(temp>=0) do_miniht_insert(return_address,rt,temp);
5037       else emit_movimm(return_address,rt);
5038     }
5039     else
5040     #endif
5041     {
5042       #ifdef REG_PREFETCH
5043       if(temp>=0)
5044       {
5045         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5046       }
5047       #endif
5048       emit_movimm(return_address,rt); // PC into link register
5049       #ifdef IMM_PREFETCH
5050       emit_prefetch(hash_table_get(return_address));
5051       #endif
5052     }
5053   }
5054 }
5055
5056 static void ujump_assemble(int i,struct regstat *i_regs)
5057 {
5058   int ra_done=0;
5059   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5060   address_generation(i+1,i_regs,regs[i].regmap_entry);
5061   #ifdef REG_PREFETCH
5062   int temp=get_reg(branch_regs[i].regmap,PTEMP);
5063   if(dops[i].rt1==31&&temp>=0)
5064   {
5065     signed char *i_regmap=i_regs->regmap;
5066     int return_address=start+i*4+8;
5067     if(get_reg(branch_regs[i].regmap,31)>0)
5068     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5069   }
5070   #endif
5071   if(dops[i].rt1==31&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5072     ujump_assemble_write_ra(i); // writeback ra for DS
5073     ra_done=1;
5074   }
5075   ds_assemble(i+1,i_regs);
5076   uint64_t bc_unneeded=branch_regs[i].u;
5077   bc_unneeded|=1|(1LL<<dops[i].rt1);
5078   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5079   load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5080   if(!ra_done&&dops[i].rt1==31)
5081     ujump_assemble_write_ra(i);
5082   int cc,adj;
5083   cc=get_reg(branch_regs[i].regmap,CCREG);
5084   assert(cc==HOST_CCREG);
5085   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5086   #ifdef REG_PREFETCH
5087   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5088   #endif
5089   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5090   if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5091   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5092   if(internal_branch(ba[i]))
5093     assem_debug("branch: internal\n");
5094   else
5095     assem_debug("branch: external\n");
5096   if (internal_branch(ba[i]) && dops[(ba[i]-start)>>2].is_ds) {
5097     ds_assemble_entry(i);
5098   }
5099   else {
5100     add_to_linker(out,ba[i],internal_branch(ba[i]));
5101     emit_jmp(0);
5102   }
5103 }
5104
5105 static void rjump_assemble_write_ra(int i)
5106 {
5107   int rt,return_address;
5108   assert(dops[i+1].rt1!=dops[i].rt1);
5109   assert(dops[i+1].rt2!=dops[i].rt1);
5110   rt=get_reg(branch_regs[i].regmap,dops[i].rt1);
5111   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]);
5112   assert(rt>=0);
5113   return_address=start+i*4+8;
5114   #ifdef REG_PREFETCH
5115   if(temp>=0)
5116   {
5117     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5118   }
5119   #endif
5120   emit_movimm(return_address,rt); // PC into link register
5121   #ifdef IMM_PREFETCH
5122   emit_prefetch(hash_table_get(return_address));
5123   #endif
5124 }
5125
5126 static void rjump_assemble(int i,struct regstat *i_regs)
5127 {
5128   int temp;
5129   int rs,cc;
5130   int ra_done=0;
5131   rs=get_reg(branch_regs[i].regmap,dops[i].rs1);
5132   assert(rs>=0);
5133   if (ds_writes_rjump_rs(i)) {
5134     // Delay slot abuse, make a copy of the branch address register
5135     temp=get_reg(branch_regs[i].regmap,RTEMP);
5136     assert(temp>=0);
5137     assert(regs[i].regmap[temp]==RTEMP);
5138     emit_mov(rs,temp);
5139     rs=temp;
5140   }
5141   address_generation(i+1,i_regs,regs[i].regmap_entry);
5142   #ifdef REG_PREFETCH
5143   if(dops[i].rt1==31)
5144   {
5145     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
5146       signed char *i_regmap=i_regs->regmap;
5147       int return_address=start+i*4+8;
5148       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5149     }
5150   }
5151   #endif
5152   #ifdef USE_MINI_HT
5153   if(dops[i].rs1==31) {
5154     int rh=get_reg(regs[i].regmap,RHASH);
5155     if(rh>=0) do_preload_rhash(rh);
5156   }
5157   #endif
5158   if(dops[i].rt1!=0&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5159     rjump_assemble_write_ra(i);
5160     ra_done=1;
5161   }
5162   ds_assemble(i+1,i_regs);
5163   uint64_t bc_unneeded=branch_regs[i].u;
5164   bc_unneeded|=1|(1LL<<dops[i].rt1);
5165   bc_unneeded&=~(1LL<<dops[i].rs1);
5166   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5167   load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,CCREG);
5168   if(!ra_done&&dops[i].rt1!=0)
5169     rjump_assemble_write_ra(i);
5170   cc=get_reg(branch_regs[i].regmap,CCREG);
5171   assert(cc==HOST_CCREG);
5172   (void)cc;
5173   #ifdef USE_MINI_HT
5174   int rh=get_reg(branch_regs[i].regmap,RHASH);
5175   int ht=get_reg(branch_regs[i].regmap,RHTBL);
5176   if(dops[i].rs1==31) {
5177     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
5178     do_preload_rhtbl(ht);
5179     do_rhash(rs,rh);
5180   }
5181   #endif
5182   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5183   #ifdef DESTRUCTIVE_WRITEBACK
5184   if((branch_regs[i].dirty>>rs)&1) {
5185     if(dops[i].rs1!=dops[i+1].rt1&&dops[i].rs1!=dops[i+1].rt2) {
5186       emit_loadreg(dops[i].rs1,rs);
5187     }
5188   }
5189   #endif
5190   #ifdef REG_PREFETCH
5191   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5192   #endif
5193   #ifdef USE_MINI_HT
5194   if(dops[i].rs1==31) {
5195     do_miniht_load(ht,rh);
5196   }
5197   #endif
5198   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
5199   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
5200   //assert(adj==0);
5201   emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5202   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
5203   if(dops[i+1].itype==COP0&&(source[i+1]&0x3f)==0x10)
5204     // special case for RFE
5205     emit_jmp(0);
5206   else
5207     emit_jns(0);
5208   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5209   #ifdef USE_MINI_HT
5210   if(dops[i].rs1==31) {
5211     do_miniht_jump(rs,rh,ht);
5212   }
5213   else
5214   #endif
5215   {
5216     do_jump_vaddr(rs);
5217   }
5218   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5219   if(dops[i].rt1!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
5220   #endif
5221 }
5222
5223 static void cjump_assemble(int i,struct regstat *i_regs)
5224 {
5225   signed char *i_regmap=i_regs->regmap;
5226   int cc;
5227   int match;
5228   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5229   assem_debug("match=%d\n",match);
5230   int s1l,s2l;
5231   int unconditional=0,nop=0;
5232   int invert=0;
5233   int internal=internal_branch(ba[i]);
5234   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5235   if(!match) invert=1;
5236   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5237   if(i>(ba[i]-start)>>2) invert=1;
5238   #endif
5239   #ifdef __aarch64__
5240   invert=1; // because of near cond. branches
5241   #endif
5242
5243   if(dops[i].ooo) {
5244     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5245     s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
5246   }
5247   else {
5248     s1l=get_reg(i_regmap,dops[i].rs1);
5249     s2l=get_reg(i_regmap,dops[i].rs2);
5250   }
5251   if(dops[i].rs1==0&&dops[i].rs2==0)
5252   {
5253     if(dops[i].opcode&1) nop=1;
5254     else unconditional=1;
5255     //assert(dops[i].opcode!=5);
5256     //assert(dops[i].opcode!=7);
5257     //assert(dops[i].opcode!=0x15);
5258     //assert(dops[i].opcode!=0x17);
5259   }
5260   else if(dops[i].rs1==0)
5261   {
5262     s1l=s2l;
5263     s2l=-1;
5264   }
5265   else if(dops[i].rs2==0)
5266   {
5267     s2l=-1;
5268   }
5269
5270   if(dops[i].ooo) {
5271     // Out of order execution (delay slot first)
5272     //printf("OOOE\n");
5273     address_generation(i+1,i_regs,regs[i].regmap_entry);
5274     ds_assemble(i+1,i_regs);
5275     int adj;
5276     uint64_t bc_unneeded=branch_regs[i].u;
5277     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5278     bc_unneeded|=1;
5279     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5280     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs2);
5281     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5282     cc=get_reg(branch_regs[i].regmap,CCREG);
5283     assert(cc==HOST_CCREG);
5284     if(unconditional)
5285       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5286     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5287     //assem_debug("cycle count (adj)\n");
5288     if(unconditional) {
5289       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5290       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5291         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5292         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5293         if(internal)
5294           assem_debug("branch: internal\n");
5295         else
5296           assem_debug("branch: external\n");
5297         if (internal && dops[(ba[i]-start)>>2].is_ds) {
5298           ds_assemble_entry(i);
5299         }
5300         else {
5301           add_to_linker(out,ba[i],internal);
5302           emit_jmp(0);
5303         }
5304         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5305         if(((u_int)out)&7) emit_addnop(0);
5306         #endif
5307       }
5308     }
5309     else if(nop) {
5310       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5311       void *jaddr=out;
5312       emit_jns(0);
5313       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5314     }
5315     else {
5316       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5317       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5318       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5319
5320       //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]);
5321       assert(s1l>=0);
5322       if(dops[i].opcode==4) // BEQ
5323       {
5324         if(s2l>=0) emit_cmp(s1l,s2l);
5325         else emit_test(s1l,s1l);
5326         if(invert){
5327           nottaken=out;
5328           emit_jne(DJT_1);
5329         }else{
5330           add_to_linker(out,ba[i],internal);
5331           emit_jeq(0);
5332         }
5333       }
5334       if(dops[i].opcode==5) // BNE
5335       {
5336         if(s2l>=0) emit_cmp(s1l,s2l);
5337         else emit_test(s1l,s1l);
5338         if(invert){
5339           nottaken=out;
5340           emit_jeq(DJT_1);
5341         }else{
5342           add_to_linker(out,ba[i],internal);
5343           emit_jne(0);
5344         }
5345       }
5346       if(dops[i].opcode==6) // BLEZ
5347       {
5348         emit_cmpimm(s1l,1);
5349         if(invert){
5350           nottaken=out;
5351           emit_jge(DJT_1);
5352         }else{
5353           add_to_linker(out,ba[i],internal);
5354           emit_jl(0);
5355         }
5356       }
5357       if(dops[i].opcode==7) // BGTZ
5358       {
5359         emit_cmpimm(s1l,1);
5360         if(invert){
5361           nottaken=out;
5362           emit_jl(DJT_1);
5363         }else{
5364           add_to_linker(out,ba[i],internal);
5365           emit_jge(0);
5366         }
5367       }
5368       if(invert) {
5369         if(taken) set_jump_target(taken, out);
5370         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5371         if (match && (!internal || !dops[(ba[i]-start)>>2].is_ds)) {
5372           if(adj) {
5373             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5374             add_to_linker(out,ba[i],internal);
5375           }else{
5376             emit_addnop(13);
5377             add_to_linker(out,ba[i],internal*2);
5378           }
5379           emit_jmp(0);
5380         }else
5381         #endif
5382         {
5383           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5384           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5385           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5386           if(internal)
5387             assem_debug("branch: internal\n");
5388           else
5389             assem_debug("branch: external\n");
5390           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5391             ds_assemble_entry(i);
5392           }
5393           else {
5394             add_to_linker(out,ba[i],internal);
5395             emit_jmp(0);
5396           }
5397         }
5398         set_jump_target(nottaken, out);
5399       }
5400
5401       if(nottaken1) set_jump_target(nottaken1, out);
5402       if(adj) {
5403         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5404       }
5405     } // (!unconditional)
5406   } // if(ooo)
5407   else
5408   {
5409     // In-order execution (branch first)
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((dops[i].opcode&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((dops[i].opcode&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((dops[i].opcode&0x2f)==6) // BLEZ
5429       {
5430         emit_cmpimm(s1l,1);
5431         nottaken=out;
5432         emit_jge(DJT_2);
5433       }
5434       if((dops[i].opcode&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<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
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,dops[i+1].rs1,dops[i+1].rs2);
5452       address_generation(i+1,&branch_regs[i],0);
5453       if (ram_offset)
5454         load_regs(regs[i].regmap,branch_regs[i].regmap,ROREG,ROREG);
5455       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5456       ds_assemble(i+1,&branch_regs[i]);
5457       cc=get_reg(branch_regs[i].regmap,CCREG);
5458       if(cc==-1) {
5459         emit_loadreg(CCREG,cc=HOST_CCREG);
5460         // CHECK: Is the following instruction (fall thru) allocated ok?
5461       }
5462       assert(cc==HOST_CCREG);
5463       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5464       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5465       assem_debug("cycle count (adj)\n");
5466       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5467       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5468       if(internal)
5469         assem_debug("branch: internal\n");
5470       else
5471         assem_debug("branch: external\n");
5472       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5473         ds_assemble_entry(i);
5474       }
5475       else {
5476         add_to_linker(out,ba[i],internal);
5477         emit_jmp(0);
5478       }
5479     }
5480     // branch not taken
5481     if(!unconditional) {
5482       if(nottaken1) set_jump_target(nottaken1, out);
5483       set_jump_target(nottaken, out);
5484       assem_debug("2:\n");
5485       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5486       // load regs
5487       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5488       address_generation(i+1,&branch_regs[i],0);
5489       if (ram_offset)
5490         load_regs(regs[i].regmap,branch_regs[i].regmap,ROREG,ROREG);
5491       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5492       ds_assemble(i+1,&branch_regs[i]);
5493       cc=get_reg(branch_regs[i].regmap,CCREG);
5494       if (cc == -1) {
5495         // Cycle count isn't in a register, temporarily load it then write it out
5496         emit_loadreg(CCREG,HOST_CCREG);
5497         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5498         void *jaddr=out;
5499         emit_jns(0);
5500         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5501         emit_storereg(CCREG,HOST_CCREG);
5502       }
5503       else{
5504         cc=get_reg(i_regmap,CCREG);
5505         assert(cc==HOST_CCREG);
5506         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5507         void *jaddr=out;
5508         emit_jns(0);
5509         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5510       }
5511     }
5512   }
5513 }
5514
5515 static void sjump_assemble(int i,struct regstat *i_regs)
5516 {
5517   signed char *i_regmap=i_regs->regmap;
5518   int cc;
5519   int match;
5520   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5521   assem_debug("smatch=%d\n",match);
5522   int s1l;
5523   int unconditional=0,nevertaken=0;
5524   int invert=0;
5525   int internal=internal_branch(ba[i]);
5526   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5527   if(!match) invert=1;
5528   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5529   if(i>(ba[i]-start)>>2) invert=1;
5530   #endif
5531   #ifdef __aarch64__
5532   invert=1; // because of near cond. branches
5533   #endif
5534
5535   //if(dops[i].opcode2>=0x10) return; // FIXME (BxxZAL)
5536   //assert(dops[i].opcode2<0x10||dops[i].rs1==0); // FIXME (BxxZAL)
5537
5538   if(dops[i].ooo) {
5539     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5540   }
5541   else {
5542     s1l=get_reg(i_regmap,dops[i].rs1);
5543   }
5544   if(dops[i].rs1==0)
5545   {
5546     if(dops[i].opcode2&1) unconditional=1;
5547     else nevertaken=1;
5548     // These are never taken (r0 is never less than zero)
5549     //assert(dops[i].opcode2!=0);
5550     //assert(dops[i].opcode2!=2);
5551     //assert(dops[i].opcode2!=0x10);
5552     //assert(dops[i].opcode2!=0x12);
5553   }
5554
5555   if(dops[i].ooo) {
5556     // Out of order execution (delay slot first)
5557     //printf("OOOE\n");
5558     address_generation(i+1,i_regs,regs[i].regmap_entry);
5559     ds_assemble(i+1,i_regs);
5560     int adj;
5561     uint64_t bc_unneeded=branch_regs[i].u;
5562     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5563     bc_unneeded|=1;
5564     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5565     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs1);
5566     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5567     if(dops[i].rt1==31) {
5568       int rt,return_address;
5569       rt=get_reg(branch_regs[i].regmap,31);
5570       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]);
5571       if(rt>=0) {
5572         // Save the PC even if the branch is not taken
5573         return_address=start+i*4+8;
5574         emit_movimm(return_address,rt); // PC into link register
5575         #ifdef IMM_PREFETCH
5576         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5577         #endif
5578       }
5579     }
5580     cc=get_reg(branch_regs[i].regmap,CCREG);
5581     assert(cc==HOST_CCREG);
5582     if(unconditional)
5583       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5584     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5585     assem_debug("cycle count (adj)\n");
5586     if(unconditional) {
5587       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5588       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5589         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5590         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5591         if(internal)
5592           assem_debug("branch: internal\n");
5593         else
5594           assem_debug("branch: external\n");
5595         if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5596           ds_assemble_entry(i);
5597         }
5598         else {
5599           add_to_linker(out,ba[i],internal);
5600           emit_jmp(0);
5601         }
5602         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5603         if(((u_int)out)&7) emit_addnop(0);
5604         #endif
5605       }
5606     }
5607     else if(nevertaken) {
5608       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5609       void *jaddr=out;
5610       emit_jns(0);
5611       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5612     }
5613     else {
5614       void *nottaken = NULL;
5615       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5616       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5617       {
5618         assert(s1l>=0);
5619         if((dops[i].opcode2&0xf)==0) // BLTZ/BLTZAL
5620         {
5621           emit_test(s1l,s1l);
5622           if(invert){
5623             nottaken=out;
5624             emit_jns(DJT_1);
5625           }else{
5626             add_to_linker(out,ba[i],internal);
5627             emit_js(0);
5628           }
5629         }
5630         if((dops[i].opcode2&0xf)==1) // BGEZ/BLTZAL
5631         {
5632           emit_test(s1l,s1l);
5633           if(invert){
5634             nottaken=out;
5635             emit_js(DJT_1);
5636           }else{
5637             add_to_linker(out,ba[i],internal);
5638             emit_jns(0);
5639           }
5640         }
5641       }
5642
5643       if(invert) {
5644         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5645         if (match && (!internal || !dops[(ba[i] - start) >> 2].is_ds)) {
5646           if(adj) {
5647             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5648             add_to_linker(out,ba[i],internal);
5649           }else{
5650             emit_addnop(13);
5651             add_to_linker(out,ba[i],internal*2);
5652           }
5653           emit_jmp(0);
5654         }else
5655         #endif
5656         {
5657           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5658           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5659           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5660           if(internal)
5661             assem_debug("branch: internal\n");
5662           else
5663             assem_debug("branch: external\n");
5664           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5665             ds_assemble_entry(i);
5666           }
5667           else {
5668             add_to_linker(out,ba[i],internal);
5669             emit_jmp(0);
5670           }
5671         }
5672         set_jump_target(nottaken, out);
5673       }
5674
5675       if(adj) {
5676         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5677       }
5678     } // (!unconditional)
5679   } // if(ooo)
5680   else
5681   {
5682     // In-order execution (branch first)
5683     //printf("IOE\n");
5684     void *nottaken = NULL;
5685     if(dops[i].rt1==31) {
5686       int rt,return_address;
5687       rt=get_reg(branch_regs[i].regmap,31);
5688       if(rt>=0) {
5689         // Save the PC even if the branch is not taken
5690         return_address=start+i*4+8;
5691         emit_movimm(return_address,rt); // PC into link register
5692         #ifdef IMM_PREFETCH
5693         emit_prefetch(hash_table_get(return_address));
5694         #endif
5695       }
5696     }
5697     if(!unconditional) {
5698       //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]);
5699         assert(s1l>=0);
5700         if((dops[i].opcode2&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5701         {
5702           emit_test(s1l,s1l);
5703           nottaken=out;
5704           emit_jns(DJT_1);
5705         }
5706         if((dops[i].opcode2&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5707         {
5708           emit_test(s1l,s1l);
5709           nottaken=out;
5710           emit_js(DJT_1);
5711         }
5712     } // if(!unconditional)
5713     int adj;
5714     uint64_t ds_unneeded=branch_regs[i].u;
5715     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5716     ds_unneeded|=1;
5717     // branch taken
5718     if(!nevertaken) {
5719       //assem_debug("1:\n");
5720       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5721       // load regs
5722       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5723       address_generation(i+1,&branch_regs[i],0);
5724       if (ram_offset)
5725         load_regs(regs[i].regmap,branch_regs[i].regmap,ROREG,ROREG);
5726       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5727       ds_assemble(i+1,&branch_regs[i]);
5728       cc=get_reg(branch_regs[i].regmap,CCREG);
5729       if(cc==-1) {
5730         emit_loadreg(CCREG,cc=HOST_CCREG);
5731         // CHECK: Is the following instruction (fall thru) allocated ok?
5732       }
5733       assert(cc==HOST_CCREG);
5734       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5735       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5736       assem_debug("cycle count (adj)\n");
5737       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5738       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5739       if(internal)
5740         assem_debug("branch: internal\n");
5741       else
5742         assem_debug("branch: external\n");
5743       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5744         ds_assemble_entry(i);
5745       }
5746       else {
5747         add_to_linker(out,ba[i],internal);
5748         emit_jmp(0);
5749       }
5750     }
5751     // branch not taken
5752     if(!unconditional) {
5753       set_jump_target(nottaken, out);
5754       assem_debug("1:\n");
5755       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5756       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5757       address_generation(i+1,&branch_regs[i],0);
5758       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5759       ds_assemble(i+1,&branch_regs[i]);
5760       cc=get_reg(branch_regs[i].regmap,CCREG);
5761       if (cc == -1) {
5762         // Cycle count isn't in a register, temporarily load it then write it out
5763         emit_loadreg(CCREG,HOST_CCREG);
5764         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5765         void *jaddr=out;
5766         emit_jns(0);
5767         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5768         emit_storereg(CCREG,HOST_CCREG);
5769       }
5770       else{
5771         cc=get_reg(i_regmap,CCREG);
5772         assert(cc==HOST_CCREG);
5773         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5774         void *jaddr=out;
5775         emit_jns(0);
5776         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5777       }
5778     }
5779   }
5780 }
5781
5782 static void pagespan_assemble(int i,struct regstat *i_regs)
5783 {
5784   int s1l=get_reg(i_regs->regmap,dops[i].rs1);
5785   int s2l=get_reg(i_regs->regmap,dops[i].rs2);
5786   void *taken = NULL;
5787   void *nottaken = NULL;
5788   int unconditional=0;
5789   if(dops[i].rs1==0)
5790   {
5791     s1l=s2l;
5792     s2l=-1;
5793   }
5794   else if(dops[i].rs2==0)
5795   {
5796     s2l=-1;
5797   }
5798   int hr=0;
5799   int addr=-1,alt=-1,ntaddr=-1;
5800   if(i_regs->regmap[HOST_BTREG]<0) {addr=HOST_BTREG;}
5801   else {
5802     while(hr<HOST_REGS)
5803     {
5804       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5805          (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5806          (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5807       {
5808         addr=hr++;break;
5809       }
5810       hr++;
5811     }
5812   }
5813   while(hr<HOST_REGS)
5814   {
5815     if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5816        (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5817        (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5818     {
5819       alt=hr++;break;
5820     }
5821     hr++;
5822   }
5823   if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
5824   {
5825     while(hr<HOST_REGS)
5826     {
5827       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5828          (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5829          (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5830       {
5831         ntaddr=hr;break;
5832       }
5833       hr++;
5834     }
5835   }
5836   assert(hr<HOST_REGS);
5837   if((dops[i].opcode&0x2e)==4||dops[i].opcode==0x11) { // BEQ/BNE/BEQL/BNEL/BC1
5838     load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
5839   }
5840   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5841   if(dops[i].opcode==2) // J
5842   {
5843     unconditional=1;
5844   }
5845   if(dops[i].opcode==3) // JAL
5846   {
5847     // TODO: mini_ht
5848     int rt=get_reg(i_regs->regmap,31);
5849     emit_movimm(start+i*4+8,rt);
5850     unconditional=1;
5851   }
5852   if(dops[i].opcode==0&&(dops[i].opcode2&0x3E)==8) // JR/JALR
5853   {
5854     emit_mov(s1l,addr);
5855     if(dops[i].opcode2==9) // JALR
5856     {
5857       int rt=get_reg(i_regs->regmap,dops[i].rt1);
5858       emit_movimm(start+i*4+8,rt);
5859     }
5860   }
5861   if((dops[i].opcode&0x3f)==4) // BEQ
5862   {
5863     if(dops[i].rs1==dops[i].rs2)
5864     {
5865       unconditional=1;
5866     }
5867     else
5868     #ifdef HAVE_CMOV_IMM
5869     if(1) {
5870       if(s2l>=0) emit_cmp(s1l,s2l);
5871       else emit_test(s1l,s1l);
5872       emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5873     }
5874     else
5875     #endif
5876     {
5877       assert(s1l>=0);
5878       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5879       if(s2l>=0) emit_cmp(s1l,s2l);
5880       else emit_test(s1l,s1l);
5881       emit_cmovne_reg(alt,addr);
5882     }
5883   }
5884   if((dops[i].opcode&0x3f)==5) // BNE
5885   {
5886     #ifdef HAVE_CMOV_IMM
5887     if(s2l>=0) emit_cmp(s1l,s2l);
5888     else emit_test(s1l,s1l);
5889     emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5890     #else
5891     assert(s1l>=0);
5892     emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5893     if(s2l>=0) emit_cmp(s1l,s2l);
5894     else emit_test(s1l,s1l);
5895     emit_cmovne_reg(alt,addr);
5896     #endif
5897   }
5898   if((dops[i].opcode&0x3f)==0x14) // BEQL
5899   {
5900     if(s2l>=0) emit_cmp(s1l,s2l);
5901     else emit_test(s1l,s1l);
5902     if(nottaken) set_jump_target(nottaken, out);
5903     nottaken=out;
5904     emit_jne(0);
5905   }
5906   if((dops[i].opcode&0x3f)==0x15) // BNEL
5907   {
5908     if(s2l>=0) emit_cmp(s1l,s2l);
5909     else emit_test(s1l,s1l);
5910     nottaken=out;
5911     emit_jeq(0);
5912     if(taken) set_jump_target(taken, out);
5913   }
5914   if((dops[i].opcode&0x3f)==6) // BLEZ
5915   {
5916     emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5917     emit_cmpimm(s1l,1);
5918     emit_cmovl_reg(alt,addr);
5919   }
5920   if((dops[i].opcode&0x3f)==7) // BGTZ
5921   {
5922     emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5923     emit_cmpimm(s1l,1);
5924     emit_cmovl_reg(ntaddr,addr);
5925   }
5926   if((dops[i].opcode&0x3f)==0x16) // BLEZL
5927   {
5928     assert((dops[i].opcode&0x3f)!=0x16);
5929   }
5930   if((dops[i].opcode&0x3f)==0x17) // BGTZL
5931   {
5932     assert((dops[i].opcode&0x3f)!=0x17);
5933   }
5934   assert(dops[i].opcode!=1); // BLTZ/BGEZ
5935
5936   //FIXME: Check CSREG
5937   if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
5938     if((source[i]&0x30000)==0) // BC1F
5939     {
5940       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5941       emit_testimm(s1l,0x800000);
5942       emit_cmovne_reg(alt,addr);
5943     }
5944     if((source[i]&0x30000)==0x10000) // BC1T
5945     {
5946       emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5947       emit_testimm(s1l,0x800000);
5948       emit_cmovne_reg(alt,addr);
5949     }
5950     if((source[i]&0x30000)==0x20000) // BC1FL
5951     {
5952       emit_testimm(s1l,0x800000);
5953       nottaken=out;
5954       emit_jne(0);
5955     }
5956     if((source[i]&0x30000)==0x30000) // BC1TL
5957     {
5958       emit_testimm(s1l,0x800000);
5959       nottaken=out;
5960       emit_jeq(0);
5961     }
5962   }
5963
5964   assert(i_regs->regmap[HOST_CCREG]==CCREG);
5965   wb_dirtys(regs[i].regmap,regs[i].dirty);
5966   if(unconditional)
5967   {
5968     emit_movimm(ba[i],HOST_BTREG);
5969   }
5970   else if(addr!=HOST_BTREG)
5971   {
5972     emit_mov(addr,HOST_BTREG);
5973   }
5974   void *branch_addr=out;
5975   emit_jmp(0);
5976   int target_addr=start+i*4+5;
5977   void *stub=out;
5978   void *compiled_target_addr=check_addr(target_addr);
5979   emit_extjump_ds(branch_addr, target_addr);
5980   if(compiled_target_addr) {
5981     set_jump_target(branch_addr, compiled_target_addr);
5982     add_jump_out(target_addr,stub);
5983   }
5984   else set_jump_target(branch_addr, stub);
5985 }
5986
5987 // Assemble the delay slot for the above
5988 static void pagespan_ds()
5989 {
5990   assem_debug("initial delay slot:\n");
5991   u_int vaddr=start+1;
5992   u_int page=get_page(vaddr);
5993   u_int vpage=get_vpage(vaddr);
5994   ll_add(jump_dirty+vpage,vaddr,(void *)out);
5995   do_dirty_stub_ds(slen*4);
5996   ll_add(jump_in+page,vaddr,(void *)out);
5997   assert(regs[0].regmap_entry[HOST_CCREG]==CCREG);
5998   if(regs[0].regmap[HOST_CCREG]!=CCREG)
5999     wb_register(CCREG,regs[0].regmap_entry,regs[0].wasdirty);
6000   if(regs[0].regmap[HOST_BTREG]!=BTREG)
6001     emit_writeword(HOST_BTREG,&branch_target);
6002   load_regs(regs[0].regmap_entry,regs[0].regmap,dops[0].rs1,dops[0].rs2);
6003   address_generation(0,&regs[0],regs[0].regmap_entry);
6004   if (ram_offset && (dops[0].is_load || dops[0].is_store))
6005     load_regs(regs[0].regmap_entry,regs[0].regmap,ROREG,ROREG);
6006   if (dops[0].is_store)
6007     load_regs(regs[0].regmap_entry,regs[0].regmap,INVCP,INVCP);
6008   is_delayslot=0;
6009   switch(dops[0].itype) {
6010     case ALU:
6011       alu_assemble(0,&regs[0]);break;
6012     case IMM16:
6013       imm16_assemble(0,&regs[0]);break;
6014     case SHIFT:
6015       shift_assemble(0,&regs[0]);break;
6016     case SHIFTIMM:
6017       shiftimm_assemble(0,&regs[0]);break;
6018     case LOAD:
6019       load_assemble(0,&regs[0]);break;
6020     case LOADLR:
6021       loadlr_assemble(0,&regs[0]);break;
6022     case STORE:
6023       store_assemble(0,&regs[0]);break;
6024     case STORELR:
6025       storelr_assemble(0,&regs[0]);break;
6026     case COP0:
6027       cop0_assemble(0,&regs[0]);break;
6028     case COP1:
6029       cop1_assemble(0,&regs[0]);break;
6030     case C1LS:
6031       c1ls_assemble(0,&regs[0]);break;
6032     case COP2:
6033       cop2_assemble(0,&regs[0]);break;
6034     case C2LS:
6035       c2ls_assemble(0,&regs[0]);break;
6036     case C2OP:
6037       c2op_assemble(0,&regs[0]);break;
6038     case MULTDIV:
6039       multdiv_assemble(0,&regs[0]);
6040       multdiv_prepare_stall(0,&regs[0]);
6041       break;
6042     case MOV:
6043       mov_assemble(0,&regs[0]);break;
6044     case SYSCALL:
6045     case HLECALL:
6046     case INTCALL:
6047     case SPAN:
6048     case UJUMP:
6049     case RJUMP:
6050     case CJUMP:
6051     case SJUMP:
6052       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
6053   }
6054   int btaddr=get_reg(regs[0].regmap,BTREG);
6055   if(btaddr<0) {
6056     btaddr=get_reg(regs[0].regmap,-1);
6057     emit_readword(&branch_target,btaddr);
6058   }
6059   assert(btaddr!=HOST_CCREG);
6060   if(regs[0].regmap[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
6061 #ifdef HOST_IMM8
6062   host_tempreg_acquire();
6063   emit_movimm(start+4,HOST_TEMPREG);
6064   emit_cmp(btaddr,HOST_TEMPREG);
6065   host_tempreg_release();
6066 #else
6067   emit_cmpimm(btaddr,start+4);
6068 #endif
6069   void *branch = out;
6070   emit_jeq(0);
6071   store_regs_bt(regs[0].regmap,regs[0].dirty,-1);
6072   do_jump_vaddr(btaddr);
6073   set_jump_target(branch, out);
6074   store_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6075   load_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6076 }
6077
6078 // Basic liveness analysis for MIPS registers
6079 void unneeded_registers(int istart,int iend,int r)
6080 {
6081   int i;
6082   uint64_t u,gte_u,b,gte_b;
6083   uint64_t temp_u,temp_gte_u=0;
6084   uint64_t gte_u_unknown=0;
6085   if (HACK_ENABLED(NDHACK_GTE_UNNEEDED))
6086     gte_u_unknown=~0ll;
6087   if(iend==slen-1) {
6088     u=1;
6089     gte_u=gte_u_unknown;
6090   }else{
6091     //u=unneeded_reg[iend+1];
6092     u=1;
6093     gte_u=gte_unneeded[iend+1];
6094   }
6095
6096   for (i=iend;i>=istart;i--)
6097   {
6098     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
6099     if(dops[i].is_jump)
6100     {
6101       // If subroutine call, flag return address as a possible branch target
6102       if(dops[i].rt1==31 && i<slen-2) dops[i+2].bt=1;
6103
6104       if(ba[i]<start || ba[i]>=(start+slen*4))
6105       {
6106         // Branch out of this block, flush all regs
6107         u=1;
6108         gte_u=gte_u_unknown;
6109         branch_unneeded_reg[i]=u;
6110         // Merge in delay slot
6111         u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6112         u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6113         u|=1;
6114         gte_u|=gte_rt[i+1];
6115         gte_u&=~gte_rs[i+1];
6116       }
6117       else
6118       {
6119         // Internal branch, flag target
6120         dops[(ba[i]-start)>>2].bt=1;
6121         if(ba[i]<=start+i*4) {
6122           // Backward branch
6123           if(dops[i].is_ujump)
6124           {
6125             // Unconditional branch
6126             temp_u=1;
6127             temp_gte_u=0;
6128           } else {
6129             // Conditional branch (not taken case)
6130             temp_u=unneeded_reg[i+2];
6131             temp_gte_u&=gte_unneeded[i+2];
6132           }
6133           // Merge in delay slot
6134           temp_u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6135           temp_u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6136           temp_u|=1;
6137           temp_gte_u|=gte_rt[i+1];
6138           temp_gte_u&=~gte_rs[i+1];
6139           temp_u|=(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2);
6140           temp_u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
6141           temp_u|=1;
6142           temp_gte_u|=gte_rt[i];
6143           temp_gte_u&=~gte_rs[i];
6144           unneeded_reg[i]=temp_u;
6145           gte_unneeded[i]=temp_gte_u;
6146           // Only go three levels deep.  This recursion can take an
6147           // excessive amount of time if there are a lot of nested loops.
6148           if(r<2) {
6149             unneeded_registers((ba[i]-start)>>2,i-1,r+1);
6150           }else{
6151             unneeded_reg[(ba[i]-start)>>2]=1;
6152             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
6153           }
6154         } /*else*/ if(1) {
6155           if (dops[i].is_ujump)
6156           {
6157             // Unconditional branch
6158             u=unneeded_reg[(ba[i]-start)>>2];
6159             gte_u=gte_unneeded[(ba[i]-start)>>2];
6160             branch_unneeded_reg[i]=u;
6161             // Merge in delay slot
6162             u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6163             u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6164             u|=1;
6165             gte_u|=gte_rt[i+1];
6166             gte_u&=~gte_rs[i+1];
6167           } else {
6168             // Conditional branch
6169             b=unneeded_reg[(ba[i]-start)>>2];
6170             gte_b=gte_unneeded[(ba[i]-start)>>2];
6171             branch_unneeded_reg[i]=b;
6172             // Branch delay slot
6173             b|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6174             b&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6175             b|=1;
6176             gte_b|=gte_rt[i+1];
6177             gte_b&=~gte_rs[i+1];
6178             u&=b;
6179             gte_u&=gte_b;
6180             if(i<slen-1) {
6181               branch_unneeded_reg[i]&=unneeded_reg[i+2];
6182             } else {
6183               branch_unneeded_reg[i]=1;
6184             }
6185           }
6186         }
6187       }
6188     }
6189     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
6190     {
6191       // SYSCALL instruction (software interrupt)
6192       u=1;
6193     }
6194     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
6195     {
6196       // ERET instruction (return from interrupt)
6197       u=1;
6198     }
6199     //u=1; // DEBUG
6200     // Written registers are unneeded
6201     u|=1LL<<dops[i].rt1;
6202     u|=1LL<<dops[i].rt2;
6203     gte_u|=gte_rt[i];
6204     // Accessed registers are needed
6205     u&=~(1LL<<dops[i].rs1);
6206     u&=~(1LL<<dops[i].rs2);
6207     gte_u&=~gte_rs[i];
6208     if(gte_rs[i]&&dops[i].rt1&&(unneeded_reg[i+1]&(1ll<<dops[i].rt1)))
6209       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
6210     // Source-target dependencies
6211     // R0 is always unneeded
6212     u|=1;
6213     // Save it
6214     unneeded_reg[i]=u;
6215     gte_unneeded[i]=gte_u;
6216     /*
6217     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
6218     printf("U:");
6219     int r;
6220     for(r=1;r<=CCREG;r++) {
6221       if((unneeded_reg[i]>>r)&1) {
6222         if(r==HIREG) printf(" HI");
6223         else if(r==LOREG) printf(" LO");
6224         else printf(" r%d",r);
6225       }
6226     }
6227     printf("\n");
6228     */
6229   }
6230 }
6231
6232 // Write back dirty registers as soon as we will no longer modify them,
6233 // so that we don't end up with lots of writes at the branches.
6234 void clean_registers(int istart,int iend,int wr)
6235 {
6236   int i;
6237   int r;
6238   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
6239   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
6240   if(iend==slen-1) {
6241     will_dirty_i=will_dirty_next=0;
6242     wont_dirty_i=wont_dirty_next=0;
6243   }else{
6244     will_dirty_i=will_dirty_next=will_dirty[iend+1];
6245     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
6246   }
6247   for (i=iend;i>=istart;i--)
6248   {
6249     if(dops[i].is_jump)
6250     {
6251       if(ba[i]<start || ba[i]>=(start+slen*4))
6252       {
6253         // Branch out of this block, flush all regs
6254         if (dops[i].is_ujump)
6255         {
6256           // Unconditional branch
6257           will_dirty_i=0;
6258           wont_dirty_i=0;
6259           // Merge in delay slot (will dirty)
6260           for(r=0;r<HOST_REGS;r++) {
6261             if(r!=EXCLUDE_REG) {
6262               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6263               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6264               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6265               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6266               if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6267               if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6268               if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6269               if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6270               if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6271               if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6272               if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6273               if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6274               if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6275               if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6276             }
6277           }
6278         }
6279         else
6280         {
6281           // Conditional branch
6282           will_dirty_i=0;
6283           wont_dirty_i=wont_dirty_next;
6284           // Merge in delay slot (will dirty)
6285           for(r=0;r<HOST_REGS;r++) {
6286             if(r!=EXCLUDE_REG) {
6287               if (1) { // !dops[i].likely) {
6288                 // Might not dirty if likely branch is not taken
6289                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6290                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6291                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6292                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6293                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6294                 if(branch_regs[i].regmap[r]==0) will_dirty_i&=~(1<<r);
6295                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6296                 //if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6297                 //if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6298                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6299                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6300                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6301                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6302                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6303               }
6304             }
6305           }
6306         }
6307         // Merge in delay slot (wont dirty)
6308         for(r=0;r<HOST_REGS;r++) {
6309           if(r!=EXCLUDE_REG) {
6310             if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6311             if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6312             if((regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6313             if((regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6314             if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6315             if((branch_regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6316             if((branch_regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6317             if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6318             if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6319             if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6320           }
6321         }
6322         if(wr) {
6323           #ifndef DESTRUCTIVE_WRITEBACK
6324           branch_regs[i].dirty&=wont_dirty_i;
6325           #endif
6326           branch_regs[i].dirty|=will_dirty_i;
6327         }
6328       }
6329       else
6330       {
6331         // Internal branch
6332         if(ba[i]<=start+i*4) {
6333           // Backward branch
6334           if (dops[i].is_ujump)
6335           {
6336             // Unconditional branch
6337             temp_will_dirty=0;
6338             temp_wont_dirty=0;
6339             // Merge in delay slot (will dirty)
6340             for(r=0;r<HOST_REGS;r++) {
6341               if(r!=EXCLUDE_REG) {
6342                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6343                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6344                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6345                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6346                 if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6347                 if(branch_regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6348                 if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6349                 if((regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6350                 if((regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6351                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6352                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6353                 if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6354                 if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6355                 if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6356               }
6357             }
6358           } else {
6359             // Conditional branch (not taken case)
6360             temp_will_dirty=will_dirty_next;
6361             temp_wont_dirty=wont_dirty_next;
6362             // Merge in delay slot (will dirty)
6363             for(r=0;r<HOST_REGS;r++) {
6364               if(r!=EXCLUDE_REG) {
6365                 if (1) { // !dops[i].likely) {
6366                   // Will not dirty if likely branch is not taken
6367                   if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6368                   if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6369                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6370                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6371                   if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6372                   if(branch_regs[i].regmap[r]==0) temp_will_dirty&=~(1<<r);
6373                   if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6374                   //if((regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6375                   //if((regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6376                   if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6377                   if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6378                   if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6379                   if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6380                   if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6381                 }
6382               }
6383             }
6384           }
6385           // Merge in delay slot (wont dirty)
6386           for(r=0;r<HOST_REGS;r++) {
6387             if(r!=EXCLUDE_REG) {
6388               if((regs[i].regmap[r]&63)==dops[i].rt1) temp_wont_dirty|=1<<r;
6389               if((regs[i].regmap[r]&63)==dops[i].rt2) temp_wont_dirty|=1<<r;
6390               if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_wont_dirty|=1<<r;
6391               if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_wont_dirty|=1<<r;
6392               if(regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6393               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_wont_dirty|=1<<r;
6394               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_wont_dirty|=1<<r;
6395               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_wont_dirty|=1<<r;
6396               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_wont_dirty|=1<<r;
6397               if(branch_regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6398             }
6399           }
6400           // Deal with changed mappings
6401           if(i<iend) {
6402             for(r=0;r<HOST_REGS;r++) {
6403               if(r!=EXCLUDE_REG) {
6404                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
6405                   temp_will_dirty&=~(1<<r);
6406                   temp_wont_dirty&=~(1<<r);
6407                   if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6408                     temp_will_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6409                     temp_wont_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6410                   } else {
6411                     temp_will_dirty|=1<<r;
6412                     temp_wont_dirty|=1<<r;
6413                   }
6414                 }
6415               }
6416             }
6417           }
6418           if(wr) {
6419             will_dirty[i]=temp_will_dirty;
6420             wont_dirty[i]=temp_wont_dirty;
6421             clean_registers((ba[i]-start)>>2,i-1,0);
6422           }else{
6423             // Limit recursion.  It can take an excessive amount
6424             // of time if there are a lot of nested loops.
6425             will_dirty[(ba[i]-start)>>2]=0;
6426             wont_dirty[(ba[i]-start)>>2]=-1;
6427           }
6428         }
6429         /*else*/ if(1)
6430         {
6431           if (dops[i].is_ujump)
6432           {
6433             // Unconditional branch
6434             will_dirty_i=0;
6435             wont_dirty_i=0;
6436           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6437             for(r=0;r<HOST_REGS;r++) {
6438               if(r!=EXCLUDE_REG) {
6439                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6440                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
6441                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6442                 }
6443                 if(branch_regs[i].regmap[r]>=0) {
6444                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6445                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6446                 }
6447               }
6448             }
6449           //}
6450             // Merge in delay slot
6451             for(r=0;r<HOST_REGS;r++) {
6452               if(r!=EXCLUDE_REG) {
6453                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6454                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6455                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6456                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6457                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6458                 if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6459                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6460                 if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6461                 if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6462                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6463                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6464                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6465                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6466                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6467               }
6468             }
6469           } else {
6470             // Conditional branch
6471             will_dirty_i=will_dirty_next;
6472             wont_dirty_i=wont_dirty_next;
6473           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6474             for(r=0;r<HOST_REGS;r++) {
6475               if(r!=EXCLUDE_REG) {
6476                 signed char target_reg=branch_regs[i].regmap[r];
6477                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6478                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6479                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6480                 }
6481                 else if(target_reg>=0) {
6482                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6483                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6484                 }
6485               }
6486             }
6487           //}
6488             // Merge in delay slot
6489             for(r=0;r<HOST_REGS;r++) {
6490               if(r!=EXCLUDE_REG) {
6491                 if (1) { // !dops[i].likely) {
6492                   // Might not dirty if likely branch is not taken
6493                   if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6494                   if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6495                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6496                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6497                   if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6498                   if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6499                   if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6500                   //if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6501                   //if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6502                   if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6503                   if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6504                   if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6505                   if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6506                   if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6507                 }
6508               }
6509             }
6510           }
6511           // Merge in delay slot (won't dirty)
6512           for(r=0;r<HOST_REGS;r++) {
6513             if(r!=EXCLUDE_REG) {
6514               if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6515               if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6516               if((regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6517               if((regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6518               if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6519               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6520               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6521               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6522               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6523               if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6524             }
6525           }
6526           if(wr) {
6527             #ifndef DESTRUCTIVE_WRITEBACK
6528             branch_regs[i].dirty&=wont_dirty_i;
6529             #endif
6530             branch_regs[i].dirty|=will_dirty_i;
6531           }
6532         }
6533       }
6534     }
6535     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
6536     {
6537       // SYSCALL instruction (software interrupt)
6538       will_dirty_i=0;
6539       wont_dirty_i=0;
6540     }
6541     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
6542     {
6543       // ERET instruction (return from interrupt)
6544       will_dirty_i=0;
6545       wont_dirty_i=0;
6546     }
6547     will_dirty_next=will_dirty_i;
6548     wont_dirty_next=wont_dirty_i;
6549     for(r=0;r<HOST_REGS;r++) {
6550       if(r!=EXCLUDE_REG) {
6551         if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6552         if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6553         if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6554         if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6555         if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6556         if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6557         if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6558         if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6559         if(i>istart) {
6560           if (!dops[i].is_jump)
6561           {
6562             // Don't store a register immediately after writing it,
6563             // may prevent dual-issue.
6564             if((regs[i].regmap[r]&63)==dops[i-1].rt1) wont_dirty_i|=1<<r;
6565             if((regs[i].regmap[r]&63)==dops[i-1].rt2) wont_dirty_i|=1<<r;
6566           }
6567         }
6568       }
6569     }
6570     // Save it
6571     will_dirty[i]=will_dirty_i;
6572     wont_dirty[i]=wont_dirty_i;
6573     // Mark registers that won't be dirtied as not dirty
6574     if(wr) {
6575         regs[i].dirty|=will_dirty_i;
6576         #ifndef DESTRUCTIVE_WRITEBACK
6577         regs[i].dirty&=wont_dirty_i;
6578         if(dops[i].is_jump)
6579         {
6580           if (i < iend-1 && !dops[i].is_ujump) {
6581             for(r=0;r<HOST_REGS;r++) {
6582               if(r!=EXCLUDE_REG) {
6583                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
6584                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
6585                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6586               }
6587             }
6588           }
6589         }
6590         else
6591         {
6592           if(i<iend) {
6593             for(r=0;r<HOST_REGS;r++) {
6594               if(r!=EXCLUDE_REG) {
6595                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
6596                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
6597                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6598               }
6599             }
6600           }
6601         }
6602         #endif
6603       //}
6604     }
6605     // Deal with changed mappings
6606     temp_will_dirty=will_dirty_i;
6607     temp_wont_dirty=wont_dirty_i;
6608     for(r=0;r<HOST_REGS;r++) {
6609       if(r!=EXCLUDE_REG) {
6610         int nr;
6611         if(regs[i].regmap[r]==regmap_pre[i][r]) {
6612           if(wr) {
6613             #ifndef DESTRUCTIVE_WRITEBACK
6614             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6615             #endif
6616             regs[i].wasdirty|=will_dirty_i&(1<<r);
6617           }
6618         }
6619         else if(regmap_pre[i][r]>=0&&(nr=get_reg(regs[i].regmap,regmap_pre[i][r]))>=0) {
6620           // Register moved to a different register
6621           will_dirty_i&=~(1<<r);
6622           wont_dirty_i&=~(1<<r);
6623           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
6624           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
6625           if(wr) {
6626             #ifndef DESTRUCTIVE_WRITEBACK
6627             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6628             #endif
6629             regs[i].wasdirty|=will_dirty_i&(1<<r);
6630           }
6631         }
6632         else {
6633           will_dirty_i&=~(1<<r);
6634           wont_dirty_i&=~(1<<r);
6635           if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6636             will_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6637             wont_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6638           } else {
6639             wont_dirty_i|=1<<r;
6640             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
6641           }
6642         }
6643       }
6644     }
6645   }
6646 }
6647
6648 #ifdef DISASM
6649   /* disassembly */
6650 void disassemble_inst(int i)
6651 {
6652     if (dops[i].bt) printf("*"); else printf(" ");
6653     switch(dops[i].itype) {
6654       case UJUMP:
6655         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6656       case CJUMP:
6657         printf (" %x: %s r%d,r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2,i?start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14):*ba);break;
6658       case SJUMP:
6659         printf (" %x: %s r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14));break;
6660       case RJUMP:
6661         if (dops[i].opcode==0x9&&dops[i].rt1!=31)
6662           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1);
6663         else
6664           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6665         break;
6666       case SPAN:
6667         printf (" %x: %s (pagespan) r%d,r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2,ba[i]);break;
6668       case IMM16:
6669         if(dops[i].opcode==0xf) //LUI
6670           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],dops[i].rt1,imm[i]&0xffff);
6671         else
6672           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6673         break;
6674       case LOAD:
6675       case LOADLR:
6676         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6677         break;
6678       case STORE:
6679       case STORELR:
6680         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rs2,dops[i].rs1,imm[i]);
6681         break;
6682       case ALU:
6683       case SHIFT:
6684         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,dops[i].rs2);
6685         break;
6686       case MULTDIV:
6687         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2);
6688         break;
6689       case SHIFTIMM:
6690         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6691         break;
6692       case MOV:
6693         if((dops[i].opcode2&0x1d)==0x10)
6694           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rt1);
6695         else if((dops[i].opcode2&0x1d)==0x11)
6696           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6697         else
6698           printf (" %x: %s\n",start+i*4,insn[i]);
6699         break;
6700       case COP0:
6701         if(dops[i].opcode2==0)
6702           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC0
6703         else if(dops[i].opcode2==4)
6704           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC0
6705         else printf (" %x: %s\n",start+i*4,insn[i]);
6706         break;
6707       case COP1:
6708         if(dops[i].opcode2<3)
6709           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC1
6710         else if(dops[i].opcode2>3)
6711           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC1
6712         else printf (" %x: %s\n",start+i*4,insn[i]);
6713         break;
6714       case COP2:
6715         if(dops[i].opcode2<3)
6716           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC2
6717         else if(dops[i].opcode2>3)
6718           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC2
6719         else printf (" %x: %s\n",start+i*4,insn[i]);
6720         break;
6721       case C1LS:
6722         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6723         break;
6724       case C2LS:
6725         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6726         break;
6727       case INTCALL:
6728         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6729         break;
6730       default:
6731         //printf (" %s %8x\n",insn[i],source[i]);
6732         printf (" %x: %s\n",start+i*4,insn[i]);
6733     }
6734 }
6735 #else
6736 static void disassemble_inst(int i) {}
6737 #endif // DISASM
6738
6739 #define DRC_TEST_VAL 0x74657374
6740
6741 static void new_dynarec_test(void)
6742 {
6743   int (*testfunc)(void);
6744   void *beginning;
6745   int ret[2];
6746   size_t i;
6747
6748   // check structure linkage
6749   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6750   {
6751     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6752   }
6753
6754   SysPrintf("testing if we can run recompiled code...\n");
6755   ((volatile u_int *)out)[0]++; // make cache dirty
6756
6757   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6758     out = ndrc->translation_cache;
6759     beginning = start_block();
6760     emit_movimm(DRC_TEST_VAL + i, 0); // test
6761     emit_ret();
6762     literal_pool(0);
6763     end_block(beginning);
6764     testfunc = beginning;
6765     ret[i] = testfunc();
6766   }
6767
6768   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6769     SysPrintf("test passed.\n");
6770   else
6771     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6772   out = ndrc->translation_cache;
6773 }
6774
6775 // clear the state completely, instead of just marking
6776 // things invalid like invalidate_all_pages() does
6777 void new_dynarec_clear_full(void)
6778 {
6779   int n;
6780   out = ndrc->translation_cache;
6781   memset(invalid_code,1,sizeof(invalid_code));
6782   memset(hash_table,0xff,sizeof(hash_table));
6783   memset(mini_ht,-1,sizeof(mini_ht));
6784   memset(restore_candidate,0,sizeof(restore_candidate));
6785   memset(shadow,0,sizeof(shadow));
6786   copy=shadow;
6787   expirep=16384; // Expiry pointer, +2 blocks
6788   pending_exception=0;
6789   literalcount=0;
6790   stop_after_jal=0;
6791   inv_code_start=inv_code_end=~0;
6792   f1_hack=0;
6793   // TLB
6794   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6795   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6796   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6797
6798   cycle_multiplier_old = cycle_multiplier;
6799   new_dynarec_hacks_old = new_dynarec_hacks;
6800 }
6801
6802 void new_dynarec_init(void)
6803 {
6804   SysPrintf("Init new dynarec\n");
6805
6806 #ifdef BASE_ADDR_DYNAMIC
6807   #ifdef VITA
6808   sceBlock = sceKernelAllocMemBlockForVM("code", 1 << TARGET_SIZE_2);
6809   if (sceBlock < 0)
6810     SysPrintf("sceKernelAllocMemBlockForVM failed\n");
6811   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6812   if (ret < 0)
6813     SysPrintf("sceKernelGetMemBlockBase failed\n");
6814   #else
6815   uintptr_t desired_addr = 0;
6816   #ifdef __ELF__
6817   extern char _end;
6818   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6819   #endif
6820   ndrc = mmap((void *)desired_addr, sizeof(*ndrc),
6821             PROT_READ | PROT_WRITE | PROT_EXEC,
6822             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
6823   if (ndrc == MAP_FAILED) {
6824     SysPrintf("mmap() failed: %s\n", strerror(errno));
6825     abort();
6826   }
6827   #endif
6828 #else
6829   #ifndef NO_WRITE_EXEC
6830   // not all systems allow execute in data segment by default
6831   if (mprotect(ndrc, sizeof(ndrc->translation_cache) + sizeof(ndrc->tramp.ops),
6832                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6833     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6834   #endif
6835 #endif
6836   out = ndrc->translation_cache;
6837   cycle_multiplier=200;
6838   new_dynarec_clear_full();
6839 #ifdef HOST_IMM8
6840   // Copy this into local area so we don't have to put it in every literal pool
6841   invc_ptr=invalid_code;
6842 #endif
6843   arch_init();
6844   new_dynarec_test();
6845   ram_offset=(uintptr_t)rdram-0x80000000;
6846   if (ram_offset!=0)
6847     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6848 }
6849
6850 void new_dynarec_cleanup(void)
6851 {
6852   int n;
6853 #ifdef BASE_ADDR_DYNAMIC
6854   #ifdef VITA
6855   sceKernelFreeMemBlock(sceBlock);
6856   sceBlock = -1;
6857   #else
6858   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6859     SysPrintf("munmap() failed\n");
6860   #endif
6861 #endif
6862   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6863   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6864   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6865   #ifdef ROM_COPY
6866   if (munmap (ROM_COPY, 67108864) < 0) {SysPrintf("munmap() failed\n");}
6867   #endif
6868 }
6869
6870 static u_int *get_source_start(u_int addr, u_int *limit)
6871 {
6872   if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6873     cycle_multiplier_override = 0;
6874
6875   if (addr < 0x00200000 ||
6876     (0xa0000000 <= addr && addr < 0xa0200000))
6877   {
6878     // used for BIOS calls mostly?
6879     *limit = (addr&0xa0000000)|0x00200000;
6880     return (u_int *)(rdram + (addr&0x1fffff));
6881   }
6882   else if (!Config.HLE && (
6883     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
6884     (0xbfc00000 <= addr && addr < 0xbfc80000)))
6885   {
6886     // BIOS. The multiplier should be much higher as it's uncached 8bit mem,
6887     // but timings in PCSX are too tied to the interpreter's BIAS
6888     if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6889       cycle_multiplier_override = 200;
6890
6891     *limit = (addr & 0xfff00000) | 0x80000;
6892     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
6893   }
6894   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
6895     *limit = (addr & 0x80600000) + 0x00200000;
6896     return (u_int *)(rdram + (addr&0x1fffff));
6897   }
6898   return NULL;
6899 }
6900
6901 static u_int scan_for_ret(u_int addr)
6902 {
6903   u_int limit = 0;
6904   u_int *mem;
6905
6906   mem = get_source_start(addr, &limit);
6907   if (mem == NULL)
6908     return addr;
6909
6910   if (limit > addr + 0x1000)
6911     limit = addr + 0x1000;
6912   for (; addr < limit; addr += 4, mem++) {
6913     if (*mem == 0x03e00008) // jr $ra
6914       return addr + 8;
6915   }
6916   return addr;
6917 }
6918
6919 struct savestate_block {
6920   uint32_t addr;
6921   uint32_t regflags;
6922 };
6923
6924 static int addr_cmp(const void *p1_, const void *p2_)
6925 {
6926   const struct savestate_block *p1 = p1_, *p2 = p2_;
6927   return p1->addr - p2->addr;
6928 }
6929
6930 int new_dynarec_save_blocks(void *save, int size)
6931 {
6932   struct savestate_block *blocks = save;
6933   int maxcount = size / sizeof(blocks[0]);
6934   struct savestate_block tmp_blocks[1024];
6935   struct ll_entry *head;
6936   int p, s, d, o, bcnt;
6937   u_int addr;
6938
6939   o = 0;
6940   for (p = 0; p < ARRAY_SIZE(jump_in); p++) {
6941     bcnt = 0;
6942     for (head = jump_in[p]; head != NULL; head = head->next) {
6943       tmp_blocks[bcnt].addr = head->vaddr;
6944       tmp_blocks[bcnt].regflags = head->reg_sv_flags;
6945       bcnt++;
6946     }
6947     if (bcnt < 1)
6948       continue;
6949     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
6950
6951     addr = tmp_blocks[0].addr;
6952     for (s = d = 0; s < bcnt; s++) {
6953       if (tmp_blocks[s].addr < addr)
6954         continue;
6955       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
6956         tmp_blocks[d++] = tmp_blocks[s];
6957       addr = scan_for_ret(tmp_blocks[s].addr);
6958     }
6959
6960     if (o + d > maxcount)
6961       d = maxcount - o;
6962     memcpy(&blocks[o], tmp_blocks, d * sizeof(blocks[0]));
6963     o += d;
6964   }
6965
6966   return o * sizeof(blocks[0]);
6967 }
6968
6969 void new_dynarec_load_blocks(const void *save, int size)
6970 {
6971   const struct savestate_block *blocks = save;
6972   int count = size / sizeof(blocks[0]);
6973   u_int regs_save[32];
6974   uint32_t f;
6975   int i, b;
6976
6977   get_addr(psxRegs.pc);
6978
6979   // change GPRs for speculation to at least partially work..
6980   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
6981   for (i = 1; i < 32; i++)
6982     psxRegs.GPR.r[i] = 0x80000000;
6983
6984   for (b = 0; b < count; b++) {
6985     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
6986       if (f & 1)
6987         psxRegs.GPR.r[i] = 0x1f800000;
6988     }
6989
6990     get_addr(blocks[b].addr);
6991
6992     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
6993       if (f & 1)
6994         psxRegs.GPR.r[i] = 0x80000000;
6995     }
6996   }
6997
6998   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
6999 }
7000
7001 int new_recompile_block(u_int addr)
7002 {
7003   u_int pagelimit = 0;
7004   u_int state_rflags = 0;
7005   int i;
7006
7007   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
7008   //printf("TRACE: count=%d next=%d (compile %x)\n",Count,next_interupt,addr);
7009   //if(debug)
7010   //printf("fpu mapping=%x enabled=%x\n",(Status & 0x04000000)>>26,(Status & 0x20000000)>>29);
7011
7012   // this is just for speculation
7013   for (i = 1; i < 32; i++) {
7014     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
7015       state_rflags |= 1 << i;
7016   }
7017
7018   start = (u_int)addr&~3;
7019   //assert(((u_int)addr&1)==0); // start-in-delay-slot flag
7020   new_dynarec_did_compile=1;
7021   if (Config.HLE && start == 0x80001000) // hlecall
7022   {
7023     // XXX: is this enough? Maybe check hleSoftCall?
7024     void *beginning=start_block();
7025     u_int page=get_page(start);
7026
7027     invalid_code[start>>12]=0;
7028     emit_movimm(start,0);
7029     emit_writeword(0,&pcaddr);
7030     emit_far_jump(new_dyna_leave);
7031     literal_pool(0);
7032     end_block(beginning);
7033     ll_add_flags(jump_in+page,start,state_rflags,(void *)beginning);
7034     return 0;
7035   }
7036   else if (f1_hack == ~0u || (f1_hack != 0 && start == f1_hack)) {
7037     void *beginning = start_block();
7038     u_int page = get_page(start);
7039     emit_readword(&psxRegs.GPR.n.sp, 0);
7040     emit_readptr(&mem_rtab, 1);
7041     emit_shrimm(0, 12, 2);
7042     emit_readptr_dualindexedx_ptrlen(1, 2, 1);
7043     emit_addimm(0, 0x18, 0);
7044     emit_adds_ptr(1, 1, 1);
7045     emit_ldr_dualindexed(1, 0, 0);
7046     emit_writeword(0, &psxRegs.GPR.r[26]); // lw k0, 0x18(sp)
7047     emit_far_call(get_addr_ht);
7048     emit_jmpreg(0); // jr k0
7049     literal_pool(0);
7050     end_block(beginning);
7051
7052     ll_add_flags(jump_in + page, start, state_rflags, beginning);
7053     SysPrintf("F1 hack to   %08x\n", start);
7054     f1_hack = start;
7055     return 0;
7056   }
7057
7058   source = get_source_start(start, &pagelimit);
7059   if (source == NULL) {
7060     SysPrintf("Compile at bogus memory address: %08x\n", addr);
7061     abort();
7062   }
7063
7064   /* Pass 1: disassemble */
7065   /* Pass 2: register dependencies, branch targets */
7066   /* Pass 3: register allocation */
7067   /* Pass 4: branch dependencies */
7068   /* Pass 5: pre-alloc */
7069   /* Pass 6: optimize clean/dirty state */
7070   /* Pass 7: flag 32-bit registers */
7071   /* Pass 8: assembly */
7072   /* Pass 9: linker */
7073   /* Pass 10: garbage collection / free memory */
7074
7075   int j;
7076   int done=0;
7077   unsigned int type,op,op2;
7078
7079   //printf("addr = %x source = %x %x\n", addr,source,source[0]);
7080
7081   /* Pass 1 disassembly */
7082
7083   for(i=0;!done;i++) {
7084     dops[i].bt=0;
7085     dops[i].ooo=0;
7086     op2=0;
7087     minimum_free_regs[i]=0;
7088     dops[i].opcode=op=source[i]>>26;
7089     switch(op)
7090     {
7091       case 0x00: strcpy(insn[i],"special"); type=NI;
7092         op2=source[i]&0x3f;
7093         switch(op2)
7094         {
7095           case 0x00: strcpy(insn[i],"SLL"); type=SHIFTIMM; break;
7096           case 0x02: strcpy(insn[i],"SRL"); type=SHIFTIMM; break;
7097           case 0x03: strcpy(insn[i],"SRA"); type=SHIFTIMM; break;
7098           case 0x04: strcpy(insn[i],"SLLV"); type=SHIFT; break;
7099           case 0x06: strcpy(insn[i],"SRLV"); type=SHIFT; break;
7100           case 0x07: strcpy(insn[i],"SRAV"); type=SHIFT; break;
7101           case 0x08: strcpy(insn[i],"JR"); type=RJUMP; break;
7102           case 0x09: strcpy(insn[i],"JALR"); type=RJUMP; break;
7103           case 0x0C: strcpy(insn[i],"SYSCALL"); type=SYSCALL; break;
7104           case 0x0D: strcpy(insn[i],"BREAK"); type=OTHER; break;
7105           case 0x0F: strcpy(insn[i],"SYNC"); type=OTHER; break;
7106           case 0x10: strcpy(insn[i],"MFHI"); type=MOV; break;
7107           case 0x11: strcpy(insn[i],"MTHI"); type=MOV; break;
7108           case 0x12: strcpy(insn[i],"MFLO"); type=MOV; break;
7109           case 0x13: strcpy(insn[i],"MTLO"); type=MOV; break;
7110           case 0x18: strcpy(insn[i],"MULT"); type=MULTDIV; break;
7111           case 0x19: strcpy(insn[i],"MULTU"); type=MULTDIV; break;
7112           case 0x1A: strcpy(insn[i],"DIV"); type=MULTDIV; break;
7113           case 0x1B: strcpy(insn[i],"DIVU"); type=MULTDIV; break;
7114           case 0x20: strcpy(insn[i],"ADD"); type=ALU; break;
7115           case 0x21: strcpy(insn[i],"ADDU"); type=ALU; break;
7116           case 0x22: strcpy(insn[i],"SUB"); type=ALU; break;
7117           case 0x23: strcpy(insn[i],"SUBU"); type=ALU; break;
7118           case 0x24: strcpy(insn[i],"AND"); type=ALU; break;
7119           case 0x25: strcpy(insn[i],"OR"); type=ALU; break;
7120           case 0x26: strcpy(insn[i],"XOR"); type=ALU; break;
7121           case 0x27: strcpy(insn[i],"NOR"); type=ALU; break;
7122           case 0x2A: strcpy(insn[i],"SLT"); type=ALU; break;
7123           case 0x2B: strcpy(insn[i],"SLTU"); type=ALU; break;
7124           case 0x30: strcpy(insn[i],"TGE"); type=NI; break;
7125           case 0x31: strcpy(insn[i],"TGEU"); type=NI; break;
7126           case 0x32: strcpy(insn[i],"TLT"); type=NI; break;
7127           case 0x33: strcpy(insn[i],"TLTU"); type=NI; break;
7128           case 0x34: strcpy(insn[i],"TEQ"); type=NI; break;
7129           case 0x36: strcpy(insn[i],"TNE"); type=NI; break;
7130 #if 0
7131           case 0x14: strcpy(insn[i],"DSLLV"); type=SHIFT; break;
7132           case 0x16: strcpy(insn[i],"DSRLV"); type=SHIFT; break;
7133           case 0x17: strcpy(insn[i],"DSRAV"); type=SHIFT; break;
7134           case 0x1C: strcpy(insn[i],"DMULT"); type=MULTDIV; break;
7135           case 0x1D: strcpy(insn[i],"DMULTU"); type=MULTDIV; break;
7136           case 0x1E: strcpy(insn[i],"DDIV"); type=MULTDIV; break;
7137           case 0x1F: strcpy(insn[i],"DDIVU"); type=MULTDIV; break;
7138           case 0x2C: strcpy(insn[i],"DADD"); type=ALU; break;
7139           case 0x2D: strcpy(insn[i],"DADDU"); type=ALU; break;
7140           case 0x2E: strcpy(insn[i],"DSUB"); type=ALU; break;
7141           case 0x2F: strcpy(insn[i],"DSUBU"); type=ALU; break;
7142           case 0x38: strcpy(insn[i],"DSLL"); type=SHIFTIMM; break;
7143           case 0x3A: strcpy(insn[i],"DSRL"); type=SHIFTIMM; break;
7144           case 0x3B: strcpy(insn[i],"DSRA"); type=SHIFTIMM; break;
7145           case 0x3C: strcpy(insn[i],"DSLL32"); type=SHIFTIMM; break;
7146           case 0x3E: strcpy(insn[i],"DSRL32"); type=SHIFTIMM; break;
7147           case 0x3F: strcpy(insn[i],"DSRA32"); type=SHIFTIMM; break;
7148 #endif
7149         }
7150         break;
7151       case 0x01: strcpy(insn[i],"regimm"); type=NI;
7152         op2=(source[i]>>16)&0x1f;
7153         switch(op2)
7154         {
7155           case 0x00: strcpy(insn[i],"BLTZ"); type=SJUMP; break;
7156           case 0x01: strcpy(insn[i],"BGEZ"); type=SJUMP; break;
7157           //case 0x02: strcpy(insn[i],"BLTZL"); type=SJUMP; break;
7158           //case 0x03: strcpy(insn[i],"BGEZL"); type=SJUMP; break;
7159           //case 0x08: strcpy(insn[i],"TGEI"); type=NI; break;
7160           //case 0x09: strcpy(insn[i],"TGEIU"); type=NI; break;
7161           //case 0x0A: strcpy(insn[i],"TLTI"); type=NI; break;
7162           //case 0x0B: strcpy(insn[i],"TLTIU"); type=NI; break;
7163           //case 0x0C: strcpy(insn[i],"TEQI"); type=NI; break;
7164           //case 0x0E: strcpy(insn[i],"TNEI"); type=NI; break;
7165           case 0x10: strcpy(insn[i],"BLTZAL"); type=SJUMP; break;
7166           case 0x11: strcpy(insn[i],"BGEZAL"); type=SJUMP; break;
7167           //case 0x12: strcpy(insn[i],"BLTZALL"); type=SJUMP; break;
7168           //case 0x13: strcpy(insn[i],"BGEZALL"); type=SJUMP; break;
7169         }
7170         break;
7171       case 0x02: strcpy(insn[i],"J"); type=UJUMP; break;
7172       case 0x03: strcpy(insn[i],"JAL"); type=UJUMP; break;
7173       case 0x04: strcpy(insn[i],"BEQ"); type=CJUMP; break;
7174       case 0x05: strcpy(insn[i],"BNE"); type=CJUMP; break;
7175       case 0x06: strcpy(insn[i],"BLEZ"); type=CJUMP; break;
7176       case 0x07: strcpy(insn[i],"BGTZ"); type=CJUMP; break;
7177       case 0x08: strcpy(insn[i],"ADDI"); type=IMM16; break;
7178       case 0x09: strcpy(insn[i],"ADDIU"); type=IMM16; break;
7179       case 0x0A: strcpy(insn[i],"SLTI"); type=IMM16; break;
7180       case 0x0B: strcpy(insn[i],"SLTIU"); type=IMM16; break;
7181       case 0x0C: strcpy(insn[i],"ANDI"); type=IMM16; break;
7182       case 0x0D: strcpy(insn[i],"ORI"); type=IMM16; break;
7183       case 0x0E: strcpy(insn[i],"XORI"); type=IMM16; break;
7184       case 0x0F: strcpy(insn[i],"LUI"); type=IMM16; break;
7185       case 0x10: strcpy(insn[i],"cop0"); type=NI;
7186         op2=(source[i]>>21)&0x1f;
7187         switch(op2)
7188         {
7189           case 0x00: strcpy(insn[i],"MFC0"); type=COP0; break;
7190           case 0x02: strcpy(insn[i],"CFC0"); type=COP0; break;
7191           case 0x04: strcpy(insn[i],"MTC0"); type=COP0; break;
7192           case 0x06: strcpy(insn[i],"CTC0"); type=COP0; break;
7193           case 0x10: strcpy(insn[i],"RFE"); type=COP0; break;
7194         }
7195         break;
7196       case 0x11: strcpy(insn[i],"cop1"); type=COP1;
7197         op2=(source[i]>>21)&0x1f;
7198         break;
7199 #if 0
7200       case 0x14: strcpy(insn[i],"BEQL"); type=CJUMP; break;
7201       case 0x15: strcpy(insn[i],"BNEL"); type=CJUMP; break;
7202       case 0x16: strcpy(insn[i],"BLEZL"); type=CJUMP; break;
7203       case 0x17: strcpy(insn[i],"BGTZL"); type=CJUMP; break;
7204       case 0x18: strcpy(insn[i],"DADDI"); type=IMM16; break;
7205       case 0x19: strcpy(insn[i],"DADDIU"); type=IMM16; break;
7206       case 0x1A: strcpy(insn[i],"LDL"); type=LOADLR; break;
7207       case 0x1B: strcpy(insn[i],"LDR"); type=LOADLR; break;
7208 #endif
7209       case 0x20: strcpy(insn[i],"LB"); type=LOAD; break;
7210       case 0x21: strcpy(insn[i],"LH"); type=LOAD; break;
7211       case 0x22: strcpy(insn[i],"LWL"); type=LOADLR; break;
7212       case 0x23: strcpy(insn[i],"LW"); type=LOAD; break;
7213       case 0x24: strcpy(insn[i],"LBU"); type=LOAD; break;
7214       case 0x25: strcpy(insn[i],"LHU"); type=LOAD; break;
7215       case 0x26: strcpy(insn[i],"LWR"); type=LOADLR; break;
7216 #if 0
7217       case 0x27: strcpy(insn[i],"LWU"); type=LOAD; break;
7218 #endif
7219       case 0x28: strcpy(insn[i],"SB"); type=STORE; break;
7220       case 0x29: strcpy(insn[i],"SH"); type=STORE; break;
7221       case 0x2A: strcpy(insn[i],"SWL"); type=STORELR; break;
7222       case 0x2B: strcpy(insn[i],"SW"); type=STORE; break;
7223 #if 0
7224       case 0x2C: strcpy(insn[i],"SDL"); type=STORELR; break;
7225       case 0x2D: strcpy(insn[i],"SDR"); type=STORELR; break;
7226 #endif
7227       case 0x2E: strcpy(insn[i],"SWR"); type=STORELR; break;
7228       case 0x2F: strcpy(insn[i],"CACHE"); type=NOP; break;
7229       case 0x30: strcpy(insn[i],"LL"); type=NI; break;
7230       case 0x31: strcpy(insn[i],"LWC1"); type=C1LS; break;
7231 #if 0
7232       case 0x34: strcpy(insn[i],"LLD"); type=NI; break;
7233       case 0x35: strcpy(insn[i],"LDC1"); type=C1LS; break;
7234       case 0x37: strcpy(insn[i],"LD"); type=LOAD; break;
7235 #endif
7236       case 0x38: strcpy(insn[i],"SC"); type=NI; break;
7237       case 0x39: strcpy(insn[i],"SWC1"); type=C1LS; break;
7238 #if 0
7239       case 0x3C: strcpy(insn[i],"SCD"); type=NI; break;
7240       case 0x3D: strcpy(insn[i],"SDC1"); type=C1LS; break;
7241       case 0x3F: strcpy(insn[i],"SD"); type=STORE; break;
7242 #endif
7243       case 0x12: strcpy(insn[i],"COP2"); type=NI;
7244         op2=(source[i]>>21)&0x1f;
7245         //if (op2 & 0x10)
7246         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
7247           if (gte_handlers[source[i]&0x3f]!=NULL) {
7248             if (gte_regnames[source[i]&0x3f]!=NULL)
7249               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
7250             else
7251               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
7252             type=C2OP;
7253           }
7254         }
7255         else switch(op2)
7256         {
7257           case 0x00: strcpy(insn[i],"MFC2"); type=COP2; break;
7258           case 0x02: strcpy(insn[i],"CFC2"); type=COP2; break;
7259           case 0x04: strcpy(insn[i],"MTC2"); type=COP2; break;
7260           case 0x06: strcpy(insn[i],"CTC2"); type=COP2; break;
7261         }
7262         break;
7263       case 0x32: strcpy(insn[i],"LWC2"); type=C2LS; break;
7264       case 0x3A: strcpy(insn[i],"SWC2"); type=C2LS; break;
7265       case 0x3B: strcpy(insn[i],"HLECALL"); type=HLECALL; break;
7266       default: strcpy(insn[i],"???"); type=NI;
7267         SysPrintf("NI %08x @%08x (%08x)\n", source[i], addr + i*4, addr);
7268         break;
7269     }
7270     dops[i].itype=type;
7271     dops[i].opcode2=op2;
7272     /* Get registers/immediates */
7273     dops[i].lt1=0;
7274     gte_rs[i]=gte_rt[i]=0;
7275     switch(type) {
7276       case LOAD:
7277         dops[i].rs1=(source[i]>>21)&0x1f;
7278         dops[i].rs2=0;
7279         dops[i].rt1=(source[i]>>16)&0x1f;
7280         dops[i].rt2=0;
7281         imm[i]=(short)source[i];
7282         break;
7283       case STORE:
7284       case STORELR:
7285         dops[i].rs1=(source[i]>>21)&0x1f;
7286         dops[i].rs2=(source[i]>>16)&0x1f;
7287         dops[i].rt1=0;
7288         dops[i].rt2=0;
7289         imm[i]=(short)source[i];
7290         break;
7291       case LOADLR:
7292         // LWL/LWR only load part of the register,
7293         // therefore the target register must be treated as a source too
7294         dops[i].rs1=(source[i]>>21)&0x1f;
7295         dops[i].rs2=(source[i]>>16)&0x1f;
7296         dops[i].rt1=(source[i]>>16)&0x1f;
7297         dops[i].rt2=0;
7298         imm[i]=(short)source[i];
7299         break;
7300       case IMM16:
7301         if (op==0x0f) dops[i].rs1=0; // LUI instruction has no source register
7302         else dops[i].rs1=(source[i]>>21)&0x1f;
7303         dops[i].rs2=0;
7304         dops[i].rt1=(source[i]>>16)&0x1f;
7305         dops[i].rt2=0;
7306         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
7307           imm[i]=(unsigned short)source[i];
7308         }else{
7309           imm[i]=(short)source[i];
7310         }
7311         break;
7312       case UJUMP:
7313         dops[i].rs1=0;
7314         dops[i].rs2=0;
7315         dops[i].rt1=0;
7316         dops[i].rt2=0;
7317         // The JAL instruction writes to r31.
7318         if (op&1) {
7319           dops[i].rt1=31;
7320         }
7321         dops[i].rs2=CCREG;
7322         break;
7323       case RJUMP:
7324         dops[i].rs1=(source[i]>>21)&0x1f;
7325         dops[i].rs2=0;
7326         dops[i].rt1=0;
7327         dops[i].rt2=0;
7328         // The JALR instruction writes to rd.
7329         if (op2&1) {
7330           dops[i].rt1=(source[i]>>11)&0x1f;
7331         }
7332         dops[i].rs2=CCREG;
7333         break;
7334       case CJUMP:
7335         dops[i].rs1=(source[i]>>21)&0x1f;
7336         dops[i].rs2=(source[i]>>16)&0x1f;
7337         dops[i].rt1=0;
7338         dops[i].rt2=0;
7339         if(op&2) { // BGTZ/BLEZ
7340           dops[i].rs2=0;
7341         }
7342         break;
7343       case SJUMP:
7344         dops[i].rs1=(source[i]>>21)&0x1f;
7345         dops[i].rs2=CCREG;
7346         dops[i].rt1=0;
7347         dops[i].rt2=0;
7348         if(op2&0x10) { // BxxAL
7349           dops[i].rt1=31;
7350           // NOTE: If the branch is not taken, r31 is still overwritten
7351         }
7352         break;
7353       case ALU:
7354         dops[i].rs1=(source[i]>>21)&0x1f; // source
7355         dops[i].rs2=(source[i]>>16)&0x1f; // subtract amount
7356         dops[i].rt1=(source[i]>>11)&0x1f; // destination
7357         dops[i].rt2=0;
7358         break;
7359       case MULTDIV:
7360         dops[i].rs1=(source[i]>>21)&0x1f; // source
7361         dops[i].rs2=(source[i]>>16)&0x1f; // divisor
7362         dops[i].rt1=HIREG;
7363         dops[i].rt2=LOREG;
7364         break;
7365       case MOV:
7366         dops[i].rs1=0;
7367         dops[i].rs2=0;
7368         dops[i].rt1=0;
7369         dops[i].rt2=0;
7370         if(op2==0x10) dops[i].rs1=HIREG; // MFHI
7371         if(op2==0x11) dops[i].rt1=HIREG; // MTHI
7372         if(op2==0x12) dops[i].rs1=LOREG; // MFLO
7373         if(op2==0x13) dops[i].rt1=LOREG; // MTLO
7374         if((op2&0x1d)==0x10) dops[i].rt1=(source[i]>>11)&0x1f; // MFxx
7375         if((op2&0x1d)==0x11) dops[i].rs1=(source[i]>>21)&0x1f; // MTxx
7376         break;
7377       case SHIFT:
7378         dops[i].rs1=(source[i]>>16)&0x1f; // target of shift
7379         dops[i].rs2=(source[i]>>21)&0x1f; // shift amount
7380         dops[i].rt1=(source[i]>>11)&0x1f; // destination
7381         dops[i].rt2=0;
7382         break;
7383       case SHIFTIMM:
7384         dops[i].rs1=(source[i]>>16)&0x1f;
7385         dops[i].rs2=0;
7386         dops[i].rt1=(source[i]>>11)&0x1f;
7387         dops[i].rt2=0;
7388         imm[i]=(source[i]>>6)&0x1f;
7389         // DSxx32 instructions
7390         if(op2>=0x3c) imm[i]|=0x20;
7391         break;
7392       case COP0:
7393         dops[i].rs1=0;
7394         dops[i].rs2=0;
7395         dops[i].rt1=0;
7396         dops[i].rt2=0;
7397         if(op2==0||op2==2) dops[i].rt1=(source[i]>>16)&0x1F; // MFC0/CFC0
7398         if(op2==4||op2==6) dops[i].rs1=(source[i]>>16)&0x1F; // MTC0/CTC0
7399         if(op2==4&&((source[i]>>11)&0x1f)==12) dops[i].rt2=CSREG; // Status
7400         if(op2==16) if((source[i]&0x3f)==0x18) dops[i].rs2=CCREG; // ERET
7401         break;
7402       case COP1:
7403         dops[i].rs1=0;
7404         dops[i].rs2=0;
7405         dops[i].rt1=0;
7406         dops[i].rt2=0;
7407         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
7408         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
7409         dops[i].rs2=CSREG;
7410         break;
7411       case COP2:
7412         dops[i].rs1=0;
7413         dops[i].rs2=0;
7414         dops[i].rt1=0;
7415         dops[i].rt2=0;
7416         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC2/CFC2
7417         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC2/CTC2
7418         dops[i].rs2=CSREG;
7419         int gr=(source[i]>>11)&0x1F;
7420         switch(op2)
7421         {
7422           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
7423           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
7424           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
7425           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
7426         }
7427         break;
7428       case C1LS:
7429         dops[i].rs1=(source[i]>>21)&0x1F;
7430         dops[i].rs2=CSREG;
7431         dops[i].rt1=0;
7432         dops[i].rt2=0;
7433         imm[i]=(short)source[i];
7434         break;
7435       case C2LS:
7436         dops[i].rs1=(source[i]>>21)&0x1F;
7437         dops[i].rs2=0;
7438         dops[i].rt1=0;
7439         dops[i].rt2=0;
7440         imm[i]=(short)source[i];
7441         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
7442         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
7443         break;
7444       case C2OP:
7445         dops[i].rs1=0;
7446         dops[i].rs2=0;
7447         dops[i].rt1=0;
7448         dops[i].rt2=0;
7449         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
7450         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
7451         gte_rt[i]|=1ll<<63; // every op changes flags
7452         if((source[i]&0x3f)==GTE_MVMVA) {
7453           int v = (source[i] >> 15) & 3;
7454           gte_rs[i]&=~0xe3fll;
7455           if(v==3) gte_rs[i]|=0xe00ll;
7456           else gte_rs[i]|=3ll<<(v*2);
7457         }
7458         break;
7459       case SYSCALL:
7460       case HLECALL:
7461       case INTCALL:
7462         dops[i].rs1=CCREG;
7463         dops[i].rs2=0;
7464         dops[i].rt1=0;
7465         dops[i].rt2=0;
7466         break;
7467       default:
7468         dops[i].rs1=0;
7469         dops[i].rs2=0;
7470         dops[i].rt1=0;
7471         dops[i].rt2=0;
7472     }
7473     /* Calculate branch target addresses */
7474     if(type==UJUMP)
7475       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
7476     else if(type==CJUMP&&dops[i].rs1==dops[i].rs2&&(op&1))
7477       ba[i]=start+i*4+8; // Ignore never taken branch
7478     else if(type==SJUMP&&dops[i].rs1==0&&!(op2&1))
7479       ba[i]=start+i*4+8; // Ignore never taken branch
7480     else if(type==CJUMP||type==SJUMP)
7481       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
7482     else ba[i]=-1;
7483
7484     /* simplify always (not)taken branches */
7485     if (type == CJUMP && dops[i].rs1 == dops[i].rs2) {
7486       dops[i].rs1 = dops[i].rs2 = 0;
7487       if (!(op & 1)) {
7488         dops[i].itype = type = UJUMP;
7489         dops[i].rs2 = CCREG;
7490       }
7491     }
7492     else if (type == SJUMP && dops[i].rs1 == 0 && (op2 & 1))
7493       dops[i].itype = type = UJUMP;
7494
7495     dops[i].is_jump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP || dops[i].itype == CJUMP || dops[i].itype == SJUMP);
7496     dops[i].is_ujump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP); // || (source[i] >> 16) == 0x1000 // beq r0,r0
7497     dops[i].is_load = (dops[i].itype == LOAD || dops[i].itype == LOADLR || op == 0x32); // LWC2
7498     dops[i].is_store = (dops[i].itype == STORE || dops[i].itype == STORELR || op == 0x3a); // SWC2
7499
7500     /* messy cases to just pass over to the interpreter */
7501     if (i > 0 && dops[i-1].is_jump) {
7502       int do_in_intrp=0;
7503       // branch in delay slot?
7504       if (dops[i].is_jump) {
7505         // don't handle first branch and call interpreter if it's hit
7506         SysPrintf("branch in delay slot @%08x (%08x)\n", addr + i*4, addr);
7507         do_in_intrp=1;
7508       }
7509       // basic load delay detection
7510       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&dops[i].rt1!=0) {
7511         int t=(ba[i-1]-start)/4;
7512         if(0 <= t && t < i &&(dops[i].rt1==dops[t].rs1||dops[i].rt1==dops[t].rs2)&&dops[t].itype!=CJUMP&&dops[t].itype!=SJUMP) {
7513           // jump target wants DS result - potential load delay effect
7514           SysPrintf("load delay @%08x (%08x)\n", addr + i*4, addr);
7515           do_in_intrp=1;
7516           dops[t+1].bt=1; // expected return from interpreter
7517         }
7518         else if(i>=2&&dops[i-2].rt1==2&&dops[i].rt1==2&&dops[i].rs1!=2&&dops[i].rs2!=2&&dops[i-1].rs1!=2&&dops[i-1].rs2!=2&&
7519               !(i>=3&&dops[i-3].is_jump)) {
7520           // v0 overwrite like this is a sign of trouble, bail out
7521           SysPrintf("v0 overwrite @%08x (%08x)\n", addr + i*4, addr);
7522           do_in_intrp=1;
7523         }
7524       }
7525       if(do_in_intrp) {
7526         dops[i-1].rs1=CCREG;
7527         dops[i-1].rs2=dops[i-1].rt1=dops[i-1].rt2=0;
7528         ba[i-1]=-1;
7529         dops[i-1].itype=INTCALL;
7530         done=2;
7531         i--; // don't compile the DS
7532       }
7533     }
7534
7535     /* Is this the end of the block? */
7536     if (i > 0 && dops[i-1].is_ujump) {
7537       if(dops[i-1].rt1==0) { // Continue past subroutine call (JAL)
7538         done=2;
7539       }
7540       else {
7541         if(stop_after_jal) done=1;
7542         // Stop on BREAK
7543         if((source[i+1]&0xfc00003f)==0x0d) done=1;
7544       }
7545       // Don't recompile stuff that's already compiled
7546       if(check_addr(start+i*4+4)) done=1;
7547       // Don't get too close to the limit
7548       if(i>MAXBLOCK/2) done=1;
7549     }
7550     if(dops[i].itype==SYSCALL&&stop_after_jal) done=1;
7551     if(dops[i].itype==HLECALL||dops[i].itype==INTCALL) done=2;
7552     if(done==2) {
7553       // Does the block continue due to a branch?
7554       for(j=i-1;j>=0;j--)
7555       {
7556         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
7557         if(ba[j]==start+i*4+4) done=j=0;
7558         if(ba[j]==start+i*4+8) done=j=0;
7559       }
7560     }
7561     //assert(i<MAXBLOCK-1);
7562     if(start+i*4==pagelimit-4) done=1;
7563     assert(start+i*4<pagelimit);
7564     if (i==MAXBLOCK-1) done=1;
7565     // Stop if we're compiling junk
7566     if(dops[i].itype==NI&&dops[i].opcode==0x11) {
7567       done=stop_after_jal=1;
7568       SysPrintf("Disabled speculative precompilation\n");
7569     }
7570   }
7571   slen=i;
7572   if (dops[i-1].is_jump) {
7573     if(start+i*4==pagelimit) {
7574       dops[i-1].itype=SPAN;
7575     }
7576   }
7577   assert(slen>0);
7578
7579   /* spacial hack(s) */
7580   if (i > 10 && source[i-1] == 0 && source[i-2] == 0x03e00008
7581       && source[i-4] == 0x8fbf0018 && source[i-6] == 0x00c0f809
7582       && dops[i-7].itype == STORE)
7583   {
7584     i = i-8;
7585     if (dops[i].itype == IMM16)
7586       i--;
7587     // swl r2, 15(r6); swr r2, 12(r6); sw r6, *; jalr r6
7588     if (dops[i].itype == STORELR && dops[i].rs1 == 6
7589       && dops[i-1].itype == STORELR && dops[i-1].rs1 == 6)
7590     {
7591       SysPrintf("F1 hack from %08x\n", start);
7592       if (f1_hack == 0)
7593         f1_hack = ~0u;
7594     }
7595   }
7596
7597   /* Pass 2 - Register dependencies and branch targets */
7598
7599   unneeded_registers(0,slen-1,0);
7600
7601   /* Pass 3 - Register allocation */
7602
7603   struct regstat current; // Current register allocations/status
7604   current.dirty=0;
7605   current.u=unneeded_reg[0];
7606   clear_all_regs(current.regmap);
7607   alloc_reg(&current,0,CCREG);
7608   dirty_reg(&current,CCREG);
7609   current.isconst=0;
7610   current.wasconst=0;
7611   current.waswritten=0;
7612   int ds=0;
7613   int cc=0;
7614   int hr=-1;
7615
7616   if((u_int)addr&1) {
7617     // First instruction is delay slot
7618     cc=-1;
7619     dops[1].bt=1;
7620     ds=1;
7621     unneeded_reg[0]=1;
7622     current.regmap[HOST_BTREG]=BTREG;
7623   }
7624
7625   for(i=0;i<slen;i++)
7626   {
7627     if(dops[i].bt)
7628     {
7629       int hr;
7630       for(hr=0;hr<HOST_REGS;hr++)
7631       {
7632         // Is this really necessary?
7633         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7634       }
7635       current.isconst=0;
7636       current.waswritten=0;
7637     }
7638
7639     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7640     regs[i].wasconst=current.isconst;
7641     regs[i].wasdirty=current.dirty;
7642     regs[i].loadedconst=0;
7643     if (!dops[i].is_jump) {
7644       if(i+1<slen) {
7645         current.u=unneeded_reg[i+1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7646         current.u|=1;
7647       } else {
7648         current.u=1;
7649       }
7650     } else {
7651       if(i+1<slen) {
7652         current.u=branch_unneeded_reg[i]&~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7653         current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7654         current.u|=1;
7655       } else { SysPrintf("oops, branch at end of block with no delay slot\n");abort(); }
7656     }
7657     dops[i].is_ds=ds;
7658     if(ds) {
7659       ds=0; // Skip delay slot, already allocated as part of branch
7660       // ...but we need to alloc it in case something jumps here
7661       if(i+1<slen) {
7662         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7663       }else{
7664         current.u=branch_unneeded_reg[i-1];
7665       }
7666       current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7667       current.u|=1;
7668       struct regstat temp;
7669       memcpy(&temp,&current,sizeof(current));
7670       temp.wasdirty=temp.dirty;
7671       // TODO: Take into account unconditional branches, as below
7672       delayslot_alloc(&temp,i);
7673       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7674       regs[i].wasdirty=temp.wasdirty;
7675       regs[i].dirty=temp.dirty;
7676       regs[i].isconst=0;
7677       regs[i].wasconst=0;
7678       current.isconst=0;
7679       // Create entry (branch target) regmap
7680       for(hr=0;hr<HOST_REGS;hr++)
7681       {
7682         int r=temp.regmap[hr];
7683         if(r>=0) {
7684           if(r!=regmap_pre[i][hr]) {
7685             regs[i].regmap_entry[hr]=-1;
7686           }
7687           else
7688           {
7689               assert(r < 64);
7690               if((current.u>>r)&1) {
7691                 regs[i].regmap_entry[hr]=-1;
7692                 regs[i].regmap[hr]=-1;
7693                 //Don't clear regs in the delay slot as the branch might need them
7694                 //current.regmap[hr]=-1;
7695               }else
7696                 regs[i].regmap_entry[hr]=r;
7697           }
7698         } else {
7699           // First instruction expects CCREG to be allocated
7700           if(i==0&&hr==HOST_CCREG)
7701             regs[i].regmap_entry[hr]=CCREG;
7702           else
7703             regs[i].regmap_entry[hr]=-1;
7704         }
7705       }
7706     }
7707     else { // Not delay slot
7708       switch(dops[i].itype) {
7709         case UJUMP:
7710           //current.isconst=0; // DEBUG
7711           //current.wasconst=0; // DEBUG
7712           //regs[i].wasconst=0; // DEBUG
7713           clear_const(&current,dops[i].rt1);
7714           alloc_cc(&current,i);
7715           dirty_reg(&current,CCREG);
7716           if (dops[i].rt1==31) {
7717             alloc_reg(&current,i,31);
7718             dirty_reg(&current,31);
7719             //assert(dops[i+1].rs1!=31&&dops[i+1].rs2!=31);
7720             //assert(dops[i+1].rt1!=dops[i].rt1);
7721             #ifdef REG_PREFETCH
7722             alloc_reg(&current,i,PTEMP);
7723             #endif
7724           }
7725           dops[i].ooo=1;
7726           delayslot_alloc(&current,i+1);
7727           //current.isconst=0; // DEBUG
7728           ds=1;
7729           //printf("i=%d, isconst=%x\n",i,current.isconst);
7730           break;
7731         case RJUMP:
7732           //current.isconst=0;
7733           //current.wasconst=0;
7734           //regs[i].wasconst=0;
7735           clear_const(&current,dops[i].rs1);
7736           clear_const(&current,dops[i].rt1);
7737           alloc_cc(&current,i);
7738           dirty_reg(&current,CCREG);
7739           if (!ds_writes_rjump_rs(i)) {
7740             alloc_reg(&current,i,dops[i].rs1);
7741             if (dops[i].rt1!=0) {
7742               alloc_reg(&current,i,dops[i].rt1);
7743               dirty_reg(&current,dops[i].rt1);
7744               assert(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt1);
7745               assert(dops[i+1].rt1!=dops[i].rt1);
7746               #ifdef REG_PREFETCH
7747               alloc_reg(&current,i,PTEMP);
7748               #endif
7749             }
7750             #ifdef USE_MINI_HT
7751             if(dops[i].rs1==31) { // JALR
7752               alloc_reg(&current,i,RHASH);
7753               alloc_reg(&current,i,RHTBL);
7754             }
7755             #endif
7756             delayslot_alloc(&current,i+1);
7757           } else {
7758             // The delay slot overwrites our source register,
7759             // allocate a temporary register to hold the old value.
7760             current.isconst=0;
7761             current.wasconst=0;
7762             regs[i].wasconst=0;
7763             delayslot_alloc(&current,i+1);
7764             current.isconst=0;
7765             alloc_reg(&current,i,RTEMP);
7766           }
7767           //current.isconst=0; // DEBUG
7768           dops[i].ooo=1;
7769           ds=1;
7770           break;
7771         case CJUMP:
7772           //current.isconst=0;
7773           //current.wasconst=0;
7774           //regs[i].wasconst=0;
7775           clear_const(&current,dops[i].rs1);
7776           clear_const(&current,dops[i].rs2);
7777           if((dops[i].opcode&0x3E)==4) // BEQ/BNE
7778           {
7779             alloc_cc(&current,i);
7780             dirty_reg(&current,CCREG);
7781             if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7782             if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7783             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2))||
7784                (dops[i].rs2&&(dops[i].rs2==dops[i+1].rt1||dops[i].rs2==dops[i+1].rt2))) {
7785               // The delay slot overwrites one of our conditions.
7786               // Allocate the branch condition registers instead.
7787               current.isconst=0;
7788               current.wasconst=0;
7789               regs[i].wasconst=0;
7790               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7791               if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7792             }
7793             else
7794             {
7795               dops[i].ooo=1;
7796               delayslot_alloc(&current,i+1);
7797             }
7798           }
7799           else
7800           if((dops[i].opcode&0x3E)==6) // BLEZ/BGTZ
7801           {
7802             alloc_cc(&current,i);
7803             dirty_reg(&current,CCREG);
7804             alloc_reg(&current,i,dops[i].rs1);
7805             if(dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) {
7806               // The delay slot overwrites one of our conditions.
7807               // Allocate the branch condition registers instead.
7808               current.isconst=0;
7809               current.wasconst=0;
7810               regs[i].wasconst=0;
7811               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7812             }
7813             else
7814             {
7815               dops[i].ooo=1;
7816               delayslot_alloc(&current,i+1);
7817             }
7818           }
7819           else
7820           // Don't alloc the delay slot yet because we might not execute it
7821           if((dops[i].opcode&0x3E)==0x14) // BEQL/BNEL
7822           {
7823             current.isconst=0;
7824             current.wasconst=0;
7825             regs[i].wasconst=0;
7826             alloc_cc(&current,i);
7827             dirty_reg(&current,CCREG);
7828             alloc_reg(&current,i,dops[i].rs1);
7829             alloc_reg(&current,i,dops[i].rs2);
7830           }
7831           else
7832           if((dops[i].opcode&0x3E)==0x16) // BLEZL/BGTZL
7833           {
7834             current.isconst=0;
7835             current.wasconst=0;
7836             regs[i].wasconst=0;
7837             alloc_cc(&current,i);
7838             dirty_reg(&current,CCREG);
7839             alloc_reg(&current,i,dops[i].rs1);
7840           }
7841           ds=1;
7842           //current.isconst=0;
7843           break;
7844         case SJUMP:
7845           //current.isconst=0;
7846           //current.wasconst=0;
7847           //regs[i].wasconst=0;
7848           clear_const(&current,dops[i].rs1);
7849           clear_const(&current,dops[i].rt1);
7850           //if((dops[i].opcode2&0x1E)==0x0) // BLTZ/BGEZ
7851           if((dops[i].opcode2&0x0E)==0x0) // BLTZ/BGEZ
7852           {
7853             alloc_cc(&current,i);
7854             dirty_reg(&current,CCREG);
7855             alloc_reg(&current,i,dops[i].rs1);
7856             if (dops[i].rt1==31) { // BLTZAL/BGEZAL
7857               alloc_reg(&current,i,31);
7858               dirty_reg(&current,31);
7859               //#ifdef REG_PREFETCH
7860               //alloc_reg(&current,i,PTEMP);
7861               //#endif
7862             }
7863             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) // The delay slot overwrites the branch condition.
7864                ||(dops[i].rt1==31&&(dops[i+1].rs1==31||dops[i+1].rs2==31||dops[i+1].rt1==31||dops[i+1].rt2==31))) { // DS touches $ra
7865               // Allocate the branch condition registers instead.
7866               current.isconst=0;
7867               current.wasconst=0;
7868               regs[i].wasconst=0;
7869               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7870             }
7871             else
7872             {
7873               dops[i].ooo=1;
7874               delayslot_alloc(&current,i+1);
7875             }
7876           }
7877           else
7878           // Don't alloc the delay slot yet because we might not execute it
7879           if((dops[i].opcode2&0x1E)==0x2) // BLTZL/BGEZL
7880           {
7881             current.isconst=0;
7882             current.wasconst=0;
7883             regs[i].wasconst=0;
7884             alloc_cc(&current,i);
7885             dirty_reg(&current,CCREG);
7886             alloc_reg(&current,i,dops[i].rs1);
7887           }
7888           ds=1;
7889           //current.isconst=0;
7890           break;
7891         case IMM16:
7892           imm16_alloc(&current,i);
7893           break;
7894         case LOAD:
7895         case LOADLR:
7896           load_alloc(&current,i);
7897           break;
7898         case STORE:
7899         case STORELR:
7900           store_alloc(&current,i);
7901           break;
7902         case ALU:
7903           alu_alloc(&current,i);
7904           break;
7905         case SHIFT:
7906           shift_alloc(&current,i);
7907           break;
7908         case MULTDIV:
7909           multdiv_alloc(&current,i);
7910           break;
7911         case SHIFTIMM:
7912           shiftimm_alloc(&current,i);
7913           break;
7914         case MOV:
7915           mov_alloc(&current,i);
7916           break;
7917         case COP0:
7918           cop0_alloc(&current,i);
7919           break;
7920         case COP1:
7921           break;
7922         case COP2:
7923           cop2_alloc(&current,i);
7924           break;
7925         case C1LS:
7926           c1ls_alloc(&current,i);
7927           break;
7928         case C2LS:
7929           c2ls_alloc(&current,i);
7930           break;
7931         case C2OP:
7932           c2op_alloc(&current,i);
7933           break;
7934         case SYSCALL:
7935         case HLECALL:
7936         case INTCALL:
7937           syscall_alloc(&current,i);
7938           break;
7939         case SPAN:
7940           pagespan_alloc(&current,i);
7941           break;
7942       }
7943
7944       // Create entry (branch target) regmap
7945       for(hr=0;hr<HOST_REGS;hr++)
7946       {
7947         int r,or;
7948         r=current.regmap[hr];
7949         if(r>=0) {
7950           if(r!=regmap_pre[i][hr]) {
7951             // TODO: delay slot (?)
7952             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
7953             if(or<0||(r&63)>=TEMPREG){
7954               regs[i].regmap_entry[hr]=-1;
7955             }
7956             else
7957             {
7958               // Just move it to a different register
7959               regs[i].regmap_entry[hr]=r;
7960               // If it was dirty before, it's still dirty
7961               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r&63);
7962             }
7963           }
7964           else
7965           {
7966             // Unneeded
7967             if(r==0){
7968               regs[i].regmap_entry[hr]=0;
7969             }
7970             else
7971             {
7972               assert(r<64);
7973               if((current.u>>r)&1) {
7974                 regs[i].regmap_entry[hr]=-1;
7975                 //regs[i].regmap[hr]=-1;
7976                 current.regmap[hr]=-1;
7977               }else
7978                 regs[i].regmap_entry[hr]=r;
7979             }
7980           }
7981         } else {
7982           // Branches expect CCREG to be allocated at the target
7983           if(regmap_pre[i][hr]==CCREG)
7984             regs[i].regmap_entry[hr]=CCREG;
7985           else
7986             regs[i].regmap_entry[hr]=-1;
7987         }
7988       }
7989       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
7990     }
7991
7992     if(i>0&&(dops[i-1].itype==STORE||dops[i-1].itype==STORELR||(dops[i-1].itype==C2LS&&dops[i-1].opcode==0x3a))&&(u_int)imm[i-1]<0x800)
7993       current.waswritten|=1<<dops[i-1].rs1;
7994     current.waswritten&=~(1<<dops[i].rt1);
7995     current.waswritten&=~(1<<dops[i].rt2);
7996     if((dops[i].itype==STORE||dops[i].itype==STORELR||(dops[i].itype==C2LS&&dops[i].opcode==0x3a))&&(u_int)imm[i]>=0x800)
7997       current.waswritten&=~(1<<dops[i].rs1);
7998
7999     /* Branch post-alloc */
8000     if(i>0)
8001     {
8002       current.wasdirty=current.dirty;
8003       switch(dops[i-1].itype) {
8004         case UJUMP:
8005           memcpy(&branch_regs[i-1],&current,sizeof(current));
8006           branch_regs[i-1].isconst=0;
8007           branch_regs[i-1].wasconst=0;
8008           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
8009           alloc_cc(&branch_regs[i-1],i-1);
8010           dirty_reg(&branch_regs[i-1],CCREG);
8011           if(dops[i-1].rt1==31) { // JAL
8012             alloc_reg(&branch_regs[i-1],i-1,31);
8013             dirty_reg(&branch_regs[i-1],31);
8014           }
8015           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8016           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8017           break;
8018         case RJUMP:
8019           memcpy(&branch_regs[i-1],&current,sizeof(current));
8020           branch_regs[i-1].isconst=0;
8021           branch_regs[i-1].wasconst=0;
8022           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
8023           alloc_cc(&branch_regs[i-1],i-1);
8024           dirty_reg(&branch_regs[i-1],CCREG);
8025           alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rs1);
8026           if(dops[i-1].rt1!=0) { // JALR
8027             alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rt1);
8028             dirty_reg(&branch_regs[i-1],dops[i-1].rt1);
8029           }
8030           #ifdef USE_MINI_HT
8031           if(dops[i-1].rs1==31) { // JALR
8032             alloc_reg(&branch_regs[i-1],i-1,RHASH);
8033             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
8034           }
8035           #endif
8036           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8037           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8038           break;
8039         case CJUMP:
8040           if((dops[i-1].opcode&0x3E)==4) // BEQ/BNE
8041           {
8042             alloc_cc(&current,i-1);
8043             dirty_reg(&current,CCREG);
8044             if((dops[i-1].rs1&&(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2))||
8045                (dops[i-1].rs2&&(dops[i-1].rs2==dops[i].rt1||dops[i-1].rs2==dops[i].rt2))) {
8046               // The delay slot overwrote one of our conditions
8047               // Delay slot goes after the test (in order)
8048               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8049               current.u|=1;
8050               delayslot_alloc(&current,i);
8051               current.isconst=0;
8052             }
8053             else
8054             {
8055               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
8056               // Alloc the branch condition registers
8057               if(dops[i-1].rs1) alloc_reg(&current,i-1,dops[i-1].rs1);
8058               if(dops[i-1].rs2) alloc_reg(&current,i-1,dops[i-1].rs2);
8059             }
8060             memcpy(&branch_regs[i-1],&current,sizeof(current));
8061             branch_regs[i-1].isconst=0;
8062             branch_regs[i-1].wasconst=0;
8063             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8064             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8065           }
8066           else
8067           if((dops[i-1].opcode&0x3E)==6) // BLEZ/BGTZ
8068           {
8069             alloc_cc(&current,i-1);
8070             dirty_reg(&current,CCREG);
8071             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
8072               // The delay slot overwrote the branch condition
8073               // Delay slot goes after the test (in order)
8074               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8075               current.u|=1;
8076               delayslot_alloc(&current,i);
8077               current.isconst=0;
8078             }
8079             else
8080             {
8081               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
8082               // Alloc the branch condition register
8083               alloc_reg(&current,i-1,dops[i-1].rs1);
8084             }
8085             memcpy(&branch_regs[i-1],&current,sizeof(current));
8086             branch_regs[i-1].isconst=0;
8087             branch_regs[i-1].wasconst=0;
8088             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8089             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8090           }
8091           else
8092           // Alloc the delay slot in case the branch is taken
8093           if((dops[i-1].opcode&0x3E)==0x14) // BEQL/BNEL
8094           {
8095             memcpy(&branch_regs[i-1],&current,sizeof(current));
8096             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
8097             alloc_cc(&branch_regs[i-1],i);
8098             dirty_reg(&branch_regs[i-1],CCREG);
8099             delayslot_alloc(&branch_regs[i-1],i);
8100             branch_regs[i-1].isconst=0;
8101             alloc_reg(&current,i,CCREG); // Not taken path
8102             dirty_reg(&current,CCREG);
8103             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8104           }
8105           else
8106           if((dops[i-1].opcode&0x3E)==0x16) // BLEZL/BGTZL
8107           {
8108             memcpy(&branch_regs[i-1],&current,sizeof(current));
8109             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
8110             alloc_cc(&branch_regs[i-1],i);
8111             dirty_reg(&branch_regs[i-1],CCREG);
8112             delayslot_alloc(&branch_regs[i-1],i);
8113             branch_regs[i-1].isconst=0;
8114             alloc_reg(&current,i,CCREG); // Not taken path
8115             dirty_reg(&current,CCREG);
8116             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8117           }
8118           break;
8119         case SJUMP:
8120           //if((dops[i-1].opcode2&0x1E)==0) // BLTZ/BGEZ
8121           if((dops[i-1].opcode2&0x0E)==0) // BLTZ/BGEZ
8122           {
8123             alloc_cc(&current,i-1);
8124             dirty_reg(&current,CCREG);
8125             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
8126               // The delay slot overwrote the branch condition
8127               // Delay slot goes after the test (in order)
8128               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8129               current.u|=1;
8130               delayslot_alloc(&current,i);
8131               current.isconst=0;
8132             }
8133             else
8134             {
8135               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
8136               // Alloc the branch condition register
8137               alloc_reg(&current,i-1,dops[i-1].rs1);
8138             }
8139             memcpy(&branch_regs[i-1],&current,sizeof(current));
8140             branch_regs[i-1].isconst=0;
8141             branch_regs[i-1].wasconst=0;
8142             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8143             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8144           }
8145           else
8146           // Alloc the delay slot in case the branch is taken
8147           if((dops[i-1].opcode2&0x1E)==2) // BLTZL/BGEZL
8148           {
8149             memcpy(&branch_regs[i-1],&current,sizeof(current));
8150             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
8151             alloc_cc(&branch_regs[i-1],i);
8152             dirty_reg(&branch_regs[i-1],CCREG);
8153             delayslot_alloc(&branch_regs[i-1],i);
8154             branch_regs[i-1].isconst=0;
8155             alloc_reg(&current,i,CCREG); // Not taken path
8156             dirty_reg(&current,CCREG);
8157             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8158           }
8159           // FIXME: BLTZAL/BGEZAL
8160           if(dops[i-1].opcode2&0x10) { // BxxZAL
8161             alloc_reg(&branch_regs[i-1],i-1,31);
8162             dirty_reg(&branch_regs[i-1],31);
8163           }
8164           break;
8165       }
8166
8167       if (dops[i-1].is_ujump)
8168       {
8169         if(dops[i-1].rt1==31) // JAL/JALR
8170         {
8171           // Subroutine call will return here, don't alloc any registers
8172           current.dirty=0;
8173           clear_all_regs(current.regmap);
8174           alloc_reg(&current,i,CCREG);
8175           dirty_reg(&current,CCREG);
8176         }
8177         else if(i+1<slen)
8178         {
8179           // Internal branch will jump here, match registers to caller
8180           current.dirty=0;
8181           clear_all_regs(current.regmap);
8182           alloc_reg(&current,i,CCREG);
8183           dirty_reg(&current,CCREG);
8184           for(j=i-1;j>=0;j--)
8185           {
8186             if(ba[j]==start+i*4+4) {
8187               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
8188               current.dirty=branch_regs[j].dirty;
8189               break;
8190             }
8191           }
8192           while(j>=0) {
8193             if(ba[j]==start+i*4+4) {
8194               for(hr=0;hr<HOST_REGS;hr++) {
8195                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
8196                   current.regmap[hr]=-1;
8197                 }
8198                 current.dirty&=branch_regs[j].dirty;
8199               }
8200             }
8201             j--;
8202           }
8203         }
8204       }
8205     }
8206
8207     // Count cycles in between branches
8208     ccadj[i]=cc;
8209     if (i > 0 && (dops[i-1].is_jump || dops[i].itype == SYSCALL || dops[i].itype == HLECALL))
8210     {
8211       cc=0;
8212     }
8213 #if !defined(DRC_DBG)
8214     else if(dops[i].itype==C2OP&&gte_cycletab[source[i]&0x3f]>2)
8215     {
8216       // this should really be removed since the real stalls have been implemented,
8217       // but doing so causes sizeable perf regression against the older version
8218       u_int gtec = gte_cycletab[source[i] & 0x3f];
8219       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? gtec/2 : 2;
8220     }
8221     else if(i>1&&dops[i].itype==STORE&&dops[i-1].itype==STORE&&dops[i-2].itype==STORE&&!dops[i].bt)
8222     {
8223       cc+=4;
8224     }
8225     else if(dops[i].itype==C2LS)
8226     {
8227       // same as with C2OP
8228       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? 4 : 2;
8229     }
8230 #endif
8231     else
8232     {
8233       cc++;
8234     }
8235
8236     if(!dops[i].is_ds) {
8237       regs[i].dirty=current.dirty;
8238       regs[i].isconst=current.isconst;
8239       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
8240     }
8241     for(hr=0;hr<HOST_REGS;hr++) {
8242       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
8243         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
8244           regs[i].wasconst&=~(1<<hr);
8245         }
8246       }
8247     }
8248     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
8249     regs[i].waswritten=current.waswritten;
8250   }
8251
8252   /* Pass 4 - Cull unused host registers */
8253
8254   uint64_t nr=0;
8255
8256   for (i=slen-1;i>=0;i--)
8257   {
8258     int hr;
8259     if(dops[i].is_jump)
8260     {
8261       if(ba[i]<start || ba[i]>=(start+slen*4))
8262       {
8263         // Branch out of this block, don't need anything
8264         nr=0;
8265       }
8266       else
8267       {
8268         // Internal branch
8269         // Need whatever matches the target
8270         nr=0;
8271         int t=(ba[i]-start)>>2;
8272         for(hr=0;hr<HOST_REGS;hr++)
8273         {
8274           if(regs[i].regmap_entry[hr]>=0) {
8275             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
8276           }
8277         }
8278       }
8279       // Conditional branch may need registers for following instructions
8280       if (!dops[i].is_ujump)
8281       {
8282         if(i<slen-2) {
8283           nr|=needed_reg[i+2];
8284           for(hr=0;hr<HOST_REGS;hr++)
8285           {
8286             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
8287             //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]);
8288           }
8289         }
8290       }
8291       // Don't need stuff which is overwritten
8292       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8293       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8294       // Merge in delay slot
8295       for(hr=0;hr<HOST_REGS;hr++)
8296       {
8297         if(dops[i+1].rt1&&dops[i+1].rt1==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8298         if(dops[i+1].rt2&&dops[i+1].rt2==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8299         if(dops[i+1].rs1==regmap_pre[i][hr]) nr|=1<<hr;
8300         if(dops[i+1].rs2==regmap_pre[i][hr]) nr|=1<<hr;
8301         if(dops[i+1].rs1==regs[i].regmap_entry[hr]) nr|=1<<hr;
8302         if(dops[i+1].rs2==regs[i].regmap_entry[hr]) nr|=1<<hr;
8303         if(ram_offset && (dops[i+1].is_load || dops[i+1].is_store)) {
8304           if(regmap_pre[i][hr]==ROREG) nr|=1<<hr;
8305           if(regs[i].regmap_entry[hr]==ROREG) nr|=1<<hr;
8306         }
8307         if(dops[i+1].is_store) {
8308           if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8309           if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8310         }
8311       }
8312     }
8313     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
8314     {
8315       // SYSCALL instruction (software interrupt)
8316       nr=0;
8317     }
8318     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
8319     {
8320       // ERET instruction (return from interrupt)
8321       nr=0;
8322     }
8323     else // Non-branch
8324     {
8325       if(i<slen-1) {
8326         for(hr=0;hr<HOST_REGS;hr++) {
8327           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
8328           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
8329           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8330           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8331         }
8332       }
8333     }
8334     for(hr=0;hr<HOST_REGS;hr++)
8335     {
8336       // Overwritten registers are not needed
8337       if(dops[i].rt1&&dops[i].rt1==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8338       if(dops[i].rt2&&dops[i].rt2==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8339       if(FTEMP==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8340       // Source registers are needed
8341       if(dops[i].rs1==regmap_pre[i][hr]) nr|=1<<hr;
8342       if(dops[i].rs2==regmap_pre[i][hr]) nr|=1<<hr;
8343       if(dops[i].rs1==regs[i].regmap_entry[hr]) nr|=1<<hr;
8344       if(dops[i].rs2==regs[i].regmap_entry[hr]) nr|=1<<hr;
8345       if(ram_offset && (dops[i].is_load || dops[i].is_store)) {
8346         if(regmap_pre[i][hr]==ROREG) nr|=1<<hr;
8347         if(regs[i].regmap_entry[hr]==ROREG) nr|=1<<hr;
8348       }
8349       if(dops[i].is_store) {
8350         if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8351         if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8352       }
8353       // Don't store a register immediately after writing it,
8354       // may prevent dual-issue.
8355       // But do so if this is a branch target, otherwise we
8356       // might have to load the register before the branch.
8357       if(i>0&&!dops[i].bt&&((regs[i].wasdirty>>hr)&1)) {
8358         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
8359           if(dops[i-1].rt1==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8360           if(dops[i-1].rt2==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8361         }
8362         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
8363           if(dops[i-1].rt1==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8364           if(dops[i-1].rt2==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8365         }
8366       }
8367     }
8368     // Cycle count is needed at branches.  Assume it is needed at the target too.
8369     if(i==0||dops[i].bt||dops[i].itype==CJUMP||dops[i].itype==SPAN) {
8370       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8371       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8372     }
8373     // Save it
8374     needed_reg[i]=nr;
8375
8376     // Deallocate unneeded registers
8377     for(hr=0;hr<HOST_REGS;hr++)
8378     {
8379       if(!((nr>>hr)&1)) {
8380         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
8381         if(dops[i].is_jump)
8382         {
8383           int map1 = 0, map2 = 0, temp = 0; // or -1 ??
8384           if (dops[i+1].is_load || dops[i+1].is_store)
8385             map1 = ROREG;
8386           if (dops[i+1].is_store)
8387             map2 = INVCP;
8388           if(dops[i+1].itype==LOADLR || dops[i+1].itype==STORELR || dops[i+1].itype==C2LS)
8389             temp = FTEMP;
8390           if((regs[i].regmap[hr]&63)!=dops[i].rs1 && (regs[i].regmap[hr]&63)!=dops[i].rs2 &&
8391              (regs[i].regmap[hr]&63)!=dops[i].rt1 && (regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8392              (regs[i].regmap[hr]&63)!=dops[i+1].rt1 && (regs[i].regmap[hr]&63)!=dops[i+1].rt2 &&
8393              regs[i].regmap[hr]!=dops[i+1].rs1 && regs[i].regmap[hr]!=dops[i+1].rs2 &&
8394              (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=PTEMP &&
8395              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
8396              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
8397              regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2)
8398           {
8399             regs[i].regmap[hr]=-1;
8400             regs[i].isconst&=~(1<<hr);
8401             if((branch_regs[i].regmap[hr]&63)!=dops[i].rs1 && (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 &&
8402                (branch_regs[i].regmap[hr]&63)!=dops[i].rt1 && (branch_regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8403                (branch_regs[i].regmap[hr]&63)!=dops[i+1].rt1 && (branch_regs[i].regmap[hr]&63)!=dops[i+1].rt2 &&
8404                branch_regs[i].regmap[hr]!=dops[i+1].rs1 && branch_regs[i].regmap[hr]!=dops[i+1].rs2 &&
8405                (branch_regs[i].regmap[hr]&63)!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
8406                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
8407                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
8408                branch_regs[i].regmap[hr]!=map1 && branch_regs[i].regmap[hr]!=map2)
8409             {
8410               branch_regs[i].regmap[hr]=-1;
8411               branch_regs[i].regmap_entry[hr]=-1;
8412               if (!dops[i].is_ujump)
8413               {
8414                 if (i < slen-2) {
8415                   regmap_pre[i+2][hr]=-1;
8416                   regs[i+2].wasconst&=~(1<<hr);
8417                 }
8418               }
8419             }
8420           }
8421         }
8422         else
8423         {
8424           // Non-branch
8425           if(i>0)
8426           {
8427             int map1 = -1, map2 = -1, temp=-1;
8428             if (dops[i].is_load || dops[i].is_store)
8429               map1 = ROREG;
8430             if (dops[i].is_store)
8431               map2 = INVCP;
8432             if (dops[i].itype==LOADLR || dops[i].itype==STORELR || dops[i].itype==C2LS)
8433               temp = FTEMP;
8434             if((regs[i].regmap[hr]&63)!=dops[i].rt1 && (regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8435                regs[i].regmap[hr]!=dops[i].rs1 && regs[i].regmap[hr]!=dops[i].rs2 &&
8436                (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2 &&
8437                (dops[i].itype!=SPAN||regs[i].regmap[hr]!=CCREG))
8438             {
8439               if(i<slen-1&&!dops[i].is_ds) {
8440                 assert(regs[i].regmap[hr]<64);
8441                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8442                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8443                 {
8444                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8445                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8446                 }
8447                 regmap_pre[i+1][hr]=-1;
8448                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8449                 regs[i+1].wasconst&=~(1<<hr);
8450               }
8451               regs[i].regmap[hr]=-1;
8452               regs[i].isconst&=~(1<<hr);
8453             }
8454           }
8455         }
8456       } // if needed
8457     } // for hr
8458   }
8459
8460   /* Pass 5 - Pre-allocate registers */
8461
8462   // If a register is allocated during a loop, try to allocate it for the
8463   // entire loop, if possible.  This avoids loading/storing registers
8464   // inside of the loop.
8465
8466   signed char f_regmap[HOST_REGS];
8467   clear_all_regs(f_regmap);
8468   for(i=0;i<slen-1;i++)
8469   {
8470     if(dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8471     {
8472       if(ba[i]>=start && ba[i]<(start+i*4))
8473       if(dops[i+1].itype==NOP||dops[i+1].itype==MOV||dops[i+1].itype==ALU
8474       ||dops[i+1].itype==SHIFTIMM||dops[i+1].itype==IMM16||dops[i+1].itype==LOAD
8475       ||dops[i+1].itype==STORE||dops[i+1].itype==STORELR||dops[i+1].itype==C1LS
8476       ||dops[i+1].itype==SHIFT||dops[i+1].itype==COP1
8477       ||dops[i+1].itype==COP2||dops[i+1].itype==C2LS||dops[i+1].itype==C2OP)
8478       {
8479         int t=(ba[i]-start)>>2;
8480         if(t > 0 && !dops[t-1].is_jump) // loop_preload can't handle jumps into delay slots
8481         if(t<2||(dops[t-2].itype!=UJUMP&&dops[t-2].itype!=RJUMP)||dops[t-2].rt1!=31) // call/ret assumes no registers allocated
8482         for(hr=0;hr<HOST_REGS;hr++)
8483         {
8484           if(regs[i].regmap[hr]>=0) {
8485             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8486               // dealloc old register
8487               int n;
8488               for(n=0;n<HOST_REGS;n++)
8489               {
8490                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8491               }
8492               // and alloc new one
8493               f_regmap[hr]=regs[i].regmap[hr];
8494             }
8495           }
8496           if(branch_regs[i].regmap[hr]>=0) {
8497             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8498               // dealloc old register
8499               int n;
8500               for(n=0;n<HOST_REGS;n++)
8501               {
8502                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8503               }
8504               // and alloc new one
8505               f_regmap[hr]=branch_regs[i].regmap[hr];
8506             }
8507           }
8508           if(dops[i].ooo) {
8509             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8510               f_regmap[hr]=branch_regs[i].regmap[hr];
8511           }else{
8512             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8513               f_regmap[hr]=branch_regs[i].regmap[hr];
8514           }
8515           // Avoid dirty->clean transition
8516           #ifdef DESTRUCTIVE_WRITEBACK
8517           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;
8518           #endif
8519           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8520           // case above, however it's always a good idea.  We can't hoist the
8521           // load if the register was already allocated, so there's no point
8522           // wasting time analyzing most of these cases.  It only "succeeds"
8523           // when the mapping was different and the load can be replaced with
8524           // a mov, which is of negligible benefit.  So such cases are
8525           // skipped below.
8526           if(f_regmap[hr]>0) {
8527             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8528               int r=f_regmap[hr];
8529               for(j=t;j<=i;j++)
8530               {
8531                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8532                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8533                 assert(r < 64);
8534                 if(regs[j].regmap[hr]==f_regmap[hr]&&(f_regmap[hr]&63)<TEMPREG) {
8535                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8536                   int k;
8537                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8538                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8539                     if(r>63) {
8540                       if(get_reg(regs[i].regmap,r&63)<0) break;
8541                       if(get_reg(branch_regs[i].regmap,r&63)<0) break;
8542                     }
8543                     k=i;
8544                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8545                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8546                         //printf("no free regs for store %x\n",start+(k-1)*4);
8547                         break;
8548                       }
8549                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8550                         //printf("no-match due to different register\n");
8551                         break;
8552                       }
8553                       if (dops[k-2].is_jump) {
8554                         //printf("no-match due to branch\n");
8555                         break;
8556                       }
8557                       // call/ret fast path assumes no registers allocated
8558                       if(k>2&&(dops[k-3].itype==UJUMP||dops[k-3].itype==RJUMP)&&dops[k-3].rt1==31) {
8559                         break;
8560                       }
8561                       assert(r < 64);
8562                       k--;
8563                     }
8564                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8565                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8566                       while(k<i) {
8567                         regs[k].regmap_entry[hr]=f_regmap[hr];
8568                         regs[k].regmap[hr]=f_regmap[hr];
8569                         regmap_pre[k+1][hr]=f_regmap[hr];
8570                         regs[k].wasdirty&=~(1<<hr);
8571                         regs[k].dirty&=~(1<<hr);
8572                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8573                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8574                         regs[k].wasconst&=~(1<<hr);
8575                         regs[k].isconst&=~(1<<hr);
8576                         k++;
8577                       }
8578                     }
8579                     else {
8580                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8581                       break;
8582                     }
8583                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8584                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8585                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8586                       regs[i].regmap_entry[hr]=f_regmap[hr];
8587                       regs[i].regmap[hr]=f_regmap[hr];
8588                       regs[i].wasdirty&=~(1<<hr);
8589                       regs[i].dirty&=~(1<<hr);
8590                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8591                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8592                       regs[i].wasconst&=~(1<<hr);
8593                       regs[i].isconst&=~(1<<hr);
8594                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8595                       branch_regs[i].wasdirty&=~(1<<hr);
8596                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8597                       branch_regs[i].regmap[hr]=f_regmap[hr];
8598                       branch_regs[i].dirty&=~(1<<hr);
8599                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8600                       branch_regs[i].wasconst&=~(1<<hr);
8601                       branch_regs[i].isconst&=~(1<<hr);
8602                       if (!dops[i].is_ujump) {
8603                         regmap_pre[i+2][hr]=f_regmap[hr];
8604                         regs[i+2].wasdirty&=~(1<<hr);
8605                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8606                       }
8607                     }
8608                   }
8609                   for(k=t;k<j;k++) {
8610                     // Alloc register clean at beginning of loop,
8611                     // but may dirty it in pass 6
8612                     regs[k].regmap_entry[hr]=f_regmap[hr];
8613                     regs[k].regmap[hr]=f_regmap[hr];
8614                     regs[k].dirty&=~(1<<hr);
8615                     regs[k].wasconst&=~(1<<hr);
8616                     regs[k].isconst&=~(1<<hr);
8617                     if (dops[k].is_jump) {
8618                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8619                       branch_regs[k].regmap[hr]=f_regmap[hr];
8620                       branch_regs[k].dirty&=~(1<<hr);
8621                       branch_regs[k].wasconst&=~(1<<hr);
8622                       branch_regs[k].isconst&=~(1<<hr);
8623                       if (!dops[k].is_ujump) {
8624                         regmap_pre[k+2][hr]=f_regmap[hr];
8625                         regs[k+2].wasdirty&=~(1<<hr);
8626                       }
8627                     }
8628                     else
8629                     {
8630                       regmap_pre[k+1][hr]=f_regmap[hr];
8631                       regs[k+1].wasdirty&=~(1<<hr);
8632                     }
8633                   }
8634                   if(regs[j].regmap[hr]==f_regmap[hr])
8635                     regs[j].regmap_entry[hr]=f_regmap[hr];
8636                   break;
8637                 }
8638                 if(j==i) break;
8639                 if(regs[j].regmap[hr]>=0)
8640                   break;
8641                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8642                   //printf("no-match due to different register\n");
8643                   break;
8644                 }
8645                 if (dops[j].is_ujump)
8646                 {
8647                   // Stop on unconditional branch
8648                   break;
8649                 }
8650                 if(dops[j].itype==CJUMP||dops[j].itype==SJUMP)
8651                 {
8652                   if(dops[j].ooo) {
8653                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8654                       break;
8655                   }else{
8656                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8657                       break;
8658                   }
8659                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8660                     //printf("no-match due to different register (branch)\n");
8661                     break;
8662                   }
8663                 }
8664                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8665                   //printf("No free regs for store %x\n",start+j*4);
8666                   break;
8667                 }
8668                 assert(f_regmap[hr]<64);
8669               }
8670             }
8671           }
8672         }
8673       }
8674     }else{
8675       // Non branch or undetermined branch target
8676       for(hr=0;hr<HOST_REGS;hr++)
8677       {
8678         if(hr!=EXCLUDE_REG) {
8679           if(regs[i].regmap[hr]>=0) {
8680             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8681               // dealloc old register
8682               int n;
8683               for(n=0;n<HOST_REGS;n++)
8684               {
8685                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8686               }
8687               // and alloc new one
8688               f_regmap[hr]=regs[i].regmap[hr];
8689             }
8690           }
8691         }
8692       }
8693       // Try to restore cycle count at branch targets
8694       if(dops[i].bt) {
8695         for(j=i;j<slen-1;j++) {
8696           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8697           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8698             //printf("no free regs for store %x\n",start+j*4);
8699             break;
8700           }
8701         }
8702         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8703           int k=i;
8704           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8705           while(k<j) {
8706             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8707             regs[k].regmap[HOST_CCREG]=CCREG;
8708             regmap_pre[k+1][HOST_CCREG]=CCREG;
8709             regs[k+1].wasdirty|=1<<HOST_CCREG;
8710             regs[k].dirty|=1<<HOST_CCREG;
8711             regs[k].wasconst&=~(1<<HOST_CCREG);
8712             regs[k].isconst&=~(1<<HOST_CCREG);
8713             k++;
8714           }
8715           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8716         }
8717         // Work backwards from the branch target
8718         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8719         {
8720           //printf("Extend backwards\n");
8721           int k;
8722           k=i;
8723           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8724             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8725               //printf("no free regs for store %x\n",start+(k-1)*4);
8726               break;
8727             }
8728             k--;
8729           }
8730           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8731             //printf("Extend CC, %x ->\n",start+k*4);
8732             while(k<=i) {
8733               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8734               regs[k].regmap[HOST_CCREG]=CCREG;
8735               regmap_pre[k+1][HOST_CCREG]=CCREG;
8736               regs[k+1].wasdirty|=1<<HOST_CCREG;
8737               regs[k].dirty|=1<<HOST_CCREG;
8738               regs[k].wasconst&=~(1<<HOST_CCREG);
8739               regs[k].isconst&=~(1<<HOST_CCREG);
8740               k++;
8741             }
8742           }
8743           else {
8744             //printf("Fail Extend CC, %x ->\n",start+k*4);
8745           }
8746         }
8747       }
8748       if(dops[i].itype!=STORE&&dops[i].itype!=STORELR&&dops[i].itype!=C1LS&&dops[i].itype!=SHIFT&&
8749          dops[i].itype!=NOP&&dops[i].itype!=MOV&&dops[i].itype!=ALU&&dops[i].itype!=SHIFTIMM&&
8750          dops[i].itype!=IMM16&&dops[i].itype!=LOAD&&dops[i].itype!=COP1)
8751       {
8752         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8753       }
8754     }
8755   }
8756
8757   // This allocates registers (if possible) one instruction prior
8758   // to use, which can avoid a load-use penalty on certain CPUs.
8759   for(i=0;i<slen-1;i++)
8760   {
8761     if (!i || !dops[i-1].is_jump)
8762     {
8763       if(!dops[i+1].bt)
8764       {
8765         if(dops[i].itype==ALU||dops[i].itype==MOV||dops[i].itype==LOAD||dops[i].itype==SHIFTIMM||dops[i].itype==IMM16
8766            ||((dops[i].itype==COP1||dops[i].itype==COP2)&&dops[i].opcode2<3))
8767         {
8768           if(dops[i+1].rs1) {
8769             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs1))>=0)
8770             {
8771               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8772               {
8773                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8774                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8775                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8776                 regs[i].isconst&=~(1<<hr);
8777                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8778                 constmap[i][hr]=constmap[i+1][hr];
8779                 regs[i+1].wasdirty&=~(1<<hr);
8780                 regs[i].dirty&=~(1<<hr);
8781               }
8782             }
8783           }
8784           if(dops[i+1].rs2) {
8785             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs2))>=0)
8786             {
8787               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8788               {
8789                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8790                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8791                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8792                 regs[i].isconst&=~(1<<hr);
8793                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8794                 constmap[i][hr]=constmap[i+1][hr];
8795                 regs[i+1].wasdirty&=~(1<<hr);
8796                 regs[i].dirty&=~(1<<hr);
8797               }
8798             }
8799           }
8800           // Preload target address for load instruction (non-constant)
8801           if(dops[i+1].itype==LOAD&&dops[i+1].rs1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8802             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8803             {
8804               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8805               {
8806                 regs[i].regmap[hr]=dops[i+1].rs1;
8807                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8808                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8809                 regs[i].isconst&=~(1<<hr);
8810                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8811                 constmap[i][hr]=constmap[i+1][hr];
8812                 regs[i+1].wasdirty&=~(1<<hr);
8813                 regs[i].dirty&=~(1<<hr);
8814               }
8815             }
8816           }
8817           // Load source into target register
8818           if(dops[i+1].lt1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8819             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8820             {
8821               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8822               {
8823                 regs[i].regmap[hr]=dops[i+1].rs1;
8824                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8825                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8826                 regs[i].isconst&=~(1<<hr);
8827                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8828                 constmap[i][hr]=constmap[i+1][hr];
8829                 regs[i+1].wasdirty&=~(1<<hr);
8830                 regs[i].dirty&=~(1<<hr);
8831               }
8832             }
8833           }
8834           // Address for store instruction (non-constant)
8835           if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR
8836              ||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8837             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8838               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8839               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8840               else {regs[i+1].regmap[hr]=AGEN1+((i+1)&1);regs[i+1].isconst&=~(1<<hr);}
8841               assert(hr>=0);
8842               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8843               {
8844                 regs[i].regmap[hr]=dops[i+1].rs1;
8845                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8846                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8847                 regs[i].isconst&=~(1<<hr);
8848                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8849                 constmap[i][hr]=constmap[i+1][hr];
8850                 regs[i+1].wasdirty&=~(1<<hr);
8851                 regs[i].dirty&=~(1<<hr);
8852               }
8853             }
8854           }
8855           if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
8856             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8857               int nr;
8858               hr=get_reg(regs[i+1].regmap,FTEMP);
8859               assert(hr>=0);
8860               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8861               {
8862                 regs[i].regmap[hr]=dops[i+1].rs1;
8863                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8864                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8865                 regs[i].isconst&=~(1<<hr);
8866                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8867                 constmap[i][hr]=constmap[i+1][hr];
8868                 regs[i+1].wasdirty&=~(1<<hr);
8869                 regs[i].dirty&=~(1<<hr);
8870               }
8871               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
8872               {
8873                 // move it to another register
8874                 regs[i+1].regmap[hr]=-1;
8875                 regmap_pre[i+2][hr]=-1;
8876                 regs[i+1].regmap[nr]=FTEMP;
8877                 regmap_pre[i+2][nr]=FTEMP;
8878                 regs[i].regmap[nr]=dops[i+1].rs1;
8879                 regmap_pre[i+1][nr]=dops[i+1].rs1;
8880                 regs[i+1].regmap_entry[nr]=dops[i+1].rs1;
8881                 regs[i].isconst&=~(1<<nr);
8882                 regs[i+1].isconst&=~(1<<nr);
8883                 regs[i].dirty&=~(1<<nr);
8884                 regs[i+1].wasdirty&=~(1<<nr);
8885                 regs[i+1].dirty&=~(1<<nr);
8886                 regs[i+2].wasdirty&=~(1<<nr);
8887               }
8888             }
8889           }
8890           if(dops[i+1].itype==LOAD||dops[i+1].itype==LOADLR||dops[i+1].itype==STORE||dops[i+1].itype==STORELR/*||dops[i+1].itype==C1LS||||dops[i+1].itype==C2LS*/) {
8891             if(dops[i+1].itype==LOAD)
8892               hr=get_reg(regs[i+1].regmap,dops[i+1].rt1);
8893             if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
8894               hr=get_reg(regs[i+1].regmap,FTEMP);
8895             if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SWC1/SDC1/SWC2/SDC2
8896               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
8897               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8898             }
8899             if(hr>=0&&regs[i].regmap[hr]<0) {
8900               int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
8901               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
8902                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
8903                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
8904                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
8905                 regs[i].isconst&=~(1<<hr);
8906                 regs[i+1].wasdirty&=~(1<<hr);
8907                 regs[i].dirty&=~(1<<hr);
8908               }
8909             }
8910           }
8911         }
8912       }
8913     }
8914   }
8915
8916   /* Pass 6 - Optimize clean/dirty state */
8917   clean_registers(0,slen-1,1);
8918
8919   /* Pass 7 - Identify 32-bit registers */
8920   for (i=slen-1;i>=0;i--)
8921   {
8922     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8923     {
8924       // Conditional branch
8925       if((source[i]>>16)!=0x1000&&i<slen-2) {
8926         // Mark this address as a branch target since it may be called
8927         // upon return from interrupt
8928         dops[i+2].bt=1;
8929       }
8930     }
8931   }
8932
8933   if(dops[slen-1].itype==SPAN) {
8934     dops[slen-1].bt=1; // Mark as a branch target so instruction can restart after exception
8935   }
8936
8937 #ifdef DISASM
8938   /* Debug/disassembly */
8939   for(i=0;i<slen;i++)
8940   {
8941     printf("U:");
8942     int r;
8943     for(r=1;r<=CCREG;r++) {
8944       if((unneeded_reg[i]>>r)&1) {
8945         if(r==HIREG) printf(" HI");
8946         else if(r==LOREG) printf(" LO");
8947         else printf(" r%d",r);
8948       }
8949     }
8950     printf("\n");
8951     #if defined(__i386__) || defined(__x86_64__)
8952     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]);
8953     #endif
8954     #ifdef __arm__
8955     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]);
8956     #endif
8957     #if defined(__i386__) || defined(__x86_64__)
8958     printf("needs: ");
8959     if(needed_reg[i]&1) printf("eax ");
8960     if((needed_reg[i]>>1)&1) printf("ecx ");
8961     if((needed_reg[i]>>2)&1) printf("edx ");
8962     if((needed_reg[i]>>3)&1) printf("ebx ");
8963     if((needed_reg[i]>>5)&1) printf("ebp ");
8964     if((needed_reg[i]>>6)&1) printf("esi ");
8965     if((needed_reg[i]>>7)&1) printf("edi ");
8966     printf("\n");
8967     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]);
8968     printf("dirty: ");
8969     if(regs[i].wasdirty&1) printf("eax ");
8970     if((regs[i].wasdirty>>1)&1) printf("ecx ");
8971     if((regs[i].wasdirty>>2)&1) printf("edx ");
8972     if((regs[i].wasdirty>>3)&1) printf("ebx ");
8973     if((regs[i].wasdirty>>5)&1) printf("ebp ");
8974     if((regs[i].wasdirty>>6)&1) printf("esi ");
8975     if((regs[i].wasdirty>>7)&1) printf("edi ");
8976     #endif
8977     #ifdef __arm__
8978     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]);
8979     printf("dirty: ");
8980     if(regs[i].wasdirty&1) printf("r0 ");
8981     if((regs[i].wasdirty>>1)&1) printf("r1 ");
8982     if((regs[i].wasdirty>>2)&1) printf("r2 ");
8983     if((regs[i].wasdirty>>3)&1) printf("r3 ");
8984     if((regs[i].wasdirty>>4)&1) printf("r4 ");
8985     if((regs[i].wasdirty>>5)&1) printf("r5 ");
8986     if((regs[i].wasdirty>>6)&1) printf("r6 ");
8987     if((regs[i].wasdirty>>7)&1) printf("r7 ");
8988     if((regs[i].wasdirty>>8)&1) printf("r8 ");
8989     if((regs[i].wasdirty>>9)&1) printf("r9 ");
8990     if((regs[i].wasdirty>>10)&1) printf("r10 ");
8991     if((regs[i].wasdirty>>12)&1) printf("r12 ");
8992     #endif
8993     printf("\n");
8994     disassemble_inst(i);
8995     //printf ("ccadj[%d] = %d\n",i,ccadj[i]);
8996     #if defined(__i386__) || defined(__x86_64__)
8997     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]);
8998     if(regs[i].dirty&1) printf("eax ");
8999     if((regs[i].dirty>>1)&1) printf("ecx ");
9000     if((regs[i].dirty>>2)&1) printf("edx ");
9001     if((regs[i].dirty>>3)&1) printf("ebx ");
9002     if((regs[i].dirty>>5)&1) printf("ebp ");
9003     if((regs[i].dirty>>6)&1) printf("esi ");
9004     if((regs[i].dirty>>7)&1) printf("edi ");
9005     #endif
9006     #ifdef __arm__
9007     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]);
9008     if(regs[i].dirty&1) printf("r0 ");
9009     if((regs[i].dirty>>1)&1) printf("r1 ");
9010     if((regs[i].dirty>>2)&1) printf("r2 ");
9011     if((regs[i].dirty>>3)&1) printf("r3 ");
9012     if((regs[i].dirty>>4)&1) printf("r4 ");
9013     if((regs[i].dirty>>5)&1) printf("r5 ");
9014     if((regs[i].dirty>>6)&1) printf("r6 ");
9015     if((regs[i].dirty>>7)&1) printf("r7 ");
9016     if((regs[i].dirty>>8)&1) printf("r8 ");
9017     if((regs[i].dirty>>9)&1) printf("r9 ");
9018     if((regs[i].dirty>>10)&1) printf("r10 ");
9019     if((regs[i].dirty>>12)&1) printf("r12 ");
9020     #endif
9021     printf("\n");
9022     if(regs[i].isconst) {
9023       printf("constants: ");
9024       #if defined(__i386__) || defined(__x86_64__)
9025       if(regs[i].isconst&1) printf("eax=%x ",(u_int)constmap[i][0]);
9026       if((regs[i].isconst>>1)&1) printf("ecx=%x ",(u_int)constmap[i][1]);
9027       if((regs[i].isconst>>2)&1) printf("edx=%x ",(u_int)constmap[i][2]);
9028       if((regs[i].isconst>>3)&1) printf("ebx=%x ",(u_int)constmap[i][3]);
9029       if((regs[i].isconst>>5)&1) printf("ebp=%x ",(u_int)constmap[i][5]);
9030       if((regs[i].isconst>>6)&1) printf("esi=%x ",(u_int)constmap[i][6]);
9031       if((regs[i].isconst>>7)&1) printf("edi=%x ",(u_int)constmap[i][7]);
9032       #endif
9033       #if defined(__arm__) || defined(__aarch64__)
9034       int r;
9035       for (r = 0; r < ARRAY_SIZE(constmap[i]); r++)
9036         if ((regs[i].isconst >> r) & 1)
9037           printf(" r%d=%x", r, (u_int)constmap[i][r]);
9038       #endif
9039       printf("\n");
9040     }
9041     if(dops[i].is_jump) {
9042       #if defined(__i386__) || defined(__x86_64__)
9043       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]);
9044       if(branch_regs[i].dirty&1) printf("eax ");
9045       if((branch_regs[i].dirty>>1)&1) printf("ecx ");
9046       if((branch_regs[i].dirty>>2)&1) printf("edx ");
9047       if((branch_regs[i].dirty>>3)&1) printf("ebx ");
9048       if((branch_regs[i].dirty>>5)&1) printf("ebp ");
9049       if((branch_regs[i].dirty>>6)&1) printf("esi ");
9050       if((branch_regs[i].dirty>>7)&1) printf("edi ");
9051       #endif
9052       #ifdef __arm__
9053       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]);
9054       if(branch_regs[i].dirty&1) printf("r0 ");
9055       if((branch_regs[i].dirty>>1)&1) printf("r1 ");
9056       if((branch_regs[i].dirty>>2)&1) printf("r2 ");
9057       if((branch_regs[i].dirty>>3)&1) printf("r3 ");
9058       if((branch_regs[i].dirty>>4)&1) printf("r4 ");
9059       if((branch_regs[i].dirty>>5)&1) printf("r5 ");
9060       if((branch_regs[i].dirty>>6)&1) printf("r6 ");
9061       if((branch_regs[i].dirty>>7)&1) printf("r7 ");
9062       if((branch_regs[i].dirty>>8)&1) printf("r8 ");
9063       if((branch_regs[i].dirty>>9)&1) printf("r9 ");
9064       if((branch_regs[i].dirty>>10)&1) printf("r10 ");
9065       if((branch_regs[i].dirty>>12)&1) printf("r12 ");
9066       #endif
9067     }
9068   }
9069 #endif // DISASM
9070
9071   /* Pass 8 - Assembly */
9072   linkcount=0;stubcount=0;
9073   ds=0;is_delayslot=0;
9074   u_int dirty_pre=0;
9075   void *beginning=start_block();
9076   if((u_int)addr&1) {
9077     ds=1;
9078     pagespan_ds();
9079   }
9080   void *instr_addr0_override = NULL;
9081
9082   if (start == 0x80030000) {
9083     // nasty hack for the fastbios thing
9084     // override block entry to this code
9085     instr_addr0_override = out;
9086     emit_movimm(start,0);
9087     // abuse io address var as a flag that we
9088     // have already returned here once
9089     emit_readword(&address,1);
9090     emit_writeword(0,&pcaddr);
9091     emit_writeword(0,&address);
9092     emit_cmp(0,1);
9093     #ifdef __aarch64__
9094     emit_jeq(out + 4*2);
9095     emit_far_jump(new_dyna_leave);
9096     #else
9097     emit_jne(new_dyna_leave);
9098     #endif
9099   }
9100   for(i=0;i<slen;i++)
9101   {
9102     //if(ds) printf("ds: ");
9103     disassemble_inst(i);
9104     if(ds) {
9105       ds=0; // Skip delay slot
9106       if(dops[i].bt) assem_debug("OOPS - branch into delay slot\n");
9107       instr_addr[i] = NULL;
9108     } else {
9109       speculate_register_values(i);
9110       #ifndef DESTRUCTIVE_WRITEBACK
9111       if (i < 2 || !dops[i-2].is_ujump)
9112       {
9113         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
9114       }
9115       if((dops[i].itype==CJUMP||dops[i].itype==SJUMP)) {
9116         dirty_pre=branch_regs[i].dirty;
9117       }else{
9118         dirty_pre=regs[i].dirty;
9119       }
9120       #endif
9121       // write back
9122       if (i < 2 || !dops[i-2].is_ujump)
9123       {
9124         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
9125         loop_preload(regmap_pre[i],regs[i].regmap_entry);
9126       }
9127       // branch target entry point
9128       instr_addr[i] = out;
9129       assem_debug("<->\n");
9130       drc_dbg_emit_do_cmp(i);
9131
9132       // load regs
9133       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
9134         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
9135       load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i].rs1,dops[i].rs2);
9136       address_generation(i,&regs[i],regs[i].regmap_entry);
9137       load_consts(regmap_pre[i],regs[i].regmap,i);
9138       if(dops[i].is_jump)
9139       {
9140         // Load the delay slot registers if necessary
9141         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2&&(dops[i+1].rs1!=dops[i].rt1||dops[i].rt1==0))
9142           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9143         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2&&(dops[i+1].rs2!=dops[i].rt1||dops[i].rt1==0))
9144           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9145         if (ram_offset && (dops[i+1].is_load || dops[i+1].is_store))
9146           load_regs(regs[i].regmap_entry,regs[i].regmap,ROREG,ROREG);
9147         if (dops[i+1].is_store)
9148           load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9149       }
9150       else if(i+1<slen)
9151       {
9152         // Preload registers for following instruction
9153         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2)
9154           if(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs1!=dops[i].rt2)
9155             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9156         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2)
9157           if(dops[i+1].rs2!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt2)
9158             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9159       }
9160       // TODO: if(is_ooo(i)) address_generation(i+1);
9161       if (dops[i].itype == CJUMP)
9162         load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
9163       if (ram_offset && (dops[i].is_load || dops[i].is_store))
9164         load_regs(regs[i].regmap_entry,regs[i].regmap,ROREG,ROREG);
9165       if (dops[i].is_store)
9166         load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9167       // assemble
9168       switch(dops[i].itype) {
9169         case ALU:
9170           alu_assemble(i,&regs[i]);break;
9171         case IMM16:
9172           imm16_assemble(i,&regs[i]);break;
9173         case SHIFT:
9174           shift_assemble(i,&regs[i]);break;
9175         case SHIFTIMM:
9176           shiftimm_assemble(i,&regs[i]);break;
9177         case LOAD:
9178           load_assemble(i,&regs[i]);break;
9179         case LOADLR:
9180           loadlr_assemble(i,&regs[i]);break;
9181         case STORE:
9182           store_assemble(i,&regs[i]);break;
9183         case STORELR:
9184           storelr_assemble(i,&regs[i]);break;
9185         case COP0:
9186           cop0_assemble(i,&regs[i]);break;
9187         case COP1:
9188           cop1_assemble(i,&regs[i]);break;
9189         case C1LS:
9190           c1ls_assemble(i,&regs[i]);break;
9191         case COP2:
9192           cop2_assemble(i,&regs[i]);break;
9193         case C2LS:
9194           c2ls_assemble(i,&regs[i]);break;
9195         case C2OP:
9196           c2op_assemble(i,&regs[i]);break;
9197         case MULTDIV:
9198           multdiv_assemble(i,&regs[i]);
9199           multdiv_prepare_stall(i,&regs[i]);
9200           break;
9201         case MOV:
9202           mov_assemble(i,&regs[i]);break;
9203         case SYSCALL:
9204           syscall_assemble(i,&regs[i]);break;
9205         case HLECALL:
9206           hlecall_assemble(i,&regs[i]);break;
9207         case INTCALL:
9208           intcall_assemble(i,&regs[i]);break;
9209         case UJUMP:
9210           ujump_assemble(i,&regs[i]);ds=1;break;
9211         case RJUMP:
9212           rjump_assemble(i,&regs[i]);ds=1;break;
9213         case CJUMP:
9214           cjump_assemble(i,&regs[i]);ds=1;break;
9215         case SJUMP:
9216           sjump_assemble(i,&regs[i]);ds=1;break;
9217         case SPAN:
9218           pagespan_assemble(i,&regs[i]);break;
9219       }
9220       if (dops[i].is_ujump)
9221         literal_pool(1024);
9222       else
9223         literal_pool_jumpover(256);
9224     }
9225   }
9226
9227   assert(slen > 0);
9228   if (slen > 0 && dops[slen-1].itype == INTCALL) {
9229     // no ending needed for this block since INTCALL never returns
9230   }
9231   // If the block did not end with an unconditional branch,
9232   // add a jump to the next instruction.
9233   else if (i > 1) {
9234     if (!dops[i-2].is_ujump && dops[i-1].itype != SPAN) {
9235       assert(!dops[i-1].is_jump);
9236       assert(i==slen);
9237       if(dops[i-2].itype!=CJUMP&&dops[i-2].itype!=SJUMP) {
9238         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9239         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9240           emit_loadreg(CCREG,HOST_CCREG);
9241         emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
9242       }
9243       else
9244       {
9245         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
9246         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
9247       }
9248       add_to_linker(out,start+i*4,0);
9249       emit_jmp(0);
9250     }
9251   }
9252   else
9253   {
9254     assert(i>0);
9255     assert(!dops[i-1].is_jump);
9256     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9257     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9258       emit_loadreg(CCREG,HOST_CCREG);
9259     emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
9260     add_to_linker(out,start+i*4,0);
9261     emit_jmp(0);
9262   }
9263
9264   // TODO: delay slot stubs?
9265   // Stubs
9266   for(i=0;i<stubcount;i++)
9267   {
9268     switch(stubs[i].type)
9269     {
9270       case LOADB_STUB:
9271       case LOADH_STUB:
9272       case LOADW_STUB:
9273       case LOADD_STUB:
9274       case LOADBU_STUB:
9275       case LOADHU_STUB:
9276         do_readstub(i);break;
9277       case STOREB_STUB:
9278       case STOREH_STUB:
9279       case STOREW_STUB:
9280       case STORED_STUB:
9281         do_writestub(i);break;
9282       case CC_STUB:
9283         do_ccstub(i);break;
9284       case INVCODE_STUB:
9285         do_invstub(i);break;
9286       case FP_STUB:
9287         do_cop1stub(i);break;
9288       case STORELR_STUB:
9289         do_unalignedwritestub(i);break;
9290     }
9291   }
9292
9293   if (instr_addr0_override)
9294     instr_addr[0] = instr_addr0_override;
9295
9296   /* Pass 9 - Linker */
9297   for(i=0;i<linkcount;i++)
9298   {
9299     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9300     literal_pool(64);
9301     if (!link_addr[i].ext)
9302     {
9303       void *stub = out;
9304       void *addr = check_addr(link_addr[i].target);
9305       emit_extjump(link_addr[i].addr, link_addr[i].target);
9306       if (addr) {
9307         set_jump_target(link_addr[i].addr, addr);
9308         add_jump_out(link_addr[i].target,stub);
9309       }
9310       else
9311         set_jump_target(link_addr[i].addr, stub);
9312     }
9313     else
9314     {
9315       // Internal branch
9316       int target=(link_addr[i].target-start)>>2;
9317       assert(target>=0&&target<slen);
9318       assert(instr_addr[target]);
9319       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9320       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9321       //#else
9322       set_jump_target(link_addr[i].addr, instr_addr[target]);
9323       //#endif
9324     }
9325   }
9326
9327   u_int source_len = slen*4;
9328   if (dops[slen-1].itype == INTCALL && source_len > 4)
9329     // no need to treat the last instruction as compiled
9330     // as interpreter fully handles it
9331     source_len -= 4;
9332
9333   if ((u_char *)copy + source_len > (u_char *)shadow + sizeof(shadow))
9334     copy = shadow;
9335
9336   // External Branch Targets (jump_in)
9337   for(i=0;i<slen;i++)
9338   {
9339     if(dops[i].bt||i==0)
9340     {
9341       if(instr_addr[i]) // TODO - delay slots (=null)
9342       {
9343         u_int vaddr=start+i*4;
9344         u_int page=get_page(vaddr);
9345         u_int vpage=get_vpage(vaddr);
9346         literal_pool(256);
9347         {
9348           assem_debug("%p (%d) <- %8x\n",instr_addr[i],i,start+i*4);
9349           assem_debug("jump_in: %x\n",start+i*4);
9350           ll_add(jump_dirty+vpage,vaddr,out);
9351           void *entry_point = do_dirty_stub(i, source_len);
9352           ll_add_flags(jump_in+page,vaddr,state_rflags,entry_point);
9353           // If there was an existing entry in the hash table,
9354           // replace it with the new address.
9355           // Don't add new entries.  We'll insert the
9356           // ones that actually get used in check_addr().
9357           struct ht_entry *ht_bin = hash_table_get(vaddr);
9358           if (ht_bin->vaddr[0] == vaddr)
9359             ht_bin->tcaddr[0] = entry_point;
9360           if (ht_bin->vaddr[1] == vaddr)
9361             ht_bin->tcaddr[1] = entry_point;
9362         }
9363       }
9364     }
9365   }
9366   // Write out the literal pool if necessary
9367   literal_pool(0);
9368   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9369   // Align code
9370   if(((u_int)out)&7) emit_addnop(13);
9371   #endif
9372   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9373   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9374   memcpy(copy, source, source_len);
9375   copy += source_len;
9376
9377   end_block(beginning);
9378
9379   // If we're within 256K of the end of the buffer,
9380   // start over from the beginning. (Is 256K enough?)
9381   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9382     out = ndrc->translation_cache;
9383
9384   // Trap writes to any of the pages we compiled
9385   for(i=start>>12;i<=(start+slen*4)>>12;i++) {
9386     invalid_code[i]=0;
9387   }
9388   inv_code_start=inv_code_end=~0;
9389
9390   // for PCSX we need to mark all mirrors too
9391   if(get_page(start)<(RAM_SIZE>>12))
9392     for(i=start>>12;i<=(start+slen*4)>>12;i++)
9393       invalid_code[((u_int)0x00000000>>12)|(i&0x1ff)]=
9394       invalid_code[((u_int)0x80000000>>12)|(i&0x1ff)]=
9395       invalid_code[((u_int)0xa0000000>>12)|(i&0x1ff)]=0;
9396
9397   /* Pass 10 - Free memory by expiring oldest blocks */
9398
9399   int end=(((out-ndrc->translation_cache)>>(TARGET_SIZE_2-16))+16384)&65535;
9400   while(expirep!=end)
9401   {
9402     int shift=TARGET_SIZE_2-3; // Divide into 8 blocks
9403     uintptr_t base_offs = ((uintptr_t)(expirep >> 13) << shift); // Base offset of this block
9404     uintptr_t base_offs_s = base_offs >> shift;
9405     inv_debug("EXP: Phase %d\n",expirep);
9406     switch((expirep>>11)&3)
9407     {
9408       case 0:
9409         // Clear jump_in and jump_dirty
9410         ll_remove_matching_addrs(jump_in+(expirep&2047),base_offs_s,shift);
9411         ll_remove_matching_addrs(jump_dirty+(expirep&2047),base_offs_s,shift);
9412         ll_remove_matching_addrs(jump_in+2048+(expirep&2047),base_offs_s,shift);
9413         ll_remove_matching_addrs(jump_dirty+2048+(expirep&2047),base_offs_s,shift);
9414         break;
9415       case 1:
9416         // Clear pointers
9417         ll_kill_pointers(jump_out[expirep&2047],base_offs_s,shift);
9418         ll_kill_pointers(jump_out[(expirep&2047)+2048],base_offs_s,shift);
9419         break;
9420       case 2:
9421         // Clear hash table
9422         for(i=0;i<32;i++) {
9423           struct ht_entry *ht_bin = &hash_table[((expirep&2047)<<5)+i];
9424           uintptr_t o1 = (u_char *)ht_bin->tcaddr[1] - ndrc->translation_cache;
9425           uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
9426           if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s) {
9427             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[1],ht_bin->tcaddr[1]);
9428             ht_bin->vaddr[1] = -1;
9429             ht_bin->tcaddr[1] = NULL;
9430           }
9431           o1 = (u_char *)ht_bin->tcaddr[0] - ndrc->translation_cache;
9432           o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
9433           if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s) {
9434             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[0],ht_bin->tcaddr[0]);
9435             ht_bin->vaddr[0] = ht_bin->vaddr[1];
9436             ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
9437             ht_bin->vaddr[1] = -1;
9438             ht_bin->tcaddr[1] = NULL;
9439           }
9440         }
9441         break;
9442       case 3:
9443         // Clear jump_out
9444         if((expirep&2047)==0)
9445           do_clear_cache();
9446         ll_remove_matching_addrs(jump_out+(expirep&2047),base_offs_s,shift);
9447         ll_remove_matching_addrs(jump_out+2048+(expirep&2047),base_offs_s,shift);
9448         break;
9449     }
9450     expirep=(expirep+1)&65535;
9451   }
9452 #ifdef ASSEM_PRINT
9453   fflush(stdout);
9454 #endif
9455   return 0;
9456 }
9457
9458 // vim:shiftwidth=2:expandtab