Certainly! The provided Python script is a comprehensive tool that functions both as an assembler and a simulator for a subset of MIPS (Microprocessor without Interlocked Pipelined Stages) assembly language instructions. Below is a detailed breakdown of the entire code, including explanations of each component, data structure, function, and walkthroughs for various instruction combinations.
Overview
The script performs the following key tasks:
- Register Mapping: Maps MIPS register names to their corresponding numbers and vice versa.
- File Processing: Reads and cleans an assembly file by removing comments and empty lines.
- Parsing: Parses labels, instructions, and data sections from the assembly code.
- Translation: Converts assembly instructions into their binary (machine code) representations.
- Simulation: Simulates the execution of the binary instructions, managing registers and memory.
- Syscall Handling: Supports system calls like printing integers or strings and exiting the program.
- User Interaction: Allows users to choose between single-step execution or automatic execution modes.
Let's dive into each component in detail.
1. Register Mapping
reg_map Dictionary
reg_map = {
'zero': 0, 'at': 1,
'v0': 2, 'v1': 3,
'a0': 4, 'a1': 5, 'a2': 6, 'a3': 7,
't0': 8, 't1': 9, 't2': 10, 't3': 11, 't4': 12,
't5': 13, 't6': 14, 't7': 15,
's0': 16, 's1':17, 's2':18, 's3':19,
's4':20, 's5':21, 's6':22, 's7':23,
't8':24, 't9':25, 'k0':26, 'k1':27,
'gp':28, 'sp':29, 'fp':30, 'ra':31
}
- Purpose: This dictionary maps MIPS register names (like
$zero, $v0, $a0) to their corresponding register numbers (0 to 31).
- Usage: Facilitates easy conversion between register names and numbers during instruction parsing and simulation.
Helper Functions
get_register_number(reg_name)
def get_register_number(reg_name):
reg_name = reg_name.strip().lstrip('$')
if reg_name.isdigit(): # For registers like $0 - $31
return int(reg_name)
elif reg_name in reg_map:
return reg_map[reg_name]
else:
raise ValueError(f"Unknown register name {reg_name}")
- Functionality: Converts a register name (e.g.,
$t0, $1) to its numeric representation.
- Logic:
- Strips any whitespace and leading
$.
- If the stripped name is a digit (like
0 to 31), it's directly converted to an integer.
- If it's a named register (like
t0), it's looked up in reg_map.
- Throws an error if the register name is unrecognized.
get_register_name(num)
def get_register_name(num):
for name, n in reg_map.items():
if n == num:
return name
raise ValueError(f"Unknown register number {num}")
- Functionality: Converts a register number back to its name.
- Logic:
- Iterates through
reg_map to find the register name corresponding to the given number.
- Throws an error if the register number is unrecognized.
2. File Processing
read_asm_file(file_path)
def read_asm_file(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
# Remove comments and empty lines
instructions = []
for line in lines:
line = re.sub(r'#.*', '', line).strip()
if line:
instructions.append(line)
return instructions
- Functionality: Reads an assembly file and cleans its content.
- Logic:
- Opens the file and reads all lines.
- For each line:
- Removes comments (anything after
#).
- Strips leading and trailing whitespace.
- Adds non-empty lines to the
instructions list.
- Result: Returns a list of cleaned assembly instructions.
3. Parsing Labels and Instructions
parse_labels_and_instructions(instructions)
def parse_labels_and_instructions(instructions):
labels = {}
parsed_instructions = []
pc = 0
data_mode = False
memory = {}
current_address = 0x10010000 # Starting address for data section
for line in instructions:
if line.startswith(".data"):
data_mode = True
continue
elif line.startswith(".text"):
data_mode = False
pc = 0
continue
if data_mode:
if ':' in line:
label, line_part = line.split(':', 1)
labels[label.strip()] = current_address
line = line_part.strip()
if line.startswith('.word'):
line = line.replace('.word', '').strip()
values = line.split(',')
for value in values:
memory[current_address] = int(value)
current_address += 4
elif line.startswith('.asciiz'):
line = line.replace('.asciiz', '').strip().strip('"')
for char in line:
memory[current_address] = ord(char)
current_address += 1
memory[current_address] = 0 # Null-terminate the string
current_address += 1
else:
if ':' in line:
label, line_part = line.split(':', 1)
labels[label.strip()] = pc
line = line_part.strip()
if line:
parsed_instructions.append(line)
pc += 4
return parsed_instructions, labels, memory
- Functionality: Parses labels, instructions, and data sections from the cleaned assembly instructions.
- Components:
- Labels Dictionary (
labels): Maps label names to their corresponding addresses.
- Parsed Instructions List (
parsed_instructions): Stores the assembly instructions excluding labels and data.
- Memory Dictionary (
memory): Simulates memory for the data section.
- Program Counter (
pc): Keeps track of the current instruction's address.
- Data Mode Flag (
data_mode): Indicates whether the parser is in the .data or .text section.
- Logic:
- Iterates through each instruction line.
- Switches between
.data and .text sections based on directives.
- In
.data Section:
- Parses labels and associates them with memory addresses starting from
0x10010000.
- Handles
.word directives by storing integer values.
- Handles
.asciiz directives by storing ASCII characters and null-terminating the string.
- In
.text Section:
- Parses labels and associates them with instruction addresses (PC).
- Appends non-label lines to
parsed_instructions and increments PC by 4 (since MIPS instructions are 4 bytes).
- Result: Returns a tuple containing the list of parsed instructions, labels dictionary, and memory dictionary.
4. Instruction to Binary Conversion
convert_to_binary(instruction, labels, current_pc)
def convert_to_binary(instruction, labels, current_pc):
# ... [Function content as in the original code]
- Functionality: Converts an assembly instruction into its binary (machine code) representation.
- Components:
- Opcodes and Function Codes: Dictionaries that store the binary codes for various MIPS operations.
- Instruction Parsing: Splits the instruction into parts (operation and operands).
- Binary Construction: Assembles the binary representation based on instruction type (R, I, J).
- Process for Different Instructions:
- Pseudo-Instructions (
li, la):
li: Load immediate value into a register.
- If the immediate fits in 16 bits, uses
addi with $zero.
- If not, splits into
lui (load upper immediate) and ori (OR immediate).
la: Load address of a label into a register.
- Splits into
lui and ori similarly to li.
- System Call (
syscall):
- Encoded with specific function codes.
- I-Type Instructions (
addi, andi, ori, lw, sw, beq, bne, lui):
- Formatted with an opcode, source and target registers, and immediate values.
- J-Type Instructions (
j, jal):
- Encoded with an opcode and a jump target address.
- R-Type Instructions (
add, sub, and, or, slt, mul, sll, srl, jr, etc.):
- Encoded with an opcode (usually
000000), source and target registers, destination register, shift amount, and function code.
- Error Handling:
- If an instruction is not recognized or improperly formatted, it prints an error message and returns
None.
- Return Value:
Example Walkthroughs
Let's explore how convert_to_binary handles different types of instructions with examples.
A. Load Immediate (li)
Assembly Instruction:
li $t0, 100
Process:
- Check Immediate Value:
100 fits in 16 bits, so it's handled using addi.
- Convert to
addi:
- Binary Encoding:
- Opcode for
addi: 001000
$zero (source register): 00000
$t0 (target register): 01000
- Immediate:
0000000001100100 (binary for 100)
- Final Binary:
00100000000010000000000001100100
B. Load Address (la)
Assembly Instruction:
la $s0, label
Process:
- Find Label Address:
- Suppose
label is at address 0x10010000.
- Split into
lui and ori:
lui $s0, 0x1001 (upper 16 bits)
ori $s0, $s0, 0x0000 (lower 16 bits)
- Binary Encoding:
lui:
- Opcode:
001111
$zero: 00000
$s0: 10000
- Immediate:
0001000000000001 (0x1001)
ori:
- Opcode:
001101
$s0: 10000
$s0: 10000
- Immediate:
0000000000000000 (0x0000)
- Final Binaries:
00111100000100000001000000000001
00110110000100000000000000000000
C. Add Instruction (add)
Assembly Instruction:
add $s1, $s2, $s3
Process:
- Extract Registers:
$s1 (destination): 10001
$s2 (source 1): 10010
$s3 (source 2): 10011
- Binary Encoding:
- Opcode:
000000 (R-type)
$s2: 10010
$s3: 10011
$s1: 10001
- Shamt:
00000 (no shift)
- Function Code for
add: 100000
- Final Binary:
00000010010100111000100000100000
D. Branch If Equal (beq)
Assembly Instruction:
beq $t0, $t1, label
Process:
- Extract Registers and Label:
$t0: 01000
$t1: 01001
label: Suppose at PC+offset.
- Calculate Offset:
- Offset = (Address of
label - (current PC + 4)) / 4
- Suppose
label is 8 bytes ahead: Offset = 2 (0000000000000010)
- Binary Encoding:
- Opcode for
beq: 000100
$t0: 01000
$t1: 01001
- Offset:
0000000000000010
- Final Binary:
00010001000010010000000000000010
E. Jump (j)
Assembly Instruction:
j label
Process:
- Find Label Address:
- Suppose
label is at address 0x00400010.
- Calculate Jump Target:
- Target =
0x00400010 >> 2 = 0x00100004
- Binary:
00000001000000000000000100
- Binary Encoding:
- Opcode for
j: 000010
- Target Address:
00000001000000000000000100
- Final Binary:
00001000000001000000000000000100
5. Generating Control Signals
generate_control_signals(op_code)
def generate_control_signals(op_code):
signals = {
'RegDst': 0,
'RegWrite': 0,
'ALUSrc': 0,
'ALUOp': '00',
'MemRead': 0,
'MemWrite': 0,
'MemtoReg': 0,
'Branch': 0,
'Jump': 0,
'Syscall': 0 # Added syscall control signal
}
if op_code in ['add', 'sub', 'and', 'or', 'slt', 'mul', 'xor', 'nor', 'sll', 'srl']:
signals['RegDst'] = 1
signals['RegWrite'] = 1
signals['ALUOp'] = '10'
elif op_code in ['addi', 'andi', 'ori', 'li', 'lui']:
signals['ALUSrc'] = 1
signals['RegWrite'] = 1
signals['ALUOp'] = '00'
elif op_code == 'lw':
signals['ALUSrc'] = 1
signals['MemtoReg'] = 1
signals['RegWrite'] = 1
signals['MemRead'] = 1
signals['ALUOp'] = '00'
elif op_code == 'sw':
signals['ALUSrc'] = 1
signals['MemWrite'] = 1
signals['ALUOp'] = '00'
elif op_code == 'beq':
signals['Branch'] = 1
signals['ALUOp'] = '01'
elif op_code == 'bne':
signals['Branch'] = 1
signals['ALUOp'] = '01'
elif op_code == 'j':
signals['Jump'] = 1
elif op_code == 'jal':
signals['Jump'] = 1
signals['RegWrite'] = 1
elif op_code == 'jr':
signals['Jump'] = 1
elif op_code == 'syscall':
signals['Syscall'] = 1 # Indicate syscall operation
else:
# Unknown operation
raise ValueError(f"Unsupported operation {op_code}")
return signals
6. Display Functions
display_registers(reg)
def display_registers(reg):
print("Registers:")
for i in range(0, 32, 4):
reg_names = []
for num in range(i, i+4):
name = get_register_name(num)
reg_names.append(name)
print(f"${reg_names[0]:<3}: {reg[reg_names[0]]:10} | "
f"${reg_names[1]:<3}: {reg[reg_names[1]]:10} | "
f"${reg_names[2]:<3}: {reg[reg_names[2]]:10} | "
f"${reg_names[3]:<3}: {reg[reg_names[3]]:10}")
print()
- Functionality: Displays the contents of all 32 MIPS registers in a formatted manner.
- Logic:
- Iterates through registers in groups of four.
- Fetches register names and values.
- Prints in a tabular format for readability.
display_memory(memory)
def display_memory(memory):
print("Memory:")
addresses = sorted(memory.keys())
for addr in addresses:
value = memory[addr]
if 32 <= value <= 126:
display_value = f"{value} ('{chr(value)}')"
else:
display_value = str(value)
print(f"Address {addr:08x}: {display_value}")
print()
- Functionality: Displays the contents of memory in a formatted manner.
- Logic:
- Sorts memory addresses.
- For each address:
- If the value is within printable ASCII range (
32 to 126), displays both the numeric value and the corresponding character.
- Otherwise, displays the numeric value only.
- Prints each memory location with its address in hexadecimal.
7. System Call Handling
syscall(reg, memory)
def syscall(reg, memory):
syscall_num = reg['v0']
if syscall_num == 1:
# Print integer in $a0
print(f"Output (int): {reg['a0']}")
elif syscall_num == 4:
# Print string at address in $a0
print("Output (string):", end="")
string_address = reg['a0']
while memory.get(string_address, 0) != 0:
print(chr(memory[string_address]), end="")
string_address +=1
print()
elif syscall_num ==10:
# Exit program
print("Exiting program.")
return False
else:
print(f"Unknown syscall: {syscall_num}")
return True
- Functionality: Handles MIPS system calls based on the value in the
$v0 register.
- Supported Syscalls:
- Print Integer (
$v0 = 1):
- Prints the integer value stored in
$a0.
- Print String (
$v0 = 4):
- Treats
$a0 as the memory address of a null-terminated string and prints it.
- Exit Program (
$v0 = 10):
- Logic:
- Fetches
syscall_num from $v0.
- Executes the corresponding action.
- Returns
False to indicate program termination for exit.
- Returns
True to continue execution otherwise.
- Error Handling:
- Prints an error message for unknown syscalls.
8. Simulation of Execution
run_simulation(parsed_instructions, labels, memory)
def run_simulation(parsed_instructions, labels, memory):
reg = {name: 0 for name in reg_map}
reg['zero'] = 0 # Ensure $zero is always 0
reg['sp'] = 0x7FFFFFFC # Initialize $sp (Stack Pointer)
pc = 0
sim_mode = input("Enter 'n' for single instruction mode, 'a' for automatic mode: ")
single_step = (sim_mode == 'n')
# Prepare the instructions in order including expanded instructions for 'li' and 'la'
instructions_list = []
pc_counter = 0
for inst in parsed_instructions:
bin_inst = convert_to_binary(inst, labels, pc_counter)
if bin_inst:
if isinstance(bin_inst, list):
# For 'li' and 'la' that expand into multiple instructions
for bi in bin_inst:
instructions_list.append((inst, bi, pc_counter))
pc_counter += 4
else:
instructions_list.append((inst, bin_inst, pc_counter))
pc_counter += 4
else:
instructions_list.append((inst, None, pc_counter))
pc_counter += 4
# Convert the instructions_list to a dictionary for easy PC lookup
inD = {pc: (inst, mc) for inst, mc, pc in instructions_list}
with open("binary_code.txt", "w") as bin_file:
while pc in inD:
current_instruction, mc = inD[pc]
parts = re.split(r'[,\s()]+', current_instruction)
parts = [p for p in parts if p] # Remove empty strings
op_code = parts[0]
# Generate control signals
try:
control_signals = generate_control_signals(op_code)
except ValueError as e:
print(f"Error: {e}")
break
if single_step:
print("\n" + "=" * 80)
print("Executing Instruction:")
print("Assembly Code:", current_instruction)
if mc:
print("Machine Code:", mc)
else:
print("Machine Code: N/A")
print("PC before execution:", pc)
print("Control Signals:", control_signals)
if mc:
if isinstance(mc, list):
for instruction in mc:
bin_file.write(f"{instruction}\n")
else:
bin_file.write(f"{mc}\n")
try:
# Handle syscall separately
if op_code == 'syscall':
if not syscall(reg, memory):
break
elif control_signals['Jump']:
if op_code == 'j' or op_code == 'jal':
label = parts[1]
if label in labels:
if op_code == 'jal':
reg['ra'] = pc + 4 # Save return address
pc = labels[label]
continue
else:
raise ValueError(f"Label {label} not found")
elif op_code == 'jr':
rs_name = get_register_name(get_register_number(parts[1]))
pc = reg[rs_name]
continue
elif control_signals['Branch']:
rs_name = get_register_name(get_register_number(parts[1]))
rt_name = get_register_name(get_register_number(parts[2]))
label = parts[3]
if op_code == 'beq' and reg[rs_name] == reg[rt_name]:
pc = labels[label]
continue
elif op_code == 'bne' and reg[rs_name] != reg[rt_name]:
pc = labels[label]
continue
else:
ALU_result = 0
if control_signals['ALUSrc']:
if op_code in ['addi', 'andi', 'ori']:
rt_name = get_register_name(get_register_number(parts[1]))
rs_name = get_register_name(get_register_number(parts[2]))
imm = int(parts[3])
if op_code == 'addi':
ALU_result = reg[rs_name] + imm
elif op_code == 'andi':
ALU_result = reg[rs_name] & imm
elif op_code == 'ori':
ALU_result = reg[rs_name] | imm
if control_signals['RegWrite']:
reg[rt_name] = ALU_result
elif op_code == 'lui':
rt_name = get_register_name(get_register_number(parts[1]))
imm = int(parts[2])
if control_signals['RegWrite']:
reg[rt_name] = imm << 16
elif op_code == 'li':
rd_name = get_register_name(get_register_number(parts[1]))
imm = int(parts[2])
if control_signals['RegWrite']:
reg[rd_name] = imm
elif op_code == 'lw':
rt_name = get_register_name(get_register_number(parts[1]))
if len(parts) == 4:
offset = int(parts[2])
base_num = get_register_number(parts[3])
base_name = get_register_name(base_num)
address = reg[base_name] + offset
elif len(parts) == 3:
# lw rt, label
label = parts[2]
address = labels.get(label)
if address is None:
raise ValueError(f"Label {label} not found")
else:
raise ValueError("Invalid lw instruction format")
if control_signals['MemRead']:
data = memory.get(address, 0)
if control_signals['RegWrite']:
reg[rt_name] = data
elif op_code == 'sw':
rt_name = get_register_name(get_register_number(parts[1]))
if len(parts) == 4:
offset = int(parts[2])
base_num = get_register_number(parts[3])
base_name = get_register_name(base_num)
address = reg[base_name] + offset
elif len(parts) == 3:
label = parts[2]
address = labels.get(label)
if address is None:
raise ValueError(f"Label {label} not found")
else:
raise ValueError("Invalid sw instruction format")
if control_signals['MemWrite']:
memory[address] = reg[rt_name]
else:
# ALU operations with register operands
rd_name = get_register_name(get_register_number(parts[1]))
rs_name = get_register_name(get_register_number(parts[2]))
rt_name = get_register_name(get_register_number(parts[3]))
if op_code == 'add':
ALU_result = reg[rs_name] + reg[rt_name]
elif op_code == 'sub':
ALU_result = reg[rs_name] - reg[rt_name]
elif op_code == 'and':
ALU_result = reg[rs_name] & reg[rt_name]
elif op_code == 'or':
ALU_result = reg[rs_name] | reg[rt_name]
elif op_code == 'slt':
ALU_result = 1 if reg[rs_name] < reg[rt_name] else 0
elif op_code == 'mul':
ALU_result = reg[rs_name] * reg[rt_name]
elif op_code == 'xor':
ALU_result = reg[rs_name] ^ reg[rt_name]
elif op_code == 'nor':
ALU_result = ~(reg[rs_name] | reg[rt_name])
elif op_code == 'sll':
rt_name = get_register_name(get_register_number(parts[2]))
shamt = int(parts[3])
ALU_result = reg[rt_name] << shamt
elif op_code == 'srl':
rt_name = get_register_name(get_register_number(parts[2]))
shamt = int(parts[3])
ALU_result = reg[rt_name] >> shamt
else:
raise ValueError(f"Unsupported ALU operation {op_code}")
if control_signals['RegWrite']:
reg[rd_name] = ALU_result
except Exception as e:
print(f"Error executing instruction: {current_instruction} -> {e}")
break
if single_step:
display_registers(reg)
# Optionally display memory
# display_memory(memory)
print("PC after execution:", pc + 4)
input("Press Enter to continue...")
pc += 4
if not single_step:
display_registers(reg)
# Optionally display memory if needed
# display_memory(memory)
- Functionality: Simulates the execution of the parsed instructions, managing the program counter (PC), registers, memory, and control signals.
- Components:
- Register Initialization:
- Initializes all registers to
0.
- Ensures
$zero remains 0.
- Initializes the stack pointer
$sp to 0x7FFFFFFC.
- Program Counter (
pc):
- Simulation Mode:
- Prompts the user to choose between single-step (
'n') and automatic ('a') execution.
- Instruction Preparation:
- Converts each assembly instruction to binary.
- Handles pseudo-instructions (
li, la) that expand into multiple instructions.
- Stores instructions in
instructions_list with their PC.
- Instruction Dictionary (
inD):
- Maps each PC to its corresponding instruction and machine code for quick lookup.
- Execution Loop:
- Runs until PC points to an instruction not in
inD.
- Control Signal Generation: Based on the opcode, generates the necessary control signals.
- Logging: In single-step mode, displays instruction details and control signals before execution.
- Binary File Writing: Writes machine code to
binary_code.txt.
- Instruction Execution:
- System Call: Handled separately via the
syscall function.
- Jump Instructions (
j, jal, jr): Updates PC to the target address.
- Branch Instructions (
beq, bne): Conditionally updates PC based on register comparisons.
- ALU Operations:
- Based on control signals and instruction type, performs arithmetic or logical operations.
- Updates destination registers accordingly.
- (, ):
9. Main Function
main()
def main():
file_path = "program.asm" # Ensure this file exists with your assembly code
instructions = read_asm_file(file_path)
parsed_instructions, labels, memory = parse_labels_and_instructions(instructions)
print("Assembly to Machine Code Conversion:")
pc_counter = 0
for inst in parsed_instructions:
bin_inst = convert_to_binary(inst, labels, pc_counter)
if bin_inst:
if isinstance(bin_inst, list):
for bi in bin_inst:
print(f"{inst} -> {bi}")
pc_counter += 4
else:
print(f"{inst} -> {bin_inst}")
pc_counter += 4
else:
print(f"{inst} -> Invalid instruction")
pc_counter += 4
run_simulation(parsed_instructions, labels, memory)
-
Functionality: Orchestrates the overall process of reading, parsing, converting, and simulating the assembly program.
-
Steps:
- File Reading: Reads
program.asm.
- Parsing: Parses labels, instructions, and initializes memory.
- Assembly to Binary Conversion:
- Iterates through each parsed instruction.
- Converts to binary using
convert_to_binary.
- Handles multi-instruction expansions (like
li and la).
- Prints the mapping from assembly to machine code.
- Simulation: Runs the simulation using
run_simulation.
-
Note: Ensure that program.asm exists in the same directory as the script with valid MIPS assembly code.
10. Execution Entry Point
if __name__ == "__main__":
main()
- Functionality: Specifies that the
main() function should be executed when the script is run directly.
Comprehensive Instruction Walkthroughs
Let's examine how the script handles various instruction types through detailed examples.
A. R-Type Instructions
Example Instructions:
add $s1, $s2, $s3 # $s1 = $s2 + $s3
sub $t0, $t1, $t2 # $t0 = $t1 - $t2
and $a0, $a1, $a2 # $a0 = $a1 & $a2
or $a3, $a4, $a5 # $a3 = $a4 | $a5
slt $v0, $v1, $v2 # $v0 = ($v1 < $v2) ? 1 : 0
mul $s0, $s1, $s2 # $s0 = $s1 * $s2
Execution Steps:
- Parsing:
- No labels or data sections; all lines are instructions.
- Binary Conversion:
- Each
add, sub, etc., is converted to its respective R-type binary code with appropriate function codes.
- Control Signals:
RegDst: 1 (destination is rd).
RegWrite: 1.
ALUOp: '10'.
- Simulation:
- ALU operations are performed based on the instruction.
- Destination registers are updated with the result.
- PC increments by 4 after each instruction.
Example Execution:
- Instruction:
add $s1, $s2, $s3
- Binary:
00000010010100111000100000100000
- Control Signals:
RegDst: 1
RegWrite: 1
ALUOp: '10'
- Operation:
reg['s1'] = reg['s2'] + reg['s3']
B. I-Type Instructions
Example Instructions:
addi $t0, $t1, 10 # $t0 = $t1 + 10
andi $t2, $t3, 15 # $t2 = $t3 & 15
ori $t4, $t5, 255 # $t4 = $t5 | 255
Execution Steps:
- Control Signals:
ALUSrc: 1 (uses immediate).
RegWrite: 1.
ALUOp: '00'.
- ALU Operations:
- Adds, ANDs, ORs as specified with immediate values.
- Simulation:
- ALU computes the result using register value and immediate.
- Destination register is updated.
- PC increments by 4.
Example Execution:
- Instruction:
addi $t0, $t1, 10
- Binary:
00100001001010000000000000001010
- Control Signals:
ALUSrc: 1
RegWrite: 1
ALUOp: '00'
- Operation:
reg['t0'] = reg['t1'] + 10
C. Memory Instructions
Example Instructions:
lw $t0, 0($t1) # Load word from memory[$t1 + 0] into $t0
sw $t0, 4($t1) # Store word from $t0 into memory[$t1 + 4]
Execution Steps:
- Control Signals:
lw:
ALUSrc: 1
MemtoReg: 1
RegWrite: 1
MemRead: 1
ALUOp: '00'.
sw:
ALUSrc: 1
MemWrite: 1
ALUOp: '00'.
- Simulation:
lw:
- Calculates address:
reg['t1'] + 0.
- Reads memory at the address.
- Updates
reg['t0'] with the read value.
sw:
- Calculates address:
reg['t1'] + 4.
- Writes
reg['t0'] to memory at the address.
- PC increments by 4 after each instruction.
Example Execution:
- Instruction:
lw $t0, 0($t1)
- Binary:
10001101001010000000000000000000
- Control Signals:
ALUSrc: 1
MemtoReg: 1
RegWrite: 1
MemRead: 1
ALUOp: '00'
- Operation:
reg['t0'] = memory[reg['t1'] + 0]
D. Branch Instructions
Example Instructions:
beq $t0, $t1, label1 # If $t0 == $t1, branch to label1
bne $t2, $t3, label2 # If $t2 != $t3, branch to label2
Execution Steps:
- Control Signals:
- Simulation:
beq:
- Compares
reg['t0'] and reg['t1'].
- If equal, sets PC to the address of
label1.
- Otherwise, PC increments by 4.
bne:
- Compares
reg['t2'] and reg['t3'].
- If not equal, sets PC to the address of
label2.
- Otherwise, PC increments by 4.
Example Execution:
- Instruction:
beq $t0, $t1, label1
- Binary:
00010001000010010000000000000010
- Control Signals:
- Operation:
- If
reg['t0'] == reg['t1'], then pc = labels['label1'].
E. Jump Instructions
Example Instructions:
j target_label # Jump to target_label
jal func_label # Jump and link to func_label
jr $ra # Jump to address in $ra
Execution Steps:
- Control Signals:
Jump: 1.
jal:
- Also sets
RegWrite: 1 (stores return address in $ra).
- Simulation:
j:
- Sets PC to the address of
target_label.
jal:
- Stores
pc + 4 in $ra (return address).
- Sets PC to the address of
func_label.
jr:
- Sets PC to the address contained in
reg['ra'].
Example Execution:
- Instruction:
j target_label
- Binary:
00001000000001000000000000000100
- Control Signals:
- Operation:
pc = labels['target_label']
11. Running the Program
To execute the script, follow these steps:
-
Prepare Assembly File:
- Create a file named
program.asm in the same directory as the script.
- Write MIPS assembly code in this file, ensuring it uses supported instructions.
Example program.asm:
.data
message: .asciiz "Hello, World!"
number: .word 42
.text
main:
li $v0, 4 # syscall for print string
la $a0, message # load address of message
syscall # print string
li $v0, 1 # syscall for print integer
lw $a0, number # load word from memory into $a0
syscall # print integer
li $v0, 10 # syscall to exit
syscall
-
Run the Script:
-
Simulation Mode:
- When prompted, enter
'n' for single-step execution or 'a' for automatic execution.
-
Observation:
- The script will display the assembly to machine code conversion.
- In single-step mode, it will execute each instruction one by one, displaying register states after each step.
- In automatic mode, it will execute all instructions without pausing.
-
Binary Output:
- The script writes the binary representations of the instructions to
binary_code.txt.
-
Syscall Outputs:
- Based on the syscalls in the assembly code, the script will print outputs (e.g., "Hello, World!" and "42") to the console.
-
Termination:
- The simulation ends when a syscall with
$v0 set to 10 is executed.
Conclusion
This Python script effectively serves as both an assembler and a simulator for a subset of MIPS assembly instructions. Here's a summary of its capabilities:
-
Assembler Features:
- Converts assembly instructions into binary machine code.
- Supports pseudo-instructions like
li and la.
- Handles labels and data sections.
-
Simulator Features:
- Emulates register operations and memory accesses.
- Handles arithmetic and logical operations.
- Manages control flow with branches and jumps.
- Supports system calls for printing and exiting.
-
User Interaction:
- Allows choosing between single-step and automatic execution.
- Displays register and memory states for better transparency.
Potential Enhancements:
-
Enhanced Error Handling:
- Provide more detailed error messages.
- Handle more complex syntax and edge cases.
-
Extended Instruction Set:
- Incorporate additional MIPS instructions for broader functionality.
-
Memory Visualization:
- Implement a more user-friendly memory display or GUI.
-
Performance Optimization:
- Optimize the simulation loop for faster execution with large programs.
-
Debugging Tools:
- Add breakpoints, watchpoints, and step-over/step-into features.
Overall, this script offers a solid foundation for understanding MIPS assembly execution and can be a valuable educational tool for those learning computer architecture and low-level programming.