Sven Tennie pushed to branch wip/supersven/riscv-ncg-fix-atomicread at Glasgow Haskell Compiler / GHC Commits: dadadff3 by Sven Tennie at 2026-11-15T10:33:03+00:00 RISC-V NCG: Zero-extend the result of MO_AtomicRead (#28130) Atomic reads of subword values used a signed load (LDR), leaving the upper bits sign-extended. This violates the zero-extended subword invariant maintained by the RV64 NCG (Note [Signed arithmetic on RISCV64]), so e.g. an atomic read of a byte holding 0xff produced -1 instead of 255. Use LDRU, which maps to lbu/lhu/lwu/ld depending on the width. Fixed test: T27533 - - - - - 2 changed files: - + changelog.d/28130 - compiler/GHC/CmmToAsm/RV64/CodeGen.hs Changes: ===================================== changelog.d/28130 ===================================== @@ -0,0 +1,14 @@ +section: compiler +synopsis: Fix the RISC-V NCG sign-extending the result of atomic reads of subword values +issues: #28130 +mrs: !16997 + +description: { + Atomic reads of 8-, 16-, and 32-bit values used a signed load (``LDR``), + which left the upper bits sign-extended. This violated the zero-extended + subword invariant maintained by the RISC-V NCG, so for example an atomic + read of a byte holding ``0xff`` produced ``-1`` instead of ``255``. + + The reads now use ``LDRU``, which maps to ``lbu``, ``lhu``, ``lwu``, or + ``ld`` depending on the width. +} ===================================== compiler/GHC/CmmToAsm/RV64/CodeGen.hs ===================================== @@ -1838,16 +1838,18 @@ genCCall (PrimTarget mop) dest_regs arg_regs = do -- __atomic_load_n(&a, __ATOMIC_ACQUIRE); -- __atomic_load_n(&a, __ATOMIC_SEQ_CST); let instrs = case ord of - MemOrderRelaxed -> unitOL $ ann moDescr (LDR (intFormat w) (OpReg w dst) (OpAddr $ AddrReg p)) + -- N.B. use an unsigned load to maintain the subword invariant; + -- a signed load would leave the upper bits sign-extended. + MemOrderRelaxed -> unitOL $ ann moDescr (LDRU (intFormat w) (OpReg w dst) (OpAddr $ AddrReg p)) MemOrderAcquire -> toOL - [ ann moDescr (LDR (intFormat w) (OpReg w dst) (OpAddr $ AddrReg p)), + [ ann moDescr (LDRU (intFormat w) (OpReg w dst) (OpAddr $ AddrReg p)), FENCE FenceRead FenceReadWrite ] MemOrderSeqCst -> toOL [ ann moDescr (FENCE FenceReadWrite FenceReadWrite), - LDR (intFormat w) (OpReg w dst) (OpAddr $ AddrReg p), + LDRU (intFormat w) (OpReg w dst) (OpAddr $ AddrReg p), FENCE FenceRead FenceReadWrite ] MemOrderRelease -> panic $ "Unexpected MemOrderRelease on an AtomicRead: " ++ show mo View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/dadadff3e9df603ac7fe7e41f47caa6d... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/dadadff3e9df603ac7fe7e41f47caa6d... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help