Sei sulla pagina 1di 27

Assembly in ARM

Argomento:

• Struttura di un programma assembly


• Esempi di costrutti base
• Primi programmi
Struttura di un programma
assembly ARM

Architettura degli Elaboratori 2021 2


Struttura programma assembly

• Un programma assembly consiste di uno o più file


testuali (con estensione .s)

• Ogni file consiste di una sequenza di istruzioni


assembly

mov r0, #0x100


mov r1, #0
Istruzioni add r1, r1, r0 Operandi
subs r0, r0, #1

Architettura degli Elaboratori 2021 3


Costruzione di un programma

• istruzione assembly ≠ istruzione macchina


• Istruzione macchina è la rappresentazione binaria di un’istruzione assembly
• (quasi) perfetta corrispondenza

• Il programma eseguibile viene costruito dal codice assembly


tramite il compilatore
• La compilazione consiste di due fasi: assemblaggio e linkaggio

• Il programma eseguibile contiene sia istruzioni macchina che dati


• Contiene un punto di ingresso che rappresenta la prima istruzione del
programma

• Esempio:
• gcc -o sum sum.s à costruisce il programma eseguibile sum a partire dal
sorgente assembly sum.s

Architettura degli Elaboratori 2021 4


Cosa manca per scrivere un
programma?
Come sommiamo i primi 0x100 numeri?
• R0: contatore
• R1: somma parziale

mov r0, #0x100


mov r1, #0

add r1, r1, r0


subs r0, r0, #1
bne ????

str r1, [???]

Architettura degli Elaboratori 2021 5


Aiutare il compilatore

• Le istruzioni assembly non bastano per costruire un


programma eseguibile

• Bisogna inoltre permettere di:


• Indicare la prima istruzione
• Allocazione di dati (e.g., allocare una cella di memoria
con un valore numerico)
• Indicare delle righe di codice (e.g., nei salti condizionati)
• Inserire commenti
•…

Architettura degli Elaboratori 2021 6


Direttive e simboli

• Simboli: sono delle stringhe che denotano dei


particolari valori (indirizzi in memoria, costanti
numeriche,…)
• Label: è un particolare simbolo utilizzato per indicare
l’indirizzo in memoria di una particolare istruzione
• Direttive: sono istruzioni per l'assemblatore che
permettono di
• Definire simboli
• Allocare aree della memoria per salvataggio di dati
• Inizializzare il contenuto delle aree di memoria

• Simboli e direttive scompaiono dopo la compilazione


Architettura degli Elaboratori 2021 7
Esempio di file assembly

Simbolo .global main


main: ldr r0, =iterazioni
(label) ldr r0, [r0] @ Numero iterazioni
mov r1, #0 @ Registro per somme parziali

ciclo: add r1, r1, r0


subs r0, r0, #1 Commento
bne ciclo

ldr r2, =output


str r1, [r2] @ salva soluzione in memoria
Istruzione
output: .space 4

iterazioni: .word 0x100


Architettura degli Elaboratori 2021 8
Direttiva
Definizione e uso di label

Definizione main: mov r0, #0x100


di label mov r1, #0

ciclo: add r1, r1, r0


subs r0, r0, #1
Utilizzo
bne ciclo della
label
• Il compilatore calcola l'indirizzo dell'istruzione dove
il label "ciclo" è definita
• Ogni volta che il label "ciclo" viene usato viene
sostituita dall'indirizzo calcolato

Architettura degli Elaboratori 2021 9


Punto di inizio

• Ogni programma eseguibile deve avere un punto di


inizio, definito dal label main

.global main
main: mov r0, #0x100
mov r1, #0

• E’ necessario inserire prima della definizione del


main la direttiva .global main

Architettura degli Elaboratori 2021 10


Commenti

Un commento inizia con @ e termina alla fine della


riga

Esempio:

mov r0, #0x100 @ Numero iterazioni

Architettura degli Elaboratori 2021 11


Sintassi di un’istruzione assembly

• La forma generale delle linee di codice assembly è:

label: istruzione operandi @commento

• Ogni campo deve essere separato da uno o più spazi


• Tutti e tre le sezioni ... : ... @ ... sono opzionali
• I label devono iniziare dal primo carattere della riga
• Le istruzioni non cominciano mai dal primo carattere
della riga: devono essere precedute da almeno 1 spazio
• L’assembly è case-insensitive

Architettura degli Elaboratori 2021 12


Allocazione di dati

• Le direttive permettono di allocare spazio per variabili e di


inizializzare il loro valore
• Esempi:
maschera: .word 0xAAAAAAAA
stringa: .ascii "Pippo»
output: .space 4

• .word, .hword, .byte alloca in memoria e inizializza costanti


(4/2/1 byte)
• .ascii alloca e inizializza una stringa
• .space, .skip allocano aree di memoria (.space inizializza a 0)

Architettura degli Elaboratori 2021 13


Segmenti di un programma

.text
.global main
main: ldr r0, =iterazioni
ldr r0, [r0] @ Numero iterazioni
mov r1, #0 @ Registro per somme parziali

ciclo: add r1, r1, r0


subs r0, r0, #1
bne ciclo

ldr r2, =output


str r1, [r2] @ salva soluzione in memoria

.bss
output: .space 4
.data
iterazioni: .word 0x100
Architettura degli Elaboratori 2021 14
Segmenti di un programma assembly

Un programma assembly è diviso in tre segmenti:

TEXT à segmento contenente codice (istruzioni)


inizia con .text

DATA à segmento contenente dati inizializzati


inizia con .data

BSS à segmento contenente dati non inizializzati


inizia con .bss

Architettura degli Elaboratori 2021 15


Definizione di altri simboli

• Altre a label è possibile definire simboli per valore


numerici con .equ

ciclo: add r1, r1, r0 .equ OFFSET, #1


subs r0, r0, #1
bne ciclo ciclo: add r1, r1, r0
subs r0, r0, #OFFSET
bne ciclo

• .equ non definisce un valore in memoria!

Architettura degli Elaboratori 2021 16


Esempi

.EQU cost ,5
Dichiara una costante cost=5

varA: .word 0xAA


Alloca una word con il valore 0xAA, l'etichetta
varA contiene l'indirizzo in memoria della word

st_base: .skip 128


Alloca 128 byte, l'etichetta punta al byte con
l'indirizzo più piccolo

Architettura degli Elaboratori 2021 17


Quick references

In Moodle trovate le quick reference sul linguaggio


ARM e sulle direttive
Assembler Control Directives Macro Directives
Directive Description Syntax Exam ple Directive Description Syntax Example
.arm Following opcodes use the ARM instruction set .arm .arm .macro Define a macro. .macro name {args, …}

ARM® and Thumb®-2 Instruction Set


.thum b Following opcodes use the THUMB instruction subset .thumb .thum b A macro can be defined without arguments, .macro NoArgsMacro
.code 16 Same as .thum b .code 16 .code 16 and can be called simply by specifying its name. name {args, …} NoArgsMacro
.code 32 Same as .arm .code 32 .code 32
A macro can also be defined with arguments, .macro ArgMacro arg, arg2

Quick Reference Card


.include Include a file. .include "file" .include "hardware.i"
and can be called the same way with commas seperating its
Byte align the following code to alignment byte boundary ArgMacro 10, 11
(default=4). Fill skipped bytes with fill (defa ult=0 or arguments.
.align .align {alignment} {, fill} {, max} .align
NOP). If the number of bytes skipped is greater than max, \arg mov r0, \arg
then don't align (de fault=alignm ent ). Arguments can be accessed by their name prefixed with a \.
.balign Same as .align .balign {alignment} {, fill} {, max} .balign 8, 0 You can define default macro arguments. .macro ArgMacro arg=1, arg2
Key to Tables Half-word align the following code to alignment byte Arguments are omited by simply placing a comma and no
ArgMacro , 11
boundary (default=4). Fill skipped half-words with fill value, or ignoring them all together (trailing only).
.balignw .balignw {alignment} {, fill} {, max} .balignw 2
Rm {, <opsh>} See Table Register, optionally shifted by constant <reglist> A comma-separated list of registers, enclosed in braces { and }. (default=0 or NOP). If the number of bytes skipped is
greater than max, then don't align (default=alignm ent ).
Arguments can be set in a modified order by referencing
them by name.
ArgMacro arg2=11, arg=10

