L06_Instruction Sets MIPS

Srevil·2022년 9월 28일
0

차례


  • Overview
  • Registers and Memory
  • **Review : Unsigned & Signed Binary Numbers
  • MIPS Instructions

Overview

Top 4 Reasons to Study MIPS

  1. Ideas presented using MIPS generalize to other architectures(even IA-32)
    = MIPS를 사용하여 제시된 아이디어는 IA-32를 포함한 다른 Architecture에 적용 가능
  2. It's relatively simple and easy to implement(compared to other architectures)
    = 다른 Architecture에 비해 상대적으로 간단하고 구현이 쉽다
  3. Learning its architecture and implementation exposes you to important concepts
    = Architecture 및 구현을 학습하면 중요한 개념을 알 수 있다.
  4. It's used in many applications
    = 많은 응용프로그램에서 사용된다.

MIPS Architecture - Applications

Workstations/Servers

  • SGI Workstations
  • SGI Servers

Embedded Applications - Examples

  • Network Routers
  • Laser Printers
  • Digital Cameras
  • Media Players
  • Game Consoles: Sony PS 2 / PSP
  • PDAs / Tablet Computers
  • Sony AIBO & QRIO Robots

MIPS Design Principles

MIPS 설계 원리

  • Simplicity Favors Regularity
    = 규칙성 유지 ( 명령어 사이의 유사성 ) / 간단하게 하기 위해서는 규칙적인게 좋음
  • Smaller is Faster
    = 더 작게, 더 적은 수의 소자 / 적을수록 빠름 ( 32개의 Base Register -> 5bit 필요 )
  • Good Design Makes Good Compromises
    = 경우에 따라서는 부분적으로 원칙을 깨는 디자인이 좋다 / 좋은 설계에는 적당한 절충 필요
  • Make the Common Case Fast
    = 사용 빈도가 높은 것을 최적화

Register and Memory

MIPS Registers and Memory

  • 32개의 범용 레지스터하며, 하나의 레지스터는 32bits
  • 메모리는 최대 4GB
  • word : 컴퓨터에서 자연스러운 접근 단위. 보통 32bits. MIPS 에서 Register 크기에 해당
  • Program Counter( PC ) : 실행중인 명령어의 메모리 주소값을 담고 있는 특별 레지스터
    • 32개의 범용 레지스터랑 별개의 레지스터로, 모든 CPU는 special Register를 가진다.
    • PC 는 컴퓨터가 켜지면 특정값으로 초기화 된다.
    • 프로그램이 실행됨에 따라 PC값 변경

MIPS Registers

Fast access to program data

Register R0/0/0/zero

  • R0/0/0/zero = hardwired to constant zero
    = 위 세 Register 는 오직 0만 저장할 수 있다.

Register names

  • $0-$31 or R0-R31 ( 32개 )
  • Specialized names based on usage convention
    = 사용 규약에 따른 전문화된 이름
  • $zero ($0) : always zero
    • s0s0-s7 ($16-$23) : "saved" registers
    • t0t0-t7 ($8-$15) : "temporary" registers
    • $sp : stack pointer
    • Other special-purpose registers

ver.Eng

ver.Kor


More about MIPS Memory Oranization

  • Two views of memory

    • 2322^{32} bytes with addresses 0,1,2,...,23212^{32}-1
      주소가 0,1,2,3,..., 23212^{32}-1로 구성된 2322^{32} bytes
      2322^{32} byte = 4GB
    • 2302^{30} 4-byte words* with addresses 0,4,8,...,23242^{32}-4
      주소가 0,4,8,..., 2322^{32}-4 인 4bytes word 2322^{32}

      즉, 8bits(1byte) 로 주소를 표기하면 2322^{32}
      32bits(4byte=words) 로 주소를 표기하면 2302^{30} 개다

  • Both views use byte addresses
    위에서 본 두가지 방식 모두 byte로 주소를 메기는 방식을 사용한다

  • Word address must be multiple of 4 (aligned)
    word 주소는 4의 배수로 정렬된 형태여야 한다
    -> Not all architectures require this
    모든 Architecture 가 위와 같은 word 주소 방식을 사용하지는 않는다


Review: Unsigned & Signed Binary Numbers

Review: Unsigned Binary Integers

부호 없는 이진 정수

  • Given an n-bit number
    x=xn12n1+xn22n2+...+x121+x020x=x_{n-1}*2^{n-1}+x_{n-2}*2^{n-2}+...+x_{1}*2^{1}+x_{0}*2^{0}
  • Range: 0 to 2n12^{n}-1
  • Example

    2진수와 10진수 상호 변환 방법

