upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools/spirv_interface.py
diff options
context:
space:
mode:
Diffstat (limited to 'tools/spirv_interface.py')
-rw-r--r--tools/spirv_interface.py522
1 files changed, 522 insertions, 0 deletions
diff --git a/tools/spirv_interface.py b/tools/spirv_interface.py
new file mode 100644
index 000000000..a9ecfa397
--- /dev/null
+++ b/tools/spirv_interface.py
@@ -0,0 +1,522 @@
1"""Reflect the user-defined graphics interfaces in a binary SPIR-V module.
2
3This reader is deliberately limited to declarations used for Vulkan stage linking. It does not
4validate shader instructions, device features, or resource bindings. IDs and debug names are local
5to each module; the result uses normalized types and Location/Component decorations instead.
6"""
7from __future__ import annotations
8
9from array import array
10from collections import defaultdict
11from dataclasses import dataclass
12import struct
13
14
15class InterfaceError(ValueError):
16 """The module's requested interface could not be reflected."""
17
18
19SPIRV_MAGIC = 0x07230203
20SPIRV_MAGIC_SWAPPED = 0x03022307
21
22# SPIR-V core grammar. The NV/EXT spelling of PerPrimitive uses the same enumerant.
23OP_ENTRY_POINT = 15
24OP_TYPE_INT = 21
25OP_TYPE_FLOAT = 22
26OP_TYPE_VECTOR = 23
27OP_TYPE_MATRIX = 24
28OP_TYPE_ARRAY = 28
29OP_TYPE_STRUCT = 30
30OP_TYPE_POINTER = 32
31OP_CONSTANT = 43
32OP_VARIABLE = 59
33OP_DECORATE = 71
34OP_MEMBER_DECORATE = 72
35OP_DECORATION_GROUP = 73
36OP_GROUP_DECORATE = 74
37OP_GROUP_MEMBER_DECORATE = 75
38
39TYPE_OPS = {OP_TYPE_INT, OP_TYPE_FLOAT, OP_TYPE_VECTOR, OP_TYPE_MATRIX,
40 OP_TYPE_ARRAY, OP_TYPE_STRUCT, OP_TYPE_POINTER}
41DECLARATION_OPS = TYPE_OPS | {OP_ENTRY_POINT, OP_CONSTANT, OP_VARIABLE, OP_DECORATE,
42 OP_MEMBER_DECORATE, OP_DECORATION_GROUP, OP_GROUP_DECORATE,
43 OP_GROUP_MEMBER_DECORATE}
44TYPE_OPERANDS = {OP_TYPE_INT: 3, OP_TYPE_FLOAT: 2, OP_TYPE_VECTOR: 3, OP_TYPE_MATRIX: 3,
45 OP_TYPE_ARRAY: 3, OP_TYPE_POINTER: 3}
46EXECUTION_STAGES = {0: "vs", 3: "gs", 4: "ps", 5365: "ms"}
47STORAGE_INPUT = 1
48STORAGE_OUTPUT = 3
49DEC_BLOCK = 2
50DEC_BUILTIN = 11
51DEC_PATCH = 15
52DEC_LOCATION = 30
53DEC_COMPONENT = 31
54DEC_INDEX = 32
55DEC_PASSTHROUGH_NV = 5250
56DEC_PER_PRIMITIVE = 5271
57DEC_PER_VERTEX = 5285
58DECORATION_NAMES = {DEC_BLOCK: "Block", DEC_BUILTIN: "BuiltIn", DEC_PATCH: "Patch",
59 DEC_LOCATION: "Location", DEC_COMPONENT: "Component", DEC_INDEX: "Index",
60 DEC_PASSTHROUGH_NV: "PassthroughNV", DEC_PER_PRIMITIVE: "PerPrimitiveEXT",
61 DEC_PER_VERTEX: "PerVertexKHR"}
62VALUE_DECORATIONS = {DEC_BUILTIN, DEC_LOCATION, DEC_COMPONENT, DEC_INDEX}
63
64# Bound expansion of arrays from malformed modules. This is far beyond the varying space of the
65# graphics stages on current Vulkan drivers. Type and layout recursion has a separate depth limit.
66MAX_EXPANDED_LOCATIONS = 16384
67MAX_TYPE_DEPTH = 64
68
69
70@dataclass(frozen=True)
71class NumericType:
72 kind: str
73 width: int
74 components: int = 1
75
76 def describe(self):
77 scalar = f"{self.kind}{self.width}"
78 return scalar if self.components == 1 else f"vec{self.components}<{scalar}>"
79
80 def location_masks(self, component):
81 slots = self.components * (self.width // 32 if self.width >= 32 else 1)
82 if self.width == 64 and component % 2:
83 raise InterfaceError("a 64-bit varying starts on an odd Component")
84 if self.width != 64 and component + slots > 4:
85 raise InterfaceError("a 16-bit or 32-bit varying extends beyond its Location")
86 if self.width == 64 and slots > 4 and component:
87 raise InterfaceError("a 64-bit vector spanning two locations needs Component 0")
88 mask = ((1 << slots) - 1) << component
89 if mask <= 0xf:
90 return (mask,)
91 return (mask & 0xf, mask >> 4)
92
93
94@dataclass(frozen=True)
95class AggregateType:
96 kind: str
97 items: tuple[NumericType | "AggregateType", ...]
98 count: int = 1
99
100 def describe(self):
101 if self.kind == "struct":
102 return "struct{" + ", ".join(item.describe() for item in self.items) + "}"
103 return f"{self.kind}[{self.count}]<{self.items[0].describe()}>"
104
105 def location_masks(self, component):
106 if self.kind == "struct":
107 if component:
108 raise InterfaceError("a structure cannot start at a nonzero Component")
109 masks = []
110 for member in self.items:
111 member_masks = member.location_masks(0)
112 if len(masks) + len(member_masks) > MAX_EXPANDED_LOCATIONS:
113 raise InterfaceError("structure uses too many interface locations to inspect")
114 masks.extend(member_masks)
115 return tuple(masks)
116 element = self.items[0].location_masks(component)
117 if len(element) * self.count > MAX_EXPANDED_LOCATIONS:
118 raise InterfaceError("aggregate uses too many interface locations to inspect")
119 return element * self.count
120
121
122@dataclass(frozen=True, order=True)
123class Address:
124 location: int
125 component: int = 0
126 index: int = 0
127
128 def describe(self):
129 suffix = f", index {self.index}" if self.index else ""
130 return f"location {self.location}, component {self.component}{suffix}"
131
132
133@dataclass(frozen=True)
134class Varying:
135 address: Address
136 type: NumericType | AggregateType
137 per_primitive: bool = False
138
139 def occupied(self):
140 for offset, mask in enumerate(self.type.location_masks(self.address.component)):
141 for component in range(4):
142 if mask & (1 << component):
143 yield Address(self.address.location + offset, component, self.address.index)
144
145 def describe(self):
146 mode = " per-primitive" if self.per_primitive else ""
147 return f"{self.type.describe()}{mode} at {self.address.describe()}"
148
149
150@dataclass(frozen=True)
151class Declaration:
152 """One standalone varying or an entire structure. Preserve member order when linking."""
153
154 varyings: tuple[Varying, ...]
155 symbol: int
156 structure: bool = False
157 block: bool = False
158 indexed_by_vertex_or_primitive: bool = False
159
160 def describe(self):
161 parts = ", ".join(varying.describe() for varying in self.varyings)
162 if self.structure:
163 kind = "block" if self.block else "struct"
164 return f"{kind} %{self.symbol} ({parts})"
165 return f"%{self.symbol} ({parts})"
166
167
168@dataclass(frozen=True)
169class StageInterface:
170 stage: str
171 entry: str
172 inputs: tuple[Declaration, ...]
173 outputs: tuple[Declaration, ...]
174
175
176@dataclass(frozen=True)
177class EntryPoint:
178 model: int
179 name: str
180 interface_ids: tuple[int, ...]
181
182
183def parse_words(data):
184 if len(data) < 20 or len(data) % 4:
185 raise InterfaceError("SPIR-V must contain a five-word header and complete 32-bit words")
186 words = array("I")
187 words.frombytes(data)
188 if words[0] == SPIRV_MAGIC_SWAPPED:
189 words.byteswap()
190 if words[0] != SPIRV_MAGIC:
191 raise InterfaceError("invalid SPIR-V magic")
192 if not 0x00010000 <= words[1] <= 0x00010600 or words[1] & 0xff:
193 raise InterfaceError(f"unsupported SPIR-V version word 0x{words[1]:08x}")
194 if not words[3] or words[4]:
195 raise InterfaceError("invalid SPIR-V ID bound or reserved header word")
196 return words
197
198
199def instructions(words):
200 start = 5
201 while start < len(words):
202 first = words[start]
203 length, opcode = first >> 16, first & 0xffff
204 end = start + length
205 if not length or end > len(words):
206 raise InterfaceError(f"invalid instruction length at word {start}")
207 if opcode in DECLARATION_OPS:
208 yield opcode, tuple(words[start + 1:end]), start
209 start = end
210
211
212def decode_literal_string(words):
213 for i, word in enumerate(words):
214 if b"\x00" in struct.pack("<I", word):
215 raw = struct.pack(f"<{i + 1}I", *words[:i + 1])
216 name, _, padding = raw.partition(b"\x00")
217 if any(padding):
218 raise InterfaceError("nonzero padding in OpEntryPoint name")
219 try:
220 return name.decode("utf-8"), i + 1
221 except UnicodeDecodeError as exc:
222 raise InterfaceError("OpEntryPoint name is not UTF-8") from exc
223 raise InterfaceError("unterminated OpEntryPoint name")
224
225
226class Module:
227 def __init__(self, data):
228 words = parse_words(data)
229 self.bound = words[3]
230 self.types = {}
231 self.constants = {}
232 self.variables = {}
233 self.entry_points = []
234 self.decorations = defaultdict(dict)
235 self.member_decorations = defaultdict(dict)
236 self.groups = set()
237 self.group_uses = []
238 self.definition_ids = set()
239 self.shape_cache = {}
240 for opcode, operands, at in instructions(words):
241 self.read_instruction(opcode, operands, at)
242 self.apply_decoration_groups()
243
244 def require_id(self, identifier):
245 if not 0 < identifier < self.bound:
246 raise InterfaceError(f"ID %{identifier} is outside the SPIR-V bound")
247
248 def define(self, identifier):
249 self.require_id(identifier)
250 if identifier in self.definition_ids:
251 raise InterfaceError(f"duplicate definition of ID %{identifier}")
252 self.definition_ids.add(identifier)
253
254 @staticmethod
255 def require_operands(operands, at, minimum, maximum=None):
256 if len(operands) < minimum or (maximum is not None and len(operands) > maximum):
257 raise InterfaceError(f"invalid operands at word {at}")
258
259 def read_instruction(self, opcode, operands, at):
260 if opcode in TYPE_OPS:
261 exact = TYPE_OPERANDS.get(opcode)
262 self.require_operands(operands, at, exact or 1, exact)
263 identifier, *args = operands
264 self.define(identifier)
265 self.types[identifier] = (opcode, tuple(args))
266 elif opcode == OP_CONSTANT:
267 self.require_operands(operands, at, 3)
268 type_id, identifier, *literal = operands
269 self.require_id(type_id)
270 self.define(identifier)
271 self.constants[identifier] = (type_id, tuple(literal))
272 elif opcode == OP_VARIABLE:
273 self.require_operands(operands, at, 3, 4)
274 pointer, identifier, storage = operands[:3]
275 self.require_id(pointer)
276 self.define(identifier)
277 self.variables[identifier] = (pointer, storage)
278 elif opcode == OP_ENTRY_POINT:
279 self.require_operands(operands, at, 3)
280 model, function, *rest = operands
281 self.require_id(function)
282 name, words_used = decode_literal_string(rest)
283 ids = tuple(rest[words_used:])
284 for identifier in ids:
285 self.require_id(identifier)
286 if len(set(ids)) != len(ids):
287 raise InterfaceError(f"duplicate entry-point interface ID in {name!r}")
288 self.entry_points.append(EntryPoint(model, name, ids))
289 elif opcode in (OP_DECORATE, OP_MEMBER_DECORATE):
290 split = 1 if opcode == OP_DECORATE else 2
291 self.require_operands(operands, at, split + 1)
292 identifier = operands[0]
293 self.require_id(identifier)
294 decoration, *extra = operands[split:]
295 if decoration not in DECORATION_NAMES:
296 return
297 expected = int(decoration in VALUE_DECORATIONS)
298 if len(extra) != expected:
299 raise InterfaceError(f"invalid {DECORATION_NAMES[decoration]} decoration at word {at}")
300 target = (self.decorations[identifier] if split == 1
301 else self.member_decorations[(identifier, operands[1])])
302 self.add_decoration(target, decoration, extra[0] if extra else True)
303 elif opcode == OP_DECORATION_GROUP:
304 self.require_operands(operands, at, 1, 1)
305 self.define(operands[0])
306 self.groups.add(operands[0])
307 else:
308 self.require_operands(operands, at, 2 if opcode == OP_GROUP_DECORATE else 3)
309 if opcode == OP_GROUP_MEMBER_DECORATE and len(operands) % 2 != 1:
310 raise InterfaceError(f"unpaired group member decoration at word {at}")
311 self.group_uses.append((opcode, operands))
312
313 @staticmethod
314 def add_decoration(target, decoration, value):
315 if decoration in target and target[decoration] != value:
316 raise InterfaceError(f"conflicting {DECORATION_NAMES[decoration]} decorations")
317 target[decoration] = value
318
319 def apply_decoration_groups(self):
320 for opcode, operands in self.group_uses:
321 group, *targets = operands
322 if group not in self.groups:
323 raise InterfaceError(f"undefined decoration group %{group}")
324 source = self.decorations.get(group, {})
325 if opcode == OP_GROUP_DECORATE:
326 destinations = ((identifier, None) for identifier in targets)
327 else:
328 destinations = zip(targets[::2], targets[1::2])
329 for identifier, member in destinations:
330 self.require_id(identifier)
331 if identifier in self.groups:
332 raise InterfaceError("decoration groups cannot decorate each other")
333 target = (self.decorations[identifier] if member is None
334 else self.member_decorations[(identifier, member)])
335 for decoration, value in source.items():
336 self.add_decoration(target, decoration, value)
337
338 def type_declaration(self, identifier):
339 try:
340 return self.types[identifier]
341 except KeyError:
342 raise InterfaceError(f"missing or unsupported varying type %{identifier}") from None
343
344 def array_count(self, identifier):
345 try:
346 type_id, literal = self.constants[identifier]
347 except KeyError:
348 raise InterfaceError(f"varying array length %{identifier} is not a literal OpConstant") from None
349 opcode, args = self.type_declaration(type_id)
350 if opcode != OP_TYPE_INT or args[0] not in (16, 32, 64) or args[1] not in (0, 1):
351 raise InterfaceError("varying array length must be an integer")
352 width, signed = args
353 if len(literal) != (width + 31) // 32:
354 raise InterfaceError("invalid literal width for varying array length")
355 count = sum(word << (32 * i) for i, word in enumerate(literal)) & ((1 << width) - 1)
356 if not count or (signed and count >> (width - 1)):
357 raise InterfaceError("varying array length must be positive")
358 return count
359
360 def shape(self, identifier, path=()):
361 if identifier in self.shape_cache:
362 return self.shape_cache[identifier]
363 if identifier in path or len(path) == MAX_TYPE_DEPTH:
364 raise InterfaceError("cyclic or excessively deep varying type")
365 opcode, args = self.type_declaration(identifier)
366 nested = (*path, identifier)
367 if opcode in (OP_TYPE_INT, OP_TYPE_FLOAT):
368 width = args[0]
369 if width not in (16, 32, 64) or (opcode == OP_TYPE_INT and args[1] not in (0, 1)):
370 raise InterfaceError("unsupported numeric type in graphics interface")
371 kind = "f" if opcode == OP_TYPE_FLOAT else ("i" if args[1] else "u")
372 result = NumericType(kind, width)
373 elif opcode == OP_TYPE_VECTOR:
374 element = self.shape(args[0], nested)
375 if not isinstance(element, NumericType) or element.components != 1 or not 2 <= args[1] <= 4:
376 raise InterfaceError("invalid varying vector type")
377 result = NumericType(element.kind, element.width, args[1])
378 elif opcode in (OP_TYPE_ARRAY, OP_TYPE_MATRIX):
379 element = self.shape(args[0], nested)
380 if opcode == OP_TYPE_ARRAY:
381 result = AggregateType("array", (element,), self.array_count(args[1]))
382 else:
383 if (not isinstance(element, NumericType) or element.kind != "f" or element.components < 2
384 or not 2 <= args[1] <= 4):
385 raise InterfaceError("invalid varying matrix type")
386 result = AggregateType("matrix", (element,), args[1])
387 elif opcode == OP_TYPE_STRUCT:
388 if not args:
389 raise InterfaceError("empty structure in graphics interface")
390 for i in range(len(args)):
391 if self.member_decorations.get((identifier, i)):
392 raise InterfaceError("decorated nested interface structure members are unsupported")
393 result = AggregateType("struct", tuple(self.shape(member, nested) for member in args))
394 else:
395 raise InterfaceError("unsupported pointer in graphics interface")
396 self.shape_cache[identifier] = result
397 return result
398
399 def pick_entry(self, stage, entry):
400 named = [candidate for candidate in self.entry_points if candidate.name == entry]
401 matches = [candidate for candidate in named if stage is None or EXECUTION_STAGES.get(candidate.model) == stage]
402 if not matches:
403 found = ", ".join(EXECUTION_STAGES.get(candidate.model, str(candidate.model)) for candidate in named)
404 if found:
405 raise InterfaceError(f"entry point {entry!r} is {found}, expected {stage}")
406 raise InterfaceError(f"entry point {entry!r} not found")
407 if len(matches) > 1:
408 raise InterfaceError(f"entry point {entry!r} is ambiguous without a stage")
409 selected = matches[0]
410 if selected.model not in EXECUTION_STAGES:
411 raise InterfaceError(f"unsupported execution model {selected.model} for entry point {entry!r}")
412 return selected
413
414 def varying_type(self, pointer, storage, stage, decorations):
415 opcode, args = self.type_declaration(pointer)
416 if opcode != OP_TYPE_POINTER or args[0] != storage:
417 raise InterfaceError("variable pointer type does not match its storage class")
418 pointee = args[1]
419 per_vertex = DEC_PER_VERTEX in decorations
420 if per_vertex and (stage, storage) != ("ps", STORAGE_INPUT):
421 raise InterfaceError("PerVertexKHR is only supported on fragment inputs")
422 primitive_array = (stage, storage) in (("gs", STORAGE_INPUT), ("ms", STORAGE_OUTPUT))
423 indexed = per_vertex or primitive_array
424 if indexed:
425 # The array indexes vertices or primitives. It is outside the linked payload shape
426 # and does not consume locations. Its length does not need to match the other stage.
427 opcode, args = self.type_declaration(pointee)
428 if opcode != OP_TYPE_ARRAY:
429 raise InterfaceError(f"{stage} requires an outer per-vertex or per-primitive array")
430 pointee = args[0]
431 return pointee, indexed
432
433 @staticmethod
434 def address(decorations, location=None):
435 location = decorations.get(DEC_LOCATION, location)
436 component = decorations.get(DEC_COMPONENT, 0)
437 index = decorations.get(DEC_INDEX, 0)
438 if location is None:
439 raise InterfaceError("user varying is missing a Location decoration")
440 if component > 3 or index > 1:
441 raise InterfaceError("invalid Component or Index decoration")
442 return Address(location, component, index)
443
444 @staticmethod
445 def check_modes(decorations):
446 if DEC_PASSTHROUGH_NV in decorations:
447 raise InterfaceError("geometry passthrough interfaces require different matching rules")
448 if DEC_PATCH in decorations:
449 raise InterfaceError("tessellation patch interfaces are unsupported")
450
451 def declaration(self, symbol, pointer, storage, stage):
452 decorations = self.decorations.get(symbol, {})
453 self.check_modes(decorations)
454 if DEC_BUILTIN in decorations:
455 return None
456 type_id, indexed = self.varying_type(pointer, storage, stage, decorations)
457 opcode, args = self.type_declaration(type_id)
458 per_primitive = DEC_PER_PRIMITIVE in decorations
459 if opcode != OP_TYPE_STRUCT:
460 varying = Varying(self.address(decorations), self.shape(type_id), per_primitive)
461 return Declaration((varying,), symbol, indexed_by_vertex_or_primitive=indexed)
462
463 member_decs = [self.member_decorations.get((type_id, i), {}) for i in range(len(args))]
464 if member_decs and all(DEC_BUILTIN in member for member in member_decs):
465 return None
466 if any(DEC_BUILTIN in member for member in member_decs):
467 raise InterfaceError("mixed built-in and user-defined structure members")
468 is_block = DEC_BLOCK in self.decorations.get(type_id, {})
469 base_location = decorations.get(DEC_LOCATION)
470 if base_location is None and not is_block:
471 raise InterfaceError("a non-block structure needs a Location")
472 if DEC_COMPONENT in decorations or DEC_INDEX in decorations:
473 raise InterfaceError("Component or Index on an entire varying structure is unsupported")
474 if base_location is not None and any(DEC_LOCATION in member for member in member_decs):
475 raise InterfaceError("both the structure and its members declare Locations")
476 if not args:
477 raise InterfaceError("empty structure in graphics interface")
478 members = []
479 next_location = base_location
480 for child, member in zip(args, member_decs):
481 self.check_modes(member)
482 address = self.address(member, next_location)
483 shape = self.shape(child, (type_id,))
484 members.append(Varying(address, shape, per_primitive or DEC_PER_PRIMITIVE in member))
485 if base_location is not None:
486 next_location += len(shape.location_masks(address.component))
487 return Declaration(tuple(members), symbol, structure=True, block=is_block,
488 indexed_by_vertex_or_primitive=indexed)
489
490 def reflect(self, stage=None, entry="main"):
491 selected = self.pick_entry(stage, entry)
492 stage = EXECUTION_STAGES[selected.model]
493 directions = {STORAGE_INPUT: [], STORAGE_OUTPUT: []}
494 slots = {STORAGE_INPUT: {}, STORAGE_OUTPUT: {}}
495 for symbol in selected.interface_ids:
496 if symbol not in self.variables:
497 raise InterfaceError(f"entry point references missing variable %{symbol}")
498 pointer, storage = self.variables[symbol]
499 if storage not in directions:
500 continue
501 try:
502 declaration = self.declaration(symbol, pointer, storage, stage)
503 if declaration is None:
504 continue
505 for varying in declaration.varyings:
506 for address in varying.occupied():
507 before = slots[storage].get(address)
508 if before is not None:
509 raise InterfaceError(
510 f"overlap with %{before} at {address.describe()}")
511 slots[storage][address] = symbol
512 except InterfaceError as exc:
513 direction = "input" if storage == STORAGE_INPUT else "output"
514 raise InterfaceError(f"{stage} {direction} variable %{symbol}: {exc}") from exc
515 directions[storage].append(declaration)
516 key = lambda declaration: declaration.varyings[0].address
517 return StageInterface(stage, entry, tuple(sorted(directions[STORAGE_INPUT], key=key)),
518 tuple(sorted(directions[STORAGE_OUTPUT], key=key)))
519
520
521def reflect_module(data, stage=None, entry="main"):
522 return Module(data).reflect(stage, entry)