简体   繁体   中英

AVR, Assembly, Flag V

I need advice on an assembler program (AVR ATMega169). I have to create code to calculate this expression.

R20 = (4 * R16 + 3 * R17 - R18) / 8

I try to calculate the arithmetic expression in the code and always check the overflow instruction but it doesn't work properly

  .org 0
start:
    ldi r16, 10
    ldi r17, 20
    ldi r18, 10
        
    lsl r16
    brvs OVERFLOW

    lsl r16
    brvs OVERFLOW

    mov r20,r17
    brvs OVERFLOW

    lsl r20
    brvs OVERFLOW

    add r20,r17
    brvs OVERFLOW

    add r20, r16
    brvs OVERFLOW

    sub r20,r18
    brvs OVERFLOW

    asr r20
    brvs OVERFLOW

    asr r20
    brvs OVERFLOW

    asr r20
    brvs OVERFLOW
    
    
    brvc OK

    OVERFLOW:
    ldi r30, 0x11

    OK:
    ldi r30, 0x11
konec:
    rjmp konec

As far as properly setting the overflow flag, most of the individual operations will set the overflow flag properly, namely add , sub , and lsl . How ever, asr does not appear to set the overflow flag in a particularly meaningful way regarding signed division.

The problematic thing is that the instructions that do properly set the overflow flag also clear the overflow flag (on success / no overflow), so they either set it or clear it based on that one individual arithmetic operation. Thus, there appears no direct way to accumulate the overflow condition across multiple instructions.

The solution is to test for overflow after each operation, perhaps by branching to the exit (skipping past the rest of the calculation — leaving garbage as in R20 though with the overflow flag set.) Since dividing by 8 cannot overflow, then if you reach that part of the code (ie without having overflowed prior calculations), then I would just clear the overflow flag after the division and before reaching the exit.

Another approach would be to or the overflow flag after each operation into some variable, then use that variable to set the overflow flag at the end. This approach would leave a more predictable value in R20 when overflow does occur, at the expense of additional instructions and variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM