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
|
// slang-emit-cuda.cpp
#include "slang-emit-cuda.h"
#include "../core/slang-writer.h"
#include "slang-emit-source-writer.h"
#include "slang-mangled-lexer.h"
#include <assert.h>
namespace Slang
{
static CUDAExtensionTracker::BaseTypeFlags _findBaseTypesUsed(IRModule* module)
{
typedef CUDAExtensionTracker::BaseTypeFlags Flags;
// All basic types are hoistable so must be in global scope.
Flags baseTypesUsed = 0;
auto moduleInst = module->getModuleInst();
// Search all the insts in global scope, for BasicTypes
for (auto inst : moduleInst->getChildren())
{
if (auto basicType = as<IRBasicType>(inst))
{
// Get the base type, and set the bit
const auto baseTypeEnum = basicType->getBaseType();
baseTypesUsed |= Flags(1) << int(baseTypeEnum);
}
}
return baseTypesUsed;
}
void CUDAExtensionTracker::finalize()
{
if (isBaseTypeRequired(BaseType::Half))
{
// The cuda_fp16.hpp header indicates the need is for version 5.3, but when this is tried
// NVRTC says it cannot load builtins.
// The lowest version that this does work for is 6.0, so that's what we use here.
// https://docs.nvidia.com/cuda/nvrtc/index.html#group__options
requireSMVersion(SemanticVersion(6, 0));
}
}
UnownedStringSlice CUDASourceEmitter::getBuiltinTypeName(IROp op)
{
switch (op)
{
case kIROp_VoidType:
return UnownedStringSlice("void");
case kIROp_BoolType:
return UnownedStringSlice("bool");
case kIROp_Int8Type:
return UnownedStringSlice("char");
case kIROp_Int16Type:
return UnownedStringSlice("short");
case kIROp_IntType:
return UnownedStringSlice("int");
case kIROp_Int64Type:
return UnownedStringSlice("longlong");
case kIROp_UInt8Type:
return UnownedStringSlice("uchar");
case kIROp_UInt16Type:
return UnownedStringSlice("ushort");
case kIROp_UIntType:
return UnownedStringSlice("uint");
case kIROp_UInt64Type:
return UnownedStringSlice("ulonglong");
#if SLANG_PTR_IS_64
case kIROp_IntPtrType:
return UnownedStringSlice("int64_t");
case kIROp_UIntPtrType:
return UnownedStringSlice("uint64_t");
#else
case kIROp_IntPtrType:
return UnownedStringSlice("int");
case kIROp_UIntPtrType:
return UnownedStringSlice("uint");
#endif
case kIROp_HalfType:
return UnownedStringSlice("__half");
case kIROp_FloatType:
return UnownedStringSlice("float");
case kIROp_DoubleType:
return UnownedStringSlice("double");
default:
return UnownedStringSlice();
}
}
UnownedStringSlice CUDASourceEmitter::getVectorPrefix(IROp op)
{
switch (op)
{
case kIROp_BoolType:
return UnownedStringSlice("bool");
case kIROp_Int8Type:
return UnownedStringSlice("char");
case kIROp_Int16Type:
return UnownedStringSlice("short");
case kIROp_IntType:
return UnownedStringSlice("int");
case kIROp_Int64Type:
return UnownedStringSlice("longlong");
case kIROp_UInt8Type:
return UnownedStringSlice("uchar");
case kIROp_UInt16Type:
return UnownedStringSlice("ushort");
case kIROp_UIntType:
return UnownedStringSlice("uint");
case kIROp_UInt64Type:
return UnownedStringSlice("ulonglong");
#if SLANG_PTR_IS_64
case kIROp_IntPtrType:
return UnownedStringSlice("longlong");
case kIROp_UIntPtrType:
return UnownedStringSlice("ulonglong");
#else
case kIROp_IntPtrType:
return UnownedStringSlice("int");
case kIROp_UIntPtrType:
return UnownedStringSlice("uint");
#endif
case kIROp_HalfType:
return UnownedStringSlice("__half");
case kIROp_FloatType:
return UnownedStringSlice("float");
case kIROp_DoubleType:
return UnownedStringSlice("double");
default:
return UnownedStringSlice();
}
}
void CUDASourceEmitter::emitTempModifiers(IRInst* temp)
{
CPPSourceEmitter::emitTempModifiers(temp);
if (as<IRModuleInst>(temp->getParent()))
{
m_writer->emit("__device__ ");
}
}
SlangResult CUDASourceEmitter::_calcCUDATextureTypeName(
IRTextureTypeBase* texType,
StringBuilder& outName)
{
// Not clear how to do this yet
if (texType->isMultisample())
{
return SLANG_FAIL;
}
switch (texType->getAccess())
{
case SLANG_RESOURCE_ACCESS_READ:
{
outName << "CUtexObject";
return SLANG_OK;
}
case SLANG_RESOURCE_ACCESS_READ_WRITE:
case SLANG_RESOURCE_ACCESS_RASTER_ORDERED:
case SLANG_RESOURCE_ACCESS_WRITE:
{
outName << "CUsurfObject";
return SLANG_OK;
}
default:
break;
}
return SLANG_FAIL;
}
SlangResult CUDASourceEmitter::calcTypeName(IRType* type, CodeGenTarget target, StringBuilder& out)
{
SLANG_UNUSED(target);
// The names CUDA produces are all compatible with 'C' (ie they aren't templated types)
SLANG_ASSERT(target == CodeGenTarget::CUDASource || target == CodeGenTarget::CSource);
switch (type->getOp())
{
case kIROp_VectorType:
{
auto vecType = static_cast<IRVectorType*>(type);
auto vecCount = int(getIntVal(vecType->getElementCount()));
const IROp elemType = vecType->getElementType()->getOp();
UnownedStringSlice prefix = getVectorPrefix(elemType);
if (prefix.getLength() <= 0)
{
return SLANG_FAIL;
}
out << prefix << vecCount;
return SLANG_OK;
}
case kIROp_TensorViewType:
{
out << "TensorView";
return SLANG_OK;
}
case kIROp_RaytracingAccelerationStructureType:
case kIROp_HitObjectType:
{
out << "OptixTraversableHandle";
return SLANG_OK;
}
default:
{
if (isNominalOp(type->getOp()))
{
out << getName(type);
return SLANG_OK;
}
if (IRBasicType::isaImpl(type->getOp()))
{
out << getBuiltinTypeName(type->getOp());
return SLANG_OK;
}
if (auto texType = as<IRTextureTypeBase>(type))
{
return _calcCUDATextureTypeName(texType, out);
}
switch (type->getOp())
{
case kIROp_SamplerStateType:
out << "SamplerState";
return SLANG_OK;
case kIROp_SamplerComparisonStateType:
out << "SamplerComparisonState";
return SLANG_OK;
default:
break;
}
break;
}
}
return Super::calcTypeName(type, target, out);
}
void CUDASourceEmitter::emitLayoutSemanticsImpl(
IRInst* inst,
char const* uniformSemanticSpelling,
EmitLayoutSemanticOption layoutSemanticOption)
{
Super::emitLayoutSemanticsImpl(inst, uniformSemanticSpelling, layoutSemanticOption);
}
void CUDASourceEmitter::emitParameterGroupImpl(
IRGlobalParam* varDecl,
IRUniformParameterGroupType* type)
{
auto elementType = type->getElementType();
m_writer->emit("extern \"C\" __constant__ ");
emitType(elementType, "SLANG_globalParams");
m_writer->emit(";\n");
m_writer->emit("#define ");
m_writer->emit(getName(varDecl));
m_writer->emit(" (&SLANG_globalParams)\n");
}
void CUDASourceEmitter::emitEntryPointAttributesImpl(
IRFunc* irFunc,
IREntryPointDecoration* entryPointDecor)
{
SLANG_UNUSED(irFunc);
SLANG_UNUSED(entryPointDecor);
}
void CUDASourceEmitter::emitFunctionPreambleImpl(IRInst* inst)
{
if (!inst)
return;
if (inst->findDecoration<IREntryPointDecoration>())
{
m_writer->emit("extern \"C\" __global__ ");
return;
}
if (inst->findDecoration<IRCudaKernelDecoration>())
{
m_writer->emit("__global__ ");
}
else if (inst->findDecoration<IRCudaHostDecoration>())
{
m_writer->emit("__host__ ");
}
else
{
m_writer->emit("__device__ ");
}
}
String CUDASourceEmitter::generateEntryPointNameImpl(IREntryPointDecoration* entryPointDecor)
{
// We have an entry-point function in the IR module, which we
// will want to emit as a `__global__` function in the generated
// CUDA C++.
//
// The most common case will be a compute kernel, in which case
// we will emit the function more or less as-is, including
// usingits original name as the name of the global symbol.
//
String funcName = Super::generateEntryPointNameImpl(entryPointDecor);
String globalSymbolName = funcName;
// We also suport emitting ray tracing kernels for use with
// OptiX, and in that case the name of the global symbol
// must be prefixed to indicate to the OptiX runtime what
// stage it is to be compiled for.
//
auto stage = entryPointDecor->getProfile().getStage();
switch (stage)
{
default:
break;
#define CASE(STAGE, PREFIX) \
case Stage::STAGE: \
globalSymbolName = #PREFIX + funcName; \
break
// Optix 7 Guide, Section 6.1 (Program input)
//
// > The input PTX should include one or more NVIDIA OptiX programs.
// > The type of program affects how the program can be used during
// > the execution of the pipeline. These program types are specified
// by prefixing the program name with the following:
//
// > Program type Function name prefix
CASE(RayGeneration, __raygen__);
CASE(Intersection, __intersection__);
CASE(AnyHit, __anyhit__);
CASE(ClosestHit, __closesthit__);
CASE(Miss, __miss__);
CASE(Callable, __direct_callable__);
//
// There are two stages (or "program types") supported by OptiX
// that Slang currently cannot target:
//
// CASE(ContinuationCallable, __continuation_callable__);
// CASE(Exception, __exception__);
//
#undef CASE
}
return globalSymbolName;
}
void CUDASourceEmitter::emitGlobalRTTISymbolPrefix()
{
m_writer->emit("__constant__ ");
}
void CUDASourceEmitter::emitLoopControlDecorationImpl(IRLoopControlDecoration* decl)
{
if (decl->getMode() == kIRLoopControl_Unroll)
{
m_writer->emit("#pragma unroll\n");
}
}
void CUDASourceEmitter::_emitInitializerListValue(IRType* dstType, IRInst* value)
{
// When constructing a matrix or vector from a single value this is handled by the default path
switch (value->getOp())
{
case kIROp_MakeVector:
case kIROp_MakeMatrix:
{
IRType* type = value->getDataType();
// If the types are the same, we can can just break down and use
if (dstType == type)
{
if (auto vecType = as<IRVectorType>(type))
{
if (UInt(getIntVal(vecType->getElementCount())) == value->getOperandCount())
{
emitType(type);
_emitInitializerList(
vecType->getElementType(),
value->getOperands(),
value->getOperandCount());
return;
}
}
else if (auto matType = as<IRMatrixType>(type))
{
const Index colCount = Index(getIntVal(matType->getColumnCount()));
const Index rowCount = Index(getIntVal(matType->getRowCount()));
// TODO(JS): If num cols = 1, then it *doesn't* actually return a vector.
// That could be argued is an error because we want swizzling or [] to work.
IRBuilder builder(matType->getModule());
builder.setInsertBefore(matType);
const Index operandCount = Index(value->getOperandCount());
// Can init, with vectors.
// For now special case if the rowVectorType is not actually a vector (when
// elementSize == 1)
if (operandCount == rowCount)
{
// Emit the braces for the Matrix struct, and then each row vector in its
// own line.
emitType(matType);
m_writer->emit("{\n");
m_writer->indent();
for (Index i = 0; i < rowCount; ++i)
{
if (i != 0)
m_writer->emit(",\n");
emitType(matType->getElementType());
m_writer->emit(colCount);
_emitInitializerList(
matType->getElementType(),
value->getOperand(i)->getOperands(),
colCount);
}
m_writer->dedent();
m_writer->emit("\n}");
return;
}
else if (operandCount == rowCount * colCount)
{
// Handle if all are explicitly defined
IRType* elementType = matType->getElementType();
IRUse* operands = value->getOperands();
// Emit the braces for the Matrix struct, and the elements of each row in
// its own line.
emitType(matType);
m_writer->emit("{\n");
m_writer->indent();
for (Index i = 0; i < rowCount; ++i)
{
if (i != 0)
m_writer->emit(",\n");
_emitInitializerListContent(elementType, operands, colCount);
operands += colCount;
}
m_writer->dedent();
m_writer->emit("\n}");
return;
}
}
}
break;
}
}
// All other cases we just use the default emitting - might not work on arrays defined in global
// scope on CUDA though
emitOperand(value, getInfo(EmitOp::General));
}
void CUDASourceEmitter::_emitInitializerListContent(
IRType* elementType,
IRUse* operands,
Index operandCount)
{
for (Index i = 0; i < operandCount; ++i)
{
if (i != 0)
m_writer->emit(", ");
_emitInitializerListValue(elementType, operands[i].get());
}
}
void CUDASourceEmitter::_emitInitializerList(
IRType* elementType,
IRUse* operands,
Index operandCount)
{
m_writer->emit("{\n");
m_writer->indent();
_emitInitializerListContent(elementType, operands, operandCount);
m_writer->dedent();
m_writer->emit("\n}");
}
void CUDASourceEmitter::emitIntrinsicCallExprImpl(
IRCall* inst,
UnownedStringSlice intrinsicDefinition,
IRInst* intrinsicInst,
EmitOpInfo const& inOuterPrec)
{
// This works around the problem, where some intrinsics that require the "half" type enabled
// don't use the half/float16_t type. For example `f16tof32` can operate on float16_t *and*
// uint. If the input is uint, although we are using the half feature (as far as CUDA is
// concerned), the half/float16_t type is not visible/directly used.
if (intrinsicDefinition.startsWith(toSlice("__half")))
{
m_extensionTracker->requireBaseType(BaseType::Half);
}
Super::emitIntrinsicCallExprImpl(inst, intrinsicDefinition, intrinsicInst, inOuterPrec);
}
bool CUDASourceEmitter::tryEmitInstStmtImpl(IRInst* inst)
{
switch (inst->getOp())
{
case kIROp_StructuredBufferGetDimensions:
{
auto count = _generateUniqueName(UnownedStringSlice("_elementCount"));
auto stride = _generateUniqueName(UnownedStringSlice("_stride"));
m_writer->emit("uint ");
m_writer->emit(count);
m_writer->emit(";\n");
m_writer->emit("uint ");
m_writer->emit(stride);
m_writer->emit(";\n");
emitOperand(
inst->getOperand(0),
leftSide(getInfo(EmitOp::General), getInfo(EmitOp::Postfix)));
m_writer->emit(".GetDimensions(&");
m_writer->emit(count);
m_writer->emit(", &");
m_writer->emit(stride);
m_writer->emit(");\n");
emitInstResultDecl(inst);
m_writer->emit("make_uint2(");
m_writer->emit(count);
m_writer->emit(", ");
m_writer->emit(stride);
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicLoad:
{
emitInstResultDecl(inst);
emitDereferenceOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(";\n");
return true;
}
case kIROp_AtomicStore:
{
emitDereferenceOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(" = ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(";\n");
return true;
}
case kIROp_AtomicExchange:
{
emitInstResultDecl(inst);
m_writer->emit("atomicExch(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicCompareExchange:
{
emitInstResultDecl(inst);
m_writer->emit("atomicCAS(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(2), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicAdd:
{
emitInstResultDecl(inst);
m_writer->emit("atomicAdd(");
bool needCloseTypeCast = false;
if (inst->getDataType()->getOp() == kIROp_Int64Type)
{
m_writer->emit("(unsigned long long*)(");
needCloseTypeCast = true;
}
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
if (needCloseTypeCast)
{
m_writer->emit(")");
}
m_writer->emit(", ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicSub:
{
emitInstResultDecl(inst);
m_writer->emit("atomicAdd(");
bool needCloseTypeCast = false;
if (inst->getDataType()->getOp() == kIROp_Int64Type)
{
m_writer->emit("(unsigned long long*)(");
needCloseTypeCast = true;
}
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
if (needCloseTypeCast)
{
m_writer->emit(")");
}
m_writer->emit(", -(");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit("));\n");
return true;
}
case kIROp_AtomicAnd:
{
emitInstResultDecl(inst);
m_writer->emit("atomicAnd(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicOr:
{
emitInstResultDecl(inst);
m_writer->emit("atomicOr(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicXor:
{
emitInstResultDecl(inst);
m_writer->emit("atomicXor(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicMin:
{
emitInstResultDecl(inst);
m_writer->emit("atomicMin(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicMax:
{
emitInstResultDecl(inst);
m_writer->emit("atomicMax(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicInc:
{
emitInstResultDecl(inst);
m_writer->emit("atomicAdd(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", 1);\n");
return true;
}
case kIROp_AtomicDec:
{
emitInstResultDecl(inst);
m_writer->emit("atomicAdd(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", -1);\n");
return true;
}
default:
return false;
}
}
bool CUDASourceEmitter::tryEmitInstExprImpl(IRInst* inst, const EmitOpInfo& inOuterPrec)
{
switch (inst->getOp())
{
case kIROp_MakeVector:
case kIROp_MakeVectorFromScalar:
{
m_writer->emit("make_");
emitType(inst->getDataType());
m_writer->emit("(");
bool isFirst = true;
char xyzwNames[] = "xyzw";
for (UInt i = 0; i < inst->getOperandCount(); i++)
{
auto arg = inst->getOperand(i);
if (auto vectorType = as<IRVectorType>(arg->getDataType()))
{
for (int j = 0; j < cast<IRIntLit>(vectorType->getElementCount())->getValue();
j++)
{
if (isFirst)
isFirst = false;
else
m_writer->emit(", ");
auto outerPrec = getInfo(EmitOp::General);
auto prec = getInfo(EmitOp::Postfix);
emitOperand(arg, leftSide(outerPrec, prec));
m_writer->emit(".");
m_writer->emitChar(xyzwNames[j]);
}
}
else
{
if (isFirst)
isFirst = false;
else
m_writer->emit(", ");
emitOperand(arg, getInfo(EmitOp::General));
}
}
m_writer->emit(")");
return true;
}
case kIROp_FloatCast:
case kIROp_CastIntToFloat:
case kIROp_IntCast:
case kIROp_CastFloatToInt:
{
if (auto dstVectorType = as<IRVectorType>(inst->getDataType()))
{
m_writer->emit("make_");
emitType(inst->getDataType());
m_writer->emit("(");
bool isFirst = true;
char xyzwNames[] = "xyzw";
for (UInt i = 0; i < inst->getOperandCount(); i++)
{
auto arg = inst->getOperand(i);
if (auto vectorType = as<IRVectorType>(arg->getDataType()))
{
for (int j = 0;
j < cast<IRIntLit>(vectorType->getElementCount())->getValue();
j++)
{
if (isFirst)
isFirst = false;
else
m_writer->emit(", ");
m_writer->emit("(");
emitType(dstVectorType->getElementType());
m_writer->emit(")");
auto outerPrec = getInfo(EmitOp::General);
auto prec = getInfo(EmitOp::Postfix);
emitOperand(arg, leftSide(outerPrec, prec));
m_writer->emit(".");
m_writer->emitChar(xyzwNames[j]);
}
}
else
{
if (isFirst)
isFirst = false;
else
m_writer->emit(", ");
m_writer->emit("(");
emitType(dstVectorType->getElementType());
m_writer->emit(")");
emitOperand(arg, getInfo(EmitOp::General));
}
}
m_writer->emit(")");
return true;
}
else if (const auto matrixType = as<IRMatrixType>(inst->getDataType()))
{
m_writer->emit("make");
emitType(inst->getDataType());
m_writer->emit("(");
for (UInt i = 0; i < inst->getOperandCount(); i++)
{
auto arg = inst->getOperand(i);
if (i > 0)
m_writer->emit(", ");
emitOperand(arg, getInfo(EmitOp::General));
}
m_writer->emit(")");
return true;
}
return false;
}
case kIROp_MakeMatrix:
case kIROp_MakeMatrixFromScalar:
case kIROp_MatrixReshape:
{
m_writer->emit("make");
emitType(inst->getDataType());
m_writer->emit("(");
for (UInt i = 0; i < inst->getOperandCount(); i++)
{
auto arg = inst->getOperand(i);
if (i > 0)
m_writer->emit(", ");
emitOperand(arg, getInfo(EmitOp::General));
}
m_writer->emit(")");
return true;
}
case kIROp_MakeArray:
{
IRType* dataType = inst->getDataType();
IRArrayType* arrayType = as<IRArrayType>(dataType);
IRType* elementType = arrayType->getElementType();
// Emit braces for the FixedArray struct.
_emitInitializerList(elementType, inst->getOperands(), Index(inst->getOperandCount()));
return true;
}
case kIROp_WaveMaskBallot:
{
m_extensionTracker->requireSMVersion(SemanticVersion(7, 0));
m_writer->emit("__ballot_sync(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(")");
return true;
}
case kIROp_WaveMaskMatch:
{
m_extensionTracker->requireSMVersion(SemanticVersion(7, 0));
m_writer->emit("__match_any_sync(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(")");
return true;
}
case kIROp_GetOptiXRayPayloadPtr:
{
m_writer->emit("((");
emitType(inst->getDataType());
m_writer->emit(")getOptiXRayPayloadPtr())");
return true;
}
case kIROp_GetOptiXHitAttribute:
{
auto typeToFetch = inst->getOperand(0);
auto idxInst = as<IRIntLit>(inst->getOperand(1));
IRIntegerValue idx = idxInst->getValue();
if (typeToFetch->getOp() == kIROp_FloatType)
{
m_writer->emit("__int_as_float(optixGetAttribute_");
}
else
{
m_writer->emit("optixGetAttribute_");
}
m_writer->emit(idx);
if (typeToFetch->getOp() == kIROp_FloatType)
{
m_writer->emit("())");
}
else
{
m_writer->emit("()");
}
return true;
}
case kIROp_GetOptiXSbtDataPtr:
{
m_writer->emit("((");
emitType(inst->getDataType());
m_writer->emit(")optixGetSbtDataPointer())");
return true;
}
case kIROp_DispatchKernel:
{
auto dispatchInst = as<IRDispatchKernel>(inst);
emitOperand(dispatchInst->getBaseFn(), getInfo(EmitOp::Atomic));
m_writer->emit("<<<");
emitOperand(dispatchInst->getThreadGroupSize(), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(dispatchInst->getDispatchSize(), getInfo(EmitOp::General));
m_writer->emit(">>>(");
for (UInt i = 0; i < dispatchInst->getArgCount(); i++)
{
if (i > 0)
m_writer->emit(", ");
emitOperand(dispatchInst->getArg(i), getInfo(EmitOp::General));
}
m_writer->emit(")");
return true;
}
case kIROp_CUDALDG:
{
m_writer->emit("__ldg(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(")");
}
return true;
default:
break;
}
return Super::tryEmitInstExprImpl(inst, inOuterPrec);
}
void CUDASourceEmitter::handleRequiredCapabilitiesImpl(IRInst* inst)
{
// Does this function declare any requirements on CUDA capabilities
// that should affect output?
for (auto decoration : inst->getDecorations())
{
if (auto smDecoration = as<IRRequireCUDASMVersionDecoration>(decoration))
{
SemanticVersion version = smDecoration->getCUDASMVersion();
m_extensionTracker->requireSMVersion(version);
}
}
}
void CUDASourceEmitter::emitVectorTypeNameImpl(IRType* elementType, IRIntegerValue elementCount)
{
m_writer->emit(getVectorPrefix(elementType->getOp()));
m_writer->emit(elementCount);
}
void CUDASourceEmitter::emitSimpleTypeImpl(IRType* type)
{
switch (type->getOp())
{
case kIROp_VectorType:
{
auto vectorType = as<IRVectorType>(type);
m_writer->emit(getVectorPrefix(vectorType->getElementType()->getOp()));
m_writer->emit(as<IRIntLit>(vectorType->getElementCount())->getValue());
break;
}
default:
m_writer->emit(_getTypeName(type));
break;
}
}
void CUDASourceEmitter::emitRateQualifiersAndAddressSpaceImpl(
IRRate* rate,
[[maybe_unused]] AddressSpace addressSpace)
{
if (as<IRGroupSharedRate>(rate))
{
m_writer->emit("__shared__ ");
}
}
void CUDASourceEmitter::emitSimpleFuncParamsImpl(IRFunc* func)
{
m_writer->emit("(");
bool hasEmittedParam = false;
auto firstParam = func->getFirstParam();
for (auto pp = firstParam; pp; pp = pp->getNextParam())
{
auto varLayout = getVarLayout(pp);
if (varLayout && varLayout->findSystemValueSemanticAttr())
{
// If it has a semantic don't output, it will be accessed via a global
continue;
}
if (hasEmittedParam)
m_writer->emit(", ");
emitSimpleFuncParamImpl(pp);
hasEmittedParam = true;
}
m_writer->emit(")");
}
void CUDASourceEmitter::emitSimpleFuncImpl(IRFunc* func)
{
// Skip the CPP impl - as it does some processing we don't need here for entry points.
CLikeSourceEmitter::emitSimpleFuncImpl(func);
}
void CUDASourceEmitter::emitSimpleValueImpl(IRInst* inst)
{
// Make sure we convert float to half when emitting a half literal to avoid
// overload ambiguity errors from CUDA.
if (inst->getOp() == kIROp_FloatLit)
{
if (inst->getDataType()->getOp() == kIROp_HalfType)
{
m_writer->emit("__half(");
CLikeSourceEmitter::emitSimpleValueImpl(inst);
m_writer->emit(")");
return;
}
}
Super::emitSimpleValueImpl(inst);
}
void CUDASourceEmitter::emitSemanticsImpl(IRInst* inst, bool allowOffsetLayout)
{
Super::emitSemanticsImpl(inst, allowOffsetLayout);
}
void CUDASourceEmitter::emitInterpolationModifiersImpl(
IRInst* varInst,
IRType* valueType,
IRVarLayout* layout)
{
Super::emitInterpolationModifiersImpl(varInst, valueType, layout);
}
void CUDASourceEmitter::emitVarDecorationsImpl(IRInst* varDecl)
{
Super::emitVarDecorationsImpl(varDecl);
}
void CUDASourceEmitter::emitMatrixLayoutModifiersImpl(IRType* varType)
{
Super::emitMatrixLayoutModifiersImpl(varType);
}
bool CUDASourceEmitter::tryEmitGlobalParamImpl(IRGlobalParam* varDecl, IRType* varType)
{
// A global shader parameter in the IR for CUDA output will
// either be the unique constant buffer that wraps all the
// global-scope parameters in the original code (which is
// handled as a special-case before this routine would be
// called), or it is one of the system-defined varying inputs
// like `threadIdx`. We won't need to emit anything in the
// output code for the latter case, so we need to emit
// nothing here and return `true` so that the base class
// uses our logic instead of the default.
//
SLANG_UNUSED(varDecl);
SLANG_UNUSED(varType);
return true;
}
void CUDASourceEmitter::emitModuleImpl(IRModule* module, DiagnosticSink* sink)
{
// Set up with all of the base types used in the module
m_extensionTracker->requireBaseTypes(_findBaseTypesUsed(module));
CLikeSourceEmitter::emitModuleImpl(module, sink);
// Emit all witness table definitions.
_emitWitnessTableDefinitions();
}
} // namespace Slang
|