[llvm] [RISC-V][Mach-O] Add assembler support for Mach-O relocations. (PR #177446)

Craig Topper via llvm-commits llvm-commits at lists.llvm.org
Thu Jan 22 11:52:16 PST 2026


================
@@ -42,10 +48,377 @@ class RISCVMachObjectWriter : public MCMachObjectTargetWriter {
 
 } // end anonymous namespace
 
+bool RISCVMachObjectWriter::getRISCVFixupKindMachOInfo(const MCFixup &Fixup,
+                                                       unsigned &RelocType,
+                                                       const MCValue Sym,
+                                                       unsigned &Log2Size,
+                                                       const MCAssembler &Asm) {
+  RelocType = unsigned(MachO::RISCV_RELOC_UNSIGNED);
+  Log2Size = ~0U;
+
+  if (Sym.getSpecifier() == RISCV::S_GOT_HI) {
+    Log2Size = Log2_32(4);
+    RelocType = unsigned(MachO::RISCV_RELOC_GOT_HI20);
+    return true;
+  }
+
+  switch (Fixup.getKind()) {
+  default:
+    return false;
+
+  case FK_Data_1:
+    Log2Size = Log2_32(1);
+    return true;
+  case FK_Data_2:
+    Log2Size = Log2_32(2);
+    return true;
+  case FK_Data_4:
+    Log2Size = Log2_32(4);
+    return true;
+  case FK_Data_8:
+    Log2Size = Log2_32(8);
+    return true;
+  case RISCV::fixup_riscv_pcrel_lo12_i:
+  case RISCV::fixup_riscv_pcrel_lo12_s:
+    llvm_unreachable("lo12 fixups should have been resolved elsewhere");
+  case RISCV::fixup_riscv_lo12_i:
+  case RISCV::fixup_riscv_lo12_s:
+    Log2Size = Log2_32(4);
+    RelocType = MachO::RISCV_RELOC_LO12;
+    return true;
+  case RISCV::fixup_riscv_pcrel_hi20:
+    Log2Size = Log2_32(4);
+    if (Sym.getSpecifier() != RISCV::S_PCREL_HI) {
+      Asm.getContext().reportError(Fixup.getLoc(),
+                                   "unknown AUIPC relocation kind");
+      return false;
+    }
+    RelocType = unsigned(MachO::RISCV_RELOC_HI20);
+    return true;
+  case RISCV::fixup_riscv_hi20:
+    Log2Size = Log2_32(4);
+    RelocType = unsigned(MachO::RISCV_RELOC_HI20);
+    return true;
+  case RISCV::fixup_riscv_call:
+  case RISCV::fixup_riscv_call_plt:
+  case RISCV::fixup_riscv_jal:
+    Log2Size = Log2_32(4);
+    RelocType = unsigned(MachO::RISCV_RELOC_BRANCH21);
+    return true;
+  }
+}
+
+static bool canUseLocalRelocation(const MCSectionMachO &Section,
+                                  const MCSymbol &Symbol, unsigned Log2Size) {
+  // Debug info sections can use local relocations.
+  if (Section.hasAttribute(MachO::S_ATTR_DEBUG))
+    return true;
+
+  // Otherwise, only pointer sized relocations are supported.
+  if (Log2Size != 2)
+    return false;
+
+  // But only if they don't point to a few forbidden sections.
----------------
topperc wrote:

```suggestion
  // But only if they don't point to a few forbidden section.
```

https://github.com/llvm/llvm-project/pull/177446


More information about the llvm-commits mailing list