<Operand2> See Table Flexible Operand 2. Shift and rotate are only available as part of Operand2. <reglist-PC> As <reglist>, must not include the PC. .balignl
W ord align the following code to alignment byte boundary
(default=4). Fill skipped words with fill (default=0 or
.balignl {alignment} {, fill} {, max} .balignl .endm
Macros can be recursive.
Mark the end of a macro. .endm .endm
NOP). If the number of bytes skipped is greater than max,
<fields> See Table PSR fields. <reglist+PC> As <reglist>, including the PC. then don't align (de fault=alignm ent ).
.exitm Exit a macro early. .exitm .exitm
Marks the end of the assembly file. Data following this
.end .end .end \@ Psudo variable that contains the macro number executed. \@ MyLabel\@:
<PSR> APSR (Application Program Status Register), CPSR (Current Processor Status Register), or SPSR <flags> Either nzcvq (ALU flags PSR[31:27]) or g (SIMD GE flags directive is not processed.
Generates errors or warnings durring assembly. If expr is
Can be used for a unique number on every macro definition.
(Saved Processor Status Register) PSR[19:16]) .fail greater than or equal to 500, it prints a warning message. .fail expr .fail 1 .purgem Undefine a macro, so that further uses do not evaluate. .purgem name .purgem NoArgsMacro
If less than it prints an error message.
C*, V* Flag is unpredictable in Architecture v4 and earlier, unchanged in Architecture v5 and later. § See Table ARM architecture versions. .err Generate an error durring assembly. .err .err Digit Encoding Formats
.print Print a string to standard output durring assembly. .print string .print "Something is broken"
Numbe r Type Base Prefix Digits Exa mple
<Rs|sh> Can be Rs or an immediate shift value. The values allowed for each shift type are the same as those +/- + or –. (+ may be omitted.) .section
Tell the assembler to assemble the following in section
.section expr .section .bss
expr . expr can be either .text, .data, or .bss. Decimal Inte ge r 10 0-9 25
shown in Table Register, optionally shifted by constant. <iflags> Interrupt flags. One or more of a, i, f (abort, interrupt, fast interrupt). .tex t
Tell assembler to assemble the following in the "text"
(code) section. You can also specify a subsection of "text" .text {subsection} .text Hex adecima l Integer 16 0x or 0X 0 - 9, A - F (10 - 15) 0xD7
with subsection . Octa l Integer 8 0 0-7 027
x,y B meaning half-register [15:0], or T meaning [31:16]. <p_mode> See Table Processor Modes Tell assembler to assemble the following in the "data"
Bina ry Inte ger 1 0b or 0B 0-1 0b11010
.data section. You can also specify a subsection of "data" with .data {subsection} .data 0
<imm8m> ARM: a 32-bit constant, formed by right-rotating an 8-bit value by an even number of bits. SPm SP for the processor mode specified by <p_mode> subsection .
Tell assembler to assemble the following in the "bss"
Floa ting Point Num ber 10 0f or 0F 0-9 0f+24.112E-25
Cha racter n/a ' Ascii Symbol 'c
Thumb: a 32-bit constant, formed by left-shifting an 8-bit value by any number of bits, or a bit <lsb> Least significant bit of bitfield. .bss (variables) section. You can also specify a subsection of
"bss" with subsection .
.bss {subsection} .bss
String n/a " and " Ascii Symbol(s) "MyString\n"
Tell assembler to assemble the following in an absolute
pattern of one of the forms 0xXYXYXYXY, 0x00XY00XY or 0xXY00XY00. <width> Width of bitfield. <width> + <lsb> must be <= 32. .struct section. Be sure to switch sections before you get back to .struct expr Numbe r Type Base Prefix Digits Exa mple
code or data. .struct 0
<prefix> See Table Prefixes for Parallel instructions {X} RsX is Rs rotated 16 bits if X present. Otherwise, RsX is Rs. feild1 is 0. field1:
.struct field1 + 4
Escape Codes
{IA|IB|DA|DB} Increment After, Increment Before, Decrement After, or Decrement Before. {!} Updates base register after data transfer if ! present (pre-indexed). field2 is 4.
Following code is inserted at the start of the section plus
field2: \ De scription Ascii \ De scription
.org .org new-lc {, fill} .org 0x20000
IB and DA are not available in Thumb state. If omitted, defaults to IA. {S} Updates condition flags if S present. new-lc . \b Backspace 8 \### Octal Character Code
Tell the assembler where it can safely place data for
.pool immediate 32bit loads (ideally after your return). Use the = .pool .pool \f Form Feed 12 \x## Hex Character Code
<size> B, SB, H, or SH, meaning Byte, Signed Byte, Halfword, and Signed Halfword respectively. {T} User mode privilege if T present. prefix operator to pool the value. ldr r0, =0x4000002
\n New Line 10 \\ \ character
SB and SH are not available in STR instructions. {R} Rounds result to nearest if R present, otherwise truncates result. Symbol Directives \r Carrige Return 13 \" " character
Directive Description Syntax Exam ple
.equ Set the value of symbol equal to expr . .equ symbol, expr .equ Version, "0.1" \t Horizontol Tab 9
.set Same as .equ .set symbol, expr .set Flavor, "CHERRY"
Set the value of symbol equal to expr . Generates an error
.equiv .equiv symbol, expr .equiv Version, "0.2"
Operation § Assembler S updates Action Notes .global
if the symbol has been previously defined.
Makes symbol visible to the linker. .global symbol .globa l MyAsmFunc
Expression Operators
Precedence Symbol Name Operation
Add Add ADD{S} Rd, Rn, <Operand2> N Z C V Rd := Rn + Operand2 N .globl Same as .global .globl symbol .globl MyOtherAsmFunc
prefix - Negate Negate argument.
with carry ADC{S} Rd, Rn, <Operand2> N Z C V Rd := Rn + Operand2 + Carry N Constant Definition Directives prefix ~ Compliment Compliment argument.
Directive Description Syntax Example
wide T2 ADD Rd, Rn, #<imm12> Rd := Rn + imm12, imm12 range 0-4095 T, P Highest * Multiplication Multiply arg1 by arg2.
.byte Define byte expr (8bit numbers) .byte expr {, …} .byte 25, 0x11, 031, 'A
.hword Define half-word expr (16bit numbers) .hword expr {, …} .hword 2, 0xFFE0 Highest / Division Divide arg1 by arg2.
saturating {doubled} 5E Q{D}ADD Rd, Rm, Rn Rd := SAT(Rm + Rn) doubled: Rd := SAT(Rm + SAT(Rn * 2)) Q .short Same as .hw ord .short expr {, …} .short 257
Highest % Remainder Divide arg1 by arg2, and return the remainder.
.word Define word expr (32bit numbers) .word expr {, …} .word 144511, 0x11223
Address Form PC-relative address ADR Rd, <label> Rd := <label>, for <label> range from current instruction see Note L N, L .int Same as .word .int expr {, …} .int 21 Highest << or < Left Shift Shift arg1 left by arg2.
.long Same as .word .long expr {, …} .long 1923, 0b10010101
Highest >> or > Right Shift Shift arg1 right by arg2.
Subtract Subtract SUB{S} Rd, Rn, <Operand2> N Z C V Rd := Rn – Operand2 N .ascii
.asciz
Define string expr (non zero terminated array of bytes)
Define string expr (ze ro terminated array of bytes)
.ascii expr {, …}
.asciz expr {, …}
.ascii "Ascii text is here"
.asciz "Zero Terminated Text" Intermediate | Bitwise OR OR arg1 with arg2.
with carry SBC{S} Rd, Rn, <Operand2> N Z C V Rd := Rn – Operand2 – NOT(Carry) N .string
.quad
Same as .asciz
Define bignum expr (break at 8bit increments)
.string expr {, …}
.quad expr {, …}
.string "My Cool String\n"
.qua d 0xDAFADAFA911
Intermediate & Bitwise AND AND arg1 with arg2.
Intermediate ^ Bitwise XOR XOR arg1 with arg2.
wide T2 SUB Rd, Rn, #<imm12> Rd := Rn – imm12, imm12 range 0-4095 T, P .octa
.float
Define bignum expr (break at 16bit increments)
Define 32bit IEEE flonum expr (floating point numbers)
.octa expr {, …}
.float expr {, …}
.octa 0xFEDCBA987654321
.floa t 0f3.14, 0F359.2e11
Intermediate ! Bitwise OR NOT OR arg1 with arg2, and NOT result.
reverse subtract RSB{S} Rd, Rn, <Operand2> N Z C V Rd := Operand2 – Rn N .single
.double
Same as .float
Define 64bit IEEE flonum expr (floating point numbers)
.single expr {, …}
.double expr {, …}
.single 0f12341243.14E2
.double 0f2E1 Lowest + Addition Add arg1 to arg2.
Generate repeat copies of value that is of size size . size Lowest - Subtraction Subtract arg2 from arg1.
reverse subtract with carry RSC{S} Rd, Rn, <Operand2> N Z C V Rd := Operand2 – Rn – NOT(Carry) A .fill
defaults to 1, and value defaults to 0.
.fill repeat {, size} {, value} .fill 32, 4, 0xFFFFFFFF

