###### tags: `組合語言` # 組合語言共筆 11 : Conditional Execution ## 1. 簡介 : 在前一章 [組合語言共筆 10 : Branch Instructions](/sj8a4jC3T9yNqwEPf1Lrmw) 中有提到,可以利用以下三種指令做條件運算 在這章要提的 Conditional Execution 是一種 **ARM `基於 Branch & Flag` 產生的**"**`簡短序列寫法`**" ``` - B{L}{<cond>} : Branch 指令,用來做條件判斷 - s : 修飾詞 {s},用來更動 CPSR 的 Flag // (ex:subs) - cmp : compare 指令,也是用來更動 flag ``` :::info - Flag 意義 | Flags | 意義 | Logical Instruction(邏輯指令) | Arithmetic Instruction(算數指令) | | -------- | -------- | -------- | -------- | | N | 運算結果是否為負 | 無意義 |當第 31 個 bit 設成負時,N=1 ( 31 bit 決定正負 )| | Z | 運算結果是否為零 | 運算結果為零 |全部 32 bit 皆為 0,Z=1| | C | Unsigned 資料 overflow | 當做 Shift 時溢位,C=1 |當結果超出 32 bit,C=1| | V | signed 資料 overflow | 無意義 |當結果超出 31 bit 時,V=1 (不算sign)| `- [補] - 溢位 overflow : 只運算結果超出儲存的記憶體大小 ( 32 or 31 bit )` ::: <br> ## 2. Conditional Execution 介紹 ### (1). Branch 轉 Conditional Execution 範例 這邊用範例來說明 Conditional Execution 先寫出 Branch 的寫法 ```assembly= cmp r0,#5 // if(r0==5) beq Bypass // goto Bypass add r1,r1,r0 // r1 = r1 + r0 Bypass:... ``` 再簡化成 Conditional Execution ```assembly= cmp r0,#5 addne r1,r1,r0 // add 加上條件 (Z != 1) ``` 會發現比起使用 Branch,`Conditional Execution 可以用更短的語法 (序列式) 來作條件判斷` ### (2). Branch vs Conditional Execution 以下簡單的比較兩者之間的優缺點 :::info - Branch v.s Conditional Execution | 方式 | 優點 | 缺點 | | -------- | -------- | -------- | | **Branch** | 邏輯簡單,程式易讀 | 要執行較多指令,較吃 CPU 效能 | | **Conditional Execution** | 省CPU效能,執行速度快 | 邏輯較複雜,不一定每個判斷都適用 | ::: <br> ## 3. Reference - [Conditional Execution | 陳丕祐](https://henrybear327.gitbooks.io/gitbook_tutorial/content/Assembly/ARM-Instruction/Conditional-Execution/index.html) - [Conditional Execution | Davespace](http://www.davespace.co.uk/arm/introduction-to-arm/conditional.html)