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