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
|
// ir-link.cpp
#include "ir-link.h"
#include "ir.h"
#include "ir-insts.h"
#include "mangle.h"
namespace Slang
{
// Needed for lookup up entry-point layouts.
//
// TODO: maybe arrange so that codegen is driven from the layout layer
// instead of the input/request layer.
EntryPointLayout* findEntryPointLayout(
ProgramLayout* programLayout,
EntryPointRequest* entryPointRequest);
struct IRSpecSymbol : RefObject
{
IRInst* irGlobalValue;
RefPtr<IRSpecSymbol> nextWithSameName;
};
struct IRSpecEnv
{
IRSpecEnv* parent = nullptr;
// A map from original values to their cloned equivalents.
typedef Dictionary<IRInst*, IRInst*> ClonedValueDictionary;
ClonedValueDictionary clonedValues;
};
struct IRSharedSpecContext
{
// The code-generation target in use
CodeGenTarget target;
// The specialized module we are building
RefPtr<IRModule> module;
// The original, unspecialized module we are copying
IRModule* originalModule;
// A map from mangled symbol names to zero or
// more global IR values that have that name,
// in the *original* module.
typedef Dictionary<String, RefPtr<IRSpecSymbol>> SymbolDictionary;
SymbolDictionary symbols;
SharedIRBuilder sharedBuilderStorage;
IRBuilder builderStorage;
// The "global" specialization environment.
IRSpecEnv globalEnv;
};
struct IRSpecContextBase
{
// A map from the mangled name of a global variable
// to the layout to use for it.
Dictionary<String, VarLayout*> globalVarLayouts;
IRSharedSpecContext* shared;
IRSharedSpecContext* getShared() { return shared; }
IRModule* getModule() { return getShared()->module; }
IRModule* getOriginalModule() { return getShared()->originalModule; }
IRSharedSpecContext::SymbolDictionary& getSymbols() { return getShared()->symbols; }
// The current specialization environment to use.
IRSpecEnv* env = nullptr;
IRSpecEnv* getEnv()
{
// TODO: need to actually establish environments on contexts we create.
//
// Or more realistically we need to change the whole approach
// to specialization and cloning so that we don't try to share
// logic between two very different cases.
return env;
}
// The IR builder to use for creating nodes
IRBuilder* builder;
// A callback to be used when a value that is not registerd in `clonedValues`
// is needed during cloning. This gives the subtype a chance to intercept
// the operation and clone (or not) as needed.
virtual IRInst* maybeCloneValue(IRInst* originalVal)
{
return originalVal;
}
};
void registerClonedValue(
IRSpecContextBase* context,
IRInst* clonedValue,
IRInst* originalValue)
{
if(!originalValue)
return;
// TODO: now that things are scoped using environments, we
// shouldn't be running into the cases where a value with
// the same key already exists. This should be changed to
// an `Add()` call.
//
context->getEnv()->clonedValues[originalValue] = clonedValue;
}
// Information on values to use when registering a cloned value
struct IROriginalValuesForClone
{
IRInst* originalVal = nullptr;
IRSpecSymbol* sym = nullptr;
IROriginalValuesForClone() {}
IROriginalValuesForClone(IRInst* originalValue)
: originalVal(originalValue)
{}
IROriginalValuesForClone(IRSpecSymbol* symbol)
: sym(symbol)
{}
};
void registerClonedValue(
IRSpecContextBase* context,
IRInst* clonedValue,
IROriginalValuesForClone const& originalValues)
{
registerClonedValue(context, clonedValue, originalValues.originalVal);
for( auto s = originalValues.sym; s; s = s->nextWithSameName )
{
registerClonedValue(context, clonedValue, s->irGlobalValue);
}
}
IRInst* cloneInst(
IRSpecContextBase* context,
IRBuilder* builder,
IRInst* originalInst,
IROriginalValuesForClone const& originalValues);
IRInst* cloneInst(
IRSpecContextBase* context,
IRBuilder* builder,
IRInst* originalInst)
{
return cloneInst(context, builder, originalInst, originalInst);
}
/// Clone any decorations from `originalValue` onto `clonedValue`
void cloneDecorations(
IRSpecContextBase* context,
IRInst* clonedValue,
IRInst* originalValue)
{
// TODO: In many cases we might be able to use this as a general-purpose
// place to do cloning of *all* the children of an instruction, and
// not just its decorations. We should look to refactor this code
// later.
IRBuilder builderStorage = *context->builder;
IRBuilder* builder = &builderStorage;
builder->setInsertInto(clonedValue);
SLANG_UNUSED(context);
for(auto originalDecoration : originalValue->getDecorations())
{
cloneInst(context, builder, originalDecoration);
}
// We will also clone the location here, just because this is a convenient bottleneck
clonedValue->sourceLoc = originalValue->sourceLoc;
}
/// Clone any decorations and children from `originalValue` onto `clonedValue`
void cloneDecorationsAndChildren(
IRSpecContextBase* context,
IRInst* clonedValue,
IRInst* originalValue)
{
IRBuilder builderStorage = *context->builder;
IRBuilder* builder = &builderStorage;
builder->setInsertInto(clonedValue);
SLANG_UNUSED(context);
for(auto originalItem : originalValue->getDecorationsAndChildren())
{
cloneInst(context, builder, originalItem);
}
// We will also clone the location here, just because this is a convenient bottleneck
clonedValue->sourceLoc = originalValue->sourceLoc;
}
// We use an `IRSpecContext` for the case where we are cloning
// code from one or more input modules to create a "linked" output
// module. Along the way, we will resolve profile-specific functions
// to the best definition for a given target.
//
struct IRSpecContext : IRSpecContextBase
{
// Override the "maybe clone" logic so that we always clone
virtual IRInst* maybeCloneValue(IRInst* originalVal) override;
};
IRInst* cloneGlobalValue(IRSpecContext* context, IRInst* originalVal);
IRInst* cloneValue(
IRSpecContextBase* context,
IRInst* originalValue);
IRType* cloneType(
IRSpecContextBase* context,
IRType* originalType);
IRInst* IRSpecContext::maybeCloneValue(IRInst* originalValue)
{
switch (originalValue->op)
{
case kIROp_StructType:
case kIROp_Func:
case kIROp_Generic:
case kIROp_GlobalVar:
case kIROp_GlobalConstant:
case kIROp_GlobalParam:
case kIROp_StructKey:
case kIROp_GlobalGenericParam:
case kIROp_WitnessTable:
return cloneGlobalValue(this, originalValue);
case kIROp_BoolLit:
{
IRConstant* c = (IRConstant*)originalValue;
return builder->getBoolValue(c->value.intVal != 0);
}
break;
case kIROp_IntLit:
{
IRConstant* c = (IRConstant*)originalValue;
return builder->getIntValue(cloneType(this, c->getDataType()), c->value.intVal);
}
break;
case kIROp_FloatLit:
{
IRConstant* c = (IRConstant*)originalValue;
return builder->getFloatValue(cloneType(this, c->getDataType()), c->value.floatVal);
}
break;
case kIROp_StringLit:
{
IRConstant* c = (IRConstant*)originalValue;
return builder->getStringValue(c->getStringSlice());
}
break;
case kIROp_PtrLit:
{
IRConstant* c = (IRConstant*)originalValue;
return builder->getPtrValue(c->value.ptrVal);
}
break;
default:
{
// In the deafult case, assume that we have some sort of "hoistable"
// instruction that requires us to create a clone of it.
UInt argCount = originalValue->getOperandCount();
IRInst* clonedValue = builder->createIntrinsicInst(
cloneType(this, originalValue->getFullType()),
originalValue->op,
argCount, nullptr);
registerClonedValue(this, clonedValue, originalValue);
for (UInt aa = 0; aa < argCount; ++aa)
{
IRInst* originalArg = originalValue->getOperand(aa);
IRInst* clonedArg = cloneValue(this, originalArg);
clonedValue->getOperands()[aa].init(clonedValue, clonedArg);
}
cloneDecorationsAndChildren(this, clonedValue, originalValue);
addHoistableInst(builder, clonedValue);
return clonedValue;
}
break;
}
}
IRInst* cloneValue(
IRSpecContextBase* context,
IRInst* originalValue);
// Find a pre-existing cloned value, or return null if none is available.
IRInst* findClonedValue(
IRSpecContextBase* context,
IRInst* originalValue)
{
IRInst* clonedValue = nullptr;
for (auto env = context->getEnv(); env; env = env->parent)
{
if (env->clonedValues.TryGetValue(originalValue, clonedValue))
{
return clonedValue;
}
}
return nullptr;
}
IRInst* cloneValue(
IRSpecContextBase* context,
IRInst* originalValue)
{
if (!originalValue)
return nullptr;
if (IRInst* clonedValue = findClonedValue(context, originalValue))
return clonedValue;
return context->maybeCloneValue(originalValue);
}
IRType* cloneType(
IRSpecContextBase* context,
IRType* originalType)
{
return (IRType*)cloneValue(context, originalType);
}
void cloneGlobalValueWithCodeCommon(
IRSpecContextBase* context,
IRGlobalValueWithCode* clonedValue,
IRGlobalValueWithCode* originalValue);
IRRate* cloneRate(
IRSpecContextBase* context,
IRRate* rate)
{
return (IRRate*) cloneType(context, rate);
}
void maybeSetClonedRate(
IRSpecContextBase* context,
IRBuilder* builder,
IRInst* clonedValue,
IRInst* originalValue)
{
if(auto rate = originalValue->getRate() )
{
clonedValue->setFullType(builder->getRateQualifiedType(
cloneRate(context, rate),
clonedValue->getFullType()));
}
}
IRGlobalVar* cloneGlobalVarImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRGlobalVar* originalVar,
IROriginalValuesForClone const& originalValues)
{
auto clonedVar = builder->createGlobalVar(
cloneType(context, originalVar->getDataType()->getValueType()));
maybeSetClonedRate(context, builder, clonedVar, originalVar);
registerClonedValue(context, clonedVar, originalValues);
// Clone any code in the body of the variable, since this
// represents the initializer.
cloneGlobalValueWithCodeCommon(
context,
clonedVar,
originalVar);
return clonedVar;
}
IRGlobalConstant* cloneGlobalConstantImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRGlobalConstant* originalVal,
IROriginalValuesForClone const& originalValues)
{
auto clonedVal = builder->createGlobalConstant(
cloneType(context, originalVal->getFullType()));
registerClonedValue(context, clonedVal, originalValues);
// Clone any code in the body of the constant, since this
// represents the initializer.
cloneGlobalValueWithCodeCommon(
context,
clonedVal,
originalVal);
return clonedVal;
}
void cloneSimpleGlobalValueImpl(
IRSpecContextBase* context,
IRInst* originalInst,
IROriginalValuesForClone const& originalValues,
IRInst* clonedInst,
bool registerValue = true)
{
if (registerValue)
registerClonedValue(context, clonedInst, originalValues);
// Set up an IR builder for inserting into the inst
IRBuilder builderStorage = *context->builder;
IRBuilder* builder = &builderStorage;
builder->setInsertInto(clonedInst);
// Clone any children of the instruction
for (auto child : originalInst->getDecorationsAndChildren())
{
cloneInst(context, builder, child);
}
}
IRGlobalParam* cloneGlobalParamImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRGlobalParam* originalVal,
IROriginalValuesForClone const& originalValues)
{
auto clonedVal = builder->createGlobalParam(
cloneType(context, originalVal->getFullType()));
cloneSimpleGlobalValueImpl(context, originalVal, originalValues, clonedVal);
if(auto linkage = originalVal->findDecoration<IRLinkageDecoration>())
{
auto mangledName = String(linkage->getMangledName());
VarLayout* layout = nullptr;
if (context->globalVarLayouts.TryGetValue(mangledName, layout))
{
builder->addLayoutDecoration(clonedVal, layout);
}
}
return clonedVal;
}
IRGeneric* cloneGenericImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRGeneric* originalVal,
IROriginalValuesForClone const& originalValues)
{
auto clonedVal = builder->emitGeneric();
registerClonedValue(context, clonedVal, originalValues);
// Clone any code in the body of the generic, since this
// computes its result value.
cloneGlobalValueWithCodeCommon(
context,
clonedVal,
originalVal);
return clonedVal;
}
IRStructKey* cloneStructKeyImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRStructKey* originalVal,
IROriginalValuesForClone const& originalValues)
{
auto clonedVal = builder->createStructKey();
cloneSimpleGlobalValueImpl(context, originalVal, originalValues, clonedVal);
return clonedVal;
}
IRGlobalGenericParam* cloneGlobalGenericParamImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRGlobalGenericParam* originalVal,
IROriginalValuesForClone const& originalValues)
{
auto clonedVal = builder->emitGlobalGenericParam();
cloneSimpleGlobalValueImpl(context, originalVal, originalValues, clonedVal);
return clonedVal;
}
IRWitnessTable* cloneWitnessTableImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRWitnessTable* originalTable,
IROriginalValuesForClone const& originalValues,
IRWitnessTable* dstTable = nullptr,
bool registerValue = true)
{
auto clonedTable = dstTable ? dstTable : builder->createWitnessTable();
cloneSimpleGlobalValueImpl(context, originalTable, originalValues, clonedTable, registerValue);
return clonedTable;
}
IRWitnessTable* cloneWitnessTableWithoutRegistering(
IRSpecContextBase* context,
IRBuilder* builder,
IRWitnessTable* originalTable,
IRWitnessTable* dstTable = nullptr)
{
return cloneWitnessTableImpl(context, builder, originalTable, IROriginalValuesForClone(), dstTable, false);
}
IRStructType* cloneStructTypeImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRStructType* originalStruct,
IROriginalValuesForClone const& originalValues)
{
auto clonedStruct = builder->createStructType();
cloneSimpleGlobalValueImpl(context, originalStruct, originalValues, clonedStruct);
return clonedStruct;
}
IRInterfaceType* cloneInterfaceTypeImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRInterfaceType* originalInterface,
IROriginalValuesForClone const& originalValues)
{
auto clonedInterface = builder->createInterfaceType();
cloneSimpleGlobalValueImpl(context, originalInterface, originalValues, clonedInterface);
return clonedInterface;
}
void cloneGlobalValueWithCodeCommon(
IRSpecContextBase* context,
IRGlobalValueWithCode* clonedValue,
IRGlobalValueWithCode* originalValue)
{
// Next we are going to clone the actual code.
IRBuilder builderStorage = *context->builder;
IRBuilder* builder = &builderStorage;
builder->setInsertInto(clonedValue);
cloneDecorations(context, clonedValue, originalValue);
// We will walk through the blocks of the function, and clone each of them.
//
// We need to create the cloned blocks first, and then walk through them,
// because blocks might be forward referenced (this is not possible
// for other cases of instructions).
for (auto originalBlock = originalValue->getFirstBlock();
originalBlock;
originalBlock = originalBlock->getNextBlock())
{
IRBlock* clonedBlock = builder->createBlock();
clonedValue->addBlock(clonedBlock);
registerClonedValue(context, clonedBlock, originalBlock);
#if 0
// We can go ahead and clone parameters here, while we are at it.
builder->curBlock = clonedBlock;
for (auto originalParam = originalBlock->getFirstParam();
originalParam;
originalParam = originalParam->getNextParam())
{
IRParam* clonedParam = builder->emitParam(
context->maybeCloneType(
originalParam->getFullType()));
cloneDecorations(context, clonedParam, originalParam);
registerClonedValue(context, clonedParam, originalParam);
}
#endif
}
// Okay, now we are in a good position to start cloning
// the instructions inside the blocks.
{
IRBlock* ob = originalValue->getFirstBlock();
IRBlock* cb = clonedValue->getFirstBlock();
while (ob)
{
SLANG_ASSERT(cb);
builder->setInsertInto(cb);
for (auto oi = ob->getFirstInst(); oi; oi = oi->getNextInst())
{
cloneInst(context, builder, oi);
}
ob = ob->getNextBlock();
cb = cb->getNextBlock();
}
}
}
void checkIRDuplicate(IRInst* inst, IRInst* moduleInst, UnownedStringSlice const& mangledName)
{
#ifdef _DEBUG
for (auto child : moduleInst->getDecorationsAndChildren())
{
if (child == inst)
continue;
if(auto childLinkage = child->findDecoration<IRLinkageDecoration>())
{
if(mangledName == childLinkage->getMangledName())
{
SLANG_UNEXPECTED("duplicate global instruction");
}
}
}
#else
SLANG_UNREFERENCED_PARAMETER(inst);
SLANG_UNREFERENCED_PARAMETER(moduleInst);
SLANG_UNREFERENCED_PARAMETER(mangledName);
#endif
}
void cloneFunctionCommon(
IRSpecContextBase* context,
IRFunc* clonedFunc,
IRFunc* originalFunc,
bool checkDuplicate = true)
{
// First clone all the simple properties.
clonedFunc->setFullType(cloneType(context, originalFunc->getFullType()));
cloneGlobalValueWithCodeCommon(
context,
clonedFunc,
originalFunc);
// Shuffle the function to the end of the list, because
// it needs to follow its dependencies.
//
// TODO: This isn't really a good requirement to place on the IR...
clonedFunc->moveToEnd();
if( checkDuplicate )
{
if( auto linkage = clonedFunc->findDecoration<IRLinkageDecoration>() )
{
checkIRDuplicate(clonedFunc, context->getModule()->getModuleInst(), linkage->getMangledName());
}
}
}
// We will forward-declare the subroutine for eagerly specializing
// an IR-level generic to argument values, because `specializeIRForEntryPoint`
// needs to perform this operation even though it is logically part of
// the later generic specialization pass.
//
IRInst* specializeGeneric(
IRSpecialize* specializeInst);
IRFunc* specializeIRForEntryPoint(
IRSpecContext* context,
EntryPointRequest* entryPointRequest,
EntryPointLayout* entryPointLayout)
{
// We start by looking up the IR symbol that
// matches the mangled name given to the
// function we want to emit.
//
// Note: the function decl-ref may refer to
// a specialization of a generic function,
// so that the mangled name of the decl-ref is
// not the same as the mangled name of the decl.
//
auto mangledName = getMangledName(entryPointRequest->getFuncDeclRef());
RefPtr<IRSpecSymbol> sym;
if (!context->getSymbols().TryGetValue(mangledName, sym))
{
SLANG_UNEXPECTED("no matching IR symbol");
return nullptr;
}
// TODO: deal with the case where we might
// have multiple (profile-overloaded) versions...
//
auto originalVal = sym->irGlobalValue;
// We will start by cloning the entry point reference
// like any other global value.
//
auto clonedVal = cloneGlobalValue(context, originalVal);
// In the case where the user is requesting a specialization
// of a generic entry point, we have a bit of a problem.
//
// This function is expected to return an `IRFunc` and
// subsequent passes expect to find, e.g., layout information
// attached to the parameters of such a func.
//
// In the generic case, the `clonedValue` won't be an
// `IRFunc`, but instead an `IRSpecialize`.
//
if(auto clonedSpec = as<IRSpecialize>(clonedVal))
{
// The Right Thing to do here is to perform some
// amount of generic specialization, at least
// until we get back an `IRFunc`.
//
// The dangerous thing is that the generic specialization
// pass can, in principle, change the signature of
// functions, so that attaching parameter layout
// information *after* specialization might not work.
//
// The compromise we make here is to directly
// invoke the logic for specializing a generic.
//
// In theory this isn't valid, because there is no
// way we can register the specialized function we
// create so that it would be re-used by other instantiations
// with the same arguments (because we cannot be
// sure the generic arguments are themselves fully specialized)
//
// In practice this isn't really a problem, because
// we don't want to share the definition between
// an entry point and an ordinary function anyway.
//
clonedVal = specializeGeneric(clonedSpec);
}
auto clonedFunc = as<IRFunc>(clonedVal);
if(!clonedFunc)
{
SLANG_UNEXPECTED("expected entry point to be a function");
return nullptr;
}
if( !clonedFunc->findDecorationImpl(kIROp_EntryPointDecoration) )
{
context->builder->addEntryPointDecoration(clonedFunc);
}
// We need to attach the layout information for
// the entry point to this declaration, so that
// we can use it to inform downstream code emit.
//
context->builder->addLayoutDecoration(
clonedFunc,
entryPointLayout);
// We will also go on and attach layout information
// to the function parameters, so that we have it
// available directly on the parameters, rather
// than having to look it up on the original entry-point layout.
if( auto firstBlock = clonedFunc->getFirstBlock() )
{
auto paramsStructLayout = getScopeStructLayout(entryPointLayout);
UInt paramLayoutCount = paramsStructLayout->fields.Count();
UInt paramCounter = 0;
for( auto pp = firstBlock->getFirstParam(); pp; pp = pp->getNextParam() )
{
UInt paramIndex = paramCounter++;
if( paramIndex < paramLayoutCount )
{
auto paramLayout = paramsStructLayout->fields[paramIndex];
context->builder->addLayoutDecoration(
pp,
paramLayout);
}
else
{
SLANG_UNEXPECTED("too many parameters");
}
}
}
return clonedFunc;
}
// Get a string form of the target so that we can
// use it to match against target-specialization modifiers
//
// TODO: We shouldn't be using strings for this.
String getTargetName(IRSpecContext* context)
{
switch( context->shared->target )
{
case CodeGenTarget::HLSL:
return "hlsl";
case CodeGenTarget::GLSL:
return "glsl";
default:
SLANG_UNEXPECTED("unhandled case");
UNREACHABLE_RETURN("unknown");
}
}
// How specialized is a given declaration for the chosen target?
enum class TargetSpecializationLevel
{
specializedForOtherTarget = 0,
notSpecialized,
specializedForTarget,
};
TargetSpecializationLevel getTargetSpecialiationLevel(
IRInst* inVal,
String const& targetName)
{
// HACK: Currently the front-end is placing modifiers related
// to target specialization on nodes like functions, even when
// those functions are being returned by a generic. This
// means that we need to try and inspect the value being
// returned by the generic if we are looking at a generic.
IRInst* val = inVal;
while( auto genericVal = as<IRGeneric>(val) )
{
auto firstBlock = genericVal->getFirstBlock();
if(!firstBlock) break;
auto returnInst = as<IRReturnVal>(firstBlock->getLastInst());
if(!returnInst) break;
val = returnInst->getVal();
}
TargetSpecializationLevel result = TargetSpecializationLevel::notSpecialized;
for(auto dd : val->getDecorations())
{
if(dd->op != kIROp_TargetDecoration)
continue;
auto decoration = (IRTargetDecoration*) dd;
if(String(decoration->getTargetName()) == targetName)
return TargetSpecializationLevel::specializedForTarget;
result = TargetSpecializationLevel::specializedForOtherTarget;
}
return result;
}
// Is `newVal` marked as being a better match for our
// chosen code-generation target?
//
// TODO: there is a missing step here where we need
// to check if things are even available in the first place...
bool isBetterForTarget(
IRSpecContext* context,
IRInst* newVal,
IRInst* oldVal)
{
String targetName = getTargetName(context);
// For right now every declaration might have zero or more
// modifiers, representing the targets for which it is specialized.
// Each modifier has a single string "tag" to represent a target.
// We thus decide that a declaration is "more specialized" by:
//
// - Does it have a modifier with a tag with the string for the current target?
// If yes, it is the most specialized it can be.
//
// - Does it have a no tags? Then it is "unspecialized" and that is okay.
//
// - Does it have a modifier with a tag for a *different* target?
// If yes, then it shouldn't even be usable on this target.
//
// Longer term a better approach is to think of this in terms
// of a "disjunction of conjunctions" that is:
//
// (A and B and C) or (A and D) or (E) or (F and G) ...
//
// A code generation target would then consist of a
// conjunction of invidual tags:
//
// (HLSL and SM_4_0 and Vertex and ...)
//
// A declaration is *applicable* on a target if one of
// its conjunctions of tags is a subset of the target's.
//
// One declaration is *better* than another on a target
// if it is applicable and its tags are a superset
// of the other's.
auto newLevel = getTargetSpecialiationLevel(newVal, targetName);
auto oldLevel = getTargetSpecialiationLevel(oldVal, targetName);
if(newLevel != oldLevel)
return UInt(newLevel) > UInt(oldLevel);
// All preceding factors being equal, an `[export]` is better
// than an `[import]`.
//
bool newIsExport = newVal->findDecoration<IRExportDecoration>() != nullptr;
bool oldIsExport = oldVal->findDecoration<IRExportDecoration>() != nullptr;
if(newIsExport != oldIsExport)
return newIsExport;
// All preceding factors being equal, a definition is
// better than a declaration.
auto newIsDef = isDefinition(newVal);
auto oldIsDef = isDefinition(oldVal);
if (newIsDef != oldIsDef)
return newIsDef;
return false;
}
IRFunc* cloneFuncImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRFunc* originalFunc,
IROriginalValuesForClone const& originalValues)
{
auto clonedFunc = builder->createFunc();
registerClonedValue(context, clonedFunc, originalValues);
cloneFunctionCommon(context, clonedFunc, originalFunc);
return clonedFunc;
}
IRInst* cloneInst(
IRSpecContextBase* context,
IRBuilder* builder,
IRInst* originalInst,
IROriginalValuesForClone const& originalValues)
{
switch (originalInst->op)
{
// We need to special-case any instruction that is not
// allocated like an ordinary `IRInst` with trailing args.
case kIROp_Func:
return cloneFuncImpl(context, builder, cast<IRFunc>(originalInst), originalValues);
case kIROp_GlobalVar:
return cloneGlobalVarImpl(context, builder, cast<IRGlobalVar>(originalInst), originalValues);
case kIROp_GlobalConstant:
return cloneGlobalConstantImpl(context, builder, cast<IRGlobalConstant>(originalInst), originalValues);
case kIROp_GlobalParam:
return cloneGlobalParamImpl(context, builder, cast<IRGlobalParam>(originalInst), originalValues);
case kIROp_WitnessTable:
return cloneWitnessTableImpl(context, builder, cast<IRWitnessTable>(originalInst), originalValues);
case kIROp_StructType:
return cloneStructTypeImpl(context, builder, cast<IRStructType>(originalInst), originalValues);
case kIROp_InterfaceType:
return cloneInterfaceTypeImpl(context, builder, cast<IRInterfaceType>(originalInst), originalValues);
case kIROp_Generic:
return cloneGenericImpl(context, builder, cast<IRGeneric>(originalInst), originalValues);
case kIROp_StructKey:
return cloneStructKeyImpl(context, builder, cast<IRStructKey>(originalInst), originalValues);
case kIROp_GlobalGenericParam:
return cloneGlobalGenericParamImpl(context, builder, cast<IRGlobalGenericParam>(originalInst), originalValues);
default:
break;
}
// The common case is that we just need to construct a cloned
// instruction with the right number of operands, intialize
// it, and then add it to the sequence.
UInt argCount = originalInst->getOperandCount();
IRInst* clonedInst = builder->createIntrinsicInst(
cloneType(context, originalInst->getFullType()),
originalInst->op,
argCount, nullptr);
registerClonedValue(context, clonedInst, originalValues);
auto oldBuilder = context->builder;
context->builder = builder;
for (UInt aa = 0; aa < argCount; ++aa)
{
IRInst* originalArg = originalInst->getOperand(aa);
IRInst* clonedArg = cloneValue(context, originalArg);
clonedInst->getOperands()[aa].init(clonedInst, clonedArg);
}
builder->addInst(clonedInst);
context->builder = oldBuilder;
cloneDecorations(context, clonedInst, originalInst);
return clonedInst;
}
IRInst* cloneGlobalValueImpl(
IRSpecContext* context,
IRInst* originalInst,
IROriginalValuesForClone const& originalValues)
{
auto clonedValue = cloneInst(context, &context->shared->builderStorage, originalInst, originalValues);
clonedValue->moveToEnd();
return clonedValue;
}
/// Clone a global value, which has the given `originalLinkage`.
///
/// The `originalVal` is a known global IR value with that linkage, if one is available.
/// (It is okay for this parameter to be null).
///
IRInst* cloneGlobalValueWithLinkage(
IRSpecContext* context,
IRInst* originalVal,
IRLinkageDecoration* originalLinkage)
{
// If the global value being cloned is already in target module, don't clone
// Why checking this?
// When specializing a generic function G (which is already in target module),
// where G calls a normal function F (which is already in target module),
// then when we are making a copy of G via cloneFuncCommom(), it will recursively clone F,
// however we don't want to make a duplicate of F in the target module.
if (originalVal->getParent() == context->getModule()->getModuleInst())
return originalVal;
// Check if we've already cloned this value, for the case where
// an original value has already been established.
if (originalVal)
{
if (IRInst* clonedVal = findClonedValue(context, originalVal))
{
return clonedVal;
}
}
if(!originalLinkage)
{
// If there is no mangled name, then we assume this is a local symbol,
// and it can't possibly have multiple declarations.
return cloneGlobalValueImpl(context, originalVal, IROriginalValuesForClone(originalVal));
}
//
// We will scan through all of the available declarations
// with the same mangled name as `originalVal` and try
// to pick the "best" one for our target.
auto mangledName = String(originalLinkage->getMangledName());
RefPtr<IRSpecSymbol> sym;
if( !context->getSymbols().TryGetValue(mangledName, sym) )
{
if(!originalVal)
return nullptr;
// This shouldn't happen!
SLANG_UNEXPECTED("no matching values registered");
UNREACHABLE_RETURN(cloneGlobalValueImpl(context, originalVal, IROriginalValuesForClone()));
}
// We will try to track the "best" declaration we can find.
//
// Generally, one declaration wil lbe better than another if it is
// more specialized for the chosen target. Otherwise, we simply favor
// definitions over declarations.
//
IRInst* bestVal = sym->irGlobalValue;
for( auto ss = sym->nextWithSameName; ss; ss = ss->nextWithSameName )
{
IRInst* newVal = ss->irGlobalValue;
if(isBetterForTarget(context, newVal, bestVal))
bestVal = newVal;
}
// Check if we've already cloned this value, for the case where
// we didn't have an original value (just a name), but we've
// now found a representative value.
if (!originalVal)
{
if (IRInst* clonedVal = findClonedValue(context, bestVal))
{
return clonedVal;
}
}
return cloneGlobalValueImpl(context, bestVal, IROriginalValuesForClone(sym));
}
// Clone a global value, where `originalVal` is one declaration/definition, but we might
// have to consider others, in order to find the "best" version of the symbol.
IRInst* cloneGlobalValue(IRSpecContext* context, IRInst* originalVal)
{
// We are being asked to clone a particular global value, but in
// the IR that comes out of the front-end there could still
// be multiple, target-specific, declarations of any given
// global value, all of which share the same mangled name.
return cloneGlobalValueWithLinkage(
context,
originalVal,
originalVal->findDecoration<IRLinkageDecoration>());
}
void insertGlobalValueSymbol(
IRSharedSpecContext* sharedContext,
IRInst* gv)
{
auto linkage = gv->findDecoration<IRLinkageDecoration>();
// Don't try to register a symbol for global values
// that don't have linkage.
//
if (!linkage)
return;
auto mangledName = String(linkage->getMangledName());
RefPtr<IRSpecSymbol> sym = new IRSpecSymbol();
sym->irGlobalValue = gv;
RefPtr<IRSpecSymbol> prev;
if (sharedContext->symbols.TryGetValue(mangledName, prev))
{
sym->nextWithSameName = prev->nextWithSameName;
prev->nextWithSameName = sym;
}
else
{
sharedContext->symbols.Add(mangledName, sym);
}
}
void insertGlobalValueSymbols(
IRSharedSpecContext* sharedContext,
IRModule* originalModule)
{
if (!originalModule)
return;
for(auto ii : originalModule->getGlobalInsts())
{
insertGlobalValueSymbol(sharedContext, ii);
}
}
void initializeSharedSpecContext(
IRSharedSpecContext* sharedContext,
Session* session,
IRModule* module,
IRModule* originalModule,
CodeGenTarget target)
{
SharedIRBuilder* sharedBuilder = &sharedContext->sharedBuilderStorage;
sharedBuilder->module = nullptr;
sharedBuilder->session = session;
IRBuilder* builder = &sharedContext->builderStorage;
builder->sharedBuilder = sharedBuilder;
if( !module )
{
module = builder->createModule();
}
sharedBuilder->module = module;
sharedContext->module = module;
sharedContext->originalModule = originalModule;
sharedContext->target = target;
// We will populate a map with all of the IR values
// that use the same mangled name, to make lookup easier
// in other steps.
insertGlobalValueSymbols(sharedContext, originalModule);
}
// implementation provided in parameter-binding.cpp
RefPtr<ProgramLayout> specializeProgramLayout(
TargetRequest * targetReq,
ProgramLayout* programLayout,
SubstitutionSet typeSubst);
struct IRSpecializationState
{
ProgramLayout* programLayout;
CodeGenTarget target;
TargetRequest* targetReq;
IRModule* irModule = nullptr;
RefPtr<ProgramLayout> newProgramLayout;
IRSharedSpecContext sharedContextStorage;
IRSpecContext contextStorage;
IRSpecEnv globalEnv;
IRSharedSpecContext* getSharedContext() { return &sharedContextStorage; }
IRSpecContext* getContext() { return &contextStorage; }
IRSpecializationState()
{
contextStorage.env = &globalEnv;
}
~IRSpecializationState()
{
newProgramLayout = nullptr;
contextStorage = IRSpecContext();
sharedContextStorage = IRSharedSpecContext();
}
};
LinkedIR linkIR(
EntryPointRequest* entryPointRequest,
ProgramLayout* programLayout,
CodeGenTarget target,
TargetRequest* targetReq)
{
IRSpecializationState stateStorage;
auto state = &stateStorage;
state->programLayout = programLayout;
state->target = target;
state->targetReq = targetReq;
auto compileRequest = entryPointRequest->compileRequest;
auto translationUnit = entryPointRequest->getTranslationUnit();
auto originalIRModule = translationUnit->irModule;
auto sharedContext = state->getSharedContext();
initializeSharedSpecContext(
sharedContext,
compileRequest->mSession,
nullptr,
originalIRModule,
target);
state->irModule = sharedContext->module;
// We also need to attach the IR definitions for symbols from
// any loaded modules:
for (auto loadedModule : compileRequest->loadedModulesList)
{
insertGlobalValueSymbols(sharedContext, loadedModule->irModule);
}
auto context = state->getContext();
context->shared = sharedContext;
context->builder = &sharedContext->builderStorage;
// Now specialize the program layout using the substitution
//
// TODO: The specialization of the layout is conceptually an AST-level operations,
// and shouldn't be done here in the IR at all.
//
RefPtr<ProgramLayout> newProgramLayout = specializeProgramLayout(
targetReq,
programLayout,
SubstitutionSet(entryPointRequest->globalGenericSubst));
// TODO: we need to register the (IR-level) arguments of the global generic parameters as the
// substitutions for the generic parameters in the original IR.
// applyGlobalGenericParamSubsitution(...);
state->newProgramLayout = newProgramLayout;
// Next, we want to optimize lookup for layout infromation
// associated with global declarations, so that we can
// look things up based on the IR values (using mangled names)
auto globalStructLayout = getScopeStructLayout(newProgramLayout);
for (auto globalVarLayout : globalStructLayout->fields)
{
auto mangledName = getMangledName(globalVarLayout->varDecl);
context->globalVarLayouts.AddIfNotExists(mangledName, globalVarLayout);
}
context->builder->setInsertInto(context->getModule()->getModuleInst());
// for now, clone all unreferenced witness tables
//
// TODO: This step should *not* be needed with the current IR
// specialization approach, so we should consider removing it.
//
for (auto sym :context->getSymbols())
{
if (sym.Value->irGlobalValue->op == kIROp_WitnessTable)
cloneGlobalValue(context, (IRWitnessTable*)sym.Value->irGlobalValue);
}
auto entryPointLayout = findEntryPointLayout(newProgramLayout, entryPointRequest);
// Next, we make sure to clone the global value for
// the entry point function itself, and rely on
// this step to recursively copy over anything else
// it might reference.
auto irEntryPoint = specializeIRForEntryPoint(context, entryPointRequest, entryPointLayout);
// HACK: right now the bindings for global generic parameters are coming in
// as part of the original IR module, and we need to make sure these get
// copied over, even if they aren't referenced.
//
for(auto inst : originalIRModule->getGlobalInsts())
{
auto bindInst = as<IRBindGlobalGenericParam>(inst);
if(!bindInst)
continue;
cloneValue(context, bindInst);
}
// HACK: we need to ensure that any tagged union types
// in the IR module have layout information copied over to them.
//
// Note that we do this *after* cloning the `bindGlobalGenericParam`
// instructions, since we expected the tagged union type(s) to
// be referenced by them.
//
for( auto taggedUnionTypeLayout : entryPointLayout->taggedUnionTypeLayouts )
{
auto taggedUnionType = taggedUnionTypeLayout->getType();
auto mangledName = getMangledTypeName(taggedUnionType);
RefPtr<IRSpecSymbol> sym;
if(!context->getSymbols().TryGetValue(mangledName, sym))
continue;
IRInst* clonedType = findClonedValue(context, sym->irGlobalValue);
if(!clonedType)
continue;
context->builder->addLayoutDecoration(clonedType, taggedUnionTypeLayout);
}
// TODO: *technically* we should consider the case where
// we have global variables with initializers, since
// these should get run whether or not the entry point
// references them.
// Now that we've cloned the entry point and everything
// it refers to, we can package up the data we return
// to the caller.
//
LinkedIR linkedIR;
linkedIR.module = state->irModule;
linkedIR.entryPoint = irEntryPoint;
return linkedIR;
}
} // namespace Slang
|