Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Viper: Unary minus changes rhs variable in place, even if assigned to new lhs variable. #14397

Open
2 tasks done
rkompass opened this issue Apr 30, 2024 · 1 comment
Open
2 tasks done
Labels

Comments

@rkompass
Copy link

Checks

  • I agree to follow the MicroPython Code of Conduct to ensure a safe and respectful space for everyone.

  • I've searched for existing issues matching this bug, and didn't find any.

Port, board and/or hardware

w600, RP2, others

MicroPython version

latest, e.g.: MicroPython v1.23.0-preview.344.gb1ac266bb on 2024-04-29; Raspberry Pi Pico W with RP2040

Reproduction

@micropython.viper
def vip_unaryminus() -> int:
    a = 5
    b = -a          
    return a+b

print(vip_unaryminus())   # -10  <---- error, should be 0

@micropython.viper
def vip_tuple_um():
    a:int = int(-5)
    b = -a          
    return (a, b)

print(vip_tuple_um())    # (5, 5)  <---- error, should be (-5, 5)

Expected behaviour

0            # as 5 and -5 cancel out, so 5 + (-5) = 0
(-5, 5)

Observed behaviour

-10
(5, 5)

Additional Information

No, I've provided everything above.
My interpretation of this errorneaous behaviour is in the issue heading.

Thank you, btw., for improving viper permanently.

@rkompass rkompass added the bug label Apr 30, 2024
@rkompass
Copy link
Author

After having a look at 3c445f6 I suspected that unary invert would exhibit the same error and so it does:

@micropython.viper
def vip_invert() -> int:
    a = 5
    b = ~a          
    return a+b

print(vip_invert())    # -12  <---- error, should be -1

@micropython.viper
def vip_tuple_inv():
    a:int = int(5)
    b = ~a          
    return (a, b)

print(vip_tuple_inv())    # (-6, -6)  <---- error, should be (5, -6)

Looking at the PR I suspect that the logic

int reg = REG_RET;
emit_pre_pop_reg_flexible(emit, &vtype, &reg, reg, reg);
ASM_OPERATION_REG(emit->as, reg);
emit_post_push_reg(emit, vtype, reg);

emits code to change the register in place, which only works if the register is not used anymore.

The right approach would be to defer the register modification to happen with the lhs register after introducing it when doing the the assignment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant