← 블로그로 돌아가기CPU 구조

Microprocessor 동작 원리: Fetch-Decode-Execute 심층 분석

Von Neumann architecture, bus, microoperation, decoding, ALU execution, branching, memory hierarchy, pipelining까지 microprocessor를 교과서 수준으로 살펴봅니다.

DennyDenny
약 18분 소요
Chalkboard feature illustration for “Microprocessor 동작 원리: Fetch-Decode-Execute 심층 분석”

요약: Fetch, decode, execute는 instruction processor를 이해하는 유용한 개념 모델입니다. Instruction address를 선택하고, instruction을 가져와 해석하고, 연산을 수행한 뒤, 다음 architectural state를 확정합니다. 작은 교육용 CPU는 이 phase를 별도 cycle로 드러낼 수 있습니다. 현대 processor는 instruction set이 요구하는 behavior를 지키면서 작업을 overlap, 분할, cache, predict, reorder합니다.

Microprocessor는 instruction-set architecture(ISA)가 정의한 instruction을 실행합니다. Architectural level에서 각 instruction은 operation과 operand를 지정하고 register, memory, flag, control flow에 정의된 변화를 만듭니다. Fetch-decode-execute는 그 behavior를 가르치기에 강력한 모델이지만 모든 구현을 문자 그대로 상자 세 개로 설명하는 것은 아닙니다.

이 안내서는 내부가 투명한 multicycle CPU에서 시작해 pipelined superscalar 구현과 그 모델을 구분합니다. 예제 instruction format과 microoperation은 교육 목적으로 일부러 만든 것으로 x86, Arm, RISC-V 또는 특정 상용 processor에 관한 주장이 아닙니다. 더 부드러운 시각적 입문이 필요하다면 fetch-decode-execute case study부터 읽으세요.

Stored-Program 구성과 현대의 Hybrid

John von Neumann이 1945년에 쓴 First Draft of a Report on the EDVAC은 stored-program digital computer를 설명한 영향력 있는 문헌입니다. 역사적으로 더 넓은 EDVAC 팀이 참여했으므로 “von Neumann architecture”는 모든 기초 아이디어를 한 사람에게만 돌리는 말이 아니라 그 구성을 가리키는 이름입니다.

            +-----------------------------+
            |          MEMORY             |
            |  (instructions + data       |
            |   share one address space)  |
            +--------------+--------------+
                           |
                  Address / Data / Control
                           |
            +--------------+--------------+
            |             CPU             |
            |  +------------------------+ |
            |  |    Control Unit (CU)   | |
            |  +------------------------+ |
            |  |  Arithmetic-Logic Unit | |
            |  +------------------------+ |
            |  | Registers / PC / IR    | |
            |  +------------------------+ |
            +-----------------------------+
                           |
                  Input / Output devices

Stored-program의 중심 아이디어는 encoding된 instruction이 electronic memory에 있고 program control에 따라 fetch될 수 있다는 것입니다. Instruction과 일반 data가 address space와 표현 방식을 공유할 수 있으므로 datapath를 다시 배선하지 않고 program을 load하고 바꿀 수 있습니다. 그렇다고 아무 software나 실행할 수 있는 것은 아닙니다. Machine은 자신의 ISA, privilege, memory model, 제공되는 device와 호환되는 software만 실행합니다.

Von Neumann과 Harvard 비교

Harvard 구성에서는 instruction과 data access가 서로 다른 memory 또는 address space를 사용합니다. 이 분리를 통해 instruction fetch와 data access를 동시에 할 수 있지만 code를 load하거나 수정하는 명시적인 규칙도 필요합니다.

많은 processor는 hybrid입니다. Core는 architectural address space 하나를 제시하면서 내부에서는 L1 instruction cache와 data cache를 따로 사용할 수 있습니다. 반대로 일부 microcontroller는 다른 resource를 공유하면서도 program space와 data space를 별도로 노출합니다. 이 용어들은 interface와 organization을 설명할 뿐 물리 bus의 수나 microarchitecture 전체를 결정하지 않습니다.

CPU와 Memory 사이 Bus의 역할

