Issue 150263
Summary Improve handling of misaligned loads on RISC-V by introducing branching
Labels new issue
Assignees
Reporter newpavlov
    Because of the (arguably) stupid handling of misaligned loads by the RISC-V spec LLVM generates extremely bad code for misaligned loads (see #110454 for the previous discussion). This can be seen in the Rust following snippet ([godbolt link](https://rust.godbolt.org/z/jeET5EKar)):
```rust
pub fn load_block(block: &[u8; 128]) -> u64 {
    let buf: [u64; 16] = core::array::from_fn(|i| {
        let chunk = block[8*i..][..8].try_into().unwrap();
        u64::from_ne_bytes(chunk)
 });
    buf.iter().sum()
}
```
LLVM IR:
```llvm
; Function Attrs: mustprogress nofree norecurse nosync nounwind nonlazybind willreturn memory(argmem: read) uwtable
define noundef i64 @load_block(ptr noalias nocapture noundef readonly align 1 dereferenceable(128) %block) unnamed_addr #0 personality ptr @rust_eh_personality {
start:
  %0 = load <16 x i64>, ptr %block, align 1, !alias.scope !3
  %1 = tail call i64 @llvm.vector.reduce.add.v16i64(<16 x i64> %0)
  ret i64 %1
}
```
LLVM emulates unaligned word loads with aligned byte loads, which results in an **extremely** inefficient codegen. Such loads are very common in cryptographic code (e.g. the `[u64; 16]` load is used in SHA-512).

Right now we have to work around it by introducing hacks like [this](https://github.com/RustCrypto/hashes/blob/master/sha2/src/sha512/riscv_zknh_utils.rs) (use aligned load if the buffer is aligned, if not, perform 17 aligned  `u64` loads and stitch results into `[u64; 16]`). Doing it manually for every algorithm implementation is obviously not practical (same for telling users to manually use `-mno-strict-align`.), and, frankly, I intend to remove the hack in the near future, performance on RISC-V be damned.

I suggest to implement the hack as an LLVM optimization. Yes, it introduces a branch, but it's the best option assuming that handling of the `Zicclsm` extension stays the same.

cc @asb 
_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to