Mars Manual Usuario

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 28

DownloadMars Manual Usuario
Open PDF In BrowserView PDF
Dept. de Teoría de la Señal y Comunicaciones y Sistemas
Telemáticos y Computación
Área de Telemática (GSyC)

MARS
MIPS Assembler and Runtime Simulator

Katia Leal Algara
katia.leal@urjc.es
http://gsyc.escet.urjc.es/~katia/

Introducción

¿Qué es MARS?

q Es un entorno de desarrollo
interactivo (IDE) para la
programación en el lenguaje
ensamblador MIPS
q Orientado a la enseñanza para
usarse junto con el “Computer
Organization and Design” de
Patterson y Hennessy
GSyC - MARS

1

Características de MARS

Features

q Control de la velocidad de ejecución
q 32 registros visibles de forma simultánea
q Modificación de los valores en registros y
en memoria
q Posibilidad de mostrar los datos en
decimal o en hexadecimal
q Navegación por la memoria
q Editor y ensamblador integrados en el
propio IDE

GSyC - MARS

2

Características 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 básicas,
pseudoinstrucciones, directivas y llamadas
al sistemas descritas en el Apéndice B
están implementadas

GSyC - MARS

3

ori

I

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

I

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 2

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

M

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)

I

Características 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 divSubtract
blt
(2) Unsigned
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])
Branch
Less Than
or
Equal += { 11/11/--/0
4 PC = Label
ZeroExtImm
16{1b’0},
immediate
}
R[rt] = (atomic) ? 1 : 0 FP(2,7)
add.d IEEE
3
FR 754 FLOATING-POINT
9
addiu I R[rt] = R[rs] + SignExtImm
Add Imm. Unsigned
(2)
Double
{F[ft],F[ft+1]}
hex
BranchAddr
2’b0
}
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,
2’b0 }
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 2’s comp.)± 0
opcode
funct
funct& R[rt]
Binary
deci-0 / Chardeci- Char- c.x.d* (-1)
(Exponent
- Bias) 11/11/--/y
S
24hex
FRMove
and
And
R
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
PRESERVED±ACROSS
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
bne
j
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{1b’0},
} 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,
2’b0 }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,
2’b0
}
S
Exponent
Fraction
Double
{F[ft],F[ft+1]}
R[rt]={24’b0,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]={16’b0,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, 16’b0}
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> 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
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 / 23’hex 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{1b’0}, immediate
swl
slt
10 1010 } 42
2a
*
106
6a
j
Interrupt
M
L E
Values for Function Results
2’b0 }+
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 2’b0
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 2’s 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
11 10
(load or instructionYes
fetch)
Exception
lwc2
tlt
c.eq.f
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

opcode
ori

Set Less Than 31

GSyC - MARS

I

R[rt] = R[rs] | ZeroExtImm
01 0100

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

4

Características de MARS

Llamadas al sistema
q Varios servicios de sistema, principalmente para
la realización de operaciones de entrada/salida,
están 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 - MARS

5

Características de MARS

Ventana de edición: similar al Notepad de Windows

GSyC - MARS

6

Características de MARS

Ventana de ejecución

q Para ensamblar un programa hay que
pinchar en el icono !
q Si no hay errores de ensamblado, se abre
la ventana de ejecución
q En caso de que el ensamblado falle, se
muestra una ventana con los errores y su
correspondiente número de línea

GSyC - MARS

7

Características de MARS

Ventana de ejecución

q Muestra varias ventanas
q Ventana Text Segment:
q Muestra el código fuente y el binario
q Se puede incluir un breakpoint en cualquier
instrucción marcando el check box
correspondiente
q La siguiente instrucción en ser ejecutada
aparece resaltada

GSyC - MARS

8

Características de MARS

Ventana de ejecución

GSyC - MARS

9

Características de MARS

Ventana de ejecución
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 símbolos
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 propósito
general, los registros de coma flotante del Coprocessor 1 y los
registros de excepción del Coprocessor 0

GSyC - MARS

10

Características de MARS

Ventana de ejecución

Figure 2. MARS execution window is active ( “Execute” tab is foremost and the execution toolbar icons are active).
GSyC - MARS
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

Características de MARS

Ventana de ejecución

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

GSyC - MARS

12

Características 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)
q Así mismo, también se puede consultar el
Apéndice B del “Computer organization and
design. The hardware/software interface”, 4
edition. Morgan Kaufmann, 2012
q El mismo apéndice se puede descargar de forma
gratuita en:
http://www.cs.wisc.edu/~larus/HP_AppA.pdf
GSyC - MARS

13

Características de MARS

Instrucciones soportadas

GSyC - MARS

14

Programación en ensamblador

¿Cuándo programar en ensamblador?
q Cuando el tamaño o la velocidad de un programa sean
críticos
q En la mayoría de sistemas embebidos, es necesaria una
respuesta rápida y fiable
q Es difícil 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 tamaño de un programa reduce costes, puesto que
se necesitan menos pastilla de memoria
q Se pueden identificar las partes críticas de un programa,
aquellas en las que se emplea más 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 programación para
un ordenador particular
GSyC - MARS

15

Programación en ensamblador

Ensambladores
q Un programa ensamblador traduce un fichero con sentencias
en lenguaje ensamblador en un fichero con instrucciones
máquina y datos binarios
q El proceso de traducción tienen dos partes:
1. Localizar posiciones de memoria etiquetadas, de tal forma
que la dirección de un nombre simbólico se conozca cuando
las instrucciones se traduzcan
2. Traducir cada sentencia en ensamblador combinando
códigos de operación, identificadores de registros y etiquetas
en una instrucción legal
q El código 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 - MARS

