Search code examples
assemblyembeddedcpu-architecturemsp430

JL instruction in MSP430


Given the code in MSP430:

     CLR  R6
     MOV  #5, R5                                  
L1:  DEC  R5
     CMP  #0, R5
     JL   L1
     INC  R6

I was told the value of R5 after execution is 4 and not 0.

Is this something specific to JL instruction?


Solution

  • JL is "Jump if less than".

    From the instruction set:

    JL : Jump to Label if (N .XOR. V) = 1 
    

    So the jump occurs only if either the negative or overflow flag (but not both) are set.

    The CMP instruction can set either of these as a result of performing b - a (R5 - 0 in this case) - CMP #0, R5 is simply a way of testing the value of R5.

    The CMP and JL together mean IF R5 < 0 GOTO L1.

    Since you have set it to 5, and decremented it to 4, it will not be less than zero, so the JL does not branch.

    Perhaps JNZ was intended ("Jump if not zero"), or its synonym JNE ("Jump if not equal").

         CLR  R6      ; R6 = 0
         MOV  #5, R5  ; R5 = 5                        
    L1:  DEC  R5      ; R5 = R5 - 1
    
         CMP  #0, R5  ; if R5 - 0 ...
         JL   L1      ; ... is less than zero ... <-- This is never true
                      ; ... then goto L1 
    
         INC  R6      ; R6 = R6 + 1
                      ; Here R5 = 4, R6 = 1
    

    Note also the the DEC instruction also sets the N and V flags, so the CMP is in fact unnecessary.

         CLR  R6      ; R6 = 0
         MOV  #5, R5  ; R5 = 5                        
    L1:  DEC  R5      ; R5 = R5 - 1
    
         JNZ  L1      ; if R5 is not zero ... 
                      ; ... then goto L1   <-- This will loop until R5 == zero
    
         INC  R6      ; R6 = R6 + 1
                      ; Here R5 = 0, R6 = 1