.zero Fills in size bytes with 0. .zero size .zero 400 Precedence Symbol Name Operation
saturating {doubled} 5E Q{D}SUB Rd, Rm, Rn Rd := SAT(Rm – Rn) doubled: Rd := SAT(Rm – SAT(Rn * 2)) Q .space Fills in size bytes with value . value defaults to 0. .space size {, value} .space 25, 0b11001100
.skip Same as .spa ce .skip size {, value} .skip 22
Exception return without stack SUBS PC, LR, #<imm8> N Z C V PC = LR – imm8, CPSR = SPSR(current mode), imm8 range 0-255.
Assembly Listing Directives
Parallel Halfword-wise addition 6 <prefix>ADD16 Rd, Rn, Rm Rd[31:16] := Rn[31:16] + Rm[31:16], Rd[15:0] := Rn[15:0] + Rm[15:0] G Directive Description Syntax Example

arithmetic Halfword-wise subtraction


.eje ct Force a page break when generating assembly listings. .eject .eject
6 <prefix>SUB16 Rd, Rn, Rm Rd[31:16] := Rn[31:16] – Rm[31:16], Rd[15:0] := Rn[15:0] – Rm[15:0] G Set the number of lines to generate for each page of the
assembly listing and the number of columns . Lines
Byte-wise addition 6 <prefix>ADD8 Rd, Rn, Rm Rd[31:24] := Rn[31:24] + Rm[31:24], Rd[23:16] := Rn[23:16] + Rm[23:16], G .psize
defaults to 60, Columns defaults to 200. A page break is
generated when the number of lines hits lines . If lines is
.psize lines {, columns} .psize 40, 80
Rd[15:8] := Rn[15:8] + Rm[15:8], Rd[7:0] := Rn[7:0] + Rm[7:0] 0, then no page breaks are generated (excluding ones by
.e je ct).
Byte-wise subtraction 6 <prefix>SUB8 Rd, Rn, Rm Rd[31:24] := Rn[31:24] – Rm[31:24], Rd[23:16] := Rn[23:16] – Rm[23:16], G .list
Start generation of an assembly listings from .list to
.list .list
Rd[15:8] := Rn[15:8] – Rm[15:8], Rd[7:0] := Rn[7:0] – Rm[7:0] .nolist.
End generation of an assembly listing. Listings can be re-
.nolist .nolist .nolist
Halfword-wise exchange, add, subtract 6 <prefix>ASX Rd, Rn, Rm Rd[31:16] := Rn[31:16] + Rm[15:0], Rd[15:0] := Rn[15:0] – Rm[31:16] G .title
started with .list again.
Uses heading as the title (2nd line, under filename and
.title "heading" .title "My Asm Output"
page number)
Halfword-wise exchange, subtract, add 6 <prefix>SAX Rd, Rn, Rm Rd[31:16] := Rn[31:16] – Rm[15:0], Rd[15:0] := Rn[15:0] + Rm[31:16] G .sbttl Uses heading as the title (3rd line, under .title ) .sbttl "heading .sbttl "Part 1: Cool stuff"

