Upload
hatu
View
221
Download
0
Embed Size (px)
Citation preview
1Arquitetura e Organização de Computadores
Instruções e Linguagem de Máquina
Prof. Otávio [email protected]
Prof. Mário Luiz [email protected]
2Arquitetura e Organização de Computadores
Instruções e Linguagem de MáquinaMáquinas RISC X CISC
• Conceitos gerais• Conjunto de instruções
Linguagem de Máquina• Conjunto de Instruções• Modos de endereçamento
MIPS• Programação com linguagem de Máquina• Simuladores
4Arquitetura e Organização de Computadores
Simplicity favors regularity– fixed size instructions – 32-bits– small number of instruction formats– opcode always the first 6 bits
Good design demands good compromises– three instruction formats
Smaller is faster– limited instruction set– compromise on number of registers in register file– limited number of addressing modes
Make the common case fast– arithmetic operands from the register file (load-store machine)– allow instructions to contain immediate operands
MIPS (RISC)
5Arquitetura e Organização de Computadores
ProcessorMemory
32 bits
230
words
read/write addr
read data
write data
word address(binary)
0…00000…01000…10000…1100
1…1100Register File
src1 addr
src2 addr
dst addr
write data
32 bits
src1data
src2data
32registers
($zero - $ra)
32
32
3232
32
32
5
5
5
PC
ALU
32 32
3232
32
0 1 2 37654
byte address(big Endian)
FetchPC = PC+4
DecodeExec
Add32
324
Add32
32branch offset
MIPSOrganização
6Arquitetura e Organização de Computadores
Processors can order bytes within a word in two ways
Little Endian Byte Ordering
– Memory address = Address of least significant byte
– Example: Intel IA-32, Alpha
Big Endian Byte Ordering
– Memory address = Address of most significant byte
– Example: SPARC, PA-RISC
MIPS can operate with both byte orderings
Byte 0Byte 1Byte 2Byte 3
32-bit Register
MSB LSB. . . . . .Byte 0Byte 1Byte 2Byte 3
a a+3a+2a+1
Memory
address
Byte 3Byte 0Byte 1Byte 2Byte 3
32-bit Register
MSB LSB. . . . . .Byte 0 Byte 1 Byte 2
a a+3a+2a+1
Memory
address
MIPSOrdenação dos bytes
e Significância
7Arquitetura e Organização de Computadores
There are 3 main types of assembly instructions– Arithmetic - add, sub, mul, shifts, and, or, etc.
– Load/store– Conditional - branches
MIPSTipos de Instrução
8Arquitetura e Organização de Computadores
add a, b, c a = b+cadd a, a, d a = d+a = d+b+cadd a, a, e a = e+a = e+d+b+c
Example: Translate the following instructions to assembly code
a = b + cd = a - e
MIPSInstruções Aritméticas
9Arquitetura e Organização de Computadores
Example: Translate the following instructions to assembly code. Remember with RISC, only 1 operation per instruction!
f = (g + h) - (i + j)
MIPSInstruções Aritméticas
10Arquitetura e Organização de Computadores
In assembly code, you can’t use variables such as a, b, c, etc
In RISC instruction sets, operands must be registers such as r1, r2, r3, etc
– r0 is typically reserved to hold the immediate value of 0
– There is a limited number of registers• MIPS has 32
MIPSOperandos
11Arquitetura e Organização de Computadores
Example: Translate the following instructions to assembly code. Assume that g, h, i, and j are already
stored in r1, r2, r3, and r4. Store f in r5
f = (g+h) - (i+j)
add r6, r1, r2add r7, r3, r4sub r5, r6, r7
MIPSOperações Aritméticas
utilizando Registradores
12Arquitetura e Organização de Computadores
With only a limited number of registers, not all data can be stored in registers at the same time.
– Registers only store data that is currently being operated on
Variables are stored in memory and then loaded into registers when needed using data transfer instructions
– Load word (lw) and store word (sw)
MIPSOperações Aritméticas
utilizando Registradores
13Arquitetura e Organização de Computadores
Load word format– lw destination register, memory location
Store word format– sw source register, memory location
Memory location format– Offset(base address)
• Base address = starting location of data in memory• Offset = how far away is location to access from base address
– Values are added together
MIPSLoad e Store
14Arquitetura e Organização de Computadores
Example: Assume that A is an array of 100 words. Assume the base address is stored in r3, g is in r1 and h is in r2
g = h + A[8]
lw r4, 32(r3)add r1, r2, r4
Offset
Base Address
MIPSExemplo Load
15Arquitetura e Organização de Computadores
Architecture usually addresses data in bytes (byte addressable)
– 32-bit architecture = 4 bytes = 1 word• lw/sw load/store 1 word or 4 bytes
– Thus, data/inst addresses are multiples of 4• Data is word aligned to be more efficient
MIPSEndereçamento
16Arquitetura e Organização de Computadores
.
.
.
10010
1011
12840
Address Data
.
.
.
MIPSEndereçamento e Dados
17Arquitetura e Organização de Computadores
Example: Assume that A is an array of 100 words. Assume the base address is stored in r3 and h is stored in r2. You may directly calculate the offset. Remember, each data piece is 4 bytes when calculating the offset
A[12] = h+A[8]
lw r1, 32(r3)add r4, r2, r1sw r4, 48(r3)
MIPSExemplo Load / Store
18Arquitetura e Organização de Computadores
Example: Assume that A is an array of 100 words. Assume the base address is stored in r3 and g, h, and i are in r1, r2, and r4 respectively. Calculate the offset using assembly instructions but don’t use multiplication yet.
g = h + A[i]
add r5, r4, r4add r5, r5, r5add r5, r5, r3lw r6, 0(r5)add r1, r6, r2
MIPSExemplo Load / Store
19Arquitetura e Organização de Computadores
Example: Assume that A is an array of 100 words. Assume the base address is stored in r3 and g, h, and i are in r1, r2, and r4 respectively. Calculate the offset using assembly instructions but don’t use multiplication yet.
g = h + A[i]
add r5, r4, r4 # Temp reg r5=2*iadd r5, r5, r5 # Temp reg r5=4*iadd r5, r5, r3 # t1 = addr of A[i] (4*i+r3)lw r6, 0(r5) # Temp reg r6=a[i]add r1, r6, r2 # g=h+a[i]
MIPSExemplo Load / Store
20Arquitetura e Organização de Computadores
MIPS fields are giving names to make them easier to discuss
• op: Basic operation of the instruction, typically called the opcode• rs: The first register source operand• rt: The second register source operand• rd: The register destination operand, it gets the result of the operation• shamt: Shift amount (0 if not shift instruction)• funct: Function. This field selects the specific variant of the operation in the op field, and is sometimes called the function code
op rs rt rd shamt funct
6 bits 5 bits 5 bits 5 bits 5 bits 6 bits
MIPSCampos das Instruções
21Arquitetura e Organização de Computadores
Problem occurs with an instruction needs a longer field than that showed on the previous slide
– I.e. LW must specify 2 registers and a constant. Limited to 5-bit constant if use previous format.
Solution: There are different formats for different types of instructions
– Previous slide is R-type (R-format):• R=register
MIPSCampos das Instruções
22Arquitetura e Organização de Computadores
I-type (I-format)– I=immediate– Now LW can specify an address up to 16-bits
Opcode determines the format
op rs rt address
6 bits 5 bits 5 bits 16 bits
MIPSCampos das Instruções
23Arquitetura e Organização de Computadores
Branch/jump instructions– Conditional branches
• beq register1, register2, Label• bne register1, register2, Label
– Unconditional branches• j Label
MIPSInstruções de Decisão
24Arquitetura e Organização de Computadores
Example: Assume f->r0, g->r1, h->r2, i->r3, j->r4
if ( i==j ) goto L1f = g+h
L1: f = f-i
beq r3, r4, L1add r0, r1, r2
L1: sub r0, r0, r3Labels will need to be
translated to instruction address in
your assembler
MIPSInstruções de Decisão
25Arquitetura e Organização de Computadores
Example: Assume f->r0, g->r1, h->r2, i->r3, j->r4
if ( i==j )f = g+h
L1: elsef = g-h
L2:
bne r3, r4, L1add r0, r1, r2j L2
L1: sub r0, r1, r2L2:
MIPSInstruções de Decisão
26Arquitetura e Organização de Computadores
Example: A is 100 elements with the base address in r5. g->r1, h->r2, i->r3, j->r4
Loop: g = g+A[i]i = i+jif ( i!=h ) goto Loop
Loop: add r6, r3, r3add r6, r6, r6add r6, r6, r5lw r7, 0(r6)add r1, r1, r7add r3, r3, r4bne r3, r2, Loop
MIPSInstruções de Decisão
27Arquitetura e Organização de Computadores
Goto statements are bad, just used them as an example.
You will want to use while loops– Or for loops but I am just showing you while
loops
MIPSWhile
28Arquitetura e Organização de Computadores
Example: Base address of save is in r6. i->r3, j->r4, k->r5
while ( save[i] == k )i = i+j
Loop: add r1, r3, r3add r1, r1, r1add r1, r1, r6lw r0, 0(r1)bne r0, r5, Exitadd r3, r3, r4j Loop
Exit:
MIPSWhile
29Arquitetura e Organização de Computadores
Example: What is the machine code for the following?
addi r4, r4, 4
decimal
binary
op rs rt Immediate
8 4 4 4
001000 00100 00100 0000 0000 0000 0100
MIPSOperando Imediato
30Arquitetura e Organização de Computadores
Last instruction format - J-type (J-format)
Branches do not use J-type.– Must specify 2 registers to compare– Use I-type
opcode Target address
MIPSEndereçamento com Jumps
31Arquitetura e Organização de Computadores
Instruction Categories
Computational
Load/Store
Jump and Branch
Floating Point - coprocessor
Memory Management
Special
R0 - R31
PCHI
LO
Registers
OP
OP
OP
rs rt rd sa funct
rs rt immediate
jump target
3 Instruction Formats: all 32 bits wide
R format
I format
J format
MIPS R3000ISA
32Arquitetura e Organização de Computadores
Name Register Number
Usage Preserve on call?
$zero 0 constant 0 (hardware) n.a.$at 1 reserved for assembler n.a.
$v0 - $v1 2-3 returned values no$a0 - $a3 4-7 arguments yes$t0 - $t7 8-15 temporaries no$s0 - $s7 16-23 saved values yes$t8 - $t9 24-25 temporaries no
$gp 28 global pointer yes$sp 29 stack pointer yes$fp 30 frame pointer yes$ra 31 return addr (hardware) yes
MIPSRegistradores
38Arquitetura e Organização de Computadores
When speed is critical. Maybe use Assembly Language for critical components.
To exploit specialized machine capabilities.
When no High Lever Language compiler is available for a machine.
When one wants to debug particularly complex structures.
Why not:
Inherently machine dependent.
Assembly Language programs are much longer.
Assembly Language programs tend to be harder to debug.
Abstraction level is much lower that with a High Level Language.
MIPSPor que utilizar Assembly?
39Arquitetura e Organização de Computadores
C program
MIPS Assy Program
Machine code Memory Dump Reverse Engineered Code
MIPSExemplo de Programa
40Arquitetura e Organização de Computadores
Three types of statements in assembly language
Typically, one statement should appear on a line
1. Executable Instructions
Generate machine code for the processor to execute at runtime
Instructions tell the processor what to do
2. Pseudo-Instructions and Macros
Translated by the assembler into real instructions
Simplify the programmer task
3. Assembler Directives
Provide information to the assembler while translating a program
Used to define segments, allocate memory variables, etc.
Non-executable: directives are not part of the instruction set
MIPSLinguagem Assembly
41Arquitetura e Organização de Computadores
Assembly language instructions have the format:
[label:] mnemonic [operands] [#comment]
Label: (optional)
– Marks the address of a memory location, must have a colon
– Typically appear in data and text segments
Mnemonic
– Identifies the operation (e.g. add, sub, etc.)
Operands
– Specify the data required by the operation
– Operands can be registers, memory variables, or constants
– Most instructions have three operands
L1: addiu $t0, $t0, 1 #increment $t0
MIPSInstruções
42Arquitetura e Organização de Computadores
Comments are very important!
– Explain the program's purpose
– When it was written, revised, and by whom
– Explain data used in the program, input, and output
– Explain instruction sequences and algorithms used
– Comments are also required at the beginning of every procedure
• Indicate input parameters and results of a procedure
• Describe what the procedure does
Single-line comment
– Begins with a hash symbol # and terminates at end of line
MIPSComentários
43Arquitetura e Organização de Computadores
# Title: Filename:# Author: Date:# Description:# Input:# Output:################# Data segment #####################.data . . .################# Code segment #####################.text.globl mainmain: # main program entry . . .li $v0, 10 # Exit programsyscall
MIPSTemplate
44Arquitetura e Organização de Computadores
.DATA directive
– Defines the data segment of a program containing data
– The program's variables should be defined under this directive
– Assembler will allocate and initialize the storage of variables
.TEXT directive
– Defines the code segment of a program containing instructions
.GLOBL directive
– Declares a symbol as global
– Global symbols can be referenced from other files
– We use this directive to declare main procedure of a program
MIPSDiretivas
45Arquitetura e Organização de Computadores
Stack Segment0x7FFFFFFF
Dynamic Area
Static Area
Text Segment
Reserved
0x04000000
0x10000000
0
Data Segment
Memory
Addresses
in Hex
Stack Grows
Downwards
MIPSMemória
46Arquitetura e Organização de Computadores
Sets aside storage in memory for a variable
May optionally assign a name (label) to the data
Syntax:
[name:] directive initializer [, initializer] . . .
var1: .WORD 10
All initializers become binary data in memory
MIPSDeclaração de Dados
47Arquitetura e Organização de Computadores
.BYTE Directive
– Stores the list of values as 8-bit bytes
.HALF Directive
– Stores the list as 16-bit values aligned on half-word boundary
.WORD Directive
– Stores the list as 32-bit values aligned on a word boundary
.WORD w:n Directive
– Stores the 32-bit value w into n consecutive words aligned on a word boundary.
MIPSDiretivas de Dados
48Arquitetura e Organização de Computadores
.FLOAT Directive
– Stores the listed values as single-precision floating point
.DOUBLE Directive
– Stores the listed values as double-precision floating point
MIPSDiretivas de Dados
49Arquitetura e Organização de Computadores
.ASCII Directive
– Allocates a sequence of bytes for an ASCII string
.ASCIIZ Directive
– Same as .ASCII directive, but adds a NULL char at end of string
– Strings are null-terminated, as in the C programming language
.SPACE n Directive
– Allocates space of n uninitialized bytes in the data segment
Special characters in strings follow C convention
– Newline: \n Tab:\t Quote: \”
MIPSDiretivas de Strings
50Arquitetura e Organização de Computadores
.DATA
var1: .BYTE 'A', 'E', 127, -1, '\n'
var2: .HALF -10, 0xffff
var3: .WORD 0x12345678
Var4: .WORD 0:10
var5: .FLOAT 12.3, -0.1
var6: .DOUBLE 1.5e-10
str1: .ASCII "A String\n"
str2: .ASCIIZ "NULL Terminated String"
array: .SPACE 100
If the initial value exceeds the maximum size, an error is
reported by assembler
MIPSDeclarações - exemplos
51Arquitetura e Organização de Computadores
Memory is viewed as an array of bytes with addresses
Byte Addressing: address points to a byte in memory
Words occupy 4 consecutive bytes in memory
– MIPS instructions and integers occupy 4 bytes
Alignment: address is a multiple of size
– Word address should be a multiple of 4
• Least significant 2 bits of address should be 00
– Halfword address should be a multiple of 2
.ALIGN n directive
– Aligns the next data definition on a 2n byte boundary
0
4
8
12
add
ress
not aligned
. . .
aligned word
not aligned
Memory
MIPSAlinhamento de Memória
52Arquitetura e Organização de Computadores
Assembler builds a symbol table for labels (variables)
– Assembler computes the address of each label in data segment
Example Symbol Table
.DATA
var1: .BYTE 1, 2,'Z'
str1: .ASCIIZ "My String\n"
var2: .WORD 0x12345678
.ALIGN 3
var3: .HALF 1000
Label
var1
str1
var2
var3
Address
0x10010000
0x10010003
0x10010010
0x10010018
0 0 0 0 0 0
var1
1 2 'Z'0x10010000
str1
'M' 'y' ' ' 'S' 't' 'r' 'i' 'n' 'g' '\n' 00x123456780x10010010
var2 (aligned)
1000var3 (address is multiple of 8)
0 0 Unused
0 00 0Unused
MIPSTabela de símbolos
53Arquitetura e Organização de Computadores
Process:
Place parameters where procedure can access them
Transfer control to the procedure
Acquire storage resources for the procedure
Perform the task
Place result where calling program can access it
Return control to calling program
Support structure:
$a0-$a3 argument passing registers
$v0-$v1 return value registers
$ra return address register
MIPSProcedures
54Arquitetura e Organização de Computadores
Parameters:
$a0 = Address of v[] $a1 = k, and Return address is in $ra
Consider the following swap procedure (written in C)
Translate this procedure to MIPS assembly language
void swap(int v[], int k)
{ int temp;
temp = v[k]
v[k] = v[k+1];
v[k+1] = temp;}
MIPSProcedures
55Arquitetura e Organização de Computadores
Parameters:
$a0 = Address of v[] $a1 = k, and Return address is in $ra
Consider the following swap procedure (written in C)
Translate this procedure to MIPS assembly language
void swap(int v[], int k)
{ int temp;
temp = v[k]
v[k] = v[k+1];
v[k+1] = temp;}
swap:
sll $t0,$a1,2 # $t0=k*4
add $t0,$t0,$a0 # $t0=v+k*4
lw $t1,0($t0) # $t1=v[k]
lw $t2,4($t0) # $t2=v[k+1]
sw $t2,0($t0) # v[k]=$t2
sw $t1,4($t0) # v[k+1]=$t1
jr $ra # return
MIPSProcedures
56Arquitetura e Organização de Computadores
Suppose we call procedure swap as: swap(a,10)
– Pass address of array a and 10 as arguments
– Call the procedure swap saving return address in $31 = $ra
– Execute procedure swap
– Return control to the point of origin (return address)
la $a0, ali $a1, 10jal swap
# return here. . .
Caller
addr a$a0=$410$a1=$5
ret addr$ra=$31
. . .
. . .
Registers
MIPSCall / Return
You should also be aware that "move" and "li" are both "pseudo-instructions".
"move $s0,$s1" might really be "add $s0,$0,$s1".
A "li" instruction might be the combination of a "lui" and a "ori" instruction so "li" may even be two instructions.
57Arquitetura e Organização de Computadores
Suppose we call procedure swap as: swap(a,10)
– Pass address of array a and 10 as arguments
– Call the procedure swap saving return address in $31 = $ra
– Execute procedure swap
– Return control to the point of origin (return address)
swap:sll $t0,$a1,2add $t0,$t0,$a0lw $t1,0($t0)lw $t2,4($t0)sw $t2,0($t0)sw $t1,4($t0)jr $ra
la $a0, ali $a1, 10jal swap
# return here. . .
Caller
addr a$a0=$410$a1=$5
ret addr$ra=$31
. . .
. . .
Registers
MIPSCall / Return
58Arquitetura e Organização de Computadores
Address Instructions Assembly Language
00400020 lui $1, 0x1001 la $a0, a00400024 ori $4, $1, 000400028 ori $5, $0, 10 li $a1,100040002C jal 0x10000f jal swap00400030 . . . # return here
swap:0040003C sll $8, $5, 2 sll $t0,$a1,200400040 add $8, $8, $4 add $t0,$t0,$a000400044 lw $9, 0($8) lw $t1,0($t0)00400048 lw $10,4($8) lw $t2,4($t0)0040004C sw $10,0($8) sw $t2,0($t0)00400050 sw $9, 4($8) sw $t1,4($t0)00400054 jr $31 jr $ra
Pseudo-DirectAddressing
PC = imm26<<2
0x10000f << 2
= 0x0040003C
MIPSJAL e JR
59Arquitetura e Organização de Computadores
Register $31is the return
address register
Address Instructions Assembly Language
00400020 lui $1, 0x1001 la $a0, a00400024 ori $4, $1, 000400028 ori $5, $0, 10 li $a1,100040002C jal 0x10000f jal swap00400030 . . . # return here
swap:0040003C sll $8, $5, 2 sll $t0,$a1,200400040 add $8, $8, $4 add $t0,$t0,$a000400044 lw $9, 0($8) lw $t1,0($t0)00400048 lw $10,4($8) lw $t2,4($t0)0040004C sw $10,0($8) sw $t2,0($t0)00400050 sw $9, 4($8) sw $t1,4($t0)00400054 jr $31 jr $ra
Pseudo-DirectAddressing
PC = imm26<<2
0x10000f << 2
= 0x0040003C
0x00400030$31
MIPSJAL e JR
60Arquitetura e Organização de Computadores
Register $31is the return
address register
Address Instructions Assembly Language
00400020 lui $1, 0x1001 la $a0, a00400024 ori $4, $1, 000400028 ori $5, $0, 10 li $a1,100040002C jal 0x10000f jal swap00400030 . . . # return here
swap:0040003C sll $8, $5, 2 sll $t0,$a1,200400040 add $8, $8, $4 add $t0,$t0,$a000400044 lw $9, 0($8) lw $t1,0($t0)00400048 lw $10,4($8) lw $t2,4($t0)0040004C sw $10,0($8) sw $t2,0($t0)00400050 sw $9, 4($8) sw $t1,4($t0)00400054 jr $31 jr $ra
Pseudo-DirectAddressing
PC = imm26<<2
0x10000f << 2
= 0x0040003C
0x00400030$31
MIPSJAL e JR
61Arquitetura e Organização de Computadores
Register $31is the return
address register
Address Instructions Assembly Language
00400020 lui $1, 0x1001 la $a0, a00400024 ori $4, $1, 000400028 ori $5, $0, 10 li $a1,100040002C jal 0x10000f jal swap00400030 . . . # return here
swap:0040003C sll $8, $5, 2 sll $t0,$a1,200400040 add $8, $8, $4 add $t0,$t0,$a000400044 lw $9, 0($8) lw $t1,0($t0)00400048 lw $10,4($8) lw $t2,4($t0)0040004C sw $10,0($8) sw $t2,0($t0)00400050 sw $9, 4($8) sw $t1,4($t0)00400054 jr $31 jr $ra
Pseudo-DirectAddressing
PC = imm26<<2
0x10000f << 2
= 0x0040003C
0x00400030$31
MIPSJAL e JR
62Arquitetura e Organização de Computadores
Register $31is the return
address register
Address Instructions Assembly Language
00400020 lui $1, 0x1001 la $a0, a00400024 ori $4, $1, 000400028 ori $5, $0, 10 li $a1,100040002C jal 0x10000f jal swap00400030 . . . # return here
swap:0040003C sll $8, $5, 2 sll $t0,$a1,200400040 add $8, $8, $4 add $t0,$t0,$a000400044 lw $9, 0($8) lw $t1,0($t0)00400048 lw $10,4($8) lw $t2,4($t0)0040004C sw $10,0($8) sw $t2,0($t0)00400050 sw $9, 4($8) sw $t1,4($t0)00400054 jr $31 jr $ra
Pseudo-DirectAddressing
PC = imm26<<2
0x10000f << 2
= 0x0040003C
0x00400030$31
MIPSJAL e JR
63Arquitetura e Organização de Computadores
Register $31is the return
address register
Address Instructions Assembly Language
00400020 lui $1, 0x1001 la $a0, a00400024 ori $4, $1, 000400028 ori $5, $0, 10 li $a1,100040002C jal 0x10000f jal swap00400030 . . . # return here
swap:0040003C sll $8, $5, 2 sll $t0,$a1,200400040 add $8, $8, $4 add $t0,$t0,$a000400044 lw $9, 0($8) lw $t1,0($t0)00400048 lw $10,4($8) lw $t2,4($t0)0040004C sw $10,0($8) sw $t2,0($t0)00400050 sw $9, 4($8) sw $t1,4($t0)00400054 jr $31 jr $ra
Pseudo-DirectAddressing
PC = imm26<<2
0x10000f << 2
= 0x0040003C
0x00400030$31
MIPSJAL e JR
64Arquitetura e Organização de Computadores
Instruction Meaning Formatjal label $31=PC+4, jump op6 = 3 imm26
jr Rs PC = Rs op6 = 0 rs5 0 0 0 8jalr Rd, Rs Rd=PC+4, PC=Rs op6 = 0 rs5 0 rd5 0 9
JAL (Jump-and-Link) used as the call instruction Save return address in $ra = PC+4 and jump to procedure
Register $ra = $31 is used by JAL as the return address
JR (Jump Register) used to return from a procedure Jump to instruction whose address is in register Rs (PC = Rs)
JALR (Jump-and-Link Register) Save return address in Rd = PC+4, and
Jump to procedure whose address is in register Rs (PC = Rs)
Can be used to call methods (addresses known only at runtime)
MIPSInstruções para Procedures
66Arquitetura e Organização de Computadores
MIPS assembly language arithmetic statement
add $t0, $s1, $s2
sub $t0, $s1, $s2
Each arithmetic instruction performs only one operation
Each arithmetic instruction fits in 32 bits and specifies exactly three operands
destination ← source1 op source2
Those operands are all contained in the datapath’s register file ($t0,$s1,$s2) – indicated by $
Operand order is fixed (destination first)
MIPSOperações Aritméticas
67Arquitetura e Organização de Computadores
MIPS assembly language arithmetic statement
add $t0, $s1, $s2
sub $t0, $s1, $s2
Each arithmetic instruction performs only one operation
Each arithmetic instruction fits in 32 bits and specifies exactly three operands
destination ← source1 op source2
Operand order is fixed (destination first)
Those operands are all contained in the datapath’s register file ($t0,$s1,$s2) – indicated by $
MIPSOperações Aritméticas
68Arquitetura e Organização de Computadores
MIPS assembly language arithmetic statement
add $t0, $s1, $s2
sub $t0, $s1, $s2
Each arithmetic instruction performs only one operation
Each arithmetic instruction fits in 32 bits and specifies exactly three operands
destination ← source1 op source2
Operand order is fixed (destination first)
Those operands are all contained in the datapath’s register file ($t0,$s1,$s2) – indicated by $
MIPSOperações Aritméticas
69Arquitetura e Organização de Computadores
Instructions, like registers and words of data, are 32 bits long
Arithmetic Instruction Format (R format):
add $t0, $s1, $s2
op rs rt rd shamt funct
op 6-bits opcode that specifies the operation
rs 5-bits register file address of the first source operand
rt 5-bits register file address of the second source operand
rd 5-bits register file address of the result’s destination
shamt 5-bits shift amount (for shift instructions)
funct 6-bits function code augmenting the opcode
MIPSOperações Aritméticas
70Arquitetura e Organização de Computadores
addi $sp, $sp, 4 #$sp = $sp + 4
slti $t0, $s2, 15 #$t0 = 1 if $s2<15
Machine format (I format):
op rs rt 16 bit immediate I format
Small constants are used often in typical code
Possible approaches? put “typical constants” in memory and load them create hard-wired registers (like $zero) for constants like 1 have special instructions that contain constants !
The constant is kept inside the instruction itself! Immediate format limits values to the range +215–1 to -215
MIPSOperações Aritméticas
71Arquitetura e Organização de Computadores
We'd also like to be able to load a 32 bit constant into a register, for this we must use two instructions
a new "load upper immediate" instruction
lui $t0, 1010101010101010
Then must get the lower order bits right, use ori $t0, $t0, 1010101010101010
16 0 8 1010101010101010
1010101010101010
0000000000000000 1010101010101010
0000000000000000
1010101010101010 1010101010101010
MIPSConstantes muito grandes
72Arquitetura e Organização de Computadores
MIPS has two basic data transfer instructions for accessing memory
lw $t0, 4($s3) #load word from memory
sw $t0, 8($s3) #store word to memory
The data is loaded into (lw) or stored from (sw) a register in the register file – a 5 bit address
The memory address – a 32 bit address – is formed by adding the contents of the base address register to the offset value
– A 16-bit field meaning access is limited to memory locations within a region of ±213 or 8,192 words (±215 or 32,768 bytes) of the address in the base register
– Note that the offset can be positive or negative
MIPSAcesso à memória
73Arquitetura e Organização de Computadores
Load/Store Instruction Format (I format):
lw $t0, 24 ($s2)
op rs rt 16 bit offsetMemory
data word address (hex)0x000000000x000000040x000000080x0000000c
0xf f f f f f f f
$s2 0x12004094
2410 + $s2 =
0x00000018+ 0x12004094 0x120040ac
0x120040ac $t0
MIPSAcesso à memória
74Arquitetura e Organização de Computadores
Since 8-bit bytes are so useful, most architectures address individual bytes in memory
– The memory address of a word must be a multiple of 4 (alignment restriction)
Big Endian: leftmost byte is word address
IBM 360/370, Motorola 68k, MIPS, Sparc, HP PA
Little Endian: rightmost byte is word address
Intel 80x86, DEC Vax, DEC Alpha (Windows NT)
msb lsb
3 2 1 0little endian byte 0
0 1 2 3big endian byte 0
MIPSAcesso à memória
75Arquitetura e Organização de Computadores
MIPS provides special instructions to move bytes
lb $t0, 1($s3) #load byte from memory
sb $t0, 6($s3) #store byte to memory
op rs rt 16 bit offset
What 8 bits get loaded and stored?
load byte places the byte from memory in the rightmost 8 bits of the destination register
- what happens to the other bits in the register?
store byte takes the byte from the rightmost 8 bits of a register and writes it to a byte in memory
- what happens to the other bits in the memory word?
MIPSAcesso à memória
76Arquitetura e Organização de Computadores
MIPS conditional branch instructions:
bne $s0, $s1, Lbl #go to Lbl if $s0≠$s1 beq $s0, $s1, Lbl #go to Lbl if $s0=$s1
Ex: if (i==j) h = i + j;
bne $s0, $s1, Lbl1add $s3, $s0, $s1
Lbl1: ...
Instruction Format (I format):
op rs rt 16 bit offset
How is the branch destination address specified?
MIPSControle de Fluxo
de Instruções
77Arquitetura e Organização de Computadores
MIPS also has an unconditional branch instruction or jump instruction: j label #go to label
Instruction Format (J Format):
op 26-bit address
PC4
32
26
32
00
from the low order 26 bits of the jump instruction
MIPSControle de Fluxo
de Instruções
78Arquitetura e Organização de Computadores
MIPS procedure call instruction:
jal ProcedureAddress #jump and link
Saves PC+4 in register $ra to have a link to the next instruction for the procedure return
Machine format (J format):
Then can do procedure return with a
jr $ra #return
Instruction format (R format):
op 26 bit address
op rs funct
MIPSAcesso à Procedures / Funções
80Arquitetura e Organização de Computadores
f = (g+h) - (i+j)
add r6, r1, r2add r7, r3, r4sub r5, r6, r7
A[12] = h+A[8]
lw r1, 32(r3)add r4, r2, r1sw r4, 48(r3)
g = h + A[i]
add r5, r4, r4add r5, r5, r5add r5, r5, r3lw r6, 0(r5)add r1, r6, r2
if ( i==j ) goto L1f = g+h
L1: f = f-i
beq r3, r4, L1add r0, r1, r2
L1: sub r0, r0, r3
81Arquitetura e Organização de Computadores
Loop: g = g+A[i]i = i+jif ( i!=h ) goto Loop
Loop: add r6, r3, r3add r6, r6, r6add r6, r6, r5lw r7, 0(r6)add r1, r1, r7add r3, r3, r4bne r3, r2, Loop
if ( i==j )f = g+h
L1: elsef = g-h
L2:
bne r3, r4, L1add r0, r1, r2j L2
L1: sub r0, r1, r2L2:
82Arquitetura e Organização de Computadores
void swap(int v[], int k){ int temp;
temp = v[k]v[k] = v[k+1];v[k+1] = temp;
}
swap:sll $t0,$a1,2 # $t0=k*4add $t0,$t0,$a0 # $t0=v+k*4lw $t1,0($t0) # $t1=v[k]lw $t2,4($t0) # $t2=v[k+1]sw $t2,0($t0) # v[k]=$t2sw $t1,4($t0) # v[k+1]=$t1jr $ra # return
$a0 = Address of v[] $a1 = k, and Return address is in $ra
while ( save[i] == k )i = i+j
Loop: add r1, r3, r3add r1, r1, r1add r1, r1, r6lw r0, 0(r1)bne r0, r5, Exitadd r3, r3, r4j Loop
Exit:
83Arquitetura e Organização de Computadores
Mnemonic Meaning Typeadd Add Raddi Add Immediate Iand Bitwise AND Randi Bitwise AND Immediate Ibeq Branch if Equal Ibne Branch if Not Equal Ij Jump to Address Jjal Jump and Link Jjr Jump to Address in Register Rlw Load Word Inor Bitwise NOR (NOT-OR) Rxor Bitwise XOR (Exclusive-OR) Ror Bitwise OR Rsll Logical Shift Left Rsrl Logical Shift Right (0-extended) Rsra Arithmetic Shift Right (sign-extended) Rsub Subtract Rsw Store Word I
84Arquitetura e Organização de Computadores
ProcessorMemory
32 bits
230
words
read/write addr
read data
write data
word address(binary)
0…00000…01000…10000…1100
1…1100Register File
src1 addr
src2 addr
dst addr
write data
32 bits
src1data
src2data
32registers
($zero - $ra)
32
32
3232
32
32
5
5
5
PC
ALU
32 32
3232
32
0 1 2 37654
byte address(big Endian)
FetchPC = PC+4
DecodeExec
Add32
324
Add32
32branch offset
85Arquitetura e Organização de Computadores
MIPSImplementações / Traduções
Exemplo 01: Operações Aritméticas
void main(){
int a,b, c;a = 3;b = a * 2;c = a + b + 2;
}
86Arquitetura e Organização de Computadores
MIPS
Exemplo 01: Operações Aritméticas
void main(){
int a,b, c;a = 3;b = a * 2;c = a + b + 2;
}
R1R2R3R4R5R6R7R8R9R31
R0 # Código# Assembly
87Arquitetura e Organização de Computadores
MIPS
Exemplo 01: Operações Aritméticas
void main(){
int a,b, c;a = 3;b = a * 2;c = a + b + 2;
}
R1 A_Address
R2R3R4R5R6R7R8R9R31
R0 # Código# Assembly
addi r2, r0, 3sw r2, 0(r1)lw r3, 0(r1)add r3, r3, r3sw r3, 4(r1)addi r4,r0, 2add r4, r4, r3add r4, r4, r2sw r4, 8(r1)
C
B
A
88Arquitetura e Organização de Computadores
MIPS
Exemplo 02: Cálculo da média
void main (){ int NotaDaP1, NotaDaP2;
int Media;
NotaDaP1 = 8; NotaDaP2 = 6;
Media = (NotaDaP1 + NotaDaP2) / 2;
}
R1R2R3R4R5R6R7R8R9R31
R0
# Código Assembly
89Arquitetura e Organização de Computadores
MIPS
Exemplo 02: Cálculo da média
void main (){ int NotaDaP1, NotaDaP2;
int Media;
NotaDaP1 = 8; NotaDaP2 = 6;
Media = (NotaDaP1 + NotaDaP2) / 2;
}
R1 NotaDaP1_Add
R2R3R4R5 NotaDaP1_Add
R6 NotaDaP2_Add
R7 Media_Add
R8R9R31
R0
# Código Assembly
addi r2, r0, 8sw r2,0(r1)addi r3, r0, 6sw r3, 4(r1)add r4, r3, r2srl r4,1sw r4,8(r1)
Ou
addi r2, r0, 8sw r2,0(r5)addi r3, r0, 6sw r3, 0(r6)add r4, r3, r2srl r4,1sw r4,0(r7)
Media
NotaDaP2
NotaDaP1
90Arquitetura e Organização de Computadores
MIPS
Exemplo 03: Leitura de um vetor
void main() { int vetor[5]=
{1, 2, 3, 4, 5}; int x, y;
y = 1; x = vetor[0];
while (y < 5) { if (vetor[y] > x) { x = vetor[y]; } y++; } return 0; }
R1R2R3R4R5R6R7R8R9R31
R0
0050004000300020001
0
91Arquitetura e Organização de Computadores
MIPS
Exemplo 03: Leitura de um vetor
void main() { int vetor[5]=
{1, 2, 3, 4, 5}; int x, y;
y = 1; x = vetor[0];
while (y < 5) { if (vetor[y] = x) { x = vetor[y]; } y++; } return 0; }
R1 Vetor_Address
R2 X_Address
R3 Y_Address
R4 YR5 XR6R7R8R9 5
R31
R0 Zero
# Código# Assembly
addi r4, r0, 1 sw r4, 0(r3) lw r5, 0(r1) sw r5, 0(r2) addi r9, r0, 5wh: beq r9,r4,exit lw r7, r1, r4 lw r8, 0(r7) bne r8,r5,notif addi r5,r8, r0
notif: addi r4,r4,1 j wh
exit:
0050004000300020001
0
Y
X
92Arquitetura e Organização de Computadores
MIPS
Exemplo 04: Busca em um vetor tamanho n
int busca( int x, int n, int v[]){ int k; k = n-1; while (k >= 0 && v[k] != x) K = k - 1; return k;}
/*A função recebe x, n >= 0 e v e devolve um índice k em 0..n-1 tal que x == v[k]. Se tal k não existe, devolve -1.
*/
R1R2R3R4R5R6R7R8R9R31
R0
# Código Assembly
93Arquitetura e Organização de Computadores
MIPS
Exemplo 05: Multiplicação por 2, n vezes
R1R2R3R4R5R6R7R8R9R31
R0
# Código Assembly
94Arquitetura e Organização de Computadores
MIPS
Exemplo 06: Divisão por 2, n vezes
R1R2R3R4R5R6R7R8R9R31
R0
# Código Assembly
95Arquitetura e Organização de Computadores
MIPS
Exemplo 07: Multiplicação m*n
R1R2R3R4R5R6R7R8R9R31
R0
# Código Assembly
96Arquitetura e Organização de Computadores
MIPS
Exemplo 08: Fatorial de n (n!)
main(){
int n, fat;int num;
if(num>=0) { fat=1; n=num; while(n>0) { fat = fat * n; n = n -1; }
}}
R1R2R3R4R5R6R7R8R9R31
R0
# Código Assembly
97Arquitetura e Organização de Computadores
MIPS
Exemplo 09: Fibonacci até n
void main(){
int a, b, auxiliar, i, n;a = 0;b = 1;
for(i = 0; i < n; i++){
auxiliar = a + b;a = b;b = auxiliar;
}}
R1R2R3R4R5R6R7R8R9R31
R0
# Código Assembly