Skip to content

Instantly share code, notes, and snippets.

@adielbm
Last active January 7, 2025 22:22
Show Gist options
  • Save adielbm/6c58e02d0d1ba3470cab9c30340f3ea0 to your computer and use it in GitHub Desktop.
Save adielbm/6c58e02d0d1ba3470cab9c30340f3ea0 to your computer and use it in GitHub Desktop.
data hazard
const STAGES = { IF: 1, ID: 2, EX: 3, MEM: 4, WB: 5 };
const removeParentheses = (str) => str.replace(/.*\(|\)/g, "");
const printRed = (text) => process.stdout.write(`\x1b[31m${text}\x1b[0m`);
function detectDataHazards(instructions) {
let destStage;
process.stdout.write("\n\n---------------------TEST----------------------\n");
const hazards = instructions.map(() => Array(3).fill(null));
instructions.forEach((curr, i) => {
const [_, currDest, currSrc1, currSrc2] = curr;
instructions.slice(0, i).forEach((prev, j) => {
// const [__, prevDest] = prev;
const [prevOp, prevDest, prevSrc1, prevSrc2] = prev;
[currSrc1, currSrc2]
.filter((src) => src)
.forEach((src, k) => {
// is src is immediate value
if (src[0] === "#") return;
src = removeParentheses(src);
if (prevOp === "lw") {
destStage = STAGES.MEM;
} else if (["add", "sub", "addi", "or", "and"].includes(prevOp)) {
destStage = STAGES.WB;
}
if (src === prevDest && j + destStage >= i + STAGES.ID) {
hazards[i][k + 1] = hazards[j][0] = true;
printRed(
`\n${src} is read in CC ${
i + STAGES.ID
} (in ins:${i}), but written in CC ${j + destStage} (in ins:${j})`
);
}
});
});
});
// Print instructions with hazards
instructions.forEach((inst, i) => {
process.stdout.write(`\n${i}: ${inst[0]}`);
inst.slice(1).forEach((val, j) => {
if (val === null) return;
hazards[i][j] ? printRed(` ${val}`) : process.stdout.write(` ${val}`);
});
});
}
// Test cases
const tests = [
[
["add", "$s0", "$t1", "$t2"],
["sub", "$t2", "$s0", "$t3"],
],
[
["lw", "$s0", "20($t1)", null],
["sub", "$t2", "$s0", "$t3"],
],
[
["lw", "$t1", "0($t0)", null],
["lw", "$t2", "4($t0)", null],
["add", "$t3", "$t1", "$t2"],
["sw", "$t3", "12($t0)", null],
["lw", "$t4", "8($t0)", null],
["add", "$t5", "$t1", "$t4"],
["sw", "$t5", "16($t0)", null],
],
[
["lw", "$t1", "0($t0)", null],
["lw", "$t2", "4($t0)", null],
["lw", "$t4", "8($t0)", null],
["add", "$t3", "$t1", "$t2"],
["sw", "$t3", "12($t0)", null],
["add", "$t5", "$t1", "$t4"],
["sw", "$t5", "16($t0)", null],
],
[
["add", "$t1", "$t0", "$t0"],
["addi", "$t2", "$t0", "#5"],
["addi", "$t4", "$t1", "#5"],
],
[
["sub", "$2", "$1", "$3"],
["and", "$12", "$2", "$5"],
["or", "$13", "$6", "$2"],
["add", "$14", "$2", "$2"],
["sw", "$14", "100($2)", null],
],
];
tests.forEach(detectDataHazards);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment