1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
|
// main.cpp
// Reflection API Example Program
// ==============================
//
// This file provides the application code for the `reflection-api` example.
// This example uses the Slang reflection API to travserse the structure
// of the parameters of a Slang program and their types.
//
// This program is a companion Slang reflection API documentation:
// https://shader-slang.org/slang/user-guide/compiling.html
//
// Boilerplate
// -----------
//
// The following lines are boilerplate common to set up this example
// to use the infrastructure for example programs in the Slang
// repository.
//
#include "slang-com-ptr.h"
#include "slang.h"
typedef SlangResult Result;
#include "core/slang-basic.h"
#include "examples/example-base/example-base.h"
using Slang::ComPtr;
using Slang::String;
using Slang::List;
static const ExampleResources resourceBase("reflection-api");
// Configuration
// -------------
//
// For simplicity, this example uses a hard-coded list of shader programs
// to compile, each represented as the name of a `.slang` file, along with
// a hard-coded list of targets to compile and reflect the programs for.
//
static const char* kSourceFileNames[] = {
"raster-simple.slang",
"compute-simple.slang",
};
static const struct
{
SlangCompileTarget format;
const char* profile;
} kTargets[] = {
{SLANG_DXIL, "sm_6_0"},
{SLANG_SPIRV, "sm_6_0"},
};
static const int kTargetCount = SLANG_COUNT_OF(kTargets);
// The `ReflectingPrinting` Type
// -------------------------
//
// We wrap most of the code for this example in a `struct`
// type, in order to provide a bit more freedom in order
// of declaration.
//
// When possible, we will follow the order of declarations
// in the accompanying document, to help readers who want
// to following along in the code while reading.
//
struct ReflectingPrinting
{
// Scoping things in a type allows us to declare functions
// out of order more easily, but we still have to forward-declare
// types when they will be used before they are declared.
//
struct AccessPath;
// Output Formatting
// -----------------
//
// This example program outputs reflection information in a format
// that is (or at least is intended to be) compatible with YAML.
//
// We do not want the code to be overly complicated with issues
// around formatting, so the details of the actual printing logic
// are largely left until later. However, there are a pair of
// macros that help to keep things tidy that we need to introduce
// here, before they are used.
//
#define WITH_ARRAY() for (int _i = (beginArray(), 1); _i; _i = (endArray(), 0))
#define SCOPED_OBJECT() ScopedObject scopedObject##__COUNTER__(this)
// Compiling a Program
// -------------------
//
Result compileAndReflectProgram(slang::ISession* session, const char* sourceFileName)
{
SCOPED_OBJECT();
printComment("program");
key("file name");
printQuotedString(sourceFileName);
String sourceFilePath = resourceBase.resolveResource(sourceFileName);
ComPtr<slang::IBlob> diagnostics;
Result result = SLANG_OK;
// ### Loading a Module
//
ComPtr<slang::IModule> module;
module = session->loadModule(sourceFilePath.getBuffer(), diagnostics.writeRef());
diagnoseIfNeeded(diagnostics);
if (!module)
return SLANG_FAIL;
List<ComPtr<slang::IComponentType>> componentsToLink;
// ### Finding Entry Points
//
key("defined entry points");
int definedEntryPointCount = module->getDefinedEntryPointCount();
WITH_ARRAY()
for (int i = 0; i < definedEntryPointCount; i++)
{
ComPtr<slang::IEntryPoint> entryPoint;
SLANG_RETURN_ON_FAIL(module->getDefinedEntryPoint(i, entryPoint.writeRef()));
element();
SCOPED_OBJECT();
key("name");
printQuotedString(entryPoint->getFunctionReflection()->getName());
componentsToLink.add(ComPtr<slang::IComponentType>(entryPoint.get()));
}
// ### Composing and Linking
//
ComPtr<slang::IComponentType> composed;
result = session->createCompositeComponentType(
(slang::IComponentType**)componentsToLink.getBuffer(),
componentsToLink.getCount(),
composed.writeRef(),
diagnostics.writeRef());
diagnoseIfNeeded(diagnostics);
SLANG_RETURN_ON_FAIL(result);
ComPtr<slang::IComponentType> program;
result = composed->link(program.writeRef(), diagnostics.writeRef());
diagnoseIfNeeded(diagnostics);
SLANG_RETURN_ON_FAIL(result);
key("layouts");
WITH_ARRAY()
for (int targetIndex = 0; targetIndex < kTargetCount; ++targetIndex)
{
element();
// ### Getting the Program Layout
//
slang::ProgramLayout* programLayout =
program->getLayout(targetIndex, diagnostics.writeRef());
diagnoseIfNeeded(diagnostics);
if (!programLayout)
{
result = SLANG_FAIL;
continue;
}
SLANG_RETURN_ON_FAIL(
collectEntryPointMetadata(program, targetIndex, definedEntryPointCount));
_programLayout = programLayout;
auto targetFormat = kTargets[targetIndex].format;
printProgramLayout(programLayout, targetFormat);
}
return result;
}
slang::ProgramLayout* _programLayout = nullptr;
Result compileAndReflectPrograms(slang::ISession* session)
{
Result result = SLANG_OK;
WITH_ARRAY()
for (auto fileName : kSourceFileNames)
{
element();
auto programResult = compileAndReflectProgram(session, fileName);
if (SLANG_FAILED(programResult))
{
result = programResult;
}
}
return result;
}
// Types and Variables
// -------------------
//
// ### Variables
//
void printVariable(slang::VariableReflection* variable)
{
SCOPED_OBJECT();
const char* name = variable->getName();
slang::TypeReflection* type = variable->getType();
key("name");
printQuotedString(name);
key("type");
printType(type);
}
// ### Types
//
void printType(slang::TypeReflection* type)
{
SCOPED_OBJECT();
const char* name = type->getName();
slang::TypeReflection::Kind kind = type->getKind();
key("name");
printQuotedString(name);
key("kind");
printTypeKind(kind);
// There is information that we would like to
// print for both types and type layouts, so
// we will factor the common logic into a
// subroutine so that we can share the code.
//
printCommonTypeInfo(type);
switch (type->getKind())
{
default:
break;
// #### Structure Types
//
case slang::TypeReflection::Kind::Struct:
{
key("fields");
int fieldCount = type->getFieldCount();
WITH_ARRAY();
for (int f = 0; f < fieldCount; f++)
{
element();
auto field = type->getFieldByIndex(f);
printVariable(field);
}
}
break;
// #### Array Types
// #### Vector Types
// #### Matrix Types
//
case slang::TypeReflection::Kind::Array:
case slang::TypeReflection::Kind::Vector:
case slang::TypeReflection::Kind::Matrix:
{
key("element type");
printType(type->getElementType());
}
break;
// #### Resource Types
//
case slang::TypeReflection::Kind::Resource:
{
key("result type");
printType(type->getResourceResultType());
}
break;
// #### Single-Element Container Types
//
case slang::TypeReflection::Kind::ConstantBuffer:
case slang::TypeReflection::Kind::ParameterBlock:
case slang::TypeReflection::Kind::TextureBuffer:
case slang::TypeReflection::Kind::ShaderStorageBuffer:
{
key("element type");
printType(type->getElementType());
}
break;
}
}
// #### Array Types
//
void printPossiblyUnbounded(size_t value)
{
if (value == ~size_t(0))
{
printf("unbounded");
}
else
{
printf("%u", unsigned(value));
}
}
void printCommonTypeInfo(slang::TypeReflection* type)
{
switch (type->getKind())
{
// #### Scalar Types
//
case slang::TypeReflection::Kind::Scalar:
{
key("scalar type");
printScalarType(type->getScalarType());
}
break;
// #### Array Types
//
case slang::TypeReflection::Kind::Array:
{
key("element count");
printPossiblyUnbounded(type->getElementCount());
}
break;
// #### Vector Types
//
case slang::TypeReflection::Kind::Vector:
{
key("element count");
print(type->getElementCount());
}
break;
// #### Matrix Types
//
case slang::TypeReflection::Kind::Matrix:
{
key("row count");
print(type->getRowCount());
key("column count");
print(type->getColumnCount());
}
break;
// #### Resource Types
//
case slang::TypeReflection::Kind::Resource:
{
key("shape");
printResourceShape(type->getResourceShape());
key("access");
printResourceAccess(type->getResourceAccess());
}
break;
default:
break;
}
}
// Layout for Types and Variables
// ------------------------------
//
// ### Variable Layouts
//
void printVariableLayout(slang::VariableLayoutReflection* variableLayout, AccessPath accessPath)
{
SCOPED_OBJECT();
key("name");
printQuotedString(variableLayout->getName());
printOffsets(variableLayout, accessPath);
printVaryingParameterInfo(variableLayout);
ExtendedAccessPath variablePath(accessPath, variableLayout);
key("type layout");
printTypeLayout(variableLayout->getTypeLayout(), variablePath);
}
// #### Offsets
void printRelativeOffsets(slang::VariableLayoutReflection* variableLayout)
{
key("relative");
int usedLayoutUnitCount = variableLayout->getCategoryCount();
WITH_ARRAY();
for (int i = 0; i < usedLayoutUnitCount; ++i)
{
element();
auto layoutUnit = variableLayout->getCategoryByIndex(i);
printOffset(variableLayout, layoutUnit);
}
}
void printOffset(
slang::VariableLayoutReflection* variableLayout,
slang::ParameterCategory layoutUnit)
{
printOffset(
layoutUnit,
variableLayout->getOffset(layoutUnit),
variableLayout->getBindingSpace(layoutUnit));
}
void printOffset(slang::ParameterCategory layoutUnit, size_t offset, size_t spaceOffset)
{
SCOPED_OBJECT();
key("value");
print(offset);
key("unit");
printLayoutUnit(layoutUnit);
// #### Spaces / Sets
switch (layoutUnit)
{
default:
break;
case slang::ParameterCategory::ConstantBuffer:
case slang::ParameterCategory::ShaderResource:
case slang::ParameterCategory::UnorderedAccess:
case slang::ParameterCategory::SamplerState:
case slang::ParameterCategory::DescriptorTableSlot:
key("space");
print(spaceOffset);
break;
}
}
// ### Type Layouts
//
void printTypeLayout(slang::TypeLayoutReflection* typeLayout, AccessPath accessPath)
{
SCOPED_OBJECT();
key("name");
printQuotedString(typeLayout->getName());
key("kind");
printTypeKind(typeLayout->getKind());
printCommonTypeInfo(typeLayout->getType());
printSizes(typeLayout);
printKindSpecificInfo(typeLayout, accessPath);
}
// #### Size
//
void printSizes(slang::TypeLayoutReflection* typeLayout)
{
key("size");
int usedLayoutUnitCount = typeLayout->getCategoryCount();
WITH_ARRAY()
for (int i = 0; i < usedLayoutUnitCount; ++i)
{
element();
auto layoutUnit = typeLayout->getCategoryByIndex(i);
printSize(typeLayout, layoutUnit);
}
// #### Alignment and Stride
if (typeLayout->getSize() != 0)
{
key("alignment in bytes");
print(typeLayout->getAlignment());
key("stride in bytes");
print(typeLayout->getStride());
}
}
void printSize(slang::TypeLayoutReflection* typeLayout, slang::ParameterCategory layoutUnit)
{
printSize(layoutUnit, typeLayout->getSize(layoutUnit));
}
void printSize(slang::ParameterCategory layoutUnit, size_t size)
{
SCOPED_OBJECT();
key("value");
printPossiblyUnbounded(size);
key("unit");
printLayoutUnit(layoutUnit);
}
// #### Kind-Specific Information
//
void printKindSpecificInfo(slang::TypeLayoutReflection* typeLayout, AccessPath accessPath)
{
switch (typeLayout->getKind())
{
// #### Structure Type Layouts
//
case slang::TypeReflection::Kind::Struct:
{
key("fields");
int fieldCount = typeLayout->getFieldCount();
WITH_ARRAY()
for (int f = 0; f < fieldCount; f++)
{
element();
auto field = typeLayout->getFieldByIndex(f);
printVariableLayout(field, accessPath);
}
}
break;
// #### Array Type Layouts
//
case slang::TypeReflection::Kind::Array:
{
key("element type layout");
printTypeLayout(typeLayout->getElementTypeLayout(), AccessPath());
}
break;
// #### Matrix Type Layouts
//
case slang::TypeReflection::Kind::Matrix:
{
key("matrix layout mode");
printMatrixLayoutMode(typeLayout->getMatrixLayoutMode());
key("element type layout");
printTypeLayout(typeLayout->getElementTypeLayout(), AccessPath());
}
break;
case slang::TypeReflection::Kind::Vector:
{
key("element type layout");
printTypeLayout(typeLayout->getElementTypeLayout(), AccessPath());
}
break;
// #### Single-Element Containers
//
case slang::TypeReflection::Kind::ConstantBuffer:
case slang::TypeReflection::Kind::ParameterBlock:
case slang::TypeReflection::Kind::TextureBuffer:
case slang::TypeReflection::Kind::ShaderStorageBuffer:
{
auto containerVarLayout = typeLayout->getContainerVarLayout();
auto elementVarLayout = typeLayout->getElementVarLayout();
key("container");
{
SCOPED_OBJECT();
printOffsets(containerVarLayout, accessPath);
}
AccessPath innerOffsets = accessPath;
innerOffsets.deepestConstantBufer = innerOffsets.leaf;
if (containerVarLayout->getTypeLayout()->getSize(
slang::ParameterCategory::SubElementRegisterSpace) != 0)
{
innerOffsets.deepestParameterBlock = innerOffsets.leaf;
}
key("content");
{
SCOPED_OBJECT();
printOffsets(elementVarLayout, innerOffsets);
ExtendedAccessPath elementOffsets(innerOffsets, elementVarLayout);
key("type layout");
printTypeLayout(elementVarLayout->getTypeLayout(), elementOffsets);
}
}
break;
case slang::TypeReflection::Kind::Resource:
{
if ((typeLayout->getResourceShape() & SLANG_RESOURCE_BASE_SHAPE_MASK) ==
SLANG_STRUCTURED_BUFFER)
{
key("element type layout");
printTypeLayout(typeLayout->getElementTypeLayout(), accessPath);
}
else
{
key("result type");
printType(typeLayout->getResourceResultType());
}
}
break;
default:
break;
}
}
// Programs and Scopes
// -------------------
//
void printProgramLayout(slang::ProgramLayout* programLayout, SlangCompileTarget targetFormat)
{
SCOPED_OBJECT();
key("target");
printTargetFormat(targetFormat);
AccessPath rootOffsets;
rootOffsets.valid = true;
key("global scope");
{
SCOPED_OBJECT();
printScope(programLayout->getGlobalParamsVarLayout(), rootOffsets);
}
key("entry points");
int entryPointCount = programLayout->getEntryPointCount();
WITH_ARRAY()
for (int i = 0; i < entryPointCount; ++i)
{
element();
printEntryPointLayout(programLayout->getEntryPointByIndex(i), rootOffsets);
}
}
// ### Global Scope
//
void printScope(slang::VariableLayoutReflection* scopeVarLayout, AccessPath accessPath)
{
ExtendedAccessPath scopeOffsets(accessPath, scopeVarLayout);
auto scopeTypeLayout = scopeVarLayout->getTypeLayout();
switch (scopeTypeLayout->getKind())
{
// #### Parameters are Grouped Into a Structure
//
case slang::TypeReflection::Kind::Struct:
{
key("parameters");
int paramCount = scopeTypeLayout->getFieldCount();
for (int i = 0; i < paramCount; i++)
{
element();
auto param = scopeTypeLayout->getFieldByIndex(i);
printVariableLayout(param, scopeOffsets);
}
}
break;
// #### Wrapped in a Constant Buffer If Needed
//
case slang::TypeReflection::Kind::ConstantBuffer:
key("automatically-introduced constant buffer");
{
SCOPED_OBJECT();
printOffsets(scopeTypeLayout->getContainerVarLayout(), scopeOffsets);
}
printScope(scopeTypeLayout->getElementVarLayout(), scopeOffsets);
break;
// #### Wrapped in a Parameter Block If Needed
//
case slang::TypeReflection::Kind::ParameterBlock:
key("automatically-introduced parameter block");
{
SCOPED_OBJECT();
printOffsets(scopeTypeLayout->getContainerVarLayout(), scopeOffsets);
}
printScope(scopeTypeLayout->getElementVarLayout(), scopeOffsets);
break;
default:
// Note that this default case is never expected to
// arise with the current Slang compiler and reflection
// API, but we include it here as a kind of failsafe.
//
key("variable layout");
printVariableLayout(scopeVarLayout, accessPath);
break;
}
}
// ### Entry Points
//
void printEntryPointLayout(slang::EntryPointReflection* entryPointLayout, AccessPath accessPath)
{
SCOPED_OBJECT();
key("stage");
printStage(entryPointLayout->getStage());
printStageSpecificInfo(entryPointLayout);
printScope(entryPointLayout->getVarLayout(), accessPath);
auto resultVariableLayout = entryPointLayout->getResultVarLayout();
if (resultVariableLayout->getTypeLayout()->getKind() != slang::TypeReflection::Kind::None)
{
key("result");
printVariableLayout(resultVariableLayout, accessPath);
}
}
// #### Stage-Specific Information
//
void printStageSpecificInfo(slang::EntryPointReflection* entryPointLayout)
{
switch (entryPointLayout->getStage())
{
default:
break;
case SLANG_STAGE_COMPUTE:
{
static const int kAxisCount = 3;
SlangUInt sizes[kAxisCount];
entryPointLayout->getComputeThreadGroupSize(kAxisCount, sizes);
key("thread group size");
SCOPED_OBJECT();
key("x");
print(sizes[0]);
key("y");
print(sizes[1]);
key("z");
print(sizes[2]);
}
break;
case SLANG_STAGE_FRAGMENT:
key("uses any sample-rate inputs");
printBool(entryPointLayout->usesAnySampleRateInput());
break;
}
}
// #### Varying Parameters
//
void printVaryingParameterInfo(slang::VariableLayoutReflection* variableLayout)
{
if (auto semanticName = variableLayout->getSemanticName())
{
key("semantic");
SCOPED_OBJECT();
key("name");
printQuotedString(semanticName);
key("index");
print(variableLayout->getSemanticIndex());
}
}
// Calculating Cumulative Offsets
// ------------------------------
//
struct CumulativeOffset
{
size_t value = 0;
size_t space = 0;
};
// ### Access Paths
struct AccessPathNode
{
slang::VariableLayoutReflection* variableLayout = nullptr;
AccessPathNode* outer = nullptr;
};
struct AccessPath
{
AccessPath() {}
bool valid = false;
AccessPathNode* deepestConstantBufer = nullptr;
AccessPathNode* deepestParameterBlock = nullptr;
AccessPathNode* leaf = nullptr;
};
void printCumulativeOffsets(
slang::VariableLayoutReflection* variableLayout,
AccessPath accessPath)
{
key("cumulative");
int usedLayoutUnitCount = variableLayout->getCategoryCount();
WITH_ARRAY();
for (int i = 0; i < usedLayoutUnitCount; ++i)
{
element();
auto layoutUnit = variableLayout->getCategoryByIndex(i);
printCumulativeOffset(variableLayout, layoutUnit, accessPath);
}
}
CumulativeOffset calculateCumulativeOffset(
slang::VariableLayoutReflection* variableLayout,
slang::ParameterCategory layoutUnit,
AccessPath accessPath)
{
CumulativeOffset result = calculateCumulativeOffset(layoutUnit, accessPath);
result.value += variableLayout->getOffset(layoutUnit);
result.space += variableLayout->getBindingSpace(layoutUnit);
return result;
}
void printCumulativeOffset(
slang::VariableLayoutReflection* variableLayout,
slang::ParameterCategory layoutUnit,
AccessPath accessPath)
{
CumulativeOffset cumulativeOffset =
calculateCumulativeOffset(variableLayout, layoutUnit, accessPath);
printOffset(layoutUnit, cumulativeOffset.value, cumulativeOffset.space);
}
// ### Tracking Access Paths
struct ExtendedAccessPath : AccessPath
{
ExtendedAccessPath(AccessPath const& base, slang::VariableLayoutReflection* variableLayout)
: AccessPath(base)
{
if (!valid)
return;
element.variableLayout = variableLayout;
element.outer = leaf;
leaf = &element;
}
AccessPathNode element;
};
// ### Accumulating Offsets Along An Access Path
CumulativeOffset calculateCumulativeOffset(
slang::ParameterCategory layoutUnit,
AccessPath accessPath)
{
CumulativeOffset result;
switch (layoutUnit)
{
// #### Layout Units That Don't Require Special Handling
//
default:
for (auto node = accessPath.leaf; node != nullptr; node = node->outer)
{
result.value += node->variableLayout->getOffset(layoutUnit);
}
break;
// #### Bytes
//
case slang::ParameterCategory::Uniform:
for (auto node = accessPath.leaf; node != accessPath.deepestConstantBufer;
node = node->outer)
{
result.value += node->variableLayout->getOffset(layoutUnit);
}
break;
// #### Layout Units That Care About Spaces
//
case slang::ParameterCategory::ConstantBuffer:
case slang::ParameterCategory::ShaderResource:
case slang::ParameterCategory::UnorderedAccess:
case slang::ParameterCategory::SamplerState:
case slang::ParameterCategory::DescriptorTableSlot:
for (auto node = accessPath.leaf; node != accessPath.deepestParameterBlock;
node = node->outer)
{
result.value += node->variableLayout->getOffset(layoutUnit);
result.space += node->variableLayout->getBindingSpace(layoutUnit);
}
for (auto node = accessPath.deepestParameterBlock; node != nullptr; node = node->outer)
{
result.space += node->variableLayout->getOffset(
slang::ParameterCategory::SubElementRegisterSpace);
}
break;
}
return result;
}
// Determining Whether Parameters Are Used
// ---------------------------------------
Result collectEntryPointMetadata(
slang::IComponentType* program,
int targetIndex,
int entryPointCount)
{
_metadataForEntryPoints.setCount(entryPointCount);
for (int entryPointIndex = 0; entryPointIndex < entryPointCount; entryPointIndex++)
{
ComPtr<slang::IMetadata> entryPointMetadata;
ComPtr<slang::IBlob> diagnostics;
SLANG_RETURN_ON_FAIL(program->getEntryPointMetadata(
entryPointIndex,
targetIndex,
entryPointMetadata.writeRef(),
diagnostics.writeRef()));
diagnoseIfNeeded(diagnostics);
_metadataForEntryPoints[entryPointIndex] = entryPointMetadata;
}
return SLANG_OK;
}
Slang::List<ComPtr<slang::IMetadata>> _metadataForEntryPoints;
typedef unsigned int StageMask;
StageMask calculateParameterStageMask(
slang::ParameterCategory layoutUnit,
CumulativeOffset offset)
{
unsigned mask = 0;
auto entryPointCount = _metadataForEntryPoints.getCount();
for (int i = 0; i < entryPointCount; ++i)
{
bool isUsed = false;
_metadataForEntryPoints[i]->isParameterLocationUsed(
SlangParameterCategory(layoutUnit),
offset.space,
offset.value,
isUsed);
if (isUsed)
{
auto entryPointStage = _programLayout->getEntryPointByIndex(i)->getStage();
mask |= 1 << unsigned(entryPointStage);
}
}
return mask;
}
StageMask calculateStageMask(
slang::VariableLayoutReflection* variableLayout,
AccessPath accessPath)
{
StageMask mask = 0;
int usedLayoutUnitCount = variableLayout->getCategoryCount();
for (int i = 0; i < usedLayoutUnitCount; ++i)
{
auto layoutUnit = variableLayout->getCategoryByIndex(i);
auto offset = calculateCumulativeOffset(variableLayout, layoutUnit, accessPath);
mask |= calculateParameterStageMask(layoutUnit, offset);
}
return mask;
}
void printStageUsage(slang::VariableLayoutReflection* variableLayout, AccessPath accessPath)
{
StageMask stageMask = calculateStageMask(variableLayout, accessPath);
key("used by stages");
WITH_ARRAY()
for (int i = 0; i < SLANG_STAGE_COUNT; i++)
{
if (stageMask & (1 << i))
{
element();
printStage(SlangStage(i));
}
}
}
void printOffsets(slang::VariableLayoutReflection* variableLayout, AccessPath accessPath)
{
key("offset");
{
SCOPED_OBJECT();
printRelativeOffsets(variableLayout);
if (accessPath.valid)
{
printCumulativeOffsets(variableLayout, accessPath);
}
}
if (accessPath.valid)
{
printStageUsage(variableLayout, accessPath);
}
}
// Formatting
// ----------
//
// Here we'll cover the logic for how we implement
// the various formatting operations used in the
// code above.
//
// ### Indentation
//
// We track a global indentation level, and whenever
// we begin a new line, we'll emit a corresponding
// amount of space (two spaces per indent, consistent
// with typical YAML formatting).
int indentation = 0;
void printIndentation()
{
for (int i = 1; i < indentation; ++i)
{
printf(" ");
}
}
// ### Objects and Arrays
//
// Both objects and arrays can be marked up purely
// with indentation in YAML. If we eventually
// change the output format to something like JSON,
// these operations would need to do more actual
// work.
void beginObject() { indentation++; }
void endObject() { indentation--; }
void beginArray() { indentation++; }
void endArray() { indentation--; }
// #### Scope-Based Objects
//
// In order to make it easier to keep the `beginObject()`
// and `endObject()` calls properly paired, we introduce
// a helper type that uses an RAII idiom to automatically
// pair up the calls.
//
struct ScopedObject
{
ScopedObject(ReflectingPrinting* outer)
: outer(outer)
{
outer->beginObject();
}
~ScopedObject() { outer->endObject(); }
ReflectingPrinting* outer = nullptr;
};
// ### Starting New Lines
//
// Typically, when we are about to emit a key
// in an object, or an element in an array,
// we need to start a new line (and print
// the appropriate indentation).
//
void newLine()
{
printf("\n");
printIndentation();
}
// The main exception is that if we've just
// emitted the `- ` for an array element then
// we don't need to start a new line if
// the next thing we emit is an object key.
//
// We *also* don't need to start a new line
// at the very beginning of the output, so
// we handle that by setting the intial state
// *as if* we have just started an array element.
bool afterArrayElement = true;
// ### Array Elements
//
void element()
{
newLine();
printf("- ");
afterArrayElement = true;
}
// ### Object Keys
//
void key(char const* key)
{
if (!afterArrayElement)
{
newLine();
}
afterArrayElement = false;
printf("%s: ", key);
}
// ### Printing Simple Values
//
// Simple scalar values like strings,
// `bool`s, and numbers don't need
// much special handling.
void printQuotedString(char const* text)
{
if (text)
{
printf("\"%s\"", text);
}
else
{
printf("null");
}
}
void printBool(bool value) { printf(value ? "true" : "false"); }
void print(size_t value) { printf("%u", unsigned(value)); }
// YAML supports comments, but JSON doesn't.
// This function could be stubbed out if
// we switch up the output format.
//
void printComment(char const* text) { printf("# %s", text); }
// Printing Enumerants
// -------------------
//
// Here we'll gather all the logic for printing the various
// `enum` types that we've worked with in the logic above.
void printTypeKind(slang::TypeReflection::Kind kind)
{
switch (kind)
{
#define CASE(TAG) \
case slang::TypeReflection::Kind::TAG: \
printf("%s", #TAG); \
break
CASE(None);
CASE(Struct);
CASE(Array);
CASE(Matrix);
CASE(Vector);
CASE(Scalar);
CASE(ConstantBuffer);
CASE(Resource);
CASE(SamplerState);
CASE(TextureBuffer);
CASE(ShaderStorageBuffer);
CASE(ParameterBlock);
CASE(GenericTypeParameter);
CASE(Interface);
CASE(OutputStream);
CASE(Specialized);
CASE(Feedback);
CASE(Pointer);
CASE(DynamicResource);
#undef CASE
default:
printf("%d # unexpected enumerant", int(kind));
break;
}
}
void printResourceShape(SlangResourceShape shape)
{
SCOPED_OBJECT();
key("base");
auto baseShape = shape & SLANG_RESOURCE_BASE_SHAPE_MASK;
switch (baseShape)
{
#define CASE(TAG) \
case SLANG_##TAG: \
printf("%s", #TAG); \
break
CASE(TEXTURE_1D);
CASE(TEXTURE_2D);
CASE(TEXTURE_3D);
CASE(TEXTURE_CUBE);
CASE(TEXTURE_BUFFER);
CASE(STRUCTURED_BUFFER);
CASE(BYTE_ADDRESS_BUFFER);
CASE(RESOURCE_UNKNOWN);
CASE(ACCELERATION_STRUCTURE);
CASE(TEXTURE_SUBPASS);
#undef CASE
default:
printf("%d # unexpected enumerant", int(baseShape));
break;
}
#define CASE(TAG) \
do \
{ \
if (shape & SLANG_TEXTURE_##TAG##_FLAG) \
{ \
key(#TAG); \
printf("true"); \
} \
} while (0)
CASE(FEEDBACK);
CASE(SHADOW);
CASE(ARRAY);
CASE(MULTISAMPLE);
#undef CASE
}
void printResourceAccess(SlangResourceAccess access)
{
switch (access)
{
#define CASE(TAG) \
case SLANG_RESOURCE_ACCESS_##TAG: \
printf("%s", #TAG); \
break
CASE(NONE);
CASE(READ);
CASE(READ_WRITE);
CASE(RASTER_ORDERED);
CASE(APPEND);
CASE(CONSUME);
CASE(WRITE);
CASE(FEEDBACK);
#undef CASE
default:
printf("%d # unexpected enumerant", int(access));
break;
}
}
void printLayoutUnit(slang::ParameterCategory layoutUnit)
{
switch (layoutUnit)
{
#define CASE(TAG, DESCRIPTION) \
case slang::ParameterCategory::TAG: \
printf("%s # %s", #TAG, DESCRIPTION); \
break
CASE(ConstantBuffer, "constant buffer slots");
CASE(ShaderResource, "texture slots");
CASE(UnorderedAccess, "uav slots");
CASE(VaryingInput, "varying input slots");
CASE(VaryingOutput, "varying output slots");
CASE(SamplerState, "sampler slots");
CASE(Uniform, "bytes");
CASE(DescriptorTableSlot, "bindings");
CASE(SpecializationConstant, "specialization constant ids");
CASE(PushConstantBuffer, "push-constant buffers");
CASE(RegisterSpace, "register space offset for a variable");
CASE(GenericResource, "generic resources");
CASE(RayPayload, "ray payloads");
CASE(HitAttributes, "hit attributes");
CASE(CallablePayload, "callable payloads");
CASE(ShaderRecord, "shader records");
CASE(ExistentialTypeParam, "existential type parameters");
CASE(ExistentialObjectParam, "existential object parameters");
CASE(SubElementRegisterSpace, "register spaces / descriptor sets");
CASE(InputAttachmentIndex, "subpass input attachments");
CASE(MetalArgumentBufferElement, "Metal argument buffer elements");
CASE(MetalAttribute, "Metal attributes");
CASE(MetalPayload, "Metal payloads");
#undef CASE
default:
printf("%d # unknown enumerant", int(layoutUnit));
break;
}
}
void printStage(SlangStage stage)
{
switch (stage)
{
#define CASE(NAME) \
case SLANG_STAGE_##NAME: \
printf(#NAME); \
break
CASE(NONE);
CASE(VERTEX);
CASE(HULL);
CASE(DOMAIN);
CASE(GEOMETRY);
CASE(FRAGMENT);
CASE(COMPUTE);
CASE(RAY_GENERATION);
CASE(INTERSECTION);
CASE(ANY_HIT);
CASE(CLOSEST_HIT);
CASE(MISS);
CASE(CALLABLE);
CASE(MESH);
CASE(AMPLIFICATION);
#undef CASE
default:
printf("%d # unexpected enumerant", int(stage));
break;
};
}
void printTargetFormat(SlangCompileTarget targetFormat)
{
switch (targetFormat)
{
#define CASE(TAG) \
case SLANG_##TAG: \
printf("%s", #TAG); \
break
CASE(TARGET_UNKNOWN);
CASE(TARGET_NONE);
CASE(GLSL);
CASE(GLSL_VULKAN_DEPRECATED);
CASE(GLSL_VULKAN_ONE_DESC_DEPRECATED);
CASE(HLSL);
CASE(SPIRV);
CASE(SPIRV_ASM);
CASE(DXBC);
CASE(DXBC_ASM);
CASE(DXIL);
CASE(DXIL_ASM);
CASE(C_SOURCE);
CASE(CPP_SOURCE);
CASE(HOST_EXECUTABLE);
CASE(SHADER_SHARED_LIBRARY);
CASE(SHADER_HOST_CALLABLE);
CASE(CUDA_SOURCE);
CASE(PTX);
CASE(CUDA_OBJECT_CODE);
CASE(OBJECT_CODE);
CASE(HOST_CPP_SOURCE);
CASE(HOST_HOST_CALLABLE);
CASE(CPP_PYTORCH_BINDING);
CASE(METAL);
CASE(METAL_LIB);
CASE(METAL_LIB_ASM);
CASE(HOST_SHARED_LIBRARY);
CASE(WGSL);
CASE(WGSL_SPIRV_ASM);
CASE(WGSL_SPIRV);
#undef CASE
default:
printf("%d # unhandled enumerant", int(targetFormat));
}
}
void printScalarType(slang::TypeReflection::ScalarType scalarType)
{
switch (scalarType)
{
#define CASE(TAG) \
case slang::TypeReflection::TAG: \
printf("%s", #TAG); \
break
CASE(None);
CASE(Void);
CASE(Bool);
CASE(Int32);
CASE(UInt32);
CASE(Int64);
CASE(UInt64);
CASE(Float16);
CASE(Float32);
CASE(Float64);
CASE(Int8);
CASE(UInt8);
CASE(Int16);
CASE(UInt16);
#undef CASE
default:
printf("%d # unhandled enumerant", int(scalarType));
}
}
void printMatrixLayoutMode(SlangMatrixLayoutMode mode)
{
switch (mode)
{
#define CASE(TAG) \
case SLANG_MATRIX_LAYOUT_##TAG: \
printf("%s", #TAG); \
break
CASE(MODE_UNKNOWN);
CASE(ROW_MAJOR);
CASE(COLUMN_MAJOR);
#undef CASE
default:
printf("%d # unhandled enumerant", int(mode));
}
}
};
struct ExampleProgram : public TestBase
{
Result execute(int argc, char* argv[])
{
parseOption(argc, argv);
ComPtr<slang::IGlobalSession> globalSession;
SLANG_RETURN_ON_FAIL(slang::createGlobalSession(globalSession.writeRef()));
Slang::List<slang::TargetDesc> targetDescs;
for (auto target : kTargets)
{
auto profile = globalSession->findProfile(target.profile);
slang::TargetDesc targetDesc;
targetDesc.format = target.format;
targetDesc.profile = profile;
targetDescs.add(targetDesc);
}
slang::SessionDesc sessionDesc;
sessionDesc.targetCount = targetDescs.getCount();
sessionDesc.targets = targetDescs.getBuffer();
ComPtr<slang::ISession> session;
SLANG_RETURN_ON_FAIL(globalSession->createSession(sessionDesc, session.writeRef()));
ReflectingPrinting printingContext;
printingContext.compileAndReflectPrograms(session);
return SLANG_OK;
}
};
int main(int argc, char* argv[])
{
ExampleProgram app;
if (SLANG_FAILED(app.execute(argc, argv)))
{
return -1;
}
return 0;
}
|