Instruction을 추적하기 전에 세 가지 논리적 역할을 구분하면 도움이 됩니다. 작은 교육용 computer에서는 전용 wire일 수 있고, 현대 on-chip interconnect에서는 encoding된 transaction일 수 있습니다.

역할일반적 방향목적
AddressRequester → memory system위치 또는 resource 식별
Write data/read dataRequester → target / target → requester전송되는 값 운반
Control과 response양방향Read/write 의도, size, validity, readiness, error, ordering encoding

Address width, architectural pointer width, physical-address width, 실제 설치된 memory는 서로 관련되지만 같지는 않습니다. Byte-addressed 32비트 virtual address는 address space 하나에서 2322^{32} byte(4 GiB)를 지정할 수 있지만 구현은 다른 physical-address width를 사용할 수 있습니다. 마찬가지로 ISA register width만으로 external memory interface의 width나 throughput이 정해지지는 않습니다.

의도적으로 단순화한 read handshake는 다음과 같습니다.

T0:  CPU drives ADDRESS lines, asserts MEM_REQ + RD
T1:  Memory decodes address, places byte on DATA lines, asserts READY
T2:  CPU latches DATA into a register, deasserts MEM_REQ

Write는 data 방향을 반대로 하고 write indication을 함께 보냅니다. 실제 protocol은 request를 pipeline하고, response를 순서와 다르게 반환하고, transaction을 burst로 나누고, 길이가 변하는 wait state를 삽입할 수 있습니다. Processor 내부의 register file, execution unit, cache, interconnect에는 하나의 보편적인 “CPU bus”가 아니라 저마다의 port와 network가 있습니다.

Bus가 추상적으로 느껴진다면 작은 것을 직접 만들어 보세요. Address control이 있는 RAM template을 열고 controller가 address를 따라 이동할 때 address line에 무슨 일이 생기는지 관찰합니다. 이어 기본 RAM memory system과 함께 read/write timing을 살펴보세요. Memory primitive는 RAM 부품 참고 문서와 ROM 부품 참고 문서에 설명되어 있습니다.

Fetch Phase는 Microoperation마다 어떻게 동작하나요?

Fetch는 현재 program-counter 값에 대응하는 instruction byte 또는 word를 가져옵니다. 투명한 multicycle datapath는 이 작업을 register-transfer microoperation으로 표현할 수 있습니다. 예제는 word-addressed 방식이며 instruction 하나가 고정된 word 하나이므로 PC + 1이 다음 instruction을 선택합니다. 실제 ISA는 각자의 alignment와 instruction length를 정의합니다. 기본 32비트 RISC-V instruction은 일반적으로 byte address를 4만큼 전진하지만 compressed extension에는 16비트 instruction도 정의되어 있습니다.

Microoperation은 register-transfer language(RTL)로 씁니다. 단순한 CPU의 일반적인 fetch는 다음과 같습니다.

T0:  MAR <- PC                  ; copy PC to memory-address register
T1:  MDR <- MEM[MAR],  PC <- PC + 1   ; start memory read, increment PC
T2:  IR  <- MDR                 ; latch the instruction

이는 가능한 교육용 3-cycle sequence 하나일 뿐 반드시 따라야 할 CPU protocol이 아닙니다. 더 빠른 memory나 더 넓은 datapath는 단계를 합칠 수 있고, cache miss는 wait cycle을 많이 추가할 수 있으며, pipeline은 이전 instruction과 fetch를 overlap할 수 있습니다.

중요한 세부 사항은 다음과 같습니다.

  • 이 모델에 MAR가 있는 이유: Memory-address register가 요청 address를 유지하는 동안 PC는 자유롭게 전진합니다. 현대 설계에서는 programmer-visible register 하나가 아니라 request queue, cache tag, pipeline state가 같은 역할을 나타낼 수 있습니다.
  • T1 동안 PC를 증가시킬 수 있는 이유: 전용 incrementer가 memory request와 동시에 동작할 수 있습니다. 이는 instruction 하나 안에서의 datapath concurrency이며 여러 instruction 사이의 instruction-level parallelism과는 다릅니다.
  • IR이 latch되는 방식: 교육용 회로에서는 load enable이 활성화될 때 instruction register가 fetch한 word를 포착합니다. 현대 front end에는 IR 하나 대신 fetch된 byte와 decode된 operation 여러 개를 담는 buffer가 있을 수 있습니다.

