Repository navigation
Expand file tree
/
Copy pathsimulator.cpp
More file actions
485 lines (400 loc) · 19.3 KB
/
Copy pathsimulator.cpp
File metadata and controls
485 lines (400 loc) · 19.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
#include <iostream>
#include "simulator.h"
#include <fstream>
#include <string>
#include <iomanip>
#include <algorithm>
// =============================================================================
// Constructor
// =============================================================================
Simulator::Simulator(const std::vector<Instruction>& prog)
: program(prog), registers(32, 0), pc(0),
cycles(0), instructions(0), stalls(0),
ex_timer(0), is_stalled(false), branch_taken(false)
{
if_id.valid = false;
id_ex.valid = false;
ex_mem.valid = false;
mem_wb.valid = false;
forwarding = true;
memory.resize(4096 / 4, 0);
}
// =============================================================================
// loadConfig — Reads config file (INI-safe)
// =============================================================================
void Simulator::loadConfig(const std::string& file) {
std::ifstream f(file);
if (!f.is_open()) {
std::cout << "WARNING: Could not open config file: " << file << "\n";
return;
}
std::string line;
while (std::getline(f, line)) {
if (line.empty()) continue;
// Skip INI section headers like [vm], [pipeline] etc.
if (line.find('[') != std::string::npos) continue;
// Strip inline comments
size_t hash = line.find('#');
if (hash != std::string::npos) line = line.substr(0, hash);
auto pos = line.find('=');
if (pos == std::string::npos) continue;
std::string key = line.substr(0, pos);
std::string val_str = line.substr(pos + 1);
key.erase(std::remove_if(key.begin(), key.end(), ::isspace), key.end());
val_str.erase(std::remove_if(val_str.begin(), val_str.end(), ::isspace), val_str.end());
for (char& c : key) c = (char)std::tolower((unsigned char)c);
// ── Phase 1 / 2 keys ─────────────────────────────────────────────────
if (key == "forwarding") forwarding = (std::stoi(val_str) == 1);
else if (key == "memory_size") memory.resize(std::stoi(val_str) / 4, 0);
else if (key == "l1i_size") l1i_size = std::stoi(val_str);
else if (key == "l1d_size") l1d_size = std::stoi(val_str);
else if (key == "l2_size") l2_size = std::stoi(val_str);
else if (key == "block_size") block_size = std::stoi(val_str);
else if (key == "associativity") associativity = std::stoi(val_str);
else if (key == "cache_latency") cache_latency = std::stoi(val_str);
else if (key == "memory_latency") memory_latency = std::stoi(val_str);
else if (key == "replacement_policy") replacement_policy = val_str;
// ── Phase 3 VM keys ───────────────────────────────────────────────────
else if (key == "virtual_size_bytes") virtual_size_bytes = (uint64_t)std::stoull(val_str);
else if (key == "physical_size_bytes") physical_size_bytes = (uint64_t)std::stoull(val_str);
else if (key == "page_size_bytes") page_size_bytes = (uint32_t)std::stoul(val_str);
else if (key == "dtlb_entries") dtlb_entries = std::stoi(val_str);
else if (key == "tlb_hit_latency") tlb_hit_latency = std::stoi(val_str);
else if (key == "page_walk_latency") page_walk_latency = std::stoi(val_str);
else if (key == "page_fault_latency") page_fault_latency = std::stoi(val_str);
// ── Instruction latencies ─────────────────────────────────────────────
else {
try { latency[key] = std::stoi(val_str); } catch (...) {}
}
}
// ── Build cache hierarchy (Phase 2) ──────────────────────────────────────
cache_sys = CacheSystem(cache_latency, 15, memory_latency);
std::string rp_upper = replacement_policy;
for (char& c : rp_upper) c = (char)std::toupper((unsigned char)c);
ReplacementPolicy rp = (rp_upper == "FIFO") ? ReplacementPolicy::FIFO : ReplacementPolicy::LRU;
if (l1i_size > 0 && block_size > 0 && associativity > 0)
cache_sys.l1i = Cache(l1i_size, block_size, associativity, rp);
if (l1d_size > 0 && block_size > 0 && associativity > 0)
cache_sys.l1d = Cache(l1d_size, block_size, associativity, rp);
if (l2_size > 0 && block_size > 0 && associativity > 0)
cache_sys.l2 = Cache(l2_size, block_size, associativity * 2, rp);
// ── Build VM subsystem (Phase 3) ─────────────────────────────────────────
VMConfig vm_cfg;
vm_cfg.virtual_size_bytes = virtual_size_bytes;
vm_cfg.physical_size_bytes = physical_size_bytes;
vm_cfg.page_size_bytes = page_size_bytes;
vm_cfg.dtlb_entries = dtlb_entries;
vm_cfg.tlb_hit_latency = tlb_hit_latency;
vm_cfg.page_walk_latency = page_walk_latency;
vm_cfg.page_fault_latency = page_fault_latency;
std::string rp_lower = replacement_policy;
for (char& c : rp_lower) c = (char)std::tolower((unsigned char)c);
vm_cfg.replacement_policy = rp_lower;
vm_cfg.compute();
vm.init(vm_cfg);
}
// =============================================================================
// Write-Back Stage
// =============================================================================
void Simulator::writeBackStage() {
if (!mem_wb.valid) return;
instructions++;
if (mem_wb.rd != 0 && mem_wb.rd != -1) {
const std::string& op = mem_wb.inst.opcode;
bool writeback = (op == "add" || op == "sub" ||
op == "addi" || op == "lw" || op == "jal" ||
op == "mul" || op == "l");
if (writeback) {
registers[mem_wb.rd] = mem_wb.result_data;
}
}
}
// =============================================================================
// Memory Stage
// =============================================================================
void Simulator::memoryStage(MEM_WB_Reg& next_mem_wb) {
if (!ex_mem.valid) { next_mem_wb.valid = false; return; }
const std::string& op = ex_mem.inst.opcode;
// ── Phase 2 path: traditional lw / sw ────────────────────────────────────
if (op == "lw" || op == "sw") {
if (mem_timer == 0) {
AccessResult res = cache_sys.accessData(ex_mem.alu_result, (op == "sw"));
mem_timer = res.total_latency;
}
if (mem_timer > 1) { mem_timer--; next_mem_wb.valid = false; return; }
mem_timer = 0;
next_mem_wb.inst = ex_mem.inst;
next_mem_wb.pc = ex_mem.pc;
next_mem_wb.rd = ex_mem.rd;
next_mem_wb.valid = true;
if (op == "lw") {
int addr = ex_mem.alu_result;
next_mem_wb.result_data = (addr >= 0 && addr / 4 < (int)memory.size()) ? memory[addr / 4] : 0;
} else {
int addr = ex_mem.alu_result;
if (addr >= 0 && addr / 4 < (int)memory.size())
memory[addr / 4] = ex_mem.store_val;
next_mem_wb.result_data = 0;
}
return;
}
// ── Phase 3 path: trace-mode L / S ───────────────────────────────────────
if (op == "l" || op == "s") {
if (mem_timer == 0) {
uint32_t vaddr = ex_mem.inst.vaddr;
bool is_store = (op == "s");
uint32_t paddr = 0;
int vm_penalty = 0;
vm.translate(vaddr, is_store, paddr, vm_penalty);
AccessResult res = cache_sys.accessData(paddr, is_store);
mem_timer = vm_penalty + res.total_latency;
}
if (mem_timer > 1) { mem_timer--; next_mem_wb.valid = false; return; }
mem_timer = 0;
next_mem_wb.inst = ex_mem.inst;
next_mem_wb.pc = ex_mem.pc;
next_mem_wb.rd = ex_mem.rd;
next_mem_wb.result_data = 0;
next_mem_wb.valid = true;
return;
}
mem_timer = 0;
next_mem_wb.inst = ex_mem.inst;
next_mem_wb.pc = ex_mem.pc;
next_mem_wb.rd = ex_mem.rd;
next_mem_wb.result_data = ex_mem.alu_result;
next_mem_wb.valid = true;
}
// =============================================================================
// Execute Stage
// =============================================================================
void Simulator::executeStage(EX_MEM_Reg& next_ex_mem, ID_EX_Reg& next_id_ex) {
if (mem_timer > 0) return;
if (!id_ex.valid) { next_ex_mem.valid = false; return; }
if (ex_timer == 0) {
int lat = 1;
if (latency.count(id_ex.opcode)) lat = latency[id_ex.opcode];
if (id_ex.opcode == "mul" && !latency.count("mul")) lat = 3;
if ((id_ex.opcode == "l" || id_ex.opcode == "s") && !latency.count(id_ex.opcode)) lat = 1;
ex_timer = lat;
}
ex_timer--;
if (ex_timer > 0) {
next_ex_mem.valid = false;
next_id_ex = id_ex;
return;
}
ex_timer = 0;
int val1 = id_ex.rs1_val;
int val2 = id_ex.rs2_val;
if (forwarding) {
if (mem_wb.valid && mem_wb.rd != 0 && mem_wb.rd != -1) {
if (mem_wb.rd == id_ex.inst.rs1) val1 = mem_wb.result_data;
if (mem_wb.rd == id_ex.inst.rs2) val2 = mem_wb.result_data;
}
if (ex_mem.valid && ex_mem.rd != 0 && ex_mem.rd != -1 &&
ex_mem.inst.opcode != "lw" && ex_mem.inst.opcode != "l") {
if (ex_mem.rd == id_ex.inst.rs1) val1 = ex_mem.alu_result;
if (ex_mem.rd == id_ex.inst.rs2) val2 = ex_mem.alu_result;
}
}
next_ex_mem.inst = id_ex.inst;
next_ex_mem.pc = id_ex.pc;
next_ex_mem.rd = id_ex.rd;
next_ex_mem.store_val = val2;
next_ex_mem.valid = true;
const std::string& op = id_ex.opcode;
if (op == "add") next_ex_mem.alu_result = val1 + val2;
else if (op == "mul") next_ex_mem.alu_result = val1 * val2;
else if (op == "sub") next_ex_mem.alu_result = val1 - val2;
else if (op == "addi") next_ex_mem.alu_result = val1 + id_ex.imm;
else if (op == "lw" || op == "sw") next_ex_mem.alu_result = val1 + id_ex.imm;
else if (op == "jal") next_ex_mem.alu_result = id_ex.pc + 1;
else if (op == "l" || op == "s") next_ex_mem.alu_result = 0;
next_id_ex.valid = false;
}
// =============================================================================
// Decode Stage
// =============================================================================
void Simulator::decodeStage(ID_EX_Reg& next_id_ex, IF_ID_Reg& next_if_id) {
if (!if_id.valid) return;
if (next_id_ex.valid) {
is_stalled = true;
next_if_id = if_id;
return;
}
Instruction inst = if_id.inst;
int rs1 = inst.rs1;
int rs2 = inst.rs2;
bool stall = false;
bool is_branch = (inst.opcode == "bne" || inst.opcode == "blt" || inst.opcode == "jal");
if (ex_mem.valid && ex_mem.rd != 0 && ex_mem.rd != -1) {
if (ex_mem.rd == rs1 || (inst.opcode != "addi" && ex_mem.rd == rs2)) {
if (!forwarding) stall = true;
if (ex_mem.inst.opcode == "lw" || ex_mem.inst.opcode == "l") stall = true;
}
}
if (id_ex.valid && id_ex.rd != 0 && id_ex.rd != -1) {
if (id_ex.rd == rs1 || (inst.opcode != "addi" && id_ex.rd == rs2)) {
if (id_ex.opcode == "lw" || id_ex.opcode == "l") stall = true;
if (!forwarding) stall = true;
if (is_branch) stall = true;
}
}
if (stall) {
next_id_ex.valid = false;
next_if_id = if_id;
is_stalled = true;
return;
}
is_stalled = false;
int r1_val = (rs1 != -1) ? registers[rs1] : 0;
int r2_val = (rs2 != -1) ? registers[rs2] : 0;
if (forwarding) {
if (mem_wb.valid && mem_wb.rd != 0 && mem_wb.rd != -1) {
if (mem_wb.rd == rs1) r1_val = mem_wb.result_data;
if (mem_wb.rd == rs2) r2_val = mem_wb.result_data;
}
if (ex_mem.valid && ex_mem.rd != 0 && ex_mem.rd != -1 &&
ex_mem.inst.opcode != "lw" && ex_mem.inst.opcode != "l") {
if (ex_mem.rd == rs1) r1_val = ex_mem.alu_result;
if (ex_mem.rd == rs2) r2_val = ex_mem.alu_result;
}
}
bool take = false;
if (inst.opcode == "bne" && r1_val != r2_val) take = true;
if (inst.opcode == "blt" && r1_val < r2_val) take = true;
if (inst.opcode == "jal") take = true;
if (take) {
pc = if_id.pc + inst.imm;
branch_taken = true;
next_id_ex.valid = false;
return;
}
next_id_ex.inst = inst;
next_id_ex.pc = if_id.pc;
next_id_ex.opcode = inst.opcode;
next_id_ex.rd = inst.rd;
next_id_ex.imm = inst.imm;
next_id_ex.rs1_val = r1_val;
next_id_ex.rs2_val = r2_val;
next_id_ex.valid = true;
next_if_id.valid = false;
}
// =============================================================================
// Fetch Stage
// =============================================================================
void Simulator::fetchStage(IF_ID_Reg& next_if_id) {
if (is_stalled) return;
if (branch_taken) {
next_if_id.valid = false;
branch_taken = false;
if_timer = 0;
return;
}
if (next_if_id.valid || pc >= (int)program.size()) return;
if (if_timer == 0) {
AccessResult res = cache_sys.accessInstruction(pc * 4);
if_timer = res.total_latency;
}
if (if_timer > 1) { if_timer--; return; }
if_timer = 0;
next_if_id.inst = program[pc];
next_if_id.pc = pc;
next_if_id.valid = true;
pc++;
}
// =============================================================================
// Run Engine
// =============================================================================
void Simulator::run(bool single_step) {
int safety = 0;
const int SAFETY_LIMIT = 500000000;
if (single_step && !trace_mode) {
std::cout << "\n=== SINGLE STEP MODE ===\n"
<< "Press [ENTER] to advance a cycle, or type 'c' to run to completion.\n";
}
while ((pc < (int)program.size() ||
if_id.valid || id_ex.valid || ex_mem.valid || mem_wb.valid)
&& safety < SAFETY_LIMIT) {
if (single_step && !trace_mode) {
std::cout << "\n--- CYCLE " << std::dec << cycles + 1 << " ---\n";
std::cout << "[Fetch] ";
if (if_timer > 0) std::cout << "Wait (Cache Miss: " << if_timer << " cycles left)\n";
else std::cout << (pc < (int)program.size() && !is_stalled && !branch_taken ? program[pc].opcode : "Bubble/Wait") << "\n";
std::cout << "[Decode] " << (if_id.valid ? if_id.inst.opcode : "Bubble");
if (is_stalled && if_id.valid) std::cout << " (Hazard Stall)";
std::cout << "\n[Execute] " << (id_ex.valid ? id_ex.inst.opcode : "Bubble") << "\n";
std::cout << "[Memory] ";
if (mem_timer > 0 && ex_mem.valid) std::cout << ex_mem.inst.opcode << " (Stall: " << mem_timer << " cycles left)\n";
else std::cout << (ex_mem.valid ? ex_mem.inst.opcode : "Bubble") << "\n";
std::cout << "[WriteBack] " << (mem_wb.valid ? mem_wb.inst.opcode : "Bubble") << "\n";
cache_sys.l1i.printActiveState("L1 Instruction Cache");
cache_sys.l1d.printActiveState("L1 Data Cache");
}
MEM_WB_Reg next_mem_wb = mem_wb;
EX_MEM_Reg next_ex_mem = ex_mem;
ID_EX_Reg next_id_ex = id_ex;
IF_ID_Reg next_if_id = if_id;
next_mem_wb.valid = false;
writeBackStage();
memoryStage(next_mem_wb);
executeStage(next_ex_mem, next_id_ex);
decodeStage(next_id_ex, next_if_id);
fetchStage(next_if_id);
if (mem_timer > 1 || if_timer > 1 || is_stalled || ex_timer > 0) stalls++;
mem_wb = next_mem_wb;
ex_mem = next_ex_mem;
id_ex = next_id_ex;
if_id = next_if_id;
cycles++;
safety++;
if (single_step && !trace_mode) {
std::cout << "Action > ";
std::string input;
std::getline(std::cin, input);
if (input == "c" || input == "C") {
single_step = false;
std::cout << "Running to completion...\n";
}
}
}
// ── Statistics ─────────────────────────────────────────────────────────────
uint64_t total_l1_hits = cache_sys.l1i.hits + cache_sys.l1d.hits;
uint64_t total_l1_misses = cache_sys.l1i.misses + cache_sys.l1d.misses;
uint64_t total_accesses = total_l1_hits + total_l1_misses;
double miss_rate = (total_accesses > 0) ? (double)total_l1_misses / total_accesses : 0.0;
if (!trace_mode) {
std::cout << "\nFINAL MEMORY STATE:\n";
for (int i = 0; i < 5; i++)
std::cout << "Address " << (i * 4) << ": " << memory[i] << "\n";
}
std::cout << "\n==================================================\n";
std::cout << " EXECUTION DASHBOARD \n";
std::cout << "==================================================\n";
std::cout << "\n[PIPELINE STATISTICS]\n";
std::cout << " Total Cycles: " << cycles << "\n";
std::cout << " Instructions: " << instructions << "\n";
std::cout << " Stalls: " << stalls << "\n";
if (cycles > 0)
std::cout << " IPC: " << std::fixed << std::setprecision(3) << (float)instructions / cycles << "\n";
std::cout << "\n[L1/L2 CACHE STATISTICS]\n";
std::cout << " Total Accesses: " << total_accesses << "\n";
std::cout << " L1 Hits: " << total_l1_hits << "\n";
std::cout << " L1 Misses: " << total_l1_misses << "\n";
std::cout << " L1 Miss Rate: " << std::fixed << std::setprecision(2) << miss_rate * 100 << "%\n";
std::cout << " L2 Hits: " << cache_sys.l2.hits << "\n";
std::cout << " L2 Misses: " << cache_sys.l2.misses << "\n";
if (trace_mode) {
VMStats vms = vm.getStats();
std::cout << "\n[VIRTUAL MEMORY STATISTICS]\n";
std::cout << " TLB Hits: " << vms.tlb_hits << "\n";
std::cout << " TLB Misses: " << vms.tlb_misses << "\n";
std::cout << " Page Walks: " << vms.page_walks << "\n";
std::cout << " Page Faults: " << vms.page_faults << "\n";
std::cout << " Page Evictions: " << vms.page_evictions << "\n";
std::cout << " Dirty Evictions: " << vms.dirty_evictions << " (Writebacks)\n";
std::cout << " Translation Penalty: " << vms.translation_penalty_cycles << " cycles\n";
}
std::cout << "==================================================\n\n";
}