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