-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec.cpp
More file actions
1936 lines (1719 loc) · 58.3 KB
/
exec.cpp
File metadata and controls
1936 lines (1719 loc) · 58.3 KB
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "spike_ref.h"
#include "CSR.h"
#include "RISCV.h"
#include "ref.h"
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <map>
extern "C" {
#include "softfloat.h"
}
namespace {
constexpr uint32_t kRamBase = 0x80000000u;
constexpr uint32_t kRamUpperBound = 0xC0000000u;
constexpr uint32_t kRamSizeBytes = kRamUpperBound - kRamBase;
constexpr uint32_t kOpcodeFloat = 0b1010011;
constexpr uint32_t kOpcodeFmadd = 0b1000011;
constexpr uint32_t kOpcodeFmsub = 0b1000111;
constexpr uint32_t kOpcodeFnmsub = 0b1001011;
constexpr uint32_t kOpcodeFnmadd = 0b1001111;
[[noreturn]] void mem_oob_fatal(const char *op, uint32_t addr, uint32_t size) {
std::cerr << "[RefCPU] " << op << " out-of-bounds: addr=0x" << std::hex
<< addr << ", size=" << std::dec << size
<< ", required: addr + size <= 0xC0000000" << std::endl;
exit(1);
}
inline void check_mem_range_or_die(const char *op, uint32_t addr,
uint32_t size) {
if (size == 0) {
return;
}
const uint64_t end =
static_cast<uint64_t>(addr) + static_cast<uint64_t>(size) - 1;
if (end >= kRamUpperBound) {
mem_oob_fatal(op, addr, size);
}
}
inline bool is_ram_range(uint32_t addr, uint32_t size) {
if (size == 0 || addr < kRamBase) {
return false;
}
const uint64_t end =
static_cast<uint64_t>(addr) + static_cast<uint64_t>(size) - 1;
return end < kRamUpperBound;
}
static inline float32_t to_f32(uint32_t v) {
float32_t f;
f.v = v;
return f;
}
static inline uint32_t from_f32(float32_t f) { return f.v; }
static inline bool is_nan(uint32_t v) {
return ((v & 0x7F800000) == 0x7F800000) && ((v & 0x007FFFFF) != 0);
}
static inline bool is_snan(uint32_t v) {
return is_nan(v) && !((v >> 22) & 1);
}
uint32_t f32_min_riscv(uint32_t a, uint32_t b) {
if (is_snan(a) || is_snan(b)) {
softfloat_exceptionFlags |= softfloat_flag_invalid;
}
bool a_nan = is_nan(a);
bool b_nan = is_nan(b);
if (a_nan && b_nan) {
return 0x7fc00000;
}
if (a_nan) {
return b;
}
if (b_nan) {
return a;
}
float32_t fa = to_f32(a);
float32_t fb = to_f32(b);
if (f32_lt(fa, fb)) {
return a;
}
if (f32_lt(fb, fa)) {
return b;
}
return a | b;
}
uint32_t f32_max_riscv(uint32_t a, uint32_t b) {
if (is_snan(a) || is_snan(b)) {
softfloat_exceptionFlags |= softfloat_flag_invalid;
}
bool a_nan = is_nan(a);
bool b_nan = is_nan(b);
if (a_nan && b_nan) {
return 0x7fc00000;
}
if (a_nan) {
return b;
}
if (b_nan) {
return a;
}
float32_t fa = to_f32(a);
float32_t fb = to_f32(b);
if (f32_lt(fa, fb)) {
return b;
}
if (f32_lt(fb, fa)) {
return a;
}
return a & b;
}
uint32_t f32_classify(float32_t f) {
uint32_t bits = from_f32(f);
uint32_t sign = (bits >> 31) & 1;
uint32_t exp = (bits >> 23) & 0xFF;
uint32_t mant = bits & 0x7FFFFF;
bool is_subnormal = (exp == 0) && (mant != 0);
bool is_zero = (exp == 0) && (mant == 0);
bool is_inf = (exp == 0xFF) && (mant == 0);
bool value_is_nan = (exp == 0xFF) && (mant != 0);
bool value_is_snan = value_is_nan && !((mant >> 22) & 1);
bool value_is_qnan = value_is_nan && ((mant >> 22) & 1);
uint32_t res = 0;
if (is_inf && sign) {
res |= (1 << 0);
} else if (!is_inf && !is_zero && !value_is_nan && !is_subnormal && sign) {
res |= (1 << 1);
} else if (is_subnormal && sign) {
res |= (1 << 2);
} else if (is_zero && sign) {
res |= (1 << 3);
} else if (is_zero && !sign) {
res |= (1 << 4);
} else if (is_subnormal && !sign) {
res |= (1 << 5);
} else if (!is_inf && !is_zero && !value_is_nan && !is_subnormal && !sign) {
res |= (1 << 6);
} else if (is_inf && !sign) {
res |= (1 << 7);
}
if (value_is_snan) {
res |= (1 << 8);
}
if (value_is_qnan) {
res |= (1 << 9);
}
return res;
}
} // namespace
std::map<uint32_t, uint32_t> load_simpoints(const std::string &filename);
Ref_cpu::~Ref_cpu() {
if (memory) {
free(memory);
}
}
void Ref_cpu::init(uint32_t reset_pc, const char *image, uint32_t size) {
state.pc = reset_pc;
ram_size = size;
if (ram_size != kRamSizeBytes) {
std::cerr << "[RefCPU] Unsupported RAM size: 0x" << std::hex << ram_size
<< ", expected 0x" << kRamSizeBytes << std::dec << std::endl;
exit(1);
}
const uint32_t ram_words = ram_size / sizeof(uint32_t);
memory = (uint32_t *)calloc(ram_words, sizeof(uint32_t));
if (!memory) {
std::cerr << "Error: Could not allocate " << ram_size
<< " bytes of memory" << std::endl;
exit(1);
}
io_words.clear();
std::ifstream inst_data(image, std::ios::in | std::ios::binary);
if (!inst_data.is_open()) {
std::cerr << "Error: Image " << (image ? image : "NULL")
<< " does not exist" << std::endl;
exit(1);
}
inst_data.seekg(0, std::ios::end);
std::streamsize img_size = inst_data.tellg();
inst_data.seekg(0, std::ios::beg);
if (img_size < 0 || static_cast<uint64_t>(img_size) > kRamSizeBytes) {
std::cerr << "[RefCPU] Image too large for 1GB RAM window: " << img_size
<< " bytes" << std::endl;
exit(1);
}
const uint32_t img_bytes = static_cast<uint32_t>(img_size);
check_mem_range_or_die("image load", kRamBase, img_bytes);
std::cout << "[RefCPU] Loading image at 0x80000000, size: " << img_size
<< " bytes" << std::endl;
if (!inst_data.read(reinterpret_cast<char *>(memory), img_bytes)) {
std::cerr << "读取文件失败!" << std::endl;
exit(1);
}
store_word(0x10000004, 0x00006000); // 和进入 OpenSBI 相关
store_word(0x0, 0xf1402573);
store_word(0x4, 0x83e005b7);
store_word(0x8, 0x800002b7);
store_word(0xc, 0x00028067);
inst_data.close();
for (int i = 0; i < 32; i++) {
state.gpr[i] = 0;
}
for (int i = 0; i < 21; i++) {
state.csr[i] = 0;
}
state.csr[csr_misa] = 0x40141103;
privilege = 0b11;
state.store = false;
asy = false;
page_fault_inst = false;
page_fault_load = false;
page_fault_store = false;
state.reserve_valid = false;
state.reserve_addr = 0;
sim_time = 0;
sim_end = false;
uart_print = false;
difftest_started = false;
}
void Ref_cpu::exec(const SimConfig &config) {
// Initialize Spike Reference Simulator if enabled
if (config.difftest) {
spike_ref = std::make_unique<SpikeRef>("RV32IMAB", 0x80000000, 0x80000000,
config.image_file.c_str());
}
// 准备 GEN_CHECKPOINT 需要的 target_intervals
std::map<uint32_t, uint32_t> target_intervals;
uint32_t finished_intervals = 0;
if (config.mode == SimMode::GEN_CHECKPOINT) {
target_intervals = load_simpoints(config.points_file);
// [特殊处理] Interval 0 无法向前预热,只能直接保存
// 如果 SimPoint 选中了 0,我们只能保存刚启动的状态
if (target_intervals.count(0)) {
uint32_t sp_id = target_intervals[0];
std::string ckpt_name = config.checkpoint_dir + "/ckpt_sp" +
std::to_string(sp_id) +
"_target0_nowarmup.gz"; // 建议加上.gz后缀
save_checkpoint(ckpt_name);
}
} else if (config.mode == SimMode::GEN_BBV) {
bbv_init_file(config.bbv_output_file.c_str());
} else if (config.mode == SimMode::RESTORE) {
restore_checkpoint(config.restore_file);
}
uint64_t restored_inst_count = 0;
// --- 主循环 ---
while (!sim_end && sim_time < MAX_SIM_TIME) {
if (sim_time % 100000000 == 0) {
std::cout << "SimTime: " << sim_time
<< " | Intervals: " << finished_intervals << std::endl;
}
// 1. 执行指令
RISCV();
// If the simulation ended (e.g., ebreak), skip Difftest for this last step
// because DUT and Spike handle termination differently.
if (sim_end)
break;
// Difftest Step
if (config.difftest && spike_ref) {
if (!difftest_started) {
// DUT starts at 0x0 with some boot code.
// Spike is configured to start at 0x80000000.
// We wait until DUT reaches 0x80000000 to sync state and start
// difftest.
if (state.pc == 0x80000000) {
spike_ref->sync_state(state, privilege);
difftest_started = true;
}
} else {
spike_ref->step(1);
if (is_io) {
// Surgical sync of the destination register after I/O read
spike_ref->sync_reg_from_dut(io_reg_idx, state.gpr[io_reg_idx]);
} else if (force_sync) {
// Sync full architectural state on interrupts or CSR writes
spike_ref->sync_state(state, privilege);
} else {
// Strict check: No automatic recovery. Mismatch = Failure.
spike_ref->reg_check(state, privilege);
}
}
}
sim_time++;
// 2. 计数逻辑 (保持和你生成 BBV 时一致,这对 SimPoint 对齐至关重要)
if (privilege == RISCV_MODE_U && is_br) {
if (config.mode == SimMode::GEN_BBV) {
bbv_commit(); // 更新内存中的 bbv_counts
}
// 这里的 interval_inst_count 决定了 Interval 的边界
interval_inst_count += current_bb_len;
current_bb_len = 0;
}
// 3. RESTORE 模式的指令数限制检查 (用于跑 Warmup + Sampling)
if (config.mode == SimMode::RESTORE && config.max_insts > 0) {
restored_inst_count++;
if (restored_inst_count >= config.max_insts) {
std::cout << "Restore run finished (max_insts reached)." << std::endl;
break;
}
}
// 4. Interval 边界处理
if (interval_inst_count >= INTERVAL_SIZE) {
// 当前 Interval (finished_intervals) 刚刚结束
finished_intervals++;
// 即将开始的 Interval 编号
// 例如:finished_intervals 变成 1823,说明我们要开始跑 Interval 1823 了
uint32_t upcoming_interval_id = finished_intervals;
// --- 模式分支处理 ---
if (config.mode == SimMode::GEN_BBV) {
std::cout << "Dump BBV at interval boundary: " << upcoming_interval_id
<< std::endl;
dump_bbv();
} else if (config.mode == SimMode::GEN_CHECKPOINT) {
// [Warmup 逻辑核心修改]
// 我们不检查 upcoming_interval_id 是否是目标,
// 而是检查 (upcoming_interval_id + 1) 是否是目标。
// 如果是,说明当前这个 Interval (upcoming_interval_id) 就是那个 Warmup
// 区间。 我们需要在进入 Warmup 区间之前保存 Checkpoint。
uint32_t target_id = upcoming_interval_id + 1; // Lookahead (向前看一个)
auto it = target_intervals.find(target_id);
if (it != target_intervals.end()) {
uint32_t sp_id = it->second;
// 文件名命名建议:明确标出这是 target 谁的 warmup
std::string ckpt_name = config.checkpoint_dir + "/ckpt_sp" +
std::to_string(sp_id) + "_target" +
std::to_string(target_id) +
"_warmup1.gz"; // warmup1 代表预热长度为1
std::cout << "Creating Warmup Checkpoint for Target " << target_id
<< std::endl;
save_checkpoint(ckpt_name);
// 优化:如果最大的目标都已经生成过预热快照了,就可以退出了
// 注意:target_intervals 是有序 map,rbegin() 是最大的 key
if (!target_intervals.empty() &&
target_id >= target_intervals.rbegin()->first) {
std::cout << "All checkpoints generated. Simulation finished."
<< std::endl;
sim_end = true;
}
}
}
// 重置区间指令计数
interval_inst_count = 0;
}
}
if (sim_time >= MAX_SIM_TIME) {
std::cerr << "Error: Simulation Timeout! (MAX_SIM_TIME = " << MAX_SIM_TIME
<< " reached)" << std::endl;
exit(1);
}
// --- 结束清理 ---
if (config.mode == SimMode::GEN_BBV) {
if (bbv_file.is_open())
bbv_file.close();
}
}
void Ref_cpu::exception(uint32_t trap_val) {
is_exception = true;
uint32_t next_pc = state.pc + 4;
// 重新获取当前状态(因为exec可能没传进来最新的)
bool ecall = (Instruction == INST_ECALL);
bool mret = (Instruction == INST_MRET);
bool sret = (Instruction == INST_SRET);
uint32_t mstatus = state.csr[csr_mstatus];
uint32_t sstatus = state.csr[csr_sstatus];
uint32_t medeleg = state.csr[csr_medeleg];
uint32_t mtvec = state.csr[csr_mtvec];
uint32_t stvec = state.csr[csr_stvec];
// 再次计算 Trap 原因 (与 RISCV() 中逻辑一致,但这里是为了确定是用 MTrap 还是
// STrap 处理)
// 注意:为了代码复用,这里其实可以简化,但为了保持你原有逻辑结构:
bool medeleg_U_ecall = (medeleg >> 8) & 1;
bool medeleg_S_ecall = (medeleg >> 9) & 1;
bool medeleg_page_fault_inst = (medeleg >> 12) & 1;
bool medeleg_page_fault_load = (medeleg >> 13) & 1;
bool medeleg_page_fault_store = (medeleg >> 15) & 1;
// 这里直接复用成员变量里的中断状态 (假设RISCV函数刚跑完,状态是新的)
// 如果不是,需要重新计算 M_software_interrupt 等
bool MTrap =
(M_software_interrupt) || (M_timer_interrupt) || (M_external_interrupt) ||
((privilege == 0) && !medeleg_U_ecall && ecall) ||
(ecall && (privilege == 1) && !medeleg_S_ecall) ||
(ecall && (privilege == 3)) ||
(page_fault_inst && !medeleg_page_fault_inst) ||
(page_fault_load && !medeleg_page_fault_load) ||
(page_fault_store && !medeleg_page_fault_store) || illegal_exception;
bool STrap = S_software_interrupt || S_timer_interrupt ||
S_external_interrupt ||
(ecall && (privilege == 0) && medeleg_U_ecall) ||
(ecall && (privilege == 1) && medeleg_S_ecall) ||
(page_fault_inst && medeleg_page_fault_inst) ||
(page_fault_load && medeleg_page_fault_load) ||
(page_fault_store && medeleg_page_fault_store);
if (MTrap) {
state.csr[csr_mepc] = state.pc;
uint32_t cause = 0;
// 计算 MCause
bool is_interrupt =
M_software_interrupt || M_timer_interrupt || M_external_interrupt;
if (is_interrupt)
cause |= (1u << 31);
uint32_t exception_code = 0;
if (M_software_interrupt)
exception_code = 3;
else if (M_timer_interrupt)
exception_code = 7;
else if (M_external_interrupt ||
(ecall && privilege == 3 && !medeleg_U_ecall))
exception_code = 11;
else if (ecall && privilege == 0 && !medeleg_U_ecall)
exception_code = 8;
else if (ecall && privilege == 1 && !medeleg_S_ecall)
exception_code = 9;
else if (page_fault_inst && !medeleg_page_fault_inst)
exception_code = 12;
else if (page_fault_load && !medeleg_page_fault_load)
exception_code = 13;
else if (page_fault_store && !medeleg_page_fault_store)
exception_code = 15;
else if (illegal_exception)
exception_code = 2;
cause |= exception_code;
state.csr[csr_mcause] = cause;
// 向量中断跳转
if ((mtvec & 1) && (cause & (1u << 31))) {
next_pc = (mtvec & 0xfffffffc) + 4 * (cause & 0x7fffffff);
} else {
next_pc =
mtvec & 0xfffffffc; // 这里的MASK可能需要根据Spec确认,通常是清除低2位
}
// 更新 mstatus
// MPP = privilege
mstatus = (mstatus & ~MSTATUS_MPP) | ((privilege & 0x3) << 11);
// MPIE = MIE
if (mstatus & MSTATUS_MIE)
mstatus |= MSTATUS_MPIE;
else
mstatus &= ~MSTATUS_MPIE;
// MIE = 0
mstatus &= ~MSTATUS_MIE;
// 同步 sstatus (sstatus 是 mstatus 的影子)
state.csr[csr_mstatus] = mstatus;
state.csr[csr_sstatus] =
mstatus & 0x800DE762; // 这是一个Mask,简单起见可以直接赋值
privilege = 3; // Machine Mode
state.csr[csr_mtval] = trap_val;
} else if (STrap) {
state.csr[csr_sepc] = state.pc;
uint32_t cause = 0;
bool is_interrupt =
S_software_interrupt || S_timer_interrupt || S_external_interrupt;
if (is_interrupt)
cause |= (1u << 31);
uint32_t exception_code = 0;
if (S_external_interrupt || (ecall && privilege == 1 && medeleg_S_ecall))
exception_code = 9;
else if (S_timer_interrupt)
exception_code = 5;
else if (ecall && privilege == 0 && medeleg_U_ecall)
exception_code = 8;
else if (S_software_interrupt)
exception_code = 1;
else if (page_fault_inst && medeleg_page_fault_inst)
exception_code = 12;
else if (page_fault_load && medeleg_page_fault_load)
exception_code = 13;
else if (page_fault_store && medeleg_page_fault_store)
exception_code = 15;
cause |= exception_code;
state.csr[csr_scause] = cause;
if ((stvec & 1) && (cause & (1u << 31))) {
next_pc = (stvec & 0xfffffffc) + 4 * (cause & 0x7fffffff);
} else {
next_pc = stvec & 0xfffffffc;
}
// 更新 sstatus
// SPP = privilege
if (privilege == 1)
sstatus |= MSTATUS_SPP;
else
sstatus &= ~MSTATUS_SPP;
// SPIE = SIE
if (sstatus & MSTATUS_SIE)
sstatus |= MSTATUS_SPIE;
else
sstatus &= ~MSTATUS_SPIE;
// SIE = 0
sstatus &= ~MSTATUS_SIE;
// 写回
state.csr[csr_sstatus] = sstatus;
// 更新 mstatus 中对应的位 (SPIE, SIE, SPP 在 mstatus 中也有对应位置)
// 简单做法:读出改完的 sstatus,把对应位刷回 mstatus
uint32_t mask = 0x800DE133;
state.csr[csr_mstatus] =
(state.csr[csr_mstatus] & ~mask) | (sstatus & mask);
privilege = 1; // Supervisor Mode
state.csr[csr_stval] = trap_val;
} else if (mret) {
// MIE = MPIE
if (mstatus & MSTATUS_MPIE)
mstatus |= MSTATUS_MIE;
else
mstatus &= ~MSTATUS_MIE;
// Privilege = MPP
privilege = GET_MPP(mstatus);
// MPIE = 1
mstatus |= MSTATUS_MPIE;
// MPP = U (0)
mstatus &= ~MSTATUS_MPP;
state.csr[csr_mstatus] = mstatus;
// 同步 sstatus
state.csr[csr_sstatus] = mstatus & 0x800DE133;
next_pc = state.csr[csr_mepc];
} else if (sret) {
// SIE = SPIE
if (sstatus & MSTATUS_SPIE)
sstatus |= MSTATUS_SIE;
else
sstatus &= ~MSTATUS_SIE;
// Privilege = SPP
privilege = GET_SPP(sstatus);
// SPIE = 1
sstatus |= MSTATUS_SPIE;
// SPP = U (0)
sstatus &= ~MSTATUS_SPP;
state.csr[csr_sstatus] = sstatus;
// 同步回 mstatus
uint32_t mask = 0x800DE133;
state.csr[csr_mstatus] =
(state.csr[csr_mstatus] & ~mask) | (sstatus & mask);
next_pc = state.csr[csr_sepc];
}
state.pc = next_pc;
}
void Ref_cpu::RISCV() {
if (privilege == RISCV_MODE_U) {
if (current_bb_len == 0) {
current_bb_head_pc = state.pc;
}
current_bb_len++;
}
is_csr = is_exception = is_br = br_taken = false;
illegal_exception = page_fault_load = page_fault_inst = page_fault_store =
asy = false;
state.store = false;
is_io = false;
force_sync = false;
uint32_t p_addr = state.pc;
if ((state.csr[csr_satp] & 0x80000000) && privilege != 3) {
page_fault_inst = !va2pa(p_addr, state.pc, 0);
if (page_fault_inst) {
exception(state.pc);
return;
}
}
check_mem_range_or_die("instruction fetch", p_addr, 4);
Instruction = load_word(p_addr);
if (Instruction == INST_EBREAK) {
uint32_t exit_code = state.gpr[10]; // a0
state.pc += 4;
std::cout << "ebreak signal received. code = 0x" << std::hex << exit_code
<< std::dec << std::endl;
std::cout << "total_sim_time: " << sim_time << std::endl;
if (exit_code == 0) {
std::cout << "\033[1;32mSuccess!\033[0m" << std::endl;
} else {
std::cout << "\033[1;31mTest Failed with code: " << exit_code << "\033[0m"
<< std::endl;
}
sim_end = true;
return;
}
// === 优化 1: 极速解码 ===
// 使用 BITS 宏直接提取字段,完全替代 bool 数组操作
uint32_t opcode = BITS(Instruction, 6, 0);
bool ecall = (Instruction == INST_ECALL);
bool mret = (Instruction == INST_MRET);
bool sret = (Instruction == INST_SRET);
// === 优化 2: 快速读取 CSR 状态 ===
uint32_t mstatus = state.csr[csr_mstatus];
uint32_t mie_reg = state.csr[csr_mie];
uint32_t mip_reg = state.csr[csr_mip];
uint32_t mideleg = state.csr[csr_mideleg];
uint32_t medeleg = state.csr[csr_medeleg];
// 提取关键位
bool mstatus_mie = (mstatus & MSTATUS_MIE) != 0;
bool mstatus_sie = (mstatus & MSTATUS_SIE) != 0;
// 异常委托位 (Exceptions)
bool medeleg_U_ecall = (medeleg >> 8) & 1;
bool medeleg_S_ecall = (medeleg >> 9) & 1;
// bool medeleg_M_ecall = (medeleg >> 11) & 1; // 通常M-ecall不委托
bool medeleg_page_fault_inst = (medeleg >> 12) & 1;
bool medeleg_page_fault_load = (medeleg >> 13) & 1;
bool medeleg_page_fault_store = (medeleg >> 15) & 1;
// === 优化 3: 中断判断逻辑 (位运算) ===
// M-mode 中断条件:Pending & Enabled & NotDelegated & (CurrentPriv < M ||
// MIE=1)
// Software Interrupts
M_software_interrupt = (mip_reg & MIP_MSIP) && (mie_reg & MIP_MSIP) &&
!(mideleg & MIP_MSIP) &&
(privilege < 3 || mstatus_mie);
// Timer Interrupts
M_timer_interrupt = (mip_reg & MIP_MTIP) && (mie_reg & MIP_MTIP) &&
!(mideleg & MIP_MTIP) && (privilege < 3 || mstatus_mie);
// External Interrupts
M_external_interrupt = (mip_reg & MIP_MEIP) && (mie_reg & MIP_MEIP) &&
!(mideleg & MIP_MEIP) &&
(privilege < 3 || mstatus_mie);
// S-mode 中断条件: Pending & Enabled & Delegated & (CurrentPriv < S || SIE=1)
// 注意:privilege < 2 (S-mode=1, U-mode=0) 意味着当前是 U 或 S
bool s_irq_enable = (privilege < 1 || (privilege == 1 && mstatus_sie));
S_software_interrupt =
(((mip_reg & MIP_MSIP) && (mie_reg & MIP_MSIP) && (mideleg & MIP_MSIP)) ||
((mip_reg & MIP_SSIP) && (mie_reg & MIP_SSIP))) &&
(privilege < 2 && s_irq_enable);
S_timer_interrupt =
(((mip_reg & MIP_MTIP) && (mie_reg & MIP_MTIP) && (mideleg & MIP_MTIP)) ||
((mip_reg & MIP_STIP) && (mie_reg & MIP_STIP))) &&
(privilege < 2 && s_irq_enable);
S_external_interrupt =
(((mip_reg & MIP_MEIP) && (mie_reg & MIP_MEIP) && (mideleg & MIP_MEIP)) ||
((mip_reg & MIP_SEIP) && (mie_reg & MIP_SEIP))) &&
(privilege < 2 && s_irq_enable);
// Trap 判断
bool MTrap =
M_software_interrupt || M_timer_interrupt || M_external_interrupt ||
((privilege == 0) && !medeleg_U_ecall && ecall) || // ecall from U
((privilege == 1) && !medeleg_S_ecall && ecall) || // ecall from S
((privilege == 3) && ecall) || // ecall from M
(page_fault_inst && !medeleg_page_fault_inst) || illegal_exception;
bool STrap = S_software_interrupt || S_timer_interrupt ||
S_external_interrupt ||
((privilege == 0) && medeleg_U_ecall && ecall) ||
((privilege == 1) && medeleg_S_ecall && ecall) ||
(page_fault_inst && medeleg_page_fault_inst);
asy = MTrap || STrap || mret || sret;
// WFI 检查 (简单处理)
if (Instruction == INST_WFI && !asy && !page_fault_inst && !page_fault_load &&
!page_fault_store) {
std::cout << " WFI " << std::endl;
std::cout << sim_time << std::endl;
exit(1);
}
if (page_fault_inst) {
exception(state.pc);
return;
} else if (illegal_exception) {
exception(Instruction);
return;
} else if (asy || Instruction == INST_ECALL) {
exception(0);
return;
} else if (opcode == number_10_opcode_ecall) {
// SYSTEM 指令 (CSR, WFI, MRET等)
if (Instruction == INST_WFI) {
is_csr = false;
} else {
is_csr = true;
}
RV32CSR();
} else if (opcode == number_11_opcode_lrw) {
RV32A();
} else if (opcode == kOpcodeFloat || opcode == kOpcodeFmadd ||
opcode == kOpcodeFmsub || opcode == kOpcodeFnmsub ||
opcode == kOpcodeFnmadd) {
RV32Zfinx();
} else {
RV32IM();
}
state.gpr[0] = 0;
}
void Ref_cpu::RV32Zfinx() {
uint32_t next_pc = state.pc + 4;
uint32_t opcode = BITS(Instruction, 6, 0);
uint32_t rd = BITS(Instruction, 11, 7);
uint32_t funct3 = BITS(Instruction, 14, 12);
uint32_t rs1 = BITS(Instruction, 19, 15);
uint32_t rs2 = BITS(Instruction, 24, 20);
uint32_t funct7 = BITS(Instruction, 31, 25);
uint32_t rs3 = BITS(Instruction, 31, 27);
uint32_t val_rs1 = state.gpr[rs1];
uint32_t val_rs2 = state.gpr[rs2];
uint32_t val_rs3 = state.gpr[rs3];
uint8_t rm = funct3;
if (rm == 7) {
rm = 0;
}
switch (rm) {
case 0:
softfloat_roundingMode = softfloat_round_near_even;
break;
case 1:
softfloat_roundingMode = softfloat_round_minMag;
break;
case 2:
softfloat_roundingMode = softfloat_round_min;
break;
case 3:
softfloat_roundingMode = softfloat_round_max;
break;
case 4:
softfloat_roundingMode = softfloat_round_near_maxMag;
break;
default:
illegal_exception = true;
return;
}
softfloat_exceptionFlags = 0;
float32_t f_rs1 = to_f32(val_rs1);
float32_t f_rs2 = to_f32(val_rs2);
float32_t f_rs3 = to_f32(val_rs3);
float32_t f_res;
uint32_t i_res = 0;
bool write_rd = true;
switch (opcode) {
case kOpcodeFloat:
switch (funct7) {
case 0x00:
f_res = f32_add(f_rs1, f_rs2);
i_res = from_f32(f_res);
break;
case 0x04:
f_res = f32_sub(f_rs1, f_rs2);
i_res = from_f32(f_res);
break;
case 0x08:
f_res = f32_mul(f_rs1, f_rs2);
i_res = from_f32(f_res);
break;
case 0x0C:
f_res = f32_div(f_rs1, f_rs2);
i_res = from_f32(f_res);
break;
case 0x2C:
if (rs2 != 0) {
illegal_exception = true;
return;
}
f_res = f32_sqrt(f_rs1);
i_res = from_f32(f_res);
break;
case 0x10:
if (funct3 == 0) {
i_res = (val_rs1 & ~0x80000000u) | (val_rs2 & 0x80000000u);
} else if (funct3 == 1) {
i_res = (val_rs1 & ~0x80000000u) | (~val_rs2 & 0x80000000u);
} else if (funct3 == 2) {
i_res = val_rs1 ^ (val_rs2 & 0x80000000u);
} else {
illegal_exception = true;
return;
}
goto skip_flags_update;
case 0x50:
if (funct3 == 2) {
i_res = f32_eq(f_rs1, f_rs2);
} else if (funct3 == 1) {
i_res = f32_lt(f_rs1, f_rs2);
} else if (funct3 == 0) {
i_res = f32_le(f_rs1, f_rs2);
} else {
illegal_exception = true;
return;
}
break;
case 0x14:
if (funct3 == 0) {
i_res = f32_min_riscv(val_rs1, val_rs2);
} else if (funct3 == 1) {
i_res = f32_max_riscv(val_rs1, val_rs2);
} else {
illegal_exception = true;
return;
}
break;
case 0x60:
if (rs2 == 0) {
i_res = static_cast<uint32_t>(
f32_to_i32(f_rs1, softfloat_roundingMode, true));
} else if (rs2 == 1) {
i_res = f32_to_ui32(f_rs1, softfloat_roundingMode, true);
} else {
illegal_exception = true;
return;
}
break;
case 0x68:
if (rs2 == 0) {
f_res = i32_to_f32(static_cast<int32_t>(val_rs1));
} else if (rs2 == 1) {
f_res = ui32_to_f32(val_rs1);
} else {
illegal_exception = true;
return;
}
i_res = from_f32(f_res);
break;
case 0x70:
if (funct3 == 0) {
illegal_exception = true;
return;
} else if (funct3 == 1) {
i_res = f32_classify(f_rs1);
} else {
illegal_exception = true;
return;
}
break;
default:
illegal_exception = true;
return;
}
break;
case kOpcodeFmadd:
f_res = f32_mulAdd(f_rs1, f_rs2, f_rs3);
i_res = from_f32(f_res);
break;
case kOpcodeFmsub: {
float32_t f_neg_rs3 = to_f32(val_rs3 ^ 0x80000000u);
f_res = f32_mulAdd(f_rs1, f_rs2, f_neg_rs3);
i_res = from_f32(f_res);
break;
}
case kOpcodeFnmsub: {
float32_t f_neg_rs1 = to_f32(val_rs1 ^ 0x80000000u);
f_res = f32_mulAdd(f_neg_rs1, f_rs2, f_rs3);
i_res = from_f32(f_res);
break;
}
case kOpcodeFnmadd: {
float32_t f_neg_rs1 = to_f32(val_rs1 ^ 0x80000000u);
float32_t f_neg_rs3 = to_f32(val_rs3 ^ 0x80000000u);
f_res = f32_mulAdd(f_neg_rs1, f_rs2, f_neg_rs3);
i_res = from_f32(f_res);
break;
}
default:
illegal_exception = true;
return;
}
skip_flags_update:
if (write_rd && rd != 0) {
state.gpr[rd] = i_res;
}
state.pc = next_pc;
}
void Ref_cpu::RV32CSR() {
// pc + 4
uint32_t next_pc = state.pc + 4;
// 使用宏直接提取,无需 copy_indice
uint32_t rd = BITS(Instruction, 11, 7);
uint32_t rs1 = BITS(Instruction, 19, 15);
uint32_t uimm = rs1; // 对于立即数CSR指令,rs1字段就是立即数
uint32_t csr_addr = BITS(Instruction, 31, 20);
uint32_t funct3 = BITS(Instruction, 14, 12);
uint32_t reg_rdata1 = state.gpr[rs1];
bool we = funct3 == 1 || rs1 != 0;
bool re = funct3 != 1 || rd != 0;
uint32_t wcmd = funct3 & 0b11;
uint32_t csr_wdata = 0, wdata;
if (funct3 & 0b100) {
wdata = rs1;
} else {
wdata = reg_rdata1;
}