Sequential instruction executor template에서 이 교육용 sequence를 볼 수 있습니다. Cycle 사이에서 pause하고 MAR 및 MDR 값을 확인하세요. Program counter 자체는 program counter와 8비트 program-counter 부품을 참고하세요.

State Machine으로서의 Fetch

개념적으로 fetch controller는 작은 finite-state machine입니다. State register가 T0, T1, T2를 encoding하고 각 state에서 combinational logic이 필요한 enable을 활성화합니다. 개별 flip-flop으로 시연할 수 있으며 합성된 하드웨어에서는 state가 다른 사용 가능한 sequential cell에 mapping될 수 있습니다. Clock 안내서는 이 state transition의 timing을 설명합니다.

Decode Phase는 Control Signal을 어떻게 만드나요?

Instruction word가 IR에 들어오면 CPU에는 의미를 가진 16비트(또는 32비트나 64비트) binary가 있습니다. Decode의 역할은 그 의미를 물리적인 control signal 집합으로 바꾸는 것입니다. Wire를 HIGH 또는 LOW로 만들어 data가 올바른 register와 ALU operation을 지나도록 route합니다.

Instruction Format

Instruction encoding은 bit field에 의미를 부여합니다. 다만 variable-length ISA는 모든 instruction에서 같은 field가 고정 위치에 있을 필요가 없습니다. 우리가 만든 fixed-width 예제는 다음과 같습니다.

| 15 14 13 12 | 11 10  9  8 |  7  6  5  4 |  3  2  1  0 |
|   OPCODE    |    REG_A    |    REG_B    |    REG_D    |
  • Opcode(4비트): 어떤 operation인지 나타냅니다. 4비트로 16개 instruction을 구분할 수 있어 ADD, SUB, AND, OR, XOR, LD, ST, JMP, BEQ, BNE, NOP, MOV, INC, DEC, NOT, HLT에 충분합니다.
  • REG_A, REG_B: Source register index입니다. 4비트 binary index이므로 24=162^4 = 16개 register를 주소로 지정할 수 있습니다.
  • REG_D: Destination register index입니다.

Immediate-mode format은 register field 하나를 immediate value에 양보합니다. 예를 들면 다음과 같습니다.

| 15 14 13 12 | 11 10  9  8 |  7  6  5  4  3  2  1  0 |
|   OPCODE    |    REG_D    |       IMMEDIATE          |

Opcode 추출

교육용 datapath에서는 opcode bit가 4-to-16 decoder로 들어가고, 각 출력이 opcode 하나에 대응합니다. 추가 logic은 register field, immediate value, mode, 현재 controller state를 해석합니다. Decoder와 encoder 및 decoder 부품을 참고하세요.

Decoder가 동작한 뒤 control unit의 나머지는 (opcode, timing_state, flag_bits)를 microoperation enable vector로 mapping하는 거대한 진리표인 combinational logic입니다.

Opcode명령 이름T2 microoperationT3 microoperationT4 microoperation
0001ADDA_BUS <- REG[REG_A]B_BUS <- REG[REG_B]REG[REG_D] <- ALU_OUT(A+B)
0010SUBA_BUS <- REG[REG_A]B_BUS <- REG[REG_B]REG[REG_D] <- ALU_OUT(A-B)
0011ANDA_BUS <- REG[REG_A]B_BUS <- REG[REG_B]REG[REG_D] <- ALU_OUT(A&B)
1010JMPPC <- IMMEDIATE--
1011BEQ(if Z=1) PC <- IMMEDIATE--

Control 구현은 다음 spectrum 위에 놓입니다.

  • Hardwired control: Combinational logic과 state가 enable을 직접 생성합니다. 작은 controller에 잘 맞고 일반 logic gate에서 합성할 수 있습니다.
  • Microprogrammed control: Control store가 datapath control을 생성하는 microinstruction sequence를 보관합니다. 복잡하거나 자주 쓰지 않는 instruction behavior를 명시하기 쉽게 만들 수 있습니다.
  • Hybrid control: Processor가 흔한 instruction에는 direct decode를 사용하고, 복잡한 case, assist, update에는 microcode 또는 sequenced control을 호출할 수 있습니다. RISC/CISC label만으로 어느 구현을 쓰는지 알 수 없습니다.

Control-unit 부품은 교육용 primitive를 제공합니다. Finite-state-machine의 기초는 counter와 state machine을 참고하세요.

Execute Phase는 실제로 어떻게 계산하나요?

Execute에서 실제 작업이 일어납니다. 지금까지 CPU는 bit를 옮기기만 했지만 이제 변환합니다.

ADD R3, R1, R2 같은 일반적인 산술 instruction에서 execute는 세 가지 일을 합니다.

  1. Register read: 예제 register file에는 REG_A와 REG_B가 주소로 지정하는 read port 두 개가 있어 두 operand가 A_BUS와 B_BUS에 동시에 도달할 수 있습니다. 교육용 version은 작은 register와 multiplexer로 조립할 수 있고, 물리 CPU는 custom 또는 합성된 multiported register 구조를 사용합니다.
  2. ALU operation: ALU가 두 operand와 opcode에서 만든 ALU function code를 받습니다. 교육용 ADD path에는 ripple-carry adder를 사용할 수 있고, 더 빠른 구조에는 carry-lookahead와 parallel-prefix 방식이 있습니다. AND/OR/XOR에서는 bitwise logic이 후보 결과를 만듭니다. ALU 동작 원리와 8비트 ALU 부품을 참고하세요.
  3. Write-back 및 선택적 flag update: Enable된 edge에서 예제는 ALU 결과를 REG_D에 저장하고 Zero(Z), Carry(C), Sign(S), Overflow(V)를 갱신합니다. Flag는 ISA마다 다릅니다. 일부 architecture는 condition-code register를 노출하고, 일부는 선택된 instruction에서만 flag를 갱신하며, 다른 architecture는 일반 register나 비교 결과를 사용합니다. CPU flag와 flags-register 부품을 참고하세요.

Fetch와 decode를 순서대로 보여 주는 같은 template에서 execute도 볼 수 있습니다. 4비트 ALU demonstration을 열어 operand가 흐르는 모습을 보고, 더 현실적인 datapath는 8비트 ALU system에서 확인하세요.

Latency가 달라지는 이유

작은 multicycle CPU에서는 단순 산술이 execute cycle 하나를 쓸 수 있지만 load는 memory를 기다립니다. 현대 processor에서는 instruction-cache miss, variable-length decoding, front-end redirect 때문에 fetch와 decode 시간도 달라질 수 있습니다. Execution latency는 operation과 operand에, memory latency는 cache 및 memory system에 달려 있습니다. 잘못 예측한 branch는 useful pipeline work를 redirect하고 refill합니다. Queue, speculation, caching, parallel execution은 ISA에서 보이는 결과를 바꾸지 않으면서 이러한 변화를 견디도록 돕습니다.

Conditional Branch는 PC의 방향을 어떻게 바꾸나요?

Branch는 control flow를 바꾸는 방법 중 하나입니다. Jump, call, return, exception, interrupt, trap도 다음 sequential program-counter 값을 바꿀 수 있습니다. Conditional branch는 ISA가 정의한 조건에 따라 fall-through address와 target 중 하나를 고릅니다.

BEQ target(같으면 branch)의 microoperation은 다음과 같습니다.

T2:  if (Z == 1) PC <- IMMEDIATE
     else        (no-op; PC already incremented during fetch)

이 custom teaching ISA에서는 target이 immediate value로 encoding되고 BEQ가 Z를 검사합니다. Control logic이 decode된 instruction, condition, controller state를 결합하여 PC source를 선택하고 load enable을 활성화합니다. 실제 ISA는 PC-relative offset을 사용하거나 register 두 개를 직접 비교하거나 delay slot과 alignment rule을 정의할 수 있습니다.

