forked from N64Recomp/N64Recomp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsp_recomp.cpp
757 lines (688 loc) · 33.2 KB
/
rsp_recomp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
#include <optional>
#include <fstream>
#include <array>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <cassert>
#include <iostream>
#include <filesystem>
#include "rabbitizer.hpp"
#include "fmt/format.h"
#include "fmt/ostream.h"
#include <toml++/toml.hpp>
using InstrId = rabbitizer::InstrId::UniqueId;
using Cop0Reg = rabbitizer::Registers::Rsp::Cop0;
constexpr size_t instr_size = sizeof(uint32_t);
constexpr uint32_t rsp_mem_mask = 0x1FFF;
// Can't use rabbitizer's operand types because we need to be able to provide a register reference or a register index
enum class RspOperand {
None,
Vt,
VtIndex,
Vd,
Vs,
VsIndex,
De,
Rt,
Rs,
Imm7,
};
std::unordered_map<InstrId, std::array<RspOperand, 3>> vector_operands{
// Vt, Rs, Imm
{ InstrId::rsp_lbv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_ldv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_lfv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_lhv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_llv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_lpv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_lqv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_lrv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_lsv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_luv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
// { InstrId::rsp_lwv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}}, // Not in rabbitizer
{ InstrId::rsp_sbv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_sdv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_sfv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_shv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_slv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_spv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_sqv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_srv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_ssv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_suv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_swv, {RspOperand::Vt, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_stv, {RspOperand::VtIndex, RspOperand::Rs, RspOperand::Imm7}},
{ InstrId::rsp_ltv, {RspOperand::VtIndex, RspOperand::Rs, RspOperand::Imm7}},
// Vd, Vs, Vt
{ InstrId::rsp_vabs, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vadd, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vaddc, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vand, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vch, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vcl, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vcr, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_veq, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vge, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vlt, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmacf, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmacu, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmadh, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmadl, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmadm, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmadn, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmrg, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmudh, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmudl, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmudm, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmudn, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vne, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vnor, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vnxor, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vor, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vsub, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vsubc, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmulf, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmulu, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vmulq, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vnand, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vxor, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}},
{ InstrId::rsp_vsar, {RspOperand::Vd, RspOperand::Vs, RspOperand::None}},
{ InstrId::rsp_vmacq, {RspOperand::Vd, RspOperand::None, RspOperand::None}},
// { InstrId::rsp_vzero, {RspOperand::Vd, RspOperand::Vs, RspOperand::Vt}}, unused pseudo
{ InstrId::rsp_vrndn, {RspOperand::Vd, RspOperand::VsIndex, RspOperand::Vt}},
{ InstrId::rsp_vrndp, {RspOperand::Vd, RspOperand::VsIndex, RspOperand::Vt}},
// Vd, De, Vt
{ InstrId::rsp_vmov, {RspOperand::Vd, RspOperand::De, RspOperand::Vt}},
{ InstrId::rsp_vrcp, {RspOperand::Vd, RspOperand::De, RspOperand::Vt}},
{ InstrId::rsp_vrcpl, {RspOperand::Vd, RspOperand::De, RspOperand::Vt}},
{ InstrId::rsp_vrcph, {RspOperand::Vd, RspOperand::De, RspOperand::Vt}},
{ InstrId::rsp_vrsq, {RspOperand::Vd, RspOperand::De, RspOperand::Vt}},
{ InstrId::rsp_vrsql, {RspOperand::Vd, RspOperand::De, RspOperand::Vt}},
{ InstrId::rsp_vrsqh, {RspOperand::Vd, RspOperand::De, RspOperand::Vt}},
// Rt, Vs
{ InstrId::rsp_mfc2, {RspOperand::Rt, RspOperand::Vs, RspOperand::None}},
{ InstrId::rsp_mtc2, {RspOperand::Rt, RspOperand::Vs, RspOperand::None}},
// Nop
{ InstrId::rsp_vnop, {RspOperand::None, RspOperand::None, RspOperand::None}}
};
std::string_view ctx_gpr_prefix(int reg) {
if (reg != 0) {
return "r";
}
return "";
}
uint32_t expected_c0_reg_value(int cop0_reg) {
switch (static_cast<Cop0Reg>(cop0_reg)) {
case Cop0Reg::RSP_COP0_SP_STATUS:
return 0; // None of the flags in RSP status are set
case Cop0Reg::RSP_COP0_SP_DMA_FULL:
return 0; // Pretend DMAs complete instantly
case Cop0Reg::RSP_COP0_SP_DMA_BUSY:
return 0; // Pretend DMAs complete instantly
case Cop0Reg::RSP_COP0_SP_SEMAPHORE:
return 0; // Always acquire the semaphore
case Cop0Reg::RSP_COP0_DPC_STATUS:
return 0; // Good enough for the microcodes that would be recompiled (i.e. non-graphics ones)
default:
fmt::print(stderr, "Unhandled mfc0: {}\n", cop0_reg);
throw std::runtime_error("Unhandled mfc0");
return 0;
}
}
std::string_view c0_reg_write_action(int cop0_reg) {
switch (static_cast<Cop0Reg>(cop0_reg)) {
case Cop0Reg::RSP_COP0_SP_SEMAPHORE:
return ""; // Ignore semaphore functionality
case Cop0Reg::RSP_COP0_SP_STATUS:
return ""; // Ignore writes to the status flags since yielding is ignored
case Cop0Reg::RSP_COP0_SP_DRAM_ADDR:
return "SET_DMA_DRAM";
case Cop0Reg::RSP_COP0_SP_MEM_ADDR:
return "SET_DMA_DMEM";
case Cop0Reg::RSP_COP0_SP_RD_LEN:
return "DO_DMA_READ";
case Cop0Reg::RSP_COP0_SP_WR_LEN:
return "DO_DMA_WRITE";
default:
fmt::print(stderr, "Unhandled mtc0: {}\n", cop0_reg);
throw std::runtime_error("Unhandled mtc0");
}
}
std::optional<int> get_rsp_element(const rabbitizer::InstructionRsp& instr) {
if (instr.hasOperand(rabbitizer::OperandType::rsp_vt_elementhigh)) {
return instr.GetRsp_elementhigh();
} else if (instr.hasOperand(rabbitizer::OperandType::rsp_vt_elementlow) || instr.hasOperand(rabbitizer::OperandType::rsp_vs_index)) {
return instr.GetRsp_elementlow();
}
return std::nullopt;
}
bool rsp_ignores_element(InstrId id) {
return id == InstrId::rsp_vmacq || id == InstrId::rsp_vnop;
}
struct BranchTargets {
std::unordered_set<uint32_t> direct_targets;
std::unordered_set<uint32_t> indirect_targets;
};
BranchTargets get_branch_targets(const std::vector<rabbitizer::InstructionRsp>& instrs) {
BranchTargets ret;
for (const auto& instr : instrs) {
if (instr.isJumpWithAddress() || instr.isBranch()) {
ret.direct_targets.insert(instr.getBranchVramGeneric() & rsp_mem_mask);
}
if (instr.doesLink()) {
ret.indirect_targets.insert(instr.getVram() + 2 * instr_size);
}
}
return ret;
}
bool process_instruction(size_t instr_index, const std::vector<rabbitizer::InstructionRsp>& instructions, std::ofstream& output_file, const BranchTargets& branch_targets, const std::unordered_set<uint32_t>& unsupported_instructions, bool indent, bool in_delay_slot) {
const auto& instr = instructions[instr_index];
uint32_t instr_vram = instr.getVram();
InstrId instr_id = instr.getUniqueId();
// Skip labels if we're duplicating an instruction into a delay slot
if (!in_delay_slot) {
// Print a label if one exists here
if (branch_targets.direct_targets.contains(instr_vram) || branch_targets.indirect_targets.contains(instr_vram)) {
fmt::print(output_file, "L_{:04X}:\n", instr_vram);
}
}
uint16_t branch_target = instr.getBranchVramGeneric() & rsp_mem_mask;
// Output a comment with the original instruction
if (instr.isBranch() || instr_id == InstrId::rsp_j) {
fmt::print(output_file, " // {}\n", instr.disassemble(0, fmt::format("L_{:04X}", branch_target)));
} else if (instr_id == InstrId::rsp_jal) {
fmt::print(output_file, " // {}\n", instr.disassemble(0, fmt::format("0x{:04X}", branch_target)));
} else {
fmt::print(output_file, " // {}\n", instr.disassemble(0));
}
auto print_indent = [&]() {
fmt::print(output_file, " ");
};
auto print_line = [&]<typename... Ts>(fmt::format_string<Ts...> fmt_str, Ts&& ...args) {
print_indent();
fmt::print(output_file, fmt_str, std::forward<Ts>(args)...);
fmt::print(output_file, ";\n");
};
auto print_branch_condition = [&]<typename... Ts>(fmt::format_string<Ts...> fmt_str, Ts&& ...args) {
fmt::print(output_file, fmt_str, std::forward<Ts>(args)...);
fmt::print(output_file, " ");
};
auto print_unconditional_branch = [&]<typename... Ts>(fmt::format_string<Ts...> fmt_str, Ts&& ...args) {
if (instr_index < instructions.size() - 1) {
uint32_t next_vram = instr_vram + 4;
process_instruction(instr_index + 1, instructions, output_file, branch_targets, unsupported_instructions, false, true);
}
print_indent();
fmt::print(output_file, fmt_str, std::forward<Ts>(args)...);
fmt::print(output_file, ";\n");
};
auto print_branch = [&]<typename... Ts>(fmt::format_string<Ts...> fmt_str, Ts&& ...args) {
fmt::print(output_file, "{{\n ");
if (instr_index < instructions.size() - 1) {
uint32_t next_vram = instr_vram + 4;
process_instruction(instr_index + 1, instructions, output_file, branch_targets, unsupported_instructions, true, true);
}
fmt::print(output_file, " ");
fmt::print(output_file, fmt_str, std::forward<Ts>(args)...);
fmt::print(output_file, ";\n }}\n");
};
if (indent) {
print_indent();
}
// Replace unsupported instructions with early returns
if (unsupported_instructions.contains(instr_vram)) {
print_line("return RspExitReason::Unsupported", instr_vram);
if (indent) {
print_indent();
}
}
int rd = (int)instr.GetO32_rd();
int rs = (int)instr.GetO32_rs();
int base = rs;
int rt = (int)instr.GetO32_rt();
int sa = (int)instr.Get_sa();
int fd = (int)instr.GetO32_fd();
int fs = (int)instr.GetO32_fs();
int ft = (int)instr.GetO32_ft();
uint16_t imm = instr.Get_immediate();
std::string unsigned_imm_string = fmt::format("{:#X}", imm);
std::string signed_imm_string = fmt::format("{:#X}", (int16_t)imm);
auto rsp_element = get_rsp_element(instr);
// If this instruction is in the vector operand table then emit the appropriate function call for its implementation
auto operand_find_it = vector_operands.find(instr_id);
if (operand_find_it != vector_operands.end()) {
const auto& operands = operand_find_it->second;
int vd = (int)instr.GetRsp_vd();
int vs = (int)instr.GetRsp_vs();
int vt = (int)instr.GetRsp_vt();
std::string operand_string = "";
for (RspOperand operand : operands) {
switch (operand) {
case RspOperand::Vt:
operand_string += fmt::format("rsp.vpu.r[{}], ", vt);
break;
case RspOperand::VtIndex:
operand_string += fmt::format("{}, ", vt);
break;
case RspOperand::Vd:
operand_string += fmt::format("rsp.vpu.r[{}], ", vd);
break;
case RspOperand::Vs:
operand_string += fmt::format("rsp.vpu.r[{}], ", vs);
break;
case RspOperand::VsIndex:
operand_string += fmt::format("{}, ", vs);
break;
case RspOperand::De:
operand_string += fmt::format("{}, ", instr.GetRsp_de() & 7);
break;
case RspOperand::Rt:
operand_string += fmt::format("{}{}, ", ctx_gpr_prefix(rt), rt);
break;
case RspOperand::Rs:
operand_string += fmt::format("{}{}, ", ctx_gpr_prefix(rs), rs);
break;
case RspOperand::Imm7:
// Sign extend the 7-bit immediate
operand_string += fmt::format("{:#X}, ", ((int8_t)(imm << 1)) >> 1);
break;
case RspOperand::None:
break;
}
}
// Trim the trailing comma off the operands
if (operand_string.size() > 0) {
operand_string = operand_string.substr(0, operand_string.size() - 2);
}
std::string uppercase_name = "";
std::string lowercase_name = instr.getOpcodeName();
uppercase_name.reserve(lowercase_name.size() + 1);
for (char c : lowercase_name) {
uppercase_name += std::toupper(c);
}
if (rsp_ignores_element(instr_id)) {
print_line("rsp.{}({})", uppercase_name, operand_string);
} else {
print_line("rsp.{}<{}>({})", uppercase_name, rsp_element.value(), operand_string);
}
}
// Otherwise, implement the instruction directly
else {
switch (instr_id) {
case InstrId::rsp_nop:
fmt::print(output_file, "\n");
break;
// Arithmetic
case InstrId::rsp_lui:
print_line("{}{} = S32({} << 16)", ctx_gpr_prefix(rt), rt, unsigned_imm_string);
break;
case InstrId::rsp_add:
case InstrId::rsp_addu:
if (rd == 0) {
fmt::print(output_file, "\n");
break;
}
print_line("{}{} = RSP_ADD32({}{}, {}{})", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rt), rt);
break;
case InstrId::rsp_negu: // pseudo instruction for subu x, 0, y
case InstrId::rsp_sub:
case InstrId::rsp_subu:
print_line("{}{} = RSP_SUB32({}{}, {}{})", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rt), rt);
break;
case InstrId::rsp_addi:
case InstrId::rsp_addiu:
print_line("{}{} = RSP_ADD32({}{}, {})", ctx_gpr_prefix(rt), rt, ctx_gpr_prefix(rs), rs, signed_imm_string);
break;
case InstrId::rsp_and:
if (rd == 0) {
fmt::print(output_file, "\n");
break;
}
print_line("{}{} = {}{} & {}{}", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rt), rt);
break;
case InstrId::rsp_andi:
print_line("{}{} = {}{} & {}", ctx_gpr_prefix(rt), rt, ctx_gpr_prefix(rs), rs, unsigned_imm_string);
break;
case InstrId::rsp_or:
print_line("{}{} = {}{} | {}{}", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rt), rt);
break;
case InstrId::rsp_ori:
print_line("{}{} = {}{} | {}", ctx_gpr_prefix(rt), rt, ctx_gpr_prefix(rs), rs, unsigned_imm_string);
break;
case InstrId::rsp_nor:
print_line("{}{} = ~({}{} | {}{})", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rt), rt);
break;
case InstrId::rsp_xor:
print_line("{}{} = {}{} ^ {}{}", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rt), rt);
break;
case InstrId::rsp_xori:
print_line("{}{} = {}{} ^ {}", ctx_gpr_prefix(rt), rt, ctx_gpr_prefix(rs), rs, unsigned_imm_string);
break;
case InstrId::rsp_sll:
print_line("{}{} = S32({}{}) << {}", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rt), rt, sa);
break;
case InstrId::rsp_sllv:
print_line("{}{} = S32({}{}) << ({}{} & 31)", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rt), rt, ctx_gpr_prefix(rs), rs);
break;
case InstrId::rsp_sra:
print_line("{}{} = S32(RSP_SIGNED({}{}) >> {})", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rt), rt, sa);
break;
case InstrId::rsp_srav:
print_line("{}{} = S32(RSP_SIGNED({}{}) >> ({}{} & 31))", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rt), rt, ctx_gpr_prefix(rs), rs);
break;
case InstrId::rsp_srl:
print_line("{}{} = S32(U32({}{}) >> {})", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rt), rt, sa);
break;
case InstrId::rsp_srlv:
print_line("{}{} = S32(U32({}{}) >> ({}{} & 31))", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rt), rt, ctx_gpr_prefix(rs), rs);
break;
case InstrId::rsp_slt:
print_line("{}{} = RSP_SIGNED({}{}) < RSP_SIGNED({}{}) ? 1 : 0", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rt), rt);
break;
case InstrId::rsp_slti:
print_line("{}{} = RSP_SIGNED({}{}) < {} ? 1 : 0", ctx_gpr_prefix(rt), rt, ctx_gpr_prefix(rs), rs, signed_imm_string);
break;
case InstrId::rsp_sltu:
print_line("{}{} = {}{} < {}{} ? 1 : 0", ctx_gpr_prefix(rd), rd, ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rt), rt);
break;
case InstrId::rsp_sltiu:
print_line("{}{} = {}{} < {} ? 1 : 0", ctx_gpr_prefix(rt), rt, ctx_gpr_prefix(rs), rs, signed_imm_string);
break;
// Loads
// TODO ld
case InstrId::rsp_lw:
print_line("{}{} = RSP_MEM_W_LOAD({}, {}{})", ctx_gpr_prefix(rt), rt, signed_imm_string, ctx_gpr_prefix(base), base);
break;
case InstrId::rsp_lh:
print_line("{}{} = RSP_MEM_H_LOAD({}, {}{})", ctx_gpr_prefix(rt), rt, signed_imm_string, ctx_gpr_prefix(base), base);
break;
case InstrId::rsp_lb:
print_line("{}{} = RSP_MEM_B({}, {}{})", ctx_gpr_prefix(rt), rt, signed_imm_string, ctx_gpr_prefix(base), base);
break;
case InstrId::rsp_lhu:
print_line("{}{} = RSP_MEM_HU_LOAD({}, {}{})", ctx_gpr_prefix(rt), rt, signed_imm_string, ctx_gpr_prefix(base), base);
break;
case InstrId::rsp_lbu:
print_line("{}{} = RSP_MEM_BU({}, {}{})", ctx_gpr_prefix(rt), rt, signed_imm_string, ctx_gpr_prefix(base), base);
break;
// Stores
case InstrId::rsp_sw:
print_line("RSP_MEM_W_STORE({}, {}{}, {}{})", signed_imm_string, ctx_gpr_prefix(base), base, ctx_gpr_prefix(rt), rt);
break;
case InstrId::rsp_sh:
print_line("RSP_MEM_H_STORE({}, {}{}, {}{})", signed_imm_string, ctx_gpr_prefix(base), base, ctx_gpr_prefix(rt), rt);
break;
case InstrId::rsp_sb:
print_line("RSP_MEM_B({}, {}{}) = {}{}", signed_imm_string, ctx_gpr_prefix(base), base, ctx_gpr_prefix(rt), rt);
break;
// Branches
case InstrId::rsp_j:
case InstrId::rsp_b:
print_unconditional_branch("goto L_{:04X}", branch_target);
break;
case InstrId::rsp_jal:
print_line("{}{} = 0x{:04X}", ctx_gpr_prefix(31), 31, instr_vram + 2 * instr_size);
print_unconditional_branch("goto L_{:04X}", branch_target);
break;
case InstrId::rsp_jr:
print_line("jump_target = {}{}", ctx_gpr_prefix(rs), rs);
print_line("debug_file = __FILE__; debug_line = __LINE__");
print_unconditional_branch("goto do_indirect_jump");
break;
case InstrId::rsp_jalr:
print_line("jump_target = {}{}; {}{} = 0x{:8X}", ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rd), rd, instr_vram + 2 * instr_size);
print_line("debug_file = __FILE__; debug_line = __LINE__");
print_unconditional_branch("goto do_indirect_jump");
break;
case InstrId::rsp_bne:
print_indent();
print_branch_condition("if ({}{} != {}{})", ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rt), rt);
print_branch("goto L_{:04X}", branch_target);
break;
case InstrId::rsp_beq:
print_indent();
print_branch_condition("if ({}{} == {}{})", ctx_gpr_prefix(rs), rs, ctx_gpr_prefix(rt), rt);
print_branch("goto L_{:04X}", branch_target);
break;
case InstrId::rsp_bgez:
print_indent();
print_branch_condition("if (RSP_SIGNED({}{}) >= 0)", ctx_gpr_prefix(rs), rs);
print_branch("goto L_{:04X}", branch_target);
break;
case InstrId::rsp_bgtz:
print_indent();
print_branch_condition("if (RSP_SIGNED({}{}) > 0)", ctx_gpr_prefix(rs), rs);
print_branch("goto L_{:04X}", branch_target);
break;
case InstrId::rsp_blez:
print_indent();
print_branch_condition("if (RSP_SIGNED({}{}) <= 0)", ctx_gpr_prefix(rs), rs);
print_branch("goto L_{:04X}", branch_target);
break;
case InstrId::rsp_bltz:
print_indent();
print_branch_condition("if (RSP_SIGNED({}{}) < 0)", ctx_gpr_prefix(rs), rs);
print_branch("goto L_{:04X}", branch_target);
break;
case InstrId::rsp_break:
print_line("return RspExitReason::Broke", instr_vram);
break;
case InstrId::rsp_mfc0:
print_line("{}{} = {}", ctx_gpr_prefix(rt), rt, expected_c0_reg_value(rd));
break;
case InstrId::rsp_mtc0:
{
std::string_view write_action = c0_reg_write_action(rd);
if (!write_action.empty()) {
print_line("{}({}{})", write_action, ctx_gpr_prefix(rt), rt); \
}
break;
}
default:
fmt::print(stderr, "Unhandled instruction: {}\n", instr.getOpcodeName());
assert(false);
return false;
}
}
return true;
}
void write_indirect_jumps(std::ofstream& output_file, const BranchTargets& branch_targets, const std::string& output_function_name) {
fmt::print(output_file,
"do_indirect_jump:\n"
" switch ((jump_target | 0x1000) & {:#X}) {{ \n", rsp_mem_mask);
for (uint32_t branch_target: branch_targets.indirect_targets) {
fmt::print(output_file, " case 0x{0:04X}: goto L_{0:04X};\n", branch_target);
}
fmt::print(output_file,
" }}\n"
" printf(\"Unhandled jump target 0x%04X in microcode {}, coming from [%s:%d]\\n\", jump_target, debug_file, debug_line);\n"
" printf(\"Register dump: r0 = %08X r1 = %08X r2 = %08X r3 = %08X r4 = %08X r5 = %08X r6 = %08X r7 = %08X\\n\"\n"
" \" r8 = %08X r9 = %08X r10 = %08X r11 = %08X r12 = %08X r13 = %08X r14 = %08X r15 = %08X\\n\"\n"
" \" r16 = %08X r17 = %08X r18 = %08X r19 = %08X r20 = %08X r21 = %08X r22 = %08X r23 = %08X\\n\"\n"
" \" r24 = %08X r25 = %08X r26 = %08X r27 = %08X r28 = %08X r29 = %08X r30 = %08X r31 = %08X\\n\",\n"
" 0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16,\n"
" r17, r18, r19, r20, r21, r22, r23, r24, r25, r26, r27, r29, r30, r31);\n"
" return RspExitReason::UnhandledJumpTarget;\n", output_function_name);
}
#ifdef _MSC_VER
inline uint32_t byteswap(uint32_t val) {
return _byteswap_ulong(val);
}
#else
constexpr uint32_t byteswap(uint32_t val) {
return __builtin_bswap32(val);
}
#endif
struct RSPRecompilerConfig {
size_t text_offset;
size_t text_size;
size_t text_address;
std::filesystem::path rom_file_path;
std::filesystem::path output_file_path;
std::string output_function_name;
std::vector<uint32_t> extra_indirect_branch_targets;
std::unordered_set<uint32_t> unsupported_instructions;
};
std::filesystem::path concat_if_not_empty(const std::filesystem::path& parent, const std::filesystem::path& child) {
if (!child.empty()) {
return parent / child;
}
return child;
}
template <typename T>
std::vector<T> toml_to_vec(const toml::array* array) {
std::vector<T> ret;
// Reserve room for all the funcs in the map.
ret.reserve(array->size());
array->for_each([&ret](auto&& el) {
if constexpr (toml::is_integer<decltype(el)>) {
ret.push_back(*el);
}
});
return ret;
}
template <typename T>
std::unordered_set<T> toml_to_set(const toml::array* array) {
std::unordered_set<T> ret;
array->for_each([&ret](auto&& el) {
if constexpr (toml::is_integer<decltype(el)>) {
ret.insert(*el);
}
});
return ret;
}
bool read_config(const std::filesystem::path& config_path, RSPRecompilerConfig& out) {
RSPRecompilerConfig ret{};
try {
const toml::table config_data = toml::parse_file(config_path.u8string());
std::filesystem::path basedir = std::filesystem::path{ config_path }.parent_path();
std::optional<uint32_t> text_offset = config_data["text_offset"].value<uint32_t>();
if (text_offset.has_value()) {
ret.text_offset = text_offset.value();
}
else {
throw toml::parse_error("Missing text_offset in config file", config_data.source());
}
std::optional<uint32_t> text_size = config_data["text_size"].value<uint32_t>();
if (text_size.has_value()) {
ret.text_size = text_size.value();
}
else {
throw toml::parse_error("Missing text_size in config file", config_data.source());
}
std::optional<uint32_t> text_address = config_data["text_address"].value<uint32_t>();
if (text_address.has_value()) {
ret.text_address = text_address.value();
}
else {
throw toml::parse_error("Missing text_address in config file", config_data.source());
}
std::optional<std::string> rom_file_path = config_data["rom_file_path"].value<std::string>();
if (rom_file_path.has_value()) {
ret.rom_file_path = concat_if_not_empty(basedir, rom_file_path.value());
}
else {
throw toml::parse_error("Missing rom_file_path in config file", config_data.source());
}
std::optional<std::string> output_file_path = config_data["output_file_path"].value<std::string>();
if (output_file_path.has_value()) {
ret.output_file_path = concat_if_not_empty(basedir, output_file_path.value());
}
else {
throw toml::parse_error("Missing output_file_path in config file", config_data.source());
}
std::optional<std::string> output_function_name = config_data["output_function_name"].value<std::string>();
if (output_function_name.has_value()) {
ret.output_function_name = output_function_name.value();
}
else {
throw toml::parse_error("Missing output_function_name in config file", config_data.source());
}
// Extra indirect branch targets (optional)
const toml::node_view branch_targets_data = config_data["extra_indirect_branch_targets"];
if (branch_targets_data.is_array()) {
const toml::array* branch_targets_array = branch_targets_data.as_array();
ret.extra_indirect_branch_targets = toml_to_vec<uint32_t>(branch_targets_array);
}
// Unsupported_instructions (optional)
const toml::node_view unsupported_instructions_data = config_data["unsupported_instructions"];
if (unsupported_instructions_data.is_array()) {
const toml::array* unsupported_instructions_array = unsupported_instructions_data.as_array();
ret.unsupported_instructions = toml_to_set<uint32_t>(unsupported_instructions_array);
}
}
catch (const toml::parse_error& err) {
std::cerr << "Syntax error parsing toml: " << *err.source().path << " (" << err.source().begin << "):\n" << err.description() << std::endl;
return false;
}
out = ret;
return true;
}
int main(int argc, const char** argv) {
if (argc != 2) {
fmt::print("Usage: {} [config file]\n", argv[0]);
std::exit(EXIT_SUCCESS);
}
RSPRecompilerConfig config;
if (!read_config(std::filesystem::path{argv[1]}, config)) {
fmt::print("Failed to parse config file {}\n", argv[0]);
std::exit(EXIT_FAILURE);
}
std::vector<uint32_t> instr_words{};
instr_words.resize(config.text_size / sizeof(uint32_t));
{
std::ifstream rom_file{ config.rom_file_path, std::ios_base::binary };
if (!rom_file.good()) {
fmt::print(stderr, "Failed to open rom file\n");
return EXIT_FAILURE;
}
rom_file.seekg(config.text_offset);
rom_file.read(reinterpret_cast<char*>(instr_words.data()), config.text_size);
}
// Disable appropriate pseudo instructions
RabbitizerConfig_Cfg.pseudos.pseudoMove = false;
RabbitizerConfig_Cfg.pseudos.pseudoBeqz = false;
RabbitizerConfig_Cfg.pseudos.pseudoBnez = false;
RabbitizerConfig_Cfg.pseudos.pseudoNot = false;
// Decode the instruction words into instructions
std::vector<rabbitizer::InstructionRsp> instrs{};
instrs.reserve(instr_words.size());
uint32_t vram = config.text_address & rsp_mem_mask;
for (uint32_t instr_word : instr_words) {
const rabbitizer::InstructionRsp& instr = instrs.emplace_back(byteswap(instr_word), vram);
vram += instr_size;
}
// Collect indirect jump targets (return addresses for linked jumps)
BranchTargets branch_targets = get_branch_targets(instrs);
// Add any additional indirect branch targets that may not be found directly in the code (e.g. from a jump table)
for (uint32_t target : config.extra_indirect_branch_targets) {
branch_targets.indirect_targets.insert(target);
}
// Open output file and write beginning
std::filesystem::create_directories(std::filesystem::path{ config.output_file_path }.parent_path());
std::ofstream output_file(config.output_file_path);
fmt::print(output_file,
"#include \"rsp.h\"\n"
"#include \"rsp_vu_impl.h\"\n"
"RspExitReason {}(uint8_t* rdram) {{\n"
" uint32_t r1 = 0, r2 = 0, r3 = 0, r4 = 0, r5 = 0, r6 = 0, r7 = 0;\n"
" uint32_t r8 = 0, r9 = 0, r10 = 0, r11 = 0, r12 = 0, r13 = 0, r14 = 0, r15 = 0;\n"
" uint32_t r16 = 0, r17 = 0, r18 = 0, r19 = 0, r20 = 0, r21 = 0, r22 = 0, r23 = 0;\n"
" uint32_t r24 = 0, r25 = 0, r26 = 0, r27 = 0, r28 = 0, r29 = 0, r30 = 0, r31 = 0;\n"
" uint32_t dma_dmem_address = 0, dma_dram_address = 0, jump_target = 0;\n"
" const char * debug_file = NULL; int debug_line = 0;\n"
" RSP rsp{{}};\n"
" r1 = 0xFC0;\n", config.output_function_name);
// Write each instruction
for (size_t instr_index = 0; instr_index < instrs.size(); instr_index++) {
process_instruction(instr_index, instrs, output_file, branch_targets, config.unsupported_instructions, false, false);
}
// Terminate instruction code with a return to indicate that the microcode has run past its end
fmt::print(output_file, " return RspExitReason::ImemOverrun;\n");
// Write the section containing the indirect jump table
write_indirect_jumps(output_file, branch_targets, config.output_function_name);
// End the file
fmt::print(output_file, "}}\n");
return 0;
}