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