Unsigned sum of absolute differences 6 USAD8 Rd, Rm, Rs Rd := Abs(Rm[31:24] – Rs[31:24]) + Abs(Rm[23:16] – Rs[23:16]) Conditional Directives
+ Abs(Rm[15:8] – Rs[15:8]) + Abs(Rm[7:0] – Rs[7:0]) Directive Description
Assembles if absolute_expression does not equal zero.
Syntax Example
.if .if {absolute_expression} .if (2+2)
and accumulate 6 USADA8 Rd, Rm, Rs, Rn Rd := Rn + Abs(Rm[31:24] – Rs[31:24]) + Abs(Rm[23:16] – Rs[23:16]) For all If's, if absolute_expression is omited, it equals 0.
Assembles if absolute_expression does not equal zero.
+ Abs(Rm[15:8] – Rs[15:8]) + Abs(Rm[7:0] – Rs[7:0]) .else if Used in .if blocks to provide alternates when previous .if's .elseif {absolute_expression} .elseif (2+3) - 5
or .e lseif's fail.
Saturate Signed saturate word, right shift 6 SSAT Rd, #<sat>, Rm{, ASR <sh>} Rd := SignedSat((Rm ASR sh), sat). <sat> range 1-32, <sh> range 1-31. Q, R .else
.endif
Assembles if all previous .if and .elseif blocks failed.
Ends an .if block.
.else
.endif
.else
.endif
Signed saturate word, left shift 6 SSAT Rd, #<sat>, Rm{, LSL <sh>} Rd := SignedSat((Rm LSL sh), sat). <sat> range 1-32, <sh> range 0-31. Q .ifdef
.ifnde f
Assembles if symb ol exists.
Assembles if symb ol does not exist.
.ifdef symbol
.ifndef symbol
.ifde f _test_i_
.ifndef _test_i_
Signed saturate two halfwords 6 SSAT16 Rd, #<sat>, Rm Rd[31:16] := SignedSat(Rm[31:16], sat), Q .ifnotdef
.ifc
Same as .ifndef
Assembles if the strings are the same.
.ifnotdef symbol
.ifc string1, string2
.ifnotdef _test_i_
.ifc "this", "that"
Rd[15:0] := SignedSat(Rm[15:0], sat). <sat> range 1-16. .ifnc Assembles if the strings are not the same. .ifnc string1, string2 .ifnc "this", "that"
.ifeqs Same as .ifc .ifeqs string1, string2 .ifeqs "those", "this"
Unsigned saturate word, right shift 6 USAT Rd, #<sat>, Rm{, ASR <sh>} Rd := UnsignedSat((Rm ASR sh), sat). <sat> range 0-31, <sh> range 1-31. Q, R .ifnes
.ifeq
Same as .ife qs
Assembles if absolute_expression equals zero.
.ifnes string1, string2
.ifeq {absolute_expression}
.ifne s "those", "this"
.ifeq (2+2) - 4
Unsigned saturate word, left shift 6 USAT Rd, #<sat>, Rm{, LSL <sh>} Rd := UnsignedSat((Rm LSL sh), sat). <sat> range 0-31, <sh> range 0-31. Q .ifne Assembles if absolute_expression does not equal zero.
Assembles if absolute_expression is greater than or equal
.ifne {absolute_expression} .ifne (2+2) - 5
.ifge .ifge {absolute_expression} .ifge 10
Unsigned saturate two halfwords 6 USAT16 Rd, #<sat>, Rm Rd[31:16] := UnsignedSat(Rm[31:16], sat), Q .ifgt
to zero.
Assembles if absolute_expression is greater than zero. .ifgt {absolute_expression} .ifgt
Rd[15:0] := UnsignedSat(Rm[15:0], sat). <sat> range 0-15. .ifle
Assembles if absolute_expression is less than or equal to
.ifle {absolute_expression} .ifle
zero.
.iflt Assembles if absolute_expression is less than zero. .iflt {absolute_expression} .iflt -10