Range of Unsinged Binary Integers

부호 없는 이진 정수 범위

Review: Unsigned vs. Signed Integers

  • Basic binary - allows representation of non-negative numbers only in
    C, JAVA, etc: unsigned int x;

    • Useful for unsigned quantities like addresses

      C, JAVA 등에서 unsigned int x 를 통해서만 음수가 아닌 수를 나타낼 수 있다.
      또한, 이런 부호가 없는 값들은 주소와 같이 서명되지 않은 수량에 유용하다.

  • Most of us need negative numbers, too!
    In C, JAVA, etc: int x;

    • How can we do this? -> Use a signed representation

      음수도 필요한데, 우리는 부호가 있는 표현을 사용함으로써 해결한다.

Signed Number Representations

  • 4 methods to represent a number
    수를 표현하는 4가지 방법
    • Sign/Magnitude (부호 절대값)
    • Two's Complement - the one almost everyone uses
    • One's Complement
    • Biased - used for exponent in Floating Point

Sign/Magnitude Representation

  • Approach: Use binary number and added sign bit
    접근 방식: 이진수 및 추가된 부호 비트 사용
  • Problems:
    • Two values of zero(+0 0000 $ -0 1000)
    • Difficult to implement in hardware - consider addition
      HW에서 구현하기 어려움
      • Must first check signs of operands
        피연산자의 부호를 먼저 확인해야함
      • Then compute value
        그런 다음 값을 계산
      • Then compute sign of result
        그런 다음 결과의 부호를 계산

Two's Complement Signed Integers

  • Goal: make the hardware easy to design
  • Approach: explicitly represent result of "borrow" in subtract
    접근 방식: 뺄셈할 때 "빌려온 값"을 명시적으로 표기한다.
    • Borrow results in "leading 1's"
    • Weight leftmost "sign bit" with 2n1-2^{n-1}
    • All negative numbers have a "1" in the sign bit
    • Single representation of zero ( do not worry about +0 and -0 )
    • Range: 2n1-2^{n-1} to +2n11+2^{n-1}-1

      2진수 음수 표현법

Sign Extension of TC Integers

TC = Two's Complement, TC 정수의 부호 확장

  • To convert a "narrower" number to a "wider" one:
    • Copy the bits of the narrower number into the lower bits
      • Copy the sign bit from the narrower number into all of the remaining bits of the remaining bits of the result
  • Example: Converting 8-bit byte to 320bit word:

    부호확장 : 레지스터 길이에 맞추어 그 값을 정확하게 표현하기 위해서 하는 것.

  • Signed : 레지스터의 남는 곳을 채우기 위해 부호를 반복하여 복사
  • Unsigned : 왼쪽 빈 부분을 0으로 채움

Biased

숫자에 일정한값(bias)를 더하여 항상 양수로 표현하는 방식


MIPS Instructions

MIPS Instructions

  • All instructions exactly 32 bits wide
    모든 명령어가 32bits 크기로 구성
  • Different formats for different purposes
    목적에 따라 다른 포맷 형태가 있다
  • Similarities in formats ease implementation
    형식이 유사하여 구현이 용이하다

    각 Format에 대해서는 아래에서 다룸

MIPS Instruction Types

  • Arithmetic & Logical - manipulate data in registers
    산술 & 논리 - 레지스터의 데이터 조작

    R-Format 사용

  • Data Transfer - move register data to/from memory
    데이터 이동 - register -> memory | memory -> register

    I-Format 사용

  • Branch - alter program flow(jump)
    분기 - 프로그램 흐름 변경

    J-Format 사용

    위 본문 내용 추가 설명
    PC = Programcounter : 실행중인 명령어의 주소값을 담고 있음
    Branch, 즉, 분기 명령어를 만나면 특정 위치로 위치를 옮기는 것이다.
    이는 PC 값이 변경됨을 의미한다.
    그런 특정 위치를 나타내는 값은 주소값이기 때문에 4의 배수.
    4의 배수는 이진수로 나타냈을 때 마지막 2비트는 항상 00이다.
    이에 공간절약을 위해 offset 값을 4로 나눈 후에 표현한다.
    아래는 PC = PC + 4 + 4*25 에 관한 내용이다.
    $s1 == $s2 라면 PC 값을 변경해준다.
    PC 값을 변경하고자 하는 순간 이미 PC 값은 +4가 된다.(현재 실행중인 명령어가 바뀌므로)
    그리고 branch 할 값은 앞서 나눠준 4를 곱하는 것이다.

MIPS Arithmetic & Logical Instructions

