Index: llvm/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.cpp =================================================================== --- llvm/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.cpp +++ llvm/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.cpp @@ -354,20 +354,21 @@ bool RISCVAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count, const MCSubtargetInfo *STI) const { - bool HasStdExtC = STI->getFeatureBits()[RISCV::FeatureStdExtC]; - unsigned MinNopLen = HasStdExtC ? 2 : 4; - - if ((Count % MinNopLen) != 0) - return false; - // The canonical nop on RISC-V is addi x0, x0, 0. for (; Count >= 4; Count -= 4) OS.write("\x13\0\0\0", 4); // The canonical nop on RVC is c.nop. - if (Count && HasStdExtC) - OS.write("\x01\0", 2); - + if (STI->getFeatureBits()[RISCV::FeatureStdExtC]) + for (; Count >= 2; Count -= 2) + OS.write("\x01\0", 2); + + // If the count is not 4-byte aligned (or 2-byte under the C extensions), we + // must be writing data into the text section (otherwise we have unaligned + // instructions, and thus have far bigger problems), so just write zeros + // instead. This also may occur for non-standard data sections which are not + // declared and thus get detected as text rather than data. + OS.write_zeros(Count); return true; } Index: llvm/test/MC/RISCV/nop-slide.ll =================================================================== --- /dev/null +++ llvm/test/MC/RISCV/nop-slide.ll @@ -0,0 +1,13 @@ +; RUN: llc -mtriple riscv64 -filetype obj -o - %s | llvm-objdump -t - | FileCheck %s + +target datalayout = "e-m:e-p:64:64-i64:64-i128:128-n64-S128" + +; Ensure that we properly handle the emission of nops into sections which may be +; classified as text but are actual data. The alignment for `c` requires the +; emission of 7 bytes of nops. + +@b = dso_local global i8 0, section ".init.data", align 1 +@c = dso_local global ptr null, section ".init.data", align 8 + +; CHECK: 0000000000000000 g O .init.data 0000000000000001 b +; CHECK: 0000000000000008 g O .init.data 0000000000000008 c