[llvm] [HLSLSemanticSignatures] Implement the prefix packing of elements (PR #218062)

Finn Plummer via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 18 10:48:44 PDT 2026


https://github.com/inbelic updated https://github.com/llvm/llvm-project/pull/218062

>From 9aca96897a86c20ade0ddcc39025e99f04cd3b56 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 21 Aug 2026 20:25:58 +0000
Subject: [PATCH 01/34] add prefix-stable packing API and documentation

---
 llvm/docs/DirectX/SemanticSignatures.md       | 51 +++++++++++++++++++
 .../Frontend/HLSL/SemanticSignaturePacking.h  | 12 +++++
 .../HLSL/SemanticSignaturePacking.cpp         |  9 ++++
 3 files changed, 72 insertions(+)

diff --git a/llvm/docs/DirectX/SemanticSignatures.md b/llvm/docs/DirectX/SemanticSignatures.md
index a30199f8ccf45..9ca20487c1624 100644
--- a/llvm/docs/DirectX/SemanticSignatures.md
+++ b/llvm/docs/DirectX/SemanticSignatures.md
@@ -174,3 +174,54 @@ reg1: B[0].xyz   | unused.w
 reg2: B[1].xyz   | unused.w
 reg3: VertexID.x | unused.yzw
 ```
+
+### Prefix-Stable Packing
+
+Prefix-stable packing is used for signatures that connect programmable shader
+stages or carry patch constant data. Elements are visited in declaration order
+and placed at the first compatible location in the 32-row by 4-column register
+space. Once an element is placed it is never moved, so appending elements to a
+signature does not change the locations assigned to its existing prefix.
+
+Elements can share unused components in a row when all applicable packing
+constraints are satisfied:
+
+- Every element in a row must have a compatible interpolation mode.
+- When native 16-bit types are enabled, every element in a row must have the
+  same component width. Without native 16-bit types, min-precision values
+  occupy 32-bit components.
+- Components are ordered from arbitrary values, to system values, to system
+  generated values.
+- A system value or system generated value cannot be placed in a dynamically
+  indexed row. Multi-row elements define the dynamically indexed range that
+  they cover.
+
+Some semantic interpretations require additional handling:
+
+- `SV_ClipDistance` and `SV_CullDistance` are packed only with each other in
+  dedicated rows. Together they may occupy at most eight components across at
+  most two rows. The rows must be adjacent when a clip or cull element spans
+  multiple rows.
+- A multi-row tessellation factor is searched for only in the last column.
+- Geometry shader output streams are packed independently.
+
+For example:
+
+```hlsl
+struct VSOut {
+  float3 A[3] : A;
+  float1x2 B  : B;
+  float2 C    : C;
+  float D     : D;
+};
+```
+
+Assuming `B` has column-major matrix orientation, the signature is allocated
+as:
+
+```text
+reg0: A[0].xyz | B[0][0].w
+reg1: A[1].xyz | B[0][1].w
+reg2: A[2].xyz | D.w
+reg3: C.xy     | unused.zw
+```
diff --git a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
index bcdb6ec71050c..7fb9b5e2f8083 100644
--- a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
+++ b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
@@ -23,12 +23,15 @@ namespace llvm::hlsl {
 
 static constexpr unsigned MaxSignatureRows = 32;
 static constexpr unsigned MaxSignatureCols = 4;
+static constexpr unsigned MaxClipCullRows = 2;
+static constexpr unsigned MaxGeometryStreams = 4;
 
 /// Denotes the element that could not be packed and why.
 class LLVM_ABI SignaturePackingError : public ErrorInfo<SignaturePackingError> {
 public:
   enum ErrorKind {
     SignatureOverflow,
+    ClipCullOverflow,
   };
 
   static char ID;
@@ -62,6 +65,15 @@ LLVM_ABI Expected<unsigned>
 packSignatureStacked(MutableArrayRef<SemanticSignatureElement> Elements,
                      Triple::EnvironmentType ShaderStage, IOType IOTy);
 
+/// Packs eligible signature elements without moving previously placed
+/// elements.
+///
+/// See llvm/docs/DirectX/SemanticSignatures.md#prefix-stable-packing for
+/// details.
+LLVM_ABI Error packSignaturePrefixStable(
+    MutableArrayRef<SemanticSignatureElement> Elements,
+    Triple::EnvironmentType ShaderStage, IOType IOTy, bool UseNative16BitTypes);
+
 } // namespace llvm::hlsl
 
 #endif // LLVM_FRONTEND_HLSL_SEMANTICSIGNATUREPACKING_H
diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 278c6a4f06d7d..a81d9bc68b5c4 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -24,6 +24,9 @@ void SignaturePackingError::log(raw_ostream &OS) const {
   case SignatureOverflow:
     OS << "signature elements do not fit in " << MaxSignatureRows << " rows";
     break;
+  case ClipCullOverflow:
+    OS << "clip/cull elements do not fit in two rows";
+    break;
   }
   OS << " (element " << ElementIndex << ")";
 }
@@ -65,3 +68,9 @@ Expected<unsigned> llvm::hlsl::packSignatureStacked(
 
   return NextRow;
 }
+
+Error llvm::hlsl::packSignaturePrefixStable(
+    MutableArrayRef<SemanticSignatureElement>, Triple::EnvironmentType, IOType,
+    bool) {
+  return Error::success();
+}

>From 349bf3310410ec2659ef96aaaac0411b21a3043a Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 21 Aug 2026 20:37:44 +0000
Subject: [PATCH 02/34] update harness

---
 .../HLSLSemanticSignaturePackingTest.cpp      | 71 ++++++++++++++-----
 1 file changed, 54 insertions(+), 17 deletions(-)

diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 5ee3223313b50..bd1baffbe1cac 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -27,6 +27,8 @@ class HLSLSemanticSignaturePackingTest : public testing::Test {
     uint8_t Cols;
     dxil::ElementType CompType;
     dxbc::PSV::InterpolationMode InterpMode;
+    uint32_t SemanticIndex = 0;
+    uint32_t GSStream = 0;
   };
 
   struct ExpectedLocation {
@@ -40,11 +42,24 @@ class HLSLSemanticSignaturePackingTest : public testing::Test {
   struct TestConfig {
     Triple::EnvironmentType ShaderStage;
     IOType IOTy;
+    bool UseNative16BitTypes;
     SmallVector<ElementConfig> Elements;
 
     TestConfig(Triple::EnvironmentType ShaderStage, IOType IOTy,
                std::initializer_list<ElementConfig> Elements)
-        : ShaderStage(ShaderStage), IOTy(IOTy), Elements(Elements) {}
+        : ShaderStage(ShaderStage), IOTy(IOTy), UseNative16BitTypes(false),
+          Elements(Elements) {}
+
+    TestConfig(Triple::EnvironmentType ShaderStage, IOType IOTy,
+               bool UseNative16BitTypes,
+               std::initializer_list<ElementConfig> Elements)
+        : ShaderStage(ShaderStage), IOTy(IOTy),
+          UseNative16BitTypes(UseNative16BitTypes), Elements(Elements) {}
+  };
+
+  enum class PackingMethod {
+    Stacked,
+    PrefixStable,
   };
 
   SmallVector<SemanticSignatureElement>
@@ -53,7 +68,7 @@ class HLSLSemanticSignaturePackingTest : public testing::Test {
     for (const ElementConfig &Element : Config.Elements) {
       SmallVector<uint32_t> SemanticIndices;
       for (uint32_t Row = 0; Row != Element.Rows; ++Row)
-        SemanticIndices.push_back(Row);
+        SemanticIndices.push_back(Element.SemanticIndex + Row);
 
       Elements.emplace_back(
           /*SigId=*/static_cast<uint32_t>(Elements.size()),
@@ -63,22 +78,41 @@ class HLSLSemanticSignaturePackingTest : public testing::Test {
           /*SemanticIndices=*/SemanticIndices,
           /*Cols=*/Element.Cols);
       Elements.back().InterpMode = Element.InterpMode;
+      Elements.back().GSStream = Element.GSStream;
     }
     return Elements;
   }
 
   Expected<unsigned>
-  packStacked(SmallVectorImpl<SemanticSignatureElement> &Elements,
-              const TestConfig &Config) {
-    return packSignatureStacked(Elements, Config.ShaderStage, Config.IOTy);
+  pack(PackingMethod Method,
+       SmallVectorImpl<SemanticSignatureElement> &Elements,
+       const TestConfig &Config) {
+    switch (Method) {
+    case PackingMethod::Stacked:
+      return packSignatureStacked(Elements, Config.ShaderStage, Config.IOTy);
+    case PackingMethod::PrefixStable: {
+      if (Error E = packSignaturePrefixStable(Elements, Config.ShaderStage,
+                                             Config.IOTy,
+                                             Config.UseNative16BitTypes))
+        return std::move(E);
+
+      unsigned Rows = 0;
+      for (const SemanticSignatureElement &Element : Elements)
+        if (Element.isAllocated())
+          Rows = std::max(Rows, Element.StartRow + Element.Rows);
+      return Rows;
+    }
+    }
+    llvm_unreachable("invalid packing method");
   }
 
-  void verifyPacking(const TestConfig &Config, unsigned ExpectedRows,
+  void verifyPacking(PackingMethod Method, const TestConfig &Config,
+                     unsigned ExpectedRows,
                      std::initializer_list<ExpectedLocation> Locations) {
     SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
     ASSERT_EQ(Elements.size(), Locations.size());
 
-    Expected<unsigned> Rows = packStacked(Elements, Config);
+    Expected<unsigned> Rows = pack(Method, Elements, Config);
     ASSERT_THAT_EXPECTED(Rows, Succeeded());
     EXPECT_EQ(*Rows, ExpectedRows);
 
@@ -90,11 +124,11 @@ class HLSLSemanticSignaturePackingTest : public testing::Test {
     }
   }
 
-  void verifyPackingError(const TestConfig &Config,
+  void verifyPackingError(PackingMethod Method, const TestConfig &Config,
                           SignaturePackingError::ErrorKind ExpectedKind,
                           unsigned ExpectedElementIndex) {
     SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
-    Expected<unsigned> Rows = packStacked(Elements, Config);
+    Expected<unsigned> Rows = pack(Method, Elements, Config);
     if (Rows) {
       ADD_FAILURE() << "expected a SignaturePackingError";
       return;
@@ -175,7 +209,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, SkipsNotAllocatedElements) {
   // Expected layout:
   // reg0: A.xy  | unused.zw
   // reg1: B.xyz | unused.w
-  verifyPacking(Config, /*ExpectedRows=*/2,
+  verifyPacking(PackingMethod::Stacked, Config, /*ExpectedRows=*/2,
                 {{/*Row=*/0, /*Col=*/0}, Unallocated, {/*Row=*/1, /*Col=*/0}});
 }
 
@@ -202,7 +236,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, StacksInDeclarationOrder) {
   // reg1: Data.xy          | unused.zw
   // reg2: ClipDistance.xyz | unused.w
   verifyPacking(
-      Config, /*ExpectedRows=*/3,
+      PackingMethod::Stacked, Config, /*ExpectedRows=*/3,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/2, /*Col=*/0}});
 }
 
@@ -231,7 +265,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, DoesNotCoPackElements) {
   // reg1: B.x | unused.yzw
   // reg2: C.x | unused.yzw
   // reg3: D.x | unused.yzw
-  verifyPacking(Config, /*ExpectedRows=*/4,
+  verifyPacking(PackingMethod::Stacked, Config, /*ExpectedRows=*/4,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/0},
                  {/*Row=*/2, /*Col=*/0},
@@ -263,7 +297,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, StacksMultiRowElements) {
   // reg4: B[1].xyz | unused.w
   // reg5: C.xyzw
   verifyPacking(
-      Config, /*ExpectedRows=*/6,
+      PackingMethod::Stacked, Config, /*ExpectedRows=*/6,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/3, /*Col=*/0}, {/*Row=*/5, /*Col=*/0}});
 }
 
@@ -281,7 +315,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, ExactlyFillsSignature) {
 
   // Expected layout:
   // reg0-31: A[0-31].xyzw
-  verifyPacking(Config, /*ExpectedRows=*/MaxSignatureRows,
+  verifyPacking(PackingMethod::Stacked, Config, /*ExpectedRows=*/MaxSignatureRows,
                 {{/*Row=*/0, /*Col=*/0}});
 }
 
@@ -305,7 +339,8 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsSignatureOverflow) {
                                dxbc::PSV::InterpolationMode::Linear});
 
   // The last element is the one that no longer fits.
-  verifyPackingError(Config, SignaturePackingError::SignatureOverflow,
+  verifyPackingError(PackingMethod::Stacked, Config,
+                     SignaturePackingError::SignatureOverflow,
                      /*ExpectedElementIndex=*/MaxSignatureRows);
 }
 
@@ -321,7 +356,8 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsSingleElementOverflow) {
                       /*Cols=*/MaxSignatureCols, dxil::ElementType::F32,
                       dxbc::PSV::InterpolationMode::Linear}});
 
-  verifyPackingError(Config, SignaturePackingError::SignatureOverflow,
+  verifyPackingError(PackingMethod::Stacked, Config,
+                     SignaturePackingError::SignatureOverflow,
                      /*ExpectedElementIndex=*/0);
 }
 
@@ -340,7 +376,8 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsMultiRowSignatureOverflow) {
                       /*Cols=*/MaxSignatureCols, dxil::ElementType::F32,
                       dxbc::PSV::InterpolationMode::Linear}});
 
-  verifyPackingError(Config, SignaturePackingError::SignatureOverflow,
+  verifyPackingError(PackingMethod::Stacked, Config,
+                     SignaturePackingError::SignatureOverflow,
                      /*ExpectedElementIndex=*/1);
 }
 

>From c56a0cc401bc90cc8126283f40fb19135376b14b Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 21 Aug 2026 20:49:12 +0000
Subject: [PATCH 03/34] add basic prefix-stable packing

---
 .../HLSL/SemanticSignaturePacking.cpp         |  95 ++++++++++++-
 .../HLSLSemanticSignaturePackingTest.cpp      | 130 ++++++++++++++++++
 2 files changed, 223 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index a81d9bc68b5c4..bfd645978b1c5 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -12,13 +12,64 @@
 
 #include "llvm/Frontend/HLSL/SemanticSignaturePacking.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/bit.h"
+#include <array>
 #include <cassert>
+#include <optional>
 
 using namespace llvm;
 using namespace llvm::hlsl;
 
 char SignaturePackingError::ID;
 
+namespace {
+
+struct SignatureRow {
+  uint8_t OccupiedColumns = 0;
+};
+
+} // namespace
+
+static uint8_t getStartColumn(uint8_t ColumnMask) {
+  assert(ColumnMask != 0 && "expected at least one occupied column");
+  return countr_zero(ColumnMask);
+}
+
+// Returns the columns that Element would occupy if it was placed at StartRow,
+// or nullopt if it cannot be placed there.
+static std::optional<uint8_t>
+canPlaceAt(ArrayRef<SignatureRow> Rows, unsigned StartRow,
+           const SemanticSignatureElement &Element) {
+  if (StartRow > Rows.size() || Element.Rows > Rows.size() - StartRow)
+    return std::nullopt;
+
+  uint8_t OccupiedColumns = 0;
+  for (unsigned ElementRow = 0; ElementRow != Element.Rows; ++ElementRow)
+    OccupiedColumns |= Rows[StartRow + ElementRow].OccupiedColumns;
+
+  for (unsigned StartCol = 0; StartCol + Element.Cols <= MaxSignatureCols;
+       ++StartCol) {
+    const uint8_t ColumnMask = static_cast<uint8_t>(
+        ((1U << Element.Cols) - 1U) << static_cast<unsigned>(StartCol));
+    if (!(OccupiedColumns & ColumnMask))
+      return ColumnMask;
+  }
+  return std::nullopt;
+}
+
+static void placeAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
+                    uint8_t ColumnMask, SemanticSignatureElement &Element) {
+  for (unsigned ElementRow = 0; ElementRow != Element.Rows; ++ElementRow) {
+    SignatureRow &Row = Rows[StartRow + ElementRow];
+    assert(!(Row.OccupiedColumns & ColumnMask) &&
+           "cannot overlap signature elements");
+    Row.OccupiedColumns |= ColumnMask;
+  }
+
+  Element.StartRow = StartRow;
+  Element.StartCol = getStartColumn(ColumnMask);
+}
+
 void SignaturePackingError::log(raw_ostream &OS) const {
   switch (Kind) {
   case SignatureOverflow:
@@ -70,7 +121,47 @@ Expected<unsigned> llvm::hlsl::packSignatureStacked(
 }
 
 Error llvm::hlsl::packSignaturePrefixStable(
-    MutableArrayRef<SemanticSignatureElement>, Triple::EnvironmentType, IOType,
-    bool) {
+    MutableArrayRef<SemanticSignatureElement> Elements,
+    Triple::EnvironmentType ShaderStage, IOType IOTy,
+    bool UseNative16BitTypes) {
+  (void)UseNative16BitTypes;
+
+  std::array<SignatureRow, MaxSignatureRows> Rows = {};
+  for (const auto &[Index, Element] : enumerate(Elements)) {
+    assert(Element.StartRow == UnallocatedRow &&
+           Element.StartCol == UnallocatedCol && "already allocated?");
+    assert(Element.Rows > 0 && "signature element must have at least one row");
+    assert(Element.Cols > 0 && Element.Cols <= MaxSignatureCols &&
+           "signature element must have between 1 and 4 columns");
+
+    SemanticInterpretation Interpretation =
+        getInterpretationKind(Element.SemanticKind, ShaderStage, IOTy);
+    if (Interpretation == SemanticInterpretation::NotAllocated)
+      continue;
+
+    assert((Interpretation == SemanticInterpretation::Arbitrary ||
+            Interpretation == SemanticInterpretation::SV ||
+            Interpretation == SemanticInterpretation::SGV ||
+            Interpretation == SemanticInterpretation::ClipCull ||
+            Interpretation == SemanticInterpretation::TessFactor) &&
+           "unexpected semantic interpretation for prefix-stable packing");
+
+    bool Placed = false;
+    for (unsigned StartRow = 0; StartRow != Rows.size(); ++StartRow) {
+      std::optional<uint8_t> ColumnMask = canPlaceAt(Rows, StartRow, Element);
+      if (!ColumnMask)
+        continue;
+
+      placeAt(Rows, StartRow, *ColumnMask, Element);
+      Placed = true;
+      break;
+    }
+
+    if (!Placed)
+      return make_error<SignaturePackingError>(
+          SignaturePackingError::SignatureOverflow,
+          static_cast<unsigned>(Index));
+  }
+
   return Error::success();
 }
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index bd1baffbe1cac..3034607613626 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -381,4 +381,134 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsMultiRowSignatureOverflow) {
                      /*ExpectedElementIndex=*/1);
 }
 
+//===----------------------------------------------------------------------===//
+// Basic prefix-stable packing tests
+//===----------------------------------------------------------------------===//
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableEmptySignature) {
+  // A signature without any elements uses no registers.
+
+  // struct VSOut {};
+  TestConfig Config(Triple::EnvironmentType::Vertex, IOType::Out,
+                    /*UseNative16BitTypes=*/false, {});
+
+  // Expected layout: no registers are used.
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/0, {});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableDeclarationOrder) {
+  // Elements are visited in declaration order and are co-packed into a
+  // register whenever the register has room left for them.
+
+  // struct VSOut {
+  //   float Fog      : FOG;
+  //   float Alpha    : COLOR0;
+  //   float2 Position : SV_Position;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Position, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: Fog.x | Alpha.y | Position.zw
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/1}, {/*Row=*/0, /*Col=*/2}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableWhenAppended) {
+  // Appending an element to a signature never moves the elements declared
+  // before it; the appended element is only packed into the space they left.
+
+  // struct Prefix {
+  //   float3 A : A;
+  //   float2 B : B;
+  // };
+  TestConfig PrefixConfig(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: A.xyz | unused.w
+  // reg1: B.xy  | unused.zw
+  expectPacking(PackingMethod::PrefixStable, PrefixConfig, /*ExpectedRows=*/2,
+                {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
+
+  // struct Extended {
+  //   float3 A : A;
+  //   float2 B : B;
+  //   float C  : C;
+  // };
+  TestConfig ExtendedConfig = PrefixConfig;
+  ExtendedConfig.Elements.push_back(
+      {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+       dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear});
+
+  // Expected layout:
+  // reg0: A.xyz | C.w
+  // reg1: B.xy  | unused.zw
+  //
+  // C is packed into the gap A left behind, and A and B keep the locations
+  // they were given in Prefix.
+  expectPacking(
+      PackingMethod::PrefixStable, ExtendedConfig, /*ExpectedRows=*/2,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/0, /*Col=*/3}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableFillsAllRows) {
+  // A signature may use all 32 rows.
+
+  // struct VSOut {
+  //   float4 A0  : A0;
+  //   ...
+  //   float4 A31 : A31;
+  // };
+  TestConfig Config(Triple::EnvironmentType::Vertex, IOType::Out,
+                    /*UseNative16BitTypes=*/false, {});
+  for (unsigned I = 0; I != MaxSignatureRows; ++I)
+    Config.Elements.push_back({dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1,
+                               /*Cols=*/MaxSignatureCols,
+                               dxil::ElementType::F32,
+                               dxbc::PSV::InterpolationMode::Linear});
+
+  SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
+  ASSERT_THAT_ERROR(pack(PackingMethod::PrefixStable, Elements, Config),
+                    Succeeded());
+
+  for (unsigned I = 0; I != MaxSignatureRows; ++I) {
+    EXPECT_EQ(Elements[I].StartRow, I) << "element " << I;
+    EXPECT_EQ(Elements[I].StartCol, 0u) << "element " << I;
+  }
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsSignatureOverflow) {
+  // A signature that requires more than 32 rows cannot be packed.
+
+  // struct VSOut {
+  //   float4 A0  : A0;
+  //   ...
+  //   float4 A32 : A32;
+  // };
+  TestConfig Config(Triple::EnvironmentType::Vertex, IOType::Out,
+                    /*UseNative16BitTypes=*/false, {});
+  for (unsigned I = 0; I != MaxSignatureRows + 1; ++I)
+    Config.Elements.push_back({dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1,
+                               /*Cols=*/MaxSignatureCols,
+                               dxil::ElementType::F32,
+                               dxbc::PSV::InterpolationMode::Linear});
+  // The last element is the one that no longer fits.
+  expectPackingError(PackingMethod::PrefixStable, Config,
+                     SignaturePackingError::SignatureOverflow,
+                     /*ExpectedElementIndex=*/MaxSignatureRows);
+}
 } // namespace

>From da6ad8ce8fa413c9f63f7d050c7a21bc755b064c Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 21 Aug 2026 21:14:18 +0000
Subject: [PATCH 04/34] enforce prefix-stable signature row compatibility

---
 .../HLSL/SemanticSignaturePacking.cpp         | 110 ++++++--
 .../HLSLSemanticSignaturePackingTest.cpp      | 255 ++++++++++++++++++
 2 files changed, 340 insertions(+), 25 deletions(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index bfd645978b1c5..03bf32cab5b4e 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -26,6 +26,18 @@ namespace {
 
 struct SignatureRow {
   uint8_t OccupiedColumns = 0;
+  unsigned ComponentWidth = 0;
+  dxbc::PSV::InterpolationMode InterpMode =
+      dxbc::PSV::InterpolationMode::Undefined;
+};
+
+// Everything the packing rules need to know about the element that is being
+// placed. It applies to every row that the element covers.
+struct ElementPlacement {
+  unsigned Rows;
+  unsigned Cols;
+  unsigned ComponentWidth;
+  dxbc::PSV::InterpolationMode InterpMode;
 };
 
 } // namespace
@@ -35,22 +47,61 @@ static uint8_t getStartColumn(uint8_t ColumnMask) {
   return countr_zero(ColumnMask);
 }
 
-// Returns the columns that Element would occupy if it was placed at StartRow,
+static unsigned getComponentWidth(dxil::ElementType ComponentType,
+                                  bool UseNative16BitTypes) {
+  assert(ComponentType != dxil::ElementType::I64 &&
+         ComponentType != dxil::ElementType::U64 &&
+         ComponentType != dxil::ElementType::F64 &&
+         ComponentType != dxil::ElementType::SNormF64 &&
+         ComponentType != dxil::ElementType::UNormF64 &&
+         "64-bit types cannot be used in a signature");
+
+  switch (ComponentType) {
+  case dxil::ElementType::F16:
+  case dxil::ElementType::I16:
+  case dxil::ElementType::U16:
+  case dxil::ElementType::SNormF16:
+  case dxil::ElementType::UNormF16:
+    // Without native 16-bit types these are min-precision types that occupy a
+    // whole 32-bit component.
+    return UseNative16BitTypes ? 16 : 32;
+  default:
+    // A boolean is loaded and stored as a 32-bit value.
+    return 32;
+  }
+}
+
+// Returns whether Placement may be co-packed into a Row that it covers.
+static bool canCoPack(const SignatureRow &Row,
+                      const ElementPlacement &Placement) {
+  if (Row.OccupiedColumns && Row.ComponentWidth != Placement.ComponentWidth)
+    return false;
+  if (Row.InterpMode != dxbc::PSV::InterpolationMode::Undefined &&
+      Row.InterpMode != Placement.InterpMode)
+    return false;
+  return true;
+}
+
+// Returns the columns that Placement would occupy if it was placed at StartRow,
 // or nullopt if it cannot be placed there.
-static std::optional<uint8_t>
-canPlaceAt(ArrayRef<SignatureRow> Rows, unsigned StartRow,
-           const SemanticSignatureElement &Element) {
-  if (StartRow > Rows.size() || Element.Rows > Rows.size() - StartRow)
+static std::optional<uint8_t> canPlaceAt(ArrayRef<SignatureRow> Rows,
+                                         unsigned StartRow,
+                                         const ElementPlacement &Placement) {
+  if (StartRow > Rows.size() || Placement.Rows > Rows.size() - StartRow)
     return std::nullopt;
 
   uint8_t OccupiedColumns = 0;
-  for (unsigned ElementRow = 0; ElementRow != Element.Rows; ++ElementRow)
-    OccupiedColumns |= Rows[StartRow + ElementRow].OccupiedColumns;
+  for (unsigned ElementRow = 0; ElementRow != Placement.Rows; ++ElementRow) {
+    const SignatureRow &Row = Rows[StartRow + ElementRow];
+    if (!canCoPack(Row, Placement))
+      return std::nullopt;
+    OccupiedColumns |= Row.OccupiedColumns;
+  }
 
-  for (unsigned StartCol = 0; StartCol + Element.Cols <= MaxSignatureCols;
+  for (unsigned StartCol = 0; StartCol + Placement.Cols <= MaxSignatureCols;
        ++StartCol) {
     const uint8_t ColumnMask = static_cast<uint8_t>(
-        ((1U << Element.Cols) - 1U) << static_cast<unsigned>(StartCol));
+        ((1U << Placement.Cols) - 1U) << static_cast<unsigned>(StartCol));
     if (!(OccupiedColumns & ColumnMask))
       return ColumnMask;
   }
@@ -58,18 +109,36 @@ canPlaceAt(ArrayRef<SignatureRow> Rows, unsigned StartRow,
 }
 
 static void placeAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
-                    uint8_t ColumnMask, SemanticSignatureElement &Element) {
-  for (unsigned ElementRow = 0; ElementRow != Element.Rows; ++ElementRow) {
+                    const ElementPlacement &Placement, uint8_t ColumnMask,
+                    SemanticSignatureElement &Element) {
+  for (unsigned ElementRow = 0; ElementRow != Placement.Rows; ++ElementRow) {
     SignatureRow &Row = Rows[StartRow + ElementRow];
     assert(!(Row.OccupiedColumns & ColumnMask) &&
            "cannot overlap signature elements");
+    if (!Row.OccupiedColumns)
+      Row.ComponentWidth = Placement.ComponentWidth;
     Row.OccupiedColumns |= ColumnMask;
+    if (Row.InterpMode == dxbc::PSV::InterpolationMode::Undefined)
+      Row.InterpMode = Placement.InterpMode;
   }
 
   Element.StartRow = StartRow;
   Element.StartCol = getStartColumn(ColumnMask);
 }
 
+static bool packElement(SemanticSignatureElement &Element,
+                        MutableArrayRef<SignatureRow> Rows,
+                        const ElementPlacement &Placement) {
+  for (unsigned StartRow = 0; StartRow != Rows.size(); ++StartRow) {
+    std::optional<uint8_t> ColumnMask = canPlaceAt(Rows, StartRow, Placement);
+    if (!ColumnMask)
+      continue;
+    placeAt(Rows, StartRow, Placement, *ColumnMask, Element);
+    return true;
+  }
+  return false;
+}
+
 void SignaturePackingError::log(raw_ostream &OS) const {
   switch (Kind) {
   case SignatureOverflow:
@@ -124,8 +193,6 @@ Error llvm::hlsl::packSignaturePrefixStable(
     MutableArrayRef<SemanticSignatureElement> Elements,
     Triple::EnvironmentType ShaderStage, IOType IOTy,
     bool UseNative16BitTypes) {
-  (void)UseNative16BitTypes;
-
   std::array<SignatureRow, MaxSignatureRows> Rows = {};
   for (const auto &[Index, Element] : enumerate(Elements)) {
     assert(Element.StartRow == UnallocatedRow &&
@@ -146,18 +213,11 @@ Error llvm::hlsl::packSignaturePrefixStable(
             Interpretation == SemanticInterpretation::TessFactor) &&
            "unexpected semantic interpretation for prefix-stable packing");
 
-    bool Placed = false;
-    for (unsigned StartRow = 0; StartRow != Rows.size(); ++StartRow) {
-      std::optional<uint8_t> ColumnMask = canPlaceAt(Rows, StartRow, Element);
-      if (!ColumnMask)
-        continue;
-
-      placeAt(Rows, StartRow, *ColumnMask, Element);
-      Placed = true;
-      break;
-    }
-
-    if (!Placed)
+    const unsigned ComponentWidth =
+        getComponentWidth(Element.CompType, UseNative16BitTypes);
+    const ElementPlacement Placement = {Element.Rows, Element.Cols,
+                                        ComponentWidth, Element.InterpMode};
+    if (!packElement(Element, Rows, Placement))
       return make_error<SignaturePackingError>(
           SignaturePackingError::SignatureOverflow,
           static_cast<unsigned>(Index));
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 3034607613626..b5c82ef7a2e88 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -511,4 +511,259 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsSignatureOverflow) {
                      SignaturePackingError::SignatureOverflow,
                      /*ExpectedElementIndex=*/MaxSignatureRows);
 }
+
+//===----------------------------------------------------------------------===//
+// Prefix-stable row compatibility tests
+//===----------------------------------------------------------------------===//
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableGeneralPacking) {
+  // Native 16-bit types are enabled.
+  // struct PSIn {
+  //   float16_t2 A : A;
+  //   float2 B     : B;
+  //   float16_t3 C : C;
+  //   float2 D     : D;
+  //   int E        : E;
+  //   float16_t2 F : F;
+  //   float16_t G  : G;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Pixel, IOType::In,
+      /*UseNative16BitTypes=*/true,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F16, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F16, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::I32, dxbc::PSV::InterpolationMode::Constant},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F16, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F16, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: A.xy | F.zw
+  // reg1: B.xy | D.zw
+  // reg2: C.xyz | G.w
+  // reg3: E.x | unused.yzw
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/0},
+                 {/*Row=*/2, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/2},
+                 {/*Row=*/3, /*Col=*/0},
+                 {/*Row=*/0, /*Col=*/2},
+                 {/*Row=*/2, /*Col=*/3}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableNative16BitWidth) {
+  // struct VSOut {
+  //   float16_t2 A : A;
+  //   float2 B     : B;
+  //   float16_t2 C : C;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/true,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F16, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F16, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: A.xy | C.zw
+  // reg1: B.xy | unused.zw
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableInterpolationMode) {
+  // struct VSOut {
+  //   float2 A                : A;
+  //   nointerpolation float2 B : B;
+  //   float2 C                : C;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Constant},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: A.xy | C.zw
+  // reg1: B.xy | unused.zw
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableCompatible16BitTypes) {
+  // struct VSOut {
+  //   nointerpolation int16_t A    : A;
+  //   nointerpolation float16_t3 B : B;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/true,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::I16, dxbc::PSV::InterpolationMode::Constant},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F16, dxbc::PSV::InterpolationMode::Constant}});
+
+  // Expected layout:
+  // reg0: A.x | B.yzw
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
+                {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/1}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableNormalized16BitTypes) {
+  // A normalized 16-bit type has the same component width as any other 16-bit
+  // type, so it co-packs with them but not with a 32-bit type.
+
+  // struct VSOut {
+  //   nointerpolation snorm half A : A;
+  //   nointerpolation float16_t B  : B;
+  //   nointerpolation float C      : C;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/true,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::SNormF16, dxbc::PSV::InterpolationMode::Constant},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F16, dxbc::PSV::InterpolationMode::Constant},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Constant}});
+
+  // Expected layout:
+  // reg0: A.x | B.y | unused.zw
+  // reg1: C.x | unused.yzw
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/1}, {/*Row=*/1, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableMinPrecisionWidth) {
+  // Without native 16-bit types, 16-bit types are min-precision types which
+  // occupy a full 32-bit component, so they co-pack with 32-bit types. This is
+  // the same signature as PrefixStableNative16BitWidth, which packs
+  // differently.
+
+  // struct VSOut {
+  //   min16float2 A : A;
+  //   float2 B      : B;
+  //   min16float2 C : C;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F16, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F16, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: A.xy | B.zw
+  // reg1: C.xy | unused.zw
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}, {/*Row=*/1, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableUndefinedInterpMode) {
+  // An undefined interpolation mode does not constrain a register, but the
+  // first defined mode packed into it does.
+
+  // struct VSOut {
+  //   float2 A                : A; // undefined interpolation mode
+  //   float B                 : B; // linear
+  //   nointerpolation float C : C; // nointerpolation
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Constant}});
+
+  // Expected layout:
+  // reg0: A.xy | B.z | unused.w
+  // reg1: C.x  | unused.yzw
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}, {/*Row=*/1, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest,
+       PrefixStableUndefinedInterpModeAfterDefined) {
+  // Once a register has a defined interpolation mode, an element with an
+  // undefined mode cannot be packed into it.
+
+  // struct VSOut {
+  //   float2 A : A; // linear
+  //   float2 B : B; // undefined interpolation mode
+  //   float2 C : C; // linear
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: A.xy | C.zw
+  // reg1: B.xy | unused.zw
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableDistinctInterpModes) {
+  // Every distinct interpolation mode requires its own register, including
+  // modes that only differ by their centroid or noperspective qualifier.
+
+  // struct VSOut {
+  //   float2 A               : A;
+  //   centroid float2 B      : B;
+  //   noperspective float2 C : C;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::LinearCentroid},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32,
+        dxbc::PSV::InterpolationMode::LinearNoperspective}});
+
+  // Expected layout:
+  // reg0: A.xy | unused.zw
+  // reg1: B.xy | unused.zw
+  // reg2: C.xy | unused.zw
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/2, /*Col=*/0}});
+}
 } // namespace

>From 7861f0aaae572a373739d737d48553bef7784dc1 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 21 Aug 2026 21:16:57 +0000
Subject: [PATCH 05/34] enforce prefix-stable component ordering

---
 .../HLSL/SemanticSignaturePacking.cpp         |  23 ++-
 .../HLSLSemanticSignaturePackingTest.cpp      | 138 ++++++++++++++++++
 2 files changed, 159 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 03bf32cab5b4e..965c3c3104b4d 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -24,11 +24,21 @@ char SignaturePackingError::ID;
 
 namespace {
 
+static_assert(SemanticInterpretation::Arbitrary < SemanticInterpretation::SV &&
+                  SemanticInterpretation::SV < SemanticInterpretation::SGV &&
+                  SemanticInterpretation::SGV <
+                      SemanticInterpretation::ClipCull &&
+                  SemanticInterpretation::ClipCull <
+                      SemanticInterpretation::TessFactor,
+              "semantic interpretations must be in component packing order");
+
 struct SignatureRow {
   uint8_t OccupiedColumns = 0;
   unsigned ComponentWidth = 0;
   dxbc::PSV::InterpolationMode InterpMode =
       dxbc::PSV::InterpolationMode::Undefined;
+  SemanticInterpretation RightmostInterpretation =
+      SemanticInterpretation::Arbitrary;
 };
 
 // Everything the packing rules need to know about the element that is being
@@ -38,6 +48,7 @@ struct ElementPlacement {
   unsigned Cols;
   unsigned ComponentWidth;
   dxbc::PSV::InterpolationMode InterpMode;
+  SemanticInterpretation Interpretation;
 };
 
 } // namespace
@@ -79,6 +90,9 @@ static bool canCoPack(const SignatureRow &Row,
   if (Row.InterpMode != dxbc::PSV::InterpolationMode::Undefined &&
       Row.InterpMode != Placement.InterpMode)
     return false;
+  if (Row.OccupiedColumns &&
+      Placement.Interpretation < Row.RightmostInterpretation)
+    return false;
   return true;
 }
 
@@ -115,11 +129,15 @@ static void placeAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
     SignatureRow &Row = Rows[StartRow + ElementRow];
     assert(!(Row.OccupiedColumns & ColumnMask) &&
            "cannot overlap signature elements");
-    if (!Row.OccupiedColumns)
+    const uint8_t PreviousOccupiedColumns = Row.OccupiedColumns;
+    if (!PreviousOccupiedColumns)
       Row.ComponentWidth = Placement.ComponentWidth;
     Row.OccupiedColumns |= ColumnMask;
     if (Row.InterpMode == dxbc::PSV::InterpolationMode::Undefined)
       Row.InterpMode = Placement.InterpMode;
+    // Non-overlapping masks compare according to their rightmost set bit.
+    if (!PreviousOccupiedColumns || ColumnMask > PreviousOccupiedColumns)
+      Row.RightmostInterpretation = Placement.Interpretation;
   }
 
   Element.StartRow = StartRow;
@@ -216,7 +234,8 @@ Error llvm::hlsl::packSignaturePrefixStable(
     const unsigned ComponentWidth =
         getComponentWidth(Element.CompType, UseNative16BitTypes);
     const ElementPlacement Placement = {Element.Rows, Element.Cols,
-                                        ComponentWidth, Element.InterpMode};
+                                        ComponentWidth, Element.InterpMode,
+                                        Interpretation};
     if (!packElement(Element, Rows, Placement))
       return make_error<SignaturePackingError>(
           SignaturePackingError::SignatureOverflow,
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index b5c82ef7a2e88..f8b42f4823947 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -766,4 +766,142 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableDistinctInterpModes) {
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/2, /*Col=*/0}});
 }
+
+//===----------------------------------------------------------------------===//
+// Prefix-stable component ordering tests
+//===----------------------------------------------------------------------===//
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSystemValueOrdering) {
+  // System values may be co-packed to the right of arbitrary values, and a
+  // system generated value may be co-packed to the right of both.
+
+  // struct PSIn {
+  //   uint A             : A;
+  //   float Position      : SV_Position;
+  //   bool IsFrontFace   : SV_IsFrontFace;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Pixel, IOType::In,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::U32, dxbc::PSV::InterpolationMode::Constant},
+       {dxbc::PSV::SemanticKind::Position, /*Rows=*/1,
+        /*Cols=*/1, dxil::ElementType::F32,
+        dxbc::PSV::InterpolationMode::Constant},
+       {dxbc::PSV::SemanticKind::IsFrontFace, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::I1, dxbc::PSV::InterpolationMode::Constant}});
+
+  // Expected layout:
+  // reg0: A.x | Position.y | IsFrontFace.z | unused.w
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/1}, {/*Row=*/0, /*Col=*/2}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableArbitraryNotRightOfSV) {
+  // Arbitrary values may never be placed to the right of a system value in the
+  // same register, so B cannot co-pack with Position even though there is
+  // space for it.
+
+  // struct VSOut {
+  //   float2 Position : SV_Position;
+  //   float2 A        : A;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Position, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: Position.xy | unused.zw
+  // reg1: A.xy        | unused.zw
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+                {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSGVIsRightmost) {
+  // Nothing may be placed to the right of a system generated value, so both A
+  // and Position are pushed into the next register.
+
+  // struct PSIn {
+  //   bool IsFrontFace : SV_IsFrontFace;
+  //   uint A           : A;
+  //   float Position    : SV_Position;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Pixel, IOType::In,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::IsFrontFace, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::I1, dxbc::PSV::InterpolationMode::Constant},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::U32, dxbc::PSV::InterpolationMode::Constant},
+       {dxbc::PSV::SemanticKind::Position, /*Rows=*/1,
+        /*Cols=*/1, dxil::ElementType::F32,
+        dxbc::PSV::InterpolationMode::Constant}});
+
+  // Expected layout:
+  // reg0: IsFrontFace.x | unused.yzw
+  // reg1: A.x | Position.y | unused.zw
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/1, /*Col=*/1}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest,
+       PrefixStableRejectsOverflowFromComponentOrdering) {
+  // Nothing may be placed to the right of a system generated value, so
+  // declaring one first leaves the rest of its register unusable by the
+  // arbitrary values that follow, and they no longer fit in 32 rows. Every
+  // element here shares an interpolation mode and a data width, so component
+  // ordering is the only reason the signature overflows.
+  //
+  // Note that the optimal algorithm packs the arbitrary values into reg0 to
+  // reg31 first and backfills IsFrontFace into reg0.w, so the very same
+  // signature does fit when it is packed optimally.
+
+  // struct PSIn {
+  //   nointerpolation bool IsFrontFace : SV_IsFrontFace;
+  //   nointerpolation int3 A0          : A0;
+  //   ...
+  //   nointerpolation int3 A31         : A31;
+  // };
+  TestConfig Config(Triple::EnvironmentType::Pixel, IOType::In,
+                    /*UseNative16BitTypes=*/false,
+                    {{dxbc::PSV::SemanticKind::IsFrontFace, /*Rows=*/1,
+                      /*Cols=*/1, dxil::ElementType::I1,
+                      dxbc::PSV::InterpolationMode::Constant}});
+  for (unsigned I = 0; I != MaxSignatureRows; ++I)
+    Config.Elements.push_back({dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1,
+                               /*Cols=*/3, dxil::ElementType::I32,
+                               dxbc::PSV::InterpolationMode::Constant});
+  // The last element is the one that no longer fits.
+  expectPackingError(PackingMethod::PrefixStable, Config,
+                     SignaturePackingError::SignatureOverflow,
+                     /*ExpectedElementIndex=*/MaxSignatureRows);
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest,
+       PrefixStableSkipsNotAllocatedElements) {
+  // Semantics accessed through dedicated intrinsics remain unallocated and do
+  // not reserve signature rows.
+
+  // struct CSIn {
+  //   uint3 DispatchThreadID : SV_DispatchThreadID;
+  //   uint GroupIndex        : SV_GroupIndex;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Compute, IOType::In,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::DispatchThreadID, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::U32, dxbc::PSV::InterpolationMode::Undefined},
+       {dxbc::PSV::SemanticKind::GroupIndex, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::U32, dxbc::PSV::InterpolationMode::Undefined}});
+
+  // Expected layout: no registers are used.
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/0,
+                {Unallocated, Unallocated});
+}
 } // namespace

>From 910fa68c0797e3ab08cd7050a6b7939ad0de24d2 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 21 Aug 2026 21:21:30 +0000
Subject: [PATCH 06/34] handle dynamically indexed prefix-stable ranges

---
 .../HLSL/SemanticSignaturePacking.cpp         | 70 ++++++++++++++++++-
 .../HLSLSemanticSignaturePackingTest.cpp      | 63 +++++++++++++++++
 2 files changed, 130 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 965c3c3104b4d..2dd59a67664aa 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -13,6 +13,7 @@
 #include "llvm/Frontend/HLSL/SemanticSignaturePacking.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/bit.h"
+#include <algorithm>
 #include <array>
 #include <cassert>
 #include <optional>
@@ -24,6 +25,40 @@ char SignaturePackingError::ID;
 
 namespace {
 
+// The range of rows covered by a dynamically indexable element. Only an
+// element that covers multiple rows is dynamically indexable, so a single-row
+// element has an empty range.
+struct IndexedRowRange {
+  uint8_t Begin = 0;
+  uint8_t End = 0;
+
+  static IndexedRowRange of(unsigned StartRow, unsigned RowCount) {
+    if (RowCount < 2)
+      return {};
+    return {static_cast<uint8_t>(StartRow),
+            static_cast<uint8_t>(StartRow + RowCount)};
+  }
+
+  bool isEmpty() const { return Begin == End; }
+
+  // An empty range is contained by every range.
+  bool contains(IndexedRowRange Other) const {
+    return Other.isEmpty() || (Begin <= Other.Begin && Other.End <= End);
+  }
+
+  IndexedRowRange unionWith(IndexedRowRange Other) const {
+    if (isEmpty())
+      return Other;
+    if (Other.isEmpty())
+      return *this;
+    return {std::min(Begin, Other.Begin), std::max(End, Other.End)};
+  }
+
+  bool operator==(IndexedRowRange Other) const {
+    return Begin == Other.Begin && End == Other.End;
+  }
+};
+
 static_assert(SemanticInterpretation::Arbitrary < SemanticInterpretation::SV &&
                   SemanticInterpretation::SV < SemanticInterpretation::SGV &&
                   SemanticInterpretation::SGV <
@@ -34,6 +69,8 @@ static_assert(SemanticInterpretation::Arbitrary < SemanticInterpretation::SV &&
 
 struct SignatureRow {
   uint8_t OccupiedColumns = 0;
+  IndexedRowRange IndexedRange;
+  bool IndexedRangeFixed = false;
   unsigned ComponentWidth = 0;
   dxbc::PSV::InterpolationMode InterpMode =
       dxbc::PSV::InterpolationMode::Undefined;
@@ -82,9 +119,25 @@ static unsigned getComponentWidth(dxil::ElementType ComponentType,
   }
 }
 
-// Returns whether Placement may be co-packed into a Row that it covers.
+// Returns whether Placement may be co-packed into a Row that it covers, where
+// IndexedRange is the range of rows that it is dynamically indexed over.
 static bool canCoPack(const SignatureRow &Row,
-                      const ElementPlacement &Placement) {
+                      const ElementPlacement &Placement,
+                      IndexedRowRange IndexedRange) {
+  const bool IsSystemValue =
+      Placement.Interpretation == SemanticInterpretation::SV ||
+      Placement.Interpretation == SemanticInterpretation::SGV;
+
+  // A system value is never dynamically indexable, so it cannot be placed in a
+  // row that is.
+  if (IsSystemValue && !Row.IndexedRange.isEmpty())
+    return false;
+
+  // A row whose indexed range is fixed only accepts elements that are indexed
+  // within that range.
+  if (Row.IndexedRangeFixed && !Row.IndexedRange.contains(IndexedRange))
+    return false;
+
   if (Row.OccupiedColumns && Row.ComponentWidth != Placement.ComponentWidth)
     return false;
   if (Row.InterpMode != dxbc::PSV::InterpolationMode::Undefined &&
@@ -104,10 +157,12 @@ static std::optional<uint8_t> canPlaceAt(ArrayRef<SignatureRow> Rows,
   if (StartRow > Rows.size() || Placement.Rows > Rows.size() - StartRow)
     return std::nullopt;
 
+  const IndexedRowRange IndexedRange =
+      IndexedRowRange::of(StartRow, Placement.Rows);
   uint8_t OccupiedColumns = 0;
   for (unsigned ElementRow = 0; ElementRow != Placement.Rows; ++ElementRow) {
     const SignatureRow &Row = Rows[StartRow + ElementRow];
-    if (!canCoPack(Row, Placement))
+    if (!canCoPack(Row, Placement, IndexedRange))
       return std::nullopt;
     OccupiedColumns |= Row.OccupiedColumns;
   }
@@ -125,6 +180,8 @@ static std::optional<uint8_t> canPlaceAt(ArrayRef<SignatureRow> Rows,
 static void placeAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
                     const ElementPlacement &Placement, uint8_t ColumnMask,
                     SemanticSignatureElement &Element) {
+  const IndexedRowRange IndexedRange =
+      IndexedRowRange::of(StartRow, Placement.Rows);
   for (unsigned ElementRow = 0; ElementRow != Placement.Rows; ++ElementRow) {
     SignatureRow &Row = Rows[StartRow + ElementRow];
     assert(!(Row.OccupiedColumns & ColumnMask) &&
@@ -138,6 +195,13 @@ static void placeAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
     // Non-overlapping masks compare according to their rightmost set bit.
     if (!PreviousOccupiedColumns || ColumnMask > PreviousOccupiedColumns)
       Row.RightmostInterpretation = Placement.Interpretation;
+
+    Row.IndexedRange = Row.IndexedRange.unionWith(IndexedRange);
+    if (Placement.Interpretation == SemanticInterpretation::SV ||
+        Placement.Interpretation == SemanticInterpretation::SGV) {
+      assert(Row.IndexedRange == IndexedRange && "incompatible index range");
+      Row.IndexedRangeFixed = true;
+    }
   }
 
   Element.StartRow = StartRow;
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index f8b42f4823947..e340222d3959d 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -904,4 +904,67 @@ TEST_F(HLSLSemanticSignaturePackingTest,
   expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/0,
                 {Unallocated, Unallocated});
 }
+
+//===----------------------------------------------------------------------===//
+// Prefix-stable dynamic indexing tests
+//===----------------------------------------------------------------------===//
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedRanges) {
+  // An element with multiple rows occupies the same columns of a contiguous
+  // range of rows, and other elements may be co-packed into the columns those
+  // rows have left. A system value cannot be placed in a dynamically indexable
+  // row, so Position starts a new register.
+
+  // struct VSOut {
+  //   float2 A[2]    : A;
+  //   float B[2]     : B;
+  //   float C        : C;
+  //   float Position : SV_Position;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/2, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/2, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Position, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: A[0].xy | B[0].z | C.w
+  // reg1: A[1].xy | B[1].z | unused.w
+  // reg2: Position.x | unused.yzw
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/0, /*Col=*/2},
+                 {/*Row=*/0, /*Col=*/3},
+                 {/*Row=*/2, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedAfterSystemValue) {
+  // A multi-row element is dynamically indexable, so it may not share any of
+  // its rows with a system value, and it requires contiguous rows.
+
+  // struct VSOut {
+  //   float Position : SV_Position;
+  //   float3 A[2]    : A;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Position, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/2, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: Position.x | unused.yzw
+  // reg1: A[0].xyz   | unused.w
+  // reg2: A[1].xyz   | unused.w
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
+                {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
+}
 } // namespace

>From 40487aa9b6c60bc3ee1a7489584da29cb21d760f Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 21 Aug 2026 21:24:01 +0000
Subject: [PATCH 07/34] pack prefix-stable tessellation factors

---
 .../HLSL/SemanticSignaturePacking.cpp         | 31 +++++++-
 .../HLSLSemanticSignaturePackingTest.cpp      | 78 +++++++++++++++++++
 2 files changed, 106 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 2dd59a67664aa..fd42f7354e3d4 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -138,13 +138,21 @@ static bool canCoPack(const SignatureRow &Row,
   if (Row.IndexedRangeFixed && !Row.IndexedRange.contains(IndexedRange))
     return false;
 
+  // A tess factor fixes the indexed range of the rows it is reserved in, so it
+  // may only extend the range that those rows already have.
+  if (Placement.Interpretation == SemanticInterpretation::TessFactor &&
+      !IndexedRange.contains(Row.IndexedRange))
+    return false;
+
   if (Row.OccupiedColumns && Row.ComponentWidth != Placement.ComponentWidth)
     return false;
   if (Row.InterpMode != dxbc::PSV::InterpolationMode::Undefined &&
       Row.InterpMode != Placement.InterpMode)
     return false;
   if (Row.OccupiedColumns &&
-      Placement.Interpretation < Row.RightmostInterpretation)
+      Placement.Interpretation < Row.RightmostInterpretation &&
+      !(Placement.Interpretation == SemanticInterpretation::Arbitrary &&
+        Row.RightmostInterpretation == SemanticInterpretation::TessFactor))
     return false;
   return true;
 }
@@ -167,6 +175,15 @@ static std::optional<uint8_t> canPlaceAt(ArrayRef<SignatureRow> Rows,
     OccupiedColumns |= Row.OccupiedColumns;
   }
 
+  // An indexed tess factor is reserved in the last column so that other
+  // elements can still be co-packed into the rows that it covers.
+  if (Placement.Interpretation == SemanticInterpretation::TessFactor) {
+    constexpr uint8_t LastColumn = 1U << (MaxSignatureCols - 1);
+    if (Placement.Cols != 1 || (OccupiedColumns & LastColumn))
+      return std::nullopt;
+    return LastColumn;
+  }
+
   for (unsigned StartCol = 0; StartCol + Placement.Cols <= MaxSignatureCols;
        ++StartCol) {
     const uint8_t ColumnMask = static_cast<uint8_t>(
@@ -198,7 +215,8 @@ static void placeAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
 
     Row.IndexedRange = Row.IndexedRange.unionWith(IndexedRange);
     if (Placement.Interpretation == SemanticInterpretation::SV ||
-        Placement.Interpretation == SemanticInterpretation::SGV) {
+        Placement.Interpretation == SemanticInterpretation::SGV ||
+        Placement.Interpretation == SemanticInterpretation::TessFactor) {
       assert(Row.IndexedRange == IndexedRange && "incompatible index range");
       Row.IndexedRangeFixed = true;
     }
@@ -297,9 +315,16 @@ Error llvm::hlsl::packSignaturePrefixStable(
 
     const unsigned ComponentWidth =
         getComponentWidth(Element.CompType, UseNative16BitTypes);
+    // Only a tess factor that covers multiple rows is dynamically indexable
+    // and needs to be reserved in the last column.
+    const SemanticInterpretation PackingInterpretation =
+        Interpretation == SemanticInterpretation::TessFactor &&
+                Element.Rows == 1
+            ? SemanticInterpretation::SV
+            : Interpretation;
     const ElementPlacement Placement = {Element.Rows, Element.Cols,
                                         ComponentWidth, Element.InterpMode,
-                                        Interpretation};
+                                        PackingInterpretation};
     if (!packElement(Element, Rows, Placement))
       return make_error<SignaturePackingError>(
           SignaturePackingError::SignatureOverflow,
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index e340222d3959d..31b68b3291eb0 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -967,4 +967,82 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedAfterSystemValue) {
   expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
                 {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
 }
+
+//===----------------------------------------------------------------------===//
+// Prefix-stable tessellation factor tests
+//===----------------------------------------------------------------------===//
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableTessFactors) {
+  // Indexed tess factors are reserved in the last column of their rows so that
+  // arbitrary values can still be co-packed into the same rows.
+
+  // struct PatchConstants {
+  //   float TessFactor[2] : SV_TessFactor;
+  //   float3 Data[2]      : DATA;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Hull, IOType::PatchConstantOrPrimitive,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::TessFactor, /*Rows=*/2, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/2, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined}});
+
+  // Expected layout:
+  // reg0: Data[0].xyz | TessFactor[0].w
+  // reg1: Data[1].xyz | TessFactor[1].w
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+                {{/*Row=*/0, /*Col=*/3}, {/*Row=*/0, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSingleRowTessFactor) {
+  // A single row tess factor is not dynamically indexable and is packed like
+  // any other system value, rather than being reserved in the last column.
+
+  // struct PatchConstants {
+  //   float TessFactor : SV_TessFactor;
+  //   float3 Data      : DATA;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Hull, IOType::PatchConstantOrPrimitive,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::TessFactor, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined}});
+
+  // Expected layout:
+  // reg0: TessFactor.x | unused.yzw
+  // reg1: Data.xyz     | unused.w
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+                {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest,
+       PrefixStableIndexedTessFactorAfterIndexedElement) {
+  // An indexed tess factor may only be placed in rows whose indexed range is
+  // contained by its own, so it cannot be packed into the rows of the wider
+  // indexed range of Data.
+
+  // struct PatchConstants {
+  //   float3 Data[3]      : DATA;
+  //   float TessFactor[2] : SV_TessFactor;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Hull, IOType::PatchConstantOrPrimitive,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/3, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined},
+       {dxbc::PSV::SemanticKind::TessFactor, /*Rows=*/2, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined}});
+
+  // Expected layout:
+  // reg0: Data[0].xyz | unused.w
+  // reg1: Data[1].xyz | unused.w
+  // reg2: Data[2].xyz | unused.w
+  // reg3: unused.xyz  | TessFactor[0].w
+  // reg4: unused.xyz  | TessFactor[1].w
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/5,
+                {{/*Row=*/0, /*Col=*/0}, {/*Row=*/3, /*Col=*/3}});
+}
 } // namespace

>From 93f805b9b10cdad2d4a27902b033bbbe3fe9971b Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 21 Aug 2026 21:27:37 +0000
Subject: [PATCH 08/34] pack prefix-stable clip and cull distance semantics

---
 .../HLSL/SemanticSignaturePacking.cpp         | 130 +++++++-
 .../HLSLSemanticSignaturePackingTest.cpp      | 299 ++++++++++++++++++
 2 files changed, 426 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index fd42f7354e3d4..f0aa466091faf 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -88,6 +88,15 @@ struct ElementPlacement {
   SemanticInterpretation Interpretation;
 };
 
+// Clip/cull elements are first packed into an independent two-row grid. Each
+// row used in that grid maps to a whole reserved row in the signature.
+struct ClipCullState {
+  std::array<SignatureRow, MaxClipCullRows> Rows;
+  std::array<unsigned, MaxClipCullRows> SignatureRows = {UnallocatedRow,
+                                                         UnallocatedRow};
+  unsigned RowsUsed = 0;
+};
+
 } // namespace
 
 static uint8_t getStartColumn(uint8_t ColumnMask) {
@@ -194,9 +203,8 @@ static std::optional<uint8_t> canPlaceAt(ArrayRef<SignatureRow> Rows,
   return std::nullopt;
 }
 
-static void placeAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
-                    const ElementPlacement &Placement, uint8_t ColumnMask,
-                    SemanticSignatureElement &Element) {
+static void placeRowsAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
+                        const ElementPlacement &Placement, uint8_t ColumnMask) {
   const IndexedRowRange IndexedRange =
       IndexedRowRange::of(StartRow, Placement.Rows);
   for (unsigned ElementRow = 0; ElementRow != Placement.Rows; ++ElementRow) {
@@ -221,7 +229,12 @@ static void placeAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
       Row.IndexedRangeFixed = true;
     }
   }
+}
 
+static void placeAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
+                    const ElementPlacement &Placement, uint8_t ColumnMask,
+                    SemanticSignatureElement &Element) {
+  placeRowsAt(Rows, StartRow, Placement, ColumnMask);
   Element.StartRow = StartRow;
   Element.StartCol = getStartColumn(ColumnMask);
 }
@@ -239,6 +252,107 @@ static bool packElement(SemanticSignatureElement &Element,
   return false;
 }
 
+// A clip/cull grid row is backed by a whole reserved signature row.
+static ElementPlacement
+getClipCullReservation(const ElementPlacement &Placement, unsigned RowCount) {
+  ElementPlacement Reservation = Placement;
+  Reservation.Rows = RowCount;
+  Reservation.Cols = MaxSignatureCols;
+  return Reservation;
+}
+
+static bool reserveClipCullRows(MutableArrayRef<SignatureRow> Rows,
+                                unsigned StartRow,
+                                const ElementPlacement &Reservation) {
+  std::optional<uint8_t> ColumnMask = canPlaceAt(Rows, StartRow, Reservation);
+  if (!ColumnMask)
+    return false;
+  placeRowsAt(Rows, StartRow, Reservation, *ColumnMask);
+  return true;
+}
+
+static std::optional<unsigned>
+reserveNextClipCullRows(MutableArrayRef<SignatureRow> Rows,
+                        const ElementPlacement &Reservation) {
+  for (unsigned StartRow = 0; StartRow != Rows.size(); ++StartRow)
+    if (reserveClipCullRows(Rows, StartRow, Reservation))
+      return StartRow;
+  return std::nullopt;
+}
+
+// Reserves the whole signature rows that back the clip/cull grid rows that the
+// element is packed into. Existing rows cannot be moved without breaking
+// prefix stability, so an indexed element requires them to be adjacent.
+static std::optional<SignaturePackingError::ErrorKind>
+reserveClipCullSignatureRows(MutableArrayRef<SignatureRow> SignatureRows,
+                             ClipCullState &State,
+                             const ElementPlacement &Placement,
+                             unsigned NewRowsUsed) {
+  if (Placement.Rows == 1) {
+    const ElementPlacement Reservation = getClipCullReservation(Placement, 1);
+    for (unsigned Row = State.RowsUsed; Row < NewRowsUsed; ++Row) {
+      std::optional<unsigned> StartRow =
+          reserveNextClipCullRows(SignatureRows, Reservation);
+      if (!StartRow)
+        return SignaturePackingError::SignatureOverflow;
+      State.SignatureRows[Row] = *StartRow;
+    }
+    return std::nullopt;
+  }
+
+  if (State.RowsUsed == 0) {
+    std::optional<unsigned> StartRow = reserveNextClipCullRows(
+        SignatureRows, getClipCullReservation(Placement, MaxClipCullRows));
+    if (!StartRow)
+      return SignaturePackingError::SignatureOverflow;
+    State.SignatureRows[0] = *StartRow;
+    State.SignatureRows[1] = *StartRow + 1;
+    return std::nullopt;
+  }
+
+  if (State.RowsUsed == 1) {
+    const unsigned StartRow = State.SignatureRows[0] + 1;
+    if (StartRow >= SignatureRows.size() ||
+        !reserveClipCullRows(SignatureRows, StartRow,
+                             getClipCullReservation(Placement, 1)))
+      return SignaturePackingError::SignatureOverflow;
+    State.SignatureRows[1] = StartRow;
+    return std::nullopt;
+  }
+
+  if (State.SignatureRows[0] + 1 != State.SignatureRows[1])
+    return SignaturePackingError::ClipCullOverflow;
+  return std::nullopt;
+}
+
+static std::optional<SignaturePackingError::ErrorKind>
+packClipCullElement(SemanticSignatureElement &Element,
+                    MutableArrayRef<SignatureRow> SignatureRows,
+                    ClipCullState &State, const ElementPlacement &Placement) {
+  std::optional<uint8_t> ColumnMask;
+  unsigned ClipCullStartRow = 0;
+  while (ClipCullStartRow + Placement.Rows <= MaxClipCullRows) {
+    ColumnMask = canPlaceAt(State.Rows, ClipCullStartRow, Placement);
+    if (ColumnMask)
+      break;
+    ++ClipCullStartRow;
+  }
+  if (!ColumnMask)
+    return SignaturePackingError::ClipCullOverflow;
+
+  const unsigned NewRowsUsed = ClipCullStartRow + Placement.Rows;
+  if (std::optional<SignaturePackingError::ErrorKind> Kind =
+          reserveClipCullSignatureRows(SignatureRows, State, Placement,
+                                       NewRowsUsed))
+    return Kind;
+
+  placeRowsAt(State.Rows, ClipCullStartRow, Placement, *ColumnMask);
+  State.RowsUsed = std::max(State.RowsUsed, NewRowsUsed);
+  Element.StartRow = State.SignatureRows[ClipCullStartRow];
+  Element.StartCol = getStartColumn(*ColumnMask);
+  return std::nullopt;
+}
+
 void SignaturePackingError::log(raw_ostream &OS) const {
   switch (Kind) {
   case SignatureOverflow:
@@ -294,6 +408,7 @@ Error llvm::hlsl::packSignaturePrefixStable(
     Triple::EnvironmentType ShaderStage, IOType IOTy,
     bool UseNative16BitTypes) {
   std::array<SignatureRow, MaxSignatureRows> Rows = {};
+  ClipCullState ClipCull;
   for (const auto &[Index, Element] : enumerate(Elements)) {
     assert(Element.StartRow == UnallocatedRow &&
            Element.StartCol == UnallocatedCol && "already allocated?");
@@ -325,6 +440,15 @@ Error llvm::hlsl::packSignaturePrefixStable(
     const ElementPlacement Placement = {Element.Rows, Element.Cols,
                                         ComponentWidth, Element.InterpMode,
                                         PackingInterpretation};
+
+    if (Interpretation == SemanticInterpretation::ClipCull) {
+      if (std::optional<SignaturePackingError::ErrorKind> Kind =
+              packClipCullElement(Element, Rows, ClipCull, Placement))
+        return make_error<SignaturePackingError>(*Kind,
+                                                 static_cast<unsigned>(Index));
+      continue;
+    }
+
     if (!packElement(Element, Rows, Placement))
       return make_error<SignaturePackingError>(
           SignaturePackingError::SignatureOverflow,
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 31b68b3291eb0..8282a0ef5fe22 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -1045,4 +1045,303 @@ TEST_F(HLSLSemanticSignaturePackingTest,
   expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/5,
                 {{/*Row=*/0, /*Col=*/0}, {/*Row=*/3, /*Col=*/3}});
 }
+
+//===----------------------------------------------------------------------===//
+// Prefix-stable clip/cull tests
+//===----------------------------------------------------------------------===//
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCull) {
+  // struct VSOut {
+  //   float3 First         : First;
+  //   float  Clip0         : SV_ClipDistance0;
+  //   float3 Cull1         : SV_CullDistance1;
+  //   float  Cull0         : SV_CullDistance0;
+  //   float2 Clip1         : SV_ClipDistance1;
+  //   float  WithFirst     : WithFirst;
+  //   float  AfterClipCull : AfterClipCull;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: First.xyz       | WithFirst.w
+  // reg1: Clip0.x         | Cull1.yzw
+  // reg2: Cull0.x         | Clip1.yz | unused.w
+  // reg3: AfterClipCull.x | unused.yzw
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/1},
+                 {/*Row=*/2, /*Col=*/0},
+                 {/*Row=*/2, /*Col=*/1},
+                 {/*Row=*/0, /*Col=*/3},
+                 {/*Row=*/3, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedClipCull) {
+  // struct VSOut {
+  //   float3 First         : First;
+  //   float  Clip0         : SV_ClipDistance0;
+  //   float2 Cull1[2]      : SV_CullDistance1;
+  //   float  Clip1         : SV_ClipDistance1;
+  //   float  WithFirst     : WithFirst;
+  //   float  AfterClipCull : AfterClipCull;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/2, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: First.xyz       | WithFirst.w
+  // reg1: Clip0.x         | Cull1[0].yz | Clip1.w
+  // reg2: unused.x        | Cull1[1].yz | unused.w
+  // reg3: AfterClipCull.x | unused.yzw
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/1},
+                 {/*Row=*/1, /*Col=*/3},
+                 {/*Row=*/0, /*Col=*/3},
+                 {/*Row=*/3, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableMultipleIndexedClipCull) {
+  // struct VSOut {
+  //   float3 First         : First;
+  //   float  Clip0         : SV_ClipDistance0;
+  //   float2 Cull1[2]      : SV_CullDistance1;
+  //   float  Clip1[2]      : SV_ClipDistance1;
+  //   float  WithFirst     : WithFirst;
+  //   float  AfterClipCull : AfterClipCull;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/2, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/2, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: First.xyz       | WithFirst.w
+  // reg1: Clip0.x         | Cull1[0].yz | Clip1[0].w
+  // reg2: unused.x        | Cull1[1].yz | Clip1[1].w
+  // reg3: AfterClipCull.x | unused.yzw
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/1},
+                 {/*Row=*/1, /*Col=*/3},
+                 {/*Row=*/0, /*Col=*/3},
+                 {/*Row=*/3, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCullFillsTwoRows) {
+  // Clip and cull distances may use a combined maximum of eight components
+  // spread over two registers.
+
+  // struct VSOut {
+  //   float4 Clip0 : SV_ClipDistance0;
+  //   float4 Cull0 : SV_CullDistance0;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/4,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/1, /*Cols=*/4,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: Clip0.xyzw
+  // reg1: Cull0.xyzw
+  expectPacking(PackingMethod::PrefixStable, Config,
+                /*ExpectedRows=*/MaxClipCullRows,
+                {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSeparatesClipCullRows) {
+  // Non-indexed clip and cull distance registers do not need to be adjacent.
+  // Elements declared between them may separate their reserved registers while
+  // the clip/cull elements continue to count toward the common two-register
+  // limit.
+
+  // struct VSOut {
+  //   float3 Clip0 : SV_ClipDistance0;
+  //   float4 A[30] : A;
+  //   float3 Cull0 : SV_CullDistance0;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/30, /*Cols=*/4,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0:     Clip0.xyz | unused.w
+  // reg1-30:  A[0-29].xyzw
+  // reg31:    Cull0.xyz | unused.w
+  expectPacking(PackingMethod::PrefixStable, Config,
+                /*ExpectedRows=*/MaxSignatureRows,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/0},
+                 {/*Row=*/31, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCullAsArbitrary) {
+  // Clip and cull distances are arbitrary values in a patch constant
+  // signature, so the two register limit does not apply to them.
+
+  // struct PatchConstants {
+  //   float3 Clip0 : SV_ClipDistance0;
+  //   float3 Clip1 : SV_ClipDistance1;
+  //   float3 Cull0 : SV_CullDistance0;
+  // };
+  TestConfig Config(
+      Triple::EnvironmentType::Hull, IOType::PatchConstantOrPrimitive,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined}});
+
+  // Expected layout:
+  // reg0: Clip0.xyz | unused.w
+  // reg1: Clip1.xyz | unused.w
+  // reg2: Cull0.xyz | unused.w
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/2, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCullWhenAppended) {
+  // Clip and cull distances reserve whole registers ahead of the elements that
+  // follow them, so appending elements does not move them either, not even
+  // when the appended elements are clip/cull values themselves.
+
+  // struct Prefix {
+  //   float3 First    : First;
+  //   float  Clip0    : SV_ClipDistance0;
+  //   float2 Cull1[2] : SV_CullDistance1;
+  // };
+  TestConfig PrefixConfig(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/2, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+
+  // Expected layout:
+  // reg0: First.xyz | unused.w
+  // reg1: Clip0.x   | Cull1[0].yz | unused.w
+  // reg2: unused.x  | Cull1[1].yz | unused.w
+  expectPacking(
+      PackingMethod::PrefixStable, PrefixConfig, /*ExpectedRows=*/3,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/1, /*Col=*/1}});
+
+  TestConfig ExtendedConfig = PrefixConfig;
+  ExtendedConfig.Elements.push_back(
+      {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/1,
+       dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear});
+  ExtendedConfig.Elements.push_back(
+      {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+       dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear});
+  ExtendedConfig.Elements.push_back(
+      {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+       dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear});
+
+  // Expected layout:
+  // reg0: First.xyz       | WithFirst.w
+  // reg1: Clip0.x         | Cull1[0].yz | Clip1.w
+  // reg2: unused.x        | Cull1[1].yz | unused.w
+  // reg3: AfterClipCull.x | unused.yzw
+  expectPacking(PackingMethod::PrefixStable, ExtendedConfig, /*ExpectedRows=*/4,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/1},
+                 {/*Row=*/1, /*Col=*/3},
+                 {/*Row=*/0, /*Col=*/3},
+                 {/*Row=*/3, /*Col=*/0}});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsClipCullOverflow) {
+  // Clip and cull distances may use at most eight components, shared between
+  // them, so nine components cannot be packed.
+
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+  expectPackingError(PackingMethod::PrefixStable, Config,
+                     SignaturePackingError::ClipCullOverflow,
+                     /*ExpectedElementIndex=*/2);
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest,
+       PrefixStableRejectsUnpackableClipCull) {
+  // These clip and cull distances fit in eight components, but they cannot be
+  // split across the two registers available to them.
+
+  TestConfig Config(
+      Triple::EnvironmentType::Vertex, IOType::Out,
+      /*UseNative16BitTypes=*/false,
+      {{dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+  expectPackingError(PackingMethod::PrefixStable, Config,
+                     SignaturePackingError::ClipCullOverflow,
+                     /*ExpectedElementIndex=*/2);
+}
 } // namespace

>From e19dce6e1dfaf5fec6fa41f151cc2049364f91b1 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 21 Aug 2026 21:31:09 +0000
Subject: [PATCH 09/34] pack geometry shader output streams independently

---
 .../HLSL/SemanticSignaturePacking.cpp         | 21 +++++++--
 .../HLSLSemanticSignaturePackingTest.cpp      | 43 +++++++++++++++++++
 2 files changed, 60 insertions(+), 4 deletions(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index f0aa466091faf..143f82c175f09 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -12,6 +12,7 @@
 
 #include "llvm/Frontend/HLSL/SemanticSignaturePacking.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/bit.h"
 #include <algorithm>
 #include <array>
@@ -407,14 +408,22 @@ Error llvm::hlsl::packSignaturePrefixStable(
     MutableArrayRef<SemanticSignatureElement> Elements,
     Triple::EnvironmentType ShaderStage, IOType IOTy,
     bool UseNative16BitTypes) {
-  std::array<SignatureRow, MaxSignatureRows> Rows = {};
-  ClipCullState ClipCull;
+  // Only a geometry shader output signature packs its streams independently.
+  const unsigned StreamCount =
+      ShaderStage == Triple::EnvironmentType::Geometry && IOTy == IOType::Out
+          ? MaxGeometryStreams
+          : 1;
+
+  SmallVector<std::array<SignatureRow, MaxSignatureRows>, 1> Rows(StreamCount);
+  SmallVector<ClipCullState, 1> ClipCullStates(StreamCount);
   for (const auto &[Index, Element] : enumerate(Elements)) {
     assert(Element.StartRow == UnallocatedRow &&
            Element.StartCol == UnallocatedCol && "already allocated?");
     assert(Element.Rows > 0 && "signature element must have at least one row");
     assert(Element.Cols > 0 && Element.Cols <= MaxSignatureCols &&
            "signature element must have between 1 and 4 columns");
+    assert(Element.GSStream < StreamCount &&
+           "signature element has an unexpected geometry stream");
 
     SemanticInterpretation Interpretation =
         getInterpretationKind(Element.SemanticKind, ShaderStage, IOTy);
@@ -441,15 +450,19 @@ Error llvm::hlsl::packSignaturePrefixStable(
                                         ComponentWidth, Element.InterpMode,
                                         PackingInterpretation};
 
+    const unsigned StreamIndex = StreamCount == 1 ? 0 : Element.GSStream;
+    MutableArrayRef<SignatureRow> StreamRows = Rows[StreamIndex];
+
     if (Interpretation == SemanticInterpretation::ClipCull) {
       if (std::optional<SignaturePackingError::ErrorKind> Kind =
-              packClipCullElement(Element, Rows, ClipCull, Placement))
+              packClipCullElement(Element, StreamRows,
+                                  ClipCullStates[StreamIndex], Placement))
         return make_error<SignaturePackingError>(*Kind,
                                                  static_cast<unsigned>(Index));
       continue;
     }
 
-    if (!packElement(Element, Rows, Placement))
+    if (!packElement(Element, StreamRows, Placement))
       return make_error<SignaturePackingError>(
           SignaturePackingError::SignatureOverflow,
           static_cast<unsigned>(Index));
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 8282a0ef5fe22..0bc94a7e3ee22 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -1344,4 +1344,47 @@ TEST_F(HLSLSemanticSignaturePackingTest,
                      SignaturePackingError::ClipCullOverflow,
                      /*ExpectedElementIndex=*/2);
 }
+
+//===----------------------------------------------------------------------===//
+// Prefix-stable geometry stream tests
+//===----------------------------------------------------------------------===//
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableGeometryStreams) {
+  // Each geometry shader output stream is packed into its own signature, so
+  // elements of different streams never share a register. The reported number
+  // of rows is the maximum used by any single stream.
+
+  // struct Stream0 {
+  //   float4 A : A;
+  //   float2 C : C;
+  // };
+  // struct Stream1 {
+  //   float4 B : B;
+  // };
+  // void GSMain(inout PointStream<Stream0> S0, inout PointStream<Stream1> S1);
+  //
+  // Elements are declared in the order A, B, C.
+  TestConfig Config(Triple::EnvironmentType::Geometry, IOType::Out,
+                    /*UseNative16BitTypes=*/false,
+                    {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1,
+                      /*Cols=*/4, dxil::ElementType::F32,
+                      dxbc::PSV::InterpolationMode::Linear, /*SemanticIndex=*/0,
+                      /*GSStream=*/0},
+                     {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1,
+                      /*Cols=*/4, dxil::ElementType::F32,
+                      dxbc::PSV::InterpolationMode::Linear, /*SemanticIndex=*/0,
+                      /*GSStream=*/1},
+                     {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1,
+                      /*Cols=*/2, dxil::ElementType::F32,
+                      dxbc::PSV::InterpolationMode::Linear, /*SemanticIndex=*/0,
+                      /*GSStream=*/0}});
+
+  // Expected layout:
+  // stream0 reg0: A.xyzw
+  // stream0 reg1: C.xy | unused.zw
+  // stream1 reg0: B.xyzw
+  expectPacking(
+      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
+}
 } // namespace

>From 7624d0ea7b450e38fadc30d950a9a6d6892da571 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 21 Aug 2026 21:38:21 +0000
Subject: [PATCH 10/34] deduplicate signature packing tests

---
 .../HLSLSemanticSignaturePackingTest.cpp      | 130 +++++-------------
 1 file changed, 36 insertions(+), 94 deletions(-)

diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 0bc94a7e3ee22..e15cdf5e6c7cd 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -187,6 +187,14 @@ TEST_F(HLSLSemanticSignaturePackingTest, CreatesSignatureFromConfig) {
 // Valid packing tests
 //===----------------------------------------------------------------------===//
 
+TEST_F(HLSLSemanticSignaturePackingTest, EmptySignature) {
+  TestConfig Config(Triple::EnvironmentType::Vertex, IOType::Out, {});
+
+  for (PackingMethod Method :
+       {PackingMethod::Stacked, PackingMethod::PrefixStable})
+    expectPacking(Method, Config, /*ExpectedRows=*/0, {});
+}
+
 TEST_F(HLSLSemanticSignaturePackingTest, SkipsNotAllocatedElements) {
   // Semantics accessed through dedicated intrinsics do not consume signature
   // rows and remain unallocated. The elements around them are packed as if the
@@ -240,8 +248,9 @@ TEST_F(HLSLSemanticSignaturePackingTest, StacksInDeclarationOrder) {
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/2, /*Col=*/0}});
 }
 
-TEST_F(HLSLSemanticSignaturePackingTest, DoesNotCoPackElements) {
-  // Elements are never co-packed even when they would fit in one row.
+TEST_F(HLSLSemanticSignaturePackingTest, CoPackingDependsOnMethod) {
+  // Stacked packing gives each element a whole row, while prefix-stable packing
+  // co-packs the same elements into the components of one row.
 
   // struct VSIn {
   //   float A : A;
@@ -260,7 +269,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, DoesNotCoPackElements) {
        {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
         dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
 
-  // Expected layout:
+  // Stacked layout:
   // reg0: A.x | unused.yzw
   // reg1: B.x | unused.yzw
   // reg2: C.x | unused.yzw
@@ -270,6 +279,14 @@ TEST_F(HLSLSemanticSignaturePackingTest, DoesNotCoPackElements) {
                  {/*Row=*/1, /*Col=*/0},
                  {/*Row=*/2, /*Col=*/0},
                  {/*Row=*/3, /*Col=*/0}});
+
+  // Prefix-stable layout:
+  // reg0: A.x | B.y | C.z | D.w
+  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/0, /*Col=*/1},
+                 {/*Row=*/0, /*Col=*/2},
+                 {/*Row=*/0, /*Col=*/3}});
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest, StacksMultiRowElements) {
@@ -315,8 +332,10 @@ TEST_F(HLSLSemanticSignaturePackingTest, ExactlyFillsSignature) {
 
   // Expected layout:
   // reg0-31: A[0-31].xyzw
-  verifyPacking(PackingMethod::Stacked, Config, /*ExpectedRows=*/MaxSignatureRows,
-                {{/*Row=*/0, /*Col=*/0}});
+  for (PackingMethod Method :
+       {PackingMethod::Stacked, PackingMethod::PrefixStable})
+    verifyPacking(Method, Config, /*ExpectedRows=*/MaxSignatureRows,
+                  {{/*Row=*/0, /*Col=*/0}});
 }
 
 //===----------------------------------------------------------------------===//
@@ -339,9 +358,10 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsSignatureOverflow) {
                                dxbc::PSV::InterpolationMode::Linear});
 
   // The last element is the one that no longer fits.
-  verifyPackingError(PackingMethod::Stacked, Config,
-                     SignaturePackingError::SignatureOverflow,
-                     /*ExpectedElementIndex=*/MaxSignatureRows);
+  for (PackingMethod Method :
+       {PackingMethod::Stacked, PackingMethod::PrefixStable})
+    verifyPackingError(Method, Config, SignaturePackingError::SignatureOverflow,
+                       /*ExpectedElementIndex=*/MaxSignatureRows);
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest, RejectsSingleElementOverflow) {
@@ -356,9 +376,10 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsSingleElementOverflow) {
                       /*Cols=*/MaxSignatureCols, dxil::ElementType::F32,
                       dxbc::PSV::InterpolationMode::Linear}});
 
-  verifyPackingError(PackingMethod::Stacked, Config,
-                     SignaturePackingError::SignatureOverflow,
-                     /*ExpectedElementIndex=*/0);
+  for (PackingMethod Method :
+       {PackingMethod::Stacked, PackingMethod::PrefixStable})
+    verifyPackingError(Method, Config, SignaturePackingError::SignatureOverflow,
+                       /*ExpectedElementIndex=*/0);
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest, RejectsMultiRowSignatureOverflow) {
@@ -376,52 +397,16 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsMultiRowSignatureOverflow) {
                       /*Cols=*/MaxSignatureCols, dxil::ElementType::F32,
                       dxbc::PSV::InterpolationMode::Linear}});
 
-  verifyPackingError(PackingMethod::Stacked, Config,
-                     SignaturePackingError::SignatureOverflow,
-                     /*ExpectedElementIndex=*/1);
+  for (PackingMethod Method :
+       {PackingMethod::Stacked, PackingMethod::PrefixStable})
+    verifyPackingError(Method, Config, SignaturePackingError::SignatureOverflow,
+                       /*ExpectedElementIndex=*/1);
 }
 
 //===----------------------------------------------------------------------===//
 // Basic prefix-stable packing tests
 //===----------------------------------------------------------------------===//
 
-TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableEmptySignature) {
-  // A signature without any elements uses no registers.
-
-  // struct VSOut {};
-  TestConfig Config(Triple::EnvironmentType::Vertex, IOType::Out,
-                    /*UseNative16BitTypes=*/false, {});
-
-  // Expected layout: no registers are used.
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/0, {});
-}
-
-TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableDeclarationOrder) {
-  // Elements are visited in declaration order and are co-packed into a
-  // register whenever the register has room left for them.
-
-  // struct VSOut {
-  //   float Fog      : FOG;
-  //   float Alpha    : COLOR0;
-  //   float2 Position : SV_Position;
-  // };
-  TestConfig Config(
-      Triple::EnvironmentType::Vertex, IOType::Out,
-      /*UseNative16BitTypes=*/false,
-      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
-        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
-       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
-        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
-       {dxbc::PSV::SemanticKind::Position, /*Rows=*/1, /*Cols=*/2,
-        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
-
-  // Expected layout:
-  // reg0: Fog.x | Alpha.y | Position.zw
-  expectPacking(
-      PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
-      {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/1}, {/*Row=*/0, /*Col=*/2}});
-}
-
 TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableWhenAppended) {
   // Appending an element to a signature never moves the elements declared
   // before it; the appended element is only packed into the space they left.
@@ -491,27 +476,6 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableFillsAllRows) {
   }
 }
 
-TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsSignatureOverflow) {
-  // A signature that requires more than 32 rows cannot be packed.
-
-  // struct VSOut {
-  //   float4 A0  : A0;
-  //   ...
-  //   float4 A32 : A32;
-  // };
-  TestConfig Config(Triple::EnvironmentType::Vertex, IOType::Out,
-                    /*UseNative16BitTypes=*/false, {});
-  for (unsigned I = 0; I != MaxSignatureRows + 1; ++I)
-    Config.Elements.push_back({dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1,
-                               /*Cols=*/MaxSignatureCols,
-                               dxil::ElementType::F32,
-                               dxbc::PSV::InterpolationMode::Linear});
-  // The last element is the one that no longer fits.
-  expectPackingError(PackingMethod::PrefixStable, Config,
-                     SignaturePackingError::SignatureOverflow,
-                     /*ExpectedElementIndex=*/MaxSignatureRows);
-}
-
 //===----------------------------------------------------------------------===//
 // Prefix-stable row compatibility tests
 //===----------------------------------------------------------------------===//
@@ -883,28 +847,6 @@ TEST_F(HLSLSemanticSignaturePackingTest,
                      /*ExpectedElementIndex=*/MaxSignatureRows);
 }
 
-TEST_F(HLSLSemanticSignaturePackingTest,
-       PrefixStableSkipsNotAllocatedElements) {
-  // Semantics accessed through dedicated intrinsics remain unallocated and do
-  // not reserve signature rows.
-
-  // struct CSIn {
-  //   uint3 DispatchThreadID : SV_DispatchThreadID;
-  //   uint GroupIndex        : SV_GroupIndex;
-  // };
-  TestConfig Config(
-      Triple::EnvironmentType::Compute, IOType::In,
-      /*UseNative16BitTypes=*/false,
-      {{dxbc::PSV::SemanticKind::DispatchThreadID, /*Rows=*/1, /*Cols=*/3,
-        dxil::ElementType::U32, dxbc::PSV::InterpolationMode::Undefined},
-       {dxbc::PSV::SemanticKind::GroupIndex, /*Rows=*/1, /*Cols=*/1,
-        dxil::ElementType::U32, dxbc::PSV::InterpolationMode::Undefined}});
-
-  // Expected layout: no registers are used.
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/0,
-                {Unallocated, Unallocated});
-}
-
 //===----------------------------------------------------------------------===//
 // Prefix-stable dynamic indexing tests
 //===----------------------------------------------------------------------===//

>From f073eea2ede83ca7b73a47f5bf29d223afe0700d Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 16:57:39 +0000
Subject: [PATCH 11/34] review: adapt prefix-stable tests to the reviewed
 packing harness

Apply stacked-packing reviews f037a272e6fc and 2c35388619db: use verifyPacking/verifyPackingError and Expected-aware assertions. Preserve the reviewed error handling and row-extent checks in the shared harness.
---
 .../HLSLSemanticSignaturePackingTest.cpp      | 68 +++++++++----------
 1 file changed, 34 insertions(+), 34 deletions(-)

diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index e15cdf5e6c7cd..cdfb2fefd8a2f 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -192,7 +192,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, EmptySignature) {
 
   for (PackingMethod Method :
        {PackingMethod::Stacked, PackingMethod::PrefixStable})
-    expectPacking(Method, Config, /*ExpectedRows=*/0, {});
+    verifyPacking(Method, Config, /*ExpectedRows=*/0, {});
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest, SkipsNotAllocatedElements) {
@@ -282,7 +282,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, CoPackingDependsOnMethod) {
 
   // Prefix-stable layout:
   // reg0: A.x | B.y | C.z | D.w
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/0, /*Col=*/1},
                  {/*Row=*/0, /*Col=*/2},
@@ -426,7 +426,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableWhenAppended) {
   // Expected layout:
   // reg0: A.xyz | unused.w
   // reg1: B.xy  | unused.zw
-  expectPacking(PackingMethod::PrefixStable, PrefixConfig, /*ExpectedRows=*/2,
+  verifyPacking(PackingMethod::PrefixStable, PrefixConfig, /*ExpectedRows=*/2,
                 {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
 
   // struct Extended {
@@ -445,7 +445,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableWhenAppended) {
   //
   // C is packed into the gap A left behind, and A and B keep the locations
   // they were given in Prefix.
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, ExtendedConfig, /*ExpectedRows=*/2,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/0, /*Col=*/3}});
 }
@@ -467,7 +467,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableFillsAllRows) {
                                dxbc::PSV::InterpolationMode::Linear});
 
   SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
-  ASSERT_THAT_ERROR(pack(PackingMethod::PrefixStable, Elements, Config),
+  ASSERT_THAT_EXPECTED(pack(PackingMethod::PrefixStable, Elements, Config),
                     Succeeded());
 
   for (unsigned I = 0; I != MaxSignatureRows; ++I) {
@@ -514,7 +514,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableGeneralPacking) {
   // reg1: B.xy | D.zw
   // reg2: C.xyz | G.w
   // reg3: E.x | unused.yzw
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/0},
                  {/*Row=*/2, /*Col=*/0},
@@ -543,7 +543,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableNative16BitWidth) {
   // Expected layout:
   // reg0: A.xy | C.zw
   // reg1: B.xy | unused.zw
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}});
 }
@@ -567,7 +567,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableInterpolationMode) {
   // Expected layout:
   // reg0: A.xy | C.zw
   // reg1: B.xy | unused.zw
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}});
 }
@@ -587,7 +587,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableCompatible16BitTypes) {
 
   // Expected layout:
   // reg0: A.x | B.yzw
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
                 {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/1}});
 }
 
@@ -613,7 +613,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableNormalized16BitTypes) {
   // Expected layout:
   // reg0: A.x | B.y | unused.zw
   // reg1: C.x | unused.yzw
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/1}, {/*Row=*/1, /*Col=*/0}});
 }
@@ -642,7 +642,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableMinPrecisionWidth) {
   // Expected layout:
   // reg0: A.xy | B.zw
   // reg1: C.xy | unused.zw
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}, {/*Row=*/1, /*Col=*/0}});
 }
@@ -669,7 +669,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableUndefinedInterpMode) {
   // Expected layout:
   // reg0: A.xy | B.z | unused.w
   // reg1: C.x  | unused.yzw
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}, {/*Row=*/1, /*Col=*/0}});
 }
@@ -697,7 +697,7 @@ TEST_F(HLSLSemanticSignaturePackingTest,
   // Expected layout:
   // reg0: A.xy | C.zw
   // reg1: B.xy | unused.zw
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}});
 }
@@ -726,7 +726,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableDistinctInterpModes) {
   // reg0: A.xy | unused.zw
   // reg1: B.xy | unused.zw
   // reg2: C.xy | unused.zw
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/2, /*Col=*/0}});
 }
@@ -757,7 +757,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSystemValueOrdering) {
 
   // Expected layout:
   // reg0: A.x | Position.y | IsFrontFace.z | unused.w
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/1}, {/*Row=*/0, /*Col=*/2}});
 }
@@ -782,7 +782,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableArbitraryNotRightOfSV) {
   // Expected layout:
   // reg0: Position.xy | unused.zw
   // reg1: A.xy        | unused.zw
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
                 {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
 }
 
@@ -809,7 +809,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSGVIsRightmost) {
   // Expected layout:
   // reg0: IsFrontFace.x | unused.yzw
   // reg1: A.x | Position.y | unused.zw
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/1, /*Col=*/1}});
 }
@@ -842,7 +842,7 @@ TEST_F(HLSLSemanticSignaturePackingTest,
                                /*Cols=*/3, dxil::ElementType::I32,
                                dxbc::PSV::InterpolationMode::Constant});
   // The last element is the one that no longer fits.
-  expectPackingError(PackingMethod::PrefixStable, Config,
+  verifyPackingError(PackingMethod::PrefixStable, Config,
                      SignaturePackingError::SignatureOverflow,
                      /*ExpectedElementIndex=*/MaxSignatureRows);
 }
@@ -879,7 +879,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedRanges) {
   // reg0: A[0].xy | B[0].z | C.w
   // reg1: A[1].xy | B[1].z | unused.w
   // reg2: Position.x | unused.yzw
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/0, /*Col=*/2},
                  {/*Row=*/0, /*Col=*/3},
@@ -906,7 +906,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedAfterSystemValue) {
   // reg0: Position.x | unused.yzw
   // reg1: A[0].xyz   | unused.w
   // reg2: A[1].xyz   | unused.w
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
                 {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
 }
 
@@ -933,7 +933,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableTessFactors) {
   // Expected layout:
   // reg0: Data[0].xyz | TessFactor[0].w
   // reg1: Data[1].xyz | TessFactor[1].w
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
                 {{/*Row=*/0, /*Col=*/3}, {/*Row=*/0, /*Col=*/0}});
 }
 
@@ -956,7 +956,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSingleRowTessFactor) {
   // Expected layout:
   // reg0: TessFactor.x | unused.yzw
   // reg1: Data.xyz     | unused.w
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
                 {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
 }
 
@@ -984,7 +984,7 @@ TEST_F(HLSLSemanticSignaturePackingTest,
   // reg2: Data[2].xyz | unused.w
   // reg3: unused.xyz  | TessFactor[0].w
   // reg4: unused.xyz  | TessFactor[1].w
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/5,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/5,
                 {{/*Row=*/0, /*Col=*/0}, {/*Row=*/3, /*Col=*/3}});
 }
 
@@ -1025,7 +1025,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCull) {
   // reg1: Clip0.x         | Cull1.yzw
   // reg2: Cull0.x         | Clip1.yz | unused.w
   // reg3: AfterClipCull.x | unused.yzw
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/1},
@@ -1065,7 +1065,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedClipCull) {
   // reg1: Clip0.x         | Cull1[0].yz | Clip1.w
   // reg2: unused.x        | Cull1[1].yz | unused.w
   // reg3: AfterClipCull.x | unused.yzw
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/1},
@@ -1104,7 +1104,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableMultipleIndexedClipCull) {
   // reg1: Clip0.x         | Cull1[0].yz | Clip1[0].w
   // reg2: unused.x        | Cull1[1].yz | Clip1[1].w
   // reg3: AfterClipCull.x | unused.yzw
-  expectPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/1},
@@ -1132,7 +1132,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCullFillsTwoRows) {
   // Expected layout:
   // reg0: Clip0.xyzw
   // reg1: Cull0.xyzw
-  expectPacking(PackingMethod::PrefixStable, Config,
+  verifyPacking(PackingMethod::PrefixStable, Config,
                 /*ExpectedRows=*/MaxClipCullRows,
                 {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
 }
@@ -1162,7 +1162,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSeparatesClipCullRows) {
   // reg0:     Clip0.xyz | unused.w
   // reg1-30:  A[0-29].xyzw
   // reg31:    Cull0.xyz | unused.w
-  expectPacking(PackingMethod::PrefixStable, Config,
+  verifyPacking(PackingMethod::PrefixStable, Config,
                 /*ExpectedRows=*/MaxSignatureRows,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/0},
@@ -1192,7 +1192,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCullAsArbitrary) {
   // reg0: Clip0.xyz | unused.w
   // reg1: Clip1.xyz | unused.w
   // reg2: Cull0.xyz | unused.w
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/2, /*Col=*/0}});
 }
@@ -1221,7 +1221,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCullWhenAppended) {
   // reg0: First.xyz | unused.w
   // reg1: Clip0.x   | Cull1[0].yz | unused.w
   // reg2: unused.x  | Cull1[1].yz | unused.w
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, PrefixConfig, /*ExpectedRows=*/3,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/1, /*Col=*/1}});
 
@@ -1241,7 +1241,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCullWhenAppended) {
   // reg1: Clip0.x         | Cull1[0].yz | Clip1.w
   // reg2: unused.x        | Cull1[1].yz | unused.w
   // reg3: AfterClipCull.x | unused.yzw
-  expectPacking(PackingMethod::PrefixStable, ExtendedConfig, /*ExpectedRows=*/4,
+  verifyPacking(PackingMethod::PrefixStable, ExtendedConfig, /*ExpectedRows=*/4,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/0},
                  {/*Row=*/1, /*Col=*/1},
@@ -1263,7 +1263,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsClipCullOverflow) {
         dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
        {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/3,
         dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
-  expectPackingError(PackingMethod::PrefixStable, Config,
+  verifyPackingError(PackingMethod::PrefixStable, Config,
                      SignaturePackingError::ClipCullOverflow,
                      /*ExpectedElementIndex=*/2);
 }
@@ -1282,7 +1282,7 @@ TEST_F(HLSLSemanticSignaturePackingTest,
         dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
        {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/2,
         dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
-  expectPackingError(PackingMethod::PrefixStable, Config,
+  verifyPackingError(PackingMethod::PrefixStable, Config,
                      SignaturePackingError::ClipCullOverflow,
                      /*ExpectedElementIndex=*/2);
 }
@@ -1325,7 +1325,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableGeometryStreams) {
   // stream0 reg0: A.xyzw
   // stream0 reg1: C.xy | unused.zw
   // stream1 reg0: B.xyzw
-  expectPacking(
+  verifyPacking(
       PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
 }

>From 82af3a9b21223c4bfe17b2db12bf2a15f3aa5c46 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 16:58:33 +0000
Subject: [PATCH 12/34] review: remove misleading const from prefix-stable
 packing

Apply stacked review 2f98b3ef30d3 and indexed review bed2f08057a1. The enumerated elements are mutated when assigning their locations.
---
 llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 143f82c175f09..a06253d605d69 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -416,7 +416,7 @@ Error llvm::hlsl::packSignaturePrefixStable(
 
   SmallVector<std::array<SignatureRow, MaxSignatureRows>, 1> Rows(StreamCount);
   SmallVector<ClipCullState, 1> ClipCullStates(StreamCount);
-  for (const auto &[Index, Element] : enumerate(Elements)) {
+  for (auto &&[Index, Element] : enumerate(Elements)) {
     assert(Element.StartRow == UnallocatedRow &&
            Element.StartCol == UnallocatedCol && "already allocated?");
     assert(Element.Rows > 0 && "signature element must have at least one row");

>From 51c77d305afd73427ecf563b280344069b0ee81b Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 16:58:39 +0000
Subject: [PATCH 13/34] review: clarify prefix-stable packing semantic
 assertions

Apply stacked review 5c084c38c507 and indexed review f2dbc42def72. Sema diagnoses invalid semantic interpretations before packing, so an assertion is sufficient here.
---
 llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index a06253d605d69..85dd036712501 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -435,7 +435,8 @@ Error llvm::hlsl::packSignaturePrefixStable(
             Interpretation == SemanticInterpretation::SGV ||
             Interpretation == SemanticInterpretation::ClipCull ||
             Interpretation == SemanticInterpretation::TessFactor) &&
-           "unexpected semantic interpretation for prefix-stable packing");
+           "unexpected semantic interpretation for prefix-stable packing, "
+           "should have been diagnosed by Sema");
 
     const unsigned ComponentWidth =
         getComponentWidth(Element.CompType, UseNative16BitTypes);

>From f8f0566b5f7b6df950c4edeb607f81dd8e18f3f9 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 16:59:06 +0000
Subject: [PATCH 14/34] review: return the prefix-stable signature row extent

Apply stacked review 2c35388619db and indexed review e874ea2f768b by returning Expected<unsigned> and checking the returned extent directly in the shared test harness.

Include clip/cull reservations and return the maximum extent across geometry streams, not their sum. Cover unallocated-only signatures and all four full geometry streams as well as the existing empty, co-packed, clip/cull and last-row cases.
---
 .../Frontend/HLSL/SemanticSignaturePacking.h  |   6 +-
 .../HLSL/SemanticSignaturePacking.cpp         |  13 ++-
 .../HLSLSemanticSignaturePackingTest.cpp      | 105 +++++++++++++++---
 3 files changed, 102 insertions(+), 22 deletions(-)

diff --git a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
index 7fb9b5e2f8083..5365a5f364501 100644
--- a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
+++ b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
@@ -70,7 +70,11 @@ packSignatureStacked(MutableArrayRef<SemanticSignatureElement> Elements,
 ///
 /// See llvm/docs/DirectX/SemanticSignatures.md#prefix-stable-packing for
 /// details.
-LLVM_ABI Error packSignaturePrefixStable(
+///
+/// Returns one past the highest allocated row, or zero if no elements were
+/// allocated. For geometry outputs this is the maximum extent of any stream,
+/// not the sum of their extents.
+LLVM_ABI Expected<unsigned> packSignaturePrefixStable(
     MutableArrayRef<SemanticSignatureElement> Elements,
     Triple::EnvironmentType ShaderStage, IOType IOTy, bool UseNative16BitTypes);
 
diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 85dd036712501..9d40718c76ffe 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -404,7 +404,7 @@ Expected<unsigned> llvm::hlsl::packSignatureStacked(
   return NextRow;
 }
 
-Error llvm::hlsl::packSignaturePrefixStable(
+Expected<unsigned> llvm::hlsl::packSignaturePrefixStable(
     MutableArrayRef<SemanticSignatureElement> Elements,
     Triple::EnvironmentType ShaderStage, IOType IOTy,
     bool UseNative16BitTypes) {
@@ -416,6 +416,7 @@ Error llvm::hlsl::packSignaturePrefixStable(
 
   SmallVector<std::array<SignatureRow, MaxSignatureRows>, 1> Rows(StreamCount);
   SmallVector<ClipCullState, 1> ClipCullStates(StreamCount);
+  unsigned NumRows = 0;
   for (auto &&[Index, Element] : enumerate(Elements)) {
     assert(Element.StartRow == UnallocatedRow &&
            Element.StartCol == UnallocatedCol && "already allocated?");
@@ -460,14 +461,14 @@ Error llvm::hlsl::packSignaturePrefixStable(
                                   ClipCullStates[StreamIndex], Placement))
         return make_error<SignaturePackingError>(*Kind,
                                                  static_cast<unsigned>(Index));
-      continue;
-    }
-
-    if (!packElement(Element, StreamRows, Placement))
+    } else if (!packElement(Element, StreamRows, Placement)) {
       return make_error<SignaturePackingError>(
           SignaturePackingError::SignatureOverflow,
           static_cast<unsigned>(Index));
+    }
+
+    NumRows = std::max(NumRows, Element.StartRow + Element.Rows);
   }
 
-  return Error::success();
+  return NumRows;
 }
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index cdfb2fefd8a2f..405d3e882ce84 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -11,7 +11,6 @@
 #include "llvm/TargetParser/Triple.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gtest/gtest.h"
-#include <algorithm>
 #include <initializer_list>
 
 using namespace llvm;
@@ -90,18 +89,9 @@ class HLSLSemanticSignaturePackingTest : public testing::Test {
     switch (Method) {
     case PackingMethod::Stacked:
       return packSignatureStacked(Elements, Config.ShaderStage, Config.IOTy);
-    case PackingMethod::PrefixStable: {
-      if (Error E = packSignaturePrefixStable(Elements, Config.ShaderStage,
-                                             Config.IOTy,
-                                             Config.UseNative16BitTypes))
-        return std::move(E);
-
-      unsigned Rows = 0;
-      for (const SemanticSignatureElement &Element : Elements)
-        if (Element.isAllocated())
-          Rows = std::max(Rows, Element.StartRow + Element.Rows);
-      return Rows;
-    }
+    case PackingMethod::PrefixStable:
+      return packSignaturePrefixStable(Elements, Config.ShaderStage,
+                                       Config.IOTy, Config.UseNative16BitTypes);
     }
     llvm_unreachable("invalid packing method");
   }
@@ -407,6 +397,72 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsMultiRowSignatureOverflow) {
 // Basic prefix-stable packing tests
 //===----------------------------------------------------------------------===//
 
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSupportedSignatures) {
+  const struct {
+    Triple::EnvironmentType Stage;
+    IOType IOTy;
+  } Signatures[] = {{Triple::Vertex, IOType::Out},
+                    {Triple::Hull, IOType::In},
+                    {Triple::Hull, IOType::Out},
+                    {Triple::Hull, IOType::PatchConstantOrPrimitive},
+                    {Triple::Domain, IOType::In},
+                    {Triple::Domain, IOType::Out},
+                    {Triple::Domain, IOType::PatchConstantOrPrimitive},
+                    {Triple::Geometry, IOType::In},
+                    {Triple::Geometry, IOType::Out},
+                    {Triple::Pixel, IOType::In},
+                    {Triple::Mesh, IOType::Out},
+                    {Triple::Mesh, IOType::PatchConstantOrPrimitive}};
+  for (const auto &Signature : Signatures) {
+    SCOPED_TRACE(static_cast<unsigned>(Signature.Stage));
+    SCOPED_TRACE(static_cast<unsigned>(Signature.IOTy));
+    TestConfig Config(
+        Signature.Stage, Signature.IOTy,
+        {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+          dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined}});
+    verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
+                  {{/*Row=*/0, /*Col=*/0}});
+  }
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableOnlyUnallocatedElements) {
+  TestConfig Config(
+      Triple::Pixel, IOType::In,
+      {{dxbc::PSV::SemanticKind::ViewID, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::U32, dxbc::PSV::InterpolationMode::Undefined}});
+
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/0,
+                {Unallocated});
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSupportedSignatures) {
+  const struct {
+    Triple::EnvironmentType Stage;
+    IOType IOTy;
+  } Signatures[] = {{Triple::Vertex, IOType::Out},
+                    {Triple::Hull, IOType::In},
+                    {Triple::Hull, IOType::Out},
+                    {Triple::Hull, IOType::PatchConstantOrPrimitive},
+                    {Triple::Domain, IOType::In},
+                    {Triple::Domain, IOType::Out},
+                    {Triple::Domain, IOType::PatchConstantOrPrimitive},
+                    {Triple::Geometry, IOType::In},
+                    {Triple::Geometry, IOType::Out},
+                    {Triple::Pixel, IOType::In},
+                    {Triple::Mesh, IOType::Out},
+                    {Triple::Mesh, IOType::PatchConstantOrPrimitive}};
+  for (const auto &Signature : Signatures) {
+    SCOPED_TRACE(static_cast<unsigned>(Signature.Stage));
+    SCOPED_TRACE(static_cast<unsigned>(Signature.IOTy));
+    TestConfig Config(
+        Signature.Stage, Signature.IOTy,
+        {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+          dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined}});
+    verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
+                  {{/*Row=*/0, /*Col=*/0}});
+  }
+}
+
 TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableWhenAppended) {
   // Appending an element to a signature never moves the elements declared
   // before it; the appended element is only packed into the space they left.
@@ -467,8 +523,9 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableFillsAllRows) {
                                dxbc::PSV::InterpolationMode::Linear});
 
   SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
-  ASSERT_THAT_EXPECTED(pack(PackingMethod::PrefixStable, Elements, Config),
-                    Succeeded());
+  Expected<unsigned> Rows = pack(PackingMethod::PrefixStable, Elements, Config);
+  ASSERT_THAT_EXPECTED(Rows, Succeeded());
+  EXPECT_EQ(*Rows, MaxSignatureRows);
 
   for (unsigned I = 0; I != MaxSignatureRows; ++I) {
     EXPECT_EQ(Elements[I].StartRow, I) << "element " << I;
@@ -1291,6 +1348,24 @@ TEST_F(HLSLSemanticSignaturePackingTest,
 // Prefix-stable geometry stream tests
 //===----------------------------------------------------------------------===//
 
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableFullGeometryStreams) {
+  TestConfig Config(Triple::Geometry, IOType::Out, {});
+  for (unsigned Stream = 0; Stream != MaxGeometryStreams; ++Stream)
+    Config.Elements.push_back(
+        {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/MaxSignatureRows,
+         /*Cols=*/MaxSignatureCols, dxil::ElementType::F32,
+         dxbc::PSV::InterpolationMode::Linear, /*SemanticIndex=*/0, Stream});
+
+  // Every stream can fill its entire register space independently. Return
+  // the maximum extent, not the sum of all streams' extents.
+  verifyPacking(PackingMethod::PrefixStable, Config,
+                /*ExpectedRows=*/MaxSignatureRows,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/0, /*Col=*/0}});
+}
+
 TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableGeometryStreams) {
   // Each geometry shader output stream is packed into its own signature, so
   // elements of different streams never share a register. The reported number

>From 66181a2e914277b1a67c93bb453147db6d57a427 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 16:59:49 +0000
Subject: [PATCH 15/34] review: document and test partial prefix-stable
 allocation on failure

Apply stacked review 538ce4ada600 and indexed review f779434c2a22. Preserve earlier locations for diagnostics while leaving the failing and subsequent elements unallocated, for both signature and clip/cull overflow.
---
 .../Frontend/HLSL/SemanticSignaturePacking.h  |  5 +++
 .../HLSLSemanticSignaturePackingTest.cpp      | 34 +++++++++++++++++++
 2 files changed, 39 insertions(+)

diff --git a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
index 5365a5f364501..b560db6d6c7e0 100644
--- a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
+++ b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
@@ -74,6 +74,11 @@ packSignatureStacked(MutableArrayRef<SemanticSignatureElement> Elements,
 /// Returns one past the highest allocated row, or zero if no elements were
 /// allocated. For geometry outputs this is the maximum extent of any stream,
 /// not the sum of their extents.
+///
+/// On failure, Elements is left partially packed: the elements preceding the
+/// one reported by the returned SignaturePackingError keep the locations
+/// they were assigned, while that element and the ones following it retain the
+/// unallocated row and column sentinels.
 LLVM_ABI Expected<unsigned> packSignaturePrefixStable(
     MutableArrayRef<SemanticSignatureElement> Elements,
     Triple::EnvironmentType ShaderStage, IOType IOTy, bool UseNative16BitTypes);
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 405d3e882ce84..6f99896a11e5b 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -1344,6 +1344,40 @@ TEST_F(HLSLSemanticSignaturePackingTest,
                      /*ExpectedElementIndex=*/2);
 }
 
+//===----------------------------------------------------------------------===//
+// Prefix-stable failure state tests
+//===----------------------------------------------------------------------===//
+
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStablePreservesPartialAllocation) {
+  for (bool IsClipCull : {false, true}) {
+    const auto Kind = IsClipCull ? dxbc::PSV::SemanticKind::ClipDistance
+                                : dxbc::PSV::SemanticKind::Arbitrary;
+    const unsigned RowCount = IsClipCull ? MaxClipCullRows : MaxSignatureRows;
+    TestConfig Config(
+        Triple::Vertex, IOType::Out,
+        {{Kind, RowCount, /*Cols=*/MaxSignatureCols, dxil::ElementType::F32,
+          dxbc::PSV::InterpolationMode::Linear},
+         {Kind, /*Rows=*/1, /*Cols=*/1, dxil::ElementType::F32,
+          dxbc::PSV::InterpolationMode::Linear},
+         {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+          dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+    verifyPackingError(PackingMethod::PrefixStable, Config,
+                       IsClipCull ? SignaturePackingError::ClipCullOverflow
+                                  : SignaturePackingError::SignatureOverflow,
+                       /*ExpectedElementIndex=*/1);
+
+    SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
+    EXPECT_THAT_EXPECTED(pack(PackingMethod::PrefixStable, Elements, Config),
+                         Failed<SignaturePackingError>());
+    EXPECT_EQ(Elements[0].StartRow, 0u);
+    EXPECT_EQ(Elements[0].StartCol, 0u);
+    for (unsigned I = 1; I != Elements.size(); ++I) {
+      EXPECT_EQ(Elements[I].StartRow, UnallocatedRow) << "element " << I;
+      EXPECT_EQ(Elements[I].StartCol, UnallocatedCol) << "element " << I;
+    }
+  }
+}
+
 //===----------------------------------------------------------------------===//
 // Prefix-stable geometry stream tests
 //===----------------------------------------------------------------------===//

>From a5995182d9d4187eefa2f059ede84d3e47c22baf Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:00:02 +0000
Subject: [PATCH 16/34] review: use the clip/cull row limit in overflow
 diagnostics

Apply stacked review f301fb9a1183 rather than spelling out the row bound. Check the clip/cull-specific message and element index, following indexed review 84026a5dee7a.
---
 llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp        | 2 +-
 .../Frontend/HLSLSemanticSignaturePackingTest.cpp          | 7 +++++++
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 9d40718c76ffe..01d096fa50e16 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -360,7 +360,7 @@ void SignaturePackingError::log(raw_ostream &OS) const {
     OS << "signature elements do not fit in " << MaxSignatureRows << " rows";
     break;
   case ClipCullOverflow:
-    OS << "clip/cull elements do not fit in two rows";
+    OS << "clip/cull elements do not fit in " << MaxClipCullRows << " rows";
     break;
   }
   OS << " (element " << ElementIndex << ")";
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 6f99896a11e5b..03ea2c09c411a 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -12,6 +12,7 @@
 #include "llvm/Testing/Support/Error.h"
 #include "gtest/gtest.h"
 #include <initializer_list>
+#include <string>
 
 using namespace llvm;
 using namespace llvm::hlsl;
@@ -1323,6 +1324,12 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsClipCullOverflow) {
   verifyPackingError(PackingMethod::PrefixStable, Config,
                      SignaturePackingError::ClipCullOverflow,
                      /*ExpectedElementIndex=*/2);
+
+  SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
+  EXPECT_THAT_EXPECTED(
+      pack(PackingMethod::PrefixStable, Elements, Config),
+      FailedWithMessage("clip/cull elements do not fit in " +
+                        std::to_string(MaxClipCullRows) + " rows (element 2)"));
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest,

>From 46c55348f009887d28afc078ad56a8315dc587b4 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 16:58:23 +0000
Subject: [PATCH 17/34] review: enforce prefix-stable packing signature
 preconditions

Apply stacked reviews 1333db46be70 and 89c618d4c046 and indexed review f92a53060bcf. Assert the supported stage and I/O combinations, exercise valid signatures, and reject stages handled by other packers even for empty signatures.

Use vertex inputs for stacked tests and vertex outputs for prefix-stable tests. Test an unallocated ViewID between allocated pixel inputs rather than passing a compute signature to the packer.
---
 .../Frontend/HLSL/SemanticSignaturePacking.h  |  7 +--
 .../HLSL/SemanticSignaturePacking.cpp         |  5 ++
 .../HLSLSemanticSignaturePackingTest.cpp      | 49 +++++++++++++------
 3 files changed, 42 insertions(+), 19 deletions(-)

diff --git a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
index b560db6d6c7e0..55e4eaa514dfe 100644
--- a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
+++ b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
@@ -79,9 +79,10 @@ packSignatureStacked(MutableArrayRef<SemanticSignatureElement> Elements,
 /// one reported by the returned SignaturePackingError keep the locations
 /// they were assigned, while that element and the ones following it retain the
 /// unallocated row and column sentinels.
-LLVM_ABI Expected<unsigned> packSignaturePrefixStable(
-    MutableArrayRef<SemanticSignatureElement> Elements,
-    Triple::EnvironmentType ShaderStage, IOType IOTy, bool UseNative16BitTypes);
+LLVM_ABI Expected<unsigned>
+packSignaturePrefixStable(MutableArrayRef<SemanticSignatureElement> Elements,
+                          Triple::EnvironmentType ShaderStage, IOType IOTy,
+                          bool UseNative16BitTypes);
 
 } // namespace llvm::hlsl
 
diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 01d096fa50e16..3988fe439c733 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -408,6 +408,11 @@ Expected<unsigned> llvm::hlsl::packSignaturePrefixStable(
     MutableArrayRef<SemanticSignatureElement> Elements,
     Triple::EnvironmentType ShaderStage, IOType IOTy,
     bool UseNative16BitTypes) {
+  assert(!(ShaderStage == Triple::Vertex && IOTy == IOType::In) &&
+         !(ShaderStage == Triple::Pixel && IOTy == IOType::Out) &&
+         "prefix-stable packing is not valid for vertex inputs or pixel "
+         "outputs");
+
   // Only a geometry shader output signature packs its streams independently.
   const unsigned StreamCount =
       ShaderStage == Triple::EnvironmentType::Geometry && IOTy == IOType::Out
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 03ea2c09c411a..f71286352f01b 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -83,10 +83,9 @@ class HLSLSemanticSignaturePackingTest : public testing::Test {
     return Elements;
   }
 
-  Expected<unsigned>
-  pack(PackingMethod Method,
-       SmallVectorImpl<SemanticSignatureElement> &Elements,
-       const TestConfig &Config) {
+  Expected<unsigned> pack(PackingMethod Method,
+                          SmallVectorImpl<SemanticSignatureElement> &Elements,
+                          const TestConfig &Config) {
     switch (Method) {
     case PackingMethod::Stacked:
       return packSignatureStacked(Elements, Config.ShaderStage, Config.IOTy);
@@ -182,8 +181,10 @@ TEST_F(HLSLSemanticSignaturePackingTest, EmptySignature) {
   TestConfig Config(Triple::EnvironmentType::Vertex, IOType::Out, {});
 
   for (PackingMethod Method :
-       {PackingMethod::Stacked, PackingMethod::PrefixStable})
+       {PackingMethod::Stacked, PackingMethod::PrefixStable}) {
+    Config.IOTy = Method == PackingMethod::Stacked ? IOType::In : IOType::Out;
     verifyPacking(Method, Config, /*ExpectedRows=*/0, {});
+  }
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest, SkipsNotAllocatedElements) {
@@ -210,6 +211,12 @@ TEST_F(HLSLSemanticSignaturePackingTest, SkipsNotAllocatedElements) {
   // reg1: B.xyz | unused.w
   verifyPacking(PackingMethod::Stacked, Config, /*ExpectedRows=*/2,
                 {{/*Row=*/0, /*Col=*/0}, Unallocated, {/*Row=*/1, /*Col=*/0}});
+
+  // ViewID is also not allocated in pixel inputs. The surrounding elements
+  // still use the same rows when packed prefix-stably.
+  Config.ShaderStage = Triple::Pixel;
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/2,
+                {{/*Row=*/0, /*Col=*/0}, Unallocated, {/*Row=*/1, /*Col=*/0}});
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest, StacksInDeclarationOrder) {
@@ -271,8 +278,9 @@ TEST_F(HLSLSemanticSignaturePackingTest, CoPackingDependsOnMethod) {
                  {/*Row=*/2, /*Col=*/0},
                  {/*Row=*/3, /*Col=*/0}});
 
-  // Prefix-stable layout:
+  // Prefix-stable layout for the corresponding vertex output signature:
   // reg0: A.x | B.y | C.z | D.w
+  Config.IOTy = IOType::Out;
   verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/0, /*Col=*/1},
@@ -324,9 +332,11 @@ TEST_F(HLSLSemanticSignaturePackingTest, ExactlyFillsSignature) {
   // Expected layout:
   // reg0-31: A[0-31].xyzw
   for (PackingMethod Method :
-       {PackingMethod::Stacked, PackingMethod::PrefixStable})
+       {PackingMethod::Stacked, PackingMethod::PrefixStable}) {
+    Config.IOTy = Method == PackingMethod::Stacked ? IOType::In : IOType::Out;
     verifyPacking(Method, Config, /*ExpectedRows=*/MaxSignatureRows,
                   {{/*Row=*/0, /*Col=*/0}});
+  }
 }
 
 //===----------------------------------------------------------------------===//
@@ -350,9 +360,11 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsSignatureOverflow) {
 
   // The last element is the one that no longer fits.
   for (PackingMethod Method :
-       {PackingMethod::Stacked, PackingMethod::PrefixStable})
+       {PackingMethod::Stacked, PackingMethod::PrefixStable}) {
+    Config.IOTy = Method == PackingMethod::Stacked ? IOType::In : IOType::Out;
     verifyPackingError(Method, Config, SignaturePackingError::SignatureOverflow,
                        /*ExpectedElementIndex=*/MaxSignatureRows);
+  }
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest, RejectsSingleElementOverflow) {
@@ -368,9 +380,11 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsSingleElementOverflow) {
                       dxbc::PSV::InterpolationMode::Linear}});
 
   for (PackingMethod Method :
-       {PackingMethod::Stacked, PackingMethod::PrefixStable})
+       {PackingMethod::Stacked, PackingMethod::PrefixStable}) {
+    Config.IOTy = Method == PackingMethod::Stacked ? IOType::In : IOType::Out;
     verifyPackingError(Method, Config, SignaturePackingError::SignatureOverflow,
                        /*ExpectedElementIndex=*/0);
+  }
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest, RejectsMultiRowSignatureOverflow) {
@@ -389,9 +403,11 @@ TEST_F(HLSLSemanticSignaturePackingTest, RejectsMultiRowSignatureOverflow) {
                       dxbc::PSV::InterpolationMode::Linear}});
 
   for (PackingMethod Method :
-       {PackingMethod::Stacked, PackingMethod::PrefixStable})
+       {PackingMethod::Stacked, PackingMethod::PrefixStable}) {
+    Config.IOTy = Method == PackingMethod::Stacked ? IOType::In : IOType::Out;
     verifyPackingError(Method, Config, SignaturePackingError::SignatureOverflow,
                        /*ExpectedElementIndex=*/1);
+  }
 }
 
 //===----------------------------------------------------------------------===//
@@ -1326,10 +1342,10 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsClipCullOverflow) {
                      /*ExpectedElementIndex=*/2);
 
   SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
-  EXPECT_THAT_EXPECTED(
-      pack(PackingMethod::PrefixStable, Elements, Config),
-      FailedWithMessage("clip/cull elements do not fit in " +
-                        std::to_string(MaxClipCullRows) + " rows (element 2)"));
+  EXPECT_THAT_EXPECTED(pack(PackingMethod::PrefixStable, Elements, Config),
+                       FailedWithMessage("clip/cull elements do not fit in " +
+                                         std::to_string(MaxClipCullRows) +
+                                         " rows (element 2)"));
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest,
@@ -1355,10 +1371,11 @@ TEST_F(HLSLSemanticSignaturePackingTest,
 // Prefix-stable failure state tests
 //===----------------------------------------------------------------------===//
 
-TEST_F(HLSLSemanticSignaturePackingTest, PrefixStablePreservesPartialAllocation) {
+TEST_F(HLSLSemanticSignaturePackingTest,
+       PrefixStablePreservesPartialAllocation) {
   for (bool IsClipCull : {false, true}) {
     const auto Kind = IsClipCull ? dxbc::PSV::SemanticKind::ClipDistance
-                                : dxbc::PSV::SemanticKind::Arbitrary;
+                                 : dxbc::PSV::SemanticKind::Arbitrary;
     const unsigned RowCount = IsClipCull ? MaxClipCullRows : MaxSignatureRows;
     TestConfig Config(
         Triple::Vertex, IOType::Out,

>From 7eebfed44eca4a69c28795eab8c6c890af38886f Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:15:45 +0000
Subject: [PATCH 18/34] review: remove duplicate supported-signatures test

Remove the duplicate introduced while rearranging the earlier review commits so the frontend unit tests can compile before applying PR #218062 feedback.
---
 .../HLSLSemanticSignaturePackingTest.cpp      | 28 -------------------
 1 file changed, 28 deletions(-)

diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index f71286352f01b..7859bc5064e83 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -452,34 +452,6 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableOnlyUnallocatedElements) {
                 {Unallocated});
 }
 
-TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSupportedSignatures) {
-  const struct {
-    Triple::EnvironmentType Stage;
-    IOType IOTy;
-  } Signatures[] = {{Triple::Vertex, IOType::Out},
-                    {Triple::Hull, IOType::In},
-                    {Triple::Hull, IOType::Out},
-                    {Triple::Hull, IOType::PatchConstantOrPrimitive},
-                    {Triple::Domain, IOType::In},
-                    {Triple::Domain, IOType::Out},
-                    {Triple::Domain, IOType::PatchConstantOrPrimitive},
-                    {Triple::Geometry, IOType::In},
-                    {Triple::Geometry, IOType::Out},
-                    {Triple::Pixel, IOType::In},
-                    {Triple::Mesh, IOType::Out},
-                    {Triple::Mesh, IOType::PatchConstantOrPrimitive}};
-  for (const auto &Signature : Signatures) {
-    SCOPED_TRACE(static_cast<unsigned>(Signature.Stage));
-    SCOPED_TRACE(static_cast<unsigned>(Signature.IOTy));
-    TestConfig Config(
-        Signature.Stage, Signature.IOTy,
-        {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
-          dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined}});
-    verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
-                  {{/*Row=*/0, /*Col=*/0}});
-  }
-}
-
 TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableWhenAppended) {
   // Appending an element to a signature never moves the elements declared
   // before it; the appended element is only packed into the space they left.

>From b39a5404f03f76d45c59176abd9a1902ad4c853f Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:16:08 +0000
Subject: [PATCH 19/34] review: define dynamically indexed signature rows
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Address hekota’s suggestion to explain the multi-row range and dynamic row selection.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3883562891
---
 llvm/docs/DirectX/SemanticSignatures.md | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/llvm/docs/DirectX/SemanticSignatures.md b/llvm/docs/DirectX/SemanticSignatures.md
index 9ca20487c1624..c3b4a68ef5879 100644
--- a/llvm/docs/DirectX/SemanticSignatures.md
+++ b/llvm/docs/DirectX/SemanticSignatures.md
@@ -193,8 +193,8 @@ constraints are satisfied:
 - Components are ordered from arbitrary values, to system values, to system
   generated values.
 - A system value or system generated value cannot be placed in a dynamically
-  indexed row. Multi-row elements define the dynamically indexed range that
-  they cover.
+  indexed row. A dynamically indexed row is a row within the range covered by
+  a multi-row element, where the row is selected using a dynamic index.
 
 Some semantic interpretations require additional handling:
 

>From 553763e279203bc4b58940a594382141fb077e15 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:16:29 +0000
Subject: [PATCH 20/34] review: name the prefix-stable element packing helper
 explicitly

Rename packElement to prefixPackElement to distinguish the first-fit prefix-stable algorithm from other packing methods.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3883695496
---
 llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 3988fe439c733..79db8bd39f209 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -240,9 +240,9 @@ static void placeAt(MutableArrayRef<SignatureRow> Rows, unsigned StartRow,
   Element.StartCol = getStartColumn(ColumnMask);
 }
 
-static bool packElement(SemanticSignatureElement &Element,
-                        MutableArrayRef<SignatureRow> Rows,
-                        const ElementPlacement &Placement) {
+static bool prefixPackElement(SemanticSignatureElement &Element,
+                              MutableArrayRef<SignatureRow> Rows,
+                              const ElementPlacement &Placement) {
   for (unsigned StartRow = 0; StartRow != Rows.size(); ++StartRow) {
     std::optional<uint8_t> ColumnMask = canPlaceAt(Rows, StartRow, Placement);
     if (!ColumnMask)
@@ -466,7 +466,7 @@ Expected<unsigned> llvm::hlsl::packSignaturePrefixStable(
                                   ClipCullStates[StreamIndex], Placement))
         return make_error<SignaturePackingError>(*Kind,
                                                  static_cast<unsigned>(Index));
-    } else if (!packElement(Element, StreamRows, Placement)) {
+    } else if (!prefixPackElement(Element, StreamRows, Placement)) {
       return make_error<SignaturePackingError>(
           SignaturePackingError::SignatureOverflow,
           static_cast<unsigned>(Index));

>From 6f86ef9ab69a2e007d1467ee8f46f09e5f6d3052 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:16:41 +0000
Subject: [PATCH 21/34] review: reject placements starting past the last
 signature row

Reject StartRow == Rows.size() explicitly rather than relying on the positive placement row count to reject it via the remaining-capacity check. Existing full-signature and overflow tests cover the valid and invalid boundaries.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884423886
---
 llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 79db8bd39f209..153abab1ffca6 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -172,7 +172,7 @@ static bool canCoPack(const SignatureRow &Row,
 static std::optional<uint8_t> canPlaceAt(ArrayRef<SignatureRow> Rows,
                                          unsigned StartRow,
                                          const ElementPlacement &Placement) {
-  if (StartRow > Rows.size() || Placement.Rows > Rows.size() - StartRow)
+  if (StartRow >= Rows.size() || Placement.Rows > Rows.size() - StartRow)
     return std::nullopt;
 
   const IndexedRowRange IndexedRange =

>From 1de57efcb66c26eb4b94e88e919d99b99e505a93 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:17:00 +0000
Subject: [PATCH 22/34] review: align the system-value ordering HLSL example

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884745269
---
 llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 7859bc5064e83..5332a34fc6577 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -787,7 +787,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSystemValueOrdering) {
 
   // struct PSIn {
   //   uint A             : A;
-  //   float Position      : SV_Position;
+  //   float Position     : SV_Position;
   //   bool IsFrontFace   : SV_IsFrontFace;
   // };
   TestConfig Config(

>From 91fbf7cd05c25705d740fdb2800f9c421da679f6 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:17:28 +0000
Subject: [PATCH 23/34] review: exercise merging differently sized indexed row
 ranges

Extend B to three rows while A still spans two. Verify their shared columns and that Position is placed after the extended indexed range.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884813641
---
 .../HLSLSemanticSignaturePackingTest.cpp         | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 5332a34fc6577..a53d239fef506 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -900,12 +900,13 @@ TEST_F(HLSLSemanticSignaturePackingTest,
 TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedRanges) {
   // An element with multiple rows occupies the same columns of a contiguous
   // range of rows, and other elements may be co-packed into the columns those
-  // rows have left. A system value cannot be placed in a dynamically indexable
-  // row, so Position starts a new register.
+  // rows have left. B extends the indexed range of the rows it shares with A.
+  // A system value cannot be placed in a dynamically indexable row, so
+  // Position starts a new register after both arrays.
 
   // struct VSOut {
   //   float2 A[2]    : A;
-  //   float B[2]     : B;
+  //   float B[3]     : B;
   //   float C        : C;
   //   float Position : SV_Position;
   // };
@@ -914,7 +915,7 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedRanges) {
       /*UseNative16BitTypes=*/false,
       {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/2, /*Cols=*/2,
         dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
-       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/2, /*Cols=*/1,
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/3, /*Cols=*/1,
         dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
        {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
         dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
@@ -924,12 +925,13 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedRanges) {
   // Expected layout:
   // reg0: A[0].xy | B[0].z | C.w
   // reg1: A[1].xy | B[1].z | unused.w
-  // reg2: Position.x | unused.yzw
-  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
+  // reg2: unused.xy | B[2].z | unused.w
+  // reg3: Position.x | unused.yzw
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/4,
                 {{/*Row=*/0, /*Col=*/0},
                  {/*Row=*/0, /*Col=*/2},
                  {/*Row=*/0, /*Col=*/3},
-                 {/*Row=*/2, /*Col=*/0}});
+                 {/*Row=*/3, /*Col=*/0}});
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableIndexedAfterSystemValue) {

>From c25a60b3d0aaf890fe5b0592631d06d902c9c773 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:17:41 +0000
Subject: [PATCH 24/34] review: test a scalar tessellation factor after
 arbitrary data

Confirm that float2 data followed by a scalar tessellation factor co-pack into one row, with the factor in column z rather than the reserved w column used for indexed factors.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884869099
---
 .../HLSLSemanticSignaturePackingTest.cpp      | 22 +++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index a53d239fef506..29b448c6e8244 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -1008,6 +1008,28 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableSingleRowTessFactor) {
                 {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}});
 }
 
+TEST_F(HLSLSemanticSignaturePackingTest,
+       PrefixStableSingleRowTessFactorAfterArbitrary) {
+  // A single-row tess factor can follow arbitrary data in the same row.
+  // Unlike an indexed tess factor, it need not occupy the last column.
+
+  // struct PatchConstants {
+  //   float2 Data      : DATA;
+  //   float TessFactor : SV_TessFactor;
+  // };
+  TestConfig Config(
+      Triple::Hull, IOType::PatchConstantOrPrimitive,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined},
+       {dxbc::PSV::SemanticKind::TessFactor, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Undefined}});
+
+  // Expected layout:
+  // reg0: Data.xy | TessFactor.z | unused.w
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/1,
+                {{/*Row=*/0, /*Col=*/0}, {/*Row=*/0, /*Col=*/2}});
+}
+
 TEST_F(HLSLSemanticSignaturePackingTest,
        PrefixStableIndexedTessFactorAfterIndexedElement) {
   // An indexed tess factor may only be placed in rows whose indexed range is

>From a97501214ba979852ee73a95a58db23c05585131 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:17:56 +0000
Subject: [PATCH 25/34] review: identify appended clip/cull test elements in
 HLSL

Add the Extended signature example so Clip1, WithFirst, and AfterClipCull are explicitly identified in declaration order rather than appearing only in the expected layout.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884965387
---
 .../Frontend/HLSLSemanticSignaturePackingTest.cpp         | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 29b448c6e8244..80af94e978d97 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -1295,6 +1295,14 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCullWhenAppended) {
       PackingMethod::PrefixStable, PrefixConfig, /*ExpectedRows=*/3,
       {{/*Row=*/0, /*Col=*/0}, {/*Row=*/1, /*Col=*/0}, {/*Row=*/1, /*Col=*/1}});
 
+  // struct Extended {
+  //   float3 First         : First;
+  //   float  Clip0         : SV_ClipDistance0;
+  //   float2 Cull1[2]      : SV_CullDistance1;
+  //   float  Clip1         : SV_ClipDistance1;
+  //   float  WithFirst     : WithFirst;
+  //   float  AfterClipCull : AfterClipCull;
+  // };
   TestConfig ExtendedConfig = PrefixConfig;
   ExtendedConfig.Elements.push_back(
       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/1,

>From add6806ca0bdebd2aba21b5a45384b335c1f7c23 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:18:23 +0000
Subject: [PATCH 26/34] review: avoid duplicating the complete clip/cull layout
 test

Replace the repeated extended-signature layout assertion with incremental prefix-stability checks. The complete indexed clip/cull layout remains covered by PrefixStableIndexedClipCull; this test now verifies that each appended element preserves all previously assigned locations.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884891452
---
 .../HLSLSemanticSignaturePackingTest.cpp      | 35 ++++++++++++-------
 1 file changed, 23 insertions(+), 12 deletions(-)

diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 80af94e978d97..58dae4a2e3536 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -1314,18 +1314,29 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCullWhenAppended) {
       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear});
 
-  // Expected layout:
-  // reg0: First.xyz       | WithFirst.w
-  // reg1: Clip0.x         | Cull1[0].yz | Clip1.w
-  // reg2: unused.x        | Cull1[1].yz | unused.w
-  // reg3: AfterClipCull.x | unused.yzw
-  verifyPacking(PackingMethod::PrefixStable, ExtendedConfig, /*ExpectedRows=*/4,
-                {{/*Row=*/0, /*Col=*/0},
-                 {/*Row=*/1, /*Col=*/0},
-                 {/*Row=*/1, /*Col=*/1},
-                 {/*Row=*/1, /*Col=*/3},
-                 {/*Row=*/0, /*Col=*/3},
-                 {/*Row=*/3, /*Col=*/0}});
+  // The complete layout is covered by PrefixStableIndexedClipCull. Here,
+  // check that each appended element leaves all earlier locations unchanged.
+  SmallVector<SemanticSignatureElement> PreviousElements =
+      makeSignature(PrefixConfig);
+  ASSERT_THAT_EXPECTED(
+      pack(PackingMethod::PrefixStable, PreviousElements, PrefixConfig),
+      Succeeded());
+  for (unsigned Count = PrefixConfig.Elements.size() + 1;
+       Count <= ExtendedConfig.Elements.size(); ++Count) {
+    SCOPED_TRACE(Count);
+    TestConfig Config = ExtendedConfig;
+    Config.Elements.resize(Count);
+    SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
+    ASSERT_THAT_EXPECTED(pack(PackingMethod::PrefixStable, Elements, Config),
+                         Succeeded());
+    for (unsigned I = 0; I != PreviousElements.size(); ++I) {
+      EXPECT_EQ(Elements[I].StartRow, PreviousElements[I].StartRow)
+          << "element " << I;
+      EXPECT_EQ(Elements[I].StartCol, PreviousElements[I].StartCol)
+          << "element " << I;
+    }
+    PreviousElements = std::move(Elements);
+  }
 }
 
 TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsClipCullOverflow) {

>From 2fb8806608d4db9ef3db98523cac220837ba4339 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:18:48 +0000
Subject: [PATCH 27/34] review: show HLSL signatures for clip/cull packing
 failures

Add source examples for the nine-component overflow and the eight-component signature that cannot be split across the available rows.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884894854
---
 .../Frontend/HLSLSemanticSignaturePackingTest.cpp      | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 58dae4a2e3536..3950a32b62218 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -1343,6 +1343,11 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsClipCullOverflow) {
   // Clip and cull distances may use at most eight components, shared between
   // them, so nine components cannot be packed.
 
+  // struct VSOut {
+  //   float3 Clip0 : SV_ClipDistance0;
+  //   float3 Cull0 : SV_CullDistance0;
+  //   float3 Clip1 : SV_ClipDistance1;
+  // };
   TestConfig Config(
       Triple::EnvironmentType::Vertex, IOType::Out,
       /*UseNative16BitTypes=*/false,
@@ -1368,6 +1373,11 @@ TEST_F(HLSLSemanticSignaturePackingTest,
   // These clip and cull distances fit in eight components, but they cannot be
   // split across the two registers available to them.
 
+  // struct VSOut {
+  //   float3 Clip0 : SV_ClipDistance0;
+  //   float3 Cull0 : SV_CullDistance0;
+  //   float2 Clip1 : SV_ClipDistance1;
+  // };
   TestConfig Config(
       Triple::EnvironmentType::Vertex, IOType::Out,
       /*UseNative16BitTypes=*/false,

>From 09bbe2d5d00ba6d2485644d90718c7843064ac1a Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:19:05 +0000
Subject: [PATCH 28/34] review: clarify left-to-right semantic category
 ordering

Explain that ordering constrains locations within a row, not declaration order, and give the system-value versus arbitrary-value example.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884916248
---
 llvm/docs/DirectX/SemanticSignatures.md | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/llvm/docs/DirectX/SemanticSignatures.md b/llvm/docs/DirectX/SemanticSignatures.md
index c3b4a68ef5879..e0b9bb53670bb 100644
--- a/llvm/docs/DirectX/SemanticSignatures.md
+++ b/llvm/docs/DirectX/SemanticSignatures.md
@@ -190,8 +190,9 @@ constraints are satisfied:
 - When native 16-bit types are enabled, every element in a row must have the
   same component width. Without native 16-bit types, min-precision values
   occupy 32-bit components.
-- Components are ordered from arbitrary values, to system values, to system
-  generated values.
+- Within each row, elements are ordered by category: arbitrary values first,
+  followed by system values, and then system-generated values. For example, a
+  system value can never be packed to the left of an arbitrary value.
 - A system value or system generated value cannot be placed in a dynamically
   indexed row. A dynamically indexed row is a row within the range covered by
   a multi-row element, where the row is selected using a dynamic index.

>From 9021593f942aedf0bff54c447d0e8078fef455db Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:19:20 +0000
Subject: [PATCH 29/34] review: document clip/cull and tessellation factor
 ordering

Include ClipCull and TessFactor in the category ordering and explain the reserved-last-column exception and scalar tessellation factors being treated as system values.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884965373
---
 llvm/docs/DirectX/SemanticSignatures.md | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/llvm/docs/DirectX/SemanticSignatures.md b/llvm/docs/DirectX/SemanticSignatures.md
index e0b9bb53670bb..eb6afabfc682e 100644
--- a/llvm/docs/DirectX/SemanticSignatures.md
+++ b/llvm/docs/DirectX/SemanticSignatures.md
@@ -193,6 +193,8 @@ constraints are satisfied:
 - Within each row, elements are ordered by category: arbitrary values first,
   followed by system values, and then system-generated values. For example, a
   system value can never be packed to the left of an arbitrary value.
+  `ClipCull` and `TessFactor` follow these categories in the internal ordering,
+  with the additional placement rules described below.
 - A system value or system generated value cannot be placed in a dynamically
   indexed row. A dynamically indexed row is a row within the range covered by
   a multi-row element, where the row is selected using a dynamic index.
@@ -204,6 +206,9 @@ Some semantic interpretations require additional handling:
   most two rows. The rows must be adjacent when a clip or cull element spans
   multiple rows.
 - A multi-row tessellation factor is searched for only in the last column.
+  Arbitrary values may fill the columns to its left, even when declared after
+  the factor. A single-row tessellation factor is ordered and packed as a
+  system value instead.
 - Geometry shader output streams are packed independently.
 
 For example:

>From a723748684d5c0bd4c6c09ba1b14d2c06007c335 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:19:32 +0000
Subject: [PATCH 30/34] review: clarify when clip/cull rows need not be
 adjacent

State explicitly that non-indexed clip/cull rows may be separated, as already covered by PrefixStableSeparatesClipCullRows.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884965374
---
 llvm/docs/DirectX/SemanticSignatures.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/docs/DirectX/SemanticSignatures.md b/llvm/docs/DirectX/SemanticSignatures.md
index eb6afabfc682e..5b5427ff2243e 100644
--- a/llvm/docs/DirectX/SemanticSignatures.md
+++ b/llvm/docs/DirectX/SemanticSignatures.md
@@ -204,7 +204,7 @@ Some semantic interpretations require additional handling:
 - `SV_ClipDistance` and `SV_CullDistance` are packed only with each other in
   dedicated rows. Together they may occupy at most eight components across at
   most two rows. The rows must be adjacent when a clip or cull element spans
-  multiple rows.
+  multiple rows. Otherwise, clip and cull rows do not need to be adjacent.
 - A multi-row tessellation factor is searched for only in the last column.
   Arbitrary values may fill the columns to its left, even when declared after
   the factor. A single-row tessellation factor is ordered and packed as a

>From a8d5621a5233348cbf8230089a1be0578f4de77f Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:20:03 +0000
Subject: [PATCH 31/34] review: explain the row category-ordering compatibility
 check

Document both the semantic ordering rejection and the exception that lets arbitrary values fill columns before an indexed tessellation factor.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884965377
---
 llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 153abab1ffca6..3e14deaa42b62 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -159,6 +159,9 @@ static bool canCoPack(const SignatureRow &Row,
   if (Row.InterpMode != dxbc::PSV::InterpolationMode::Undefined &&
       Row.InterpMode != Placement.InterpMode)
     return false;
+  // Do not append an earlier semantic category after a later one in a row.
+  // Indexed tess factors are reserved in the last column, so arbitrary values
+  // may still fill the columns to their left without violating that ordering.
   if (Row.OccupiedColumns &&
       Placement.Interpretation < Row.RightmostInterpretation &&
       !(Placement.Interpretation == SemanticInterpretation::Arbitrary &&

>From 5ba7aaa5cabad38575546d0bf68e84e171b57e4d Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:21:21 +0000
Subject: [PATCH 32/34] review: diagnose blocked adjacent clip/cull row
 reservations

Report ClipCullNotAdjacent when an existing signature element prevents extending a clip/cull reservation into the next row, instead of claiming the entire signature exceeds 32 rows.

Cover the reported Clip/Color/Cull example, its diagnostic and preserved locations, and extension at the last signature row. Keep SignatureOverflow for an extension beyond the register space.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884965378
---
 .../Frontend/HLSL/SemanticSignaturePacking.h  |  1 +
 .../HLSL/SemanticSignaturePacking.cpp         | 10 ++-
 .../HLSLSemanticSignaturePackingTest.cpp      | 67 +++++++++++++++++++
 3 files changed, 75 insertions(+), 3 deletions(-)

diff --git a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
index 55e4eaa514dfe..ac3b7bb6a117c 100644
--- a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
+++ b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
@@ -32,6 +32,7 @@ class LLVM_ABI SignaturePackingError : public ErrorInfo<SignaturePackingError> {
   enum ErrorKind {
     SignatureOverflow,
     ClipCullOverflow,
+    ClipCullNotAdjacent,
   };
 
   static char ID;
diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 3e14deaa42b62..911cf7e1c6ec3 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -316,10 +316,11 @@ reserveClipCullSignatureRows(MutableArrayRef<SignatureRow> SignatureRows,
 
   if (State.RowsUsed == 1) {
     const unsigned StartRow = State.SignatureRows[0] + 1;
-    if (StartRow >= SignatureRows.size() ||
-        !reserveClipCullRows(SignatureRows, StartRow,
-                             getClipCullReservation(Placement, 1)))
+    if (StartRow >= SignatureRows.size())
       return SignaturePackingError::SignatureOverflow;
+    if (!reserveClipCullRows(SignatureRows, StartRow,
+                             getClipCullReservation(Placement, 1)))
+      return SignaturePackingError::ClipCullNotAdjacent;
     State.SignatureRows[1] = StartRow;
     return std::nullopt;
   }
@@ -365,6 +366,9 @@ void SignaturePackingError::log(raw_ostream &OS) const {
   case ClipCullOverflow:
     OS << "clip/cull elements do not fit in " << MaxClipCullRows << " rows";
     break;
+  case ClipCullNotAdjacent:
+    OS << "indexed clip/cull elements require adjacent signature rows";
+    break;
   }
   OS << " (element " << ElementIndex << ")";
 }
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 3950a32b62218..58b94c6c84314 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -1339,6 +1339,73 @@ TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableClipCullWhenAppended) {
   }
 }
 
+TEST_F(HLSLSemanticSignaturePackingTest,
+       PrefixStableRejectsBlockedClipCullExtension) {
+  // The signature has room, but extending Clip's reserved row for the indexed
+  // Cull element would overlap Color. Report adjacency rather than capacity.
+
+  // struct VSOut {
+  //   float Clip    : SV_ClipDistance0;
+  //   float4 Color  : COLOR;
+  //   float Cull[2] : SV_CullDistance0;
+  // };
+  TestConfig Config(
+      Triple::Vertex, IOType::Out,
+      {{dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/4,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/2, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+  verifyPackingError(PackingMethod::PrefixStable, Config,
+                     SignaturePackingError::ClipCullNotAdjacent,
+                     /*ExpectedElementIndex=*/2);
+
+  SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
+  EXPECT_THAT_EXPECTED(
+      pack(PackingMethod::PrefixStable, Elements, Config),
+      FailedWithMessage("indexed clip/cull elements require adjacent signature "
+                        "rows (element 2)"));
+  EXPECT_EQ(Elements[0].StartRow, 0u);
+  EXPECT_EQ(Elements[0].StartCol, 0u);
+  EXPECT_EQ(Elements[1].StartRow, 1u);
+  EXPECT_EQ(Elements[1].StartCol, 0u);
+  EXPECT_EQ(Elements[2].StartRow, UnallocatedRow);
+  EXPECT_EQ(Elements[2].StartCol, UnallocatedCol);
+}
+
+TEST_F(HLSLSemanticSignaturePackingTest,
+       PrefixStableClipCullExtensionAtSignatureBoundary) {
+  // A two-row clip/cull range can end at the last signature row, but cannot
+  // extend beyond it. The latter is still a genuine capacity overflow.
+
+  // struct VSOut {
+  //   float4 Data[30] : DATA;
+  //   float Clip      : SV_ClipDistance0;
+  //   float Cull[2]   : SV_CullDistance0;
+  // };
+  TestConfig Config(
+      Triple::Vertex, IOType::Out,
+      {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/MaxSignatureRows - 2,
+        /*Cols=*/4, dxil::ElementType::F32,
+        dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/2, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear}});
+  verifyPacking(PackingMethod::PrefixStable, Config,
+                /*ExpectedRows=*/MaxSignatureRows,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/MaxSignatureRows - 2, /*Col=*/0},
+                 {/*Row=*/MaxSignatureRows - 2, /*Col=*/1}});
+
+  // Extending Data to 31 rows pushes Clip into the last signature row.
+  ++Config.Elements[0].Rows;
+  verifyPackingError(PackingMethod::PrefixStable, Config,
+                     SignaturePackingError::SignatureOverflow,
+                     /*ExpectedElementIndex=*/2);
+}
+
 TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsClipCullOverflow) {
   // Clip and cull distances may use at most eight components, shared between
   // them, so nine components cannot be packed.

>From 8150832ef18475f90f43b867f72459eafeca7a4d Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:22:10 +0000
Subject: [PATCH 33/34] review: diagnose separated reserved clip/cull rows
 accurately

Use ClipCullNotAdjacent when an indexed element would span two non-consecutive reserved rows rather than claiming the clip/cull components exceed the two-row limit.

Test the reported seven-component example, the exact message and preserved prefix, and a reordered signature proving that those same components fit when the rows are adjacent.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884965383
---
 .../HLSL/SemanticSignaturePacking.cpp         |  2 +-
 .../HLSLSemanticSignaturePackingTest.cpp      | 50 +++++++++++++++++++
 2 files changed, 51 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 911cf7e1c6ec3..39082cc2bba36 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -326,7 +326,7 @@ reserveClipCullSignatureRows(MutableArrayRef<SignatureRow> SignatureRows,
   }
 
   if (State.SignatureRows[0] + 1 != State.SignatureRows[1])
-    return SignaturePackingError::ClipCullOverflow;
+    return SignaturePackingError::ClipCullNotAdjacent;
   return std::nullopt;
 }
 
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 58b94c6c84314..31d569ac0216a 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -1374,6 +1374,56 @@ TEST_F(HLSLSemanticSignaturePackingTest,
   EXPECT_EQ(Elements[2].StartCol, UnallocatedCol);
 }
 
+TEST_F(HLSLSemanticSignaturePackingTest,
+       PrefixStableRejectsNonAdjacentClipCullRows) {
+  // These seven clip/cull components fit in two rows, but Color separates the
+  // reserved rows. Clip1 cannot span them without moving existing elements.
+
+  // struct VSOut {
+  //   float3 Clip0   : SV_ClipDistance0;
+  //   float4 Color   : COLOR;
+  //   float2 Cull0   : SV_CullDistance0;
+  //   float Clip1[2] : SV_ClipDistance1;
+  // };
+  TestConfig Config(
+      Triple::Vertex, IOType::Out,
+      {{dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/1, /*Cols=*/3,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/4,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::CullDistance, /*Rows=*/1, /*Cols=*/2,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+       {dxbc::PSV::SemanticKind::ClipDistance, /*Rows=*/2, /*Cols=*/1,
+        dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear,
+        /*SemanticIndex=*/1}});
+  verifyPackingError(PackingMethod::PrefixStable, Config,
+                     SignaturePackingError::ClipCullNotAdjacent,
+                     /*ExpectedElementIndex=*/3);
+
+  SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
+  EXPECT_THAT_EXPECTED(
+      pack(PackingMethod::PrefixStable, Elements, Config),
+      FailedWithMessage("indexed clip/cull elements require adjacent signature "
+                        "rows (element 3)"));
+  for (unsigned I = 0; I != 3; ++I) {
+    EXPECT_EQ(Elements[I].StartRow, I) << "element " << I;
+    EXPECT_EQ(Elements[I].StartCol, 0u) << "element " << I;
+  }
+  EXPECT_EQ(Elements[3].StartRow, UnallocatedRow);
+  EXPECT_EQ(Elements[3].StartCol, UnallocatedCol);
+
+  // Declaring Color last leaves adjacent clip/cull rows and the same
+  // components fit. This is an adjacency failure, not a clip/cull overflow.
+  ElementConfig Color = Config.Elements[1];
+  Config.Elements.erase(Config.Elements.begin() + 1);
+  Config.Elements.push_back(Color);
+  verifyPacking(PackingMethod::PrefixStable, Config, /*ExpectedRows=*/3,
+                {{/*Row=*/0, /*Col=*/0},
+                 {/*Row=*/1, /*Col=*/0},
+                 {/*Row=*/0, /*Col=*/3},
+                 {/*Row=*/2, /*Col=*/0}});
+}
+
 TEST_F(HLSLSemanticSignaturePackingTest,
        PrefixStableClipCullExtensionAtSignatureBoundary) {
   // A two-row clip/cull range can end at the last signature row, but cannot

>From b3d5088f3cebae0bc7b3bbf7ad4fcc13c91f25f0 Mon Sep 17 00:00:00 2001
From: Finn Plummer <mail at inbelic.dev>
Date: Fri, 18 Sep 2026 17:22:42 +0000
Subject: [PATCH 34/34] review: validate geometry streams before indexing
 packing state

Return InvalidGeometryStream in all build modes for out-of-range geometry output streams or nonzero streams on other signatures. Use the validated GSStream directly instead of the redundant ternary.

Cover the stream-count boundary, a maximal uint32 index, geometry inputs, vertex outputs and pixel inputs, including the diagnostic and partial-allocation behavior. Existing tests cover all four valid output streams.

Review: https://github.com/llvm/llvm-project/pull/218062#discussion_r3884965385
---
 .../Frontend/HLSL/SemanticSignaturePacking.h  |  1 +
 .../HLSL/SemanticSignaturePacking.cpp         | 13 +++--
 .../HLSLSemanticSignaturePackingTest.cpp      | 47 +++++++++++++++++++
 3 files changed, 58 insertions(+), 3 deletions(-)

diff --git a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
index ac3b7bb6a117c..ae18b636c62f8 100644
--- a/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
+++ b/llvm/include/llvm/Frontend/HLSL/SemanticSignaturePacking.h
@@ -33,6 +33,7 @@ class LLVM_ABI SignaturePackingError : public ErrorInfo<SignaturePackingError> {
     SignatureOverflow,
     ClipCullOverflow,
     ClipCullNotAdjacent,
+    InvalidGeometryStream,
   };
 
   static char ID;
diff --git a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
index 39082cc2bba36..b1bbae18655ce 100644
--- a/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
+++ b/llvm/lib/Frontend/HLSL/SemanticSignaturePacking.cpp
@@ -369,6 +369,11 @@ void SignaturePackingError::log(raw_ostream &OS) const {
   case ClipCullNotAdjacent:
     OS << "indexed clip/cull elements require adjacent signature rows";
     break;
+  case InvalidGeometryStream:
+    OS << "signature element has an invalid geometry stream: expected an index "
+          "less than "
+       << MaxGeometryStreams << " for geometry outputs, or zero otherwise";
+    break;
   }
   OS << " (element " << ElementIndex << ")";
 }
@@ -435,8 +440,10 @@ Expected<unsigned> llvm::hlsl::packSignaturePrefixStable(
     assert(Element.Rows > 0 && "signature element must have at least one row");
     assert(Element.Cols > 0 && Element.Cols <= MaxSignatureCols &&
            "signature element must have between 1 and 4 columns");
-    assert(Element.GSStream < StreamCount &&
-           "signature element has an unexpected geometry stream");
+    if (Element.GSStream >= StreamCount)
+      return make_error<SignaturePackingError>(
+          SignaturePackingError::InvalidGeometryStream,
+          static_cast<unsigned>(Index));
 
     SemanticInterpretation Interpretation =
         getInterpretationKind(Element.SemanticKind, ShaderStage, IOTy);
@@ -464,7 +471,7 @@ Expected<unsigned> llvm::hlsl::packSignaturePrefixStable(
                                         ComponentWidth, Element.InterpMode,
                                         PackingInterpretation};
 
-    const unsigned StreamIndex = StreamCount == 1 ? 0 : Element.GSStream;
+    const unsigned StreamIndex = Element.GSStream;
     MutableArrayRef<SignatureRow> StreamRows = Rows[StreamIndex];
 
     if (Interpretation == SemanticInterpretation::ClipCull) {
diff --git a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
index 31d569ac0216a..bd090b4701721 100644
--- a/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
+++ b/llvm/unittests/Frontend/HLSLSemanticSignaturePackingTest.cpp
@@ -1548,6 +1548,53 @@ TEST_F(HLSLSemanticSignaturePackingTest,
 // Prefix-stable geometry stream tests
 //===----------------------------------------------------------------------===//
 
+TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableRejectsInvalidStreams) {
+  // Validate stream indices before indexing packing state, including in
+  // release builds. Only geometry outputs may use a nonzero stream.
+  const struct {
+    Triple::EnvironmentType Stage;
+    IOType IOTy;
+    unsigned InvalidStream;
+  } Signatures[] = {{Triple::Geometry, IOType::Out, MaxGeometryStreams},
+                    {Triple::Geometry, IOType::Out, ~uint32_t{0}},
+                    {Triple::Geometry, IOType::In, 1},
+                    {Triple::Vertex, IOType::Out, 1},
+                    {Triple::Pixel, IOType::In, 1}};
+  for (const auto &Signature : Signatures) {
+    SCOPED_TRACE(static_cast<unsigned>(Signature.Stage));
+    SCOPED_TRACE(static_cast<unsigned>(Signature.IOTy));
+    SCOPED_TRACE(Signature.InvalidStream);
+    TestConfig Config(
+        Signature.Stage, Signature.IOTy,
+        {{dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+          dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear},
+         {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+          dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear,
+          /*SemanticIndex=*/1, Signature.InvalidStream},
+         {dxbc::PSV::SemanticKind::Arbitrary, /*Rows=*/1, /*Cols=*/1,
+          dxil::ElementType::F32, dxbc::PSV::InterpolationMode::Linear,
+          /*SemanticIndex=*/2}});
+    verifyPackingError(PackingMethod::PrefixStable, Config,
+                       SignaturePackingError::InvalidGeometryStream,
+                       /*ExpectedElementIndex=*/1);
+
+    SmallVector<SemanticSignatureElement> Elements = makeSignature(Config);
+    EXPECT_THAT_EXPECTED(
+        pack(PackingMethod::PrefixStable, Elements, Config),
+        FailedWithMessage(
+            "signature element has an invalid geometry stream: expected an "
+            "index less than " +
+            std::to_string(MaxGeometryStreams) +
+            " for geometry outputs, or zero otherwise (element 1)"));
+    EXPECT_EQ(Elements[0].StartRow, 0u);
+    EXPECT_EQ(Elements[0].StartCol, 0u);
+    for (unsigned I = 1; I != Elements.size(); ++I) {
+      EXPECT_EQ(Elements[I].StartRow, UnallocatedRow) << "element " << I;
+      EXPECT_EQ(Elements[I].StartCol, UnallocatedCol) << "element " << I;
+    }
+  }
+}
+
 TEST_F(HLSLSemanticSignaturePackingTest, PrefixStableFullGeometryStreams) {
   TestConfig Config(Triple::Geometry, IOType::Out, {});
   for (unsigned Stream = 0; Stream != MaxGeometryStreams; ++Stream)



More information about the llvm-commits mailing list