1//===- SemanticSignatures.cpp - HLSL Semantic Signature helpers -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file This file implements a library for working with HLSL shader input and
10/// output semantic signatures and their DirectX metadata representation.
11///
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Frontend/HLSL/SemanticSignatures.h"
15#include "llvm/ADT/Enum.h"
16#include "llvm/ADT/STLForwardCompat.h"
17#include "llvm/ADT/bit.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/Metadata.h"
20#include "llvm/IR/Type.h"
21#include "llvm/Support/ErrorHandling.h"
22#include <algorithm>
23#include <cassert>
24
25using namespace llvm;
26using namespace llvm::hlsl;
27using llvm::dxbc::PSV::InterpolationMode;
28
29namespace {
30
31// Inclusive upper bounds of the operand enums
32constexpr uint32_t MaxCompType =
33 static_cast<uint32_t>(dxil::ElementType::LastEntry);
34constexpr uint32_t MaxSemanticKind =
35 static_cast<uint32_t>(dxbc::PSV::SemanticKind::Invalid);
36constexpr uint32_t MaxInterpMode =
37 static_cast<uint32_t>(dxbc::PSV::InterpolationMode::Invalid);
38
39Error makeError(const Twine &Msg) {
40 return createStringError(EC: inconvertibleErrorCode(), S: Msg);
41}
42
43Expected<uint64_t> extractInt(const MDNode *Node, unsigned OpId) {
44 auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD: Node->getOperand(I: OpId));
45 if (!CI)
46 return makeError(Msg: "expected integer operand " + Twine(OpId));
47 return CI->getZExtValue();
48}
49} // namespace
50
51InterpolationModifier
52hlsl::getInterpolationSamplingLocation(InterpolationModifier Modifiers) {
53 return std::max(l: {Modifiers & InterpolationModifier::Center,
54 Modifiers & InterpolationModifier::Centroid,
55 Modifiers & InterpolationModifier::Sample});
56}
57
58dxbc::PSV::InterpolationMode
59hlsl::getInterpolationMode(InterpolationModifier Modifiers) {
60 if (Modifiers == InterpolationModifier::None)
61 return InterpolationMode::Undefined;
62 if (any(Val: Modifiers & InterpolationModifier::NoInterpolation))
63 return Modifiers == InterpolationModifier::NoInterpolation
64 ? InterpolationMode::Constant
65 : InterpolationMode::Invalid;
66
67 bool NoPerspective = any(Val: Modifiers & InterpolationModifier::NoPerspective);
68 switch (getInterpolationSamplingLocation(Modifiers)) {
69 case InterpolationModifier::Sample:
70 return NoPerspective ? InterpolationMode::LinearNoperspectiveSample
71 : InterpolationMode::LinearSample;
72 case InterpolationModifier::Centroid:
73 return NoPerspective ? InterpolationMode::LinearNoperspectiveCentroid
74 : InterpolationMode::LinearCentroid;
75 case InterpolationModifier::Center:
76 case InterpolationModifier::None:
77 return NoPerspective ? InterpolationMode::LinearNoperspective
78 : InterpolationMode::Linear;
79 default:
80 llvm_unreachable("invalid interpolation sampling location");
81 }
82}
83
84dxbc::PSV::InterpolationMode hlsl::normalizeInterpolationMode(
85 dxbc::PSV::InterpolationMode Mode, dxil::ElementType CompType,
86 dxbc::PSV::SemanticKind Kind, Triple::EnvironmentType Stage, IOType IO) {
87 if (!((Stage == Triple::Pixel && IO == IOType::In) ||
88 (Stage == Triple::Vertex && IO == IOType::Out)))
89 return InterpolationMode::Undefined;
90
91 if (Mode == InterpolationMode::Undefined) {
92 switch (CompType) {
93 case dxil::ElementType::F16:
94 case dxil::ElementType::F32:
95 case dxil::ElementType::SNormF16:
96 case dxil::ElementType::UNormF16:
97 case dxil::ElementType::SNormF32:
98 case dxil::ElementType::UNormF32:
99 Mode = InterpolationMode::Linear;
100 break;
101 default:
102 Mode = InterpolationMode::Constant;
103 break;
104 }
105 }
106
107 if (Kind == dxbc::PSV::SemanticKind::Position) {
108 switch (Mode) {
109 case InterpolationMode::Linear:
110 return InterpolationMode::LinearNoperspective;
111 case InterpolationMode::LinearCentroid:
112 return InterpolationMode::LinearNoperspectiveCentroid;
113 case InterpolationMode::LinearSample:
114 return InterpolationMode::LinearNoperspectiveSample;
115 default:
116 break;
117 }
118 }
119 return Mode;
120}
121
122dxbc::PSV::SemanticKind hlsl::getSemanticKind(StringRef SemanticName) {
123 if (!SemanticName.consume_front_insensitive(Prefix: "SV_"))
124 return dxbc::PSV::SemanticKind::Arbitrary;
125
126 for (const auto &Kind : dxbc::PSV::getSemanticKinds())
127 if (SemanticName.equals_insensitive(RHS: Kind.name()))
128 return Kind.value();
129
130 return dxbc::PSV::SemanticKind::Invalid;
131}
132
133ArrayRef<SemanticStageInfo>
134hlsl::getAvailableStages(dxbc::PSV::SemanticKind SemanticKind) {
135 switch (SemanticKind) {
136 case dxbc::PSV::SemanticKind::Arbitrary: {
137 static constexpr IOType OutOrPatchConstant =
138 IOType::Out | IOType::PatchConstantOrPrimitive;
139 static constexpr SemanticStageInfo Stages[] = {
140 {.Stage: Triple::Vertex, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::Arbitrary},
141 {.Stage: Triple::Geometry, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::Arbitrary},
142 {.Stage: Triple::Hull, .AllowedIOTypesMask: IOType::All, .Interpretation: SemanticInterpretation::Arbitrary},
143 {.Stage: Triple::Domain, .AllowedIOTypesMask: IOType::All, .Interpretation: SemanticInterpretation::Arbitrary},
144 {.Stage: Triple::Pixel, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::Arbitrary},
145 {.Stage: Triple::Mesh, .AllowedIOTypesMask: OutOrPatchConstant, .Interpretation: SemanticInterpretation::Arbitrary},
146 };
147 return Stages;
148 }
149 case dxbc::PSV::SemanticKind::DispatchThreadID:
150 case dxbc::PSV::SemanticKind::GroupID:
151 case dxbc::PSV::SemanticKind::GroupIndex:
152 case dxbc::PSV::SemanticKind::GroupThreadID: {
153 static constexpr SemanticStageInfo Stages[] = {
154 {.Stage: Triple::Compute, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::NotAllocated},
155 {.Stage: Triple::Mesh, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::NotAllocated},
156 {.Stage: Triple::Amplification, .AllowedIOTypesMask: IOType::In,
157 .Interpretation: SemanticInterpretation::NotAllocated},
158 };
159 return Stages;
160 }
161 case dxbc::PSV::SemanticKind::ViewID: {
162 static constexpr IOType InOrPatchConstant =
163 IOType::In | IOType::PatchConstantOrPrimitive;
164 static constexpr SemanticStageInfo Stages[] = {
165 {.Stage: Triple::Vertex, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::NotAllocated},
166 {.Stage: Triple::Hull, .AllowedIOTypesMask: InOrPatchConstant, .Interpretation: SemanticInterpretation::NotAllocated},
167 {.Stage: Triple::Domain, .AllowedIOTypesMask: InOrPatchConstant,
168 .Interpretation: SemanticInterpretation::NotAllocated},
169 {.Stage: Triple::Geometry, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::NotAllocated},
170 {.Stage: Triple::Pixel, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::NotAllocated},
171 {.Stage: Triple::Mesh, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::NotAllocated},
172 };
173 return Stages;
174 }
175 case dxbc::PSV::SemanticKind::StartVertexLocation:
176 case dxbc::PSV::SemanticKind::StartInstanceLocation: {
177 static constexpr SemanticStageInfo Stages[] = {
178 {.Stage: Triple::Vertex, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::NotAllocated}};
179 return Stages;
180 }
181 case dxbc::PSV::SemanticKind::SampleIndex: {
182 static constexpr SemanticStageInfo Stages[] = {
183 {.Stage: Triple::Pixel, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::NotPacked}};
184 return Stages;
185 }
186 case dxbc::PSV::SemanticKind::Barycentrics: {
187 static constexpr SemanticStageInfo Stages[] = {
188 {.Stage: Triple::Pixel, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::NotPacked}};
189 return Stages;
190 }
191 case dxbc::PSV::SemanticKind::Target: {
192 static constexpr SemanticStageInfo Stages[] = {
193 {.Stage: Triple::Pixel, .AllowedIOTypesMask: IOType::Out, .Interpretation: SemanticInterpretation::Target}};
194 return Stages;
195 }
196 case dxbc::PSV::SemanticKind::VertexID:
197 case dxbc::PSV::SemanticKind::InstanceID: {
198 static constexpr SemanticStageInfo Stages[] = {
199 {.Stage: Triple::Vertex, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::SV}};
200 return Stages;
201 }
202 case dxbc::PSV::SemanticKind::PrimitiveID: {
203 static constexpr SemanticStageInfo Stages[] = {
204 {.Stage: Triple::Pixel, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::SGV}};
205 return Stages;
206 }
207 case dxbc::PSV::SemanticKind::IsFrontFace: {
208 static constexpr SemanticStageInfo Stages[] = {
209 {.Stage: Triple::Geometry, .AllowedIOTypesMask: IOType::Out, .Interpretation: SemanticInterpretation::SGV},
210 {.Stage: Triple::Pixel, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::SGV}};
211 return Stages;
212 }
213 case dxbc::PSV::SemanticKind::ShadingRate: {
214 static constexpr SemanticStageInfo Stages[] = {
215 {.Stage: Triple::Vertex, .AllowedIOTypesMask: IOType::Out, .Interpretation: SemanticInterpretation::SV},
216 {.Stage: Triple::Hull, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::SV},
217 {.Stage: Triple::Domain, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::SV},
218 {.Stage: Triple::Geometry, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::SV},
219 {.Stage: Triple::Pixel, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::SV},
220 {.Stage: Triple::Mesh, .AllowedIOTypesMask: IOType::PatchConstantOrPrimitive,
221 .Interpretation: SemanticInterpretation::SV}};
222 return Stages;
223 }
224 case dxbc::PSV::SemanticKind::Position: {
225 static constexpr SemanticStageInfo Stages[] = {
226 {.Stage: Triple::Vertex, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::Arbitrary},
227 {.Stage: Triple::Vertex, .AllowedIOTypesMask: IOType::Out, .Interpretation: SemanticInterpretation::SV},
228 {.Stage: Triple::Hull, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::SV},
229 {.Stage: Triple::Hull, .AllowedIOTypesMask: IOType::PatchConstantOrPrimitive,
230 .Interpretation: SemanticInterpretation::Arbitrary},
231 {.Stage: Triple::Domain, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::SV},
232 {.Stage: Triple::Domain, .AllowedIOTypesMask: IOType::PatchConstantOrPrimitive,
233 .Interpretation: SemanticInterpretation::Arbitrary},
234 {.Stage: Triple::Geometry, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::SV},
235 {.Stage: Triple::Pixel, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::SV},
236 {.Stage: Triple::Mesh, .AllowedIOTypesMask: IOType::Out, .Interpretation: SemanticInterpretation::SV},
237 };
238 return Stages;
239 }
240 case dxbc::PSV::SemanticKind::ClipDistance:
241 case dxbc::PSV::SemanticKind::CullDistance: {
242 static constexpr SemanticStageInfo Stages[] = {
243 {.Stage: Triple::Vertex, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::Arbitrary},
244 {.Stage: Triple::Vertex, .AllowedIOTypesMask: IOType::Out, .Interpretation: SemanticInterpretation::ClipCull},
245 {.Stage: Triple::Hull, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::ClipCull},
246 {.Stage: Triple::Hull, .AllowedIOTypesMask: IOType::PatchConstantOrPrimitive,
247 .Interpretation: SemanticInterpretation::Arbitrary},
248 {.Stage: Triple::Domain, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::ClipCull},
249 {.Stage: Triple::Domain, .AllowedIOTypesMask: IOType::PatchConstantOrPrimitive,
250 .Interpretation: SemanticInterpretation::Arbitrary},
251 {.Stage: Triple::Geometry, .AllowedIOTypesMask: IOType::InOut, .Interpretation: SemanticInterpretation::ClipCull},
252 {.Stage: Triple::Pixel, .AllowedIOTypesMask: IOType::In, .Interpretation: SemanticInterpretation::ClipCull},
253 {.Stage: Triple::Mesh, .AllowedIOTypesMask: IOType::Out, .Interpretation: SemanticInterpretation::ClipCull},
254 };
255 return Stages;
256 }
257 case dxbc::PSV::SemanticKind::TessFactor:
258 case dxbc::PSV::SemanticKind::InsideTessFactor: {
259 static constexpr SemanticStageInfo Stages[] = {
260 {.Stage: Triple::Hull, .AllowedIOTypesMask: IOType::PatchConstantOrPrimitive,
261 .Interpretation: SemanticInterpretation::TessFactor},
262 {.Stage: Triple::Domain, .AllowedIOTypesMask: IOType::PatchConstantOrPrimitive,
263 .Interpretation: SemanticInterpretation::TessFactor},
264 };
265 return Stages;
266 }
267 default:
268 return {};
269 }
270}
271
272SemanticInterpretation
273hlsl::getInterpretationKind(dxbc::PSV::SemanticKind SemanticKind,
274 Triple::EnvironmentType ShaderStage, IOType IOTy) {
275 assert(llvm::has_single_bit(static_cast<unsigned>(IOTy)) &&
276 "a single IOType is expected, not a mask of IOTypes");
277 for (const SemanticStageInfo &Info : getAvailableStages(SemanticKind))
278 if (Info.Stage == ShaderStage && any(Val: Info.AllowedIOTypesMask & IOTy))
279 return Info.Interpretation;
280 return SemanticInterpretation::Invalid;
281}
282
283Expected<SemanticSignatureElement>
284SemanticSignatureElement::fromMetadata(const MDNode *Node) {
285 // Operand positions within a signature element metadata node.
286 enum class OpIdx : unsigned {
287 SigId,
288 SemanticName,
289 CompType,
290 SemanticKind,
291 SemanticIndices,
292 InterpMode,
293 Rows,
294 Cols,
295 StartRow,
296 StartCol,
297 UsageMask,
298 DynIndexMask,
299 GSStream,
300 LastEntry = GSStream,
301 };
302 const unsigned NumElementOperands = to_underlying(E: OpIdx::LastEntry) + 1;
303
304 if (!Node)
305 return makeError(Msg: "signature element node is null");
306 if (Node->getNumOperands() != NumElementOperands)
307 return makeError(Msg: "signature element node has wrong number of operands");
308
309 SemanticSignatureElement Elem;
310
311 Expected<uint64_t> SigId = extractInt(Node, OpId: to_underlying(E: OpIdx::SigId));
312 if (!SigId)
313 return SigId.takeError();
314 Elem.SigId = *SigId;
315
316 auto *Name =
317 dyn_cast<MDString>(Val: Node->getOperand(I: to_underlying(E: OpIdx::SemanticName)));
318 if (!Name)
319 return makeError(Msg: "expected semantic name string");
320 Elem.SemanticName = Name->getString();
321
322 Expected<uint64_t> CompType =
323 extractInt(Node, OpId: to_underlying(E: OpIdx::CompType));
324 if (!CompType)
325 return CompType.takeError();
326 if (*CompType > MaxCompType)
327 return makeError(Msg: "invalid component type");
328 Elem.CompType = static_cast<dxil::ElementType>(*CompType);
329
330 Expected<uint64_t> SemanticKind =
331 extractInt(Node, OpId: to_underlying(E: OpIdx::SemanticKind));
332 if (!SemanticKind)
333 return SemanticKind.takeError();
334 if (*SemanticKind > MaxSemanticKind)
335 return makeError(Msg: "invalid semantic kind");
336 Elem.SemanticKind = static_cast<dxbc::PSV::SemanticKind>(*SemanticKind);
337
338 auto *Indices =
339 dyn_cast<MDNode>(Val: Node->getOperand(I: to_underlying(E: OpIdx::SemanticIndices)));
340 if (!Indices)
341 return makeError(Msg: "expected semantic indices node");
342 for (unsigned I = 0, E = Indices->getNumOperands(); I != E; ++I) {
343 Expected<uint64_t> Index = extractInt(Node: Indices, OpId: I);
344 if (!Index)
345 return Index.takeError();
346 Elem.SemanticIndices.push_back(Elt: *Index);
347 }
348
349 Expected<uint64_t> InterpMode =
350 extractInt(Node, OpId: to_underlying(E: OpIdx::InterpMode));
351 if (!InterpMode)
352 return InterpMode.takeError();
353 if (*InterpMode > MaxInterpMode)
354 return makeError(Msg: "invalid interpolation mode");
355 Elem.InterpMode = static_cast<dxbc::PSV::InterpolationMode>(*InterpMode);
356
357 Expected<uint64_t> Rows = extractInt(Node, OpId: to_underlying(E: OpIdx::Rows));
358 if (!Rows)
359 return Rows.takeError();
360 Elem.Rows = *Rows;
361
362 Expected<uint64_t> Cols = extractInt(Node, OpId: to_underlying(E: OpIdx::Cols));
363 if (!Cols)
364 return Cols.takeError();
365 if (*Cols < 1 || *Cols > 4)
366 return makeError(Msg: "number of components per row must be within 1-4");
367 Elem.Cols = *Cols;
368
369 Expected<uint64_t> StartRow =
370 extractInt(Node, OpId: to_underlying(E: OpIdx::StartRow));
371 if (!StartRow)
372 return StartRow.takeError();
373 Elem.StartRow = *StartRow;
374
375 Expected<uint64_t> StartCol =
376 extractInt(Node, OpId: to_underlying(E: OpIdx::StartCol));
377 if (!StartCol)
378 return StartCol.takeError();
379 if (*StartCol > 3 && *StartCol != UnallocatedCol)
380 return makeError(Msg: "start column must be within 0-3 or unallocated");
381 Elem.StartCol = *StartCol;
382
383 // The row/col sentinels are always set together
384 if ((Elem.StartRow == UnallocatedRow) != (Elem.StartCol == UnallocatedCol))
385 return makeError(Msg: "start row and column sentinels must be set together");
386
387 Expected<uint64_t> UsageMask =
388 extractInt(Node, OpId: to_underlying(E: OpIdx::UsageMask));
389 if (!UsageMask)
390 return UsageMask.takeError();
391 if (*UsageMask > 0xF)
392 return makeError(Msg: "usage mask must be a 4-bit value");
393 Elem.UsageMask = *UsageMask;
394
395 Expected<uint64_t> DynIndexMask =
396 extractInt(Node, OpId: to_underlying(E: OpIdx::DynIndexMask));
397 if (!DynIndexMask)
398 return DynIndexMask.takeError();
399 if (*DynIndexMask > 0xF)
400 return makeError(Msg: "dynamic index mask must be a 4-bit value");
401 Elem.DynIndexMask = *DynIndexMask;
402
403 Expected<uint64_t> GSStream =
404 extractInt(Node, OpId: to_underlying(E: OpIdx::GSStream));
405 if (!GSStream)
406 return GSStream.takeError();
407 if (*GSStream > 3)
408 return makeError(Msg: "geometry shader stream index must be within 0-3");
409 Elem.GSStream = *GSStream;
410
411 if (Elem.SemanticIndices.size() != Elem.Rows)
412 return makeError(
413 Msg: "number of semantic indices must equal the number of rows");
414
415 return Elem;
416}
417
418MDNode *SemanticSignatureElement::toMetadata(LLVMContext &Ctx) const {
419 Type *I32Ty = Type::getInt32Ty(C&: Ctx);
420 Type *I8Ty = Type::getInt8Ty(C&: Ctx);
421 auto GetI32 = [&](uint32_t Val) -> Metadata * {
422 return ConstantAsMetadata::get(C: ConstantInt::get(Ty: I32Ty, V: Val));
423 };
424 auto GetI8 = [&](uint8_t Val) -> Metadata * {
425 return ConstantAsMetadata::get(C: ConstantInt::get(Ty: I8Ty, V: Val));
426 };
427
428 SmallVector<Metadata *> IndexOps;
429 for (uint32_t Index : SemanticIndices)
430 IndexOps.push_back(Elt: GetI32(Index));
431
432 return MDNode::get(Context&: Ctx,
433 MDs: {GetI32(SigId), MDString::get(Context&: Ctx, Str: SemanticName),
434 GetI32(static_cast<uint32_t>(CompType)),
435 GetI32(static_cast<uint32_t>(SemanticKind)),
436 MDNode::get(Context&: Ctx, MDs: IndexOps),
437 GetI32(static_cast<uint32_t>(InterpMode)), GetI32(Rows),
438 GetI8(Cols), GetI32(StartRow), GetI8(StartCol),
439 GetI8(UsageMask), GetI8(DynIndexMask), GetI32(GSStream)});
440}
441