/******************************************************* * File: AddXY.m * Date: Oct. 11, 2021 * Author: DSS * Computer: acad * Assemble: asm AddXY * Execute: AddXY * Purpose: to demonstrate allocation of automatic (local) variables on the stack. * * This program will declare ints x and y by allocating space for them in * main()'s stack frame. x and y will be read and stored directly * Their sum will be computed and output * Several registers will be aliased * * It uses minimal code, optimizing several things *******************************************************/ define(varMem,16) define(xOffset,0) define(yOffset,4) define(xReg,%r12) define(yReg,%r13) define(zReg,%r14) .global main main: push %rbp # keep stack aligned # Make room for x and y on the stack subq $varMem, %rsp # must also remain divisible by 16 # Read values leaq prompt(%rip), %rdi # load format string to proper register call printf # print it # Read x and y xor %rax,%rax leaq fmt_in(%rip), %rdi # load format string movq %rsp, %rsi addq $xOffset, %rsi movq %rsp, %rdx addq $yOffset, %rdx call scanf # Load and sum # Put x location in xReg movq %rsp,xReg # Stack pointer into xReg addq $xOffset, xReg # xReg now has address of X movq (xReg),xReg # Load the value of x into xReg # Put y location in xReg movq %rsp,yReg # Stack pointer into yReg addq $yOffset, yReg # xReg now has address of X movq (yReg),yReg # Load the value of y into yReg # Sum xor zReg, zReg # Clear the sum register zReg addq xReg, zReg # Add x to it addq yReg, zReg # Add y to it # Print leaq frmto(%rip),%rdi # Output format mov xReg,%rsi mov yReg,%rdx mov zReg,%rcx xor %rax,%rax call printf done: addq $varMem, %rsp # Deallocate the variables pop %rbp ret .data prompt: .asciz "enter x and y: " fmt_in: .asciz "%d %d" frmto: .asciz "%d + %d = %d\n"