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