MIPS 산술 & 논리 명령

  • Instruction usage (assembly)
    명령어 사용법(어셈블리)
  • Instruction characteristics
    명령어 특징
    • Always 3 operands : destination + 2 sources
      항상 3개의 피연산자 사용 : 목적지 + 피연산자 2개
    • Operand order is fixed
      순서 고정
    • Operands are always general purpose registers
      항상 범용 Register에 적용
  • Design Principles:
    설계 원칙
    • Design Principle 1: Simplicity favors regularity
      간단하게 하기 위해서는 규칙적인 것이 좋다
    • Design Principle 2: Smaller is faster
      작은 것이 더 빠르다

Arithmetic Instruction Examples


Compiler 는 변수를 Register에 매핑하는 것을 추적( 필요한 경우 메모리에 스필 )
Spil = 자주 사용되지 않는 변수들을 메모리에 저장하고, 자주 사용되는건 Reg에 저장

Assembly Programming

  • .text
    • 실제 코드를 작성하는데 사용되는 section
    • .global __start 선언과 함께 시작 되어야 함.
    • .global __start 는 커널에게 프로그램이 어디에서부터 실행 시작하는지 알려줌
  • .data
    • 초기화된 데이터나 상수를 선언하는데 사용
    • 선언된 데이터들은 프로그램 실행 중 변경되지 않음
    • 상수, 파일이름, 버퍼 사이즈 등을 선언할 수 있음
  • .bss
    • 초기화 되지 않는 변수를 선언하는데 사용

Arithmetic & Logical Instructions - Binary Representation

산술 & 논리 명령 - 이진 표현

  • 형태

About R-Format

  • Used for arithmetic, logical, shift instruction
    산술, 논리, 시프트 명령에 사용

    • op : Basic operation of the instruction (opcode)
      op : 명령어가 실행할 연산의 종류. 연산자(opcode)라고 부름
    • rs : first register source operand
      rs : 첫 번째 sorce 피연산자 레지스터
    • rt : second register source operand
      rt : 두 번째 source 피연산자 레지스터
    • rd : register destination operand
      rd : 목적지 레지스터. 연산 결과가 기억됨
    • shmat : shift amount ( 00000 for now - more about this later )
      shmat : 자리이동량(shift 량)
    • funct : function - specific type of operation
      funct : 기능. op 필드에서 연산의 종류를 표시 -> funct 필드에서 한 연산을 구체적으로 지정
  • Also called "R-Format" or "R-Type" Instructions

  • Example

MIPS Data Transfer Instructions

  • Transfer data between registers and memory
    레지스터와 메모리 간 데이터 전송
  • Instruction format(assembly)
  • Uses:
    • Accessing a variable in main memory
      main memory 에 변수 access
    • Accessing an array element in main memory
      main memory 에 배열 요소 access
  • Notes about offset:
    • offset must be a constant
    • offset is signed(positive or negative)

Example - Loading a Simple Variable

단일 변수 load

추가 정보 from Book

  • MIPS의 산술 연산은 레지스터에서만 실행
  • 메모리와 레지스터 간에 데이터를 주고받는 명령어가 필요(Data Transfer Instructions)
  • (메모리에 기억된 데이터) 워드에 접근하려면 메모리 주소를 지정해야함.
  • 메모리 = 주소가 인덱스 역할을 하는 1차원 배열. 주소는 0 부터 시작
  • 메모리 주소 = lw 명령어의 상수 부분(offset)과 레지스터 값의 합(()안의 내용)
  • 배열이나 구조체 같은 자료구조는 메모리에 보관


lw R5, 8(R2) 명령을 실행하는 과정이다.
1. Register는 R0~R31 까지 총 32개로 이루어져 있다.
2. Memory는 word 단위로 구성 => 메모리 주소가 4byte씩 증가
3. lw 는 Memory -> Register
4. lw R5, 8(R2) -> R2 0x10 이라는 주소를 가지고 있다.
5. 그렇다면, 8(R2)는 0x10 + 8 이다.
6. 즉, R5에 저장할 값은 메모리 주소 0X18에 있는 값

Example - Array Variable

배열 예시

a[3] = z를 Assembly로 작성하는 과정이다.
1. R2에 0x08이라는 메모리 주소가 저장
2. 그림에서 보다시피 배열의 경우 a[0]에서부터 순서대로 4byte 씩 증가한 주소에 메모리를 차지
3. R5에 z 값이 저장되어 있고, 이 값이 105라고 가정하자
4. 그럼 a[3]에 105를 저장해줘야 한다.
5. 앞서 말한 것 처럼 배열은 memory에 저장.
6. R5는 레지스터 값이니 sw 명령을 이용하여 메모리에 값을 저장해줘야 함.
7. sw R5, 12(R2) -> 12는 4 * 3

  • 4는 워드크기를 의미하며, 3은 인덱스를 의미한다.
  • 이 예시에서 12를 offset, R2를 base register라고 한다.
  • offset : 상수부분
  • base register : 주소 계산을 위해 더해지는 레지스터
  1. 0x08 + 12(0xc) = 0x14 => R5 값을 메모리 주소 0x14(a[3])에 저장