Debug Directives
Directive Description Syntax Example
Generate debug information for code as a function. If label
.func .func name {, label} .func CoolFunc
is omited, label is assumed to be name .
.endfunc Mark the end of a function. .endfunc .endfunc
See GAS documentation for info. Not very useful unless
.stabs .stabs string, type, other, desc, value
your generate assembly listings from another source.

Looping Directives
Directive Description Syntax Example
Repeat the sequence of lines between .rept and .e ndr
.rept .rept count .rept 10
count number of times.

Architettura degli Elaboratori 2021 18


Evaluate a comma delimited sequence of statements to
.irp .irp symbol, values… .irp newval, 1, 2, 3
assign to the value of symbol .
.irpc For each character in values , assign its value. .irp symbol, value .irp newval, 123
Symbol can be referenced with \symbol. \symbol .byte 0xC\new val
.endr End .re pt, .irp, and .irpc sequences. .endr .endr
Costrutti di base (if, for)

Architettura degli Elaboratori 2021 19


If-then-else

int a = 10;
int b = 20;
int c; // c= min(a,b)

if(a<b)
c = a;
else
c = b;

Architettura degli Elaboratori 2021 20


If-then-else in ARM

.data
addr_a: .word 10 @ inizializza a=10
addr_b: .word 20 @ inizializza b=20

