[clang] [CIR] Implement HLSL Matrix Truncation to Matrix dest (PR #242703)

Amr Hesham via cfe-commits cfe-commits at lists.llvm.org
Sat Nov 14 13:12:07 PST 2026


https://github.com/AmrDeveloper created https://github.com/llvm/llvm-project/pull/242703

Implement support for HLSL Matrix Truncation to Matrix dest

>From 62ad82226908f043f01cf48ad7db5cec822a2f8a Mon Sep 17 00:00:00 2001
From: Amr Hesham <amr96 at programmer.net>
Date: Sat, 14 Nov 2026 20:01:05 +0100
Subject: [PATCH] [CIR] Implement HLSL Matrix Truncation to Matrix dest

---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |  9 +++---
 .../CIR/Dialect/IR/CIRTypeConstraints.td      |  6 ++++
 clang/lib/CIR/CodeGen/CIRGenBuilder.h         | 13 ++++++++
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp          |  6 ----
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp    | 31 +++++++++++++++++++
 clang/lib/CIR/Dialect/IR/CIRDialect.cpp       | 25 +++++++++------
 .../CIR/CodeGenHLSL/matrixx-truncation.hlsl   | 24 ++++++++++++++
 7 files changed, 93 insertions(+), 21 deletions(-)
 create mode 100644 clang/test/CIR/CodeGenHLSL/matrixx-truncation.hlsl

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 82e3095e527b13..c11b444e85057c 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -6841,12 +6841,12 @@ def CIR_VecShuffleOp : CIR_Op<"vec.shuffle", [
   }];
 
   let arguments = (ins
-    CIR_VectorType:$vec1,
-    CIR_VectorType:$vec2,
+    CIR_AnyVectorOrMatrixType:$vec1,
+    CIR_AnyVectorOrMatrixType:$vec2,
     CIR_IntArrayAttr:$indices
   );
 
-  let results = (outs CIR_VectorType:$result);
+  let results = (outs CIR_AnyVectorOrMatrixType:$result);
   let assemblyFormat = [{
     `(` $vec1 `,` $vec2 `:` qualified(type($vec1)) `)` $indices `:`
      qualified(type($result)) attr-dict
@@ -6962,8 +6962,7 @@ def CIR_VecSplatOp : CIR_Op<"vec.splat", [
   }];
 
   let arguments = (ins CIR_VectorElementType:$value);
-  let results = (outs AnyTypeOf<[CIR_VectorType, CIR_MatrixType],
-                                "vector or matrix type">:$result);
+  let results = (outs CIR_AnyVectorOrMatrixType:$result);
 
   let assemblyFormat = [{
     $value `:` type($value) `,` qualified(type($result)) attr-dict
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRTypeConstraints.td b/clang/include/clang/CIR/Dialect/IR/CIRTypeConstraints.td
index cfa498f87df9c4..c2b0f0d864ff88 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRTypeConstraints.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRTypeConstraints.td
@@ -441,6 +441,12 @@ def CIR_AnyIntOrVecOrMatrixOfIntType
     let cppFunctionName = "isIntOrVectorOrMatrixOfIntType";
 }
 
+def CIR_AnyVectorOrMatrixType
+    : AnyTypeOf<[CIR_AnyVectorType, CIR_AnyMatrixType],
+        "vector or matrix type"> {
+    let cppFunctionName = "isVectorOrMatrixType";
+}
+
 def CIR_AnyFloatOrVecOrMatrixOfFloatType
     : AnyTypeOf<[CIR_AnyFloatType, CIR_VectorOfFloatType,
                  CIR_MatrixOfFloatType],
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuilder.h b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
index 3f96bc927b6245..114c2956d022e0 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuilder.h
+++ b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
@@ -812,6 +812,19 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
                                      getArrayAttr(maskAttrs));
   }
 
