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