You are on page 1of 28

Departamento de Sistemas Telemticos y Computacin

(GSyC)

MARS
MIPS Assembler and Runtime Simulator

Katia Leal Algara


Septiembre 2012
katia@gsyc.es
http://gsyc.escet.urjc.es/~katia/
GSyC 2012 - MARS

Introduccin

Qu es MARS?

!
q Es un entorno de desarrollo
interactivo (IDE) para la
programacin en el lenguaje
ensamblador MIPS!
q Orientado a la enseanza para
usarse junto con el Computer
Organization and Design de
Patterson y Hennessy!

GSyC 2012 - MARS

Caractersticas de MARS

Features

!
q Control de la velocidad de ejecucin!
q 32 registros visibles de forma simultnea!
q Modificacin de los valores en registros y
en memoria!
q Posibilidad de mostrar los datos en
decimal o en hexadecimal!
q Navegacin por la memoria!
q Editor y ensamblador integrados en el
propio IDE!

GSyC 2012 - MARS

Caractersticas de MARS

Repertorio de instrucciones

!
q Ensambla y simula casi todas las
instrucciones documentadas en el libro de
texto Computer Organization and Design,
Fourth Edition by Patterson and Hennessy,
Elsevier - Morgan Kaufmann, 2009!
q Todas las instrucciones bsicas,
pseudoinstrucciones, directivas y llamadas
al sistemas descritas en el Apndice B
estn implementadas

GSyC 2012 - MARS

ori

Set Less Than

slt

R R[rd] = (R[rs] < R[rt]) ? 1 : 0

IPS Reference Data Card (Green Card) 1. Pull along perforation


separate cardData
2. Fold
bottom
side (columns
3 and 4)
MIPStoReference
1. together
Pull along
Card
(Green
Card)

M I P S Reference Data
sll

dhex

0 / 2ahex

Store FP Single
Shift Left Logical
Store FP
Shift Right Logical
Double

swc1

sll

M[R[rs]+SignExtImm] = F[rt]
M[R[rs]+SignExtImm] = F[rt];

R R[rd] = R[rt] << shamt

(2) 39/--/--/-(2)

0 / 00hex

31

26 25

21 20

sdc1 R I R[rd] = R[rt] >> shamt


3d/--/--/-srl
PSEUDOINSTRUCTION SET
M[R[rs]+SignExtImm+4] = F[rt+1]0 / 02hex

M[R[rs]+SignExtImm](7:0) =

NAME

28hex
sb
Store Byte
I
R[rt] = (R[rs] < SignExtImm)? 1 : 0 (2) ahex
FLOATING-POINT
INSTRUCTION
FORMATS
R[rt](7:0)
(2)
Branch Less Than
R[rt] = (R[rs] < SignExtImm)
M[R[rs]+SignExtImm]
opcode sc
fmt
ft
fs= R[rt];
fd 38hex funct Branch Greater Than
bhex
StoreFR
Conditional
I
I
Branch Less Than or Equal
R[rt] = (atomic) ? 1 : 0 (2,7)
?1:0
(2,6)
31 SET
26 25
21 20 OPCODE
16 15
11 10
6 5
0
1
ARITHMETIC CORE INSTRUCTION
Branch
Greater Than or Equal
2
M[R[rs]+SignExtImm](15:0)
=
0
/
2b
R R[rd] = (R[rs] < R[rt]) ? 1 : 0
(6)
29hex
hex
StoreFI
Halfword
I
/ FMT
Load
Immediate
opcode sh
fmt
ft /FT
immediate
R[rt](15:0)
(2)
FOR/ FUNCT
Move
0 / 00hex
R R[rd] = R[rt] << shamt
31
26 25
21 20
16 15
0
sw
I M[R[rs]+SignExtImm]
= R[rt]
(2) 2bhex
NAME, MNEMONIC Store
MATWord
OPERATION
(Hex)
REGISTER
NAME, NUMBER, U
0 /FP02True
FI
11/8/1/-if(FPcond)PC=PC+4+BranchAddr
(4)
R R[rd] = R[rt] >> shamtOPCODE Branch On
hex bc1t
0
/
22
sub
PSEUDOINSTRUCTION
SET
Subtract
R R[rd] = R[rs] - R[rt]
(1)

Caractersticas de MARS
Shift Left Logical

(3)

Shift
Right Logical
CORE
INSTRUCTION
SET srl
FOR/ FUNCT
M[R[rs]+SignExtImm](7:0)
=
sb
Store Byte
I
NAME,
MNEMONIC MAT
OPERATION
(in Verilog)
(Hex)
R[rt](7:0)
0
/
20
add
Add
R R[rd] = R[rs] + R[rt]
(1)
hex
M[R[rs]+SignExtImm] =8 R[rt];
addi
AddStore
Immediate
I R[rt] = R[rs]
(1,2)
sc
Conditional
I + SignExtImm
hex

hex

Branch On FP False bc1f FI if(!FPcond)PC=PC+4+BranchAddr(4) 11/8/0/-NAME