+  cir::VecShuffleOp createVecShuffle(mlir::Location loc, mlir::Value vec1,
+                                     mlir::Type resultTy,
+                                     llvm::ArrayRef<int64_t> mask) {
+    cir::ConstantOp poison =
+        getConstant(loc, cir::PoisonAttr::get(vec1.getType()));
+    auto maskAttrs = llvm::to_vector_of<mlir::Attribute>(
+        llvm::map_range(mask, [&](int32_t idx) {
+          return cir::IntAttr::get(getSInt32Ty(), idx);
+        }));
+    return cir::VecShuffleOp::create(*this, loc, resultTy, vec1, poison,
+                                     getArrayAttr(maskAttrs));
+  }
+
   cir::VecShuffleOp createVecShuffle(mlir::Location loc, mlir::Value vec1,
                                      mlir::Value vec2,
                                      llvm::ArrayRef<int64_t> mask) {
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 76273e1f95e1f1..5750233d796a03 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -3095,12 +3095,6 @@ Address CIRGenFunction::createMemTemp(QualType ty, CharUnits align,
   Address result =
       createTempAlloca(convertTypeForMem(ty), /*destAddrSpace=*/{}, align, loc,
                        name, /*arraySize=*/nullptr, alloca, ip);
-  if (ty->isConstantMatrixType()) {
-    assert(!cir::MissingFeatures::matrixType());
-    cgm.errorNYI(loc, "createMemTemp constant matrix type");
-    return Address::invalid();
-  }
-
   return result;
 }
 
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index ee885fe1574f14..890afbbaa8cadc 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -2975,7 +2975,38 @@ mlir::Value ScalarExprEmitter::VisitCastExpr(CastExpr *ce) {
     }
     return builder.createExtractElement(loc, vec, /*idx=*/0);
   }
+  case CK_HLSLMatrixTruncation: {
+    assert((destTy->isMatrixType() || destTy->isBuiltinType()) &&
+           "Destination type must be a matrix or builtin type.");
+    mlir::Value matrix = Visit(subExpr);
+    mlir::Location loc = cgf.getLoc(subExpr->getSourceRange());
+    if (const auto *matTy = destTy->getAs<ConstantMatrixType>()) {
+      llvm::SmallVector<int64_t> mask(matTy->getNumElementsFlattened());
+      unsigned numCols = matTy->getNumColumns();
+      unsigned numRows = matTy->getNumRows();
+
+      auto *srcMatTy = subExpr->getType()->getAs<ConstantMatrixType>();
+      assert(srcMatTy && "Source type must be a matrix type.");
+      assert(numRows <= srcMatTy->getNumRows());
+      assert(numCols <= srcMatTy->getNumColumns());
+
+      for (unsigned row = 0; row < numRows; row++)
+        for (unsigned column = 0; column < numCols; column++)
+          mask[matTy->getColumnMajorFlattenedIndex(row, column)] =
+              srcMatTy->getColumnMajorFlattenedIndex(row, column);
+
+      auto elementTy =
+          mlir::cast<cir::MatrixType>(matrix.getType()).getElementType();
+      auto resultTy = cir::MatrixType::get(builder.getContext(), elementTy,
+                                           numRows, numCols);
+      return builder.createVecShuffle(loc, matrix, resultTy, mask);
+    }
 
+    cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
+                                   "ScalarExprEmitter::VisitCastExpr: HLSL "
+                                   "Matrix truncation with non-matrix dest");
+    return {};
+  }
   default:
     cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
                                    "CastExpr: ", ce->getCastKindName());
