-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathGenPack.cpp
1473 lines (1249 loc) · 56.4 KB
/
GenPack.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
//===--- GenPack.cpp - Swift IR Generation For Variadic Generics ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for type and value packs in Swift.
//
//===----------------------------------------------------------------------===//
#include "GenPack.h"
#include "GenProto.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/PackConformance.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/IRGen/GenericRequirement.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "llvm/IR/DerivedTypes.h"
#include "GenTuple.h"
#include "GenType.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "MetadataRequest.h"
#include "ResilientTypeInfo.h"
using namespace swift;
using namespace irgen;
static void cleanupTypeMetadataPackImpl(IRGenFunction &IGF, StackAddress pack,
llvm::Value *shape);
static void cleanupWitnessTablePackImpl(IRGenFunction &IGF, StackAddress pack,
llvm::Value *shape);
static CanPackArchetypeType
getForwardedPackArchetypeType(CanPackType packType) {
if (auto expansion = packType.unwrapSingletonPackExpansion())
return dyn_cast<PackArchetypeType>(expansion.getPatternType());
return CanPackArchetypeType();
}
static MetadataResponse
tryGetLocalPackTypeMetadata(IRGenFunction &IGF, CanPackType packType,
DynamicMetadataRequest request) {
if (auto result = IGF.tryGetLocalTypeMetadata(packType, request))
return result;
if (auto packArchetypeType = getForwardedPackArchetypeType(packType)) {
if (auto result = IGF.tryGetLocalTypeMetadata(packArchetypeType, request))
return result;
}
return MetadataResponse();
}
static llvm::Value *tryGetLocalPackTypeData(IRGenFunction &IGF,
CanPackType packType,
LocalTypeDataKind localDataKind) {
if (auto *wtable = IGF.tryGetLocalTypeData(packType, localDataKind))
return wtable;
if (auto packArchetypeType = getForwardedPackArchetypeType(packType)) {
// Also unwrap the pack conformance, if there is one.
if (localDataKind.isPackProtocolConformance()) {
localDataKind = LocalTypeDataKind::forProtocolWitnessTable(
localDataKind.getPackProtocolConformance()
->getPatternConformances()[0]);
}
if (auto *wtable =
IGF.tryGetLocalTypeData(packArchetypeType, localDataKind))
return wtable;
}
return nullptr;
}
static void accumulateSum(IRGenFunction &IGF, llvm::Value *&result,
llvm::Value *value) {
if (result == nullptr) {
result = value;
return;
}
result = IGF.Builder.CreateAdd(result, value);
}
llvm::Value *
irgen::emitIndexOfStructuralPackComponent(IRGenFunction &IGF,
CanPackType packType,
unsigned structuralIndex) {
assert(structuralIndex < packType->getNumElements());
unsigned numFixedComponents = 0;
llvm::Value *length = nullptr;
for (unsigned i = 0; i < structuralIndex; ++i) {
auto componentType = packType.getElementType(i);
if (auto expansion = dyn_cast<PackExpansionType>(componentType)) {
auto countType = expansion.getCountType();
auto expansionLength = IGF.emitPackShapeExpression(countType);
accumulateSum(IGF, length, expansionLength);
} else {
numFixedComponents++;
}
}
if (numFixedComponents > 0 || !length) {
auto fixedLength =
llvm::ConstantInt::get(IGF.IGM.SizeTy, numFixedComponents);
accumulateSum(IGF, length, fixedLength);
}
assert(length);
return length;
}
using PackExplosionCallback = void (CanType eltTy,
unsigned scalarIndex,
llvm::Value *dynamicIndex,
llvm::Value *dynamicLength);
static std::pair<unsigned, llvm::Value *>
visitPackExplosion(IRGenFunction &IGF, CanPackType type,
llvm::function_ref<PackExplosionCallback> callback) {
llvm::Value *result = nullptr;
// If shape(T) == t and shape(U) == u, the shape expression for a pack
// {T..., Int, T..., U..., String} becomes 't + t + u + 2'.
unsigned scalarElements = 0;
for (auto elt : type.getElementTypes()) {
if (auto expansionType = dyn_cast<PackExpansionType>(elt)) {
auto reducedShape = expansionType.getCountType();
auto *eltCount = IGF.emitPackShapeExpression(reducedShape);
callback(elt, scalarElements, result, eltCount);
accumulateSum(IGF, result, eltCount);
continue;
}
callback(elt, scalarElements, result, nullptr);
++scalarElements;
}
return std::make_pair(scalarElements, result);
}
llvm::Value *IRGenFunction::emitPackShapeExpression(CanType type) {
type = type->getReducedShape()->getCanonicalType();
auto kind = LocalTypeDataKind::forPackShapeExpression();
llvm::Value *result = tryGetLocalTypeData(type, kind);
if (result != nullptr)
return result;
auto pair = visitPackExplosion(
*this, cast<PackType>(type),
[&](CanType, unsigned, llvm::Value *, llvm::Value *) {});
if (pair.first > 0) {
auto *constant = llvm::ConstantInt::get(IGM.SizeTy, pair.first);
accumulateSum(*this, pair.second, constant);
} else if (pair.second == nullptr) {
pair.second = llvm::ConstantInt::get(IGM.SizeTy, 0);
}
setScopedLocalTypeData(type, kind, pair.second);
return pair.second;
}
MetadataResponse
irgen::emitPackArchetypeMetadataRef(IRGenFunction &IGF,
CanPackArchetypeType type,
DynamicMetadataRequest request) {
if (auto result = IGF.tryGetLocalTypeMetadata(type, request))
return result;
auto packType = CanPackType::getSingletonPackExpansion(type);
auto response = emitTypeMetadataPackRef(IGF, packType, request);
IGF.setScopedLocalTypeMetadata(type, response);
return response;
}
static Address emitFixedSizeMetadataPackRef(IRGenFunction &IGF,
CanPackType packType,
DynamicMetadataRequest request) {
assert(!packType->containsPackExpansionType());
unsigned elementCount = packType->getNumElements();
auto allocType = llvm::ArrayType::get(
IGF.IGM.TypeMetadataPtrTy, elementCount);
auto pack = IGF.createAlloca(allocType, IGF.IGM.getPointerAlignment());
IGF.Builder.CreateLifetimeStart(pack,
IGF.IGM.getPointerSize() * elementCount);
for (unsigned i : indices(packType->getElementTypes())) {
Address slot = IGF.Builder.CreateStructGEP(
pack, i, IGF.IGM.getPointerSize());
auto metadata = IGF.emitTypeMetadataRef(
packType.getElementType(i), request).getMetadata();
IGF.Builder.CreateStore(metadata, slot);
}
return pack;
}
llvm::Value *irgen::maskMetadataPackPointer(IRGenFunction &IGF,
llvm::Value *patternPack) {
// If the pack is on the heap, the LSB is set, so mask it off.
patternPack =
IGF.Builder.CreatePtrToInt(patternPack, IGF.IGM.SizeTy);
patternPack =
IGF.Builder.CreateAnd(patternPack, llvm::ConstantInt::get(IGF.IGM.SizeTy, -2));
patternPack =
IGF.Builder.CreateIntToPtr(patternPack, IGF.IGM.TypeMetadataPtrPtrTy);
return patternPack;
}
/// Use this to index into packs to correctly handle on-heap packs.
static llvm::Value *loadMetadataAtIndex(IRGenFunction &IGF,
llvm::Value *patternPack,
llvm::Value *index) {
patternPack = maskMetadataPackPointer(IGF, patternPack);
Address patternPackAddress(patternPack, IGF.IGM.TypeMetadataPtrTy,
IGF.IGM.getPointerAlignment());
// Load the metadata pack element from the current source index.
Address fromPtr(
IGF.Builder.CreateInBoundsGEP(patternPackAddress.getElementType(),
patternPackAddress.getAddress(), index),
patternPackAddress.getElementType(), patternPackAddress.getAlignment());
return IGF.Builder.CreateLoad(fromPtr);
}
static llvm::Value *bindMetadataAtIndex(IRGenFunction &IGF,
CanType elementArchetype,
llvm::Value *patternPack,
llvm::Value *index,
DynamicMetadataRequest request) {
if (auto response = IGF.tryGetLocalTypeMetadata(elementArchetype, request))
return response.getMetadata();
llvm::Value *metadata = loadMetadataAtIndex(IGF, patternPack, index);
// Bind the metadata pack element to the element archetype.
IGF.setScopedLocalTypeMetadata(elementArchetype,
MetadataResponse::forComplete(metadata));
return metadata;
}
/// Use this to index into packs to correctly handle on-heap packs.
static llvm::Value *loadWitnessTableAtIndex(IRGenFunction &IGF,
llvm::Value *wtablePack,
llvm::Value *index) {
// If the pack is on the heap, the LSB is set, so mask it off.
wtablePack =
IGF.Builder.CreatePtrToInt(wtablePack, IGF.IGM.SizeTy);
wtablePack =
IGF.Builder.CreateAnd(wtablePack, llvm::ConstantInt::get(IGF.IGM.SizeTy, -2));
wtablePack =
IGF.Builder.CreateIntToPtr(wtablePack, IGF.IGM.WitnessTablePtrPtrTy);
Address patternPackAddress(wtablePack, IGF.IGM.WitnessTablePtrTy,
IGF.IGM.getPointerAlignment());
// Load the witness table pack element from the current source index.
Address fromPtr(
IGF.Builder.CreateInBoundsGEP(patternPackAddress.getElementType(),
patternPackAddress.getAddress(), index),
patternPackAddress.getElementType(), patternPackAddress.getAlignment());
return IGF.Builder.CreateLoad(fromPtr);
}
static llvm::Value *bindWitnessTableAtIndex(IRGenFunction &IGF,
CanType elementArchetype,
ProtocolConformanceRef conf,
llvm::Value *wtablePack,
llvm::Value *index) {
auto key = LocalTypeDataKind::forProtocolWitnessTable(conf);
if (auto *wtable = IGF.tryGetLocalTypeData(elementArchetype, key))
return wtable;
auto *wtable = loadWitnessTableAtIndex(IGF, wtablePack, index);
// Bind the witness table pack element to the element archetype.
IGF.setScopedLocalTypeData(elementArchetype, key, wtable);
return wtable;
}
/// Find the pack archetype for the given interface type in the given
/// opened element context, which is known to be a forwarding context.
static CanPackArchetypeType
getMappedPackArchetypeType(const OpenedElementContext &context, CanType ty) {
auto packType = cast<PackType>(
context.environment->maybeApplyOuterContextSubstitutions(ty)
->getCanonicalType());
auto archetype = getForwardedPackArchetypeType(packType);
assert(archetype);
return archetype;
}
static void bindElementSignatureRequirementsAtIndex(
IRGenFunction &IGF, OpenedElementContext const &context, llvm::Value *index,
DynamicMetadataRequest request) {
enumerateGenericSignatureRequirements(
context.signature, [&](GenericRequirement requirement) {
switch (requirement.getKind()) {
case GenericRequirement::Kind::Shape:
case GenericRequirement::Kind::Metadata:
case GenericRequirement::Kind::WitnessTable:
case GenericRequirement::Kind::Value:
break;
case GenericRequirement::Kind::MetadataPack: {
auto ty = requirement.getTypeParameter();
auto patternPackArchetype = getMappedPackArchetypeType(context, ty);
auto response =
IGF.emitTypeMetadataRef(patternPackArchetype, request);
auto elementArchetype =
context.environment
->mapContextualPackTypeIntoElementContext(
patternPackArchetype)
->getCanonicalType();
auto *patternPack = response.getMetadata();
auto elementMetadata = bindMetadataAtIndex(
IGF, elementArchetype, patternPack, index, request);
assert(elementMetadata);
(void)elementMetadata;
break;
}
case GenericRequirement::Kind::WitnessTablePack: {
auto ty = requirement.getTypeParameter();
auto proto = requirement.getProtocol();
auto patternPackArchetype = getMappedPackArchetypeType(context, ty);
auto elementArchetype =
context.environment
->mapContextualPackTypeIntoElementContext(
patternPackArchetype)
->getCanonicalType();
llvm::Value *_metadata = nullptr;
auto packConformance = ProtocolConformanceRef::forAbstract(
patternPackArchetype, proto);
auto *wtablePack = emitWitnessTableRef(IGF, patternPackArchetype,
&_metadata, packConformance);
auto elementConformance = ProtocolConformanceRef::forAbstract(
elementArchetype, proto);
auto *wtable = bindWitnessTableAtIndex(
IGF, elementArchetype, elementConformance, wtablePack, index);
assert(wtable);
(void)wtable;
break;
}
}
});
}
static llvm::Value *emitPackExpansionElementMetadata(
IRGenFunction &IGF, OpenedElementContext context, CanType patternTy,
llvm::Value *index, DynamicMetadataRequest request) {
bindElementSignatureRequirementsAtIndex(IGF, context, index, request);
// Replace pack archetypes with element archetypes in the pattern type.
auto instantiatedPatternTy =
context.environment
->mapContextualPackTypeIntoElementContext(patternTy);
// Emit the element metadata.
auto element = IGF.emitTypeMetadataRef(instantiatedPatternTy, request)
.getMetadata();
return element;
}
/// Store the values corresponding to the specified pack expansion \p
/// expansionTy for each index in its range [dynamicIndex, dynamicIndex +
/// dynamicLength) produced by the provided function \p elementForIndex into
/// the indicated buffer \p pack.
static void emitPackExpansionPack(
IRGenFunction &IGF, Address pack,
llvm::Value *dynamicIndex, llvm::Value *dynamicLength,
function_ref<llvm::Value *(llvm::Value *)> elementForIndex) {
auto *prev = IGF.Builder.GetInsertBlock();
auto *check = IGF.createBasicBlock("pack-expansion-check");
auto *loop = IGF.createBasicBlock("pack-expansion-loop");
auto *rest = IGF.createBasicBlock("pack-expansion-rest");
IGF.Builder.CreateBr(check);
IGF.Builder.emitBlock(check);
// An index into the source metadata pack.
auto *phi = IGF.Builder.CreatePHI(IGF.IGM.SizeTy, 2);
phi->addIncoming(llvm::ConstantInt::get(IGF.IGM.SizeTy, 0), prev);
// If we reach the end, jump to the continuation block.
auto *cond = IGF.Builder.CreateICmpULT(phi, dynamicLength);
IGF.Builder.CreateCondBr(cond, loop, rest);
IGF.Builder.emitBlock(loop);
ConditionalDominanceScope condition(IGF);
IGF.withLocalStackPackAllocs([&]() {
auto *element = elementForIndex(phi);
// Store the element metadata into to the current destination index.
auto *eltIndex = IGF.Builder.CreateAdd(dynamicIndex, phi);
Address eltPtr(IGF.Builder.CreateInBoundsGEP(pack.getElementType(),
pack.getAddress(), eltIndex),
pack.getElementType(), pack.getAlignment());
IGF.Builder.CreateStore(element, eltPtr);
});
// Increment our counter.
auto *next = IGF.Builder.CreateAdd(phi,
llvm::ConstantInt::get(IGF.IGM.SizeTy, 1));
phi->addIncoming(next, IGF.Builder.GetInsertBlock());
// Repeat the loop.
IGF.Builder.CreateBr(check);
// Fall through.
IGF.Builder.emitBlock(rest);
}
static void emitPackExpansionMetadataPack(IRGenFunction &IGF, Address pack,
CanPackExpansionType expansionTy,
llvm::Value *dynamicIndex,
llvm::Value *dynamicLength,
DynamicMetadataRequest request) {
emitPackExpansionPack(
IGF, pack, dynamicIndex, dynamicLength, [&](auto *index) {
auto context =
OpenedElementContext::createForContextualExpansion(IGF.IGM.Context, expansionTy);
auto patternTy = expansionTy.getPatternType();
return emitPackExpansionElementMetadata(IGF, context, patternTy, index,
request);
});
}
std::pair<StackAddress, llvm::Value *>
irgen::emitTypeMetadataPack(IRGenFunction &IGF, CanPackType packType,
DynamicMetadataRequest request) {
auto *shape = IGF.emitPackShapeExpression(packType);
if (auto *constantInt = dyn_cast<llvm::ConstantInt>(shape)) {
assert(packType->getNumElements() == constantInt->getValue());
auto pack =
StackAddress(emitFixedSizeMetadataPackRef(IGF, packType, request));
IGF.recordStackPackMetadataAlloc(pack, constantInt);
return {pack, constantInt};
}
assert(packType->containsPackExpansionType());
auto pack = IGF.emitDynamicAlloca(IGF.IGM.TypeMetadataPtrTy, shape,
IGF.IGM.getPointerAlignment(),
/*allowTaskAlloc=*/true);
auto visitFn =
[&](CanType eltTy, unsigned staticIndex,
llvm::Value *dynamicIndex,
llvm::Value *dynamicLength) {
if (staticIndex != 0 || dynamicIndex == nullptr) {
auto *constant = llvm::ConstantInt::get(IGF.IGM.SizeTy, staticIndex);
accumulateSum(IGF, dynamicIndex, constant);
}
if (auto expansionTy = dyn_cast<PackExpansionType>(eltTy)) {
emitPackExpansionMetadataPack(IGF, pack.getAddress(), expansionTy,
dynamicIndex, dynamicLength, request);
} else {
Address eltPtr(
IGF.Builder.CreateInBoundsGEP(pack.getAddress().getElementType(),
pack.getAddressPointer(),
dynamicIndex),
pack.getAddress().getElementType(),
pack.getAlignment());
auto metadata = IGF.emitTypeMetadataRef(eltTy, request).getMetadata();
IGF.Builder.CreateStore(metadata, eltPtr);
}
};
visitPackExplosion(IGF, packType, visitFn);
IGF.recordStackPackMetadataAlloc(pack, shape);
return {pack, shape};
}
static std::optional<unsigned> countForShape(llvm::Value *shape) {
if (auto *constant = dyn_cast<llvm::ConstantInt>(shape))
return constant->getValue().getZExtValue();
return std::nullopt;
}
MetadataResponse
irgen::emitTypeMetadataPackRef(IRGenFunction &IGF, CanPackType packType,
DynamicMetadataRequest request) {
if (auto result = tryGetLocalPackTypeMetadata(IGF, packType, request))
return result;
StackAddress pack;
llvm::Value *shape;
std::tie(pack, shape) = emitTypeMetadataPack(IGF, packType, request);
auto *metadata = pack.getAddress().getAddress();
metadata = IGF.Builder.CreatePointerCast(
metadata, IGF.IGM.TypeMetadataPtrTy->getPointerTo());
if (!IGF.canStackPromotePackMetadata()) {
metadata = IGF.Builder.CreateCall(
IGF.IGM.getAllocateMetadataPackFunctionPointer(), {metadata, shape});
cleanupTypeMetadataPack(IGF, pack, shape);
}
auto response = MetadataResponse::forComplete(metadata);
IGF.setScopedLocalTypeMetadata(packType, response);
return response;
}
static Address emitFixedSizeWitnessTablePack(IRGenFunction &IGF,
CanPackType packType,
PackConformance *packConformance) {
assert(!packType->containsPackExpansionType());
unsigned elementCount = packType->getNumElements();
auto allocType =
llvm::ArrayType::get(IGF.IGM.WitnessTablePtrTy, elementCount);
auto pack = IGF.createAlloca(allocType, IGF.IGM.getPointerAlignment());
IGF.Builder.CreateLifetimeStart(pack,
IGF.IGM.getPointerSize() * elementCount);
for (unsigned i : indices(packType->getElementTypes())) {
Address slot =
IGF.Builder.CreateStructGEP(pack, i, IGF.IGM.getPointerSize());
auto conformance = packConformance->getPatternConformances()[i];
llvm::Value *_metadata = nullptr;
auto *wtable =
emitWitnessTableRef(IGF, packType.getElementType(i),
/*srcMetadataCache=*/&_metadata, conformance);
IGF.Builder.CreateStore(wtable, slot);
}
return pack;
}
static llvm::Value *emitPackExpansionElementWitnessTable(
IRGenFunction &IGF, OpenedElementContext context, CanType patternTy,
ProtocolConformanceRef conformance, llvm::Value **srcMetadataCache,
llvm::Value *index) {
bindElementSignatureRequirementsAtIndex(IGF, context, index,
MetadataState::Complete);
// Replace pack archetypes with element archetypes in the pattern type.
auto instantiatedPatternTy =
context.environment->mapContextualPackTypeIntoElementContext(patternTy);
auto instantiatedConformance =
lookupConformance(instantiatedPatternTy, conformance.getProtocol());
// Emit the element witness table.
auto *wtable = emitWitnessTableRef(IGF, instantiatedPatternTy,
srcMetadataCache, instantiatedConformance);
return wtable;
}
static void emitPackExpansionWitnessTablePack(
IRGenFunction &IGF, Address pack, CanPackExpansionType expansionTy,
ProtocolConformanceRef conformance, llvm::Value *dynamicIndex,
llvm::Value *dynamicLength) {
emitPackExpansionPack(
IGF, pack, dynamicIndex, dynamicLength, [&](auto *index) {
llvm::Value *_metadata = nullptr;
auto context =
OpenedElementContext::createForContextualExpansion(IGF.IGM.Context, expansionTy);
auto patternTy = expansionTy.getPatternType();
return emitPackExpansionElementWitnessTable(
IGF, context, patternTy, conformance,
/*srcMetadataCache=*/&_metadata, index);
});
}
std::pair<StackAddress, llvm::Value *>
irgen::emitWitnessTablePack(IRGenFunction &IGF, CanPackType packType,
PackConformance *packConformance) {
auto *shape = IGF.emitPackShapeExpression(packType);
if (auto *constantInt = dyn_cast<llvm::ConstantInt>(shape)) {
assert(packType->getNumElements() == constantInt->getValue());
auto pack = StackAddress(
emitFixedSizeWitnessTablePack(IGF, packType, packConformance));
IGF.recordStackPackWitnessTableAlloc(pack, constantInt);
return {pack, constantInt};
}
assert(packType->containsPackExpansionType());
auto pack = IGF.emitDynamicAlloca(IGF.IGM.WitnessTablePtrTy, shape,
IGF.IGM.getPointerAlignment(),
/*allowTaskAlloc=*/true);
auto index = 0;
auto visitFn = [&](CanType eltTy, unsigned staticIndex,
llvm::Value *dynamicIndex, llvm::Value *dynamicLength) {
if (staticIndex != 0 || dynamicIndex == nullptr) {
auto *constant = llvm::ConstantInt::get(IGF.IGM.SizeTy, staticIndex);
accumulateSum(IGF, dynamicIndex, constant);
}
auto conformance = packConformance->getPatternConformances()[index];
if (auto expansionTy = dyn_cast<PackExpansionType>(eltTy)) {
emitPackExpansionWitnessTablePack(IGF, pack.getAddress(), expansionTy,
conformance, dynamicIndex,
dynamicLength);
} else {
Address eltPtr(
IGF.Builder.CreateInBoundsGEP(pack.getAddress().getElementType(),
pack.getAddressPointer(), dynamicIndex),
pack.getAddress().getElementType(), pack.getAlignment());
llvm::Value *_metadata = nullptr;
auto *wtable = emitWitnessTableRef(
IGF, eltTy, /*srcMetadataCache=*/&_metadata, conformance);
IGF.Builder.CreateStore(wtable, eltPtr);
}
++index;
};
visitPackExplosion(IGF, packType, visitFn);
IGF.recordStackPackWitnessTableAlloc(pack, shape);
return {pack, shape};
}
static void cleanupWitnessTablePackImpl(IRGenFunction &IGF, StackAddress pack,
llvm::Value *shape) {
if (pack.getExtraInfo()) {
IGF.emitDeallocateDynamicAlloca(pack);
} else if (auto count = countForShape(shape)) {
IGF.Builder.CreateLifetimeEnd(pack.getAddress(),
IGF.IGM.getPointerSize() * (count.value()));
}
}
void irgen::cleanupWitnessTablePack(IRGenFunction &IGF, StackAddress pack,
llvm::Value *shape) {
cleanupWitnessTablePackImpl(IGF, pack, shape);
IGF.eraseStackPackWitnessTableAlloc(pack, shape);
}
void irgen::cleanupStackAllocPacks(IRGenFunction &IGF,
ArrayRef<StackPackAlloc> allocs) {
for (auto alloc : llvm::reverse(allocs)) {
StackAddress addr;
uint8_t kind;
llvm::Value *shape;
std::tie(addr, shape, kind) = alloc;
switch ((GenericRequirement::Kind)kind) {
case GenericRequirement::Kind::MetadataPack:
cleanupTypeMetadataPackImpl(IGF, addr, shape);
break;
case GenericRequirement::Kind::WitnessTablePack:
cleanupWitnessTablePackImpl(IGF, addr, shape);
break;
default:
llvm_unreachable("bad requirement in stack pack alloc");
}
}
}
void IRGenFunction::recordStackPackMetadataAlloc(StackAddress addr,
llvm::Value *shape) {
OutstandingStackPackAllocs.insert(
{addr, shape, (uint8_t)GenericRequirement::Kind::MetadataPack});
}
void IRGenFunction::eraseStackPackMetadataAlloc(StackAddress addr,
llvm::Value *shape) {
auto removed = OutstandingStackPackAllocs.remove(
{addr, shape, (uint8_t)GenericRequirement::Kind::MetadataPack});
assert(removed && "erased stack pack metadata addr that wasn't recorded!?");
(void)removed;
}
void IRGenFunction::recordStackPackWitnessTableAlloc(StackAddress addr,
llvm::Value *shape) {
OutstandingStackPackAllocs.insert(
{addr, shape, (uint8_t)GenericRequirement::Kind::WitnessTablePack});
}
void IRGenFunction::eraseStackPackWitnessTableAlloc(StackAddress addr,
llvm::Value *shape) {
auto removed = OutstandingStackPackAllocs.remove(
{addr, shape, (uint8_t)GenericRequirement::Kind::WitnessTablePack});
assert(removed && "erased stack pack metadata addr that wasn't recorded!?");
(void)removed;
}
void IRGenFunction::withLocalStackPackAllocs(llvm::function_ref<void()> fn) {
auto oldSize = OutstandingStackPackAllocs.size();
fn();
SmallVector<StackPackAlloc, 2> allocs;
for (auto index = oldSize, size = OutstandingStackPackAllocs.size();
index < size; ++index) {
allocs.push_back(OutstandingStackPackAllocs[index]);
}
while (OutstandingStackPackAllocs.size() > oldSize) {
OutstandingStackPackAllocs.pop_back();
}
cleanupStackAllocPacks(*this, allocs);
}
llvm::Value *irgen::emitWitnessTablePackRef(IRGenFunction &IGF,
CanPackType packType,
PackConformance *conformance) {
assert(Lowering::TypeConverter::protocolRequiresWitnessTable(
conformance->getProtocol()) &&
"looking up witness table for protocol that doesn't have one");
if (auto *wtable = tryGetLocalPackTypeData(
IGF, packType,
LocalTypeDataKind::forAbstractProtocolWitnessTable(
conformance->getProtocol())))
return wtable;
auto localDataKind =
LocalTypeDataKind::forProtocolWitnessTablePack(conformance);
if (auto *wtable = tryGetLocalPackTypeData(IGF, packType, localDataKind))
return wtable;
StackAddress pack;
llvm::Value *shape;
std::tie(pack, shape) = emitWitnessTablePack(IGF, packType, conformance);
auto *result = pack.getAddress().getAddress();
result = IGF.Builder.CreatePointerCast(
result, IGF.IGM.WitnessTablePtrTy->getPointerTo());
if (!IGF.canStackPromotePackMetadata()) {
result = IGF.Builder.CreateCall(
IGF.IGM.getAllocateWitnessTablePackFunctionPointer(), {result, shape});
cleanupWitnessTablePack(IGF, pack, shape);
}
IGF.setScopedLocalTypeData(packType, localDataKind, result);
return result;
}
llvm::Value *irgen::emitTypeMetadataPackElementRef(
IRGenFunction &IGF, CanPackType packType,
ArrayRef<ProtocolConformanceRef> conformances, llvm::Value *index,
DynamicMetadataRequest request,
llvm::SmallVectorImpl<llvm::Value *> &wtables) {
// If the packs have already been materialized, just gep into them.
auto materializedMetadataPack =
tryGetLocalPackTypeMetadata(IGF, packType, request);
llvm::SmallVector<llvm::Value *> materializedWtablePacks;
for (auto conformance : conformances) {
auto *wtablePack = tryGetLocalPackTypeData(
IGF, packType,
LocalTypeDataKind::forProtocolWitnessTable(conformance));
materializedWtablePacks.push_back(wtablePack);
}
if (materializedMetadataPack &&
llvm::all_of(materializedWtablePacks,
[](auto *wtablePack) { return wtablePack; })) {
auto *metadataPack = materializedMetadataPack.getMetadata();
auto *metadata = loadMetadataAtIndex(IGF, metadataPack, index);
for (auto *wtablePack : materializedWtablePacks) {
auto *wtable = loadWitnessTableAtIndex(IGF, wtablePack, index);
wtables.push_back(wtable);
}
return metadata;
}
// Otherwise, in general, there's no already available array of metadata
// which can be indexed into.
auto *shape = IGF.emitPackShapeExpression(packType);
// If the shape and the index are both constant, the type for which metadata
// will be emitted is statically available.
auto *constantShape = dyn_cast<llvm::ConstantInt>(shape);
auto *constantIndex = dyn_cast<llvm::ConstantInt>(index);
if (constantShape && constantIndex) {
assert(packType->getNumElements() == constantShape->getValue());
auto index = constantIndex->getValue().getZExtValue();
assert(packType->getNumElements() > index);
auto ty = packType.getElementType(index);
auto response = IGF.emitTypeMetadataRef(ty, request);
auto *metadata = response.getMetadata();
for (auto conformance : conformances) {
auto patternConformance = conformance.getPack()
->getPatternConformances()[index];
auto *wtable =
emitWitnessTableRef(IGF, ty, /*srcMetadataCache=*/&metadata,
patternConformance);
wtables.push_back(wtable);
}
return metadata;
}
// A pack consists of types and pack expansion types. An example:
// {repeat each T, Int, repeat each T, repeat each U, String},
// The above type has length 5. The type "repeat each U" is at index 3.
//
// A pack _explosion_ is notionally obtained by flat-mapping the pack by the
// the operation of "listing elements" in pack expansion types.
//
// The explosion of the example pack looks like
// {T_0, T_1, ..., Int, T_0, T_1, ..., U_0, U_1, ..., String}
// ^^^^^^^^^^^^^
// the runtime components of "each T"
//
// We have an index into the explosion,
//
// {T_0, T_1, ..., Int, T_0, T_1, ..., U_0, U_1, ... String}
// ------------%index------------>
//
// and we need to obtain the element in the explosion corresponding to it.
//
// {T_0, T_1, ..., Int, T_0, T_1, ..., T_k, ..., U_0, U_1, ... String}
// ------------%index---------------> ^^^
//
// Unfortunately, the explosion has not (the first check in this function)
// been materialized--and doing so is likely wasteful--so we can't simply
// index into some array.
//
// Instead, _notionally_, we will "compute"
// (1) the index into the _pack_ and
// {repeat each T, Int, repeat each T, repeat each U, String}
// ------%outer------> ^^^^^^^^^^^^^
// (2) the index within the elements of the pack expansion type
// {T_0, T_2, ..., T_k, ...}
// ----%inner---> ^^^
//
// In fact, we won't ever materialize %outer into any register. Instead, we
// can just brach to materializing the metadata (and witness tables) once
// we've determined which outer element's range contains %index.
//
// As for %inner, it will only be materialized in those blocks corresponding
// to pack expansions.
//
// Create the following control flow:
//
// +-------+ t_0 is not t_N _is_ an
// |entry: | an expansion expansion
// |... | +----------+ +----------+ +----------+
// |... | --> |check_0: | -> ... -> |check_N: | -> |trap: |
// | | | %i == %u0| | %i < %uN | | llvm.trap|
// +-------+ +----------+ +----------+ +----------+
// %outer = 0 %outer = N
// | |
// V V
// +----------+ +-----------------------+
// |emit_1: | |emit_N: |
// | %inner=0 | | %inner = %index - %lN |
// | %m_1 = | | %m_N = |
// | %wt_1_1= | | %wt_1_N = |
// | %wt_k_1= | | %wt_k_N = |
// +----------+ +-----------------------+
// | |
// V V
// +-------------------------------------------
// |exit:
// | %m = phi [ %m_1, %emit_1 ],
// | ...
// | [ %m_N, %emit_N ]
// | %wt_1 = phi [ %wt_1_1, %emit_1 ],
// | ...
// | [ %m_1_N, %emit_N ]
// | ...
// | %wt_k = phi [ %wt_k_1, %emit_1 ],
// | ...
// | [ %m_k_N, %emit_N ]
auto *current = IGF.Builder.GetInsertBlock();
// Terminate the block that branches to continue checking or metadata/wtable
// emission depending on whether the index is in the pack expansion's bounds.
auto emitCheckBranch = [&IGF](llvm::Value *condition,
llvm::BasicBlock *inBounds,
llvm::BasicBlock *outOfBounds) {
if (condition) {
IGF.Builder.CreateCondBr(condition, inBounds, outOfBounds);
} else {
assert(!inBounds &&
"no condition to check but a materialization block!?");
IGF.Builder.CreateBr(outOfBounds);
}
};
// The block which emission will continue in after we finish emitting
// metadata/wtables for this element.
auto *exit = IGF.createBasicBlock("pack-index-element-exit");
IGF.Builder.emitBlock(exit);
auto *metadataPhi = IGF.Builder.CreatePHI(IGF.IGM.TypeMetadataPtrTy,
packType.getElementTypes().size());
llvm::SmallVector<llvm::PHINode *, 2> wtablePhis;
wtablePhis.reserve(conformances.size());
for (auto idx : indices(conformances)) {
(void)idx;
wtablePhis.push_back(IGF.Builder.CreatePHI(
IGF.IGM.WitnessTablePtrTy, packType.getElementTypes().size()));
}
IGF.Builder.SetInsertPoint(current);
// The previous checkBounds' block's comparision of %index. Use it to emit a
// branch to the current block or the previous block's metadata/wtable
// emission block.
llvm::Value *previousCondition = nullptr;
// The previous type's materialize block. Use it as the inBounds target when
// branching from the previous block.
llvm::BasicBlock *previousInBounds = nullptr;
// The lower bound of indices for the current pack expansion. Inclusive.
llvm::Value *lowerBound = llvm::ConstantInt::get(IGF.IGM.SizeTy, 0);
for (unsigned i = 0, e = packType->getNumElements(); i < e; ++i) {
auto elementTy = packType.getElementType(i);
// The block within which it will be checked whether %index corresponds to
// an element of the pack expansion elementTy.
auto *checkBounds = IGF.createBasicBlock("pack-index-element-bounds");
// Finish emitting the previous block, either entry or check_i-1.
//
// Branch from the previous bounds-check block either to this bounds-check
// block or to the previous metadata/wtable emission block.
emitCheckBranch(previousCondition, previousInBounds, checkBounds);
// (1) Emit check_i {{
IGF.Builder.emitBlock(checkBounds);
ConditionalDominanceScope dominanceScope(IGF);
// The upper bound for the current pack expansion. Exclusive.
llvm::Value *upperBound = nullptr;
llvm::Value *condition = nullptr;
if (auto expansionTy = dyn_cast<PackExpansionType>(elementTy)) {
auto reducedShape = expansionTy.getCountType();
auto *length = IGF.emitPackShapeExpression(reducedShape);
upperBound = IGF.Builder.CreateAdd(lowerBound, length);
// %index < %upperBound
//
// It's not necessary to check that %index >= %lowerBound. Either
// elementTy is the first element type in packType or we branched here
// from some series of checkBounds blocks in each of which it was
// determined that %index is greater than the indices of the
// corresponding element type.
condition = IGF.Builder.CreateICmpULT(index, upperBound);
} else {
upperBound = IGF.Builder.CreateAdd(
lowerBound, llvm::ConstantInt::get(IGF.IGM.SizeTy, 1));
// %index == %lowerBound
condition = IGF.Builder.CreateICmpEQ(lowerBound, index);
}
// }} Finished emitting check_i, except for the terminator which will be
// emitted in the next iteration once the new outOfBounds block is
// available.
// (2) Emit emit_i {{
// The block within which the metadata/wtables corresponding to %inner will
// be materialized.
auto *materialize = IGF.createBasicBlock("pack-index-element-metadata");
IGF.Builder.emitBlock(materialize);
IGF.withLocalStackPackAllocs([&]() {
llvm::Value *metadata = nullptr;
llvm::SmallVector<llvm::Value *, 2> wtables;
wtables.reserve(conformances.size());
if (auto expansionTy = dyn_cast<PackExpansionType>(elementTy)) {
// Actually materialize %inner. Then use it to get the metadata from
// the pack expansion at that index.
auto *relativeIndex = IGF.Builder.CreateSub(index, lowerBound);
auto context = OpenedElementContext::createForContextualExpansion(
IGF.IGM.Context, expansionTy);
auto patternTy = expansionTy.getPatternType();
metadata = emitPackExpansionElementMetadata(IGF, context, patternTy,
relativeIndex, request);
for (auto conformance : conformances) {
auto patternConformance =