Debian Codegraph @

third_party/smol-v/source/smolv.cpp

raw
1 // smol-v - public domain - https://github.com/aras-p/smol-v
2 // authored on 2016 by Aras Pranckevicius
3 // no warranty implied; use at your own risk
4
5 #include "smolv.h"
6 #include <stdint.h>
7 #include <vector>
8 #include <algorithm>
9 #include <cstdio>
10 #include <cstring>
11
12 #if !defined(_MSC_VER) && __cplusplus < 201103L
13 #define static_assert(x,y)
14 #endif
15
16 #define _SMOLV_ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
17
18 // --------------------------------------------------------------------------------------------
19 // Metadata about known SPIR-V operations
20
21 enum SpvOp
22 {
23 SpvOpNop = 0,
24 SpvOpUndef = 1,
25 SpvOpSourceContinued = 2,
26 SpvOpSource = 3,
27 SpvOpSourceExtension = 4,
28 SpvOpName = 5,
29 SpvOpMemberName = 6,
30 SpvOpString = 7,
31 SpvOpLine = 8,
32 SpvOpExtension = 10,
33 SpvOpExtInstImport = 11,
34 SpvOpExtInst = 12,
35 SpvOpVectorShuffleCompact = 13, // not in SPIR-V, added for SMOL-V!
36 SpvOpMemoryModel = 14,
37 SpvOpEntryPoint = 15,
38 SpvOpExecutionMode = 16,
39 SpvOpCapability = 17,
40 SpvOpTypeVoid = 19,
41 SpvOpTypeBool = 20,
42 SpvOpTypeInt = 21,
43 SpvOpTypeFloat = 22,
44 SpvOpTypeVector = 23,
45 SpvOpTypeMatrix = 24,
46 SpvOpTypeImage = 25,
47 SpvOpTypeSampler = 26,
48 SpvOpTypeSampledImage = 27,
49 SpvOpTypeArray = 28,
50 SpvOpTypeRuntimeArray = 29,
51 SpvOpTypeStruct = 30,
52 SpvOpTypeOpaque = 31,
53 SpvOpTypePointer = 32,
54 SpvOpTypeFunction = 33,
55 SpvOpTypeEvent = 34,
56 SpvOpTypeDeviceEvent = 35,
57 SpvOpTypeReserveId = 36,
58 SpvOpTypeQueue = 37,
59 SpvOpTypePipe = 38,
60 SpvOpTypeForwardPointer = 39,
61 SpvOpConstantTrue = 41,
62 SpvOpConstantFalse = 42,
63 SpvOpConstant = 43,
64 SpvOpConstantComposite = 44,
65 SpvOpConstantSampler = 45,
66 SpvOpConstantNull = 46,
67 SpvOpSpecConstantTrue = 48,
68 SpvOpSpecConstantFalse = 49,
69 SpvOpSpecConstant = 50,
70 SpvOpSpecConstantComposite = 51,
71 SpvOpSpecConstantOp = 52,
72 SpvOpFunction = 54,
73 SpvOpFunctionParameter = 55,
74 SpvOpFunctionEnd = 56,
75 SpvOpFunctionCall = 57,
76 SpvOpVariable = 59,
77 SpvOpImageTexelPointer = 60,
78 SpvOpLoad = 61,
79 SpvOpStore = 62,
80 SpvOpCopyMemory = 63,
81 SpvOpCopyMemorySized = 64,
82 SpvOpAccessChain = 65,
83 SpvOpInBoundsAccessChain = 66,
84 SpvOpPtrAccessChain = 67,
85 SpvOpArrayLength = 68,
86 SpvOpGenericPtrMemSemantics = 69,
87 SpvOpInBoundsPtrAccessChain = 70,
88 SpvOpDecorate = 71,
89 SpvOpMemberDecorate = 72,
90 SpvOpDecorationGroup = 73,
91 SpvOpGroupDecorate = 74,
92 SpvOpGroupMemberDecorate = 75,
93 SpvOpVectorExtractDynamic = 77,
94 SpvOpVectorInsertDynamic = 78,
95 SpvOpVectorShuffle = 79,
96 SpvOpCompositeConstruct = 80,
97 SpvOpCompositeExtract = 81,
98 SpvOpCompositeInsert = 82,
99 SpvOpCopyObject = 83,
100 SpvOpTranspose = 84,
101 SpvOpSampledImage = 86,
102 SpvOpImageSampleImplicitLod = 87,
103 SpvOpImageSampleExplicitLod = 88,
104 SpvOpImageSampleDrefImplicitLod = 89,
105 SpvOpImageSampleDrefExplicitLod = 90,
106 SpvOpImageSampleProjImplicitLod = 91,
107 SpvOpImageSampleProjExplicitLod = 92,
108 SpvOpImageSampleProjDrefImplicitLod = 93,
109 SpvOpImageSampleProjDrefExplicitLod = 94,
110 SpvOpImageFetch = 95,
111 SpvOpImageGather = 96,
112 SpvOpImageDrefGather = 97,
113 SpvOpImageRead = 98,
114 SpvOpImageWrite = 99,
115 SpvOpImage = 100,
116 SpvOpImageQueryFormat = 101,
117 SpvOpImageQueryOrder = 102,
118 SpvOpImageQuerySizeLod = 103,
119 SpvOpImageQuerySize = 104,
120 SpvOpImageQueryLod = 105,
121 SpvOpImageQueryLevels = 106,
122 SpvOpImageQuerySamples = 107,
123 SpvOpConvertFToU = 109,
124 SpvOpConvertFToS = 110,
125 SpvOpConvertSToF = 111,
126 SpvOpConvertUToF = 112,
127 SpvOpUConvert = 113,
128 SpvOpSConvert = 114,
129 SpvOpFConvert = 115,
130 SpvOpQuantizeToF16 = 116,
131 SpvOpConvertPtrToU = 117,
132 SpvOpSatConvertSToU = 118,
133 SpvOpSatConvertUToS = 119,
134 SpvOpConvertUToPtr = 120,
135 SpvOpPtrCastToGeneric = 121,
136 SpvOpGenericCastToPtr = 122,
137 SpvOpGenericCastToPtrExplicit = 123,
138 SpvOpBitcast = 124,
139 SpvOpSNegate = 126,
140 SpvOpFNegate = 127,
141 SpvOpIAdd = 128,
142 SpvOpFAdd = 129,
143 SpvOpISub = 130,
144 SpvOpFSub = 131,
145 SpvOpIMul = 132,
146 SpvOpFMul = 133,
147 SpvOpUDiv = 134,
148 SpvOpSDiv = 135,
149 SpvOpFDiv = 136,
150 SpvOpUMod = 137,
151 SpvOpSRem = 138,
152 SpvOpSMod = 139,
153 SpvOpFRem = 140,
154 SpvOpFMod = 141,
155 SpvOpVectorTimesScalar = 142,
156 SpvOpMatrixTimesScalar = 143,
157 SpvOpVectorTimesMatrix = 144,
158 SpvOpMatrixTimesVector = 145,
159 SpvOpMatrixTimesMatrix = 146,
160 SpvOpOuterProduct = 147,
161 SpvOpDot = 148,
162 SpvOpIAddCarry = 149,
163 SpvOpISubBorrow = 150,
164 SpvOpUMulExtended = 151,
165 SpvOpSMulExtended = 152,
166 SpvOpAny = 154,
167 SpvOpAll = 155,
168 SpvOpIsNan = 156,
169 SpvOpIsInf = 157,
170 SpvOpIsFinite = 158,
171 SpvOpIsNormal = 159,
172 SpvOpSignBitSet = 160,
173 SpvOpLessOrGreater = 161,
174 SpvOpOrdered = 162,
175 SpvOpUnordered = 163,
176 SpvOpLogicalEqual = 164,
177 SpvOpLogicalNotEqual = 165,
178 SpvOpLogicalOr = 166,
179 SpvOpLogicalAnd = 167,
180 SpvOpLogicalNot = 168,
181 SpvOpSelect = 169,
182 SpvOpIEqual = 170,
183 SpvOpINotEqual = 171,
184 SpvOpUGreaterThan = 172,
185 SpvOpSGreaterThan = 173,
186 SpvOpUGreaterThanEqual = 174,
187 SpvOpSGreaterThanEqual = 175,
188 SpvOpULessThan = 176,
189 SpvOpSLessThan = 177,
190 SpvOpULessThanEqual = 178,
191 SpvOpSLessThanEqual = 179,
192 SpvOpFOrdEqual = 180,
193 SpvOpFUnordEqual = 181,
194 SpvOpFOrdNotEqual = 182,
195 SpvOpFUnordNotEqual = 183,
196 SpvOpFOrdLessThan = 184,
197 SpvOpFUnordLessThan = 185,
198 SpvOpFOrdGreaterThan = 186,
199 SpvOpFUnordGreaterThan = 187,
200 SpvOpFOrdLessThanEqual = 188,
201 SpvOpFUnordLessThanEqual = 189,
202 SpvOpFOrdGreaterThanEqual = 190,
203 SpvOpFUnordGreaterThanEqual = 191,
204 SpvOpShiftRightLogical = 194,
205 SpvOpShiftRightArithmetic = 195,
206 SpvOpShiftLeftLogical = 196,
207 SpvOpBitwiseOr = 197,
208 SpvOpBitwiseXor = 198,
209 SpvOpBitwiseAnd = 199,
210 SpvOpNot = 200,
211 SpvOpBitFieldInsert = 201,
212 SpvOpBitFieldSExtract = 202,
213 SpvOpBitFieldUExtract = 203,
214 SpvOpBitReverse = 204,
215 SpvOpBitCount = 205,
216 SpvOpDPdx = 207,
217 SpvOpDPdy = 208,
218 SpvOpFwidth = 209,
219 SpvOpDPdxFine = 210,
220 SpvOpDPdyFine = 211,
221 SpvOpFwidthFine = 212,
222 SpvOpDPdxCoarse = 213,
223 SpvOpDPdyCoarse = 214,
224 SpvOpFwidthCoarse = 215,
225 SpvOpEmitVertex = 218,
226 SpvOpEndPrimitive = 219,
227 SpvOpEmitStreamVertex = 220,
228 SpvOpEndStreamPrimitive = 221,
229 SpvOpControlBarrier = 224,
230 SpvOpMemoryBarrier = 225,
231 SpvOpAtomicLoad = 227,
232 SpvOpAtomicStore = 228,
233 SpvOpAtomicExchange = 229,
234 SpvOpAtomicCompareExchange = 230,
235 SpvOpAtomicCompareExchangeWeak = 231,
236 SpvOpAtomicIIncrement = 232,
237 SpvOpAtomicIDecrement = 233,
238 SpvOpAtomicIAdd = 234,
239 SpvOpAtomicISub = 235,
240 SpvOpAtomicSMin = 236,
241 SpvOpAtomicUMin = 237,
242 SpvOpAtomicSMax = 238,
243 SpvOpAtomicUMax = 239,
244 SpvOpAtomicAnd = 240,
245 SpvOpAtomicOr = 241,
246 SpvOpAtomicXor = 242,
247 SpvOpPhi = 245,
248 SpvOpLoopMerge = 246,
249 SpvOpSelectionMerge = 247,
250 SpvOpLabel = 248,
251 SpvOpBranch = 249,
252 SpvOpBranchConditional = 250,
253 SpvOpSwitch = 251,
254 SpvOpKill = 252,
255 SpvOpReturn = 253,
256 SpvOpReturnValue = 254,
257 SpvOpUnreachable = 255,
258 SpvOpLifetimeStart = 256,
259 SpvOpLifetimeStop = 257,
260 SpvOpGroupAsyncCopy = 259,
261 SpvOpGroupWaitEvents = 260,
262 SpvOpGroupAll = 261,
263 SpvOpGroupAny = 262,
264 SpvOpGroupBroadcast = 263,
265 SpvOpGroupIAdd = 264,
266 SpvOpGroupFAdd = 265,
267 SpvOpGroupFMin = 266,
268 SpvOpGroupUMin = 267,
269 SpvOpGroupSMin = 268,
270 SpvOpGroupFMax = 269,
271 SpvOpGroupUMax = 270,
272 SpvOpGroupSMax = 271,
273 SpvOpReadPipe = 274,
274 SpvOpWritePipe = 275,
275 SpvOpReservedReadPipe = 276,
276 SpvOpReservedWritePipe = 277,
277 SpvOpReserveReadPipePackets = 278,
278 SpvOpReserveWritePipePackets = 279,
279 SpvOpCommitReadPipe = 280,
280 SpvOpCommitWritePipe = 281,
281 SpvOpIsValidReserveId = 282,
282 SpvOpGetNumPipePackets = 283,
283 SpvOpGetMaxPipePackets = 284,
284 SpvOpGroupReserveReadPipePackets = 285,
285 SpvOpGroupReserveWritePipePackets = 286,
286 SpvOpGroupCommitReadPipe = 287,
287 SpvOpGroupCommitWritePipe = 288,
288 SpvOpEnqueueMarker = 291,
289 SpvOpEnqueueKernel = 292,
290 SpvOpGetKernelNDrangeSubGroupCount = 293,
291 SpvOpGetKernelNDrangeMaxSubGroupSize = 294,
292 SpvOpGetKernelWorkGroupSize = 295,
293 SpvOpGetKernelPreferredWorkGroupSizeMultiple = 296,
294 SpvOpRetainEvent = 297,
295 SpvOpReleaseEvent = 298,
296 SpvOpCreateUserEvent = 299,
297 SpvOpIsValidEvent = 300,
298 SpvOpSetUserEventStatus = 301,
299 SpvOpCaptureEventProfilingInfo = 302,
300 SpvOpGetDefaultQueue = 303,
301 SpvOpBuildNDRange = 304,
302 SpvOpImageSparseSampleImplicitLod = 305,
303 SpvOpImageSparseSampleExplicitLod = 306,
304 SpvOpImageSparseSampleDrefImplicitLod = 307,
305 SpvOpImageSparseSampleDrefExplicitLod = 308,
306 SpvOpImageSparseSampleProjImplicitLod = 309,
307 SpvOpImageSparseSampleProjExplicitLod = 310,
308 SpvOpImageSparseSampleProjDrefImplicitLod = 311,
309 SpvOpImageSparseSampleProjDrefExplicitLod = 312,
310 SpvOpImageSparseFetch = 313,
311 SpvOpImageSparseGather = 314,
312 SpvOpImageSparseDrefGather = 315,
313 SpvOpImageSparseTexelsResident = 316,
314 SpvOpNoLine = 317,
315 SpvOpAtomicFlagTestAndSet = 318,
316 SpvOpAtomicFlagClear = 319,
317 SpvOpImageSparseRead = 320,
318 SpvOpSizeOf = 321,
319 SpvOpTypePipeStorage = 322,
320 SpvOpConstantPipeStorage = 323,
321 SpvOpCreatePipeFromPipeStorage = 324,
322 SpvOpGetKernelLocalSizeForSubgroupCount = 325,
323 SpvOpGetKernelMaxNumSubgroups = 326,
324 SpvOpTypeNamedBarrier = 327,
325 SpvOpNamedBarrierInitialize = 328,
326 SpvOpMemoryNamedBarrier = 329,
327 SpvOpModuleProcessed = 330,
328 };
329 static const int kKnownOpsCount = SpvOpModuleProcessed+1;
330
331
332 static const char* kSpirvOpNames[] =
333 {
334 "Nop",
335 "Undef",
336 "SourceContinued",
337 "Source",
338 "SourceExtension",
339 "Name",
340 "MemberName",
341 "String",
342 "Line",
343 "#9",
344 "Extension",
345 "ExtInstImport",
346 "ExtInst",
347 "VectorShuffleCompact",
348 "MemoryModel",
349 "EntryPoint",
350 "ExecutionMode",
351 "Capability",
352 "#18",
353 "TypeVoid",
354 "TypeBool",
355 "TypeInt",
356 "TypeFloat",
357 "TypeVector",
358 "TypeMatrix",
359 "TypeImage",
360 "TypeSampler",
361 "TypeSampledImage",
362 "TypeArray",
363 "TypeRuntimeArray",
364 "TypeStruct",
365 "TypeOpaque",
366 "TypePointer",
367 "TypeFunction",
368 "TypeEvent",
369 "TypeDeviceEvent",
370 "TypeReserveId",
371 "TypeQueue",
372 "TypePipe",
373 "TypeForwardPointer",
374 "#40",
375 "ConstantTrue",
376 "ConstantFalse",
377 "Constant",
378 "ConstantComposite",
379 "ConstantSampler",
380 "ConstantNull",
381 "#47",
382 "SpecConstantTrue",
383 "SpecConstantFalse",
384 "SpecConstant",
385 "SpecConstantComposite",
386 "SpecConstantOp",
387 "#53",
388 "Function",
389 "FunctionParameter",
390 "FunctionEnd",
391 "FunctionCall",
392 "#58",
393 "Variable",
394 "ImageTexelPointer",
395 "Load",
396 "Store",
397 "CopyMemory",
398 "CopyMemorySized",
399 "AccessChain",
400 "InBoundsAccessChain",
401 "PtrAccessChain",
402 "ArrayLength",
403 "GenericPtrMemSemantics",
404 "InBoundsPtrAccessChain",
405 "Decorate",
406 "MemberDecorate",
407 "DecorationGroup",
408 "GroupDecorate",
409 "GroupMemberDecorate",
410 "#76",
411 "VectorExtractDynamic",
412 "VectorInsertDynamic",
413 "VectorShuffle",
414 "CompositeConstruct",
415 "CompositeExtract",
416 "CompositeInsert",
417 "CopyObject",
418 "Transpose",
419 "#85",
420 "SampledImage",
421 "ImageSampleImplicitLod",
422 "ImageSampleExplicitLod",
423 "ImageSampleDrefImplicitLod",
424 "ImageSampleDrefExplicitLod",
425 "ImageSampleProjImplicitLod",
426 "ImageSampleProjExplicitLod",
427 "ImageSampleProjDrefImplicitLod",
428 "ImageSampleProjDrefExplicitLod",
429 "ImageFetch",
430 "ImageGather",
431 "ImageDrefGather",
432 "ImageRead",
433 "ImageWrite",
434 "Image",
435 "ImageQueryFormat",
436 "ImageQueryOrder",
437 "ImageQuerySizeLod",
438 "ImageQuerySize",
439 "ImageQueryLod",
440 "ImageQueryLevels",
441 "ImageQuerySamples",
442 "#108",
443 "ConvertFToU",
444 "ConvertFToS",
445 "ConvertSToF",
446 "ConvertUToF",
447 "UConvert",
448 "SConvert",
449 "FConvert",
450 "QuantizeToF16",
451 "ConvertPtrToU",
452 "SatConvertSToU",
453 "SatConvertUToS",
454 "ConvertUToPtr",
455 "PtrCastToGeneric",
456 "GenericCastToPtr",
457 "GenericCastToPtrExplicit",
458 "Bitcast",
459 "#125",
460 "SNegate",
461 "FNegate",
462 "IAdd",
463 "FAdd",
464 "ISub",
465 "FSub",
466 "IMul",
467 "FMul",
468 "UDiv",
469 "SDiv",
470 "FDiv",
471 "UMod",
472 "SRem",
473 "SMod",
474 "FRem",
475 "FMod",
476 "VectorTimesScalar",
477 "MatrixTimesScalar",
478 "VectorTimesMatrix",
479 "MatrixTimesVector",
480 "MatrixTimesMatrix",
481 "OuterProduct",
482 "Dot",
483 "IAddCarry",
484 "ISubBorrow",
485 "UMulExtended",
486 "SMulExtended",
487 "#153",
488 "Any",
489 "All",
490 "IsNan",
491 "IsInf",
492 "IsFinite",
493 "IsNormal",
494 "SignBitSet",
495 "LessOrGreater",
496 "Ordered",
497 "Unordered",
498 "LogicalEqual",
499 "LogicalNotEqual",
500 "LogicalOr",
501 "LogicalAnd",
502 "LogicalNot",
503 "Select",
504 "IEqual",
505 "INotEqual",
506 "UGreaterThan",
507 "SGreaterThan",
508 "UGreaterThanEqual",
509 "SGreaterThanEqual",
510 "ULessThan",
511 "SLessThan",
512 "ULessThanEqual",
513 "SLessThanEqual",
514 "FOrdEqual",
515 "FUnordEqual",
516 "FOrdNotEqual",
517 "FUnordNotEqual",
518 "FOrdLessThan",
519 "FUnordLessThan",
520 "FOrdGreaterThan",
521 "FUnordGreaterThan",
522 "FOrdLessThanEqual",
523 "FUnordLessThanEqual",
524 "FOrdGreaterThanEqual",
525 "FUnordGreaterThanEqual",
526 "#192",
527 "#193",
528 "ShiftRightLogical",
529 "ShiftRightArithmetic",
530 "ShiftLeftLogical",
531 "BitwiseOr",
532 "BitwiseXor",
533 "BitwiseAnd",
534 "Not",
535 "BitFieldInsert",
536 "BitFieldSExtract",
537 "BitFieldUExtract",
538 "BitReverse",
539 "BitCount",
540 "#206",
541 "DPdx",
542 "DPdy",
543 "Fwidth",
544 "DPdxFine",
545 "DPdyFine",
546 "FwidthFine",
547 "DPdxCoarse",
548 "DPdyCoarse",
549 "FwidthCoarse",
550 "#216",
551 "#217",
552 "EmitVertex",
553 "EndPrimitive",
554 "EmitStreamVertex",
555 "EndStreamPrimitive",
556 "#222",
557 "#223",
558 "ControlBarrier",
559 "MemoryBarrier",
560 "#226",
561 "AtomicLoad",
562 "AtomicStore",
563 "AtomicExchange",
564 "AtomicCompareExchange",
565 "AtomicCompareExchangeWeak",
566 "AtomicIIncrement",
567 "AtomicIDecrement",
568 "AtomicIAdd",
569 "AtomicISub",
570 "AtomicSMin",
571 "AtomicUMin",
572 "AtomicSMax",
573 "AtomicUMax",
574 "AtomicAnd",
575 "AtomicOr",
576 "AtomicXor",
577 "#243",
578 "#244",
579 "Phi",
580 "LoopMerge",
581 "SelectionMerge",
582 "Label",
583 "Branch",
584 "BranchConditional",
585 "Switch",
586 "Kill",
587 "Return",
588 "ReturnValue",
589 "Unreachable",
590 "LifetimeStart",
591 "LifetimeStop",
592 "#258",
593 "GroupAsyncCopy",
594 "GroupWaitEvents",
595 "GroupAll",
596 "GroupAny",
597 "GroupBroadcast",
598 "GroupIAdd",
599 "GroupFAdd",
600 "GroupFMin",
601 "GroupUMin",
602 "GroupSMin",
603 "GroupFMax",
604 "GroupUMax",
605 "GroupSMax",
606 "#272",
607 "#273",
608 "ReadPipe",
609 "WritePipe",
610 "ReservedReadPipe",
611 "ReservedWritePipe",
612 "ReserveReadPipePackets",
613 "ReserveWritePipePackets",
614 "CommitReadPipe",
615 "CommitWritePipe",
616 "IsValidReserveId",
617 "GetNumPipePackets",
618 "GetMaxPipePackets",
619 "GroupReserveReadPipePackets",
620 "GroupReserveWritePipePackets",
621 "GroupCommitReadPipe",
622 "GroupCommitWritePipe",
623 "#289",
624 "#290",
625 "EnqueueMarker",
626 "EnqueueKernel",
627 "GetKernelNDrangeSubGroupCount",
628 "GetKernelNDrangeMaxSubGroupSize",
629 "GetKernelWorkGroupSize",
630 "GetKernelPreferredWorkGroupSizeMultiple",
631 "RetainEvent",
632 "ReleaseEvent",
633 "CreateUserEvent",
634 "IsValidEvent",
635 "SetUserEventStatus",
636 "CaptureEventProfilingInfo",
637 "GetDefaultQueue",
638 "BuildNDRange",
639 "ImageSparseSampleImplicitLod",
640 "ImageSparseSampleExplicitLod",
641 "ImageSparseSampleDrefImplicitLod",
642 "ImageSparseSampleDrefExplicitLod",
643 "ImageSparseSampleProjImplicitLod",
644 "ImageSparseSampleProjExplicitLod",
645 "ImageSparseSampleProjDrefImplicitLod",
646 "ImageSparseSampleProjDrefExplicitLod",
647 "ImageSparseFetch",
648 "ImageSparseGather",
649 "ImageSparseDrefGather",
650 "ImageSparseTexelsResident",
651 "NoLine",
652 "AtomicFlagTestAndSet",
653 "AtomicFlagClear",
654 "ImageSparseRead",
655 "SizeOf",
656 "TypePipeStorage",
657 "ConstantPipeStorage",
658 "CreatePipeFromPipeStorage",
659 "GetKernelLocalSizeForSubgroupCount",
660 "GetKernelMaxNumSubgroups",
661 "TypeNamedBarrier",
662 "NamedBarrierInitialize",
663 "MemoryNamedBarrier",
664 "ModuleProcessed",
665 };
666 static_assert(_SMOLV_ARRAY_SIZE(kSpirvOpNames) == kKnownOpsCount, "kSpirvOpNames table mismatch with known SpvOps");
667
668
669 struct OpData
670 {
671 uint8_t hasResult; // does it have result ID?
672 uint8_t hasType; // does it have type ID?
673 uint8_t deltaFromResult; // How many words after (optional) type+result to write out as deltas from result?
674 uint8_t varrest; // should the rest of words be written in varint encoding?
675 };
676 static const OpData kSpirvOpData[] =
677 {
678 {0, 0, 0, 0}, // Nop
679 {1, 1, 0, 0}, // Undef
680 {0, 0, 0, 0}, // SourceContinued
681 {0, 0, 0, 1}, // Source
682 {0, 0, 0, 0}, // SourceExtension
683 {0, 0, 0, 0}, // Name
684 {0, 0, 0, 0}, // MemberName
685 {0, 0, 0, 0}, // String
686 {0, 0, 0, 1}, // Line
687 {1, 1, 0, 0}, // #9
688 {0, 0, 0, 0}, // Extension
689 {1, 0, 0, 0}, // ExtInstImport
690 {1, 1, 0, 1}, // ExtInst
691 {1, 1, 2, 1}, // VectorShuffleCompact - new in SMOLV
692 {0, 0, 0, 1}, // MemoryModel
693 {0, 0, 0, 1}, // EntryPoint
694 {0, 0, 0, 1}, // ExecutionMode
695 {0, 0, 0, 1}, // Capability
696 {1, 1, 0, 0}, // #18
697 {1, 0, 0, 1}, // TypeVoid
698 {1, 0, 0, 1}, // TypeBool
699 {1, 0, 0, 1}, // TypeInt
700 {1, 0, 0, 1}, // TypeFloat
701 {1, 0, 0, 1}, // TypeVector
702 {1, 0, 0, 1}, // TypeMatrix
703 {1, 0, 0, 1}, // TypeImage
704 {1, 0, 0, 1}, // TypeSampler
705 {1, 0, 0, 1}, // TypeSampledImage
706 {1, 0, 0, 1}, // TypeArray
707 {1, 0, 0, 1}, // TypeRuntimeArray
708 {1, 0, 0, 1}, // TypeStruct
709 {1, 0, 0, 1}, // TypeOpaque
710 {1, 0, 0, 1}, // TypePointer
711 {1, 0, 0, 1}, // TypeFunction
712 {1, 0, 0, 1}, // TypeEvent
713 {1, 0, 0, 1}, // TypeDeviceEvent
714 {1, 0, 0, 1}, // TypeReserveId
715 {1, 0, 0, 1}, // TypeQueue
716 {1, 0, 0, 1}, // TypePipe
717 {0, 0, 0, 1}, // TypeForwardPointer
718 {1, 1, 0, 0}, // #40
719 {1, 1, 0, 0}, // ConstantTrue
720 {1, 1, 0, 0}, // ConstantFalse
721 {1, 1, 0, 0}, // Constant
722 {1, 1, 9, 0}, // ConstantComposite
723 {1, 1, 0, 1}, // ConstantSampler
724 {1, 1, 0, 0}, // ConstantNull
725 {1, 1, 0, 0}, // #47
726 {1, 1, 0, 0}, // SpecConstantTrue
727 {1, 1, 0, 0}, // SpecConstantFalse
728 {1, 1, 0, 0}, // SpecConstant
729 {1, 1, 9, 0}, // SpecConstantComposite
730 {1, 1, 0, 0}, // SpecConstantOp
731 {1, 1, 0, 0}, // #53
732 {1, 1, 0, 1}, // Function
733 {1, 1, 0, 0}, // FunctionParameter
734 {0, 0, 0, 0}, // FunctionEnd
735 {1, 1, 9, 0}, // FunctionCall
736 {1, 1, 0, 0}, // #58
737 {1, 1, 0, 1}, // Variable
738 {1, 1, 0, 0}, // ImageTexelPointer
739 {1, 1, 1, 1}, // Load
740 {0, 0, 2, 1}, // Store
741 {0, 0, 0, 0}, // CopyMemory
742 {0, 0, 0, 0}, // CopyMemorySized
743 {1, 1, 0, 1}, // AccessChain
744 {1, 1, 0, 0}, // InBoundsAccessChain
745 {1, 1, 0, 0}, // PtrAccessChain
746 {1, 1, 0, 0}, // ArrayLength
747 {1, 1, 0, 0}, // GenericPtrMemSemantics
748 {1, 1, 0, 0}, // InBoundsPtrAccessChain
749 {0, 0, 0, 1}, // Decorate
750 {0, 0, 0, 1}, // MemberDecorate
751 {1, 0, 0, 0}, // DecorationGroup
752 {0, 0, 0, 0}, // GroupDecorate
753 {0, 0, 0, 0}, // GroupMemberDecorate
754 {1, 1, 0, 0}, // #76
755 {1, 1, 1, 1}, // VectorExtractDynamic
756 {1, 1, 2, 1}, // VectorInsertDynamic
757 {1, 1, 2, 1}, // VectorShuffle
758 {1, 1, 9, 0}, // CompositeConstruct
759 {1, 1, 1, 1}, // CompositeExtract
760 {1, 1, 2, 1}, // CompositeInsert
761 {1, 1, 1, 0}, // CopyObject
762 {1, 1, 0, 0}, // Transpose
763 {1, 1, 0, 0}, // #85
764 {1, 1, 0, 0}, // SampledImage
765 {1, 1, 2, 1}, // ImageSampleImplicitLod
766 {1, 1, 2, 1}, // ImageSampleExplicitLod
767 {1, 1, 3, 1}, // ImageSampleDrefImplicitLod
768 {1, 1, 3, 1}, // ImageSampleDrefExplicitLod
769 {1, 1, 2, 1}, // ImageSampleProjImplicitLod
770 {1, 1, 2, 1}, // ImageSampleProjExplicitLod
771 {1, 1, 3, 1}, // ImageSampleProjDrefImplicitLod
772 {1, 1, 3, 1}, // ImageSampleProjDrefExplicitLod
773 {1, 1, 2, 1}, // ImageFetch
774 {1, 1, 3, 1}, // ImageGather
775 {1, 1, 3, 1}, // ImageDrefGather
776 {1, 1, 2, 1}, // ImageRead
777 {0, 0, 3, 1}, // ImageWrite
778 {1, 1, 1, 0}, // Image
779 {1, 1, 1, 0}, // ImageQueryFormat
780 {1, 1, 1, 0}, // ImageQueryOrder
781 {1, 1, 2, 0}, // ImageQuerySizeLod
782 {1, 1, 1, 0}, // ImageQuerySize
783 {1, 1, 2, 0}, // ImageQueryLod
784 {1, 1, 1, 0}, // ImageQueryLevels
785 {1, 1, 1, 0}, // ImageQuerySamples
786 {1, 1, 0, 0}, // #108
787 {1, 1, 1, 0}, // ConvertFToU
788 {1, 1, 1, 0}, // ConvertFToS
789 {1, 1, 1, 0}, // ConvertSToF
790 {1, 1, 1, 0}, // ConvertUToF
791 {1, 1, 1, 0}, // UConvert
792 {1, 1, 1, 0}, // SConvert
793 {1, 1, 1, 0}, // FConvert
794 {1, 1, 1, 0}, // QuantizeToF16
795 {1, 1, 1, 0}, // ConvertPtrToU
796 {1, 1, 1, 0}, // SatConvertSToU
797 {1, 1, 1, 0}, // SatConvertUToS
798 {1, 1, 1, 0}, // ConvertUToPtr
799 {1, 1, 1, 0}, // PtrCastToGeneric
800 {1, 1, 1, 0}, // GenericCastToPtr
801 {1, 1, 1, 1}, // GenericCastToPtrExplicit
802 {1, 1, 1, 0}, // Bitcast
803 {1, 1, 0, 0}, // #125
804 {1, 1, 1, 0}, // SNegate
805 {1, 1, 1, 0}, // FNegate
806 {1, 1, 2, 0}, // IAdd
807 {1, 1, 2, 0}, // FAdd
808 {1, 1, 2, 0}, // ISub
809 {1, 1, 2, 0}, // FSub
810 {1, 1, 2, 0}, // IMul
811 {1, 1, 2, 0}, // FMul
812 {1, 1, 2, 0}, // UDiv
813 {1, 1, 2, 0}, // SDiv
814 {1, 1, 2, 0}, // FDiv
815 {1, 1, 2, 0}, // UMod
816 {1, 1, 2, 0}, // SRem
817 {1, 1, 2, 0}, // SMod
818 {1, 1, 2, 0}, // FRem
819 {1, 1, 2, 0}, // FMod
820 {1, 1, 2, 0}, // VectorTimesScalar
821 {1, 1, 2, 0}, // MatrixTimesScalar
822 {1, 1, 2, 0}, // VectorTimesMatrix
823 {1, 1, 2, 0}, // MatrixTimesVector
824 {1, 1, 2, 0}, // MatrixTimesMatrix
825 {1, 1, 2, 0}, // OuterProduct
826 {1, 1, 2, 0}, // Dot
827 {1, 1, 2, 0}, // IAddCarry
828 {1, 1, 2, 0}, // ISubBorrow
829 {1, 1, 2, 0}, // UMulExtended
830 {1, 1, 2, 0}, // SMulExtended
831 {1, 1, 0, 0}, // #153
832 {1, 1, 1, 0}, // Any
833 {1, 1, 1, 0}, // All
834 {1, 1, 1, 0}, // IsNan
835 {1, 1, 1, 0}, // IsInf
836 {1, 1, 1, 0}, // IsFinite
837 {1, 1, 1, 0}, // IsNormal
838 {1, 1, 1, 0}, // SignBitSet
839 {1, 1, 2, 0}, // LessOrGreater
840 {1, 1, 2, 0}, // Ordered
841 {1, 1, 2, 0}, // Unordered
842 {1, 1, 2, 0}, // LogicalEqual
843 {1, 1, 2, 0}, // LogicalNotEqual
844 {1, 1, 2, 0}, // LogicalOr
845 {1, 1, 2, 0}, // LogicalAnd
846 {1, 1, 1, 0}, // LogicalNot
847 {1, 1, 3, 0}, // Select
848 {1, 1, 2, 0}, // IEqual
849 {1, 1, 2, 0}, // INotEqual
850 {1, 1, 2, 0}, // UGreaterThan
851 {1, 1, 2, 0}, // SGreaterThan
852 {1, 1, 2, 0}, // UGreaterThanEqual
853 {1, 1, 2, 0}, // SGreaterThanEqual
854 {1, 1, 2, 0}, // ULessThan
855 {1, 1, 2, 0}, // SLessThan
856 {1, 1, 2, 0}, // ULessThanEqual
857 {1, 1, 2, 0}, // SLessThanEqual
858 {1, 1, 2, 0}, // FOrdEqual
859 {1, 1, 2, 0}, // FUnordEqual
860 {1, 1, 2, 0}, // FOrdNotEqual
861 {1, 1, 2, 0}, // FUnordNotEqual
862 {1, 1, 2, 0}, // FOrdLessThan
863 {1, 1, 2, 0}, // FUnordLessThan
864 {1, 1, 2, 0}, // FOrdGreaterThan
865 {1, 1, 2, 0}, // FUnordGreaterThan
866 {1, 1, 2, 0}, // FOrdLessThanEqual
867 {1, 1, 2, 0}, // FUnordLessThanEqual
868 {1, 1, 2, 0}, // FOrdGreaterThanEqual
869 {1, 1, 2, 0}, // FUnordGreaterThanEqual
870 {1, 1, 0, 0}, // #192
871 {1, 1, 0, 0}, // #193
872 {1, 1, 2, 0}, // ShiftRightLogical
873 {1, 1, 2, 0}, // ShiftRightArithmetic
874 {1, 1, 2, 0}, // ShiftLeftLogical
875 {1, 1, 2, 0}, // BitwiseOr
876 {1, 1, 2, 0}, // BitwiseXor
877 {1, 1, 2, 0}, // BitwiseAnd
878 {1, 1, 1, 0}, // Not
879 {1, 1, 4, 0}, // BitFieldInsert
880 {1, 1, 3, 0}, // BitFieldSExtract
881 {1, 1, 3, 0}, // BitFieldUExtract
882 {1, 1, 1, 0}, // BitReverse
883 {1, 1, 1, 0}, // BitCount
884 {1, 1, 0, 0}, // #206
885 {1, 1, 0, 0}, // DPdx
886 {1, 1, 0, 0}, // DPdy
887 {1, 1, 0, 0}, // Fwidth
888 {1, 1, 0, 0}, // DPdxFine
889 {1, 1, 0, 0}, // DPdyFine
890 {1, 1, 0, 0}, // FwidthFine
891 {1, 1, 0, 0}, // DPdxCoarse
892 {1, 1, 0, 0}, // DPdyCoarse
893 {1, 1, 0, 0}, // FwidthCoarse
894 {1, 1, 0, 0}, // #216
895 {1, 1, 0, 0}, // #217
896 {0, 0, 0, 0}, // EmitVertex
897 {0, 0, 0, 0}, // EndPrimitive
898 {0, 0, 0, 0}, // EmitStreamVertex
899 {0, 0, 0, 0}, // EndStreamPrimitive
900 {1, 1, 0, 0}, // #222
901 {1, 1, 0, 0}, // #223
902 {0, 0, 3, 0}, // ControlBarrier
903 {0, 0, 2, 0}, // MemoryBarrier
904 {1, 1, 0, 0}, // #226
905 {1, 1, 0, 0}, // AtomicLoad
906 {0, 0, 0, 0}, // AtomicStore
907 {1, 1, 0, 0}, // AtomicExchange
908 {1, 1, 0, 0}, // AtomicCompareExchange
909 {1, 1, 0, 0}, // AtomicCompareExchangeWeak
910 {1, 1, 0, 0}, // AtomicIIncrement
911 {1, 1, 0, 0}, // AtomicIDecrement
912 {1, 1, 0, 0}, // AtomicIAdd
913 {1, 1, 0, 0}, // AtomicISub
914 {1, 1, 0, 0}, // AtomicSMin
915 {1, 1, 0, 0}, // AtomicUMin
916 {1, 1, 0, 0}, // AtomicSMax
917 {1, 1, 0, 0}, // AtomicUMax
918 {1, 1, 0, 0}, // AtomicAnd
919 {1, 1, 0, 0}, // AtomicOr
920 {1, 1, 0, 0}, // AtomicXor
921 {1, 1, 0, 0}, // #243
922 {1, 1, 0, 0}, // #244
923 {1, 1, 0, 0}, // Phi
924 {0, 0, 2, 1}, // LoopMerge
925 {0, 0, 1, 1}, // SelectionMerge
926 {1, 0, 0, 0}, // Label
927 {0, 0, 1, 0}, // Branch
928 {0, 0, 3, 1}, // BranchConditional
929 {0, 0, 0, 0}, // Switch
930 {0, 0, 0, 0}, // Kill
931 {0, 0, 0, 0}, // Return
932 {0, 0, 0, 0}, // ReturnValue
933 {0, 0, 0, 0}, // Unreachable
934 {0, 0, 0, 0}, // LifetimeStart
935 {0, 0, 0, 0}, // LifetimeStop
936 {1, 1, 0, 0}, // #258
937 {1, 1, 0, 0}, // GroupAsyncCopy
938 {0, 0, 0, 0}, // GroupWaitEvents
939 {1, 1, 0, 0}, // GroupAll
940 {1, 1, 0, 0}, // GroupAny
941 {1, 1, 0, 0}, // GroupBroadcast
942 {1, 1, 0, 0}, // GroupIAdd
943 {1, 1, 0, 0}, // GroupFAdd
944 {1, 1, 0, 0}, // GroupFMin
945 {1, 1, 0, 0}, // GroupUMin
946 {1, 1, 0, 0}, // GroupSMin
947 {1, 1, 0, 0}, // GroupFMax
948 {1, 1, 0, 0}, // GroupUMax
949 {1, 1, 0, 0}, // GroupSMax
950 {1, 1, 0, 0}, // #272
951 {1, 1, 0, 0}, // #273
952 {1, 1, 0, 0}, // ReadPipe
953 {1, 1, 0, 0}, // WritePipe
954 {1, 1, 0, 0}, // ReservedReadPipe
955 {1, 1, 0, 0}, // ReservedWritePipe
956 {1, 1, 0, 0}, // ReserveReadPipePackets
957 {1, 1, 0, 0}, // ReserveWritePipePackets
958 {0, 0, 0, 0}, // CommitReadPipe
959 {0, 0, 0, 0}, // CommitWritePipe
960 {1, 1, 0, 0}, // IsValidReserveId
961 {1, 1, 0, 0}, // GetNumPipePackets
962 {1, 1, 0, 0}, // GetMaxPipePackets
963 {1, 1, 0, 0}, // GroupReserveReadPipePackets
964 {1, 1, 0, 0}, // GroupReserveWritePipePackets
965 {0, 0, 0, 0}, // GroupCommitReadPipe
966 {0, 0, 0, 0}, // GroupCommitWritePipe
967 {1, 1, 0, 0}, // #289
968 {1, 1, 0, 0}, // #290
969 {1, 1, 0, 0}, // EnqueueMarker
970 {1, 1, 0, 0}, // EnqueueKernel
971 {1, 1, 0, 0}, // GetKernelNDrangeSubGroupCount
972 {1, 1, 0, 0}, // GetKernelNDrangeMaxSubGroupSize
973 {1, 1, 0, 0}, // GetKernelWorkGroupSize
974 {1, 1, 0, 0}, // GetKernelPreferredWorkGroupSizeMultiple
975 {0, 0, 0, 0}, // RetainEvent
976 {0, 0, 0, 0}, // ReleaseEvent
977 {1, 1, 0, 0}, // CreateUserEvent
978 {1, 1, 0, 0}, // IsValidEvent
979 {0, 0, 0, 0}, // SetUserEventStatus
980 {0, 0, 0, 0}, // CaptureEventProfilingInfo
981 {1, 1, 0, 0}, // GetDefaultQueue
982 {1, 1, 0, 0}, // BuildNDRange
983 {1, 1, 2, 1}, // ImageSparseSampleImplicitLod
984 {1, 1, 2, 1}, // ImageSparseSampleExplicitLod
985 {1, 1, 3, 1}, // ImageSparseSampleDrefImplicitLod
986 {1, 1, 3, 1}, // ImageSparseSampleDrefExplicitLod
987 {1, 1, 2, 1}, // ImageSparseSampleProjImplicitLod
988 {1, 1, 2, 1}, // ImageSparseSampleProjExplicitLod
989 {1, 1, 3, 1}, // ImageSparseSampleProjDrefImplicitLod
990 {1, 1, 3, 1}, // ImageSparseSampleProjDrefExplicitLod
991 {1, 1, 2, 1}, // ImageSparseFetch
992 {1, 1, 3, 1}, // ImageSparseGather
993 {1, 1, 3, 1}, // ImageSparseDrefGather
994 {1, 1, 1, 0}, // ImageSparseTexelsResident
995 {0, 0, 0, 0}, // NoLine
996 {1, 1, 0, 0}, // AtomicFlagTestAndSet
997 {0, 0, 0, 0}, // AtomicFlagClear
998 {1, 1, 0, 0}, // ImageSparseRead
999 {1, 1, 0, 0}, // SizeOf
1000 {1, 1, 0, 0}, // TypePipeStorage
1001 {1, 1, 0, 0}, // ConstantPipeStorage
1002 {1, 1, 0, 0}, // CreatePipeFromPipeStorage
1003 {1, 1, 0, 0}, // GetKernelLocalSizeForSubgroupCount
1004 {1, 1, 0, 0}, // GetKernelMaxNumSubgroups
1005 {1, 1, 0, 0}, // TypeNamedBarrier
1006 {1, 1, 0, 1}, // NamedBarrierInitialize
1007 {0, 0, 2, 1}, // MemoryNamedBarrier
1008 {1, 1, 0, 0}, // ModuleProcessed
1009 };
1010 static_assert(_SMOLV_ARRAY_SIZE(kSpirvOpData) == kKnownOpsCount, "kSpirvOpData table mismatch with known SpvOps");
1011
1012
1013 static bool smolv_OpHasResult(SpvOp op)
1014 {
1015 if (op < 0 || op >= kKnownOpsCount)
1016 return false;
1017 return kSpirvOpData[op].hasResult != 0;
1018 }
1019
1020 static bool smolv_OpHasType(SpvOp op)
1021 {
1022 if (op < 0 || op >= kKnownOpsCount)
1023 return false;
1024 return kSpirvOpData[op].hasType != 0;
1025 }
1026
1027 static int smolv_OpDeltaFromResult(SpvOp op)
1028 {
1029 if (op < 0 || op >= kKnownOpsCount)
1030 return 0;
1031 return kSpirvOpData[op].deltaFromResult;
1032 }
1033
1034 static bool smolv_OpVarRest(SpvOp op)
1035 {
1036 if (op < 0 || op >= kKnownOpsCount)
1037 return false;
1038 return kSpirvOpData[op].varrest != 0;
1039 }
1040
1041 static bool smolv_OpDebugInfo(SpvOp op)
1042 {
1043 return
1044 op == SpvOpSourceContinued ||
1045 op == SpvOpSource ||
1046 op == SpvOpSourceExtension ||
1047 op == SpvOpName ||
1048 op == SpvOpMemberName ||
1049 op == SpvOpString ||
1050 op == SpvOpLine ||
1051 op == SpvOpNoLine ||
1052 op == SpvOpModuleProcessed;
1053 }
1054
1055
1056 static int smolv_DecorationExtraOps(int dec)
1057 {
1058 if (dec == 0 || (dec >= 2 && dec <= 5)) // RelaxedPrecision, Block..ColMajor
1059 return 0;
1060 if (dec >= 29 && dec <= 37) // Stream..XfbStride
1061 return 1;
1062 return -1; // unknown, encode length
1063 }
1064
1065
1066 // --------------------------------------------------------------------------------------------
1067
1068
1069 static bool smolv_CheckGenericHeader(const uint32_t* words, size_t wordCount, uint32_t expectedMagic)
1070 {
1071 if (!words)
1072 return false;
1073 if (wordCount < 5)
1074 return false;
1075
1076 uint32_t headerMagic = words[0];
1077 if (headerMagic != expectedMagic)
1078 return false;
1079 uint32_t headerVersion = words[1];
1080 if (headerVersion < 0x00010000 || headerVersion > 0x00010300)
1081 return false; // only support 1.0 through 1.3
1082
1083 return true;
1084 }
1085
1086 static const int kSpirVHeaderMagic = 0x07230203;
1087 static const int kSmolHeaderMagic = 0x534D4F4C; // "SMOL"
1088
1089 static bool smolv_CheckSpirVHeader(const uint32_t* words, size_t wordCount)
1090 {
1091 //@TODO: if SPIR-V header magic was reversed, that means the file got written
1092 // in a "big endian" order. Need to byteswap all words then.
1093 return smolv_CheckGenericHeader(words, wordCount, kSpirVHeaderMagic);
1094 }
1095 static bool smolv_CheckSmolHeader(const uint8_t* bytes, size_t byteCount)
1096 {
1097 if (!smolv_CheckGenericHeader((const uint32_t*)bytes, byteCount/4, kSmolHeaderMagic))
1098 return false;
1099 if (byteCount < 24) // one more word past header to store decoded length
1100 return false;
1101 return true;
1102 }
1103
1104
1105 static void smolv_Write4(smolv::ByteArray& arr, uint32_t v)
1106 {
1107 arr.push_back(v & 0xFF);
1108 arr.push_back((v >> 8) & 0xFF);
1109 arr.push_back((v >> 16) & 0xFF);
1110 arr.push_back(v >> 24);
1111 }
1112
1113 static void smolv_Write4(uint8_t*& buf, uint32_t v)
1114 {
1115 memcpy(buf, &v, 4);
1116 buf += 4;
1117 }
1118
1119
1120 static bool smolv_Read4(const uint8_t*& data, const uint8_t* dataEnd, uint32_t& outv)
1121 {
1122 if (data + 4 > dataEnd)
1123 return false;
1124 outv = (data[0]) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1125 data += 4;
1126 return true;
1127 }
1128
1129
1130 // --------------------------------------------------------------------------------------------
1131
1132 // Variable-length integer encoding for unsigned integers. In each byte:
1133 // - highest bit set if more bytes follow, cleared if this is last byte.
1134 // - other 7 bits are the actual value payload.
1135 // Takes 1-5 bytes to encode an integer (values between 0 and 127 take one byte, etc.).
1136
1137 static void smolv_WriteVarint(smolv::ByteArray& arr, uint32_t v)
1138 {
1139 while (v > 127)
1140 {
1141 arr.push_back((v & 127) | 128);
1142 v >>= 7;
1143 }
1144 arr.push_back(v & 127);
1145 }
1146
1147 static bool smolv_ReadVarint(const uint8_t*& data, const uint8_t* dataEnd, uint32_t& outVal)
1148 {
1149 uint32_t v = 0;
1150 uint32_t shift = 0;
1151 while (data < dataEnd)
1152 {
1153 uint8_t b = *data;
1154 v |= (b & 127) << shift;
1155 shift += 7;
1156 data++;
1157 if (!(b & 128))
1158 break;
1159 }
1160 outVal = v;
1161 return true; //@TODO: report failures
1162 }
1163
1164 static uint32_t smolv_ZigEncode(int32_t i)
1165 {
1166 return (uint32_t(i) << 1) ^ (i >> 31);
1167 }
1168
1169 static int32_t smolv_ZigDecode(uint32_t u)
1170 {
1171 return (u & 1) ? ((u >> 1) ^ ~0) : (u >> 1);
1172 }
1173
1174
1175 // Remap most common Op codes (Load, Store, Decorate, VectorShuffle etc.) to be in < 16 range, for
1176 // more compact varint encoding. This basically swaps rarely used op values that are < 16 with the
1177 // ones that are common.
1178
1179 static SpvOp smolv_RemapOp(SpvOp op)
1180 {
1181 # define _SMOLV_SWAP_OP(op1,op2) if (op==op1) return op2; if (op==op2) return op1
1182 _SMOLV_SWAP_OP(SpvOpDecorate,SpvOpNop); // 0: 24%
1183 _SMOLV_SWAP_OP(SpvOpLoad,SpvOpUndef); // 1: 17%
1184 _SMOLV_SWAP_OP(SpvOpStore,SpvOpSourceContinued); // 2: 9%
1185 _SMOLV_SWAP_OP(SpvOpAccessChain,SpvOpSource); // 3: 7.2%
1186 _SMOLV_SWAP_OP(SpvOpVectorShuffle,SpvOpSourceExtension); // 4: 5.0%
1187 // Name - already small enum value - 5: 4.4%
1188 // MemberName - already small enum value - 6: 2.9%
1189 _SMOLV_SWAP_OP(SpvOpMemberDecorate,SpvOpString); // 7: 4.0%
1190 _SMOLV_SWAP_OP(SpvOpLabel,SpvOpLine); // 8: 0.9%
1191 _SMOLV_SWAP_OP(SpvOpVariable,(SpvOp)9); // 9: 3.9%
1192 _SMOLV_SWAP_OP(SpvOpFMul,SpvOpExtension); // 10: 3.9%
1193 _SMOLV_SWAP_OP(SpvOpFAdd,SpvOpExtInstImport); // 11: 2.5%
1194 // ExtInst - already small enum value - 12: 1.2%
1195 // VectorShuffleCompact - already small enum value - used for compact shuffle encoding
1196 _SMOLV_SWAP_OP(SpvOpTypePointer,SpvOpMemoryModel); // 14: 2.2%
1197 _SMOLV_SWAP_OP(SpvOpFNegate,SpvOpEntryPoint); // 15: 1.1%
1198 # undef _SMOLV_SWAP_OP
1199 return op;
1200 }
1201
1202
1203 // For most compact varint encoding of common instructions, the instruction length should come out
1204 // into 3 bits (be <8). SPIR-V instruction lengths are always at least 1, and for some other
1205 // instructions they are guaranteed to be some other minimum length. Adjust the length before encoding,
1206 // and after decoding accordingly.
1207
1208 static uint32_t smolv_EncodeLen(SpvOp op, uint32_t len)
1209 {
1210 len--;
1211 if (op == SpvOpVectorShuffle) len -= 4;
1212 if (op == SpvOpVectorShuffleCompact) len -= 4;
1213 if (op == SpvOpDecorate) len -= 2;
1214 if (op == SpvOpLoad) len -= 3;
1215 if (op == SpvOpAccessChain) len -= 3;
1216 return len;
1217 }
1218
1219 static uint32_t smolv_DecodeLen(SpvOp op, uint32_t len)
1220 {
1221 len++;
1222 if (op == SpvOpVectorShuffle) len += 4;
1223 if (op == SpvOpVectorShuffleCompact) len += 4;
1224 if (op == SpvOpDecorate) len += 2;
1225 if (op == SpvOpLoad) len += 3;
1226 if (op == SpvOpAccessChain) len += 3;
1227 return len;
1228 }
1229
1230
1231 // Shuffling bits of length + opcode to be more compact in varint encoding in typical cases:
1232 // 0x LLLL OOOO is how SPIR-V encodes it (L=length, O=op), we shuffle into:
1233 // 0x LLLO OOLO, so that common case (op<16, len<8) is encoded into one byte.
1234
1235 static void smolv_WriteLengthOp(smolv::ByteArray& arr, uint32_t len, SpvOp op)
1236 {
1237 len = smolv_EncodeLen(op, len);
1238 op = smolv_RemapOp(op);
1239 uint32_t oplen = ((len >> 4) << 20) | ((op >> 4) << 8) | ((len & 0xF) << 4) | (op & 0xF);
1240 smolv_WriteVarint(arr, oplen);
1241 }
1242
1243 static bool smolv_ReadLengthOp(const uint8_t*& data, const uint8_t* dataEnd, uint32_t& outLen, SpvOp& outOp)
1244 {
1245 uint32_t val;
1246 if (!smolv_ReadVarint(data, dataEnd, val))
1247 return false;
1248 outLen = ((val >> 20) << 4) | ((val >> 4) & 0xF);
1249 outOp = (SpvOp)(((val >> 4) & 0xFFF0) | (val & 0xF));
1250
1251 outOp = smolv_RemapOp(outOp);
1252 outLen = smolv_DecodeLen(outOp, outLen);
1253 return true;
1254 }
1255
1256
1257
1258 #define _SMOLV_READ_OP(len, words, op) \
1259 uint32_t len = words[0] >> 16; \
1260 if (len < 1) return false; /* malformed instruction, length needs to be at least 1 */ \
1261 if (words + len > wordsEnd) return false; /* malformed instruction, goes past end of data */ \
1262 SpvOp op = (SpvOp)(words[0] & 0xFFFF)
1263
1264
1265 bool smolv::Encode(const void* spirvData, size_t spirvSize, ByteArray& outSmolv, uint32_t flags)
1266 {
1267 const size_t wordCount = spirvSize / 4;
1268 const uint32_t* words = (const uint32_t*)spirvData;
1269 const uint32_t* wordsEnd = words + wordCount;
1270 if (!smolv_CheckSpirVHeader(words, wordCount))
1271 return false;
1272
1273 // reserve space in output (typical compression is to about 30%; reserve half of input space)
1274 outSmolv.reserve(outSmolv.size() + spirvSize/2);
1275
1276 // header
1277 smolv_Write4(outSmolv, kSmolHeaderMagic);
1278 smolv_Write4(outSmolv, words[1]); // version
1279 smolv_Write4(outSmolv, words[2]); // generator
1280 smolv_Write4(outSmolv, words[3]); // bound
1281 smolv_Write4(outSmolv, words[4]); // schema
1282
1283 const size_t headerSpirvSizeOffset = outSmolv.size(); // size field may get updated later if stripping is enabled
1284 smolv_Write4(outSmolv, (uint32_t)spirvSize); // space needed to decode (i.e. original SPIR-V size)
1285
1286 size_t strippedSpirvWordCount = wordCount;
1287 uint32_t prevResult = 0;
1288 uint32_t prevDecorate = 0;
1289
1290 words += 5;
1291 while (words < wordsEnd)
1292 {
1293 _SMOLV_READ_OP(instrLen, words, op);
1294
1295 if ((flags & kEncodeFlagStripDebugInfo) && smolv_OpDebugInfo(op))
1296 {
1297 strippedSpirvWordCount -= instrLen;
1298 words += instrLen;
1299 continue;
1300 }
1301
1302 // A usual case of vector shuffle, with less than 4 components, each with a value
1303 // in [0..3] range: encode it in a more compact form, with the swizzle pattern in one byte.
1304 // Turn this into a VectorShuffleCompact instruction, that takes up unused slot in Ops.
1305 uint32_t swizzle = 0;
1306 if (op == SpvOpVectorShuffle && instrLen <= 9)
1307 {
1308 uint32_t swz0 = instrLen > 5 ? words[5] : 0;
1309 uint32_t swz1 = instrLen > 6 ? words[6] : 0;
1310 uint32_t swz2 = instrLen > 7 ? words[7] : 0;
1311 uint32_t swz3 = instrLen > 8 ? words[8] : 0;
1312 if (swz0 < 4 && swz1 < 4 && swz2 < 4 && swz3 < 4)
1313 {
1314 op = SpvOpVectorShuffleCompact;
1315 swizzle = (swz0 << 6) | (swz1 << 4) | (swz2 << 2) | (swz3);
1316 }
1317 }
1318
1319 // length + opcode
1320 smolv_WriteLengthOp(outSmolv, instrLen, op);
1321
1322 size_t ioffs = 1;
1323 // write type as varint, if we have it
1324 if (smolv_OpHasType(op))
1325 {
1326 smolv_WriteVarint(outSmolv, words[ioffs]);
1327 ioffs++;
1328 }
1329 // write result as delta+zig+varint, if we have it
1330 if (smolv_OpHasResult(op))
1331 {
1332 uint32_t v = words[ioffs];
1333 smolv_WriteVarint(outSmolv, smolv_ZigEncode(v - prevResult)); // some deltas are negative, use zig
1334 prevResult = v;
1335 ioffs++;
1336 }
1337
1338 // Decorate & MemberDecorate: IDs relative to previous decorate
1339 if (op == SpvOpDecorate || op == SpvOpMemberDecorate)
1340 {
1341 uint32_t v = words[ioffs];
1342 smolv_WriteVarint(outSmolv, smolv_ZigEncode(v - prevDecorate)); // spirv-remapped deltas often negative, use zig
1343 prevDecorate = v;
1344 ioffs++;
1345 }
1346
1347 // MemberDecorate special encoding: whole row of MemberDecorate instructions is often referring
1348 // to the same type and linearly increasing member indices. Scan ahead to see how many we have,
1349 // and encode whole bunch as one.
1350 if (op == SpvOpMemberDecorate)
1351 {
1352 // scan ahead until we reach end, non-member-decoration or different type
1353 const uint32_t decorationType = words[ioffs-1];
1354 const uint32_t* memberWords = words;
1355 uint32_t prevIndex = 0;
1356 uint32_t prevOffset = 0;
1357 // write a byte on how many we have encoded as a bunch
1358 size_t countLocation = outSmolv.size();
1359 outSmolv.push_back(0);
1360 int count = 0;
1361 while (memberWords < wordsEnd && count < 255)
1362 {
1363 _SMOLV_READ_OP(memberLen, memberWords, memberOp);
1364 if (memberOp != SpvOpMemberDecorate)
1365 break;
1366 if (memberLen < 4)
1367 return false; // invalid input
1368 if (memberWords[1] != decorationType)
1369 break;
1370
1371 // write member index as delta from previous
1372 uint32_t memberIndex = memberWords[2];
1373 smolv_WriteVarint(outSmolv, memberIndex - prevIndex);
1374 prevIndex = memberIndex;
1375
1376 // decoration (and length if not common/known)
1377 uint32_t memberDec = memberWords[3];
1378 smolv_WriteVarint(outSmolv, memberDec);
1379 const int knownExtraOps = smolv_DecorationExtraOps(memberDec);
1380 if (knownExtraOps == -1)
1381 smolv_WriteVarint(outSmolv, memberLen-4);
1382 else if (knownExtraOps + 4 != memberLen)
1383 return false; // invalid input
1384
1385 // Offset decorations are most often linearly increasing, so encode as deltas
1386 if (memberDec == 35) // Offset
1387 {
1388 if (memberLen != 5)
1389 return false;
1390 smolv_WriteVarint(outSmolv, memberWords[4]-prevOffset);
1391 prevOffset = memberWords[4];
1392 }
1393 else
1394 {
1395 // write rest of decorations as varint
1396 for (int i = 4; i < memberLen; ++i)
1397 smolv_WriteVarint(outSmolv, memberWords[i]);
1398 }
1399
1400 memberWords += memberLen;
1401 ++count;
1402 }
1403 outSmolv[countLocation] = count;
1404 words = memberWords;
1405 continue;
1406 }
1407
1408 // Write out this many IDs, encoding them relative+zigzag to result ID
1409 int relativeCount = smolv_OpDeltaFromResult(op);
1410 for (int i = 0; i < relativeCount && ioffs < instrLen; ++i, ++ioffs)
1411 {
1412 uint32_t delta = prevResult - words[ioffs];
1413 // some deltas are negative (often on branches, or if program was processed by spirv-remap),
1414 // so use zig encoding
1415 smolv_WriteVarint(outSmolv, smolv_ZigEncode(delta));
1416 }
1417
1418 if (op == SpvOpVectorShuffleCompact)
1419 {
1420 // compact vector shuffle, just write out single swizzle byte
1421 outSmolv.push_back(swizzle);
1422 ioffs = instrLen;
1423 }
1424 else if (smolv_OpVarRest(op))
1425 {
1426 // write out rest of words with variable encoding (expected to be small integers)
1427 for (; ioffs < instrLen; ++ioffs)
1428 smolv_WriteVarint(outSmolv, words[ioffs]);
1429 }
1430 else
1431 {
1432 // write out rest of words without any encoding
1433 for (; ioffs < instrLen; ++ioffs)
1434 smolv_Write4(outSmolv, words[ioffs]);
1435 }
1436
1437 words += instrLen;
1438 }
1439
1440 if (strippedSpirvWordCount != wordCount)
1441 {
1442 uint8_t* headerSpirvSize = &outSmolv[headerSpirvSizeOffset];
1443 smolv_Write4(headerSpirvSize, (uint32_t)strippedSpirvWordCount * 4);
1444 }
1445
1446 return true;
1447 }
1448
1449
1450 size_t smolv::GetDecodedBufferSize(const void* smolvData, size_t smolvSize)
1451 {
1452 if (!smolv_CheckSmolHeader((const uint8_t*)smolvData, smolvSize))
1453 return 0;
1454 const uint32_t* words = (const uint32_t*)smolvData;
1455 return words[5];
1456 }
1457
1458
1459 bool smolv::Decode(const void* smolvData, size_t smolvSize, void* spirvOutputBuffer, size_t spirvOutputBufferSize)
1460 {
1461 // check header, and whether we have enough output buffer space
1462 const size_t neededBufferSize = GetDecodedBufferSize(smolvData, smolvSize);
1463 if (neededBufferSize == 0)
1464 return false; // invalid SMOL-V
1465 if (spirvOutputBufferSize < neededBufferSize)
1466 return false; // not enough space in output buffer
1467 if (spirvOutputBuffer == NULL)
1468 return false; // output buffer is null
1469
1470 const uint8_t* bytes = (const uint8_t*)smolvData;
1471 const uint8_t* bytesEnd = bytes + smolvSize;
1472
1473 uint8_t* outSpirv = (uint8_t*)spirvOutputBuffer;
1474
1475 uint32_t val;
1476
1477 // header
1478 smolv_Write4(outSpirv, kSpirVHeaderMagic); bytes += 4;
1479 smolv_Read4(bytes, bytesEnd, val); smolv_Write4(outSpirv, val); // version
1480 smolv_Read4(bytes, bytesEnd, val); smolv_Write4(outSpirv, val); // generator
1481 smolv_Read4(bytes, bytesEnd, val); smolv_Write4(outSpirv, val); // bound
1482 smolv_Read4(bytes, bytesEnd, val); smolv_Write4(outSpirv, val); // schema
1483 bytes += 4; // decode buffer size
1484
1485 uint32_t prevResult = 0;
1486 uint32_t prevDecorate = 0;
1487
1488 while (bytes < bytesEnd)
1489 {
1490 // read length + opcode
1491 uint32_t instrLen;
1492 SpvOp op;
1493 if (!smolv_ReadLengthOp(bytes, bytesEnd, instrLen, op))
1494 return false;
1495 const bool wasSwizzle = (op == SpvOpVectorShuffleCompact);
1496 if (wasSwizzle)
1497 op = SpvOpVectorShuffle;
1498 smolv_Write4(outSpirv, (instrLen << 16) | op);
1499
1500 size_t ioffs = 1;
1501
1502 // read type as varint, if we have it
1503 if (smolv_OpHasType(op))
1504 {
1505 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1506 smolv_Write4(outSpirv, val);
1507 ioffs++;
1508 }
1509 // read result as delta+varint, if we have it
1510 if (smolv_OpHasResult(op))
1511 {
1512 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1513 val = prevResult + smolv_ZigDecode(val);
1514 smolv_Write4(outSpirv, val);
1515 prevResult = val;
1516 ioffs++;
1517 }
1518
1519 // Decorate: IDs relative to previous decorate
1520 if (op == SpvOpDecorate || op == SpvOpMemberDecorate)
1521 {
1522 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1523 val = prevDecorate + smolv_ZigDecode(val);
1524 smolv_Write4(outSpirv, val);
1525 prevDecorate = val;
1526 ioffs++;
1527 }
1528
1529 // MemberDecorate special decoding
1530 if (op == SpvOpMemberDecorate)
1531 {
1532 if (bytes >= bytesEnd)
1533 return false; // broken input
1534 int count = *bytes++;
1535 int prevIndex = 0;
1536 int prevOffset = 0;
1537 for (int m = 0; m < count; ++m)
1538 {
1539 // read member index
1540 uint32_t memberIndex;
1541 if (!smolv_ReadVarint(bytes, bytesEnd, memberIndex)) return false;
1542 memberIndex += prevIndex;
1543 prevIndex = memberIndex;
1544
1545 // decoration (and length if not common/known)
1546 uint32_t memberDec;
1547 if (!smolv_ReadVarint(bytes, bytesEnd, memberDec)) return false;
1548 const int knownExtraOps = smolv_DecorationExtraOps(memberDec);
1549 uint32_t memberLen;
1550 if (knownExtraOps == -1)
1551 {
1552 if (!smolv_ReadVarint(bytes, bytesEnd, memberLen)) return false;
1553 memberLen += 4;
1554 }
1555 else
1556 memberLen = 4 + knownExtraOps;
1557
1558 // write SPIR-V op+length (unless it's first member decoration, in which case it was written before)
1559 if (m != 0)
1560 {
1561 smolv_Write4(outSpirv, (memberLen << 16) | op);
1562 smolv_Write4(outSpirv, prevDecorate);
1563 }
1564 smolv_Write4(outSpirv, memberIndex);
1565 smolv_Write4(outSpirv, memberDec);
1566 // Special case for Offset decorations
1567 if (memberDec == 35) // Offset
1568 {
1569 if (memberLen != 5)
1570 return false;
1571 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1572 val += prevOffset;
1573 smolv_Write4(outSpirv, val);
1574 prevOffset = val;
1575 }
1576 else
1577 {
1578 for (int i = 4; i < memberLen; ++i)
1579 {
1580 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1581 smolv_Write4(outSpirv, val);
1582 }
1583 }
1584 }
1585 continue;
1586 }
1587
1588 // Read this many IDs, that are relative to result ID
1589 int relativeCount = smolv_OpDeltaFromResult(op);
1590 for (int i = 0; i < relativeCount && ioffs < instrLen; ++i, ++ioffs)
1591 {
1592 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1593 val = smolv_ZigDecode(val);
1594 smolv_Write4(outSpirv, prevResult - val);
1595 }
1596
1597 if (wasSwizzle && instrLen <= 9)
1598 {
1599 uint32_t swizzle = *bytes++;
1600 if (instrLen > 5) smolv_Write4(outSpirv, (swizzle >> 6) & 3);
1601 if (instrLen > 6) smolv_Write4(outSpirv, (swizzle >> 4) & 3);
1602 if (instrLen > 7) smolv_Write4(outSpirv, (swizzle >> 2) & 3);
1603 if (instrLen > 8) smolv_Write4(outSpirv, swizzle & 3);
1604 }
1605 else if (smolv_OpVarRest(op))
1606 {
1607 // read rest of words with variable encoding
1608 for (; ioffs < instrLen; ++ioffs)
1609 {
1610 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1611 smolv_Write4(outSpirv, val);
1612 }
1613 }
1614 else
1615 {
1616 // read rest of words without any encoding
1617 for (; ioffs < instrLen; ++ioffs)
1618 {
1619 if (!smolv_Read4(bytes, bytesEnd, val)) return false;
1620 smolv_Write4(outSpirv, val);
1621 }
1622 }
1623 }
1624
1625 if ((uint8_t*)spirvOutputBuffer + neededBufferSize != outSpirv)
1626 return false; // something went wrong during decoding? we should have decoded to exact output size
1627
1628 return true;
1629 }
1630
1631
1632
1633 // --------------------------------------------------------------------------------------------
1634 // Calculating instruction count / space stats on SPIR-V and SMOL-V
1635
1636
1637 struct smolv::Stats
1638 {
1639 Stats() { memset(this, 0, sizeof(*this)); }
1640 size_t opCounts[kKnownOpsCount];
1641 size_t opSizes[kKnownOpsCount];
1642 size_t smolOpSizes[kKnownOpsCount];
1643 size_t varintCountsOp[6];
1644 size_t varintCountsType[6];
1645 size_t varintCountsRes[6];
1646 size_t varintCountsOther[6];
1647 size_t totalOps;
1648 size_t totalSize;
1649 size_t totalSizeSmol;
1650 size_t inputCount;
1651 };
1652
1653
1654 smolv::Stats* smolv::StatsCreate()
1655 {
1656 return new Stats();
1657 }
1658
1659 void smolv::StatsDelete(smolv::Stats *s)
1660 {
1661 delete s;
1662 }
1663
1664
1665 bool smolv::StatsCalculate(smolv::Stats* stats, const void* spirvData, size_t spirvSize)
1666 {
1667 if (!stats)
1668 return false;
1669
1670 const size_t wordCount = spirvSize / 4;
1671 const uint32_t* words = (const uint32_t*)spirvData;
1672 const uint32_t* wordsEnd = words + wordCount;
1673 if (!smolv_CheckSpirVHeader(words, wordCount))
1674 return false;
1675 words += 5;
1676
1677 stats->inputCount++;
1678 stats->totalSize += wordCount;
1679
1680 while (words < wordsEnd)
1681 {
1682 _SMOLV_READ_OP(instrLen, words, op);
1683
1684 if (op < kKnownOpsCount)
1685 {
1686 stats->opCounts[op]++;
1687 stats->opSizes[op] += instrLen;
1688 }
1689 words += instrLen;
1690 stats->totalOps++;
1691 }
1692
1693 return true;
1694 }
1695
1696
1697 bool smolv::StatsCalculateSmol(smolv::Stats* stats, const void* smolvData, size_t smolvSize)
1698 {
1699 if (!stats)
1700 return false;
1701
1702 // debugging helper to dump all encoded bytes to stdout, keep at "if 0"
1703 # if 0
1704 # define _SMOLV_DEBUG_PRINT_ENCODED_BYTES() { \
1705 printf("Op %-22s ", op < kKnownOpsCount ? kSpirvOpNames[op] : "???"); \
1706 for (const uint8_t* b = instrBegin; b < bytes; ++b) \
1707 printf("%02x ", *b); \
1708 printf("\n"); \
1709 }
1710 # else
1711 # define _SMOLV_DEBUG_PRINT_ENCODED_BYTES() {}
1712 # endif
1713
1714 const uint8_t* bytes = (const uint8_t*)smolvData;
1715 const uint8_t* bytesEnd = bytes + smolvSize;
1716 if (!smolv_CheckSmolHeader(bytes, smolvSize))
1717 return false;
1718 bytes += 24;
1719
1720 stats->totalSizeSmol += smolvSize;
1721
1722 uint32_t val;
1723 while (bytes < bytesEnd)
1724 {
1725 const uint8_t* instrBegin = bytes;
1726 const uint8_t* varBegin;
1727
1728 // read length + opcode
1729 uint32_t instrLen;
1730 SpvOp op;
1731 varBegin = bytes;
1732 if (!smolv_ReadLengthOp(bytes, bytesEnd, instrLen, op))
1733 return false;
1734 const bool wasSwizzle = (op == SpvOpVectorShuffleCompact);
1735 if (wasSwizzle)
1736 op = SpvOpVectorShuffle;
1737 stats->varintCountsOp[bytes-varBegin]++;
1738
1739 size_t ioffs = 1;
1740 if (smolv_OpHasType(op))
1741 {
1742 varBegin = bytes;
1743 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1744 stats->varintCountsType[bytes-varBegin]++;
1745 ioffs++;
1746 }
1747 if (smolv_OpHasResult(op))
1748 {
1749 varBegin = bytes;
1750 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1751 stats->varintCountsRes[bytes-varBegin]++;
1752 ioffs++;
1753 }
1754
1755 if (op == SpvOpDecorate || op == SpvOpMemberDecorate)
1756 {
1757 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1758 ioffs++;
1759 }
1760 // MemberDecorate special decoding
1761 if (op == SpvOpMemberDecorate)
1762 {
1763 if (bytes >= bytesEnd)
1764 return false; // broken input
1765 int count = *bytes++;
1766 for (int m = 0; m < count; ++m)
1767 {
1768 uint32_t memberIndex;
1769 if (!smolv_ReadVarint(bytes, bytesEnd, memberIndex)) return false;
1770 uint32_t memberDec;
1771 if (!smolv_ReadVarint(bytes, bytesEnd, memberDec)) return false;
1772 const int knownExtraOps = smolv_DecorationExtraOps(memberDec);
1773 uint32_t memberLen;
1774 if (knownExtraOps == -1)
1775 {
1776 if (!smolv_ReadVarint(bytes, bytesEnd, memberLen)) return false;
1777 memberLen += 4;
1778 }
1779 else
1780 memberLen = 4 + knownExtraOps;
1781 for (int i = 4; i < memberLen; ++i)
1782 {
1783 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1784 }
1785 }
1786 stats->smolOpSizes[op] += bytes - instrBegin;
1787 _SMOLV_DEBUG_PRINT_ENCODED_BYTES();
1788 continue;
1789 }
1790
1791 int relativeCount = smolv_OpDeltaFromResult(op);
1792 for (int i = 0; i < relativeCount && ioffs < instrLen; ++i, ++ioffs)
1793 {
1794 varBegin = bytes;
1795 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1796 stats->varintCountsRes[bytes-varBegin]++;
1797 }
1798
1799 if (wasSwizzle && instrLen <= 9)
1800 {
1801 bytes++;
1802 }
1803 else if (smolv_OpVarRest(op))
1804 {
1805 for (; ioffs < instrLen; ++ioffs)
1806 {
1807 varBegin = bytes;
1808 if (!smolv_ReadVarint(bytes, bytesEnd, val)) return false;
1809 stats->varintCountsOther[bytes-varBegin]++;
1810 }
1811 }
1812 else
1813 {
1814 for (; ioffs < instrLen; ++ioffs)
1815 {
1816 if (!smolv_Read4(bytes, bytesEnd, val)) return false;
1817 }
1818 }
1819
1820 if (op < kKnownOpsCount)
1821 {
1822 stats->smolOpSizes[op] += bytes - instrBegin;
1823 }
1824 _SMOLV_DEBUG_PRINT_ENCODED_BYTES();
1825 }
1826
1827 return true;
1828 }
1829
1830 static bool CompareOpCounters (std::pair<SpvOp,size_t> a, std::pair<SpvOp,size_t> b)
1831 {
1832 return a.second > b.second;
1833 }
1834
1835 void smolv::StatsPrint(const Stats* stats)
1836 {
1837 if (!stats)
1838 return;
1839
1840 typedef std::pair<SpvOp,size_t> OpCounter;
1841 OpCounter counts[kKnownOpsCount];
1842 OpCounter sizes[kKnownOpsCount];
1843 OpCounter sizesSmol[kKnownOpsCount];
1844 for (int i = 0; i < kKnownOpsCount; ++i)
1845 {
1846 counts[i].first = (SpvOp)i;
1847 counts[i].second = stats->opCounts[i];
1848 sizes[i].first = (SpvOp)i;
1849 sizes[i].second = stats->opSizes[i];
1850 sizesSmol[i].first = (SpvOp)i;
1851 sizesSmol[i].second = stats->smolOpSizes[i];
1852 }
1853 std::sort(counts, counts + kKnownOpsCount, CompareOpCounters);
1854 std::sort(sizes, sizes + kKnownOpsCount, CompareOpCounters);
1855 std::sort(sizesSmol, sizesSmol + kKnownOpsCount, CompareOpCounters);
1856
1857 printf("Stats for %i SPIR-V inputs, total size %i words (%.1fKB):\n", (int)stats->inputCount, (int)stats->totalSize, stats->totalSize * 4.0f / 1024.0f);
1858 printf("Most occuring ops:\n");
1859 for (int i = 0; i < 30; ++i)
1860 {
1861 SpvOp op = counts[i].first;
1862 printf(" #%2i: %4i %-20s %4i (%4.1f%%)\n", i, op, kSpirvOpNames[op], (int)counts[i].second, (float)counts[i].second / (float)stats->totalOps * 100.0f);
1863 }
1864 printf("Largest total size of ops:\n");
1865 for (int i = 0; i < 30; ++i)
1866 {
1867 SpvOp op = sizes[i].first;
1868 printf(" #%2i: %-22s %6i (%4.1f%%) avg len %.1f\n",
1869 i,
1870 kSpirvOpNames[op],
1871 (int)sizes[i].second*4,
1872 (float)sizes[i].second / (float)stats->totalSize * 100.0f,
1873 (float)sizes[i].second*4 / (float)stats->opCounts[op]
1874 );
1875 }
1876 printf("SMOL varint encoding counts per byte length:\n");
1877 printf(" B: %6s %6s %6s %6s\n", "Op", "Type", "Result", "Other");
1878 for (int i = 1; i < 6; ++i)
1879 {
1880 printf(" %i: %6i %6i %6i %6i\n", i, (int)stats->varintCountsOp[i], (int)stats->varintCountsType[i], (int)stats->varintCountsRes[i], (int)stats->varintCountsOther[i]);
1881 }
1882 printf("Largest total size of ops in SMOL:\n");
1883 for (int i = 0; i < 30; ++i)
1884 {
1885 SpvOp op = sizesSmol[i].first;
1886 printf(" #%2i: %-22s %6i (%4.1f%%) avg len %.1f\n",
1887 i,
1888 kSpirvOpNames[op],
1889 (int)sizesSmol[i].second,
1890 (float)sizesSmol[i].second / (float)stats->totalSizeSmol * 100.0f,
1891 (float)sizesSmol[i].second / (float)stats->opCounts[op]
1892 );
1893 }
1894 }
1895