.bss
addr_c: .skip 4 @ alloca c (4 byte)

.text

...

Architettura degli Elaboratori 2021 21


If-then-else in ARM (2)

...
.text
LDR R0, =addr_a @ carica indirizzo di a
LDR R1, [R0] @ copia a in R1
LDR R0, =addr_b @ carica indirizzo di b
LDR R2, [R0] @ copia b in R2
LDR R0, =addr_c @ carica indirizzo di c
CMP R1, R2 @ confronta R1(=a) e R2(=b)
BGE else_case @ se R1>=R2 salta
STR R1, [R0] @ imposta c=a
B end_if
else_case: STR R2, [R0] @ imposta c=b
end_if: NOP
Architettura degli Elaboratori 2021 22
If-then-else in ARM (short version)

...
.text
LDR R0, =addr_a @ carica indirizzo di a
LDR R1, [R0] @ copia a in R1
LDR R0, =addr_b @ carica indirizzo di b
LDR R2, [R0] @ copia b in R2
LDR R0, =addr_c @ carica indirizzo di c
CMP R1, R2 @ confronta R1 e R2
STRLT R1, [R0] @ imposta c=a se a<b
STRGE R2, [R0] @ imposta c=b se a>=b

Architettura degli Elaboratori 2021 23


For loop

int sum = 0;
int n = 100;
for(int i=1; i<=n; i++){
sum = sum + i;
}

Architettura degli Elaboratori 2021 24


For loop in ARM

.data
addr_n: .word 100 @ inizializza n=100

.bss
add_sum: .skip 4 @ alloca sum (4 byte)

.text
...

Architettura degli Elaboratori 2021 25


For loop in ARM (2)

...
.text
LDR R3, = addr_n @ copia indirizzo di n
LDR R2, [R3] @ copia n in R2
MOV R1, #0 @ R1 contiene somma parziale
MOV R0, #0 @ R0 è il contatore i
...

Architettura degli Elaboratori 2021 26


For loop in ARM (3)

...
for_loop: ADD R1, R1, R0 @ calcola sum=sum+i
ADD R0, R0, #1 @ incremento contatore
CMP R0, R2 @ confronta se i<=n
BLE for_loop @ se si, ripeti loop

LDR R3, =addr_sum


STR R1, [R3]

Architettura degli Elaboratori 2021 27

Potrebbero piacerti anche