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