How come my loop is not displaying properly in Assembly?

43 views Asked by At
.output: .string "X = %d, Y = %d Current Minimum of Y is:%d \n"
.balign 4
.global main

main:   stp     x29, x30, [sp,-16]!
        mov     x29, sp
        mov     x18, -10        // The variable X
        mov     x19, 0          // The variable Y
        mov     x20, 0          // Current minimum of Y

Loop:
        cmp     x18, 4           // Compare X (x18) with 4
        b.gt    end

        mov     x19, 0          // Set Y to zero for each loop
        mov     x21, 0          // x21, x22, and x23 initialize variables for the equation
        mov     x22, 0
        mov     x23, 0

        add     x19, x19, -127  // Y - 127

        mov     x24, -15         // Load immediate value -15 into x24
        mul     x24, x24, x18   // X becomes -15x, store the result in x24
        add     x21, x19, x24   // Y = -15x - 127

        mov     x24, x18         // Load immediate value x into x24
        mul     x24, x24, x24   // x24 becomes x^2
        mov     x25, 31          // Load immediate value 31 into x25
        mul     x24, x24, x25   // x^2 becomes 31x^2
        add     x22, x21, x24   // Y = 31x^2 - 15x - 127

        mov     x24, x18         // Load immediate value x into x24
        mul     x24, x24, x24   // x24 becomes x^2
        mul     x24, x24, x18   // x^2 becomes x^3
        mov     x25, 3           // Load immediate value 3 into x25
        mul     x24, x24, x25   // x^3 becomes 3x^3
        add     x23, x24, x22   // Y = 3x^3 + 31x^2 - 15x - 127

        cmp     x23, x20
        b.lt    update_min

        b       print

update_min:
        mov     x20, x23

print:  adrp    x0, .output
        add     x0, x0, :lo12: .output
        mov     x1, x18
        mov     x2, x23
        mov     x3, x20
        bl      printf

        add     x18, x18, 1       // Increment X (x18)
        b       Loop

end:    ldp     x29, x30, [sp], 16
       ret

I'm trying to learn the ins and outs of assembly and my first major chunk of code is to have an equation loop over values from -10 to 4 and display the current minimum Y.

For some reason the Minimum Y value shows up as 0 from -10 to -2 and then works properly.

I think this has something to do with the fact that I set the Y register to 0 for each loop to prevent the previous result from carrying over. To that end I've tried to edit that line so its and very small number, but that didn't work. I also tried to edit the update_min label so it adds zero instead of moving the current value to it in case its smaller.

From here, I don't actually know what needs to be changed here. Can some help point me into the right direction?

0

There are 0 answers