-
Notifications
You must be signed in to change notification settings - Fork 272
/
Copy pathslang-ir-autodiff.cpp
3946 lines (3465 loc) · 140 KB
/
slang-ir-autodiff.cpp
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
#include "slang-ir-autodiff.h"
#include "../core/slang-performance-profiler.h"
#include "slang-ir-address-analysis.h"
#include "slang-ir-autodiff-fwd.h"
#include "slang-ir-autodiff-pairs.h"
#include "slang-ir-autodiff-rev.h"
#include "slang-ir-inline.h"
#include "slang-ir-single-return.h"
#include "slang-ir-ssa-simplification.h"
#include "slang-ir-validate.h"
namespace Slang
{
bool isBackwardDifferentiableFunc(IRInst* func)
{
for (auto decorations : func->getDecorations())
{
switch (decorations->getOp())
{
case kIROp_BackwardDifferentiableDecoration:
case kIROp_UserDefinedBackwardDerivativeDecoration:
return true;
}
}
return false;
}
IRInst* _lookupWitness(
IRBuilder* builder,
IRInst* witness,
IRInst* requirementKey,
IRType* resultType = nullptr)
{
if (auto witnessTable = as<IRWitnessTable>(witness))
{
for (auto entry : witnessTable->getEntries())
{
if (entry->getRequirementKey() == requirementKey)
return entry->getSatisfyingVal();
}
}
else if (auto interfaceType = as<IRInterfaceType>(witness))
{
for (UIndex ii = 0; ii < interfaceType->getOperandCount(); ii++)
{
auto entry = cast<IRInterfaceRequirementEntry>(interfaceType->getOperand(ii));
if (entry->getRequirementKey() == requirementKey)
return entry->getRequirementVal();
}
}
else if (as<IRMakeWitnessPack>(witness))
{
// We are looking up a witness from a type pack.
// This is only allowed if we are looking up a differential type.
// We should turn this into an actual witness table for the type pack/tuple type.
SLANG_UNEXPECTED("looking up from a witness pack is invalid and should have been lowered.");
}
else
{
SLANG_ASSERT(resultType);
return builder->emitLookupInterfaceMethodInst(resultType, witness, requirementKey);
}
return nullptr;
}
static IRInst* _getDiffTypeFromPairType(
AutoDiffSharedContext* sharedContext,
IRBuilder* builder,
IRDifferentialPairTypeBase* type)
{
auto witness = type->getWitness();
SLANG_RELEASE_ASSERT(witness);
// Special case when the primal type is an InterfaceType/AssociatedType
if (as<IRInterfaceType>(type->getValueType()) || as<IRAssociatedType>(type->getValueType()))
{
// The differential type is the IDifferentiable interface type.
if (as<IRDifferentialPairType>(type) || as<IRDifferentialPairUserCodeType>(type))
return sharedContext->differentiableInterfaceType;
else if (as<IRDifferentialPtrPairType>(type))
return sharedContext->differentiablePtrInterfaceType;
else
SLANG_UNEXPECTED("Unexpected differential pair type");
}
if (as<IRDifferentialPairType>(type) || as<IRDifferentialPairUserCodeType>(type))
return _lookupWitness(
builder,
witness,
sharedContext->differentialAssocTypeStructKey,
builder->getTypeKind());
else if (as<IRDifferentialPtrPairType>(type))
return _lookupWitness(
builder,
witness,
sharedContext->differentialAssocRefTypeStructKey,
builder->getTypeKind());
else
SLANG_UNEXPECTED("Unexpected differential pair type");
}
static IRInst* _getDiffTypeWitnessFromPairType(
AutoDiffSharedContext* sharedContext,
IRBuilder* builder,
IRDifferentialPairTypeBase* type)
{
auto witnessTable = type->getWitness();
if (as<IRDifferentialPairType>(type) || as<IRDifferentialPairUserCodeType>(type))
return _lookupWitness(
builder,
witnessTable,
sharedContext->differentialAssocTypeWitnessStructKey,
sharedContext->differentialAssocTypeWitnessTableType);
else if (as<IRDifferentialPtrPairType>(type))
return _lookupWitness(
builder,
witnessTable,
sharedContext->differentialAssocRefTypeWitnessStructKey,
sharedContext->differentialAssocRefTypeWitnessTableType);
else
SLANG_UNEXPECTED("Unexpected differential pair type");
}
bool isNoDiffType(IRType* paramType)
{
while (paramType)
{
if (auto attrType = as<IRAttributedType>(paramType))
{
if (attrType->findAttr<IRNoDiffAttr>())
return true;
paramType = attrType->getBaseType();
}
else if (auto ptrType = asRelevantPtrType(paramType))
{
paramType = ptrType->getValueType();
}
else
{
return false;
}
}
return false;
}
IRInst* lookupForwardDerivativeReference(IRInst* primalFunction)
{
if (auto jvpDefinition = primalFunction->findDecoration<IRForwardDerivativeDecoration>())
return jvpDefinition->getForwardDerivativeFunc();
return nullptr;
}
IRInst* DifferentialPairTypeBuilder::findSpecializationForParam(
IRInst* specializeInst,
IRInst* genericParam)
{
// Get base generic that's being specialized.
auto genericType = as<IRGeneric>(as<IRSpecialize>(specializeInst)->getBase());
SLANG_ASSERT(genericType);
// Find the index of genericParam in the base generic.
int paramIndex = -1;
int currentIndex = 0;
for (auto param : genericType->getParams())
{
if (param == genericParam)
paramIndex = currentIndex;
currentIndex++;
}
SLANG_ASSERT(paramIndex >= 0);
// Return the corresponding operand in the specialization inst.
return specializeInst->getOperand(1 + paramIndex);
}
IRInst* DifferentialPairTypeBuilder::emitFieldAccessor(
IRBuilder* builder,
IRInst* baseInst,
IRStructKey* key)
{
IRInst* pairType = nullptr;
if (auto basePtrType = asRelevantPtrType(baseInst->getDataType()))
{
auto loweredType = lowerDiffPairType(builder, basePtrType->getValueType());
pairType = builder->getPtrType(kIROp_PtrType, (IRType*)loweredType);
}
else
{
auto loweredType = lowerDiffPairType(builder, baseInst->getDataType());
pairType = loweredType;
}
if (auto basePairStructType = as<IRStructType>(pairType))
{
return as<IRFieldExtract>(builder->emitFieldExtract(
findStructField(basePairStructType, key)->getFieldType(),
baseInst,
key));
}
else if (auto ptrType = asRelevantPtrType(pairType))
{
if (auto ptrInnerSpecializedType = as<IRSpecialize>(ptrType->getValueType()))
{
auto genericType =
findInnerMostGenericReturnVal(as<IRGeneric>(ptrInnerSpecializedType->getBase()));
if (const auto genericBasePairStructType = as<IRStructType>(genericType))
{
return as<IRFieldAddress>(builder->emitFieldAddress(
builder->getPtrType((IRType*)findSpecializationForParam(
ptrInnerSpecializedType,
findStructField(ptrInnerSpecializedType, key)->getFieldType())),
baseInst,
key));
}
}
else if (auto ptrBaseStructType = as<IRStructType>(ptrType->getValueType()))
{
return as<IRFieldAddress>(builder->emitFieldAddress(
builder->getPtrType(
(IRType*)findStructField(ptrBaseStructType, key)->getFieldType()),
baseInst,
key));
}
}
else if (auto specializedType = as<IRSpecialize>(pairType))
{
auto genericType = findInnerMostGenericReturnVal(as<IRGeneric>(specializedType->getBase()));
if (auto genericBasePairStructType = as<IRStructType>(genericType))
{
return as<IRFieldExtract>(builder->emitFieldExtract(
(IRType*)findSpecializationForParam(
specializedType,
findStructField(genericBasePairStructType, key)->getFieldType()),
baseInst,
key));
}
else if (auto genericPtrType = asRelevantPtrType(genericType))
{
if (auto genericPairStructType = as<IRStructType>(genericPtrType->getValueType()))
{
return as<IRFieldAddress>(builder->emitFieldAddress(
builder->getPtrType((IRType*)findSpecializationForParam(
specializedType,
findStructField(genericPairStructType, key)->getFieldType())),
baseInst,
key));
}
}
}
else
{
SLANG_UNEXPECTED("Unrecognized field. Cannot emit field accessor");
}
return nullptr;
}
bool isExistentialOrRuntimeInst(IRInst* inst)
{
if (auto lookup = as<IRLookupWitnessMethod>(inst))
{
return isExistentialOrRuntimeInst(lookup->getWitnessTable());
}
return as<IRExtractExistentialType>(inst) || as<IRExtractExistentialWitnessTable>(inst) ||
as<IRMakeExistential>(inst) || as<IRInterfaceType>(inst->getDataType());
}
bool isRuntimeType(IRType* type)
{
if (as<IRExtractExistentialType>(type))
return true;
if (auto lookup = as<IRLookupWitnessMethod>(type))
{
return isExistentialOrRuntimeInst(lookup->getWitnessTable());
}
return false;
}
IRInst* getExistentialBaseWitnessTable(IRBuilder* builder, IRType* type)
{
if (auto lookupWitnessMethod = as<IRLookupWitnessMethod>(type))
{
return lookupWitnessMethod->getWitnessTable();
}
else if (auto extractExistentialType = as<IRExtractExistentialType>(type))
{
return builder->emitExtractExistentialWitnessTable(extractExistentialType->getOperand(0));
}
else
{
SLANG_UNEXPECTED("Unexpected existential type");
}
}
IRInst* getCacheKey(IRBuilder* builder, IRInst* primalType)
{
if (auto lookupWitness = as<IRLookupWitnessMethod>(primalType))
return lookupWitness->getRequirementKey();
else if (auto extractExistentialType = as<IRExtractExistentialType>(primalType))
{
auto interfaceType = extractExistentialType->getOperand(0)->getDataType();
// We will cache on the interface's this-type, since the interface type itself can be
// deallocated during the lowering process.
//
return builder->getThisType(interfaceType);
}
return primalType;
}
IRInst* DifferentialPairTypeBuilder::emitExistentialMakePair(
IRBuilder* builder,
IRInst* pairType,
IRInst* primalInst,
IRInst* diffInst)
{
auto baseWitness = getExistentialBaseWitnessTable(builder, (IRType*)pairType);
auto pairTypeKey = cast<IRLookupWitnessMethod>(pairType)->getRequirementKey();
auto makePairKey = makePairKeyMap[pairTypeKey];
auto makePairMethod = builder->emitLookupInterfaceMethodInst(
makePairFuncTypeMap[makePairKey],
baseWitness,
makePairKey);
List<IRInst*> args;
args.add(primalInst);
args.add(diffInst);
auto makePairVal = builder->emitCallInst((IRType*)pairType, makePairMethod, args);
return makePairVal;
}
IRInst* DifferentialPairTypeBuilder::emitPrimalFieldAccess(
IRBuilder* builder,
IRType* loweredPairType,
IRInst* baseInst)
{
if (isRuntimeType(loweredPairType))
{
auto baseWitness = getExistentialBaseWitnessTable(builder, (IRType*)loweredPairType);
auto pairTypeKey = cast<IRLookupWitnessMethod>(loweredPairType)->getRequirementKey();
auto getPrimalKey = getPrimalKeyMap[pairTypeKey];
auto primalFieldMethod = builder->emitLookupInterfaceMethodInst(
getPrimalFuncTypeMap[getPrimalKey],
baseWitness,
getPrimalKey);
auto primalFieldVal =
builder->emitCallInst(primalTypeMap[loweredPairType], primalFieldMethod, baseInst);
return primalFieldVal;
}
else
{
return emitFieldAccessor(builder, baseInst, this->globalPrimalKey);
}
}
IRInst* DifferentialPairTypeBuilder::emitDiffFieldAccess(
IRBuilder* builder,
IRType* loweredPairType,
IRInst* baseInst)
{
if (isRuntimeType(loweredPairType))
{
auto baseWitness = getExistentialBaseWitnessTable(builder, (IRType*)loweredPairType);
auto pairTypeKey = cast<IRLookupWitnessMethod>(loweredPairType)->getRequirementKey();
auto getDiffKey = getDiffKeyMap[pairTypeKey];
auto diffFieldMethod = builder->emitLookupInterfaceMethodInst(
getDiffFuncTypeMap[getDiffKey],
baseWitness,
getDiffKey);
auto diffFieldVal =
builder->emitCallInst(diffTypeMap[loweredPairType], diffFieldMethod, baseInst);
return diffFieldVal;
}
else
{
return emitFieldAccessor(builder, baseInst, this->globalDiffKey);
}
}
IRStructKey* DifferentialPairTypeBuilder::_getOrCreateDiffStructKey()
{
if (!this->globalDiffKey)
{
IRBuilder builder(sharedContext->moduleInst);
// Insert directly at top level (skip any generic scopes etc.)
builder.setInsertInto(sharedContext->moduleInst);
this->globalDiffKey = builder.createStructKey();
builder.addNameHintDecoration(
this->globalDiffKey,
UnownedTerminatedStringSlice("differential"));
}
return this->globalDiffKey;
}
IRStructKey* DifferentialPairTypeBuilder::_getOrCreatePrimalStructKey()
{
if (!this->globalPrimalKey)
{
// Insert directly at top level (skip any generic scopes etc.)
IRBuilder builder(sharedContext->moduleInst);
builder.setInsertInto(sharedContext->moduleInst);
this->globalPrimalKey = builder.createStructKey();
builder.addNameHintDecoration(
this->globalPrimalKey,
UnownedTerminatedStringSlice("primal"));
}
return this->globalPrimalKey;
}
IRInst* DifferentialPairTypeBuilder::getOrCreateCommonDiffPairInterface(IRBuilder* builder)
{
if (!this->commonDiffPairInterface)
{
this->commonDiffPairInterface = builder->createInterfaceType(0, nullptr);
builder->addNameHintDecoration(
this->commonDiffPairInterface,
UnownedStringSlice("IDiffPair"));
}
return this->commonDiffPairInterface;
}
IRInst* DifferentialPairTypeBuilder::_createDiffPairInterfaceRequirement(
IRType* origBaseType,
IRType*)
{
// We will create an interface requirement for the type's pair & then create implementations in
// all the implementing witness tables.
//
IRBuilder builder(sharedContext->moduleInst);
// Find the right interface to put the requirement in.
IRInterfaceType* interfaceType = nullptr;
// Find the effective type to put in the requirement entry
// for the base type
//
IRType* requirementBaseType = nullptr;
// Requirement key (only used for associated types)
//
IRInst* requirementKey = nullptr;
// Add a name hint to the key.
StringBuilder nameBuilderReqKey;
nameBuilderReqKey << "DiffPair_Req_";
if (auto lookup = as<IRLookupWitnessMethod>(origBaseType))
{
interfaceType =
cast<IRInterfaceType>(cast<IRWitnessTableType>(lookup->getWitnessTable()->getDataType())
->getConformanceType());
requirementBaseType =
cast<IRType>(findInterfaceRequirement(interfaceType, lookup->getRequirementKey()));
requirementKey = lookup->getRequirementKey();
if (auto nameHint = lookup->getRequirementKey()->findDecoration<IRNameHintDecoration>())
{
nameBuilderReqKey << nameHint->getName();
}
else
{
nameBuilderReqKey << "unknown_assoc_type";
}
}
else if (auto extractType = as<IRExtractExistentialType>(origBaseType))
{
auto existentialType = extractType->getOperand(0);
interfaceType = cast<IRInterfaceType>(existentialType->getDataType());
requirementBaseType = builder.getThisType(interfaceType);
requirementKey = nullptr;
if (auto nameHint = interfaceType->findDecoration<IRNameHintDecoration>())
{
nameBuilderReqKey << nameHint->getName();
}
else
{
nameBuilderReqKey << "unknown_interface_type";
}
}
else
{
SLANG_UNEXPECTED("Unexpected type for differential pair interface requirement");
}
auto diffPairInterfaceType =
cast<IRInterfaceType>(getOrCreateCommonDiffPairInterface(&builder));
// Add 4 requirements to the interface:
// the associated pair type, getPrimal, getDiff & makePair
//
builder.setInsertInto(interfaceType);
IRStructKey* diffPairRequirementKey = builder.createStructKey();
IRStructKey* getPrimalRequirementKey = builder.createStructKey();
IRStructKey* getDiffRequirementKey = builder.createStructKey();
IRStructKey* makePairRequirementKey = builder.createStructKey();
makePairKeyMap[diffPairRequirementKey] = makePairRequirementKey;
getPrimalKeyMap[diffPairRequirementKey] = getPrimalRequirementKey;
getDiffKeyMap[diffPairRequirementKey] = getDiffRequirementKey;
List<IRInst*> entries;
// Add all the old requirements to the new interface.
for (UInt i = 0; i < interfaceType->getOperandCount(); i++)
entries.add(interfaceType->getOperand(i));
//
// Create the new requirement entries.
//
{
// Create & insert the requirement key.
List<IRInterfaceType*> constraintTypes;
constraintTypes.add(diffPairInterfaceType);
auto entry = builder.createInterfaceRequirementEntry(
diffPairRequirementKey,
builder.getAssociatedType(constraintTypes.getArrayView()));
builder.addNameHintDecoration(diffPairRequirementKey, nameBuilderReqKey.getUnownedSlice());
entries.add(entry);
}
{
// Create & insert the getPrimal requirement.
List<IRType*> paramTypes;
List<IRInterfaceType*> paramConstraintTypes;
paramConstraintTypes.add(diffPairInterfaceType);
paramTypes.add(builder.getAssociatedType(paramConstraintTypes.getArrayView()));
auto entryFuncType = builder.getFuncType(paramTypes, requirementBaseType);
auto entry =
builder.createInterfaceRequirementEntry(getPrimalRequirementKey, entryFuncType);
getPrimalFuncTypeMap[getPrimalRequirementKey] = entryFuncType;
StringBuilder entryNameBuilder;
entryNameBuilder << nameBuilderReqKey.getUnownedSlice() << "_getPrimal";
builder.addNameHintDecoration(entry, entryNameBuilder.getUnownedSlice());
entries.add(entry);
}
{
// Create & insert the getDiff requirement.
List<IRType*> paramTypes;
List<IRInterfaceType*> paramConstraintTypes;
paramConstraintTypes.add(diffPairInterfaceType);
paramTypes.add(builder.getAssociatedType(paramConstraintTypes.getArrayView()));
List<IRInterfaceType*> resultConstraintTypes;
resultConstraintTypes.add(sharedContext->differentiableInterfaceType);
auto resultType = builder.getAssociatedType(resultConstraintTypes.getArrayView());
auto entryFuncType = builder.getFuncType(paramTypes, resultType);
auto entry = builder.createInterfaceRequirementEntry(getDiffRequirementKey, entryFuncType);
getDiffFuncTypeMap[getDiffRequirementKey] = entryFuncType;
StringBuilder entryNameBuilder;
entryNameBuilder << nameBuilderReqKey.getUnownedSlice() << "_getDiff";
builder.addNameHintDecoration(entry, entryNameBuilder.getUnownedSlice());
entries.add(entry);
}
{
// Create & insert the makePair requirement.
List<IRType*> paramTypes;
paramTypes.add(requirementBaseType);
List<IRInterfaceType*> paramConstraintTypes;
paramConstraintTypes.add(sharedContext->differentiableInterfaceType);
paramTypes.add(builder.getAssociatedType(paramConstraintTypes.getArrayView()));
List<IRInterfaceType*> resultConstraintTypes;
resultConstraintTypes.add(diffPairInterfaceType);
auto entryFuncType = builder.getFuncType(
paramTypes,
builder.getAssociatedType(resultConstraintTypes.getArrayView()));
auto entry = builder.createInterfaceRequirementEntry(makePairRequirementKey, entryFuncType);
makePairFuncTypeMap[makePairRequirementKey] = entryFuncType;
StringBuilder entryNameBuilder;
entryNameBuilder << nameBuilderReqKey.getUnownedSlice() << "_makePair";
builder.addNameHintDecoration(entry, entryNameBuilder.getUnownedSlice());
entries.add(entry);
}
{
// Create the new interface type.
auto newInterfaceType =
builder.createInterfaceType(entries.getCount(), entries.getBuffer());
// Transfer decorations from the old interface to the new one.
interfaceType->transferDecorationsTo(newInterfaceType);
interfaceType->replaceUsesWith(newInterfaceType);
// Replace the interface maps in the caches.
if (this->pairTypeCache.containsKey(interfaceType))
this->pairTypeCache[newInterfaceType] = this->pairTypeCache[interfaceType];
if (this->existentialPairTypeCache.containsKey(interfaceType))
this->existentialPairTypeCache[newInterfaceType] =
this->existentialPairTypeCache[interfaceType];
interfaceType->removeAndDeallocate();
interfaceType = newInterfaceType;
}
//
// Implement the requirements in all the witness tables.
//
// Collect all witness tables of the given interfaceType.
List<IRWitnessTable*> concreteWitnessTables;
auto witnessTableType = builder.getWitnessTableType(interfaceType);
for (auto use = witnessTableType->firstUse; use; use = use->nextUse)
{
if (auto witnessTable = as<IRWitnessTable>(use->getUser()))
{
if (use->getUser()->getFullType() == witnessTableType)
concreteWitnessTables.add(witnessTable);
}
}
DifferentiableTypeConformanceContext ctx(sharedContext);
ctx.buildGlobalWitnessDictionary();
for (auto concreteWitnessTable : concreteWitnessTables)
{
IRType* concretePrimalType = nullptr;
// What requirement are we trying to satisfy?
if (as<IRThisType>(requirementBaseType))
{
// For this types, we should lower the concrete type of the witness table itself.
concretePrimalType = concreteWitnessTable->getConcreteType();
}
else if (as<IRAssociatedType>(requirementBaseType))
{
// For associated types, look it up in the witness table.
concretePrimalType =
(IRType*)findWitnessTableEntry(concreteWitnessTable, requirementKey);
}
else
{
// We shouldn't see any other case here.
SLANG_UNEXPECTED("Unexpected requirement base type");
}
// Create the pair type.
auto witness = ctx.tryGetDifferentiableWitness(
&builder,
concretePrimalType,
DiffConformanceKind::Value);
// Really should not see a case where the original interface is differentiable, but
// we can't find the witness table.
//
SLANG_ASSERT(witness);
auto concretePairType = builder.getDifferentialPairType(
concretePrimalType,
witness); // TODO: Need to handle the other conformance kinds
auto concreteDiffType =
(IRType*)_getDiffTypeFromPairType(sharedContext, &builder, concretePairType);
auto loweredStructType = (IRType*)lowerDiffPairType(&builder, concretePairType);
// Create an (empty) witness table for loweredStuctType : IDiffPair_...
// This is just so that there is a bound on the any-value-size for each group of pair types.
//
auto witnessTable = builder.createWitnessTable(diffPairInterfaceType, loweredStructType);
builder.addKeepAliveDecoration(witnessTable);
builder.setInsertInto(concreteWitnessTable);
// Create the associated type entry.
{
builder.createWitnessTableEntry(
concreteWitnessTable,
diffPairRequirementKey,
loweredStructType);
}
// Create the getPrimal method.
{
auto primalMethod = builder.createFunc();
StringBuilder nameBuilder;
getTypeNameHint(nameBuilder, loweredStructType);
nameBuilder << "_getPrimal";
builder.addNameHintDecoration(primalMethod, nameBuilder.getUnownedSlice());
primalMethod->setFullType(builder.getFuncType(
List<IRType*>({(IRType*)loweredStructType}),
concretePrimalType));
builder.setInsertInto(primalMethod);
auto block = builder.emitBlock();
builder.setInsertInto(block);
auto param = builder.emitParam((IRType*)loweredStructType);
builder.emitReturn(
builder.emitFieldExtract(concretePrimalType, param, _getOrCreatePrimalStructKey()));
builder.setInsertInto(concreteWitnessTable);
builder.createWitnessTableEntry(
concreteWitnessTable,
getPrimalRequirementKey,
primalMethod);
}
// Create the getDiff method.
{
auto diffMethod = builder.createFunc();
StringBuilder nameBuilder;
getTypeNameHint(nameBuilder, loweredStructType);
nameBuilder << "_getDiff";
builder.addNameHintDecoration(diffMethod, nameBuilder.getUnownedSlice());
diffMethod->setFullType(
builder.getFuncType(List<IRType*>({(IRType*)loweredStructType}), concreteDiffType));
builder.setInsertInto(diffMethod);
auto block = builder.emitBlock();
builder.setInsertInto(block);
auto param = builder.emitParam((IRType*)loweredStructType);
builder.emitReturn(
builder.emitFieldExtract(concreteDiffType, param, _getOrCreateDiffStructKey()));
builder.setInsertInto(concreteWitnessTable);
builder.createWitnessTableEntry(
concreteWitnessTable,
getDiffRequirementKey,
diffMethod);
}
// Create the makePair method.
{
auto makePairMethod = builder.createFunc();
StringBuilder nameBuilder;
getTypeNameHint(nameBuilder, loweredStructType);
nameBuilder << "_makePair";
builder.addNameHintDecoration(makePairMethod, nameBuilder.getUnownedSlice());
makePairMethod->setFullType(builder.getFuncType(
List<IRType*>({concretePrimalType, concreteDiffType}),
(IRType*)loweredStructType));
builder.setInsertInto(makePairMethod);
auto block = builder.emitBlock();
builder.setInsertInto(block);
auto param1 = builder.emitParam(concretePrimalType);
auto param2 = builder.emitParam(concreteDiffType);
List<IRInst*> args = {param1, param2};
auto pair = builder.emitMakeStruct((IRType*)loweredStructType, args);
builder.emitReturn(pair);
builder.setInsertInto(concreteWitnessTable);
builder.createWitnessTableEntry(
concreteWitnessTable,
makePairRequirementKey,
makePairMethod);
}
}
return diffPairRequirementKey;
}
IRInst* DifferentialPairTypeBuilder::_createDiffPairType(IRType* origBaseType, IRType* diffType)
{
switch (origBaseType->getOp())
{
case kIROp_LookupWitness:
case kIROp_Specialize:
case kIROp_Param:
return nullptr;
default:
break;
}
IRBuilder builder(sharedContext->moduleInst);
builder.setInsertBefore(diffType);
auto pairStructType = builder.createStructType();
StringBuilder nameBuilder;
nameBuilder << "DiffPair_";
getTypeNameHint(nameBuilder, origBaseType);
builder.addNameHintDecoration(pairStructType, nameBuilder.toString().getUnownedSlice());
builder.createStructField(pairStructType, _getOrCreatePrimalStructKey(), origBaseType);
builder.createStructField(pairStructType, _getOrCreateDiffStructKey(), (IRType*)diffType);
return pairStructType;
}
IRInst* DifferentialPairTypeBuilder::lowerDiffPairType(IRBuilder* builder, IRType* originalPairType)
{
IRInst* result = nullptr;
auto pairType = as<IRDifferentialPairTypeBase>(originalPairType);
if (!pairType)
return originalPairType;
// We make our type cache keyed on the primal type, not the pair type.
// This is because there may be duplicate pair types for the same
// primal type but different witness tables, and we don't want to treat
// them as distinct.
// We might want to consider making witness tables part of IR
// deduplication (make them HOISTABLE insts), but that is a bigger
// change. Another alternative is to make the witness operand of
// `IRDifferentialPairTypeBase` be child instead of an operand
// so that it is not considered part of the type for deduplication
// purposes.
auto primalType = pairType->getValueType();
if (isRuntimeType(primalType))
{
// Existential case.
auto cacheKey = getCacheKey(builder, primalType);
auto diffType = _getDiffTypeFromPairType(sharedContext, builder, pairType);
IRInst* pairReqKey = nullptr;
if (!existentialPairTypeCache.tryGetValue(cacheKey, pairReqKey))
{
pairReqKey = _createDiffPairInterfaceRequirement(primalType, (IRType*)diffType);
existentialPairTypeCache.add(cacheKey, pairReqKey);
}
auto baseWitnessTable = getExistentialBaseWitnessTable(builder, primalType);
result = builder->emitLookupInterfaceMethodInst(
builder->getTypeKind(),
baseWitnessTable,
pairReqKey);
primalTypeMap[result] = primalType;
diffTypeMap[result] = (IRType*)diffType;
return result;
}
else if (auto typePack = as<IRTypePack>(primalType))
{
// Lower DiffPair(TypePack(a_0, a_1, ...), MakeWitnessPack(w_0, w_1, ...)) as
// TypePack(DiffPair(a_0, w_0), DiffPair(a_1, w_1), ...)
//
auto cacheKey = primalType;
if (pairTypeCache.tryGetValue(cacheKey, result))
return result;
auto packWitness = pairType->getWitness();
// Right now we only support concrete witness tables for type packs.
auto concretePackWitness = as<IRWitnessTable>(packWitness);
SLANG_ASSERT(concretePackWitness);
// Get diff type pack.
IRTypePack* diffTypePack = nullptr;
if (concretePackWitness->getConformanceType() ==
this->sharedContext->differentiableInterfaceType)
diffTypePack = as<IRTypePack>(findWitnessTableEntry(
concretePackWitness,
this->sharedContext->differentialAssocTypeStructKey));
else if (
concretePackWitness->getConformanceType() ==
this->sharedContext->differentiablePtrInterfaceType)
diffTypePack = as<IRTypePack>(findWitnessTableEntry(
concretePackWitness,
this->sharedContext->differentialAssocRefTypeStructKey));
else
SLANG_UNEXPECTED("Unexpected witness table");
SLANG_ASSERT(diffTypePack);
List<IRType*> args;
for (UInt i = 0; i < typePack->getOperandCount(); i++)
{
auto type = (IRType*)typePack->getOperand(i);
auto diffType = (IRType*)typePack->getOperand(i);
if (pairTypeCache.tryGetValue(type, result))
{
args.add((IRType*)result);
continue;
}
// Lower the diff pair type.
auto loweredPairType = (IRType*)_createDiffPairType(type, diffType);
pairTypeCache.add(type, loweredPairType);
args.add(loweredPairType);
}
auto loweredTypePack = builder->getTypePack(args.getCount(), args.getBuffer());
// TODO: Unify the cache between the three cases.
pairTypeCache.add(cacheKey, loweredTypePack);
return loweredTypePack;
}
else
{
auto cacheKey = primalType;
if (pairTypeCache.tryGetValue(primalType, result))
return result;
if (as<IRParam, IRDynamicCastBehavior::NoUnwrap>(primalType))
{
result = nullptr;
return result;
}
if (as<IRThisType>(primalType) || as<IRAssociatedType>(primalType))
{
List<IRInterfaceType*> constraintTypes;
constraintTypes.add(this->commonDiffPairInterface);
return builder->getAssociatedType(constraintTypes.getArrayView());
}
auto diffType = _getDiffTypeFromPairType(sharedContext, builder, pairType);
if (!diffType)
return result;
// Concrete case.
result = _createDiffPairType(primalType, (IRType*)diffType);
pairTypeCache.add(cacheKey, result);
return result;
}
}
IRInterfaceType* findDifferentiableRefInterface(IRModuleInst* moduleInst)
{
for (auto inst : moduleInst->getGlobalInsts())
{
if (auto interfaceType = as<IRInterfaceType>(inst))
{
if (auto decor = interfaceType->findDecoration<IRNameHintDecoration>())
{
if (decor->getName() == "IDifferentiablePtrType")
{
return interfaceType;
}
}
}
}
return nullptr;
}
AutoDiffSharedContext::AutoDiffSharedContext(TargetProgram* target, IRModuleInst* inModuleInst)
: moduleInst(inModuleInst), targetProgram(target)
{
differentiableInterfaceType = as<IRInterfaceType>(findDifferentiableInterface());
if (differentiableInterfaceType)
{
differentialAssocTypeStructKey = findDifferentialTypeStructKey();
differentialAssocTypeWitnessStructKey = findDifferentialTypeWitnessStructKey();
differentialAssocTypeWitnessTableType = findDifferentialTypeWitnessTableType();
zeroMethodStructKey = findZeroMethodStructKey();
zeroMethodType = cast<IRFuncType>(
getInterfaceEntryAtIndex(differentiableInterfaceType, 2)->getRequirementVal());
addMethodStructKey = findAddMethodStructKey();