Skip to content

Code generation error on AVR using u16::to_be() #98167

Closed
@mutantbob

Description

@mutantbob

I tried this code on AVR (arduino Uno = atmega328p) with opt-level="z":

let pixels = [0xf800u16, 0x07e0, 0x001f];
let mut buf = [0u16; 3];
{
    let mut i = 0;
    for pixel in pixels.map(u16::to_be) {
        buf[i] = pixel;
        i += 1;
    }
    let _ = uwriteln!(serial, "debug buf {:?} mapped", buf);
}

I expected to see this happen:
debug buf [248, 57351, 7936] mapped

Instead, this happened:
debug buf [0, 57568, 7967] mapped

An alternate code that emits the correct output is

    {
        for (i, pixel) in pixels.iter().enumerate() {
            buf[i] = pixel.to_be();
        }
        let _ = uwriteln!(serial, "debug buf {:?} enumerate", buf);
    }

This compiler error is corrupting the pixel stream transmitted via SPI to an ST7789 display from an Arduino Uno. What appears to be happening is that instead of the bytes being swapped, the LSB is being copied to the MSB. I do not have the expertise to decompile and examine the assembly code.

Meta

rustc --version --verbose:

rustc 1.62.0-nightly (88860d547 2022-05-09)
binary: rustc
commit-hash: 88860d5474a32f507dde8fba8df35fd2064f11b9
commit-date: 2022-05-09
host: x86_64-unknown-linux-gnu
release: 1.62.0-nightly
LLVM version: 14.0.1

The malfunction also occurs with cargo +nightly.

rustc +nightly --version --verbose

rustc 1.63.0-nightly (b31f9cc22 2022-06-15)
binary: rustc
commit-hash: b31f9cc22bcd720b37ddf927afe378108a5b9a54
commit-date: 2022-06-15
host: x86_64-unknown-linux-gnu
release: 1.63.0-nightly
LLVM version: 14.0.5

The full code can be cloned from https://github.com/mutantbob/rust-avr-code-generation-bug

Metadata

Metadata

Assignees

Labels

A-codegenArea: Code generationC-bugCategory: This is a bug.O-AVRTarget: AVR processors (ATtiny, ATmega, etc.)

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions