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