05 AssemblyProgramming
05 AssemblyProgramming
(Part 1)
1 / 18
Outline
Effective documentation
2 / 18
Documenting your code
.data
(constant and variable definitions)
.text
3 / 18
Just to reiterate . . . (required from here on out)
Once at top of file:
Header block
1. author name
2. date of current version
3. high-level description of your program
4 / 18
Outline
Effective documentation
5 / 18
Compositionality
Main challenge
• math expressions are compositional
• assembly instructions are not compositional
Compositionality in math:
• use expressions as arguments to other expressions
• example: a * (b + 3)
Non-compositionality in assembly:
• can’t use instructions as arguments to other instructions
• not valid MIPS: mult $t0 (addi $t1 3)
6 / 18
Significance of compositionality (PL aside)
7 / 18
Sequentializing expressions
Goal
Find a sequence of assembly instructions that implements the
pseudocode expression
8 / 18
Finding the right sequence of instructions
Example
# Pseudocode:
# d = (a+b) * (c+4)
tmp1 = a+b
# Register mappings: tmp2 = c+4
# a: t0, b: t1, c: t2, d: t3 d = tmp1 * tmp2
add $t4, $t0, $t1 # tmp1 = a+b
addi $t5, $t2, 4 # tmp2 = c+4
mul $t3, $t4, $t5 # d = tmp1 * tmp2
9 / 18
Finding the right sequence of instructions
+ d
Example
# Pseudocode:
# c = a + 3*(b+2) tmp2 * a
# Register mappings:
# a: t0, b: t1, c: t2
addi $t3, $t1, 2 # tmp1 = b+2 3 + tmp1
mul $t4, $t3, 3 # tmp2 = 3*tmp1
add $t2, $t0, $t4 # c = a + tmp2
b 2
10 / 18
Optimizing register usage
# Pseudocode:
# c = a + 3*(b+2)
# Register mappings:
# a: $t0, b: $t1, c: $t2
# tmp1: $t3, tmp2: $t4
11 / 18
Exercise
# Pseudocode:
# d = a - 3 * (b + c + 8)
# Register mappings:
# a: t0, b: t1, c: t2, d: t3
12 / 18
Logical expressions
Logical expressions
• values: True, False
• boolean operators: not (!), and (&&), or (||)
• relational operators: ==, !=, >, >=, <, <=
In MIPS:
• conceptually, False = 0, True = 1
• non-relational logical operations are bitwise, not boolean
13 / 18
Bitwise logic operations
and $t1, $t2, $t3 # $t1 = $t2 & $t3 (bitwise and)
or $t1, $t2, $t3 # $t1 = $t2 | $t3 (bitwise or)
xor $t1, $t2, $t3 # $t1 = $t2 ^ $t3 (bitwise xor)
Immediate variants
andi $t1, $t2, 0x0F # $t1 = $t2 & 0x0F (bitwise and)
ori $t1, $t2, 0xF0 # $t1 = $t2 | 0xF0 (bitwise or)
xori $t1, $t2, 0xFF # $t1 = $t2 ^ 0xFF (bitwise xor)
14 / 18
Bitwise logic vs. boolean logic
15 / 18
Relational operations
Logical expressions
• values: True, False
• boolean operators: not (!), and (&&), or (||)
• relational operators: ==, !=, >, >=, <, <=
16 / 18
Exercise
# Pseudocode:
# c = (a < b) || ((a+b) == 10)
# Register mappings:
# a: t0, b: t1, c: t2
17 / 18
Exercise
# Pseudocode:
# c = (a < b) && ((a+b) % 3) == 2
# Register mappings:
# a: t0, b: t1, c: t2
18 / 18