Branch불 조건Mnemonic
BEQZ=1Z = 1같으면 branch
BNEZ=0Z = 0다르면 branch
BLTS≠VS \ne V작으면 branch(부호 있음)
BGES=VS = V크거나 같으면 branch
BCSC=1C = 1Carry가 set이면 branch
BVSV=1V = 1Overflow가 set이면 branch

이 표는 설명용이지 보편 규칙은 아니지만 Boolean condition이 control decision이 되는 방식을 보여 줍니다. 드모르간 법칙은 같은 조건을 동등한 논리로 표현할 수 있고, synthesis 및 target cell library가 최종 area와 delay를 결정합니다. 부호 있는 flag 산술에서 S와 V가 나오는 방식은 2의 보수를 참고하세요.

Branch는 CPU의 예측 회로가 가치를 발휘하는 곳이기도 합니다. Modern extension 부분에서 branch prediction을 다룹니다.

Memory Hierarchy란 무엇이며 왜 단계가 많나요?

Storage 기술은 access latency, capacity, bandwidth, energy, persistence, cost 사이에서 tradeoff합니다. Processor의 size와 cycle count는 generation 및 operating frequency마다 바뀌므로 고정된 표 하나가 아니라 hierarchy를 중심으로 architecture를 이해해야 합니다.

계층일반적 역할흔한 구현중요한 구분
Architectural register즉시 쓰는 operand와 stateMultiported register file, latch, flip-flopISA가 이름을 지정함
L1 instruction/data cache가장 latency가 낮은 cached code와 dataOn-chip SRAM보통 core 하나 또는 작은 core group 전용
Mid/last-level cacheExternal memory 전에 miss 포착더 큰 on-chip SRAM 구조일부 level에서 공유되는 경우가 많음
Main memoryActive program working setDRAM휘발성, on-chip cache보다 훨씬 크고 느림
Persistent storageFile과 영구 dataNAND flash 또는 magnetic mediaCPU cache의 다음 level이 아니라 I/O와 operating system을 통해 접근

정확한 숫자보다 오래 유지되는 원칙은 세 가지입니다.

  • Locality가 caching을 효과적으로 만듭니다: Temporal locality는 최근에 접근한 block을 다시 사용하고, spatial locality는 가까운 address를 사용합니다.
  • Latency와 bandwidth는 다릅니다: 첫 요청 byte가 돌아오는 데 오래 걸리면서도 연속된 많은 byte에는 높은 transfer rate를 유지할 수 있습니다.
  • Miss는 다음 level을 드러냅니다: Hardware prefetching, 여러 outstanding miss, out-of-order execution, software layout이 비용 일부를 overlap하거나 피할 수 있지만 모든 access를 같은 속도로 만들지는 못합니다.

이 stack의 storage 쪽을 interactive하게 시작하려면 RAM과 ROM 및 multi-byte value가 memory에 놓이는 방식을 다룬 endianness를 읽으세요.

Memory-sensitive workload에서는 access pattern과 cache behavior가 성능을 지배할 수 있습니다. Compute-bound, branch-heavy, I/O-bound workload에서는 다른 bottleneck이 지배할 수 있습니다. Optimization을 고르기 전에 측정하세요.

Pipelining이란 무엇이며 어떻게 더 빠르게 만드나요?

교육용 machine은 multicycle이며 overlap하지 않습니다. Instruction 하나가 fetch, decode, execute, write-back을 모두 마친 뒤 다음 instruction을 시작합니다. 진정한 single-cycle CPU는 다릅니다. 하나의 긴 clock period 안에 architectural instruction 전체를 완료합니다. 두 방식 모두 instruction의 일부 구간에서 hardware를 충분히 사용하지 못합니다.

Pipelining은 서로 다른 instruction이 동시에 서로 다른 hardware stage를 차지하게 합니다. Pipeline register가 stage를 나눕니다. 아래의 이상적인 3-stage 예제에서 instruction 하나는 fetch부터 execute까지 여전히 3 cycle이 걸리지만 pipeline을 채운 뒤에는 cycle마다 instruction을 최대 하나 완료할 수 있습니다.

