[llvm] [AMDGPU] Relax long branches in the assembler on gfx1251 (PR #228363)

Jay Foad via llvm-commits llvm-commits at lists.llvm.org
Fri Oct 2 03:52:29 PDT 2026


https://github.com/jayfoad updated https://github.com/llvm/llvm-project/pull/228363

>From 8814ffd419dd6ec0b40b9d7dd1a50aa8a2f630de Mon Sep 17 00:00:00 2001
From: Jay Foad <jay.foad at amd.com>
Date: Thu, 1 Oct 2026 21:27:22 +0100
Subject: [PATCH 1/2] [AMDGPU] Relax long branches in the assembler on gfx1251

On subtargets with FeatureUseAddPC64Inst, s_add_pc_i64 with a 32-bit
literal, which the hardware sign-extends, can implement a relative
branch of up to +/-2GB without needing any registers. Use it to relax
out of range branches in the assembler, the way targets like X86 do,
instead of relying on the BranchRelaxation pass:

  s_branch target
    -> s_add_pc_i64 target        ; 8 bytes

  s_cbranch_<cc> target
    -> s_cbranch_<!cc> 2          ; 12 bytes
       s_add_pc_i64 target

This is done with two new MC-only pseudos, S_BRANCH_LONG and
S_CBRANCH_LONG, which are expanded by the code emitter, and a new fixup
kind for the literal. We assume that no branch within a single code
object needs more than +/-2GB, so there is no further relaxation to a
64-bit literal.

Any branch whose fixup cannot be resolved at assembly time is also
relaxed, even if the target turns out to be nearby, and uses an
R_AMDGPU_REL32 relocation instead of R_AMDGPU_REL16. This includes
branches to symbols in other sections, and to global or weak symbols in
the same section, because ELF keeps relocations for PC-relative
references to non-local symbols. The exception is branches to undefined
symbols: these are not relaxed, so they are still diagnosed as
"undefined label", since they are most likely typos. (X86 would instead
emit a relocation and leave it to the linker.)

This changes the behavior for hand-written assembly: on these
subtargets, an out of range s_branch or s_cbranch_* is no longer
diagnosed with "branch size exceeds simm16". Instead it silently grows
from 4 bytes to 8 or 12 bytes.

In codegen, isBranchOffsetInRange now always returns true on these
subtargets, so BranchRelaxation never inserts long branches, and
GCNPreRALongBranchReg returns early instead of reserving registers for
them. Branch sizes are no longer verified in the AsmPrinter since the
assembler may relax them. getInstSizeInBytes still reports the size of
the short form, so size estimates such as the codeLenInByte comment may
undercount code with long branches.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply at anthropic.com>
---
 .../Target/AMDGPU/GCNPreRALongBranchReg.cpp   |   4 +
 .../AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp  | 107 +++++++++++-
 .../MCTargetDesc/AMDGPUELFObjectWriter.cpp    |   3 +
 .../AMDGPU/MCTargetDesc/AMDGPUFixupKinds.h    |   4 +
 .../MCTargetDesc/AMDGPUMCCodeEmitter.cpp      |  52 +++++-
 llvm/lib/Target/AMDGPU/SIInstrInfo.cpp        |  32 ++--
 llvm/lib/Target/AMDGPU/SIProgramInfo.cpp      |   2 +
 llvm/lib/Target/AMDGPU/SOPInstructions.td     |  24 +++
 .../AMDGPU/branch-relaxation-gfx1250.ll       | 113 ++++--------
 .../AMDGPU/branch-relaxation-gfx1251.ll       |  65 +++++++
 .../AMDGPU/branch-relaxation-add-pc64-range.s |  28 +++
 .../MC/AMDGPU/branch-relaxation-add-pc64.s    | 165 ++++++++++++++++++
 llvm/test/MC/AMDGPU/max-branch-distance.s     |  27 ++-
 13 files changed, 522 insertions(+), 104 deletions(-)
 create mode 100644 llvm/test/CodeGen/AMDGPU/branch-relaxation-gfx1251.ll
 create mode 100644 llvm/test/MC/AMDGPU/branch-relaxation-add-pc64-range.s
 create mode 100644 llvm/test/MC/AMDGPU/branch-relaxation-add-pc64.s

diff --git a/llvm/lib/Target/AMDGPU/GCNPreRALongBranchReg.cpp b/llvm/lib/Target/AMDGPU/GCNPreRALongBranchReg.cpp
index b4f2c30e870f1d..016b5f7acf90ea 100644
--- a/llvm/lib/Target/AMDGPU/GCNPreRALongBranchReg.cpp
+++ b/llvm/lib/Target/AMDGPU/GCNPreRALongBranchReg.cpp
@@ -112,6 +112,10 @@ void GCNPreRALongBranchReg::generateBlockInfo(
 
 bool GCNPreRALongBranchReg::run(MachineFunction &MF) {
   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
+  // Long branches are relaxed by the assembler without needing any registers.
+  if (STM.useAddPC64Inst())
+    return false;
+
   const SIInstrInfo *TII = STM.getInstrInfo();
   const SIRegisterInfo *TRI = STM.getRegisterInfo();
   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
diff --git a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp
index 5cd2aa86560ae9..43c4d22c6708e9 100644
--- a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp
+++ b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp
@@ -51,10 +51,83 @@ class AMDGPUAsmBackend : public MCAsmBackend {
   MCFixupKindInfo getFixupKindInfo(MCFixupKind Kind) const override;
 };
 
-} //End anonymous namespace
+struct LongBranchInfo {
+  // MC opcode of the short branch with the inverted condition, or 0 if the
+  // branch is unconditional.
+  unsigned SkipOpc;
+  // MC opcode of s_add_pc_i64.
+  unsigned AddPCOpc;
+};
+
+} // End anonymous namespace
+
+// Get the information needed to relax a short branch into S_BRANCH_LONG or
+// S_CBRANCH_LONG on subtargets with FeatureUseAddPC64Inst.
+static std::optional<LongBranchInfo> getLongBranchInfo(unsigned Opcode) {
+  switch (Opcode) {
+  case AMDGPU::S_BRANCH_gfx12:
+    return LongBranchInfo{0, AMDGPU::S_ADD_PC_I64_gfx12};
+  case AMDGPU::S_CBRANCH_SCC0_gfx12:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_SCC1_gfx12,
+                          AMDGPU::S_ADD_PC_I64_gfx12};
+  case AMDGPU::S_CBRANCH_SCC1_gfx12:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_SCC0_gfx12,
+                          AMDGPU::S_ADD_PC_I64_gfx12};
+  case AMDGPU::S_CBRANCH_VCCZ_gfx12:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_VCCNZ_gfx12,
+                          AMDGPU::S_ADD_PC_I64_gfx12};
+  case AMDGPU::S_CBRANCH_VCCNZ_gfx12:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_VCCZ_gfx12,
+                          AMDGPU::S_ADD_PC_I64_gfx12};
+  case AMDGPU::S_CBRANCH_EXECZ_gfx12:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_EXECNZ_gfx12,
+                          AMDGPU::S_ADD_PC_I64_gfx12};
+  case AMDGPU::S_CBRANCH_EXECNZ_gfx12:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_EXECZ_gfx12,
+                          AMDGPU::S_ADD_PC_I64_gfx12};
+  case AMDGPU::S_BRANCH_gfx13:
+    return LongBranchInfo{0, AMDGPU::S_ADD_PC_I64_gfx13};
+  case AMDGPU::S_CBRANCH_SCC0_gfx13:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_SCC1_gfx13,
+                          AMDGPU::S_ADD_PC_I64_gfx13};
+  case AMDGPU::S_CBRANCH_SCC1_gfx13:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_SCC0_gfx13,
+                          AMDGPU::S_ADD_PC_I64_gfx13};
+  case AMDGPU::S_CBRANCH_VCCZ_gfx13:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_VCCNZ_gfx13,
+                          AMDGPU::S_ADD_PC_I64_gfx13};
+  case AMDGPU::S_CBRANCH_VCCNZ_gfx13:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_VCCZ_gfx13,
+                          AMDGPU::S_ADD_PC_I64_gfx13};
+  case AMDGPU::S_CBRANCH_EXECZ_gfx13:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_EXECNZ_gfx13,
+                          AMDGPU::S_ADD_PC_I64_gfx13};
+  case AMDGPU::S_CBRANCH_EXECNZ_gfx13:
+    return LongBranchInfo{AMDGPU::S_CBRANCH_EXECZ_gfx13,
+                          AMDGPU::S_ADD_PC_I64_gfx13};
+  default:
+    return std::nullopt;
+  }
+}
 
 void AMDGPUAsmBackend::relaxInstruction(MCInst &Inst,
                                         const MCSubtargetInfo &STI) const {
+  if (STI.hasFeature(AMDGPU::FeatureUseAddPC64Inst)) {
+    std::optional<LongBranchInfo> Info = getLongBranchInfo(Inst.getOpcode());
+    assert(Info && "unexpected instruction to relax");
+    MCInst Res;
+    if (Info->SkipOpc) {
+      Res.setOpcode(AMDGPU::S_CBRANCH_LONG);
+      Res.addOperand(MCOperand::createImm(Info->SkipOpc));
+    } else {
+      Res.setOpcode(AMDGPU::S_BRANCH_LONG);
+    }
+    Res.addOperand(MCOperand::createImm(Info->AddPCOpc));
+    Res.addOperand(Inst.getOperand(0));
+    Inst = std::move(Res);
+    return;
+  }
+
   MCInst Res;
   unsigned RelaxedOpcode = AMDGPU::getSOPPWithRelaxation(Inst.getOpcode());
   Res.setOpcode(RelaxedOpcode);
@@ -62,13 +135,26 @@ void AMDGPUAsmBackend::relaxInstruction(MCInst &Inst,
   Inst = std::move(Res);
 }
 
-bool AMDGPUAsmBackend::fixupNeedsRelaxationAdvanced(const MCFragment &,
+bool AMDGPUAsmBackend::fixupNeedsRelaxationAdvanced(const MCFragment &F,
                                                     const MCFixup &Fixup,
-                                                    const MCValue &,
+                                                    const MCValue &Target,
                                                     uint64_t Value,
                                                     bool Resolved) const {
+  if (F.getSubtargetInfo()->hasFeature(AMDGPU::FeatureUseAddPC64Inst)) {
+    if (!Resolved) {
+      // Do not relax branches to undefined symbols, so that the object writer
+      // still reports them as undefined labels, which are most likely typos.
+      const MCSymbol *Sym = Target.getAddSym();
+      return !Sym || !Sym->isUndefined();
+    }
+
+    // Relax short branches that are out of range into long branches.
+    return !isInt<16>((int64_t(Value) - 4) / 4);
+  }
+
   if (!Resolved)
     return true;
+
   // if the branch target has an offset of x3f this needs to be relaxed to
   // add a s_nop 0 immediately after branch to effectively increment offset
   // for hardware workaround in gfx1010
@@ -78,6 +164,13 @@ bool AMDGPUAsmBackend::fixupNeedsRelaxationAdvanced(const MCFragment &,
 bool AMDGPUAsmBackend::mayNeedRelaxation(unsigned Opcode,
                                          ArrayRef<MCOperand> Operands,
                                          const MCSubtargetInfo &STI) const {
+  if (STI.hasFeature(AMDGPU::FeatureUseAddPC64Inst)) {
+    // Branches with a symbolic target can be relaxed into long branches.
+    int64_t Imm;
+    return getLongBranchInfo(Opcode) && Operands[0].isExpr() &&
+           !Operands[0].getExpr()->evaluateAsAbsolute(Imm);
+  }
+
   if (!STI.hasFeature(AMDGPU::FeatureOffset3fBug))
     return false;
 
@@ -91,6 +184,8 @@ static unsigned getFixupKindNumBytes(unsigned Kind) {
   switch (Kind) {
   case AMDGPU::fixup_si_sopp_br:
     return 2;
+  case AMDGPU::fixup_si_add_pc_lit32:
+    return 4;
   case FK_SecRel_1:
   case FK_Data_1:
     return 1;
@@ -121,6 +216,11 @@ static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
 
     return BrImm;
   }
+  case AMDGPU::fixup_si_add_pc_lit32:
+    // The literal is sign-extended to 64 bits.
+    if (Ctx && !isInt<32>(SignedValue))
+      Ctx->reportError(Fixup.getLoc(), "branch size exceeds 32 bits");
+    return Value;
   case FK_Data_1:
   case FK_Data_2:
   case FK_Data_4:
@@ -179,6 +279,7 @@ MCFixupKindInfo AMDGPUAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
   const static MCFixupKindInfo Infos[AMDGPU::NumTargetFixupKinds] = {
       // name                   offset bits  flags
       {"fixup_si_sopp_br", 0, 16, 0},
+      {"fixup_si_add_pc_lit32", 0, 32, 0},
   };
 
   if (mc::isRelocation(Kind))
diff --git a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFObjectWriter.cpp b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFObjectWriter.cpp
index 0d5a8be6220db2..1c278a5d0961d6 100644
--- a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFObjectWriter.cpp
+++ b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFObjectWriter.cpp
@@ -78,6 +78,9 @@ unsigned AMDGPUELFObjectWriter::getRelocType(const MCFixup &Fixup,
     return IsPCRel ? ELF::R_AMDGPU_REL64 : ELF::R_AMDGPU_ABS64;
   }
 
+  if (Fixup.getKind() == AMDGPU::fixup_si_add_pc_lit32)
+    return ELF::R_AMDGPU_REL32;
+
   if (Fixup.getKind() == AMDGPU::fixup_si_sopp_br) {
     const auto *SymA = Target.getAddSym();
     assert(SymA);
diff --git a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUFixupKinds.h b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUFixupKinds.h
index d49bb196ab3a18..2af2c2bf930bcf 100644
--- a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUFixupKinds.h
+++ b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUFixupKinds.h
@@ -17,6 +17,10 @@ enum Fixups {
   /// 16-bit PC relative fixup for SOPP branch instructions.
   fixup_si_sopp_br = FirstTargetFixupKind,
 
+  /// 32-bit PC relative fixup for the literal of s_add_pc_i64 when it is used
+  /// as a long branch.
+  fixup_si_add_pc_lit32,
+
   // Marker
   LastTargetFixupKind,
   NumTargetFixupKinds = LastTargetFixupKind - FirstTargetFixupKind
diff --git a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp
index 18c0919471d6dc..9c9a6982bb0cd0 100644
--- a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp
+++ b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp
@@ -21,6 +21,7 @@
 #include "llvm/MC/MCCodeEmitter.h"
 #include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCInstBuilder.h"
 #include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCSubtargetInfo.h"
@@ -35,10 +36,12 @@ namespace {
 class AMDGPUMCCodeEmitter : public MCCodeEmitter {
   const MCRegisterInfo &MRI;
   const MCInstrInfo &MCII;
+  MCContext &Ctx;
 
 public:
-  AMDGPUMCCodeEmitter(const MCInstrInfo &MCII, const MCRegisterInfo &MRI)
-      : MRI(MRI), MCII(MCII) {}
+  AMDGPUMCCodeEmitter(const MCInstrInfo &MCII, const MCRegisterInfo &MRI,
+                      MCContext &Ctx)
+      : MRI(MRI), MCII(MCII), Ctx(Ctx) {}
 
   /// Encode the instruction and write it to the OS.
   void encodeInstruction(const MCInst &MI, SmallVectorImpl<char> &CB,
@@ -84,6 +87,10 @@ class AMDGPUMCCodeEmitter : public MCCodeEmitter {
                             const MCSubtargetInfo &STI) const;
 
 private:
+  void expandLongBranch(const MCInst &MI, SmallVectorImpl<char> &CB,
+                        SmallVectorImpl<MCFixup> &Fixups,
+                        const MCSubtargetInfo &STI) const;
+
   uint64_t getImplicitOpSelHiEncoding(int Opcode) const;
   void getMachineOpValueCommon(const MCInst &MI, const MCOperand &MO,
                                unsigned OpNo, APInt &Op,
@@ -112,7 +119,7 @@ class AMDGPUMCCodeEmitter : public MCCodeEmitter {
 
 MCCodeEmitter *llvm::createAMDGPUMCCodeEmitter(const MCInstrInfo &MCII,
                                                MCContext &Ctx) {
-  return new AMDGPUMCCodeEmitter(MCII, *Ctx.getRegisterInfo());
+  return new AMDGPUMCCodeEmitter(MCII, *Ctx.getRegisterInfo(), Ctx);
 }
 
 static void addFixup(SmallVectorImpl<MCFixup> &Fixups, uint32_t Offset,
@@ -403,6 +410,11 @@ void AMDGPUMCCodeEmitter::encodeInstruction(const MCInst &MI,
                                             SmallVectorImpl<MCFixup> &Fixups,
                                             const MCSubtargetInfo &STI) const {
   int Opcode = MI.getOpcode();
+  if (Opcode == AMDGPU::S_BRANCH_LONG || Opcode == AMDGPU::S_CBRANCH_LONG) {
+    expandLongBranch(MI, CB, Fixups, STI);
+    return;
+  }
+
   APInt Encoding, Scratch;
   getBinaryCodeForInstr(MI, Fixups, Encoding, Scratch,  STI);
   const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
@@ -495,6 +507,40 @@ void AMDGPUMCCodeEmitter::encodeInstruction(const MCInst &MI,
   }
 }
 
+// Expand S_BRANCH_LONG or S_CBRANCH_LONG, created by branch relaxation, into an
+// s_add_pc_i64 with a 32-bit literal, optionally preceded by an inverted short
+// branch that skips over it. s_add_pc_i64 sign-extends the literal, so this can
+// reach +/-2GB, which is assumed to be enough for any branch within a single
+// code object.
+void AMDGPUMCCodeEmitter::expandLongBranch(const MCInst &MI,
+                                           SmallVectorImpl<char> &CB,
+                                           SmallVectorImpl<MCFixup> &Fixups,
+                                           const MCSubtargetInfo &STI) const {
+  bool IsCond = MI.getOpcode() == AMDGPU::S_CBRANCH_LONG;
+  unsigned AddPCOpc = MI.getOperand(IsCond ? 1 : 0).getImm();
+  const MCExpr *Target = MI.getOperand(IsCond ? 2 : 1).getExpr();
+
+  if (IsCond) {
+    // Skip over the 2 dwords of the s_add_pc_i64.
+    unsigned SkipOpc = MI.getOperand(0).getImm();
+    encodeInstruction(MCInstBuilder(SkipOpc).addImm(2), CB, Fixups, STI);
+  }
+
+  // Encode s_add_pc_i64 with lit(0) to force a zero 32-bit literal, which the
+  // fixup will fill in.
+  uint32_t LitOffset = CB.size() + 4;
+  const MCExpr *Zero = AMDGPUMCExpr::createLit(LitModifier::Lit, 0, Ctx);
+  encodeInstruction(MCInstBuilder(AddPCOpc).addExpr(Zero), CB, Fixups, STI);
+  assert(CB.size() == LitOffset + 4 && "expected a 32-bit literal");
+
+  // s_add_pc_i64 adds the literal to the address of the next instruction, which
+  // is 4 bytes after the literal.
+  const MCExpr *Value = MCBinaryExpr::createAdd(
+      Target, MCConstantExpr::create(-4, Ctx), Ctx, Target->getLoc());
+  addFixup(Fixups, LitOffset, Value, AMDGPU::fixup_si_add_pc_lit32,
+           /*PCRel=*/true);
+}
+
 void AMDGPUMCCodeEmitter::getSOPPBrEncoding(const MCInst &MI, unsigned OpNo,
                                             APInt &Op,
                                             SmallVectorImpl<MCFixup> &Fixups,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
index 78ba4d6e01e2ec..385c42f6b3eecb 100644
--- a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
@@ -3089,6 +3089,11 @@ bool SIInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
   // because its dest block is unanalyzable.
   assert(isSOPP(BranchOp) || isSOPK(BranchOp));
 
+  // With s_add_pc_i64, out of range branches are relaxed by the assembler
+  // without needing any registers.
+  if (ST.useAddPC64Inst())
+    return true;
+
   // Convert to dwords.
   BrOffset /= 4;
 
@@ -3125,29 +3130,16 @@ void SIInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
   assert(RestoreBB.empty() &&
          "restore block should be inserted for restoring clobbered registers");
 
+  assert(!ST.useAddPC64Inst() &&
+         "long branches should be relaxed by the assembler");
+  assert(RS && "RegScavenger required for long branching");
+
   MachineFunction *MF = MBB.getParent();
   MachineRegisterInfo &MRI = MF->getRegInfo();
   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
   auto I = MBB.end();
   auto &MCCtx = MF->getContext();
 
-  if (ST.useAddPC64Inst()) {
-    MCSymbol *Offset =
-        MCCtx.createTempSymbol("offset", /*AlwaysAddSuffix=*/true);
-    auto AddPC = BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_PC_I64))
-                     .addSym(Offset, MO_FAR_BRANCH_OFFSET);
-    MCSymbol *PostAddPCLabel =
-        MCCtx.createTempSymbol("post_addpc", /*AlwaysAddSuffix=*/true);
-    AddPC->setPostInstrSymbol(*MF, PostAddPCLabel);
-    auto *OffsetExpr = MCBinaryExpr::createSub(
-        MCSymbolRefExpr::create(DestBB.getSymbol(), MCCtx),
-        MCSymbolRefExpr::create(PostAddPCLabel, MCCtx), MCCtx);
-    Offset->setVariableValue(OffsetExpr);
-    return;
-  }
-
-  assert(RS && "RegScavenger required for long branching");
-
   // FIXME: Virtual register workaround for RegScavenger not working with empty
   // blocks.
   Register PCReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
@@ -10437,7 +10429,11 @@ unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
 
 TargetInstrInfo::InstSizeVerifyMode
 SIInstrInfo::getInstSizeVerifyMode(const MachineInstr &MI) const {
-  if (MI.isBranch() && ST.hasOffset3fBug())
+  // Branches may be relaxed by the assembler. The final layout is not known
+  // until then, so getInstSizeInBytes reports the size of the short form, which
+  // is the common case, and size-based heuristics may undercount code that has
+  // long branches.
+  if (MI.isBranch() && (ST.hasOffset3fBug() || ST.useAddPC64Inst()))
     return InstSizeVerifyMode::NoVerify;
   return InstSizeVerifyMode::ExactSize;
 }
diff --git a/llvm/lib/Target/AMDGPU/SIProgramInfo.cpp b/llvm/lib/Target/AMDGPU/SIProgramInfo.cpp
index 713f214bf315a8..c7336a106594f4 100644
--- a/llvm/lib/Target/AMDGPU/SIProgramInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/SIProgramInfo.cpp
@@ -229,6 +229,8 @@ uint64_t SIProgramInfo::getFunctionCodeSize(const MachineFunction &MF) {
 
     for (const MachineInstr &MI : MBB) {
       // TODO: CodeSize should account for multiple functions.
+      // FIXME: This undercounts branches that are relaxed by the assembler. See
+      // SIInstrInfo::getInstSizeVerifyMode.
 
       if (MI.isMetaInstruction())
         continue;
diff --git a/llvm/lib/Target/AMDGPU/SOPInstructions.td b/llvm/lib/Target/AMDGPU/SOPInstructions.td
index b336af3bcd01f8..39851a12aa4372 100644
--- a/llvm/lib/Target/AMDGPU/SOPInstructions.td
+++ b/llvm/lib/Target/AMDGPU/SOPInstructions.td
@@ -1648,6 +1648,30 @@ defm S_CBRANCH_CDBGUSER : SOPP_With_Relaxation <
 } // End isBranch = 1
 } // End isTerminator = 1
 
+// Long branches that MC branch relaxation can create on subtargets with
+// FeatureUseAddPC64Inst. These are never generated by codegen. $add_pc_opc is
+// the MC opcode of s_add_pc_i64 and $skip_opc is the MC opcode of the short
+// branch with the inverted condition. They are encoded as:
+//
+// S_BRANCH_LONG:
+//   s_add_pc_i64 $target   ; 32-bit literal
+//
+// S_CBRANCH_LONG:
+//   $skip_opc 2
+//   s_add_pc_i64 $target   ; 32-bit literal
+let isBranch = 1, isTerminator = 1 in {
+def S_BRANCH_LONG : PseudoInstSI <(outs),
+  (ins i32imm:$add_pc_opc, SOPPBrTarget:$target)> {
+  let isBarrier = 1;
+  let Size = 8;
+}
+
+def S_CBRANCH_LONG : PseudoInstSI <(outs),
+  (ins i32imm:$skip_opc, i32imm:$add_pc_opc, SOPPBrTarget:$target)> {
+  let Size = 12;
+}
+} // End isBranch = 1, isTerminator = 1
+
 let hasSideEffects = 1 in {
 def S_BARRIER : SOPP_Pseudo <"s_barrier", (ins), "",
   [(int_amdgcn_s_barrier)]> {
diff --git a/llvm/test/CodeGen/AMDGPU/branch-relaxation-gfx1250.ll b/llvm/test/CodeGen/AMDGPU/branch-relaxation-gfx1250.ll
index b472ab6b475188..4980880d884216 100644
--- a/llvm/test/CodeGen/AMDGPU/branch-relaxation-gfx1250.ll
+++ b/llvm/test/CodeGen/AMDGPU/branch-relaxation-gfx1250.ll
@@ -1,5 +1,11 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
 ; RUN: llc -mtriple=amdgpu12.50 -amdgpu-s-branch-bits=4 -simplifycfg-require-and-preserve-domtree=1 -amdgpu-long-branch-factor=0 < %s | FileCheck -enable-var-scope -check-prefix=GCN %s
+
+; On gfx1251, long branches are relaxed by the assembler instead of the
+; BranchRelaxation pass, so -amdgpu-s-branch-bits has no effect. The point of
+; the GCN-ADD-PC64 checks is to show that codegen does not relax any branches.
+; See branch-relaxation-gfx1251.ll and MC/AMDGPU/branch-relaxation-add-pc64.s
+; for tests of the relaxation itself.
 ; RUN: llc -mtriple=amdgpu12.51 -amdgpu-s-branch-bits=4 -simplifycfg-require-and-preserve-domtree=1 -amdgpu-long-branch-factor=0 < %s | FileCheck -enable-var-scope -check-prefix=GCN-ADD-PC64 %s
 
 
@@ -60,11 +66,8 @@ define amdgpu_kernel void @uniform_conditional_max_short_forward_branch(ptr addr
 ; GCN-ADD-PC64-NEXT:    s_load_b32 s0, s[4:5], 0x2c nv
 ; GCN-ADD-PC64-NEXT:    s_wait_kmcnt 0x0
 ; GCN-ADD-PC64-NEXT:    s_cmp_eq_u32 s0, 0
-; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB0_1
-; GCN-ADD-PC64-NEXT:  ; %bb.3: ; %bb
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB0_2-.Lpost_addpc0
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc0:
-; GCN-ADD-PC64-NEXT:  .LBB0_1: ; %bb2
+; GCN-ADD-PC64-NEXT:    s_cbranch_scc1 .LBB0_2
+; GCN-ADD-PC64-NEXT:  ; %bb.1: ; %bb2
 ; GCN-ADD-PC64-NEXT:    ;;#ASMSTART
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
@@ -135,11 +138,8 @@ define amdgpu_kernel void @uniform_conditional_min_long_forward_branch(ptr addrs
 ; GCN-ADD-PC64-NEXT:    s_load_b32 s0, s[4:5], 0x2c nv
 ; GCN-ADD-PC64-NEXT:    s_wait_kmcnt 0x0
 ; GCN-ADD-PC64-NEXT:    s_cmp_eq_u32 s0, 0
-; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB1_1
-; GCN-ADD-PC64-NEXT:  ; %bb.3: ; %bb0
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB1_2-.Lpost_addpc1
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc1:
-; GCN-ADD-PC64-NEXT:  .LBB1_1: ; %bb2
+; GCN-ADD-PC64-NEXT:    s_cbranch_scc1 .LBB1_2
+; GCN-ADD-PC64-NEXT:  ; %bb.1: ; %bb2
 ; GCN-ADD-PC64-NEXT:    ;;#ASMSTART
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
@@ -213,11 +213,8 @@ define amdgpu_kernel void @uniform_conditional_min_long_forward_vcnd_branch(ptr
 ; GCN-ADD-PC64-NEXT:    s_load_b32 s0, s[4:5], 0x2c nv
 ; GCN-ADD-PC64-NEXT:    s_wait_kmcnt 0x0
 ; GCN-ADD-PC64-NEXT:    s_cmp_eq_f32 s0, 0
-; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB2_1
-; GCN-ADD-PC64-NEXT:  ; %bb.3: ; %bb0
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB2_2-.Lpost_addpc2
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc2:
-; GCN-ADD-PC64-NEXT:  .LBB2_1: ; %bb2
+; GCN-ADD-PC64-NEXT:    s_cbranch_scc1 .LBB2_2
+; GCN-ADD-PC64-NEXT:  ; %bb.1: ; %bb2
 ; GCN-ADD-PC64-NEXT:    ;;#ASMSTART
 ; GCN-ADD-PC64-NEXT:     ; 32 bytes
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
@@ -305,11 +302,8 @@ define amdgpu_kernel void @min_long_forward_vbranch(ptr addrspace(1) %arg) #0 {
 ; GCN-ADD-PC64-NEXT:    v_add_nc_u64_e32 v[0:1], s[0:1], v[0:1]
 ; GCN-ADD-PC64-NEXT:    s_mov_b32 s0, exec_lo
 ; GCN-ADD-PC64-NEXT:    v_cmpx_ne_u32_e32 0, v2
-; GCN-ADD-PC64-NEXT:    s_cbranch_execnz .LBB3_1
-; GCN-ADD-PC64-NEXT:  ; %bb.3: ; %bb
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB3_2-.Lpost_addpc3
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc3:
-; GCN-ADD-PC64-NEXT:  .LBB3_1: ; %bb2
+; GCN-ADD-PC64-NEXT:    s_cbranch_execz .LBB3_2
+; GCN-ADD-PC64-NEXT:  ; %bb.1: ; %bb2
 ; GCN-ADD-PC64-NEXT:    ;;#ASMSTART
 ; GCN-ADD-PC64-NEXT:     ; 32 bytes
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
@@ -387,12 +381,8 @@ define amdgpu_kernel void @long_backward_sbranch(ptr addrspace(1) %arg) #0 {
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
 ; GCN-ADD-PC64-NEXT:    ;;#ASMEND
 ; GCN-ADD-PC64-NEXT:    s_cmp_lt_i32 s0, 10
-; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB4_2
-; GCN-ADD-PC64-NEXT:  ; %bb.3: ; %bb2
-; GCN-ADD-PC64-NEXT:    ; in Loop: Header=BB4_1 Depth=1
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB4_1-.Lpost_addpc4
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc4:
-; GCN-ADD-PC64-NEXT:  .LBB4_2: ; %bb3
+; GCN-ADD-PC64-NEXT:    s_cbranch_scc1 .LBB4_1
+; GCN-ADD-PC64-NEXT:  ; %bb.2: ; %bb3
 ; GCN-ADD-PC64-NEXT:    s_endpgm
 bb:
   br label %bb2
@@ -479,11 +469,8 @@ define amdgpu_kernel void @uniform_unconditional_min_long_forward_branch(ptr add
 ; GCN-ADD-PC64-NEXT:    s_wait_kmcnt 0x0
 ; GCN-ADD-PC64-NEXT:    s_cmp_eq_u32 s0, 0
 ; GCN-ADD-PC64-NEXT:    s_mov_b32 s0, -1
-; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB5_1
-; GCN-ADD-PC64-NEXT:  ; %bb.7: ; %bb0
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB5_4-.Lpost_addpc6
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc6:
-; GCN-ADD-PC64-NEXT:  .LBB5_1: ; %Flow
+; GCN-ADD-PC64-NEXT:    s_cbranch_scc1 .LBB5_4
+; GCN-ADD-PC64-NEXT:  ; %bb.1: ; %Flow
 ; GCN-ADD-PC64-NEXT:    s_and_b32 s0, s0, exec_lo
 ; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB5_3
 ; GCN-ADD-PC64-NEXT:  .LBB5_2: ; %bb2
@@ -506,13 +493,8 @@ define amdgpu_kernel void @uniform_unconditional_min_long_forward_branch(ptr add
 ; GCN-ADD-PC64-NEXT:    s_mov_b32 s0, 0
 ; GCN-ADD-PC64-NEXT:    s_sleep 0
 ; GCN-ADD-PC64-NEXT:    s_and_b32 s0, s0, exec_lo
-; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB5_5
-; GCN-ADD-PC64-NEXT:  ; %bb.9: ; %bb3
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB5_2-.Lpost_addpc7
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc7:
-; GCN-ADD-PC64-NEXT:  .LBB5_5: ; %bb3
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB5_3-.Lpost_addpc5
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc5:
+; GCN-ADD-PC64-NEXT:    s_cbranch_scc1 .LBB5_2
+; GCN-ADD-PC64-NEXT:    s_branch .LBB5_3
 bb0:
   %tmp = icmp ne i32 %arg1, 0
   br i1 %tmp, label %bb2, label %bb3
@@ -577,12 +559,8 @@ define amdgpu_kernel void @uniform_unconditional_min_long_backward_branch(ptr ad
 ; GCN-ADD-PC64-NEXT:    ;;#ASMEND
 ; GCN-ADD-PC64-NEXT:    s_sleep 0
 ; GCN-ADD-PC64-NEXT:    s_sleep 0
-; GCN-ADD-PC64-NEXT:    s_cbranch_vccz .LBB6_2
-; GCN-ADD-PC64-NEXT:  ; %bb.3: ; %loop
-; GCN-ADD-PC64-NEXT:    ; in Loop: Header=BB6_1 Depth=1
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB6_1-.Lpost_addpc8
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc8:
-; GCN-ADD-PC64-NEXT:  .LBB6_2: ; %DummyReturnBlock
+; GCN-ADD-PC64-NEXT:    s_cbranch_vccnz .LBB6_1
+; GCN-ADD-PC64-NEXT:  ; %bb.2: ; %DummyReturnBlock
 ; GCN-ADD-PC64-NEXT:    s_endpgm
 entry:
   br label %loop
@@ -666,11 +644,8 @@ define amdgpu_kernel void @expand_requires_expand(i32 %cond0) #0 {
 ; GCN-ADD-PC64-NEXT:  .LBB7_2: ; %Flow
 ; GCN-ADD-PC64-NEXT:    s_delay_alu instid0(SALU_CYCLE_1)
 ; GCN-ADD-PC64-NEXT:    s_and_b32 s0, s0, exec_lo
-; GCN-ADD-PC64-NEXT:    s_cbranch_scc1 .LBB7_3
-; GCN-ADD-PC64-NEXT:  ; %bb.5: ; %Flow
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB7_4-.Lpost_addpc9
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc9:
-; GCN-ADD-PC64-NEXT:  .LBB7_3: ; %bb2
+; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB7_4
+; GCN-ADD-PC64-NEXT:  ; %bb.3: ; %bb2
 ; GCN-ADD-PC64-NEXT:    ;;#ASMSTART
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
@@ -759,11 +734,8 @@ define amdgpu_kernel void @uniform_inside_divergent(ptr addrspace(1) %out, i32 %
 ; GCN-ADD-PC64-NEXT:    s_mov_b32 s3, exec_lo
 ; GCN-ADD-PC64-NEXT:    s_delay_alu instid0(VALU_DEP_1)
 ; GCN-ADD-PC64-NEXT:    v_cmpx_gt_u32_e32 16, v0
-; GCN-ADD-PC64-NEXT:    s_cbranch_execnz .LBB8_1
-; GCN-ADD-PC64-NEXT:  ; %bb.4: ; %entry
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB8_3-.Lpost_addpc10
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc10:
-; GCN-ADD-PC64-NEXT:  .LBB8_1: ; %if
+; GCN-ADD-PC64-NEXT:    s_cbranch_execz .LBB8_3
+; GCN-ADD-PC64-NEXT:  ; %bb.1: ; %if
 ; GCN-ADD-PC64-NEXT:    s_load_b96 s[0:2], s[4:5], 0x24 nv
 ; GCN-ADD-PC64-NEXT:    v_mov_b32_e32 v0, 0
 ; GCN-ADD-PC64-NEXT:    s_wait_kmcnt 0x0
@@ -874,11 +846,8 @@ define amdgpu_kernel void @analyze_mask_branch() #0 {
 ; GCN-ADD-PC64-NEXT:  .LBB9_2: ; %Flow1
 ; GCN-ADD-PC64-NEXT:    s_wait_xcnt 0x0
 ; GCN-ADD-PC64-NEXT:    s_and_not1_saveexec_b32 s0, s0
-; GCN-ADD-PC64-NEXT:    s_cbranch_execnz .LBB9_3
-; GCN-ADD-PC64-NEXT:  ; %bb.6: ; %Flow1
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB9_5-.Lpost_addpc11
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc11:
-; GCN-ADD-PC64-NEXT:  .LBB9_3: ; %loop.preheader
+; GCN-ADD-PC64-NEXT:    s_cbranch_execz .LBB9_5
+; GCN-ADD-PC64-NEXT:  ; %bb.3: ; %loop.preheader
 ; GCN-ADD-PC64-NEXT:    s_mov_b32 vcc_lo, 0
 ; GCN-ADD-PC64-NEXT:  .LBB9_4: ; %loop
 ; GCN-ADD-PC64-NEXT:    ; =>This Inner Loop Header: Depth=1
@@ -892,11 +861,7 @@ define amdgpu_kernel void @analyze_mask_branch() #0 {
 ; GCN-ADD-PC64-NEXT:    ;;#ASMEND
 ; GCN-ADD-PC64-NEXT:    s_sleep 0
 ; GCN-ADD-PC64-NEXT:    s_sleep 0
-; GCN-ADD-PC64-NEXT:    s_cbranch_vccnz .LBB9_5
-; GCN-ADD-PC64-NEXT:  ; %bb.8: ; %loop
-; GCN-ADD-PC64-NEXT:    ; in Loop: Header=BB9_4 Depth=1
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB9_4-.Lpost_addpc12
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc12:
+; GCN-ADD-PC64-NEXT:    s_cbranch_vccz .LBB9_4
 ; GCN-ADD-PC64-NEXT:  .LBB9_5: ; %UnifiedReturnBlock
 ; GCN-ADD-PC64-NEXT:    s_endpgm
 entry:
@@ -1030,11 +995,8 @@ define amdgpu_kernel void @long_branch_hang(ptr addrspace(1) nocapture %arg, i32
 ; GCN-ADD-PC64-NEXT:    s_mov_b32 s0, 0
 ; GCN-ADD-PC64-NEXT:    s_cselect_b32 s8, -1, 0
 ; GCN-ADD-PC64-NEXT:    s_cmp_lt_i32 s3, 6
-; GCN-ADD-PC64-NEXT:    s_cbranch_scc1 .LBB10_1
-; GCN-ADD-PC64-NEXT:  ; %bb.7: ; %bb
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB10_2-.Lpost_addpc13
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc13:
-; GCN-ADD-PC64-NEXT:  .LBB10_1: ; %bb13
+; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB10_2
+; GCN-ADD-PC64-NEXT:  ; %bb.1: ; %bb13
 ; GCN-ADD-PC64-NEXT:    ;;#ASMSTART
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
 ; GCN-ADD-PC64-NEXT:    v_nop_e64
@@ -1044,10 +1006,8 @@ define amdgpu_kernel void @long_branch_hang(ptr addrspace(1) nocapture %arg, i32
 ; GCN-ADD-PC64-NEXT:    s_mov_b32 s0, s8
 ; GCN-ADD-PC64-NEXT:    s_sleep 0
 ; GCN-ADD-PC64-NEXT:    s_and_b32 s7, s7, exec_lo
-; GCN-ADD-PC64-NEXT:    s_cbranch_scc1 .LBB10_3
-; GCN-ADD-PC64-NEXT:  ; %bb.9: ; %bb13
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB10_4-.Lpost_addpc14
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc14:
+; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB10_4
+; GCN-ADD-PC64-NEXT:    s_branch .LBB10_3
 ; GCN-ADD-PC64-NEXT:  .LBB10_2: ; %Flow
 ; GCN-ADD-PC64-NEXT:    s_and_b32 s7, s7, exec_lo
 ; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB10_4
@@ -1062,11 +1022,8 @@ define amdgpu_kernel void @long_branch_hang(ptr addrspace(1) nocapture %arg, i32
 ; GCN-ADD-PC64-NEXT:    s_delay_alu instid0(SALU_CYCLE_1)
 ; GCN-ADD-PC64-NEXT:    s_and_b32 s0, s0, exec_lo
 ; GCN-ADD-PC64-NEXT:    ; implicit-def: $sgpr0
-; GCN-ADD-PC64-NEXT:    s_cbranch_scc1 .LBB10_5
-; GCN-ADD-PC64-NEXT:  ; %bb.11: ; %Flow5
-; GCN-ADD-PC64-NEXT:    s_add_pc_i64 .LBB10_6-.Lpost_addpc15
-; GCN-ADD-PC64-NEXT:  .Lpost_addpc15:
-; GCN-ADD-PC64-NEXT:  .LBB10_5: ; %bb14
+; GCN-ADD-PC64-NEXT:    s_cbranch_scc0 .LBB10_6
+; GCN-ADD-PC64-NEXT:  ; %bb.5: ; %bb14
 ; GCN-ADD-PC64-NEXT:    s_cmp_lt_i32 s1, 9
 ; GCN-ADD-PC64-NEXT:    s_cselect_b32 s0, -1, 0
 ; GCN-ADD-PC64-NEXT:    s_cmp_lt_i32 s2, s3
diff --git a/llvm/test/CodeGen/AMDGPU/branch-relaxation-gfx1251.ll b/llvm/test/CodeGen/AMDGPU/branch-relaxation-gfx1251.ll
new file mode 100644
index 00000000000000..5543ddf73607ec
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/branch-relaxation-gfx1251.ll
@@ -0,0 +1,65 @@
+; RUN: llc -mtriple=amdgpu12.51 -filetype=obj < %s | llvm-objdump -d - | FileCheck --check-prefixes=CHECK,NORELAX %s
+; RUN: llc -mtriple=amdgpu12.51 -filetype=obj --mc-relax-all < %s | llvm-objdump -d - | FileCheck --check-prefixes=CHECK,RELAXALL %s
+
+; On subtargets with FeatureUseAddPC64Inst, branches are relaxed by the
+; assembler instead of the BranchRelaxation pass. Out of range branches are
+; relaxed into s_add_pc_i64 with a 32-bit literal, preceded by an inverted
+; branch over it if the original branch was conditional.
+
+; CHECK-LABEL: <short_forward_branch>:
+; NORELAX:          s_cbranch_scc1 {{.*}} // [[#%.12X,BR:]]:
+; NORELAX-NEXT:     s_nop 0 // [[#%.12X,BR+4]]:
+; NORELAX-NOT:      s_add_pc_i64
+; RELAXALL:         s_cbranch_scc0 2
+; RELAXALL-NEXT:    s_add_pc_i64 lit(0x[[#%x,OFFSET:]]) // [[#%.12X,ADDPC:]]:
+; RELAXALL:         s_load_b64 {{.*}} // [[#%.12X,ADDPC+8+OFFSET]]:
+; CHECK:            s_endpgm
+define amdgpu_kernel void @short_forward_branch(ptr addrspace(1) %arg, i32 %cnd) {
+bb:
+  %cmp = icmp eq i32 %cnd, 0
+  br i1 %cmp, label %bb3, label %bb2
+
+bb2:
+  call void asm sideeffect "s_nop 0", ""()
+  br label %bb3
+
+bb3:
+  store volatile i32 %cnd, ptr addrspace(1) %arg
+  ret void
+}
+
+; CHECK-LABEL: <long_forward_branch>:
+; CHECK:       s_cbranch_scc0 2
+; CHECK-NEXT:  s_add_pc_i64 0x20000 // [[#%.12X,ADDPC:]]:
+; CHECK:       s_load_b64 {{.*}} // [[#%.12X,ADDPC+8+0x20000]]:
+; CHECK:       s_endpgm
+define amdgpu_kernel void @long_forward_branch(ptr addrspace(1) %arg, i32 %cnd) {
+bb:
+  %cmp = icmp eq i32 %cnd, 0
+  br i1 %cmp, label %bb3, label %bb2
+
+bb2:
+  call void asm sideeffect ".fill 32768, 4, 0xbf800000", ""()
+  br label %bb3
+
+bb3:
+  store volatile i32 %cnd, ptr addrspace(1) %arg
+  ret void
+}
+
+; The loop starts immediately after the s_mov_b32, so the s_add_pc_i64 must
+; branch back to LOOP+4. Its literal is -0x2000c, sign-extended by the hardware,
+; but the disassembler prints it zero-extended.
+; CHECK-LABEL: <long_backward_branch>:
+; CHECK:       s_mov_b32 vcc_lo, exec_lo // [[#%.12X,LOOP:]]:
+; CHECK:       s_cbranch_vccz 2
+; CHECK-NEXT:  s_add_pc_i64 0xfffdfff4 // [[#%.12X,LOOP+0x20008]]:
+; CHECK-NEXT:  s_endpgm
+define amdgpu_kernel void @long_backward_branch() {
+entry:
+  br label %loop
+
+loop:
+  call void asm sideeffect ".fill 32768, 4, 0xbf800000", ""()
+  br label %loop
+}
diff --git a/llvm/test/MC/AMDGPU/branch-relaxation-add-pc64-range.s b/llvm/test/MC/AMDGPU/branch-relaxation-add-pc64-range.s
new file mode 100644
index 00000000000000..5aafd444296f43
--- /dev/null
+++ b/llvm/test/MC/AMDGPU/branch-relaxation-add-pc64-range.s
@@ -0,0 +1,28 @@
+// RUN: llvm-mc -triple=amdgpu12.51 -filetype=obj %s -o %t.o
+// RUN: llvm-objdump -d %t.o | FileCheck %s
+// RUN: not llvm-mc -triple=amdgpu12.51 -filetype=obj --defsym=ERR=1 %s -o /dev/null 2>&1 | FileCheck --check-prefix=ERR --implicit-check-not=error: %s
+
+// Test the range of branches that are relaxed into s_add_pc_i64. Its 32-bit
+// literal is sign-extended, so the offset from the next instruction must fit in
+// a signed 32-bit integer. A relaxed s_branch is 8 bytes long, so the offset is
+// target - (. + 8). The targets are defined with .set so that they are far away
+// without making the object file huge.
+
+// CHECK:      s_add_pc_i64 0x7fffffff
+.set fwd_max, . + 0x80000007
+  s_branch fwd_max
+
+// The disassembler prints the literal zero-extended.
+// CHECK-NEXT: s_add_pc_i64 0x80000000
+.set back_max, . - 0x7ffffff8
+  s_branch back_max
+
+.ifdef ERR
+// ERR: [[@LINE+2]]:12: error: branch size exceeds 32 bits
+.set fwd_over, . + 0x80000008
+  s_branch fwd_over
+
+// ERR: [[@LINE+2]]:12: error: branch size exceeds 32 bits
+.set back_over, . - 0x7ffffff9
+  s_branch back_over
+.endif
diff --git a/llvm/test/MC/AMDGPU/branch-relaxation-add-pc64.s b/llvm/test/MC/AMDGPU/branch-relaxation-add-pc64.s
new file mode 100644
index 00000000000000..5dceb7ddfc56b2
--- /dev/null
+++ b/llvm/test/MC/AMDGPU/branch-relaxation-add-pc64.s
@@ -0,0 +1,165 @@
+// RUN: llvm-mc -triple=amdgpu12.51-amd-amdhsa -filetype=obj %s -o %t.o
+// RUN: llvm-objdump -d --disassemble-symbols=fwd_short,fwd_max,fwd_over,fwd_cond,back_max,back_over,back_cond,ext_cond_global,ext_global,ext_weak,ext_other_section,ext_local %t.o | FileCheck %s
+// RUN: llvm-readobj -r %t.o | FileCheck --check-prefix=RELOC %s
+// RUN: llvm-mc -triple=amdgpu13.10-amd-amdhsa -mattr=+use-add-pc64-inst -filetype=obj %s -o %t13.o
+// RUN: llvm-objdump -d --disassemble-symbols=fwd_short,fwd_max,fwd_over,fwd_cond,back_max,back_over,back_cond,ext_cond_global,ext_global,ext_weak,ext_other_section,ext_local %t13.o | FileCheck %s
+// RUN: not llvm-mc -triple=amdgpu12.50-amd-amdhsa -filetype=obj %s -o /dev/null 2>&1 | FileCheck --check-prefix=ERR %s
+// RUN: not llvm-mc -triple=amdgpu12.51-amd-amdhsa -filetype=obj --defsym=UNDEF=1 %s -o /dev/null 2>&1 | FileCheck --check-prefix=UNDEF --implicit-check-not=error: %s
+
+// Test that SOPP branches are relaxed into s_add_pc_i64 with a 32-bit literal
+// when they are out of range, on subtargets with FeatureUseAddPC64Inst. The
+// literal is sign-extended by the hardware, but the disassembler prints negative
+// values zero-extended.
+
+// CHECK-LABEL: <fwd_short>:
+// CHECK-NEXT: s_branch
+// CHECK-NEXT: s_nop 0
+fwd_short:
+  s_branch fwd_short_target
+  s_nop 0
+fwd_short_target:
+  s_endpgm
+
+// The maximum forward branch offset is 0x7fff dwords.
+// CHECK-LABEL: <fwd_max>:
+// CHECK-NEXT: s_branch {{.*}} // {{[0-9A-F]+}}: {{....}}7FFF
+fwd_max:
+  s_branch fwd_max_target
+fwd_max_fill:
+  .fill 0x7fff, 4, 0xbf800000
+fwd_max_target:
+  s_endpgm
+
+// ERR: [[@LINE+5]]:12: error: branch size exceeds simm16
+// CHECK-LABEL: <fwd_over>:
+// CHECK-NEXT: s_add_pc_i64 0x20000 // {{[0-9A-F]+}}: BE804BFF 00020000
+// CHECK-EMPTY:
+fwd_over:
+  s_branch fwd_over_target
+fwd_over_fill:
+  .fill 0x8000, 4, 0xbf800000
+fwd_over_target:
+  s_endpgm
+
+// Conditional branches are relaxed into a short branch with the inverted
+// condition that skips over the s_add_pc_i64.
+// CHECK-LABEL: <fwd_cond>:
+// CHECK-NEXT: s_cbranch_scc1 {{.*}} // {{[0-9A-F]+}}: {{....}}0002
+// CHECK-NEXT: s_add_pc_i64 0x2003c
+// CHECK-NEXT: s_cbranch_scc0 {{.*}} // {{[0-9A-F]+}}: {{....}}0002
+// CHECK-NEXT: s_add_pc_i64 0x20030
+// CHECK-NEXT: s_cbranch_vccnz {{.*}} // {{[0-9A-F]+}}: {{....}}0002
+// CHECK-NEXT: s_add_pc_i64 0x20024
+// CHECK-NEXT: s_cbranch_vccz {{.*}} // {{[0-9A-F]+}}: {{....}}0002
+// CHECK-NEXT: s_add_pc_i64 0x20018
+// CHECK-NEXT: s_cbranch_execnz {{.*}} // {{[0-9A-F]+}}: {{....}}0002
+// CHECK-NEXT: s_add_pc_i64 0x2000c
+// CHECK-NEXT: s_cbranch_execz {{.*}} // {{[0-9A-F]+}}: {{....}}0002
+// CHECK-NEXT: s_add_pc_i64 0x20000
+// CHECK-EMPTY:
+fwd_cond:
+  s_cbranch_scc0 fwd_cond_target
+  s_cbranch_scc1 fwd_cond_target
+  s_cbranch_vccz fwd_cond_target
+  s_cbranch_vccnz fwd_cond_target
+  s_cbranch_execz fwd_cond_target
+  s_cbranch_execnz fwd_cond_target
+fwd_cond_fill:
+  .fill 0x8000, 4, 0xbf800000
+fwd_cond_target:
+  s_endpgm
+
+// The maximum backward branch offset is -0x8000 dwords.
+back_max_target:
+  .fill 0x7fff, 4, 0xbf800000
+// CHECK-LABEL: <back_max>:
+// CHECK-NEXT: s_branch {{.*}} // {{[0-9A-F]+}}: {{....}}8000
+back_max:
+  s_branch back_max_target
+
+back_over_target:
+  .fill 0x8000, 4, 0xbf800000
+// ERR: [[@LINE+4]]:12: error: branch size exceeds simm16
+// CHECK-LABEL: <back_over>:
+// CHECK-NEXT: s_add_pc_i64 0xfffdfff8 // {{[0-9A-F]+}}: BE804BFF FFFDFFF8
+back_over:
+  s_branch back_over_target
+
+// CHECK-LABEL: <back_cond>:
+// CHECK-NEXT: s_cbranch_execz {{.*}} // {{[0-9A-F]+}}: {{....}}0002
+// CHECK-NEXT: s_add_pc_i64 0xfffdffec
+back_cond:
+  s_cbranch_execnz back_over_target
+
+// Branches whose target cannot be resolved at assembly time are always relaxed
+// and use a 32-bit PC-relative relocation, even if the target turns out to be
+// nearby. This includes symbols in other sections, and global or weak symbols
+// in the same section, because ELF keeps relocations for PC-relative references
+// to non-local symbols. (Without FeatureUseAddPC64Inst these would use a short
+// branch with an R_AMDGPU_REL16 relocation.)
+
+.globl global_sym
+global_sym:
+  s_endpgm
+
+.weak weak_sym
+weak_sym:
+  s_endpgm
+
+local_sym:
+  s_endpgm
+
+// CHECK-LABEL: <ext_cond_global>:
+// CHECK-NEXT: s_cbranch_scc0 {{.*}} // {{[0-9A-F]+}}: {{....}}0002
+// CHECK-NEXT: s_add_pc_i64 lit(0x0)
+// CHECK-EMPTY:
+ext_cond_global:
+  s_cbranch_scc1 global_sym
+
+// CHECK-LABEL: <ext_global>:
+// CHECK-NEXT: s_add_pc_i64 lit(0x0)
+// CHECK-EMPTY:
+ext_global:
+  s_branch global_sym
+
+// CHECK-LABEL: <ext_weak>:
+// CHECK-NEXT: s_add_pc_i64 lit(0x0)
+// CHECK-EMPTY:
+ext_weak:
+  s_branch weak_sym
+
+// CHECK-LABEL: <ext_other_section>:
+// CHECK-NEXT: s_add_pc_i64 lit(0x0)
+// CHECK-EMPTY:
+ext_other_section:
+  s_branch other_section_sym
+
+// A branch to a nearby local symbol is resolved at assembly time, so it is not
+// relaxed and does not need a relocation.
+// CHECK-LABEL: <ext_local>:
+// CHECK-NEXT: s_branch local_sym
+// CHECK-EMPTY:
+ext_local:
+  s_branch local_sym
+
+// RELOC:      Section ({{[0-9]+}}) .rela.text {
+// RELOC-NEXT:   R_AMDGPU_REL32 global_sym 0xFFFFFFFFFFFFFFFC
+// RELOC-NEXT:   R_AMDGPU_REL32 global_sym 0xFFFFFFFFFFFFFFFC
+// RELOC-NEXT:   R_AMDGPU_REL32 weak_sym 0xFFFFFFFFFFFFFFFC
+// RELOC-NEXT:   R_AMDGPU_REL32 .text.other 0xFFFFFFFFFFFFFFFC
+// RELOC-NEXT: }
+
+// Branches to undefined symbols are not relaxed, so that they are still
+// diagnosed, because they are most likely typos.
+.ifdef UNDEF
+// UNDEF: [[@LINE+1]]:12: error: undefined label 'undefined_sym'
+  s_branch undefined_sym
+// UNDEF: [[@LINE+1]]:18: error: undefined label 'undefined_sym'
+  s_cbranch_scc0 undefined_sym
+// UNDEF: [[@LINE+1]]:12: error: undefined label '.Lundefined_temp'
+  s_branch .Lundefined_temp
+.endif
+
+.section .text.other,"ax", at progbits
+other_section_sym:
+  s_endpgm
diff --git a/llvm/test/MC/AMDGPU/max-branch-distance.s b/llvm/test/MC/AMDGPU/max-branch-distance.s
index 77f831fe162972..cbe5ba5300cc69 100644
--- a/llvm/test/MC/AMDGPU/max-branch-distance.s
+++ b/llvm/test/MC/AMDGPU/max-branch-distance.s
@@ -1,7 +1,30 @@
-//  RUN: not llvm-mc -triple=amdgpu6.00 -filetype=obj -o /dev/null %s 2>&1 | FileCheck -check-prefix=ERROR %s
-//  ERROR: max-branch-distance.s:7:12: error: branch size exceeds simm16
+// RUN: not llvm-mc -triple=amdgpu6.00 -filetype=obj -o /dev/null %s 2>&1 | FileCheck -check-prefix=ERROR %s
+// RUN: not llvm-mc -triple=amdgpu12.50 -filetype=obj -o /dev/null %s 2>&1 | FileCheck -check-prefix=ERROR %s
+
+// On subtargets with FeatureUseAddPC64Inst, out of range branches are silently
+// relaxed into s_add_pc_i64 instead of being diagnosed.
+// RUN: llvm-mc -triple=amdgpu12.51 -filetype=obj -o %t.o %s 2>&1 | count 0
+// RUN: llvm-objdump -d --disassemble-symbols=branch,cbranch,end %t.o | FileCheck -check-prefix=RELAX %s
 
 // fill v_nop
 LBB0_0:
     .fill 32768, 4, 0x0000007e
+
+// ERROR: max-branch-distance.s:[[@LINE+5]]:12: error: branch size exceeds simm16
+// The unconditional branch grows from 4 to 8 bytes.
+// RELAX:      [[#%.16x,BR:]] <branch>:
+// RELAX-NEXT: s_add_pc_i64
+branch:
   s_branch LBB0_0
+
+// ERROR: max-branch-distance.s:[[@LINE+6]]:18: error: branch size exceeds simm16
+// The conditional branch grows from 4 to 12 bytes.
+// RELAX:      [[#%.16x,BR+8]] <cbranch>:
+// RELAX-NEXT: s_cbranch_scc1
+// RELAX-NEXT: s_add_pc_i64
+cbranch:
+  s_cbranch_scc0 LBB0_0
+
+// RELAX:      [[#%.16x,BR+20]] <end>:
+end:
+  s_endpgm

>From a06e36d062ca06e807c6096c2afb2a53a515a96e Mon Sep 17 00:00:00 2001
From: Jay Foad <jay.foad at amd.com>
Date: Fri, 2 Oct 2026 11:51:29 +0100
Subject: [PATCH 2/2] Rename pseudos

---
 .../AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp      |  8 ++++----
 .../AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp   | 15 ++++++++-------
 llvm/lib/Target/AMDGPU/SOPInstructions.td         |  8 ++++----
 3 files changed, 16 insertions(+), 15 deletions(-)

diff --git a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp
index 43c4d22c6708e9..6d40dc863bc9e7 100644
--- a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp
+++ b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp
@@ -61,8 +61,8 @@ struct LongBranchInfo {
 
 } // End anonymous namespace
 
-// Get the information needed to relax a short branch into S_BRANCH_LONG or
-// S_CBRANCH_LONG on subtargets with FeatureUseAddPC64Inst.
+// Get the information needed to relax a short branch into S_BRANCH_long_pseudo
+// or S_CBRANCH_long_pseudo on subtargets with FeatureUseAddPC64Inst.
 static std::optional<LongBranchInfo> getLongBranchInfo(unsigned Opcode) {
   switch (Opcode) {
   case AMDGPU::S_BRANCH_gfx12:
@@ -117,10 +117,10 @@ void AMDGPUAsmBackend::relaxInstruction(MCInst &Inst,
     assert(Info && "unexpected instruction to relax");
     MCInst Res;
     if (Info->SkipOpc) {
-      Res.setOpcode(AMDGPU::S_CBRANCH_LONG);
+      Res.setOpcode(AMDGPU::S_CBRANCH_long_pseudo);
       Res.addOperand(MCOperand::createImm(Info->SkipOpc));
     } else {
-      Res.setOpcode(AMDGPU::S_BRANCH_LONG);
+      Res.setOpcode(AMDGPU::S_BRANCH_long_pseudo);
     }
     Res.addOperand(MCOperand::createImm(Info->AddPCOpc));
     Res.addOperand(Inst.getOperand(0));
diff --git a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp
index 9c9a6982bb0cd0..1db2b0e6ee2124 100644
--- a/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp
+++ b/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp
@@ -410,7 +410,8 @@ void AMDGPUMCCodeEmitter::encodeInstruction(const MCInst &MI,
                                             SmallVectorImpl<MCFixup> &Fixups,
                                             const MCSubtargetInfo &STI) const {
   int Opcode = MI.getOpcode();
-  if (Opcode == AMDGPU::S_BRANCH_LONG || Opcode == AMDGPU::S_CBRANCH_LONG) {
+  if (Opcode == AMDGPU::S_BRANCH_long_pseudo ||
+      Opcode == AMDGPU::S_CBRANCH_long_pseudo) {
     expandLongBranch(MI, CB, Fixups, STI);
     return;
   }
@@ -507,16 +508,16 @@ void AMDGPUMCCodeEmitter::encodeInstruction(const MCInst &MI,
   }
 }
 
-// Expand S_BRANCH_LONG or S_CBRANCH_LONG, created by branch relaxation, into an
-// s_add_pc_i64 with a 32-bit literal, optionally preceded by an inverted short
-// branch that skips over it. s_add_pc_i64 sign-extends the literal, so this can
-// reach +/-2GB, which is assumed to be enough for any branch within a single
-// code object.
+// Expand S_BRANCH_long_pseudo or S_CBRANCH_long_pseudo, created by branch
+// relaxation, into an s_add_pc_i64 with a 32-bit literal, optionally preceded
+// by an inverted short branch that skips over it. s_add_pc_i64 sign-extends the
+// literal, so this can reach +/-2GB, which is assumed to be enough for any
+// branch within a single code object.
 void AMDGPUMCCodeEmitter::expandLongBranch(const MCInst &MI,
                                            SmallVectorImpl<char> &CB,
                                            SmallVectorImpl<MCFixup> &Fixups,
                                            const MCSubtargetInfo &STI) const {
-  bool IsCond = MI.getOpcode() == AMDGPU::S_CBRANCH_LONG;
+  bool IsCond = MI.getOpcode() == AMDGPU::S_CBRANCH_long_pseudo;
   unsigned AddPCOpc = MI.getOperand(IsCond ? 1 : 0).getImm();
   const MCExpr *Target = MI.getOperand(IsCond ? 2 : 1).getExpr();
 
diff --git a/llvm/lib/Target/AMDGPU/SOPInstructions.td b/llvm/lib/Target/AMDGPU/SOPInstructions.td
index 39851a12aa4372..f1fe9ee2f9baaf 100644
--- a/llvm/lib/Target/AMDGPU/SOPInstructions.td
+++ b/llvm/lib/Target/AMDGPU/SOPInstructions.td
@@ -1653,20 +1653,20 @@ defm S_CBRANCH_CDBGUSER : SOPP_With_Relaxation <
 // the MC opcode of s_add_pc_i64 and $skip_opc is the MC opcode of the short
 // branch with the inverted condition. They are encoded as:
 //
-// S_BRANCH_LONG:
+// S_BRANCH_long_pseudo:
 //   s_add_pc_i64 $target   ; 32-bit literal
 //
-// S_CBRANCH_LONG:
+// S_CBRANCH_long_pseudo:
 //   $skip_opc 2
 //   s_add_pc_i64 $target   ; 32-bit literal
 let isBranch = 1, isTerminator = 1 in {
-def S_BRANCH_LONG : PseudoInstSI <(outs),
+def S_BRANCH_long_pseudo : PseudoInstSI <(outs),
   (ins i32imm:$add_pc_opc, SOPPBrTarget:$target)> {
   let isBarrier = 1;
   let Size = 8;
 }
 
-def S_CBRANCH_LONG : PseudoInstSI <(outs),
+def S_CBRANCH_long_pseudo : PseudoInstSI <(outs),
   (ins i32imm:$skip_opc, i32imm:$add_pc_opc, SOPPBrTarget:$target)> {
   let Size = 12;
 }



More information about the llvm-commits mailing list