Executing code
Code execution follows a basic pattern. However, the exact implementation
may vary based on the CPU design.
Instruction cycle
While running.
Fetch step
Using the MAR, MDR, and PC, fetch instruction from memory and
increment Program counter.
Decode instruction.
Determines which circuits to use.
Determines if additional information (operands) need to to fully
use the instruction.
Fetch needed operands.
Adjust program counter.
Determine effective address (where data is).
Operands may be
Actual data to use. - no additional action in fetch/decode.
Address in memory where data resides or will be put.
(direct memory operation) - no additional action in fetch/decode.
Address in memory that contains an address of the data.
(indirect memory operation) - requires additional access to memory.
However program counter not modified.
Execute step.
Perform the requested action.
Most likely involving the ALU.
But could be changing the PC to jump to different block of code.
Branch, Jump, Call
May be as simple as loading data into a CPU register.
Or setting or clearing a CPU status flag.
Done
Version targeting one of the early 1980s 8 bit data bus CPUs.
Initialize Program Counter (PC) to start address of program in memory.
While running program
Do
Fetch instruction opcode from memory
Increment PC
Decode instruction opcode to determine task and if any additional operands
required.
Fetch operands, adjusting PC as needed.
If operand is pointer, additional memory fetches may be performed.
These normally do not affect the PC.
But they do tie up the address and data buses. (bottleneck)
Execute instruction.
Perform requested task.
Generally leaves results in ALU or pre-defined CPU work register.
But could be a write back to memory.
Done
RISC architectures usually fetch whole instruction (opcode and operand) in
single fetch. RISC also attempts to complete instruction in one clock cycle.
While running
Fetch instruction
Increment PC
Decode instruction
Execute instruction
Writeback result if required.
Done
CPUs vary as to how handling of completed calculations, called write-back,
is implemented.
Some CPU designs allow this as a third operand. Common in RISC CPUs
Add R2,R3,R1 ; add contents of R1 and R3 and store in R2
# although part of the instuction,
# the writeback to R2 treated as separate stage of instruction.
Others implement this as a separate instruction.
ADC $2043 ; Adds contents of memory $2043 to accumulator
STA $2043 ; Write current accumulator to $2043
Newer CPUs, with wider buses, may fetch multiple instructions, implement
pipelining and may even attempt parallel execution of instructions.
A simplified generic version of the fetch-execute (good test question) :
While running
Fetch opcode
Increment program counter (PC)
Decode opcode
While operands needed
Fetch operand
Increment PC
Endwhile
Execute instruction
Endwhile
|
Example