Cycle:        1     2     3     4     5     6
Fetch:       I1    I2    I3    I4    I5    I6
Decode:            I1    I2    I3    I4    I5
Execute:                 I1    I2    I3    I4

독립적인 instruction이 길게 이어지고 stage가 완벽히 균형 잡혀 있다면 이상적인 throughput은 overlap하지 않은 예제의 약 세 배에 가까워집니다. Register overhead, stall, 고르지 않은 stage delay가 이득을 줄입니다. 많은 stall을 설명하는 hazard는 세 종류입니다.

  • Structural hazard: Stage 두 개가 같은 hardware를 원합니다. Hardware를 복제해 해결합니다(예: PC increment와 ALU 작업에 별도 adder 사용).
  • Data hazard: Instruction i+1i+1이 아직 pipeline 안에 있는 instruction ii의 결과를 필요로 합니다. Forwarding(ALU output을 다음 ALU operation의 입력으로 route) 또는 stall로 해결합니다.
  • Control hazard: Branch가 execute에서 다음 PC를 결정했지만 fetch는 이미 잘못된 instruction 두 개를 가져왔습니다. Branch prediction으로 해결하고 잘못 예측하면 pipeline을 flush합니다.

Pipeline boundary를 추가하면 stage당 combinational work를 줄이고 period를 짧게 만들 수 있지만, 각 boundary는 clock-to-Q, setup, clocking, power, control overhead를 더합니다. Pipeline이 깊어질수록 일부 redirect 뒤에 버리는 작업도 늘어납니다. 보편적으로 가장 좋은 depth는 없으며 workload와 구현에 따라 달라집니다. 이 tradeoff 뒤의 물리 timing은 전파 지연과 setup, hold, metastability를 참고하세요.

RISC와 CISC: Decode의 두 흐름

RISC와 CISC는 ISA 설계의 역사적 경향을 설명하며 서로 다른 두 구현 법칙이 아닙니다. Mnemonic 수만으로 processor를 정확히 분류할 수 없고 어느 label도 CPI나 성능을 예측하지 않습니다.

경향RISC 지향 예CISC 지향 예
Encoding적은 수의 규칙적인 format, fixed-width base encoding이 흔함더 다양한 format과 operand encoding
Memory operandLoad/store 구성이 흔함일부 산술 instruction이 memory에 직접 접근 가능
Architectural stateGeneral-purpose register가 많은 경우가 흔함더 전문화되거나 implicit한 operand를 포함할 수 있음
구현Speculation, micro-op, microcode를 사용할 수 있음흔한 operation을 짧은 internal operation으로 pipeline할 수 있음

경계는 열려 있습니다. RISC-V에는 규칙적인 32비트 base encoding과 선택적 16비트 compressed encoding이 있습니다. Arm에는 여러 instruction encoding과 풍부한 extension이 있습니다. x86은 variable-length architectural instruction을 사용하지만 많은 구현이 흔한 instruction을 internal operation으로 decode합니다. Label은 code density, decode work, compatibility, compiler targeting 같은 ISA tradeoff를 논의하는 데 사용하고 “단순 hardware”와 “복잡한 hardware”를 대신하는 말로 쓰지 마세요.

기본 Pipeline 위에는 어떤 현대적 Extension이 있나요?

Single-issue in-order 5-stage pipeline은 학부 과정의 전형적인 CPU입니다. 실제 chip은 훨씬 더 공격적입니다. 각각 별도 글이 필요할 만큼 큰 주제이므로 자세히 유도하지는 않지만 layer를 살펴보겠습니다.

Out-of-Order Execution

Instruction i+1i+1이 결과를 기다리지만 i+2i+2가 독립적이라면 out-of-order core는 독립된 작업을 먼저 schedule할 수 있습니다. 흔한 구현은 renamed register, issue queue 또는 reservation station, in-order retirement 구조를 사용해 exception과 architectural state를 precise하게 유지합니다. 정확한 구조는 microarchitecture마다 다릅니다.

Superscalar Issue

Superscalar CPU는 dependency와 resource가 허용할 때 cycle마다 operation을 둘 이상 issue하거나 execute할 수 있습니다. Front-end width, execution port, data dependency, cache miss, branch behavior, retirement width가 각각 bottleneck이 될 수 있습니다. 광고된 width가 application throughput을 보장하지는 않습니다.

Branch Prediction

Branch predictor는 branch가 execute되기 전에 direction과 target을 추정하여 speculative fetch가 계속되게 합니다. Accuracy는 code와 predictor design에 따라 크게 달라집니다. 올바른 prediction은 control redirect를 피하고, 잘못된 prediction은 더 젊은 dependent work를 버리고 확인된 path에서 다시 시작합니다. Penalty가 반드시 전체 pipeline depth와 같지는 않습니다.

SIMD와 Vector Extension

Single-Instruction Multiple-Data(SIMD)는 architectural instruction 하나로 packed lane 여러 개를 연산합니다. 예를 들어 512비트 vector에는 32비트 element 16개를 담을 수 있지만 지원 operation과 실제 throughput은 ISA와 구현에 따라 달라집니다. SIMD는 규칙적인 data parallelism이 있는 workload에 유리하며 branching, data layout, memory bandwidth, tail handling이 이득을 제한할 수 있습니다.

SMT(Hyperthreading)

Simultaneous multithreading은 여러 hardware thread의 instruction이 core의 front end와 execution resource를 공유하게 합니다. 한 thread가 쓰지 않는 slot을 채울 수 있지만 thread끼리 cache, queue, bandwidth, execution unit을 두고 경쟁하기도 합니다. Resource 요구가 서로 보완되는지 충돌하는지에 따라 이득이 달라집니다.

Speculation

Processor는 예측한 branch와 아직 해결되지 않은 memory dependency를 지나 추측 실행할 수 있습니다. 안전하게 retire할 수 있을 때까지 결과가 architectural state가 되지 못하도록 막지만 microarchitectural effect는 남을 수 있습니다. Spectre 계열 공격은 그 effect가 side channel을 만들 수 있음을 보였고, Meltdown은 privilege check를 충분히 일찍 강제하지 못한 관련 transient-execution failure를 악용했습니다. 두 계열을 하나의 mechanism으로 단순화해서는 안 됩니다.

이 모든 것을 실제로, 작은 규모라도 어떻게 만들까요?

Block diagram과 production processor 사이에는 넓고 가치 있는 공간이 있습니다. 작은 simulated CPU는 instruction sequencing, control, datapath decision을 보이게 만듭니다. 규모를 키우면 optimization 외에도 physical timing, verification, memory ordering, privilege, exception, I/O가 더해지지만 교육용 model은 여전히 유용한 토대입니다.

합리적인 starter project 순서는 다음과 같습니다.

  1. 4비트 ALU를 만듭니다. Adder, logic gate, operation을 선택할 multiplexer를 결합합니다. ALU 동작 원리를 따라가고 4비트 ALU demonstration template을 사용해 보세요.
  2. Register file을 만듭니다. 4비트 register 네 개에 read용 multiplexer와 write용 decoder를 연결합니다.
  3. Memory를 만듭니다. 작은 address control RAM이면 충분합니다.
  4. Program counter를 만듭니다. Address bus에 맞는 크기로 load enable이 있는 counter를 사용합니다. 8비트 program-counter 부품을 참고하세요.
  5. Control unit을 만듭니다. 작은 ISA에서는 (opcode, timing_state, flags)에서 enable을 유도하고 각 state transition을 문서화합니다.
  6. System을 배선하고 검증합니다. Sequential instruction executor template은 simulated cycle을 하나씩 진행할 수 있는 교육용 datapath입니다.

한 단계씩 만드는 서사는 companion 글인 시뮬레이터에서 CPU를 처음부터 만들기에서 wiring decision까지 자세히 설명합니다.

전체 Cycle 연결하기

