-
Notifications
You must be signed in to change notification settings - Fork 272
/
Copy pathslang-ir-link.cpp
2331 lines (2064 loc) · 78.8 KB
/
slang-ir-link.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
// slang-ir-link.cpp
#include "slang-ir-link.h"
#include "../compiler-core/slang-artifact.h"
#include "../core/slang-performance-profiler.h"
#include "slang-capability.h"
#include "slang-ir-autodiff.h"
#include "slang-ir-insts.h"
#include "slang-ir-layout.h"
#include "slang-ir-specialize-target-switch.h"
#include "slang-ir-string-hash.h"
#include "slang-ir.h"
#include "slang-legalize-types.h"
#include "slang-mangle.h"
#include "slang-module-library.h"
namespace Slang
{
/// Find a suitable layout for `entryPoint` in `programLayout`.
///
/// TODO: This function should be eliminated. See its body
/// for an explanation of the problems.
EntryPointLayout* findEntryPointLayout(ProgramLayout* programLayout, EntryPoint* entryPoint);
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 API-level target request
TargetRequest* targetReq = nullptr;
// The specialized module we are building
RefPtr<IRModule> module;
// A map from mangled symbol names to zero or
// more global IR values that have that name,
// in the *original* module.
typedef Dictionary<ImmutableHashedString, RefPtr<IRSpecSymbol>> SymbolDictionary;
SymbolDictionary symbols;
Dictionary<ImmutableHashedString, bool> isImportedSymbol;
bool useAutodiff = false;
IRBuilder builderStorage;
// The "global" specialization environment.
IRSpecEnv globalEnv;
};
void insertGlobalValueSymbol(IRSharedSpecContext* sharedContext, IRInst* gv);
struct WitnessTableCloneInfo : RefObject
{
IRWitnessTable* clonedTable;
IRWitnessTable* originalTable;
Dictionary<UnownedStringSlice, IRWitnessTableEntry*> deferredEntries;
};
struct IRSpecContextBase
{
IRSharedSpecContext* shared;
IRSharedSpecContext* getShared() { return shared; }
IRModule* getModule() { return getShared()->module; }
List<IRModule*> irModules;
HashSet<UnownedStringSlice> deferredWitnessTableEntryKeys;
List<RefPtr<WitnessTableCloneInfo>> witnessTables;
IRSpecSymbol* findSymbols(UnownedStringSlice mangledName)
{
ImmutableHashedString hashedName(mangledName);
RefPtr<IRSpecSymbol> symbol;
if (shared->symbols.tryGetValue(hashedName, symbol))
return symbol;
for (auto m : irModules)
{
for (auto inst : m->findSymbolByMangledName(hashedName))
insertGlobalValueSymbol(shared, inst);
}
if (shared->symbols.tryGetValue(hashedName, symbol))
return symbol;
shared->symbols[hashedName] = nullptr;
return nullptr;
}
// 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;
switch (clonedValue->getOp())
{
case kIROp_LookupWitness:
// If `originalVal` represents a witness table entry key, add the key
// to witnessTableEntryWorkList.
context->deferredWitnessTableEntryKeys.add(
getMangledName(as<IRLookupWitnessMethod>(clonedValue)->getRequirementKey()));
break;
case kIROp_ForwardDerivativeDecoration:
case kIROp_BackwardDerivativeDecoration:
case kIROp_UserDefinedBackwardDerivativeDecoration:
if (context->getShared()->useAutodiff)
{
if (auto key = as<IRStructKey>(clonedValue->getOperand(0)))
context->deferredWitnessTableEntryKeys.add(getMangledName(key));
}
break;
}
}
// 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);
}
bool isAutoDiffDecoration(IRInst* decor)
{
switch (decor->getOp())
{
case kIROp_ForwardDerivativeDecoration:
case kIROp_BackwardDerivativeIntermediateTypeDecoration:
case kIROp_BackwardDerivativePrimalDecoration:
case kIROp_BackwardDerivativePropagateDecoration:
case kIROp_BackwardDerivativePrimalContextDecoration:
case kIROp_BackwardDerivativePrimalReturnDecoration:
case kIROp_PrimalSubstituteDecoration:
case kIROp_BackwardDerivativeDecoration:
case kIROp_UserDefinedBackwardDerivativeDecoration:
case kIROp_DifferentiableTypeDictionaryDecoration:
case kIROp_ForwardDifferentiableDecoration:
case kIROp_BackwardDifferentiableDecoration:
return true;
default:
return false;
}
}
/// 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())
{
if (!context->shared->useAutodiff && isAutoDiffDecoration(originalDecoration))
continue;
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())
{
if (!context->shared->useAutodiff && isAutoDiffDecoration(originalItem))
continue;
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->getOp())
{
case kIROp_StructType:
case kIROp_ClassType:
case kIROp_Func:
case kIROp_Generic:
case kIROp_GlobalVar:
case kIROp_GlobalParam:
case kIROp_GlobalConstant:
case kIROp_StructKey:
case kIROp_InterfaceRequirementEntry:
case kIROp_GlobalGenericParam:
case kIROp_WitnessTable:
case kIROp_InterfaceType:
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;
SLANG_RELEASE_ASSERT(c->value.ptrVal == nullptr);
return builder->getNullPtrValue(cloneType(this, c->getFullType()));
}
break;
case kIROp_VoidLit:
{
return builder->getVoidValue();
}
break;
default:
{
// In the default case, assume that we have some sort of "hoistable"
// instruction that requires us to create a clone of it.
UInt argCount = originalValue->getOperandCount();
ShortList<IRInst*> newArgs;
newArgs.setCount(argCount);
for (UInt aa = 0; aa < argCount; ++aa)
{
IRInst* originalArg = originalValue->getOperand(aa);
IRInst* clonedArg = cloneValue(this, originalArg);
newArgs[aa] = clonedArg;
}
IRInst* clonedValue = builder->createIntrinsicInst(
cloneType(this, originalValue->getFullType()),
originalValue->getOp(),
argCount,
newArgs.getArrayView().getBuffer());
registerClonedValue(this, clonedValue, originalValue);
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,
IROriginalValuesForClone const& originalValues);
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, originalValues);
return clonedVar;
}
/// Clone certain special decorations for `clonedInst` from its (potentially multiple) definitions.
///
/// In most cases, once we've decided on the "best" definition to use for an IR instruction,
/// we only want the linking process to use the decorations from the single best definition.
/// In some casses, though, the canonical best definition might not have all the information.
///
/// A concrete example is the `[bindExistentialsSlots(...)]` decorations for global shader
/// parameters and entry points. These decorations are only generated as part of the IR
/// associated with a specialization of a program, and not the original IR for the modules
/// of the program.
///
/// This function scans through all the `originalValues` that were considered for `clonedInst`,
/// and copies over any decorations that are allowed to come from a non-"best" definition.
/// For a given decoration opcode, only one such decoration will ever be copied, and nothing
/// will be copied if the instruction already has a matching decoration (that was cloned
/// from the "best" definition).
///
static void cloneExtraDecorationsFromInst(
IRSpecContextBase* context,
IRBuilder* builder,
IRInst* clonedInst,
IRInst* originalInst)
{
for (auto decoration : originalInst->getDecorations())
{
switch (decoration->getOp())
{
default:
break;
case kIROp_ForwardDerivativeDecoration:
case kIROp_UserDefinedBackwardDerivativeDecoration:
case kIROp_PrimalSubstituteDecoration:
if (!context->getShared()->useAutodiff)
break;
[[fallthrough]];
case kIROp_HLSLExportDecoration:
case kIROp_BindExistentialSlotsDecoration:
case kIROp_LayoutDecoration:
case kIROp_PublicDecoration:
case kIROp_SequentialIDDecoration:
case kIROp_IntrinsicOpDecoration:
case kIROp_NonCopyableTypeDecoration:
case kIROp_DynamicDispatchWitnessDecoration:
if (!clonedInst->findDecorationImpl(decoration->getOp()))
{
cloneInst(context, builder, decoration);
}
break;
}
}
// We will also copy over source location information from the alternative
// values, in case any of them has it available.
//
if (originalInst->sourceLoc.isValid() && !clonedInst->sourceLoc.isValid())
{
clonedInst->sourceLoc = originalInst->sourceLoc;
}
}
static void cloneExtraDecorations(
IRSpecContextBase* context,
IRInst* clonedInst,
IROriginalValuesForClone const& originalValues)
{
IRBuilder builderStorage = *context->builder;
IRBuilder* builder = &builderStorage;
builder->setInsertInto(clonedInst);
// If the `clonedInst` already has any non-decoration
// children, then we want to insert before those,
// to maintain the invariant that decorations always
// precede non-decoration instructions in the list of
// decorations and children.
//
if (auto firstChild = clonedInst->getFirstChild())
{
builder->setInsertBefore(firstChild);
}
for (auto sym = originalValues.sym; sym; sym = sym->nextWithSameName)
{
cloneExtraDecorationsFromInst(context, builder, clonedInst, sym->irGlobalValue);
}
}
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);
}
// Also clone certain decorations if they appear on *any*
// definition of the symbol (not necessarily the one
// we picked as the primary/best).
//
cloneExtraDecorations(context, clonedInst, originalValues);
}
IRGlobalParam* cloneGlobalParamImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRGlobalParam* originalVal,
IROriginalValuesForClone const& originalValues)
{
auto clonedVal = builder->createGlobalParam(cloneType(context, originalVal->getFullType()));
cloneSimpleGlobalValueImpl(context, originalVal, originalValues, clonedVal);
return clonedVal;
}
IRGlobalConstant* cloneGlobalConstantImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRGlobalConstant* originalVal,
IROriginalValuesForClone const& originalValues)
{
auto oldBuilder = context->builder;
context->builder = builder;
auto clonedType = cloneType(context, originalVal->getFullType());
IRGlobalConstant* clonedVal = nullptr;
if (auto originalInitVal = originalVal->getValue())
{
auto clonedInitVal = cloneValue(context, originalInitVal);
clonedVal = builder->emitGlobalConstant(clonedType, clonedInitVal);
}
else
{
clonedVal = builder->emitGlobalConstant(clonedType);
}
cloneSimpleGlobalValueImpl(context, originalVal, originalValues, clonedVal);
context->builder = oldBuilder;
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, originalValues);
// We want to clone extra decorations on the
// return value from other symbols as well.
auto clonedInnerVal = findGenericReturnVal(clonedVal);
for (auto originalSym = originalValues.sym; originalSym;
originalSym = originalSym->nextWithSameName.get())
{
auto originalGeneric = as<IRGeneric>(originalSym->irGlobalValue);
if (!originalGeneric)
continue;
auto originalInnerVal = findGenericReturnVal(originalGeneric);
// Register all generic parameters before cloning the decorations.
auto clonedParam = clonedVal->getFirstParam();
auto originalParam = originalGeneric->getFirstParam();
ShortList<KeyValuePair<IRInst*, IRInst*>> paramMapping;
for (; clonedParam && originalParam;
(clonedParam = as<IRParam, IRDynamicCastBehavior::NoUnwrap>(clonedParam->next)),
(originalParam = as<IRParam, IRDynamicCastBehavior::NoUnwrap>(originalParam->next)))
{
paramMapping.add(KeyValuePair<IRInst*, IRInst*>(clonedParam, originalParam));
}
// Generic parameter list does not match, bail.
if (clonedParam || originalParam)
continue;
for (const auto& [key, value] : paramMapping)
registerClonedValue(context, key, value);
IRBuilder builderStorage = *builder;
IRBuilder* decorBuilder = &builderStorage;
decorBuilder->setInsertInto(clonedInnerVal);
if (auto firstChild = clonedInnerVal->getFirstChild())
{
decorBuilder->setInsertBefore(firstChild);
}
cloneExtraDecorationsFromInst(context, decorBuilder, clonedInnerVal, originalInnerVal);
}
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(originalVal->getFullType());
cloneSimpleGlobalValueImpl(context, originalVal, originalValues, clonedVal);
return clonedVal;
}
bool shouldDeepCloneWitnessTable(IRSpecContextBase* context, IRWitnessTable* table)
{
for (auto decor : table->getDecorations())
{
switch (decor->getOp())
{
case kIROp_HLSLExportDecoration:
case kIROp_KeepAliveDecoration:
return true;
}
}
auto conformanceType = getResolvedInstForDecorations(table->getConformanceType());
for (auto decor : conformanceType->getDecorations())
{
switch (decor->getOp())
{
case kIROp_ComInterfaceDecoration:
return true;
case kIROp_KnownBuiltinDecoration:
{
auto name = as<IRKnownBuiltinDecoration>(decor)->getName();
if (name == toSlice("IDifferentiable") || name == toSlice("IDifferentiablePtr"))
return context->getShared()->useAutodiff;
break;
}
default:
break;
}
}
return false;
}
IRWitnessTable* cloneWitnessTableImpl(
IRSpecContextBase* context,
IRBuilder* builder,
IRWitnessTable* originalTable,
IROriginalValuesForClone const& originalValues,
IRWitnessTable* dstTable = nullptr,
bool registerValue = true)
{
IRWitnessTable* clonedTable = dstTable;
IRType* clonedBaseType = nullptr;
if (!clonedTable)
{
clonedBaseType = cloneType(context, (IRType*)(originalTable->getConformanceType()));
auto clonedSubType = cloneType(context, (IRType*)(originalTable->getConcreteType()));
clonedTable = builder->createWitnessTable(clonedBaseType, clonedSubType);
if (clonedTable->hasDecorationOrChild())
return clonedTable;
}
else
{
clonedBaseType = (IRType*)clonedTable->getConformanceType();
}
if (registerValue)
registerClonedValue(context, clonedTable, originalValues);
// Set up an IR builder for inserting into the witness table
IRBuilder builderStorage = *context->builder;
IRBuilder* entryBuilder = &builderStorage;
entryBuilder->setInsertInto(clonedTable);
// Clone decorations first
for (auto decoration : originalTable->getDecorations())
{
cloneInst(context, entryBuilder, decoration);
}
cloneExtraDecorations(context, clonedTable, originalValues);
RefPtr<WitnessTableCloneInfo> witnessInfo = new WitnessTableCloneInfo();
witnessInfo->clonedTable = clonedTable;
witnessInfo->originalTable = originalTable;
bool shouldDeepClone = shouldDeepCloneWitnessTable(context, originalTable);
// Clone only the witness table entries that are actually used
for (auto child : originalTable->getDecorationsAndChildren())
{
if (auto entry = as<IRWitnessTableEntry>(child))
{
if (!shouldDeepClone)
{
// Skip witness table entries during the first pass,
// and just add them to the deferred work list.
witnessInfo->deferredEntries.add(getMangledName(entry->getRequirementKey()), entry);
continue;
}
}
// Clone any non-entry children as is
cloneInst(context, entryBuilder, child);
}
context->witnessTables.add(witnessInfo);
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(originalInterface->getOperandCount(), nullptr);
registerClonedValue(context, clonedInterface, originalValues);
for (UInt i = 0; i < originalInterface->getOperandCount(); i++)
{
auto clonedKey = cloneValue(context, originalInterface->getOperand(i));
clonedInterface->setOperand(i, clonedKey);
}
cloneSimpleGlobalValueImpl(context, originalInterface, originalValues, clonedInterface, false);
return clonedInterface;
}
void cloneGlobalValueWithCodeCommon(
IRSpecContextBase* context,
IRGlobalValueWithCode* clonedValue,
IRGlobalValueWithCode* originalValue,
IROriginalValuesForClone const& originalValues)
{
// Next we are going to clone the actual code.
IRBuilder builderStorage = *context->builder;
IRBuilder* builder = &builderStorage;
builder->setInsertInto(clonedValue);
cloneDecorations(context, clonedValue, originalValue);
cloneExtraDecorations(context, clonedValue, originalValues);
clonedValue->setFullType((IRType*)cloneValue(context, originalValue->getFullType()));
// 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();
struct ParamCloneInfo
{
IRParam* originalParam;
IRParam* clonedParam;
};
while (ob)
{
ShortList<ParamCloneInfo> paramCloneInfos;
SLANG_ASSERT(cb);
builder->setInsertInto(cb);
for (auto oi = ob->getFirstInst(); oi; oi = oi->getNextInst())
{
if (oi->getOp() == kIROp_Param)
{
// Params may have forward references in its type and
// decorations, so we just create a placeholder for it
// in this first pass.
IRParam* clonedParam = builder->emitParam(nullptr);
registerClonedValue(context, clonedParam, oi);
paramCloneInfos.add({(IRParam*)oi, clonedParam});
}
else
{
if (oi->getOp() == kIROp_DifferentiableTypeAnnotation &&
!context->getShared()->useAutodiff)
continue;
cloneInst(context, builder, oi);
}
}
// Clone the type and decorations of parameters after all instructs in the block
// have been cloned.
for (auto param : paramCloneInfos)
{
builder->setInsertInto(param.clonedParam);
param.clonedParam->setFullType(
(IRType*)cloneValue(context, param.originalParam->getFullType()));
cloneDecorations(context, param.clonedParam, param.originalParam);
}
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,
IROriginalValuesForClone const& originalValues,
bool checkDuplicate = true)
{
// First clone all the simple properties.
clonedFunc->setFullType(cloneType(context, originalFunc->getFullType()));
cloneGlobalValueWithCodeCommon(context, clonedFunc, originalFunc, originalValues);
// 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);
/// Copy layout information for an entry-point function to its parameters.
///
/// When layout information is initially attached to an IR entry point,
/// it may be attached to a declaration that would have no `IRParam`s
/// to represent the entry-point parameters.
///
/// After linking, we expect an entry point to have a full definition,
/// so it becomes possible to copy per-parameter layout information
/// from the entry-point layout down to the individual parameters,
/// which simplifies subsequent IR steps taht want to look for
/// per-parameter layout information.
///
/// TODO: This step should probably be hoisted out to be an independent
/// IR pass that runs after linking, rather than being folded into
/// the linking step.
///
static void maybeCopyLayoutInformationToParameters(IRFunc* func, IRBuilder* builder)
{