Data Transfer Instructions - Binary Representation

  • 형태

About I-Format

  • Used for memory access - load, store instructions

    • op : Basic operation of the instruction(opcode)
    • rs : first register source operand (=Address)
    • rt : second register source operand(source for sw / destination for lw)
    • offset : 16-bit signed address offset
  • Also called "I-Format" or "I-Type" Instructions

  • Example

MIPS Conditional Branch Instructions

MIPS 조건부 분기 명령어

  • Conditional branches allow decision making
    조건부 분기로 의사 결정 가능

  • Example

Binary Representation - Branch

  • 형태

  • Branch Instructions use I-Format

  • offset is added to PC when branch is taken
    분기 명령 조건을 만족할 때, PC에 offset 값을 추가

Branch Example


위 사진에서 보다시피, beq 실행해서 조건을 만족하여 L1으로 옮기면,
PC 값에 +4가 아닌 +8이 된다.

Comparisons - What about <,<=,>,>= ?

비교문에 관해

  • bne, beq test equality of two numbers
    bne, beq 명령은 두 수가 똑같은지 확인한다

  • slt, slti compare magnitude of signed numbers
    부호를 지칭하는 수를 비교한다

    • slt : set less than
    • slti : set less than immediate
    • 위 두 명령은 부호가 있는 정수 비교에 사용
  • Combine with bne or beq to branch:
    bne 또는 beq 명령과 같이 사용

  • Why not include a blt instruction in hardware?
    blt명령을 왜 HW에 포함시키지 않는가?

    • blt 명령은 pseudo instruction이다. bne or beq + slt
    • pseudo instruction = 구현되어 있지 않은 명령어
    • Supporting in hardware would lower performance
      Hardware에서 지원하면 성능이 떨어진다
    • Assembler provides this function if desired(by generating the two instructions)
      Assembler가 원하는 경우 두 가지 명령을 사용하여 구현 가능한 기능

Signed vs. Unsigned Comparisons

  • slt, slti compare signed numbers
  • sltu, sltui compare unsigned numbers

Binary Representation - Jump

  • 형태

  • Jump Instruction uses J-Format(op=2)

  • What happens during execution?

    상위 4비트의 PC를 연결하여 완전한 32비트 주소를 형성.
    << 2 를 사용하여 word offset으로 변경
    사진 설명
    점프 후 PC = 현재 PC 상위 4비트 + Jump 후 PC의 하위 26비트(<<2)

Jump Example

J-Format 형태를 보면 address 가 26bits.
배운 내용을 바탕으로하면 명령어의 길이는 32bits.
그렇다면, 이 26bits를 어떻게 32bits로 만들 것인가?
우선, 모든 명령어는 00으로 끝난다. 그렇기에 address에 00을 붙임으로서 28bit
나머지 4bit는 PC의 상위 4bit(MSB)를 가져온다.
정보 출처

Constants / Immediate Instructions

  • Small constants are used quite frequently
    작은 상수는 자주 사용

    e.g. A = A + 5;
    B = B + 1;
    C = C - 18;

      
  • MIPS Immediate Instructions ( I-Format )
  • Allows up to 16-bit constants
    최대 16비트 상수 허용

Why are Immediates only 16 bits?

  • Because 16 bits fits neatly in a 32-bit instruction
    16bit 가 32bit 명령어에 깔끔하게 들어 맞기 때문
  • Because most constants are small(i.e. < 16 bits)
    `대부분의 상수가 작기 때문(예: 16비트 미만)
  • Design Principle 4 : Make the Common Case Fast

MIPS Logical Instructions

Logical Operations - Applications

Larger Constants

  • Immediate operations provide for 16-bit constants
    Immediate operation 은 16bit 상수를 제공
  • What about when we need larger constants?
  • Use "load upper immediate -lui"(I-Format)

    추가 정보

MIPS Shift Instructions

  • MIPS Logical Shift Instructions
    • Shitf left : sll (shift-left logical) instruction
    • Rigth shitf : srl (shift-right logical) instruction

Shitf Instruction Encodings

profile
UOU_Unknown

0개의 댓글