[clang] [llvm] [HLSL] Adding HLSL `clip` function. (PR #114588)

via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 4 13:21:21 PST 2024


================
@@ -99,6 +99,42 @@ static void initializeAlloca(CodeGenFunction &CGF, AllocaInst *AI, Value *Size,
   I->addAnnotationMetadata("auto-init");
 }
 
+static Value *handleHlslClip(const CallExpr *E, CodeGenFunction *CGF) {
+  Value *Op0 = CGF->EmitScalarExpr(E->getArg(0));
+
+  Constant *FZeroConst = ConstantFP::getZero(CGF->FloatTy);
+  Value *CMP;
+
+  if (const auto *VecTy = E->getArg(0)->getType()->getAs<clang::VectorType>()) {
+    FZeroConst = ConstantVector::getSplat(
+        ElementCount::getFixed(VecTy->getNumElements()), FZeroConst);
+    auto *FCompInst = CGF->Builder.CreateFCmpOLT(Op0, FZeroConst);
+    CMP = CGF->Builder.CreateIntrinsic(
+        CGF->Builder.getInt1Ty(), CGF->CGM.getHLSLRuntime().getAnyIntrinsic(),
+        {FCompInst}, nullptr);
+  } else
+    CMP = CGF->Builder.CreateFCmpOLT(Op0, FZeroConst);
+
+  if (CGF->CGM.getTarget().getTriple().isDXIL())
+    return CGF->Builder.CreateIntrinsic(CGF->VoidTy, llvm::Intrinsic::dx_clip,
----------------
joaosaffran wrote:

Here is an example of the current generated IR:
```
define void @test_vector(<4 x float> noundef %Buf) {
entry:
  %Buf.addr = alloca <4 x float>, align 16
  store <4 x float> %Buf, ptr %Buf.addr, align 16
  %1 = load <4 x float>, ptr %Buf.addr, align 16
  %2 = fcmp olt <4 x float> %1, zeroinitializer
  %3 = call i1 @llvm.spv.any.v4i1(<4 x i1> %2)
  br i1 %3, label %lt0, label %end

lt0:                                              ; preds = %entry
  call void @llvm.spv.clip()
  br label %end

end:                                              ; preds = %lt0, %entry
  ret void
}
```

The challenge, I see, with invoke `selectAny` when handling `selectClip` is that we need to call `any` before calling the conditional branch. In order to call `selectAny` in `llvm/lib/Target/SPIRV/SPIRVInstructionSelector.cpp` that would also require creating the branch call when selecting the spirv instruction. That doesn't seem to be the proper place to generate the branching code. Please, let me know if I am missing something here.

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


More information about the cfe-commits mailing list