LLVM 24.0.0git
DXILSignatureAnalysis.cpp
Go to the documentation of this file.
1//===- DXILSignatureAnalysis.cpp - Semantic signatures --------------------===//
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
10#include "DirectX.h"
11#include "llvm/ADT/STLExtras.h"
15#include "llvm/IR/Constants.h"
18#include "llvm/IR/IntrinsicsDirectX.h"
19#include "llvm/IR/Module.h"
22#include "llvm/Support/Error.h"
24#include <array>
25#include <set>
26
27using namespace llvm;
28using namespace llvm::dxil;
29using namespace llvm::hlsl;
30
31static Error signatureError(const Twine &Message) {
33}
34
35static bool isSignatureAccess(const IntrinsicInst &I) {
36 return I.getIntrinsicID() == Intrinsic::dx_load_input ||
37 I.getIntrinsicID() == Intrinsic::dx_store_output;
38}
39
40// Validate widths before fromMetadata extracts integer values or narrows them.
42 if (!Node || Node->getNumOperands() != 13)
43 return signatureError("expected a 13-operand signature element");
44 for (unsigned I = 0; I != 13; ++I) {
45 if (I == 1 || I == 4)
46 continue;
47 auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(Node->getOperand(I));
48 unsigned Width = (I == 7 || (I >= 9 && I <= 11)) ? 8 : 32;
49 if (!CI || CI->getBitWidth() != Width)
50 return signatureError("expected i" + Twine(Width) + " at operand " +
51 Twine(I));
52 }
53 if (!isa_and_nonnull<MDString>(Node->getOperand(1)))
54 return signatureError("expected semantic name string");
55 auto *Indices = dyn_cast_or_null<MDNode>(Node->getOperand(4));
56 if (!Indices)
57 return signatureError("expected semantic indices node");
58 for (const MDOperand &Index : Indices->operands()) {
60 if (!CI || CI->getBitWidth() != 32)
61 return signatureError("expected i32 semantic index");
62 }
63 return Error::success();
64}
65
71
73 switch (E.SemanticKind) {
74 case dxbc::PSV::SemanticKind::Target:
75 if (E.CompType != ElementType::F16 && E.CompType != ElementType::F32)
76 return signatureError(
77 "SV_Target requires 16- or 32-bit floating-point components");
78 break;
79 case dxbc::PSV::SemanticKind::Position:
80 if (E.Rows != 1 || E.Cols != 4 ||
81 (E.CompType != ElementType::F16 && E.CompType != ElementType::F32))
82 return signatureError(
83 "SV_Position requires one row of four floating-point components");
84 break;
85 case dxbc::PSV::SemanticKind::VertexID:
86 if (E.Rows != 1 || E.Cols != 1 ||
87 (E.CompType != ElementType::I16 && E.CompType != ElementType::U16 &&
88 E.CompType != ElementType::I32 && E.CompType != ElementType::U32))
89 return signatureError(
90 "SV_VertexID requires a scalar 16- or 32-bit integer");
91 break;
92 case dxbc::PSV::SemanticKind::InstanceID:
93 if (E.Rows != 1 || E.Cols != 1 ||
94 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
95 return signatureError(
96 "SV_InstanceID requires a scalar 16- or 32-bit unsigned integer");
97 break;
98 case dxbc::PSV::SemanticKind::ShadingRate:
99 if (E.Rows != 1 || E.Cols != 1 ||
100 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
101 return signatureError(
102 "SV_ShadingRate requires a scalar 16- or 32-bit unsigned integer");
103 break;
104 case dxbc::PSV::SemanticKind::SampleIndex:
105 if (E.Rows != 1 || E.Cols != 1 ||
106 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
107 return signatureError(
108 "SV_SampleIndex requires a scalar 16- or 32-bit unsigned integer");
109 break;
110 case dxbc::PSV::SemanticKind::PrimitiveID:
111 if (E.Rows != 1 || E.Cols != 1 ||
112 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
113 return signatureError(
114 "SV_PrimitiveID requires a scalar 16- or 32-bit unsigned integer");
115 break;
116 case dxbc::PSV::SemanticKind::IsFrontFace:
117 if (E.Rows != 1 || E.Cols != 1 ||
118 (E.CompType != ElementType::I32 && E.CompType != ElementType::U32))
119 return signatureError("SV_IsFrontFace requires a scalar 32-bit integer");
120 break;
121 case dxbc::PSV::SemanticKind::Coverage:
122 if (E.Rows != 1 || E.Cols != 1 || E.CompType != ElementType::U32)
123 return signatureError(
124 "SV_Coverage requires a scalar 32-bit unsigned integer");
125 break;
126 case dxbc::PSV::SemanticKind::StencilRef:
127 if (E.Rows != 1 || E.Cols != 1 ||
128 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
129 return signatureError(
130 "SV_StencilRef requires a scalar 16- or 32-bit unsigned integer");
131 break;
132 case dxbc::PSV::SemanticKind::ViewPortArrayIndex:
133 if (E.Rows != 1 || E.Cols != 1 ||
134 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
135 return signatureError("SV_ViewportArrayIndex requires a scalar 16- or "
136 "32-bit unsigned integer");
137 break;
138 case dxbc::PSV::SemanticKind::RenderTargetArrayIndex:
139 if (E.Rows != 1 || E.Cols != 1 ||
140 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
141 return signatureError("SV_RenderTargetArrayIndex requires a scalar 16- "
142 "or 32-bit unsigned integer");
143 break;
144 case dxbc::PSV::SemanticKind::Barycentrics:
145 if (E.Rows != 1 || E.Cols != 3 ||
146 (E.CompType != ElementType::F16 && E.CompType != ElementType::F32))
147 return signatureError("SV_Barycentrics requires one row of three 16- or "
148 "32-bit floating-point components");
149 break;
150 default:
151 break;
152 }
153 return Error::success();
154}
155
157 switch (E.SemanticKind) {
158 case dxbc::PSV::SemanticKind::Target:
159 if (E.Rows != 1 || E.SemanticIndices.front() >= 8)
160 return signatureError(
161 "pixel targets require one row and an index within 0-7");
162 break;
163 case dxbc::PSV::SemanticKind::VertexID:
164 if (E.SemanticIndices.front() != 0)
165 return signatureError("SV_VertexID requires semantic index 0");
166 break;
167 case dxbc::PSV::SemanticKind::Barycentrics:
168 if (E.SemanticIndices.front() != 0)
169 return signatureError("SV_Barycentrics requires semantic index 0");
170 break;
171 case dxbc::PSV::SemanticKind::SampleIndex:
172 if (E.SemanticIndices.front() != 0)
173 return signatureError("SV_SampleIndex requires semantic index 0");
174 break;
175 case dxbc::PSV::SemanticKind::PrimitiveID:
176 if (E.SemanticIndices.front() != 0)
177 return signatureError("SV_PrimitiveID requires semantic index 0");
178 break;
179 case dxbc::PSV::SemanticKind::IsFrontFace:
180 if (E.SemanticIndices.front() != 0)
181 return signatureError("SV_IsFrontFace requires semantic index 0");
182 break;
183 case dxbc::PSV::SemanticKind::Coverage:
184 if (E.SemanticIndices.front() != 0)
185 return signatureError("SV_Coverage requires semantic index 0");
186 break;
187 case dxbc::PSV::SemanticKind::StencilRef:
188 if (E.SemanticIndices.front() != 0)
189 return signatureError("SV_StencilRef requires semantic index 0");
190 break;
191 case dxbc::PSV::SemanticKind::ViewPortArrayIndex:
192 if (E.SemanticIndices.front() != 0)
193 return signatureError("SV_ViewportArrayIndex requires semantic index 0");
194 break;
195 case dxbc::PSV::SemanticKind::RenderTargetArrayIndex:
196 if (E.SemanticIndices.front() != 0)
197 return signatureError(
198 "SV_RenderTargetArrayIndex requires semantic index 0");
199 break;
200 default:
201 break;
202 }
203 return Error::success();
204}
205
206static Error
208 const VersionTuple &ShaderModelVersion) {
209 switch (E.SemanticKind) {
210 case dxbc::PSV::SemanticKind::Barycentrics:
211 if (ShaderModelVersion < VersionTuple(6, 1))
212 return signatureError("SV_Barycentrics requires shader model 6.1");
213 break;
214 default:
215 break;
216 }
217 return Error::success();
218}
219
224 const VersionTuple &ShaderModelVersion,
225 bool Native16, unsigned &Extent) {
226 if (!MD)
227 return Error::success();
228 auto *List = dyn_cast<MDNode>(MD);
229 if (!List)
230 return signatureError("expected a signature element list or null");
231
232 std::set<std::pair<std::string, uint32_t>> Semantics;
233 constexpr unsigned MaxAllocatedElements = MaxSignatureRows * 4;
234 unsigned NumAllocated = 0;
235 std::array<uint8_t, MaxSignatureRows> AllocatedColumns = {};
236 std::array<dxbc::PSV::InterpolationMode, MaxSignatureRows> RowModes = {};
237 std::array<bool, MaxSignatureRows> RowNative16 = {};
238 for (const MDOperand &Op : List->operands()) {
240 if (Error Err = checkElementNode(Node))
241 return Err;
243 if (!Parsed)
244 return Parsed.takeError();
245 SemanticSignatureElement E = std::move(*Parsed);
246 if (E.SigId != Out.size())
247 return signatureError("signature IDs must be dense and in list order");
248 if (Stage != Triple::Vertex && Stage != Triple::Pixel)
249 return signatureError("nonempty signatures are currently supported only "
250 "for vertex and pixel entries");
251 if (!E.Rows || E.Rows > MaxSignatureRows)
252 return signatureError("signature row count must be within 1-32");
253 if (E.SemanticName.empty() || E.SemanticName.contains('\0'))
254 return signatureError("invalid semantic name");
255 if (E.CompType != ElementType::F16 && E.CompType != ElementType::F32 &&
256 !isIntegerComponent(E.CompType))
257 return signatureError("unsupported signature component type");
258 if (E.GSStream != 0)
259 return signatureError("nonzero stream requires a geometry output");
260 auto NamedKind = getSemanticKind(E.SemanticName);
261 auto Interpretation = getInterpretationKind(NamedKind, Stage, IO);
262 if (Interpretation == SemanticInterpretation::Invalid)
263 return signatureError("invalid or unsupported semantic for this stage "
264 "and signature category");
265 if (Interpretation == SemanticInterpretation::NotAllocated)
266 return signatureError("semantic accessed by a dedicated intrinsic must "
267 "not appear in an input/output signature");
268 auto ExpectedKind = Interpretation == SemanticInterpretation::Arbitrary
269 ? dxbc::PSV::SemanticKind::Arbitrary
270 : NamedKind;
271 if (E.SemanticKind != ExpectedKind)
272 return signatureError("semantic name and kind disagree at this signature "
273 "point");
274 if (Interpretation == SemanticInterpretation::NotPacked) {
275 if (E.isAllocated())
276 return signatureError(E.SemanticName +
277 " must not have an allocated location");
278 } else {
279 if (!E.isAllocated())
280 return signatureError("signature element " + Twine(E.SigId) + " ('" +
281 E.SemanticName + "') has no allocated location");
282 if (E.StartRow >= MaxSignatureRows ||
283 E.Rows > MaxSignatureRows - E.StartRow || E.StartCol + E.Cols > 4)
284 return signatureError(
285 "allocated signature element exceeds register bounds");
286 }
287 if (E.InterpMode == dxbc::PSV::InterpolationMode::Invalid)
288 return signatureError("invalid interpolation mode");
289
290 for (uint32_t Index : E.SemanticIndices)
291 if (!Semantics.emplace(E.SemanticName.upper(), Index).second)
292 return signatureError("duplicate semantic name and index");
293 if (Error Err = diagnoseSemanticType(E))
294 return Err;
295 if (Error Err = diagnoseSemanticIndex(E))
296 return Err;
297 if (Error Err = diagnoseSemanticShaderModel(E, ShaderModelVersion))
298 return Err;
299 if (E.SemanticKind == dxbc::PSV::SemanticKind::Barycentrics) {
301 if (E.InterpMode == Mode::Undefined || E.InterpMode == Mode::Constant)
302 return signatureError("SV_Barycentrics requires perspective or "
303 "noperspective interpolation");
304 }
305
306 if (Stage == Triple::Vertex && IO == IOType::In &&
307 (E.StartRow != Extent || E.StartCol != 0))
308 return signatureError("vertex inputs require stacked locations in "
309 "signature order (element " +
310 Twine(E.SigId) + ")");
311 if (Interpretation == SemanticInterpretation::Target &&
312 (E.StartRow != E.SemanticIndices.front() || E.StartCol != 0))
313 return signatureError("pixel target location must match its semantic "
314 "index at column 0");
315 if (Stage == Triple::Pixel && IO == IOType::In &&
316 isIntegerComponent(E.CompType) &&
317 E.InterpMode != dxbc::PSV::InterpolationMode::Constant)
318 return signatureError(
319 "integer pixel inputs require constant interpolation");
320
321 if (E.isAllocated()) {
322 if (++NumAllocated > MaxAllocatedElements)
323 return signatureError("too many signature elements");
324 // Co-packed elements must obey row constraints, even when their component
325 // masks do not overlap. Min-precision types occupy 32-bit components.
326 bool IsNative16 = Native16 && (E.CompType == ElementType::F16 ||
327 E.CompType == ElementType::I16 ||
328 E.CompType == ElementType::U16);
329 uint8_t Mask = E.getDeclaredMask();
330 for (unsigned Row = E.StartRow; Row != E.StartRow + E.Rows; ++Row) {
331 if (AllocatedColumns[Row] & Mask)
332 return signatureError("signature elements overlap at row " +
333 Twine(Row) + " (element " + Twine(E.SigId) +
334 ")");
335 if (AllocatedColumns[Row] && RowModes[Row] != E.InterpMode)
336 return signatureError(
337 "signature elements have different interpolation "
338 "modes at row " +
339 Twine(Row) + " (element " + Twine(E.SigId) + ")");
340 if (AllocatedColumns[Row] && RowNative16[Row] != IsNative16)
341 return signatureError("signature elements have different component "
342 "widths at row " +
343 Twine(Row) + " (element " + Twine(E.SigId) +
344 ")");
345 AllocatedColumns[Row] |= Mask;
346 RowModes[Row] = E.InterpMode;
347 RowNative16[Row] = IsNative16;
348 }
349 Extent = std::max(Extent, E.StartRow + E.Rows);
350 }
351 E.SemanticName = Info.Names.insert(E.SemanticName).first->getKey();
352
353 // Access masks will be recomputed so reset to 0 here.
354 E.UsageMask = 0;
355 E.DynIndexMask = 0;
356 Out.push_back(std::move(E));
357 }
358 return Error::success();
359}
360
362 bool Input = I.getIntrinsicID() == Intrinsic::dx_load_input;
363 auto &Elements = Input ? Sig.Inputs : Sig.Outputs;
364 auto *ID = dyn_cast<ConstantInt>(I.getArgOperand(0));
365 auto *Col = dyn_cast<ConstantInt>(I.getArgOperand(2));
366 StringRef Category = Input ? "input" : "output";
367 assert(ID && "signature ID is marked as ImmArg and must be constant");
368 if (ID->getZExtValue() >= Elements.size())
369 return signatureError(Category +
370 " signature: signature access has an invalid element "
371 "ID " +
372 Twine(ID->getZExtValue()));
373 auto &E = Elements[ID->getZExtValue()];
374 auto AccessError = [&](const Twine &Message) {
375 return signatureError(Category + " signature element " + Twine(E.SigId) +
376 " ('" + E.SemanticName + "'): " + Message);
377 };
378 if (E.SemanticKind == dxbc::PSV::SemanticKind::SampleIndex)
379 return AccessError("must not be read with dx.op.load/store");
380 Type *Ty = Input ? I.getType() : I.getArgOperand(3)->getType();
381 unsigned Width = 1;
382 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
383 Width = VT->getNumElements();
384 Ty = VT->getElementType();
385 }
386 if (!Col || Col->getZExtValue() >= E.Cols ||
387 Width > E.Cols - Col->getZExtValue())
388 return AccessError("signature access has an invalid component index");
389 auto *Row = dyn_cast<ConstantInt>(I.getArgOperand(1));
390 if (Row && Row->getZExtValue() >= E.Rows)
391 return AccessError("signature access has an invalid row index");
392 if (!Row && E.Rows == 1)
393 return AccessError(
394 "dynamic indexing requires a multi-row signature element");
395 bool CorrectType = false;
396 switch (E.CompType) {
397 case ElementType::F16:
398 CorrectType = Ty->isHalfTy();
399 break;
400 case ElementType::F32:
401 CorrectType = Ty->isFloatTy();
402 break;
403 case ElementType::I16:
404 case ElementType::U16:
405 CorrectType = Ty->isIntegerTy(16);
406 break;
407 case ElementType::I1:
408 // Boolean signature elements use the i32 load/store overload.
409 CorrectType = Ty->isIntegerTy(32);
410 break;
411 case ElementType::I32:
412 case ElementType::U32:
413 CorrectType = Ty->isIntegerTy(32);
414 break;
415 default:
416 llvm_unreachable("invalid signature component type");
417 }
418 if (!CorrectType)
419 return AccessError("signature access type disagrees with its element");
420 uint8_t Mask = ((1U << Width) - 1) << Col->getZExtValue();
421 E.UsageMask |= Mask << E.getStartColOrZero();
422 if (!Row)
423 E.DynIndexMask |= Mask;
424 return Error::success();
425}
426
428 // Each output vector needs four component bits, so one 32-bit word holds
429 // eight vectors. Adding seven rounds up to include a partially filled word.
430 unsigned Words = (Sig.OutputVectors + 7) / 8;
431 Sig.InputOutputMap.assign(Sig.InputVectors * 4 * Words, 0);
432 // Conservatively connect every accessed input component to every written
433 // output component. This includes control, memory, call, and dynamic-index
434 // dependencies without incorrectly claiming that unknown dependencies are
435 // absent. Unused components and padding remain zero. Both DXIL and PSV use
436 // this same map; a more precise dependency analysis can refine it later.
437 for (const auto &Input : Sig.Inputs) {
438 if (!Input.isAllocated())
439 continue;
440 for (unsigned IR = 0; IR != Input.Rows; ++IR)
441 for (unsigned IC = 0; IC != 4; ++IC) {
442 if (!(Input.UsageMask & (1U << IC)))
443 continue;
444 unsigned Base = ((Input.StartRow + IR) * 4 + IC) * Words;
445 for (const auto &Output : Sig.Outputs) {
446 // Unallocated outputs, such as SV_StencilRef, have no row in the
447 // dependency table.
448 if (!Output.isAllocated())
449 continue;
450 for (unsigned OR = 0; OR != Output.Rows; ++OR)
451 for (unsigned OC = 0; OC != 4; ++OC) {
452 if (!(Output.UsageMask & (1U << OC)))
453 continue;
454 unsigned Bit = (Output.StartRow + OR) * 4 + OC;
455 Sig.InputOutputMap[Base + Bit / 32] |= 1U << (Bit % 32);
456 }
457 }
458 }
459 }
460}
461
465 if (NamedMDNode *Table = M.getNamedMetadata("dx.semantic.signatures")) {
466 for (const MDNode *Record : Table->operands()) {
467 if (Record->getNumOperands() != 3)
468 return signatureError(
469 "expected an entry/input/output signature triple");
470 auto *VAM = dyn_cast_or_null<ValueAsMetadata>(Record->getOperand(0));
471 auto *F = VAM ? dyn_cast<Function>(VAM->getValue()) : nullptr;
472 if (!F || F->getParent() != &M || F->isDeclaration())
473 return signatureError(
474 "signature entry must be a defined function in the module");
475 auto EP =
477 [F](const EntryProperties &E) { return E.Entry == F; });
478 if (EP == MMI.EntryPropertyVec.end())
479 return signatureError("signature function is not a shader entry");
480 if (Info.Entries.contains(F))
481 return signatureError("duplicate signature record for entry '" +
482 F->getName() + "'");
483 EntrySignature Sig;
484 Sig.Stage = EP->ShaderStage;
486 M.getModuleFlag("dx.nativelowprec")))
487 Sig.UseNative16Bit = !Native->isZero();
488 if (Sig.UseNative16Bit && MMI.ShaderModelVersion < VersionTuple(6, 2))
489 return signatureError(
490 "native 16-bit signatures require shader model 6.2");
491 auto AddContext = [&](Error Err, StringRef Category) -> Error {
492 return signatureError("entry '" + F->getName() + "' " + Category +
493 " signature: " + toString(std::move(Err)));
494 };
495 if (Error Err = parseSignature(
496 Record->getOperand(1), Sig.Inputs, Info, Sig.Stage, IOType::In,
498 return AddContext(std::move(Err), "input");
499 if (Error Err = parseSignature(
500 Record->getOperand(2), Sig.Outputs, Info, Sig.Stage, IOType::Out,
502 return AddContext(std::move(Err), "output");
503 for (const Instruction &I : instructions(F))
504 if (auto *II = dyn_cast<IntrinsicInst>(&I);
506 if (Error Err = analyzeAccess(*II, Sig))
507 return signatureError("entry '" + F->getName() +
508 "': " + toString(std::move(Err)));
510 Info.Entries.try_emplace(F, std::move(Sig));
511 }
512 }
513 // Signature IDs are local to an entry. Do not guess which entry a helper's
514 // accesses belong to, even if that helper happens to have a single caller.
515 for (const Function &F : M)
516 if (!Info.Entries.contains(&F))
517 for (const Instruction &I : instructions(F))
518 if (auto *II = dyn_cast<IntrinsicInst>(&I);
520 return signatureError("signature access in function '" + F.getName() +
521 "' has no entry signature metadata");
522 return std::move(Info);
523}
524
526 const ModuleMetadataInfo &MMI) {
527 auto Result = analyzeModule(M, MMI);
528 if (!Result) {
529 M.getContext().emitError("Invalid semantic signature: " +
530 toString(Result.takeError()));
531 return ModuleSignatureInfo();
532 }
533 return std::move(*Result);
534}
535
538 VersionTuple ValidatorVersion) {
539 if (Elements.empty())
540 return nullptr;
541 auto I32 = [&](uint32_t V) {
542 return ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Ctx), V));
543 };
544 auto I8 = [&](uint8_t V) {
545 return ConstantAsMetadata::get(ConstantInt::get(Type::getInt8Ty(Ctx), V));
546 };
548 for (const auto &E : Elements) {
549 SmallVector<Metadata *> Indices, Props;
550 for (uint32_t Index : E.SemanticIndices)
551 Indices.push_back(I32(Index));
552 if (E.GSStream)
553 Props.append({I32(0), I32(E.GSStream)});
554 if (E.DynIndexMask)
555 Props.append({I32(2), I32(E.DynIndexMask)});
556 if (E.UsageMask &&
557 (ValidatorVersion.empty() || ValidatorVersion == VersionTuple(0, 0) ||
558 ValidatorVersion >= VersionTuple(1, 5)))
559 Props.append({I32(3), I32(E.UsageMask >> E.getStartColOrZero())});
561 Ctx, {I32(E.SigId), MDString::get(Ctx, E.SemanticName),
562 I8(static_cast<uint8_t>(E.CompType)),
563 I8(static_cast<uint8_t>(E.SemanticKind)),
564 MDNode::get(Ctx, Indices), I8(static_cast<uint8_t>(E.InterpMode)),
565 I32(E.Rows), I8(E.Cols), I32(E.StartRow), I8(E.StartCol),
566 Props.empty() ? nullptr : MDNode::get(Ctx, Props)}));
567 }
568 return MDNode::get(Ctx, Nodes);
569}
570
572 switch (Type) {
573 case ElementType::I1:
574 return Legacy ? dxbc::SigComponentType::Unknown
575 : dxbc::SigComponentType::UInt32;
576 case ElementType::I16:
577 return dxbc::SigComponentType::SInt16;
578 case ElementType::U16:
579 return dxbc::SigComponentType::UInt16;
580 case ElementType::I32:
581 return dxbc::SigComponentType::SInt32;
582 case ElementType::U32:
583 return dxbc::SigComponentType::UInt32;
584 case ElementType::F16:
585 return dxbc::SigComponentType::Float16;
586 case ElementType::F32:
587 return dxbc::SigComponentType::Float32;
588 default:
589 llvm_unreachable("invalid signature component type");
590 }
591}
592
594 using KindTy = dxbc::PSV::SemanticKind;
595 switch (Kind) {
596 case KindTy::Arbitrary:
597 return dxbc::D3DSystemValue::Undefined;
598 case KindTy::VertexID:
599 return dxbc::D3DSystemValue::VertexID;
600 case KindTy::InstanceID:
601 return dxbc::D3DSystemValue::InstanceID;
602 case KindTy::Position:
603 return dxbc::D3DSystemValue::Position;
604 case KindTy::IsFrontFace:
605 return dxbc::D3DSystemValue::IsFrontFace;
606 case KindTy::ClipDistance:
607 return dxbc::D3DSystemValue::ClipDistance;
608 case KindTy::CullDistance:
609 return dxbc::D3DSystemValue::CullDistance;
610 case KindTy::Target:
611 return dxbc::D3DSystemValue::Target;
612 case KindTy::ShadingRate:
613 return dxbc::D3DSystemValue::ShadingRate;
614 case KindTy::Barycentrics:
615 return dxbc::D3DSystemValue::Barycentrics;
616 case KindTy::SampleIndex:
617 return dxbc::D3DSystemValue::SampleIndex;
618 case KindTy::PrimitiveID:
619 return dxbc::D3DSystemValue::PrimitiveID;
620 case KindTy::StencilRef:
621 return dxbc::D3DSystemValue::StencilRef;
622 case KindTy::ViewPortArrayIndex:
623 return dxbc::D3DSystemValue::ViewPortArrayIndex;
624 case KindTy::Coverage:
625 return dxbc::D3DSystemValue::Coverage;
626 case KindTy::RenderTargetArrayIndex:
627 return dxbc::D3DSystemValue::RenderTargetArrayIndex;
628 default:
629 llvm_unreachable("validated vertex/pixel signature semantic");
630 }
631}
632
633// The DXIL reader normalizes system-value semantic names when loading module
634// metadata. The validator then recreates ISG1/OSG1 from those normalized names
635// and compares the parts byte-for-byte, so the container must use the same
636// spelling even if HLSL (or the source metadata) used a different casing.
638 using Kind = dxbc::PSV::SemanticKind;
639 switch (E.SemanticKind) {
640 case Kind::Arbitrary:
641 return E.SemanticName;
642 case Kind::VertexID:
643 return "SV_VertexID";
644 case Kind::InstanceID:
645 return "SV_InstanceID";
646 case Kind::Position:
647 return "SV_Position";
648 case Kind::IsFrontFace:
649 return "SV_IsFrontFace";
650 case Kind::ClipDistance:
651 return "SV_ClipDistance";
652 case Kind::CullDistance:
653 return "SV_CullDistance";
654 case Kind::Target:
655 return "SV_Target";
656 case Kind::ShadingRate:
657 return "SV_ShadingRate";
658 case Kind::Barycentrics:
659 return "SV_Barycentrics";
660 case Kind::SampleIndex:
661 return "SV_SampleIndex";
662 case Kind::PrimitiveID:
663 return "SV_PrimitiveID";
664 case Kind::StencilRef:
665 return "SV_StencilRef";
666 case Kind::ViewPortArrayIndex:
667 return "SV_ViewportArrayIndex";
668 case Kind::Coverage:
669 return "SV_Coverage";
670 case Kind::RenderTargetArrayIndex:
671 return "SV_RenderTargetArrayIndex";
672 default:
673 llvm_unreachable("validated vertex/pixel signature semantic");
674 }
675}
676
679 bool Input, bool Native16, bool Legacy) {
680 for (const auto &E : Elements) {
681 uint8_t Mask = E.getDeclaredMask();
682 uint8_t ExclusiveMask =
683 Input ? E.getAlwaysReadsMask() : E.getNeverWritesMask();
684 if (Legacy)
685 ExclusiveMask = Input ? 0 : static_cast<uint8_t>(~Mask);
686 for (auto [Row, Index] : enumerate(E.SemanticIndices))
687 Sig.addParam(E.GSStream, getContainerSemanticName(E), Index,
688 getSystemValue(E.SemanticKind),
689 getComponentType(E.CompType, Legacy),
690 E.isAllocated() ? E.StartRow + Row : UnallocatedRow, Mask,
691 ExclusiveMask, E.getMinPrecision(!Native16));
692 }
693}
694
697 bool Legacy) {
698 for (const auto &E : Elements) {
699 auto Type = getComponentType(E.CompType, Legacy);
700 // SigComponentType and PSV ComponentType share COMPONENT_TYPE definitions.
701 Dest.push_back(
702 {E.SemanticKind == dxbc::PSV::SemanticKind::Arbitrary ? E.SemanticName
703 : StringRef(),
704 E.SemanticIndices,
705 E.isAllocated() ? static_cast<uint8_t>(E.StartRow) : uint8_t(0),
706 E.Cols, E.getStartColOrZero(), E.isAllocated(), E.SemanticKind,
707 static_cast<dxbc::PSV::ComponentType>(Type), E.InterpMode,
708 E.DynIndexMask, static_cast<uint8_t>(E.GSStream)});
709 }
710}
711
713 VersionTuple ValidatorVersion) const {
714 if (Inputs.empty() && Outputs.empty())
715 return nullptr;
716 return MDNode::get(Ctx,
717 {emitSignature(Ctx, Inputs, ValidatorVersion),
718 emitSignature(Ctx, Outputs, ValidatorVersion), nullptr});
719}
720
722 mcdxbc::Signature &Output,
723 VersionTuple ValidatorVersion) const {
724 bool Legacy = !ValidatorVersion.empty() &&
725 ValidatorVersion != VersionTuple(0, 0) &&
726 ValidatorVersion < VersionTuple(1, 5);
729}
730
732 // Each output vector needs four component bits, so one 32-bit word holds
733 // eight vectors. Conservatively mark every written output component as
734 // dependent on the view ID, matching the conservative input/output map.
735 SmallVector<uint32_t> Mask((OutputVectors + 7) / 8, 0);
736 for (const auto &Output : Outputs) {
737 if (!Output.isAllocated())
738 continue;
739 for (unsigned R = 0; R != Output.Rows; ++R)
740 for (unsigned C = 0; C != 4; ++C) {
741 if (!(Output.UsageMask & (1U << C)))
742 continue;
743 unsigned Bit = (Output.StartRow + R) * 4 + C;
744 Mask[Bit / 32] |= 1U << (Bit % 32);
745 }
746 }
747 return Mask;
748}
749
751 VersionTuple ValidatorVersion,
752 bool UsesViewID) const {
753 bool Legacy = !ValidatorVersion.empty() &&
754 ValidatorVersion != VersionTuple(0, 0) &&
755 ValidatorVersion < VersionTuple(1, 5);
761 if (UsesViewID)
763 if (Stage == Triple::Vertex)
765 llvm::any_of(Outputs, [](const auto &E) {
766 return E.SemanticKind == dxbc::PSV::SemanticKind::Position;
767 });
768 if (Stage == Triple::Pixel)
770 llvm::any_of(Inputs, [](const auto &E) {
771 return E.InterpMode == dxbc::PSV::InterpolationMode::LinearSample ||
772 E.InterpMode ==
773 dxbc::PSV::InterpolationMode::LinearNoperspectiveSample ||
774 E.SemanticKind == dxbc::PSV::SemanticKind::SampleIndex;
775 });
776}
777
781 if (UsesViewID)
784 return State;
785}
786
788 auto Print = [&](StringRef Name, ArrayRef<SemanticSignatureElement> Elements,
789 unsigned Vectors) {
790 OS << " " << Name << ": " << Elements.size() << " elements, " << Vectors
791 << " vectors\n";
792 for (const auto &E : Elements)
793 OS << " " << E.SigId << ": " << E.SemanticName << " rows=" << E.Rows
794 << " cols=" << unsigned(E.Cols) << " at " << E.StartRow << ":"
795 << unsigned(E.StartCol) << " usage=" << unsigned(E.UsageMask)
796 << " dynamic=" << unsigned(E.DynIndexMask) << '\n';
797 };
798 Print("Inputs", Inputs, InputVectors);
799 Print("Outputs", Outputs, OutputVectors);
800}
801
803 for (const Function &F : M)
804 if (const auto *Sig = get(&F)) {
805 OS << "Semantic signatures for '" << F.getName() << "':\n";
806 Sig->print(OS);
807 }
808}
809
810AnalysisKey SignatureAnalysis::Key;
815
821
823 Info = std::make_unique<ModuleSignatureInfo>(collectSignatures(
824 M, getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata()));
825 return false;
826}
827
832
834 if (Info)
835 Info->print(OS, *M);
836}
837
840 "DXIL Semantic Signature Analysis", false, true)
843 "DXIL Semantic Signature Analysis", false, true)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static GlobalVariable * buildSignature(Module &M, Signature &Sig, StringRef Name, StringRef SectionName, const dxil::ModuleMetadataInfo &MMI)
static Error diagnoseSemanticType(const SemanticSignatureElement &E)
static Error diagnoseSemanticIndex(const SemanticSignatureElement &E)
static bool isSignatureAccess(const IntrinsicInst &I)
static bool isIntegerComponent(ElementType Type)
static MDNode * emitSignature(LLVMContext &Ctx, ArrayRef< SemanticSignatureElement > Elements, VersionTuple ValidatorVersion)
static void buildSignature(mcdxbc::Signature &Sig, ArrayRef< SemanticSignatureElement > Elements, bool Input, bool Native16, bool Legacy)
static dxbc::D3DSystemValue getSystemValue(dxbc::PSV::SemanticKind Kind)
static Expected< ModuleSignatureInfo > analyzeModule(Module &M, const ModuleMetadataInfo &MMI)
static ModuleSignatureInfo collectSignatures(Module &M, const ModuleMetadataInfo &MMI)
static dxbc::SigComponentType getComponentType(ElementType Type, bool Legacy)
static void buildDependencyMap(EntrySignature &Sig)
static Error diagnoseSemanticShaderModel(const SemanticSignatureElement &E, const VersionTuple &ShaderModelVersion)
static Error checkElementNode(const MDNode *Node)
static void buildPSVElements(SmallVectorImpl< mcdxbc::PSVSignatureElement > &Dest, ArrayRef< SemanticSignatureElement > Elements, bool Legacy)
static StringRef getContainerSemanticName(const SemanticSignatureElement &E)
static Error signatureError(const Twine &Message)
static Error analyzeAccess(const IntrinsicInst &I, EntrySignature &Sig)
static Error parseSignature(Metadata *MD, SmallVectorImpl< SemanticSignatureElement > &Out, ModuleSignatureInfo &Info, Triple::EnvironmentType Stage, IOType IO, const VersionTuple &ShaderModelVersion, bool Native16, unsigned &Extent)
Module.h This file contains the declarations for the Module class.
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:85
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains some templates that are useful if you are working with the STL at all.
This file contains some functions that are useful when dealing with strings.
The Input class is used to parse a yaml document into in-memory structs and vectors.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
void print(raw_ostream &OS, const Module *M) const override
print - Print out the internal state of the pass.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Metadata node.
Definition Metadata.h:1087
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
Tuple of metadata.
Definition Metadata.h:1505
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A tuple of MDNodes.
Definition Metadata.h:1806
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Represents a version number in the form major[.minor[.subminor[.build]]].
bool empty() const
Determine whether this version information is empty (e.g., all version components are zero).
const EntrySignature * get(const Function *F) const
void print(raw_ostream &OS, const Module &M) const
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *M) const override
print - Print out the internal state of the pass.
Result run(Module &M, ModuleAnalysisManager &AM)
void addParam(uint32_t Stream, StringRef Name, uint32_t Index, dxbc::D3DSystemValue SystemValue, dxbc::SigComponentType CompType, uint32_t Register, uint8_t Mask, uint8_t ExclusiveMask, dxbc::SigMinPrecision MinPrecision)
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
static constexpr uint32_t UnallocatedRow
LLVM_ABI SemanticInterpretation getInterpretationKind(dxbc::PSV::SemanticKind SemanticKind, Triple::EnvironmentType ShaderStage, IOType IOTy)
LLVM_ABI dxbc::PSV::SemanticKind getSemanticKind(StringRef SemanticName)
static constexpr unsigned MaxSignatureRows
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:721
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
DWARFExpression::Operation Op
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
SmallVector< hlsl::SemanticSignatureElement > Inputs
SmallVector< uint32_t > getDependencyState(bool UsesViewID) const
Return the serialized dx.viewIdState words for this entry: input scalar count, output scalar count,...
Triple::EnvironmentType Stage
void buildSignatures(mcdxbc::Signature &Input, mcdxbc::Signature &Output, VersionTuple ValidatorVersion) const
Append ISG1/OSG1 parameters to the supplied builders.
SmallVector< hlsl::SemanticSignatureElement > Outputs
void updatePSV(mcdxbc::PSVRuntimeInfo &PSV, VersionTuple ValidatorVersion, bool UsesViewID) const
Append PSV signature elements and set vector extents, the dependency map, the view ID output mask if ...
SmallVector< uint32_t > getViewIDOutputMask() const
Return the mask of output scalars that depend on the view ID.
MDTuple * getAsMetadata(LLVMContext &Ctx, VersionTuple ValidatorVersion) const
Return the DXIL input/output/patch-constant signature triple.
SmallVector< uint32_t > InputOutputMap
void print(raw_ostream &OS) const
SmallVector< EntryProperties > EntryPropertyVec
static LLVM_ABI Expected< SemanticSignatureElement > fromMetadata(const MDNode *Node)
dxbc::PSV::v3::RuntimeInfo BaseData
SmallVector< PSVSignatureElement > InputElements
SmallVector< PSVSignatureElement > OutputElements
std::array< SmallVector< uint32_t >, 4 > OutputVectorMasks
std::array< SmallVector< uint32_t >, 4 > InputOutputMap