Assembly Language for Beginners

(Jeff_L) #1
1.9. SCANF()

27 ldr w1, [x29,28]
28 ; W1=x
29 ; load pointer to the "You entered %d...\n" string
30 ; printf() will take text string from X0 and "x" variable from X1 (or W1)
31 adrp x0, .LC2
32 add x0, x0, :lo12:.LC2
33 bl printf
34 ; return 0
35 mov w0, 0
36 ; restore FP and LR, then add 32 to SP:
37 ldp x29, x30, [sp], 32
38 ret


There is 32 bytes are allocated for stack frame, which is bigger than it needed. Perhaps some memory
aligning issue? The most interesting part is finding space for thexvariable in the stack frame (line 22).
Why 28? Somehow, compiler decided to place this variable at the end of stack frame instead of beginning.
The address is passed toscanf(), which just stores the user input value in the memory at that address.
This is 32-bit value of typeint. The value is fetched at line 27 and then passed toprintf().

MIPS

A place in the local stack is allocated for thexvariable, and it is to be referred as$sp+ 24.

Itsaddressispassedtoscanf(),andtheuserinputvaluesisloadedusingtheLW(“LoadWord”)instruction
and then passed toprintf().

Listing 1.71: Optimizing GCC 4.4.5 (assembly output)
$LC0:
.ascii "Enter X:\000"
$LC1:
.ascii "%d\000"
$LC2:
.ascii "You entered %d...\012\000"
main:
; function prologue:
lui $28,%hi(__gnu_local_gp)
addiu $sp,$sp,-40
addiu $28,$28,%lo(__gnu_local_gp)
sw $31,36($sp)
; call puts():
lw $25,%call16(puts)($28)
lui $4,%hi($LC0)
jalr $25
addiu $4,$4,%lo($LC0) ; branch delay slot
; call scanf():
lw $28,16($sp)
lui $4,%hi($LC1)
lw $25,%call16(__isoc99_scanf)($28)
; set 2nd argument of scanf(), $a1=$sp+24:
addiu $5,$sp,24
jalr $25
addiu $4,$4,%lo($LC1) ; branch delay slot

; call printf():
lw $28,16($sp)
; set 2nd argument of printf(),
; load word at address $sp+24:
lw $5,24($sp)
lw $25,%call16(printf)($28)
lui $4,%hi($LC2)
jalr $25
addiu $4,$4,%lo($LC2) ; branch delay slot

; function epilogue:
lw $31,36($sp)
; set return value to 0:
move $2,$0
; return:
Free download pdf