diff --git a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
index 10a61434a4a30d..3d89f0b2700102 100644
--- a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
@@ -4666,31 +4666,36 @@ OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
   }
 
   return cir::ConstVectorAttr::get(
-      getType(), mlir::ArrayAttr::get(getContext(), elements));
+      mlir::cast<cir::VectorType>(getType()),
+      mlir::ArrayAttr::get(getContext(), elements));
 }
 
 LogicalResult cir::VecShuffleOp::verify() {
-  if (getVec1().getType().isScalable() || getVec2().getType().isScalable() ||
-      getResult().getType().isScalable())
+  if (!mlir::isa<cir::VectorType>(getType()))
+    return success();
+
+  auto vec1Ty = mlir::cast<cir::VectorType>(getVec1().getType());
+  auto vec2Ty = mlir::cast<cir::VectorType>(getVec2().getType());
+  auto resultTy = mlir::cast<cir::VectorType>(getResult().getType());
+  if (vec1Ty.isScalable() || vec2Ty.isScalable() || resultTy.isScalable())
     return emitOpError() << "scalable vectors are not supported";
 
   // The number of elements in the indices array must match the number of
   // elements in the result type.
-  if (getIndices().size() != getResult().getType().getFixedSize()) {
+  if (getIndices().size() != resultTy.getFixedSize()) {
     return emitOpError() << ": the number of elements in " << getIndices()
-                         << " and " << getResult().getType() << " don't match";
+                         << " and " << resultTy << " don't match";
   }
 
   // The element types of the two input vectors and of the result type must
   // match.
-  if (getVec1().getType().getElementType() !=
-      getResult().getType().getElementType()) {
+  if (vec1Ty.getElementType() != resultTy.getElementType()) {
     return emitOpError() << ": element types of " << getVec1().getType()
-                         << " and " << getResult().getType() << " don't match";
+                         << " and " << resultTy << " don't match";
   }
 
-  const uint64_t maxValidIndex = getVec1().getType().getFixedSize() +
-                                 getVec2().getType().getFixedSize() - 1;
+  const uint64_t maxValidIndex =
+      vec1Ty.getFixedSize() + vec2Ty.getFixedSize() - 1;
   if (llvm::any_of(
           getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
             return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
diff --git a/clang/test/CIR/CodeGenHLSL/matrixx-truncation.hlsl b/clang/test/CIR/CodeGenHLSL/matrixx-truncation.hlsl
new file mode 100644
index 00000000000000..10cef611a3f968
--- /dev/null
+++ b/clang/test/CIR/CodeGenHLSL/matrixx-truncation.hlsl
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 -x hlsl -std=hlsl2021 -triple spirv-unknown-vulkan-library -finclude-default-header -fclangir -emit-cir %s -o %t.cir
+// RUN: FileCheck --input-file=%t.cir %s -check-prefix=CIR
+// RUN: %clang_cc1 -x hlsl -std=hlsl2021 -triple spirv-unknown-vulkan-library -finclude-default-header -fclangir -emit-llvm %s -o %t-cir.ll
+// RUN: FileCheck --input-file=%t-cir.ll %s -check-prefix=LLVM
+// RUN: %clang_cc1 -x hlsl -std=hlsl2021 -triple spirv-unknown-vulkan-library -finclude-default-header -emit-llvm -disable-llvm-passes %s -o %t.ll
+// RUN: FileCheck --input-file=%t.ll %s -check-prefix=LLVM
+
+void trunc_cast() {
+  int4x4 a;
+  int3x4 b = (int3x4) a;
+}
+
+// CIR: %[[A_ADDR:.*]] = cir.alloca "a" {{.*}} : !cir.ptr<!cir.matrix<4 x 4 x !s32i>>
+// CIR: %[[B_ADDR:.*]] = cir.alloca "b" {{.*}} init : !cir.ptr<!cir.matrix<3 x 4 x !s32i>>
+// CIR: %[[TMP_A:.*]] = cir.load {{.*}} %[[A_ADDR]] : !cir.ptr<!cir.matrix<4 x 4 x !s32i>>, !cir.matrix<4 x 4 x !s32i>
+// CIR: %[[POISON:.*]] = cir.const #cir.poison : !cir.matrix<4 x 4 x !s32i>
+// CIR: %[[RESULT:.*]] = cir.vec.shuffle(%[[TMP_A]], %[[POISON]] : !cir.matrix<4 x 4 x !s32i>) [#cir.int<0> : !s32i, #cir.int<1> : !s32i, #cir.int<2> : !s32i, #cir.int<4> : !s32i, #cir.int<5> : !s32i, #cir.int<6> : !s32i, #cir.int<8> : !s32i, #cir.int<9> : !s32i, #cir.int<10> : !s32i, #cir.int<12> : !s32i, #cir.int<13> : !s32i, #cir.int<14> : !s32i] : !cir.matrix<3 x 4 x !s32i> loc(#loc6)
+// CIR: cir.store {{.*}} %[[RESULT]], %[[B_ADDR]] : !cir.matrix<3 x 4 x !s32i>, !cir.ptr<!cir.matrix<3 x 4 x !s32i>>
+
+// LLVM: %[[A_ADDR:.*]] = alloca [4 x <4 x i32>], align 4
+// LLVM: %[[B_ADDR:.*]] = alloca [4 x <3 x i32>], align 4
+// LLVM: %[[TMP_A:.*]] = load <16 x i32>, ptr %[[A_ADDR]], align 4
+// LLVM: %[[RESULT:.*]] = shufflevector <16 x i32> %[[TMP_A]], <16 x i32> poison, <12 x i32> <i32 0, i32 1, i32 2, i32 4, i32 5, i32 6, i32 8, i32 9, i32 10, i32 12, i32 13, i32 14>
+// LLVM: store <12 x i32> %[[RESULT]], ptr %[[B_ADDR]], align 4



More information about the cfe-commits mailing list