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::StencilRef:
122 if (E.Rows != 1 || E.Cols != 1 ||
123 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
124 return signatureError(
125 "SV_StencilRef requires a scalar 16- or 32-bit unsigned integer");
126 break;
127 case dxbc::PSV::SemanticKind::Barycentrics:
128 if (E.Rows != 1 || E.Cols != 3 ||
129 (E.CompType != ElementType::F16 && E.CompType != ElementType::F32))
130 return signatureError("SV_Barycentrics requires one row of three 16- or "
131 "32-bit floating-point components");
132 break;
133 default:
134 break;
135 }
136 return Error::success();
137}
138
140 switch (E.SemanticKind) {
141 case dxbc::PSV::SemanticKind::Target:
142 if (E.Rows != 1 || E.SemanticIndices.front() >= 8)
143 return signatureError(
144 "pixel targets require one row and an index within 0-7");
145 break;
146 case dxbc::PSV::SemanticKind::VertexID:
147 if (E.SemanticIndices.front() != 0)
148 return signatureError("SV_VertexID requires semantic index 0");
149 break;
150 case dxbc::PSV::SemanticKind::Barycentrics:
151 if (E.SemanticIndices.front() != 0)
152 return signatureError("SV_Barycentrics requires semantic index 0");
153 break;
154 case dxbc::PSV::SemanticKind::SampleIndex:
155 if (E.SemanticIndices.front() != 0)
156 return signatureError("SV_SampleIndex requires semantic index 0");
157 break;
158 case dxbc::PSV::SemanticKind::PrimitiveID:
159 if (E.SemanticIndices.front() != 0)
160 return signatureError("SV_PrimitiveID requires semantic index 0");
161 break;
162 case dxbc::PSV::SemanticKind::IsFrontFace:
163 if (E.SemanticIndices.front() != 0)
164 return signatureError("SV_IsFrontFace requires semantic index 0");
165 break;
166 case dxbc::PSV::SemanticKind::StencilRef:
167 if (E.SemanticIndices.front() != 0)
168 return signatureError("SV_StencilRef requires semantic index 0");
169 break;
170 default:
171 break;
172 }
173 return Error::success();
174}
175
176static Error
178 const VersionTuple &ShaderModelVersion) {
179 switch (E.SemanticKind) {
180 case dxbc::PSV::SemanticKind::Barycentrics:
181 if (ShaderModelVersion < VersionTuple(6, 1))
182 return signatureError("SV_Barycentrics requires shader model 6.1");
183 break;
184 default:
185 break;
186 }
187 return Error::success();
188}
189
194 const VersionTuple &ShaderModelVersion,
195 bool Native16, unsigned &Extent) {
196 if (!MD)
197 return Error::success();
198 auto *List = dyn_cast<MDNode>(MD);
199 if (!List)
200 return signatureError("expected a signature element list or null");
201
202 std::set<std::pair<std::string, uint32_t>> Semantics;
203 constexpr unsigned MaxAllocatedElements = MaxSignatureRows * 4;
204 unsigned NumAllocated = 0;
205 std::array<uint8_t, MaxSignatureRows> AllocatedColumns = {};
206 std::array<dxbc::PSV::InterpolationMode, MaxSignatureRows> RowModes = {};
207 std::array<bool, MaxSignatureRows> RowNative16 = {};
208 for (const MDOperand &Op : List->operands()) {
210 if (Error Err = checkElementNode(Node))
211 return Err;
213 if (!Parsed)
214 return Parsed.takeError();
215 SemanticSignatureElement E = std::move(*Parsed);
216 if (E.SigId != Out.size())
217 return signatureError("signature IDs must be dense and in list order");
218 if (Stage != Triple::Vertex && Stage != Triple::Pixel)
219 return signatureError("nonempty signatures are currently supported only "
220 "for vertex and pixel entries");
221 if (!E.Rows || E.Rows > MaxSignatureRows)
222 return signatureError("signature row count must be within 1-32");
223 if (E.SemanticName.empty() || E.SemanticName.contains('\0'))
224 return signatureError("invalid semantic name");
225 if (E.CompType != ElementType::F16 && E.CompType != ElementType::F32 &&
226 !isIntegerComponent(E.CompType))
227 return signatureError("unsupported signature component type");
228 if (E.GSStream != 0)
229 return signatureError("nonzero stream requires a geometry output");
230 auto NamedKind = getSemanticKind(E.SemanticName);
231 auto Interpretation = getInterpretationKind(NamedKind, Stage, IO);
232 if (Interpretation == SemanticInterpretation::Invalid)
233 return signatureError("invalid or unsupported semantic for this stage "
234 "and signature category");
235 if (Interpretation == SemanticInterpretation::NotAllocated)
236 return signatureError("semantic accessed by a dedicated intrinsic must "
237 "not appear in an input/output signature");
238 auto ExpectedKind = Interpretation == SemanticInterpretation::Arbitrary
239 ? dxbc::PSV::SemanticKind::Arbitrary
240 : NamedKind;
241 if (E.SemanticKind != ExpectedKind)
242 return signatureError("semantic name and kind disagree at this signature "
243 "point");
244 if (Interpretation == SemanticInterpretation::NotPacked) {
245 if (E.isAllocated())
246 return signatureError(E.SemanticName +
247 " must not have an allocated location");
248 } else {
249 if (!E.isAllocated())
250 return signatureError("signature element " + Twine(E.SigId) + " ('" +
251 E.SemanticName + "') has no allocated location");
252 if (E.StartRow >= MaxSignatureRows ||
253 E.Rows > MaxSignatureRows - E.StartRow || E.StartCol + E.Cols > 4)
254 return signatureError(
255 "allocated signature element exceeds register bounds");
256 }
257 if (E.InterpMode == dxbc::PSV::InterpolationMode::Invalid)
258 return signatureError("invalid interpolation mode");
259
260 for (uint32_t Index : E.SemanticIndices)
261 if (!Semantics.emplace(E.SemanticName.upper(), Index).second)
262 return signatureError("duplicate semantic name and index");
263 if (Error Err = diagnoseSemanticType(E))
264 return Err;
265 if (Error Err = diagnoseSemanticIndex(E))
266 return Err;
267 if (Error Err = diagnoseSemanticShaderModel(E, ShaderModelVersion))
268 return Err;
269 if (E.SemanticKind == dxbc::PSV::SemanticKind::Barycentrics) {
271 if (E.InterpMode == Mode::Undefined || E.InterpMode == Mode::Constant)
272 return signatureError("SV_Barycentrics requires perspective or "
273 "noperspective interpolation");
274 }
275
276 if (Stage == Triple::Vertex && IO == IOType::In &&
277 (E.StartRow != Extent || E.StartCol != 0))
278 return signatureError("vertex inputs require stacked locations in "
279 "signature order (element " +
280 Twine(E.SigId) + ")");
281 if (Interpretation == SemanticInterpretation::Target &&
282 (E.StartRow != E.SemanticIndices.front() || E.StartCol != 0))
283 return signatureError("pixel target location must match its semantic "
284 "index at column 0");
285 if (Stage == Triple::Pixel && IO == IOType::In &&
286 isIntegerComponent(E.CompType) &&
287 E.InterpMode != dxbc::PSV::InterpolationMode::Constant)
288 return signatureError(
289 "integer pixel inputs require constant interpolation");
290
291 if (E.isAllocated()) {
292 if (++NumAllocated > MaxAllocatedElements)
293 return signatureError("too many signature elements");
294 // Co-packed elements must obey row constraints, even when their component
295 // masks do not overlap. Min-precision types occupy 32-bit components.
296 bool IsNative16 = Native16 && (E.CompType == ElementType::F16 ||
297 E.CompType == ElementType::I16 ||
298 E.CompType == ElementType::U16);
299 uint8_t Mask = E.getDeclaredMask();
300 for (unsigned Row = E.StartRow; Row != E.StartRow + E.Rows; ++Row) {
301 if (AllocatedColumns[Row] & Mask)
302 return signatureError("signature elements overlap at row " +
303 Twine(Row) + " (element " + Twine(E.SigId) +
304 ")");
305 if (AllocatedColumns[Row] && RowModes[Row] != E.InterpMode)
306 return signatureError(
307 "signature elements have different interpolation "
308 "modes at row " +
309 Twine(Row) + " (element " + Twine(E.SigId) + ")");
310 if (AllocatedColumns[Row] && RowNative16[Row] != IsNative16)
311 return signatureError("signature elements have different component "
312 "widths at row " +
313 Twine(Row) + " (element " + Twine(E.SigId) +
314 ")");
315 AllocatedColumns[Row] |= Mask;
316 RowModes[Row] = E.InterpMode;
317 RowNative16[Row] = IsNative16;
318 }
319 Extent = std::max(Extent, E.StartRow + E.Rows);
320 }
321 E.SemanticName = Info.Names.insert(E.SemanticName).first->getKey();
322
323 // Access masks will be recomputed so reset to 0 here.
324 E.UsageMask = 0;
325 E.DynIndexMask = 0;
326 Out.push_back(std::move(E));
327 }
328 return Error::success();
329}
330
332 bool Input = I.getIntrinsicID() == Intrinsic::dx_load_input;
333 auto &Elements = Input ? Sig.Inputs : Sig.Outputs;
334 auto *ID = dyn_cast<ConstantInt>(I.getArgOperand(0));
335 auto *Col = dyn_cast<ConstantInt>(I.getArgOperand(2));
336 StringRef Category = Input ? "input" : "output";
337 assert(ID && "signature ID is marked as ImmArg and must be constant");
338 if (ID->getZExtValue() >= Elements.size())
339 return signatureError(Category +
340 " signature: signature access has an invalid element "
341 "ID " +
342 Twine(ID->getZExtValue()));
343 auto &E = Elements[ID->getZExtValue()];
344 auto AccessError = [&](const Twine &Message) {
345 return signatureError(Category + " signature element " + Twine(E.SigId) +
346 " ('" + E.SemanticName + "'): " + Message);
347 };
348 if (E.SemanticKind == dxbc::PSV::SemanticKind::SampleIndex)
349 return AccessError("must not be read with dx.op.load/store");
350 Type *Ty = Input ? I.getType() : I.getArgOperand(3)->getType();
351 unsigned Width = 1;
352 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
353 Width = VT->getNumElements();
354 Ty = VT->getElementType();
355 }
356 if (!Col || Col->getZExtValue() >= E.Cols ||
357 Width > E.Cols - Col->getZExtValue())
358 return AccessError("signature access has an invalid component index");
359 auto *Row = dyn_cast<ConstantInt>(I.getArgOperand(1));
360 if (Row && Row->getZExtValue() >= E.Rows)
361 return AccessError("signature access has an invalid row index");
362 if (!Row && E.Rows == 1)
363 return AccessError(
364 "dynamic indexing requires a multi-row signature element");
365 bool CorrectType = false;
366 switch (E.CompType) {
367 case ElementType::F16:
368 CorrectType = Ty->isHalfTy();
369 break;
370 case ElementType::F32:
371 CorrectType = Ty->isFloatTy();
372 break;
373 case ElementType::I16:
374 case ElementType::U16:
375 CorrectType = Ty->isIntegerTy(16);
376 break;
377 case ElementType::I1:
378 // Boolean signature elements use the i32 load/store overload.
379 CorrectType = Ty->isIntegerTy(32);
380 break;
381 case ElementType::I32:
382 case ElementType::U32:
383 CorrectType = Ty->isIntegerTy(32);
384 break;
385 default:
386 llvm_unreachable("invalid signature component type");
387 }
388 if (!CorrectType)
389 return AccessError("signature access type disagrees with its element");
390 uint8_t Mask = ((1U << Width) - 1) << Col->getZExtValue();
391 E.UsageMask |= Mask << E.getStartColOrZero();
392 if (!Row)
393 E.DynIndexMask |= Mask;
394 return Error::success();
395}
396
398 // Each output vector needs four component bits, so one 32-bit word holds
399 // eight vectors. Adding seven rounds up to include a partially filled word.
400 unsigned Words = (Sig.OutputVectors + 7) / 8;
401 Sig.InputOutputMap.assign(Sig.InputVectors * 4 * Words, 0);
402 // Conservatively connect every accessed input component to every written
403 // output component. This includes control, memory, call, and dynamic-index
404 // dependencies without incorrectly claiming that unknown dependencies are
405 // absent. Unused components and padding remain zero. Both DXIL and PSV use
406 // this same map; a more precise dependency analysis can refine it later.
407 for (const auto &Input : Sig.Inputs) {
408 if (!Input.isAllocated())
409 continue;
410 for (unsigned IR = 0; IR != Input.Rows; ++IR)
411 for (unsigned IC = 0; IC != 4; ++IC) {
412 if (!(Input.UsageMask & (1U << IC)))
413 continue;
414 unsigned Base = ((Input.StartRow + IR) * 4 + IC) * Words;
415 for (const auto &Output : Sig.Outputs) {
416 // Unallocated outputs, such as SV_StencilRef, have no row in the
417 // dependency table.
418 if (!Output.isAllocated())
419 continue;
420 for (unsigned OR = 0; OR != Output.Rows; ++OR)
421 for (unsigned OC = 0; OC != 4; ++OC) {
422 if (!(Output.UsageMask & (1U << OC)))
423 continue;
424 unsigned Bit = (Output.StartRow + OR) * 4 + OC;
425 Sig.InputOutputMap[Base + Bit / 32] |= 1U << (Bit % 32);
426 }
427 }
428 }
429 }
430}
431
435 if (NamedMDNode *Table = M.getNamedMetadata("dx.semantic.signatures")) {
436 for (const MDNode *Record : Table->operands()) {
437 if (Record->getNumOperands() != 3)
438 return signatureError(
439 "expected an entry/input/output signature triple");
440 auto *VAM = dyn_cast_or_null<ValueAsMetadata>(Record->getOperand(0));
441 auto *F = VAM ? dyn_cast<Function>(VAM->getValue()) : nullptr;
442 if (!F || F->getParent() != &M || F->isDeclaration())
443 return signatureError(
444 "signature entry must be a defined function in the module");
445 auto EP =
447 [F](const EntryProperties &E) { return E.Entry == F; });
448 if (EP == MMI.EntryPropertyVec.end())
449 return signatureError("signature function is not a shader entry");
450 if (Info.Entries.contains(F))
451 return signatureError("duplicate signature record for entry '" +
452 F->getName() + "'");
453 EntrySignature Sig;
454 Sig.Stage = EP->ShaderStage;
456 M.getModuleFlag("dx.nativelowprec")))
457 Sig.UseNative16Bit = !Native->isZero();
458 if (Sig.UseNative16Bit && MMI.ShaderModelVersion < VersionTuple(6, 2))
459 return signatureError(
460 "native 16-bit signatures require shader model 6.2");
461 auto AddContext = [&](Error Err, StringRef Category) -> Error {
462 return signatureError("entry '" + F->getName() + "' " + Category +
463 " signature: " + toString(std::move(Err)));
464 };
465 if (Error Err = parseSignature(
466 Record->getOperand(1), Sig.Inputs, Info, Sig.Stage, IOType::In,
468 return AddContext(std::move(Err), "input");
469 if (Error Err = parseSignature(
470 Record->getOperand(2), Sig.Outputs, Info, Sig.Stage, IOType::Out,
472 return AddContext(std::move(Err), "output");
473 for (const Instruction &I : instructions(F))
474 if (auto *II = dyn_cast<IntrinsicInst>(&I);
476 if (Error Err = analyzeAccess(*II, Sig))
477 return signatureError("entry '" + F->getName() +
478 "': " + toString(std::move(Err)));
480 Info.Entries.try_emplace(F, std::move(Sig));
481 }
482 }
483 // Signature IDs are local to an entry. Do not guess which entry a helper's
484 // accesses belong to, even if that helper happens to have a single caller.
485 for (const Function &F : M)
486 if (!Info.Entries.contains(&F))
487 for (const Instruction &I : instructions(F))
488 if (auto *II = dyn_cast<IntrinsicInst>(&I);
490 return signatureError("signature access in function '" + F.getName() +
491 "' has no entry signature metadata");
492 return std::move(Info);
493}
494
496 const ModuleMetadataInfo &MMI) {
497 auto Result = analyzeModule(M, MMI);
498 if (!Result) {
499 M.getContext().emitError("Invalid semantic signature: " +
500 toString(Result.takeError()));
501 return ModuleSignatureInfo();
502 }
503 return std::move(*Result);
504}
505
508 VersionTuple ValidatorVersion) {
509 if (Elements.empty())
510 return nullptr;
511 auto I32 = [&](uint32_t V) {
512 return ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Ctx), V));
513 };
514 auto I8 = [&](uint8_t V) {
515 return ConstantAsMetadata::get(ConstantInt::get(Type::getInt8Ty(Ctx), V));
516 };
518 for (const auto &E : Elements) {
519 SmallVector<Metadata *> Indices, Props;
520 for (uint32_t Index : E.SemanticIndices)
521 Indices.push_back(I32(Index));
522 if (E.GSStream)
523 Props.append({I32(0), I32(E.GSStream)});
524 if (E.DynIndexMask)
525 Props.append({I32(2), I32(E.DynIndexMask)});
526 if (E.UsageMask &&
527 (ValidatorVersion.empty() || ValidatorVersion == VersionTuple(0, 0) ||
528 ValidatorVersion >= VersionTuple(1, 5)))
529 Props.append({I32(3), I32(E.UsageMask >> E.getStartColOrZero())});
531 Ctx, {I32(E.SigId), MDString::get(Ctx, E.SemanticName),
532 I8(static_cast<uint8_t>(E.CompType)),
533 I8(static_cast<uint8_t>(E.SemanticKind)),
534 MDNode::get(Ctx, Indices), I8(static_cast<uint8_t>(E.InterpMode)),
535 I32(E.Rows), I8(E.Cols), I32(E.StartRow), I8(E.StartCol),
536 Props.empty() ? nullptr : MDNode::get(Ctx, Props)}));
537 }
538 return MDNode::get(Ctx, Nodes);
539}
540
542 switch (Type) {
543 case ElementType::I1:
544 return Legacy ? dxbc::SigComponentType::Unknown
545 : dxbc::SigComponentType::UInt32;
546 case ElementType::I16:
547 return dxbc::SigComponentType::SInt16;
548 case ElementType::U16:
549 return dxbc::SigComponentType::UInt16;
550 case ElementType::I32:
551 return dxbc::SigComponentType::SInt32;
552 case ElementType::U32:
553 return dxbc::SigComponentType::UInt32;
554 case ElementType::F16:
555 return dxbc::SigComponentType::Float16;
556 case ElementType::F32:
557 return dxbc::SigComponentType::Float32;
558 default:
559 llvm_unreachable("invalid signature component type");
560 }
561}
562
564 using KindTy = dxbc::PSV::SemanticKind;
565 switch (Kind) {
566 case KindTy::Arbitrary:
567 return dxbc::D3DSystemValue::Undefined;
568 case KindTy::VertexID:
569 return dxbc::D3DSystemValue::VertexID;
570 case KindTy::InstanceID:
571 return dxbc::D3DSystemValue::InstanceID;
572 case KindTy::Position:
573 return dxbc::D3DSystemValue::Position;
574 case KindTy::IsFrontFace:
575 return dxbc::D3DSystemValue::IsFrontFace;
576 case KindTy::ClipDistance:
577 return dxbc::D3DSystemValue::ClipDistance;
578 case KindTy::CullDistance:
579 return dxbc::D3DSystemValue::CullDistance;
580 case KindTy::Target:
581 return dxbc::D3DSystemValue::Target;
582 case KindTy::ShadingRate:
583 return dxbc::D3DSystemValue::ShadingRate;
584 case KindTy::Barycentrics:
585 return dxbc::D3DSystemValue::Barycentrics;
586 case KindTy::SampleIndex:
587 return dxbc::D3DSystemValue::SampleIndex;
588 case KindTy::PrimitiveID:
589 return dxbc::D3DSystemValue::PrimitiveID;
590 case KindTy::StencilRef:
591 return dxbc::D3DSystemValue::StencilRef;
592 default:
593 llvm_unreachable("validated vertex/pixel signature semantic");
594 }
595}
596
597// The DXIL reader normalizes system-value semantic names when loading module
598// metadata. The validator then recreates ISG1/OSG1 from those normalized names
599// and compares the parts byte-for-byte, so the container must use the same
600// spelling even if HLSL (or the source metadata) used a different casing.
602 using Kind = dxbc::PSV::SemanticKind;
603 switch (E.SemanticKind) {
604 case Kind::Arbitrary:
605 return E.SemanticName;
606 case Kind::VertexID:
607 return "SV_VertexID";
608 case Kind::InstanceID:
609 return "SV_InstanceID";
610 case Kind::Position:
611 return "SV_Position";
612 case Kind::IsFrontFace:
613 return "SV_IsFrontFace";
614 case Kind::ClipDistance:
615 return "SV_ClipDistance";
616 case Kind::CullDistance:
617 return "SV_CullDistance";
618 case Kind::Target:
619 return "SV_Target";
620 case Kind::ShadingRate:
621 return "SV_ShadingRate";
622 case Kind::Barycentrics:
623 return "SV_Barycentrics";
624 case Kind::SampleIndex:
625 return "SV_SampleIndex";
626 case Kind::PrimitiveID:
627 return "SV_PrimitiveID";
628 case Kind::StencilRef:
629 return "SV_StencilRef";
630 default:
631 llvm_unreachable("validated vertex/pixel signature semantic");
632 }
633}
634
637 bool Input, bool Native16, bool Legacy) {
638 for (const auto &E : Elements) {
639 uint8_t Mask = E.getDeclaredMask();
640 uint8_t ExclusiveMask =
641 Input ? E.getAlwaysReadsMask() : E.getNeverWritesMask();
642 if (Legacy)
643 ExclusiveMask = Input ? 0 : static_cast<uint8_t>(~Mask);
644 for (auto [Row, Index] : enumerate(E.SemanticIndices))
645 Sig.addParam(E.GSStream, getContainerSemanticName(E), Index,
646 getSystemValue(E.SemanticKind),
647 getComponentType(E.CompType, Legacy),
648 E.isAllocated() ? E.StartRow + Row : UnallocatedRow, Mask,
649 ExclusiveMask, E.getMinPrecision(!Native16));
650 }
651}
652
655 bool Legacy) {
656 for (const auto &E : Elements) {
657 auto Type = getComponentType(E.CompType, Legacy);
658 // SigComponentType and PSV ComponentType share COMPONENT_TYPE definitions.
659 Dest.push_back(
660 {E.SemanticKind == dxbc::PSV::SemanticKind::Arbitrary ? E.SemanticName
661 : StringRef(),
662 E.SemanticIndices,
663 E.isAllocated() ? static_cast<uint8_t>(E.StartRow) : uint8_t(0),
664 E.Cols, E.getStartColOrZero(), E.isAllocated(), E.SemanticKind,
665 static_cast<dxbc::PSV::ComponentType>(Type), E.InterpMode,
666 E.DynIndexMask, static_cast<uint8_t>(E.GSStream)});
667 }
668}
669
671 VersionTuple ValidatorVersion) const {
672 if (Inputs.empty() && Outputs.empty())
673 return nullptr;
674 return MDNode::get(Ctx,
675 {emitSignature(Ctx, Inputs, ValidatorVersion),
676 emitSignature(Ctx, Outputs, ValidatorVersion), nullptr});
677}
678
680 mcdxbc::Signature &Output,
681 VersionTuple ValidatorVersion) const {
682 bool Legacy = !ValidatorVersion.empty() &&
683 ValidatorVersion != VersionTuple(0, 0) &&
684 ValidatorVersion < VersionTuple(1, 5);
687}
688
690 // Each output vector needs four component bits, so one 32-bit word holds
691 // eight vectors. Conservatively mark every written output component as
692 // dependent on the view ID, matching the conservative input/output map.
693 SmallVector<uint32_t> Mask((OutputVectors + 7) / 8, 0);
694 for (const auto &Output : Outputs) {
695 if (!Output.isAllocated())
696 continue;
697 for (unsigned R = 0; R != Output.Rows; ++R)
698 for (unsigned C = 0; C != 4; ++C) {
699 if (!(Output.UsageMask & (1U << C)))
700 continue;
701 unsigned Bit = (Output.StartRow + R) * 4 + C;
702 Mask[Bit / 32] |= 1U << (Bit % 32);
703 }
704 }
705 return Mask;
706}
707
709 VersionTuple ValidatorVersion,
710 bool UsesViewID) const {
711 bool Legacy = !ValidatorVersion.empty() &&
712 ValidatorVersion != VersionTuple(0, 0) &&
713 ValidatorVersion < VersionTuple(1, 5);
719 if (UsesViewID)
721 if (Stage == Triple::Vertex)
723 llvm::any_of(Outputs, [](const auto &E) {
724 return E.SemanticKind == dxbc::PSV::SemanticKind::Position;
725 });
726 if (Stage == Triple::Pixel)
728 llvm::any_of(Inputs, [](const auto &E) {
729 return E.InterpMode == dxbc::PSV::InterpolationMode::LinearSample ||
730 E.InterpMode ==
731 dxbc::PSV::InterpolationMode::LinearNoperspectiveSample ||
732 E.SemanticKind == dxbc::PSV::SemanticKind::SampleIndex;
733 });
734}
735
739 if (UsesViewID)
742 return State;
743}
744
746 auto Print = [&](StringRef Name, ArrayRef<SemanticSignatureElement> Elements,
747 unsigned Vectors) {
748 OS << " " << Name << ": " << Elements.size() << " elements, " << Vectors
749 << " vectors\n";
750 for (const auto &E : Elements)
751 OS << " " << E.SigId << ": " << E.SemanticName << " rows=" << E.Rows
752 << " cols=" << unsigned(E.Cols) << " at " << E.StartRow << ":"
753 << unsigned(E.StartCol) << " usage=" << unsigned(E.UsageMask)
754 << " dynamic=" << unsigned(E.DynIndexMask) << '\n';
755 };
756 Print("Inputs", Inputs, InputVectors);
757 Print("Outputs", Outputs, OutputVectors);
758}
759
761 for (const Function &F : M)
762 if (const auto *Sig = get(&F)) {
763 OS << "Semantic signatures for '" << F.getName() << "':\n";
764 Sig->print(OS);
765 }
766}
767
768AnalysisKey SignatureAnalysis::Key;
773
779
781 Info = std::make_unique<ModuleSignatureInfo>(collectSignatures(
782 M, getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata()));
783 return false;
784}
785
790
792 if (Info)
793 Info->print(OS, *M);
794}
795
798 "DXIL Semantic Signature Analysis", false, true)
801 "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