Custom teaching CPU에서 ADD R3, R1, R2를 실행해 봅시다. R1 = 5, R2 = 7이고 instruction은 word address 0x10에 있다고 가정합니다. Trace에는 의도한 microoperation이 있어 datapath를 cycle마다 audit할 수 있습니다.

Initial state: PC = 0x10,  R1 = 0x05,  R2 = 0x07,  R3 = 0x00,  Z=C=S=V=0
Memory at 0x10: 0001 0001 0010 0011   (opcode, source A, source B, destination)

CYCLE 1 (T0, fetch):
  MAR <- PC                            ; MAR = 0x10
  ADDRESS_BUS <- MAR
  RD <- 1, MEM_REQ <- 1

CYCLE 2 (T1, fetch):
  MDR <- DATA_BUS                      ; MDR = 0x1123
  PC  <- PC + 1                        ; PC  = 0x11

CYCLE 3 (T2, fetch + start decode):
  IR  <- MDR                           ; IR  = 0x1123
  RD <- 0, MEM_REQ <- 0
  (control unit decodes IR[15:12] = 0001 = ADD)

CYCLE 4 (T3, execute step 1):
  A_BUS <- REG[IR[11:8]]               ; A_BUS = R1 = 0x05
  B_BUS <- REG[IR[7:4]]                ; B_BUS = R2 = 0x07

CYCLE 5 (T4, execute step 2):
  ALU_OUT <- A_BUS + B_BUS             ; ALU_OUT = 0x0C
  Z <- (ALU_OUT == 0)                  ; Z = 0
  C <- carry_out                       ; C = 0
  S <- ALU_OUT[MSB]                    ; S = 0
  V <- overflow                        ; V = 0

CYCLE 6 (T5, write-back):
  REG[IR[3:0]] <- ALU_OUT              ; R3 = 0x0C

(go to CYCLE 1 for the next instruction)

이 custom controller에서는 instruction 하나를 완료하는 데 6 cycle이 걸립니다. Pipelined version은 hazard를 검출하고 처리한다는 조건 아래 ADD가 retire되기 전 younger instruction을 시작할 수 있습니다. 현대 out-of-order core는 architectural instruction 하나를 여러 internal operation으로 표현할 수 있으므로 이 trace는 architectural intent와 가능한 구현 하나를 설명할 뿐 다른 processor의 정확한 내부 cycle을 뜻하지 않습니다.

Sequential instruction executor template에서 simulated bus value와 trace를 비교하세요. 일치하면 이 model과 test case가 검증되는 것이지 x86, Arm, RISC-V 구현이 검증되는 것은 아닙니다. Case study에는 안내식 walkthrough가 있습니다.

Microprocessor 이야기의 다음 단계

이제 교과서 수준의 기반을 갖추었습니다. 그 너머에는 각각 글 하나로도 부족할 주제가 있습니다.

  • Cache — set-associative mapping, replacement policy, write-through와 write-back
  • Virtual memory — page table, TLB, translation, protection
  • Exception과 interrupt — control unit의 비동기 영역
  • Multi-core coherence — MESI, snooping, ring bus, mesh interconnect
  • Power와 clocking — voltage-frequency scaling, clock gating, clock skew
  • Security와 side channel — speculation의 비용

학습 목적으로 자신의 CPU를 설계한다면 CPU를 처음부터 만들기가 자연스러운 다음 글입니다. Instruction stream에서 data가 사는 곳까지 더 따라가고 싶다면 RAM과 ROM 및 endianness가 다음 두 렌즈입니다.

Fetch-decode-execute는 software에 보이는 instruction과 hardware state change를 잇는 간결한 다리입니다. Sequential instruction executor template을 열고 각 transfer를 진행하기 전에 예측한 뒤 trace와 비교하세요. 모든 state change에 명시적인 원인이 있을 때 연습은 성공한 것입니다.


다음으로 직접 만들기: DigiSim에서 sequential instruction executor template을 열어 첫 instruction을 단계별로 실행하세요. 이어 시뮬레이터에서 CPU를 처음부터 만들기를 읽고 처음부터 직접 배선해 보세요.

주요 및 기술 참고 자료

아이디어를 실제로 작동하는 회로로 만들어 보세요.