# Instruction Cycle
<[LINK](https://en.wikipedia.org/wiki/Instruction_cycle)>
## 簡述
CPU 執行指令會依序經過三種主要階段,獲取 (fetch)、解碼 (decode)、與執行 (execute)。因此,instrcution cycle 又被稱為 fetch-decode-execute cycle 或 fetch-execute cycle。從電腦開機 (boot-up) 到關閉的期間,CPU 遵守由三種階段構成的循環週期。
現代複雜處理器並不會等待整個週期完成後再執行下一條指令,通常會使用 CPU pipeline 加速指令執行。
## Role of components
其中一個特殊的 register ,稱作 PC (program counter),在讀取指令時會經常用到。PC 會保存下一個要執行的 指令的記憶體位置。
在 fetch 階段,PC 所儲存的地址會被複製到 MDR (memory address register),之後 PC 中的地址會被增加,指向下個要被執行的指令。接著 CPU 透過在 MAR 中的位置,從記憶體複製指令到 MDR (memory data register)。MDR 具有兩中功能,其一是上述提及,用來儲存由記憶體取得的資料,其二是存放要被寫回記憶體的資料。
decode 階段,CU (control unit) 會對 CIR (current instruction register) 中的指令進行解碼,抽象一點就是解讀指令代表的意義,之後 CU 會將解讀出的訊號、資料傳給在 CPU 內的各個元件如 ALU (alrithmatic logic unit), FPU (floating point unit)。
:::info
現代的 CPU 裡封裝了各個元件,主要有 CU, ALU, MUX, PC, ROM, cache...
:::
不同的 CPU 對應各自的指令集架構,自然會有不同的 instruction cycle,不過都會類似於以下的指令週期
### fetch-decode-execute cycle graph
```graphviz
digraph {
node[shape=box]
start->a0
subgraph cluster_0 {
label="fetch stage"
color="green"
a0[label="address in PC cpoied to MAR"]
b0[label="PC imcremented to \"point\" to\n the next insteuction"]
c0[label="instruction found at address\n described by MAR copied\n to the MDR"]
d0[label="instruction in MDR copied\n to the CIR"]
a0->b0
b0->c0
c0->d0
}
subgraph cluster_1 {
label="decode stage"
color="blue"
a1[label="CU decodes the contents\n of the CIR"]
}
d0->a1
subgraph cluster_2 {
label="excute stage"
color="red"
a2[label="CU sends signals to relevant\n components (e.g. ALU)"]
}
a1->a2
a2->end
}
```
此外,大多數 CPU 都會發生中斷 (interrupt)。這將導致 CPU 跳轉到 interrupt service routine,執行該 routine 後返回。在某些情况下,指令會在中途被中斷,指令不會產生任何影響,但會在中斷返回後重新執行。
## Initiation
當系統開機時,指令週期會立即開始。PC 的初始值會根據不同系統的架構來定義。舉例來說,intel IA-32 CPU 預先將 PC 的值設為 `0xfffffff0`。通常,該地址指向 ROM 中的一組指令,從而開始進行載入或啟動 (loading or booting)操作系统。