MNEMONIC
OPERATION
0 / 23hex
subu
Unsigned
R R[rd]
= R[rs]
- R[rt]
R Lo=R[rs]/R[rt];
0/--/--/1a
Divide
Hi=R[rs]%R[rt]
28hex div Subtract
blt
(2) Unsigned
if(R[rs]<R[rt]) PC = Label
Less Than
divu
Divide
RBranch
(1) May cause overflow
exception
Lo=R[rs]/R[rt];
Hi=R[rs]%R[rt]
(6) 0/--/--/1b
bgt
if(R[rs]>R[rt])
PC}= Label
Branch
Than
add.s FR
FP Add Single
F[fd ]=Greater
F[fs] + F[ft]
(2)
SignExtImm = { 11/10/--/0
16{immediate[15]},
immediate
Add 38hex
{F[fd],F[fd+1]}
=(3)
{F[fs],F[fs+1]}
ble
if(R[rs]<=R[rt])
Less Than
or
Equal += { 11/11/--/0
4 PC = Label
ZeroExtImm
16{1b0},
immediate
}
R[rt] = (atomic) ? 1 : 0 FP(2,7)
754 FLOATING-POINT
add.d IEEE
3
FRBranch
9
addiu I R[rt] = R[rs] + SignExtImm
Add Imm. Unsigned
(2)
Double
{F[ft],F[ft+1]}
hex
BranchAddr
2b0
}
bge
if(R[rs]>=R[rt])
PC
= Label
Branch Greater (4)
Than
or Equal = { 14{immediate[15]},
OPCODES,
BASE CONVERSION,
ASCII SYMBOLS
IEEEimmediate,
754 Symbols
M[R[rs]+SignExtImm](15:0)
= FP Compare29Single c.x.s* STANDARD
FR FPcond = (F[fs] op
11/10/--/y
? 1 : 0 = { PC+4[31:28],
0 /ASCII
21hex
addu (1)sh
AddStore
Unsigned
R MIPS
R[rd] =(2)
+ R[rt]
(5)F[ft])
JumpAddr
address,
2b0 }
Halfword
IR[rs]
MIPS
MIPS
HexaHexa- ASCII
li
R[rd]
=
immediate
Load
Immediate
hex
Exponent
Fraction
Object
Deci- R[rt](15:0)Deci(2)
FP Compare
FPcond = ({F[fs],F[fs+1]}
op considered
(6)
unsigned
(vs.0 2s comp.) 0
opcode
funct& R[rt]
Binary
deci-0 / Chardeci- Char- c.x.d* (-1)
(Exponent
- Bias) 11/11/--/y
S
24hex
FRMove
and
And
Rfunct
R[rd] = R[rs]
move
R[rd]
= R[rs]
0numbers
(1 + Fraction)
2Operands
mal
Double 2b
{F[ft],F[ft+1]})
?1:0
sw
Store Word (31:26)
I (5:0)
M[R[rs]+SignExtImm]
R[rt] mal
(2)
mal =c acter
mal acter
(7)
Atomic
test&set pair; R[rt] = 10if pair atomic,
atomic
hex
andi
And Immediate
I(5:0)
R[rt] = R[rs]
& ZeroExtImm
(3)
0 0 if not
Denorm
eq
,
lt
,
or
le
)
(op
is
==,
<,
or
<=)
(
y
is
32,
3c,
or
3e)
*
(x
is
hex
where Single
Precision
Bias = 127,USE,
sll
add.f
00 0000
0
0 NUL
64
40 Single
(1)
REGISTER
NAME,
NUMBER,
CALL CONVENTION
div.s
FP Divide
FR F[fd]
11/10/--/3
= F[fs] / F[ft] FORMATS
0 / 22@
BASIC
INSTRUCTION
subif(R[rs]==R[rt])
Subtract
R
R[rd]
=
R[rs]
R[rt]
(1)
1
to
MAX
1
anything

Fl.
Pt. Num.
hex
sub
.f
00
0001
1
1
SOH
65
41
A
Double
Precision
Bias
=
1023.
4hex
beq
Branch On Equal
I
PRESERVEDACROSS
FP Divide
{F[fd],F[fd+1]} = {F[fs],F[fs+1]} /
PC=PC+4+BranchAddr
j
srl
USE rdMAX shamt 0
mul
0010 - R[rt]
2 (4) 2 STX
66
420 / 23Bhex div.d FRR NAME
opcodeNUMBER
rs
rt 11/11/--/3
funct
subu
Subtract Unsigned
R .fR[rd]00
= R[rs]
Double
{F[ft],F[ft+1]}
A CALL?
if(R[rs]!=R[rt])
jal
sra
.f
00 0011
3
3 5hex
ETX
67
43
C
MAX
06 5
NaN 0
Single
Precision
31 = F[fs]
26 25 and 21 20
16 15
11 10
bne
Branch On Not Equal
I May div
FR F[fd]
11/10/--/2
FP Multiply Single mul.s IEEE
* F[ft]
(1)
cause.f overflow
exception
PC=PC+4+BranchAddr
$zero
0
The Constant
Value
N.A.= 2047
beq
sllv
sqrt
00 0100
4 (4) 4 EOT
68
44
D
S.P.0MAX immediate
= 255, D.P. MAX
I
opcode
rs
rt
Double
Precision
Formats:
FP
Multiply
{F[fd],F[fd+1]}
=
{F[fs],F[fs+1]}
*
(2)
SignExtImm
= 00
{ 16{immediate[15]},
}45
j
bne
Jump
J PC=JumpAddr
abs.f
0101
5 (5) 5 2ENQ
69
E mul.d FR
11/11/--/2
hex immediate
$at
1
Assembler
Temporary
No
Double
31S
26 25{F[ft],F[ft+1]}
21 20
16 15 Fraction
0
Exponent
blez
srlv
mov.f
0110
6 immediate
46
F
(3)
ZeroExtImm
= 00
{ 16{1b0},
} 70
jal
Jump And Link
J R[31]=PC+8;PC=JumpAddr
(5) 6 3ACK
hex
11/10/--/1
FP Subtract Single sub.s FR F[fd]=F[fs] - F[ft]

NAME

NUMBER

$zero
$at

0
1

$v0-$v1

2-3

$a0-$a3
$t0-$t7
$s0-$s7
$t8-$t9
$k0-$k1
$gp
$sp
$fp
$ra

4-7
8-15
16-23
24-25
26-27
28
29
30
31

(Green Card) 1. Pull along perforation to separate card 2. Fold bottom side (columns 3 and 4) together

Set Less Than Imm. slti


Set Less Than Imm.
sltiu
Unsigned
Set Less Than Unsig. sltu

R[rt] = R[rs] | ZeroExtImm

MIPS Reference Data Card (Green Card) 1. Pull

perforati

Or Immediate

The Co
Assem
Values
and Ex
Argum
Tempo
Saved
Tempo
Reserv
Global
Stack P
Frame
Return

Values for Function


Results
bgtz
srav
J $v0-$v1
address
neg.f
0111
7
7 BEL
71
47
31opcode
30
23 22
0
(4)
BranchAddr
= {0014{immediate[15]},
immediate,
2b0 }G
No
0 / 08hex
FP Subtract
{F[fd],F[fd+1]} =2-3
{F[fs],F[fs+1]}
jr
R PC=R[rs]
and Expression
Evaluation
addi
jr
00
1000
8
8
BS
72
48
H
sub.d FR
11/11/--/1
31
26
25
0
(5)
JumpAddr
=
{
PC+4[31:28],
address,
2b0
}
S
Exponent
Fraction
Double
{F[ft],F[ft+1]}
R[rt]={24b0,M[R[rs]
jalr
00 1001
9
9 24 HT
73
49
I
$a0-$a3
4-7 Inc.,Arguments
No
Copyright
2009
by Elsevier,
All
rights
reserved. From Patterson and Hennessy,
Computer Organization and Design, 4th
lbu
Load Byte Unsignedaddiu
I Operands considered
hex (vs.
lwc1
I
31/--/--/-Load
FP
Single
F[rt]=M[R[rs]+SignExtImm]
(2)

63
62
52
51
0
(6)
unsigned
numbers
2
s
comp.)
+SignExtImm](7:0)}
slti
movz
00 1010 10 (2) a LF
74
4a
J
$t0-$t7
8-15
Temporaries
No
Load
F[rt]=M[R[rs]+SignExtImm];
(2)
ALLOCATION
STACK FRAME
(7) R[rt]={16b0,M[R[rs]
Atomic test&set00pair;
atomic,
0 ifFP4b
not atomic
sltiu movn
1011R[rt]
11= 1 ifbpair
VT
75
K
Load Halfword
ldc1 MEMORY
I
35/--/--/-25hex
lhu
I
Double
F[rt+1]=M[R[rs]+SignExtImm+4]
Higher
$s0-$s7
16-23 Stack
Saved Temporaries
Yes
andi
syscall round.w
Unsigned
+SignExtImm](15:0)}
.f 00 1100 12 (2) c FF
76
4c
L
...
BASIC INSTRUCTION
FORMATS .f 00 1101 13
mfhi $sp
R R[rd] =7fff
0 /--/--/10
Move From
Hi fffchex
Memory
ori
break
CR
77
4d HiM
ll
Load Linked
I R[rt] =trunc.w
M[R[rs]+SignExtImm]
(2,7) d 30hex
Argument
6
$t8-$t9
24-25
Temporaries
No
mflo
Move From
LoN
R R[rd] = Lo
0 /--/--/12
Addresses
xori
ceil.w.f rt
00 1110 14rd e f SO
78
4efunct
R
opcode
rs
shamt
Argument
5
lui
Load Upper Imm.
I R[rt] = {imm, 16b0}
mfc0
$k0-$k1
Reserved for
OS$fp
Kernel
No
Move From
R R[rd]
10 /0/--/0
= CR[rs] 26-27
lui
sync
floor.w.f 00 1111
15
f hexSI
79
4f Control
O
31
26I 25 R[rt] = M[R[rs]+SignExtImm]
21 20
16 15
11 10
6 5
0 mult R {Hi,Lo} = R[rs] * R[rt]
Multiply
0/--/--/18
lw
Load Word
mfhi
hex
01 0000 16 (2)10 23DLE
80
50
P
$gp
28
Global Pointer
Saved Registers Yes
Multiply51Unsigned
= R[rs] * R[rt]
(6) 0/--/--/19
I
opcode
rs = ~ (R[rs] | R[rt])
rt
immediate
mthi
(2)
01 0001 17
110 / 27
DC1
81
Q multu R {Hi,Lo}
Stack
nor
Nor
R R[rd]
hex
Dynamic
Data
$sp
29
Stack
Pointer
Yes
sra
Shift Right
Arith.
R
0/--/--/3
R[rd]
=
R[rt]
>>>
shamt
mflo
movz
.f
01
0010
18
12
DC2
82
52
R
Grows
$gp 1000 8000hex
31
26R25 R[rd] = R[rs]
21 20| R[rt]
16 15
0
0 / 25hex
or
Or
$fp
30 = F[rt]
Frame(2)
Pointer
Yes
swc1
Store FP53SingleS
I M[R[rs]+SignExtImm]
39/--/--/-mtlo
movn.f
01 0011 19
13 DC3
83

Jump Register

Static
Data
address
(3)14 dhex
Local Variables Yes
Store FP54
M[R[rs]+SignExtImm]
= F[rt];
20
DC4
84
T
$ra
Return(2)
Address
sdc1
I
3d/--/--/-1000 0000hex31
Double
M[R[rs]+SignExtImm+4]
=
F[rt+1]
21
15
NAK
85
55
U
0
0
/
2a
slt
$sp
hex
Text 4th ed.
01 0110
22 (2)16 Patterson
86
56
V Computer Organization and Design,
2009slti
by Elsevier,
All<rights
reserved.
and Hennessy,
aSYN
Lower
Set Copyright
Less Than Imm.
I R[rt]Inc.,
= (R[rs]
SignExtImm)?
1 : 0From
FLOATING-POINT
FORMATS
pc
0040
0000hex
01 0111 23
17 hex
ETB
87
57
W INSTRUCTION
Memory
Set Less Than Imm.
R[rt] = (R[rs] < SignExtImm)
FR
opcode
fmt
ft
fs
fd
funct
01 1000 24
18 bCAN
88
58
X
sltiu mult
I
Addresses
Unsigned
? 1 : 0 01 1001 25 (2,6)19 hex
Reserved
21 20
16 015
11
10
6 5
0
multu
EM
89
5931 Y 26 25
hex
Set Less Than Unsig. sltu div
R R[rd] = (R[rs] < R[rt])
? 1 : 0 26 (6)1a0 / 2b
01 1010
SUB
90 FI 5a opcode
Z
hex
fmt
ft
immediate
divu
01 1011 27
1b0 / 00
ESC
91
5b31 [ 26 25 DATA
ALIGNMENT
sll
Shift Left Logical
R R[rd] = R[rt] << shamt
21 20
16 15
0
hex
01 1100 28
1c0 / 02FS
92
5c
\
Shift Right Logical srl
R R[rd] = R[rt] >> shamt
Double Word
hex
PSEUDOINSTRUCTION
SET
01 1101 29
1d GS
93
5d
]
M[R[rs]+SignExtImm](7:0)
MNEMONIC Word OPERATION
Word
01 1110 = 30
1e 28hex
RS
94
5e
^NAME
sb
Store Byte
I
blt
R[rt](7:0)
if(R[rs]<R[rt]) PC = Label
01 1111 31 (2) 1f US
95 Branch
5f Less
_ Than
Halfword
Halfword
Halfword
Halfword
bgt
if(R[rs]>R[rt])
PC
=
Label
Branch
Greater
Than
M[R[rs]+SignExtImm]
= R[rt]; 32
add
cvt.s.f
10 0000
20 38Space 96
60

Store Conditional lbsc


I
ble
if(R[rs]<=R[rt])
= Label
R[rt].f= (atomic)
? 1 : 033 (2,7)21 hex
Byte
Byte
Byte PC
Byte
Byte Byte
Byte
Byte
lh
addu
cvt.d
10 0001
!
97 Branch
61 Less
a Than or Equal
lwl
sub M[R[rs]+SignExtImm](15:0)
2
3PC = Label
4
5
6
7
10 0010 = 34
22 29 "
98 Branch
62 Greater
b Than or Equal 0 bge 1 if(R[rs]>=R[rt])
sh
Store Halfword
I
li
R[rd]
=
immediate
Load
Immediate
hex
Value
of
three
least
significant
bits
of
byte
address
(Big
Endian)
lw
subu
10R[rt](15:0)
0011 35 (2)23
#
99
63
c
move
R[rd] = R[rs]
lbu
and
cvt.w.f
10 0100
$
100 Move
64
d
sw
Store Word
I M[R[rs]+SignExtImm]
= R[rt] 36 (2)24 2bhex
EXCEPTION CONTROL REGISTERS: CAUSE AND STATUS
lhu
or
10 0101 37
25 %
101
65
e
REGISTER NAME,
NUMBER, USE,
CALL CONVENTION
0
/
22
B
Interrupt
Exception
sub
Subtract
R R[rd] = R[rs] - R[rt]
hex
lwr
xor
10 0110 38 (1)26
&
102
66
f
PRESERVED ACROSS
D USE
NAME
Mask
Code
Subtract Unsigned subu nor
R R[rd] = R[rs] - R[rt]10 0111 39
270 / 23hex 103
67
g NUMBER
A CALL?
31
15
8
6
2
sb(1) May cause overflow exception
10 1000 40
28
(
104
68
$zero h
0
The Constant
Value 0
N.A.
}
Pending
U
E I
sh(2) SignExtImm = { 16{immediate[15]},
10 1001 immediate
41
29
)
105
69$at i
1
Assembler Temporary
No
(3) ZeroExtImm
= { 16{1b0}, immediate
swl
slt
10 1010 } 42
2a
*
106
6a
j
Interrupt
M
L E
Values for Function Results
2b0 }+
2-3
No
sw(4) BranchAddr
sltu = { 14{immediate[15]},
10 1011immediate,
43
2b
107 $v0-$v1
6b
k
15
8
4
1 0
and Expression Evaluation
(5) JumpAddr = { PC+4[31:28],
10address,
1100 2b0
44 } 2c
,
108
6c
l
BD
= Branch Delay, UM = User Mode,
EL = Exception Level, IE =Interrupt Enable
$a0-$a3
4-7
Arguments
No
(6) Operands considered unsigned
comp.) 10numbers
1101 (vs.
45 2s 2d
109
6d
m
EXCEPTION
$t0-$t7
Temporaries CODES
No
(7) Atomic test&set pair; R[rt] = 10
1 if1110
pair atomic,
not atomic
swr
46 0 if2e
.
110
6e
n 8-15
Number
Name
Cause of Exception
Number Name Cause of Exception
$s0-$s7
Temporaries
Yes
cache
10 1111 47
2f
/
111
6f
o 16-23 Saved
BASIC INSTRUCTION
FORMATS
0
Int
Interrupt (hardware)
9
Bp
Breakpoint Exception
$t8-$t9
No
ll
tge
c.f.f
11 0000 48
30
0
112
70
p 24-25 Temporaries
R
opcode
rs
rt
rd
shamt
funct
Address Error Exception
Reserved Instruction
for
OS Kernel
No
lwc1
tgeu
c.un.f
11 0001 49
31
1
113 $k0-$k1
71
q 26-27 Reserved
4
AdEL
10
RI
31
26 25
21 20
16 15
10
(load or instructionYes
fetch)
Exception
lwc2
tlt
c.eq.f
11 11
0010
50 6 5 32
2 0 114
72
$gp r
28
Global Pointer
I
opcode pref rs tltu
rtc.ueq.f
immediate
Address Error Exception
Coprocessor
11 0011
51
33
3
115
73$sp s
29
Stack5Pointer
Yes
AdES
11
CpU
31
26 25
21 20
16 15
teq
(store)
Unimplemented
c.olt
.f
11 0100 52
34
4 0 116
74$fp t
30
Frame Pointer
Yes
J
opcode ldc1
c.ult.f address
11 0101 53
35
5
117
75$ra u
Bus Error onYes
Arithmetic Overflow
31
Return
Address
6
IBE
12
Ov

J
Or Immediate

Set Less Than 31

opcode
ori
I R[rt] = R[rs] | ZeroExtImm
01 0100

01 0101
26R25 R[rd] = (R[rs] < R[rt])
?1:0

GSyC 2012 - MARS

Caractersticas de MARS

Llamadas al sistema
!
q Varios servicios de sistema, principalmente para
la realizacin de operaciones de entrada/salida,
estn disponibles:!
q
q
q
q
q
q
q
q
q
q

print integer !
print float!
print double!
print string !
sbrk (allocate heap memory) !
exit (terminate execution)!
print character !
read character!
MIDI out!
!

(http://courses.missouristate.edu/KenVollmar/MARS/Help/SyscallHelp.html)!
GSyC 2012 - MARS

Caractersticas de MARS

Ventana de edicin: similar al Notepad de Windows

GSyC 2012 - MARS

Caractersticas de MARS

Ventana de ejecucin

!
q Para ensamblar un programa hay que
pinchar en el icono! !
q Si no hay errores de ensamblado, se abre
la ventana de ejecucin!
q En caso de que el ensamblado falle, se
muestra una ventana con los errores y su
correspondiente nmero de lnea!

GSyC 2012 - MARS

Caractersticas de MARS

Ventana de ejecucin

qMuestra varias ventanas!


qVentana Text Segment: !
q Muestra el cdigo fuente y el binario!
q Se puede incluir un breakpoint en cualquier
instruccin marcando el check box
correspondiente!
q La siguiente instruccin en ser ejecutada
aparece resaltada!

GSyC 2012 - MARS

Caractersticas de MARS

Ventana de ejecucin

GSyC 2012 - MARS

Caractersticas de MARS

Ventana de ejecucin
q Ventana Data Segment:!
q Datos almacenados por el programa!
q Controles para mostrar el contenido de partes especiales de la
memoria, como la pila o el heap!
q Posibilidad de mostrar el contenido de las posiciones de
memoria en hexadecimal o en decimal!

q Ventana Labels: tabla de smbolos!


q Muestra el valor de las etiquetas creadas en por el programa!

q Ventana Registers:!
q Muestra el contenido de los registro, tanto en decimal como en
hexadecimal!
q Existen ventanas separadas para los registros de propsito
general, los registros de coma flotante del Coprocessor 1 y los
registros de excepcin del Coprocessor 0!

GSyC 2012 - MARS

10

Caractersticas de MARS

Ventana de ejecucin

Figure -2. MARS


MARS execution window is active ( Execute tab is foremost and the execution toolbar icons are active).
GSyC 2012
leftmost column. When stepping through program execution
manually or at reduced run speeds, the next instruction to be
executed is highlighted.

Another permanent display is the console window on the lower


portion of the screen. It includes two tabs, one for MARS
messages such as assembly errors and another for runtime input

11

Caractersticas de MARS

Ventana de ejecucin

q Consola!
q Mensajes de MARS, mensajes de error de
ensamblado
q Mensajes de entrada/salida generados en
tiempo de ejecucin por las llamadas al sistema
q Estas ventanas se activan cuando se escribe
texto sobre ellas

GSyC 2012 - MARS

12

Caractersticas de MARS

Instrucciones soportadas

q El listado completo de instrucciones,


pseudo instrucciones, llamadas al sistema,
directivas y excepciones soportadas se
puede consultar en la ayuda de MARS
(Help-F1)!
qAs mismo, tambin se puede consultar el
Apndice B del Computer organization and
design. The hardware/software interface, 4
edition. Morgan Kaufmann, 2012!
q El mismo apndice se puede descargar de forma
gratuita en:
http://www.cs.wisc.edu/~larus/HP_AppA.pdf!
GSyC 2012 - MARS

13

Caractersticas de MARS

Instrucciones soportadas

GSyC 2012 - MARS

14

Programacin en ensamblador

Cundo programar en ensamblador?


q Cuando el tamao o la velocidad de un programa sean
crticos!
q En la mayora de sistemas embebidos, es necesaria una
respuesta rpida y fiable!
q Es difcil para los programadores asegurar que un programa
en lenguaje de alto nivel responde en un intervalo de tiempo
determinado: tiempo de respuesta!
q Reducir el tamao de un programa reduce costes, puesto que
se necesitan menos pastilla de memoria!
q Se pueden identificar las partes crticas de un programa,
aquellas en las que se emplea ms tiempo, para
recodificarlas en lenguaje ensamblador!
q Programar en lenguaje ensamblador nos permite explotar
instrucciones especializadas: copia de strings!
q Cuando no hay disponible un lenguaje de programacin para
un ordenador particular!
GSyC 2012 - MARS

15

Programacin en ensamblador

Ensambladores
q Un programa ensamblador traduce un fichero con sentencias
en lenguaje ensamblador en un fichero con instrucciones
mquina y datos binarios!
q El proceso de traduccin tienen dos partes:!
1. Localizar posiciones de memoria etiquetadas, de tal forma
que la direccin de un nombre simblico se conozca cuando
las instrucciones se traduzcan!
2. Traducir cada sentencia en ensamblador combinando
cdigos de operacin, identificadores de registros y etiquetas
en una instruccin legal!
q El cdigo objeto o fichero objeto no puede ser ejecutado
puesto que incluye referencias a datos o procedimientos en
otros ficheros!
q Variables externas o globales!
q Variables locales!

GSyC 2012 - MARS

16

A-8

Appendix A

Assemblers, Linkers, and the SPIM Simulator

Programacin en ensamblador
#include <stdio.h>
main (int
char *argv[])
Linkadores
o argc,
enlazadores
{
int

int i;
q El programa
depende de otra herramienta, el
int sum ensamblador
= 0;
linkador!
for (i = 0; i <= 100; i = i + 1) sum = sum + i * i;
printf ("The sum from 0 .. 100 is %d\n", sum);
q El linkador
combina un conjunto de ficheros objeto y libreras
}
en un fichero ejecutable resolviendo las referencias a
FIGURE A.1.5 The routine written in the C programming language.
etiquetas externas!

High-level language program

Program

Compiler

Assembler

Linker

Computer

Assembly language program

FIGURE A.1.6
compiler.

Assembly language either is written by a programmer or is the output of a

tainty about the time cost of operations, programmers may find it difficult to
ensure that a high-level language program responds within a definite time intervalsay, 1 millisecond after a sensor detects that a tire is skidding. An assembly
language programmer, on the other hand, has tight control over which instrucexecute. In addition, in embedded applications, reducing a programs size,
GSyC 2012 -tions
MARS
so that it fits in fewer memory chips, reduces the cost of the embedded computer.
A hybrid approach, in which most of a program is written in a high-level language and time-critical sections are written in assembly language, builds on the

17

Programacin en ensamblador
Appendix A Assemblers, Linkers, and the SPIM Simulator

Formato de un fichero objeto en UNIX


Object file
header

Text
segment

Data
segment

Relocation
information

Symbol
table

Debugging
information

FIGURE A.2.1 Object file. A UNIX assembler produces an object file with six distinct sections.

q Cabecera: contiene el tamao y la posicin del resto de


campos
del fichero!
gram. This
relocation
information is necessary because the assembler does not
q which
Text memory
segment:
contiene
el cdigo
lenguaje
mquina
know
locations
a procedure
or en
piece
of data will
occupyde
after it is
las rutinas
fichero
fuente!
linked with
the rest del
of the
program.
Procedures and data from a file are stored in a
contiguous
of memory,
but thelaassembler
does notbinaria
know where
this memq Datapiece
segment:
contiene
representacin
de los
ory willdatos
be located.
The assembler
also por
passes
some symbol table entries to the
inicializados
utilizados
el programa!
linker.
In particular, the
assembler must record
which sobre
external
symbols are
q Informacin
de realojamiento:
informacin
aquellas
definedinstrucciones
in a file and what
unresolved
references occur
in a file.
y datos
que dependen
de direcciones
absolutas!
q Tabla de smbolos: asocia direcciones con etiquetas
externas y contiene una lista de referencias sin resolver!
Elaboration: For convenience, assemblers assume each file starts at the same
q Informacin
de depuracin:
informacin
el debugger
! the
address
(for example, location
0) with the expectation
that para
the linker
will relocate
code and data when they are assigned locations in memory. The assembler produces
GSyC 2012
- MARS which contains an entry describing each instruction or data 18
relocation
information,
word
in the file that references an absolute address. On MIPS, only the subroutine call, load,
and store instructions reference absolute addresses. Instructions that use PC-relative

Programacin en ensamblador
A.5 Memory Usage

Gestin
de la memoria
!
q Los sistemas basados en el procesador MIPS dividen la memoria en
tres partes!
7fff fffchex
Stack segment

Dynamic data
10000000hex

Static data

Data segment
Text segment

400000hex

Reserved

q Limitations of MARS as of Release 4.2 include memory segments

FIGURE A.5.1
Layout
memory.
(text,
data,ofstack,
kernel text, kernel data) are limited to 4MB each

starting at their respective base addresses!


GSyC 2012 - MARS

19

A MIPS processor consists of an integer processing unit (the CPU) and a collection of coprocessors that perform ancillary tasks or operate on other types of data
such as floating-point numbers (see Figure A.10.1). SPIM simulates two coprocesProgramacin
en 0ensamblador
sors. Coprocessor
handles exceptions and interrupts. Coprocessor 1 is the floating-point unit. SPIM simulates most aspects of this unit.

Modos
de direccionamiento
Addressing
Modes
!

MIPS
is a load-store
architecture, which
means that only load and lo
store
instrucq
MIPS
es una arquitectura
carga-almacenamiento,
que
tions access memory. Computation instructions operate only on values in regissignifica que slo las instrucciones de carga y
ters. The bare machine provides only one memory-addressing mode: c(rx),
almacenamiento
pueden
acceder
a memoria!
which
uses the sum of the
immediate
c and register rx as the address. The virq
instrucciones
computacionales
operan
slo
datos
tualLas
machine
provides the
following addressing
modes
for sobre
load and
store
instructions:
almacenados en registros!
Format

Address computation

(register)

contents of register

imm

immediate

imm (register)

immediate + contents of register

label

address of label

label imm

address of label + or immediate

label imm (register)

address of label + or (immediate + contents of register)

Most load and store instructions operate only on aligned data. A quantity is
aligned if its memory address is a multiple of its size in bytes. Therefore, a halfGSyC 2012 - MARS

20

struction
expands to between
several machine
When youissingle-step
or examThe
correspondence
the twoinstructions.
sets of instructions
fairly simple
since
ine memory,
instructions
that you to
seefill
aredelay
different
SPIM
does notthe
reorganize
instructions
slots.from the source program.
The correspondence
between
the two sets of instructions is fairly simple since
Programacin
en ensamblador
SPIM does not reorganize instructions to fill delay slots.

Byte Order

Ordenacin
de los bytes
Processors
can
! number bytes within a word so the byte with the lowest number is
Byte Order
q Losorbytes
de unaone.
palabra
pueden enumerar!
either the leftmost
rightmost
These
convention
used by a machine is called
Processors can number bytes within a word so the byte with the lowest number is
its byte order. q
MIPS
processors que
can utiliza
operate
eithersebig-endian
La convencin
unawith
mquina
denomina or little-endian
either the leftmost
or rightmost
The convention used by a machine is called
ordenacin
losone.
bytes!
byte order. For example,
in adebig-endian
machine, the directive .byte 0, 1, 2, 3
its byte order.qMIPS
processors
can
operate
with either
big-endian
or little-endian
El
procesador
MIPS
puede
operar
tanto
en
big-endian
como
would result in a memory word containing
byte order. For example,
in a big-endian
machine, the directive .byte 0, 1, 2, 3
en little-endian
!
would resultq
in Por
a memory
word
containing
ejemplo,
en una
mquina big-endian, la directiva .byte
Byte
0, 1, 2, 3 resulta en
que# una palabra de memoria
contiene:!
0

1Byte 2#

while in a little-endian machine, the word would contain


q Mientrasmachine,
que su lathe
mquina
fuera little-endian
la palabra
while in a little-endian
word would
contain
contendra:!

GSyC 2012 - MARS

Byte #
3

2Byte 1#

21

SPIM operates with both byte orders. SPIMs byte order is the same as the byte

Sintaxis del ensamblador

Sintaxis del ensamblador


q Comentarios !
q #!
q Todo lo que hay despus de este carcter se ignora!

q Etiquetas!
q Se utilizan para referirse a posiciones de memoria o a
instrucciones!
q Son case insensitive!
q Slo se puede utilizar una etiqueta por lnea!
q Van seguidas de :!

qSecciones ms importantes:

!!

q .data
q .text
GSyC 2012 - MARS

22

Sintaxis del ensamblador

Seccin .data <addr>

qComandos que especifican cmo se debe


rellenar la memoria antes de que el
programa comience su ejecucin!
qEl formato de un comando .data es:
[label:] .datatype val1 [,val2 [, ]]

qTipos de datos representados:!


q.ascii str
Acepta strings que contienen caracteres ASCII+secuencias
de escape y los almacena en memoria!
q.asciiz str
Como .ascii, solo que termina los strings con el byte cero!

GSyC 2012 - MARS

23

Sintaxis del ensamblador

Seccin .data <addr>


q Los caracteres especiales dentro de un string siguen la convencin
de C!

!
!
!
q.byte b1,, bn
Almacena n valores de 8 bits en bytes sucesivos de memoria!
q.half h1, , hn
Almacena n valores de 16 bits en medias palabras sucesivas de
memoria!
q.word w1,, wn
Almacena n valores de 32 bits en palabras sucesivas de memoria!
q.space n
Reserva n bytes de espacio en el segmento de datos
!
GSyC 2012 - MARS

24

Sintaxis del ensamblador

Seccin .text <addr>

qInstrucciones simblicas que sern


codificadas y ejecutadas cuando el
programa comience!
qFormato de un comando .text:
[label:] instruction [p1 [, p2 [, p3]]]
Donde instruction es el nombre de la
instruccin y p1, p2 y p3 son los tres

operandos!
qEl tipo y nmero de los operandos viene
determinado por el tipo de instruccin!
GSyC 2012 - MARS

25

Sintaxis del ensamblador

Ejemplo
fibs:
size:
main:

loop:

.data
.word
0 : 12
.word 12
.text
la
$t0, fibs
la
$t5, size
lw
$t5, 0($t5)
li
$t2, 1
add.d $f0, $f2, $f4
sw
$t2, 0($t0)
sw
$t2, 4($t0)
addi $t1, $t5, -2
lw
$t3, 0($t0)
lw
$t4, 4($t0)
add $t2, $t3, $t4
sw
$t2, 8($t0)
addi $t0, $t0, 4
addi $t1, $t1, -1
bgtz $t1, loop
la
$a0, fibs
add $a1, $zero, $t5
jal print
li
$v0, 10
syscall

GSyC 2012 - MARS

# "array" of 12 words to contain fib values


# size of "array"
#
#
#
#

load
load
load
1 is

address of array
address of size variable
array size
first and second Fib. number

#
#
#
#
#
#
#
#
#
#
#
#
#
#
#

F[0] = 1
F[1] = F[0] = 1
Counter for loop, will execute (size-2) times
Get value from array F[n]
Get value from array F[n+1]
$t2 = F[n] + F[n+1]
Store F[n+2] = F[n] + F[n+1] in array
increment address of Fib. number source
decrement loop counter
repeat if not finished yet.
first argument for print (array)
second argument for print (size)
call print routine.
system call for exit
we are out of here.

26

Sintaxis del ensamblador

Otras convenciones que veremos

qLlamadas al sistema!
qEntrada/Salida!
qLlamada a procedimiento!
qExcepciones e interrupciones!

GSyC 2012 - MARS

27

You might also like