16

A-8

Appendix A

Assemblers, Linkers, and the SPIM Simulator

Programación en ensamblador
#include 
main (int
char *argv[])
Linkadores
o argc,
enlazadores
{
int

int i;
q El programa
depende de otra herramienta, el
int sum ensamblador
= 0;
linkadorfor (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 librerías
}
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 interval—say, 1 millisecond after a sensor detects that a tire is skidding. An assembly
language programmer, on the other hand, has tight control over which instructions execute. In addition, in embedded applications, reducing a program’s size,
GSyC - 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

Programación 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 tamaño y la posición del resto de
campos
del fichero
gram. This
relocation
information is necessary because the assembler does not
q which
Text memory
segment:
contiene
el código
lenguaje
máquina
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
representación
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 Información
de realojamiento:
información
aquellas
definedinstrucciones
in a file and what
unresolved
references occur
in a file.
y datos
que dependen
de direcciones
absolutas
q Tabla de símbolos: 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 Información
de depuración:
información
el debugger
address
(for example, location
0) with the expectation
that para
the linker
will relocate the
code and data when they are assigned locations in memory. The assembler produces
GSyC - MARS
relocation
information, which contains an entry describing each instruction or data 18
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

Programación en ensamblador
A.5 Memory Usage

Gestión 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 - 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 coprocesProgramación
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
is a load-store
architecture, which
means that only load and lo
store
instrucqMIPS
MIPS
es una arquitectura
carga-almacenamiento,
que
tions access memory. Computation instructions operate only on values in regissignifica que sólo 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 virqtualLas
instrucciones
computacionales
operan
sólo
datos
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 - 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
Programación
en ensamblador
SPIM does not reorganize instructions to fill delay slots.

Byte Order

Ordenación
de within
los bytes
Processors
can
number bytes
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 convención
unawith
máquina
denomina or little-endian
either the leftmost
or rightmost
The convention used by a machine is called
ordenación
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 resultqin Por
a memory
word
containing
ejemplo,
en una
máquina big-endian, la directiva .byte
Byte
0, 1, 2, 3 resulta en
que# una palabra de memoria
contiene:
0

1Byte 2#

3

0

1

3

2

while in a little-endian machine, the word would contain
q Mientrasmachine,
que su lathe
máquina
fuera little-endian
la palabra
while in a little-endian
word would
contain
contendría:

GSyC - MARS

Byte #
3

2Byte 1#

0

3

2

0

1

21

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

Sintaxis del ensamblador

Sintaxis del ensamblador
q Comentarios
q “#”
q Todo lo que hay después de este carácter se ignora

q Etiquetas
q Se utilizan para referirse a posiciones de memoria o a
instrucciones
q Son case insensitive
q Sólo se puede utilizar una etiqueta por línea
q Van seguidas de “:”

q Secciones más importantes:
q .data
q .text
GSyC - MARS

22

Sintaxis del ensamblador

Sección .data 

q Comandos que especifican cómo se debe
rellenar la memoria antes de que el
programa comience su ejecución
q El formato de un comando .data es:
[label:] .datatype val1 [,val2 [, …]]

q Tipos 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 - MARS

23

Sintaxis del ensamblador

Sección .data 
q Los caracteres especiales dentro de un string siguen la convención
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 - MARS

24

Sintaxis del ensamblador

Sección .text 

q Instrucciones simbólicas que serán
codificadas y ejecutadas cuando el
programa comience
q Formato de un comando .text:
[label:] instruction [p1 [, p2 [, p3]]]
Donde instruction es el nombre de la
instrucción y p1, p2 y p3 son los tres

operandos
q El tipo y número de los operandos viene
determinado por el tipo de instrucción
GSyC - MARS

25

Sintaxis del ensamblador

Ejemplo
fibs:
size:
main:

loop:

.data
.word
0
.word 12
.text
la
$t0,
la
$t5,
lw
$t5,
li
$t2,
sw
$t2,
sw
$t2,
addi $t1,
lw
$t3,
lw
$t4,
add $t2,
sw
$t2,
addi $t0,
addi $t1,
bgtz $t1,
li
$v0,
syscall

GSyC - MARS

: 12

# "array" of 12 words to contain fib values
# size of "array"

fibs
size
0($t5)
1
0($t0)
4($t0)
$t5, -2
0($t0)
4($t0)
$t3, $t4
8($t0)
$t0, 4
$t1, -1
loop
10

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

load address of array
load address of size variable
load array size
1 is 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.
system call for exit
we are out of here.

26

Sintaxis del ensamblador

Otras convenciones que veremos …

qLlamadas al sistema
qEntrada/Salida
qLlamada a subrutina

GSyC - MARS

27



Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
Linearized                      : No
Page Count                      : 28
PDF Version                     : 1.4
Title                           : Mars_ManualUsuario.ppt
Author                          : Katia Leal Algara
Subject                         : 
Producer                        : Mac OS X 10.12.5 Quartz PDFContext
Creator                         : PowerPoint
Create Date                     : 2017:09:21 08:40:49Z
Modify Date                     : 2017:09:21 08:40:49Z
Apple Keywords                  : 
EXIF Metadata provided by EXIF.tools

Navigation menu