資工系必修 共筆
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    ###### tags: `計算機組織_戴碧如` ## Chapter 2 - Instructions: Language of the Computer [TOC] #### Instruction Set - 比較通用的是 Simplified implementation - 設計一套最簡單的指令,需要複雜的動作時,用這些簡單的指令組合而成 #### Arithmetic Operations - Two sources and one destination > add a, b, c => a = b + c (a gets b + c) :::success Design Principle 1: Simplicity favors regularity ::: #### Register Operands - MIPS has a 32 x 32-bit register file - 32-bit data called a "word" - Assembler names - $t0, $t1, ...,$t9 for temporary values (專門拿來暫存的) - $s0, Ss1, ...,$s7 for saved variables (專門拿來存要長期持有的變數) :::success Design Principle 2: Smaller is faster ::: #### Memory Operands - To apply arithmetic operations - **Load** values from memory into registers - **Stor** result from register to memory - Memory is **bytes addressed** - Words are aligned in memory (每個 word 的第一個 byte 一定是 4 的倍數) - MIPS is Big Endian - Most-significant byte at least address of a word ![](https://i.imgur.com/zxriL39.png =50%x) #### Example1 - C code: ``` g = h + A[8]; ``` - MIPS code: ``` lw $t0, 32($s3) add $s1, $s2, $t0 ``` #### Example2 - C code: ``` A[12] = h + A[8]; ``` - MIPS code: ``` lw $t0, 32($s3) add $t0, $s2, $t0 sw $t0, 48($s3) ``` #### immediate Operands - Constant data specified in an instruction ``` addi $s3, $s3, 4 ``` - No subtract immediate instruction 可以加上 負數 :::success Design Principle 3: Make the common case fast ::: #### The Constant Zero - MIPS register 0 ($zero) is the constant 0 - cannot be ovwewritten - 用於 copy, a = b `add $t2, $s1, $zero` => `$t2` = `$s1` #### MIPS Instruction Encoding 有兩種表示法 R-Type, I-Type - **R-format**:通常用於算術和邏輯操作 ![](https://i.imgur.com/1kxuhqY.png) - op: operation code (opcode) - rs: first source register number - rt: second source register number - rd: destination register number - shamt: shift amount (00000 for now) - funct: function code (extends opcode) - **I-format**:通常用於加載和存儲數據,以及分支和跳轉操作 ![](https://i.imgur.com/FmY4GRM.png) - Immediate arithmetic and load/store instructions - rt: destination or source register number - Constant: -2^15 to 2^15-1 (常數可以表示 16-bit 的有號數) - Address: offset added to base in rs (要跳轉的位址會是放入與 rs 位址之間差了多少的 instruction 數量 => 指令位移量) :::success Design Principle 4: Good design demands good compromises ::: #### Stored Program Computer - Instruction cycle 指令的循環週期 - Fetch(抓取到 CPU ), Decode(解析), Execute(執行) ![](https://i.imgur.com/6fl9Jm8.png) - Memory 雖然是以 8-bit (1 byte) 為單位,但是每個指令 (word) 是以 32-bit (4 byte) 為單位,故每個指令會需要用到 4 byte 的記憶體空間儲存。 - Program Counter (PC) => 程式指令計數器,用來記錄下一個要執行的指令位址。每當開始執行該指令時,PC 會直接更新至 **下一個** 指令位址。 ![](https://i.imgur.com/DlpCnom.png) ![](https://i.imgur.com/a8VCkx1.png) - 以此範例來說,lw 會從 1200($t1) 的這個位址當中,取得 value。 - $t1 儲存的是位址 (address) = 10008000 (hex) - $t0 儲存的是值 (value) = 0000A111 (hex) #### Shift Operation ``` sll $t2, $s0, 4 ``` t2 是要寫入的 Register s0 是要位移的目標 4 是要位移的量 #### AND Operation 跟 0 作 and 都會變成 0 跟 1 作 and 會是 自己 ``` and $t0, $t1, $t2 ``` #### OR Operation 跟 0 作 or 會是 自己 跟 1 作 or 都會變成 1 ``` and $t0, $t1, $t2 ``` #### NOT Operation - 用 NOR 實現 NOT ``` nor $t0, $t1, $zero ``` > Register 0: always read as zero #### Conditional Operation - branch if equal ``` beq rs, rt, L1 ``` - branch if not equal ``` bne rs, rt, L1 ``` - jump ``` j L1 ``` #### Loop Statements ![](https://i.imgur.com/FvFG3fN.png) #### Compiling Loop Statements ![](https://i.imgur.com/760ZU46.png) #### Basic Blocks - 沒有跳來跳去的區塊,稱為 Basic Blocks - 就可以對他做最佳化 #### More Conditional Operations ``` slt rd, rs, rt ``` => if (rs < rt) then rd = 1; else rd = 0 ex. ``` slt $t0, $s1, $s2 bne $t0, $zero, L ``` #### Signed vs Unsigned ![](https://i.imgur.com/0L290Jv.png) #### Procedure Calling - Steps required 1. Place parameters in registers 把需要引入的參數先放到暫存器 2. Transfer control to procedure 跳轉至 Procedure 3. Acquire storage for procedure 配置空間 4. Perform procedure's opreation 執行程式 5. Place result in register for caller 回傳值至 caller 6. Return to place of call 跳轉回去主要的程式執行的地方 #### Register Usage - $a0 – $a3: arguments (reg’s 4 – 7) - $v0, $v1: result values (reg’s 2 and 3) - $t0 – $t9: temporaries - Can be overwritten by callee 因為是 暫時的 覆蓋掉沒關係 - $s0 – $s7: saved - Must be saved/restored by callee - $gp: global pointer for static data (reg 28) - $sp: stack pointer (reg 29) - $fp: frame pointer (reg 30) - $ra: return address (reg 31) 紀錄 return 的位址,才知道 return 時要跳回去哪裡 #### Procedure Call Instructions - Procedure Call: jump and link (jal) ``` jal ProcedureLabel ``` - Procedure Return: jump register ``` jr $ra ``` #### Using More Registers - Stack - 位址會從**高位址至低位址** - 兩個指標:`$fp`(頭)、`$sp`(尾) - 通常都會直接使用 `$sp` 做操作 ![](https://i.imgur.com/uKhL1bX.png) #### Memory Layout - 一般來說會把記憶體空間切成以下的圖示 ![](https://i.imgur.com/BgLtUEN.png) #### Leaf Procedure ![](https://i.imgur.com/2GoYv8u.png) ![](https://i.imgur.com/R9DUHe6.png) #### Non-Leaf Procedures ![](https://i.imgur.com/1uVXnZk.png) ![](https://i.imgur.com/F20MS6T.png) #### Character Data - 字元資料 - 一個 Byte (16-bit) 儲存一個字元 - ASCII: 128 個字元 - Latin-1: 256 個字元 - Unicode: 32-bit 儲存一個字元 #### Byte/Haldword Operations ![](https://i.imgur.com/StJC7Y0.png) #### String Copy Example ![](https://i.imgur.com/ziEiAfL.png) ![](https://i.imgur.com/OQfzXTJ.png) :::info 重點: 因為是對字串做複製,所以每一個字元在複製時,會使用到`lbu $t2, 0($t1)`把字元 load 進來,再使用`sb $t2 0($t3)`把複製的字元丟給目的地。 ::: #### 32-bit Constants - 大部分情況 16-bit 就能夠表示常數了 - 但如果還想要表示更大的常數,可以使用`lui rt, constant`這個語法 - `lui` => load upper immediate - 因為一個 word 會使用 32-bit 儲存,所以使用`lui`會把這個constan 的 16-bit 丟到 32-bit 的前半部。 - 再使用`ori $s0, $s0, constant`把原本後半部分的 16-bit 取代成 constant,就能夠用 32-bit 表示常數了。 ![](https://i.imgur.com/61zXnEi.png) #### Branch Addressing - 在使用 Branch 指令時,會需要定義 Label 的位址,但是那個位址不會直接儲存在機器語言表示的指令裡,而通常要跳去的 Label 位址不會離現在的 PC (Programing Counter) 太遠,所以會直接紀錄目前 PC 位址和 Label 之間差了多少個 word。 - Target Address = PC + offset x 4 :::danger PC 此時已經 +4 了,因為在執行此段 branch 指令時,PC 會先 +4,準備下一個指令。 ::: ![](https://i.imgur.com/JfjHay5.png) #### Jump Addressing - 因為一段指令(word)只能用 32-bit 表示,所以包含 op code 只剩下 26-bit 可以表示要 Jump 的位址 - 因為一個指令要 4bytes 所以記憶體在儲存時,位址一定會 4 的倍數,所以最後 32-bit 的位址後兩位元一定是0。(只需要花 30 bit 表示) - 最高位元 4-bit 用 PC的前 4 位元,因為跳的位址也不會太遠,所以直接複製 PC 的前 4 位元。(只需要使用 26-bit 表示,也是最大能夠表示的範圍) ![](https://i.imgur.com/w1BTVgG.png) #### Target Example ![](https://i.imgur.com/NgaGfyd.png) #### Assembler Pseudoinstructions ![](https://i.imgur.com/xkaF7QV.png) #### 指令對應的 Type | R-Type | I-Type | J-Typr | |:------------------- |:------------------ |:-------- | | `add rd, rs, rt` | `addi rt, rs, imm` | - | | `sll rd, rt, shamt` | `slti rt, rs, imm` | - | | - | `lw rt, imm(rs)` | - | | - | `sw rt, imm(rs)` | - | | `jr rs` | `beq rs, rt, imm` | `j addr` | - R-Type | op | rs | rt | rd | shamt | func | |:---:|:---:|:---:|:---:|:-----:|:----:| | 6 | 5 | 5 | 5 | 6 | 6 | - I-Typr | op | rs | rt | constant / address | |:---:|:---:|:---:|:------------------:| | 6 | 5 | 5 | 16 | - J-Type | op | address | |:---:|:-------:| | 6 | 26 | #### 組合語言 指令統整 :::spoiler 統整內容 `add a, b, c` => a = b + c - Register File - MIPS 有 32 x 32-bit 的 register file - 1 個 word 等於 32 bits - $t0 ~ $t9 是專屬給 temporary values - $s0 ~ $s7 是專屬給 saved variables - Memory - **Load** => from memory into register - **Store** => from register to memory - 以 byte 為單位,等於是 8 bits - 存入 word 的位址,位址一定是 4 的倍數,因為一個 word 是 32 bits `lw $t0, 32($s3)` => 從 s3 的位址往後 32 個 byte 的值,存入暫存變數 $t0。(如果 $s3 代表陣列 A[0] => 則 32($s3) 代表 A[8]) `sw $t0, 48($s3)` => $t0 的 data 存入 A[12] ($s3 代表 A[0]) `slt rd, rs, rt` => if (rs < rt) rd = 1; else rd = 0; slt => set on less than :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully