Toy_Reid
Toy_Reid

Reputation: 69

Very simple compare function not working

I've just started learning assembly in one of my classes and am having trouble writing a program that takes two arrays and compares each element, then stores the larger value back into the first array.

Here is my code with excruciatingly elementary comments (note that this is being ran on an arduino, hence the asm pseudo-function):

void sort1 (char *A, char *B, int N) {
  asm(
    "mov a1, %[A];"           // Move address A into a1 
    "mov a2, %[B];"           // Move address B into a2
    "mov a3, %[N];"           // Move array size N into a3

    "mov r1, #0;"  // r1 = 0
    "L1: cmp r1, a3;" // compare r1 and N
         "it ge;"
         "bge end;"  // if r1 >= N, jump to end (end condition of for loop is met)
       "ldrb v1,[a1];" // load a1 into v1
       "ldrb v2,[a2];" // load a2 into v2
       "cmp v1, v2;" // compare v1 and v2
         "it lt;" // if v1 is less than v2
         "strblt v2,[a1];" // store v2 in a1
       "add a1, #1;" // go to next element in array A
       "add a2, #1;" // go to next element in array B
       "add r1, #1;" // r1 = r1 + 1, equivalent to "i++"
       "b L1;" // branch to beginning of loop
    "end:"

    : : [A]"r"(A), [B]"r"(B), [N]"r"(N)  // Substitute C++ variables
    : "a1", "a2", "a3", "r1", "v1", "v2" // Place any registers used here to not clobber
  );  
}

Currently my program is giving back the same arrays A and B regardless of a value in B being greater than the one in A.

Any help is greatly appreciated. Sorry this is such a simple question that probably has a very simple solution, but most of this has been self-learning and I'm struggling figuring out where the problem is.

Upvotes: 0

Views: 85

Answers (1)

David Wohlferd
David Wohlferd

Reputation: 7483

Combining all the comments into an answer:

I don't know much about ARM, but isn't a2 just an alternate name for r1 (per this)? If so, trying to use both like this seems like a bad idea.

And as Peter mentioned, I might use a "memory" clobber here as well as "cc".

Also, it appears that mov a3, %[N] is unnecessary. It looks like you can just use %[N] (which is already a register) and save yourself a register.

And finally, my standard comments about why you shouldn't use gcc's inline asm is here.

Upvotes: 3

Related Questions