-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathAbstractionPattern.cpp
2858 lines (2552 loc) · 103 KB
/
AbstractionPattern.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
//===--- AbstractionPattern.cpp - Abstraction patterns --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 defines routines relating to abstraction patterns.
// working in concert with the Clang importer.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "libsil"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ForeignAsyncConvention.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/Basic/Defer.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/SIL/AbstractionPatternGenerators.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/PrettyPrinter.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
using namespace swift;
using namespace swift::Lowering;
AbstractionPattern
TypeConverter::getAbstractionPattern(AbstractStorageDecl *decl,
bool isNonObjC) {
if (auto var = dyn_cast<VarDecl>(decl)) {
return getAbstractionPattern(var, isNonObjC);
} else {
return getAbstractionPattern(cast<SubscriptDecl>(decl), isNonObjC);
}
}
AbstractionPattern
TypeConverter::getAbstractionPattern(SubscriptDecl *decl, bool isNonObjC) {
auto sig = decl->getGenericSignatureOfContext().getCanonicalSignature();
auto type = sig.getReducedType(decl->getElementInterfaceType());
return AbstractionPattern(sig, type);
}
static const clang::Type *getClangType(const clang::Decl *decl) {
if (auto valueDecl = dyn_cast<clang::ValueDecl>(decl)) {
return valueDecl->getType().getTypePtr();
}
// This should *really* be a ValueDecl.
return cast<clang::ObjCPropertyDecl>(decl)->getType().getTypePtr();
}
static Bridgeability getClangDeclBridgeability(const clang::Decl *decl) {
// These declarations are always imported without bridging (for now).
if (isa<clang::VarDecl>(decl) ||
isa<clang::FieldDecl>(decl) ||
isa<clang::IndirectFieldDecl>(decl))
return Bridgeability::None;
// Functions and methods always use normal bridging.
return Bridgeability::Full;
}
AbstractionPattern
TypeConverter::getAbstractionPattern(VarDecl *var, bool isNonObjC) {
auto sig = var->getDeclContext()
->getGenericSignatureOfContext()
.getCanonicalSignature();
auto interfaceType = var->getInterfaceType();
if (auto *packExpansionType = interfaceType->getAs<PackExpansionType>())
interfaceType = packExpansionType->getPatternType();
auto swiftType = sig.getReducedType(interfaceType);
if (isNonObjC)
return AbstractionPattern(sig, swiftType);
if (auto clangDecl = var->getClangDecl()) {
auto clangType = getClangType(clangDecl);
auto contextType = var->getDeclContext()->mapTypeIntoContext(swiftType);
swiftType =
getLoweredBridgedType(AbstractionPattern(sig, swiftType, clangType),
contextType, getClangDeclBridgeability(clangDecl),
SILFunctionTypeRepresentation::CFunctionPointer,
TypeConverter::ForMemory)
->getCanonicalType();
return AbstractionPattern(sig, swiftType, clangType);
}
return AbstractionPattern(sig, swiftType);
}
AbstractionPattern TypeConverter::getAbstractionPattern(EnumElementDecl *decl) {
assert(decl->hasAssociatedValues());
assert(!decl->hasClangNode());
// This cannot be implemented correctly for Optional.Some.
assert(!decl->getParentEnum()->isOptionalDecl() &&
"Optional.Some does not have a unique abstraction pattern because "
"optionals are re-abstracted");
auto sig = decl->getParentEnum()
->getGenericSignatureOfContext()
.getCanonicalSignature();
auto type = sig.getReducedType(decl->getArgumentInterfaceType());
return AbstractionPattern(sig, type);
}
AbstractionPattern::EncodedForeignInfo
AbstractionPattern::EncodedForeignInfo::encode(
const std::optional<ForeignErrorConvention> &foreignError,
const std::optional<ForeignAsyncConvention> &foreignAsync) {
// Foreign async convention takes precedence.
if (foreignAsync.has_value()) {
return EncodedForeignInfo(EncodedForeignInfo::Async,
foreignAsync->completionHandlerParamIndex(),
foreignAsync->completionHandlerErrorParamIndex(),
foreignAsync->completionHandlerFlagParamIndex(),
foreignAsync->completionHandlerFlagIsErrorOnZero());
} else if (foreignError.has_value()) {
return EncodedForeignInfo(EncodedForeignInfo::Error,
foreignError->getErrorParameterIndex(),
foreignError->isErrorParameterReplacedWithVoid(),
foreignError->stripsResultOptionality());
} else {
return {};
}
}
AbstractionPattern AbstractionPattern::getObjCMethod(
CanType origType, const clang::ObjCMethodDecl *method,
const std::optional<ForeignErrorConvention> &foreignError,
const std::optional<ForeignAsyncConvention> &foreignAsync) {
auto errorInfo = EncodedForeignInfo::encode(foreignError, foreignAsync);
return getObjCMethod(origType, method, errorInfo);
}
AbstractionPattern AbstractionPattern::getCurriedObjCMethod(
CanType origType, const clang::ObjCMethodDecl *method,
const std::optional<ForeignErrorConvention> &foreignError,
const std::optional<ForeignAsyncConvention> &foreignAsync) {
auto errorInfo = EncodedForeignInfo::encode(foreignError, foreignAsync);
return getCurriedObjCMethod(origType, method, errorInfo);
}
AbstractionPattern
AbstractionPattern::getCurriedCFunctionAsMethod(CanType origType,
const AbstractFunctionDecl *function) {
auto clangFn = cast<clang::ValueDecl>(function->getClangDecl());
return getCurriedCFunctionAsMethod(origType,
clangFn->getType().getTypePtr(),
function->getImportAsMemberStatus());
}
AbstractionPattern
AbstractionPattern::getCurriedCXXMethod(CanType origType,
const AbstractFunctionDecl *function) {
auto clangMethod = cast<clang::CXXMethodDecl>(function->getClangDecl());
return getCurriedCXXMethod(origType, clangMethod, function->getImportAsMemberStatus());
}
AbstractionPattern
AbstractionPattern::getOptional(AbstractionPattern object) {
switch (object.getKind()) {
case Kind::Invalid:
llvm_unreachable("querying invalid abstraction pattern!");
case Kind::Tuple:
case Kind::PartialCurriedObjCMethodType:
case Kind::CurriedObjCMethodType:
case Kind::CFunctionAsMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::ObjCMethodType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::OpaqueFunction:
case Kind::OpaqueDerivativeFunction:
case Kind::ObjCCompletionHandlerArgumentsType:
llvm_unreachable("cannot add optionality to non-type abstraction");
case Kind::Opaque:
return AbstractionPattern::getOpaque();
case Kind::ClangType:
return AbstractionPattern(object.getGenericSubstitutions(),
object.getGenericSignature(),
OptionalType::get(object.getType())
->getCanonicalType(),
object.getClangType());
case Kind::Type:
return AbstractionPattern(object.getGenericSubstitutions(),
object.getGenericSignature(),
OptionalType::get(object.getType())
->getCanonicalType());
case Kind::Discard:
return AbstractionPattern::getDiscard(
object.getGenericSubstitutions(),
object.getGenericSignature(),
OptionalType::get(object.getType())
->getCanonicalType());
}
llvm_unreachable("bad kind");
}
bool AbstractionPattern::isConcreteType() const {
assert(isTypeParameter());
return (getKind() != Kind::Opaque &&
GenericSig != nullptr &&
GenericSig->isConcreteType(getType()));
}
bool AbstractionPattern::requiresClass() const {
switch (getKind()) {
case Kind::Opaque:
return false;
case Kind::Type:
case Kind::Discard:
case Kind::ClangType: {
auto type = getType();
if (auto element = dyn_cast<PackElementType>(type))
type = element.getPackType();
if (auto archetype = dyn_cast<ArchetypeType>(type))
return archetype->requiresClass();
if (type->isTypeParameter()) {
if (getKind() == Kind::ClangType) {
// ObjC generics are always class constrained.
return true;
}
assert(GenericSig &&
"Dependent type in pattern without generic signature?");
return GenericSig->requiresClass(type);
}
return false;
}
default:
return false;
}
}
LayoutConstraint AbstractionPattern::getLayoutConstraint() const {
switch (getKind()) {
case Kind::Opaque:
return LayoutConstraint();
case Kind::Type:
case Kind::Discard:
case Kind::ClangType: {
auto type = getType();
if (auto archetype = dyn_cast<ArchetypeType>(type)) {
return archetype->getLayoutConstraint();
} else if (isa<DependentMemberType>(type) ||
isa<GenericTypeParamType>(type)) {
if (getKind() == Kind::ClangType) {
// ObjC generics are always class constrained.
return LayoutConstraint::getLayoutConstraint(
LayoutConstraintKind::Class);
}
assert(GenericSig &&
"Dependent type in pattern without generic signature?");
return GenericSig->getLayoutConstraint(type);
}
return LayoutConstraint();
}
default:
return LayoutConstraint();
}
}
bool AbstractionPattern::isNoncopyable(CanType substTy) const {
auto copyable
= substTy->getASTContext().getProtocol(KnownProtocolKind::Copyable);
auto isDefinitelyCopyable = [&](CanType t) -> bool {
auto result = copyable->getParentModule()
->checkConformanceWithoutContext(t, copyable,
/*allowMissing=*/false);
return result.has_value() && !result.value().isInvalid();
};
// If the substituted type definitely conforms, that's authoritative.
if (isDefinitelyCopyable(substTy)) {
return false;
}
// If the substituted type is fully concrete, that's it. If there are unbound
// type variables in the type, then we may have to account for the upper
// abstraction bound from the abstraction pattern.
if (!substTy->hasTypeParameter()) {
return true;
}
switch (getKind()) {
case Kind::Opaque: {
// The abstraction pattern doesn't provide any more specific bounds.
return true;
}
case Kind::Type:
case Kind::Discard:
case Kind::ClangType: {
// See whether the abstraction pattern's context gives us an upper bound
// that ensures the type is copyable.
auto type = getType();
if (hasGenericSignature() && getType()->hasTypeParameter()) {
type = GenericEnvironment::mapTypeIntoContext(
getGenericSignature().getGenericEnvironment(), getType())
->getReducedType(getGenericSignature());
}
return !isDefinitelyCopyable(type);
}
case Kind::Tuple: {
// A tuple is noncopyable if any element is.
if (doesTupleVanish()) {
return getVanishingTupleElementPatternType().value()
.isNoncopyable(substTy);
}
auto substTupleTy = cast<TupleType>(substTy);
for (unsigned i = 0, e = getNumTupleElements(); i < e; ++i) {
if (getTupleElementType(i).isNoncopyable(substTupleTy.getElementType(i))){
return true;
}
}
return false;
}
// Functions are, at least for now, always copyable.
case Kind::CurriedObjCMethodType:
case Kind::PartialCurriedObjCMethodType:
case Kind::CFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::ObjCMethodType:
case Kind::ObjCCompletionHandlerArgumentsType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::OpaqueFunction:
case Kind::OpaqueDerivativeFunction:
return false;
case Kind::Invalid:
llvm_unreachable("asking invalid abstraction pattern");
}
}
bool AbstractionPattern::matchesTuple(CanType substType) const {
switch (getKind()) {
case Kind::Invalid:
llvm_unreachable("querying invalid abstraction pattern!");
case Kind::PartialCurriedObjCMethodType:
case Kind::CurriedObjCMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::CFunctionAsMethodType:
case Kind::ObjCMethodType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::OpaqueFunction:
case Kind::OpaqueDerivativeFunction:
return false;
case Kind::Opaque:
return true;
case Kind::ObjCCompletionHandlerArgumentsType:
case Kind::ClangType:
case Kind::Type:
case Kind::Discard:
if (isTypeParameterOrOpaqueArchetype())
return true;
if (!isa<TupleType>(getType()))
return false;
LLVM_FALLTHROUGH;
case Kind::Tuple: {
if (doesTupleVanish()) {
// TODO: recurse into elements.
return true;
}
auto substTupleType = dyn_cast<TupleType>(substType);
if (!substTupleType) return false;
size_t nextSubstIndex = 0;
auto nextComponentIsAcceptable = [&](bool isPackExpansion) -> bool {
if (nextSubstIndex == substTupleType->getNumElements())
return false;
auto substComponentType = substTupleType.getElementType(nextSubstIndex++);
return (isPackExpansion == isa<PackExpansionType>(substComponentType));
};
for (auto elt : getTupleElementTypes()) {
bool isPackExpansion = elt.isPackExpansion();
if (isPackExpansion && elt.GenericSubs) {
auto origExpansion = cast<PackExpansionType>(elt.getType());
auto substShape = cast<PackType>(
origExpansion.getCountType().subst(elt.GenericSubs)
->getCanonicalType());
for (auto shapeElt : substShape.getElementTypes()) {
if (!nextComponentIsAcceptable(isa<PackExpansionType>(shapeElt)))
return false;
}
} else if (!nextComponentIsAcceptable(isPackExpansion)) {
return false;
}
}
return nextSubstIndex == substTupleType->getNumElements();
}
}
llvm_unreachable("bad kind");
}
static const clang::FunctionType *
getClangFunctionType(const clang::Type *clangType) {
if (auto ptrTy = clangType->getAs<clang::PointerType>()) {
clangType = ptrTy->getPointeeType().getTypePtr();
} else if (auto blockTy = clangType->getAs<clang::BlockPointerType>()) {
clangType = blockTy->getPointeeType().getTypePtr();
} else if (auto refTy = clangType->getAs<clang::ReferenceType>()) {
clangType = refTy->getPointeeType().getTypePtr();
}
return clangType->castAs<clang::FunctionType>();
}
static
const clang::Type *getClangFunctionParameterType(const clang::Type *ty,
unsigned index) {
// TODO: adjust for error type parameter.
// If we're asking about parameters, we'd better have a FunctionProtoType.
auto fnType = getClangFunctionType(ty)->castAs<clang::FunctionProtoType>();
assert(index < fnType->getNumParams());
return fnType->getParamType(index).getTypePtr();
}
static
const clang::Type *getClangArrayElementType(const clang::Type *ty,
unsigned index) {
return ty->castAsArrayTypeUnsafe()->getElementType().getTypePtr();
}
static CanType getCanTupleElementType(CanType type, unsigned index) {
if (auto tupleTy = dyn_cast<TupleType>(type))
return tupleTy.getElementType(index);
assert(index == 0);
return type;
}
AbstractionPattern
AbstractionPattern::getTupleElementType(unsigned index) const {
switch (getKind()) {
case Kind::Invalid:
llvm_unreachable("querying invalid abstraction pattern!");
case Kind::PartialCurriedObjCMethodType:
case Kind::CurriedObjCMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::CFunctionAsMethodType:
case Kind::ObjCMethodType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::OpaqueFunction:
case Kind::OpaqueDerivativeFunction:
llvm_unreachable("function types are not tuples");
case Kind::Opaque:
return *this;
case Kind::Tuple:
assert(index < getNumTupleElements_Stored());
return OrigTupleElements[index];
case Kind::ClangType:
return AbstractionPattern(getGenericSubstitutions(),
getGenericSignature(),
getCanTupleElementType(getType(), index),
getClangArrayElementType(getClangType(), index));
case Kind::Discard:
llvm_unreachable("operation not needed on discarded abstractions yet");
case Kind::Type:
if (isTypeParameterOrOpaqueArchetype())
return AbstractionPattern::getOpaque();
return AbstractionPattern(getGenericSubstitutions(),
getGenericSignature(),
getCanTupleElementType(getType(), index));
case Kind::ObjCCompletionHandlerArgumentsType: {
// Match up the tuple element with the parameter from the Clang block type,
// skipping the error parameter and flag indexes if any.
auto callback = cast<clang::FunctionProtoType>(getClangType());
auto errorIndex = getEncodedForeignInfo()
.getAsyncCompletionHandlerErrorParamIndex();
auto flagIndex = getEncodedForeignInfo()
.getAsyncCompletionHandlerErrorFlagParamIndex();
unsigned paramIndex = index;
if (errorIndex && paramIndex >= *errorIndex)
++paramIndex;
if (flagIndex && paramIndex >= *flagIndex)
++paramIndex;
return AbstractionPattern(getGenericSubstitutions(),
getGenericSignature(),
getCanTupleElementType(getType(), index),
callback->getParamType(paramIndex).getTypePtr());
}
}
llvm_unreachable("bad kind");
}
bool AbstractionPattern::doesTupleContainPackExpansionType() const {
switch (getKind()) {
case Kind::Invalid:
llvm_unreachable("querying invalid abstraction pattern!");
case Kind::Opaque:
case Kind::PartialCurriedObjCMethodType:
case Kind::CurriedObjCMethodType:
case Kind::CFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::ObjCMethodType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::OpaqueFunction:
case Kind::OpaqueDerivativeFunction:
llvm_unreachable("pattern is not a tuple");
case Kind::Tuple: {
for (auto &elt :
llvm::ArrayRef(OrigTupleElements, getNumTupleElements_Stored())) {
if (elt.isPackExpansion())
return true;
}
return true;
}
case Kind::ObjCCompletionHandlerArgumentsType:
case Kind::Type:
case Kind::Discard:
case Kind::ClangType:
return cast<TupleType>(getType()).containsPackExpansionType();
}
llvm_unreachable("bad kind");
}
bool AbstractionPattern::doesTupleVanish() const {
assert(isTuple());
return getVanishingTupleElementPatternType().has_value();
}
std::optional<AbstractionPattern>
AbstractionPattern::getVanishingTupleElementPatternType() const {
if (!isTuple())
return std::nullopt;
if (!GenericSubs)
return std::nullopt;
// Substitution causes tuples to vanish when substituting the elements
// produces a singleton tuple and it didn't start that way.
auto numOrigElts = getNumTupleElements();
// Track whether we've found a single element.
std::optional<AbstractionPattern> singletonEltType;
bool hadOrigExpansion = false;
for (auto index : range(numOrigElts)) {
auto eltType = getTupleElementType(index);
// If this pattern isn't a pack expansion, we've got a new candidate
// singleton. If this is the second such candidate, of course, it's
// not a singleton.
if (!eltType.isPackExpansion()) {
if (singletonEltType)
return std::nullopt;
singletonEltType = eltType;
// Otherwise, check what the expansion shape expands to.
} else {
hadOrigExpansion = true;
auto expansionType = cast<PackExpansionType>(eltType.getType());
auto substShape = cast<PackType>(
expansionType.getCountType().subst(GenericSubs)->getCanonicalType());
auto expansionCount = substShape->getNumElements();
// If it expands to multiple elements or to a single expansion, we
// won't have a singleton tuple. If it expands to a single scalar
// element, this is a singleton candidate.
if (expansionCount > 1) {
return std::nullopt;
} else if (expansionCount == 1) {
auto substExpansion =
dyn_cast<PackExpansionType>(substShape.getElementType(0));
if (substExpansion)
return std::nullopt;
if (singletonEltType)
return std::nullopt;
singletonEltType = eltType.getPackExpansionPatternType();
}
}
}
// If we found a singleton scalar element, and we didn't start with
// a singleton element, that's the index we want to return.
if (singletonEltType && !(numOrigElts == 1 && !hadOrigExpansion))
return singletonEltType;
return std::nullopt;
}
void AbstractionPattern::forEachTupleElement(CanType substType,
llvm::function_ref<void(TupleElementGenerator &)> handleElement) const {
TupleElementGenerator elt(*this, substType);
for (; !elt.isFinished(); elt.advance()) {
handleElement(elt);
}
elt.finish();
}
TupleElementGenerator::TupleElementGenerator(
AbstractionPattern origTupleType,
CanType substType)
: origTupleType(origTupleType), substType(substType) {
assert(origTupleType.isTuple());
assert(origTupleType.matchesTuple(substType));
origTupleVanishes = origTupleType.doesTupleVanish();
origTupleTypeIsOpaque = origTupleType.isOpaqueTuple();
numOrigElts = origTupleType.getNumTupleElements();
if (!isFinished()) loadElement();
}
void AbstractionPattern::forEachExpandedTupleElement(CanType substType,
llvm::function_ref<void(AbstractionPattern origEltType,
CanType substEltType,
const TupleTypeElt &elt)>
handleElement) const {
assert(matchesTuple(substType));
// Handle opaque patterns by just iterating the substituted components.
if (!isTuple()) {
auto substTupleType = cast<TupleType>(substType);
auto substEltTypes = substTupleType.getElementTypes();
for (auto i : indices(substEltTypes)) {
handleElement(getTupleElementType(i), substEltTypes[i],
substTupleType->getElement(i));
}
return;
}
// For vanishing tuples, just call the callback once.
if (auto origEltType = getVanishingTupleElementPatternType()) {
handleElement(*origEltType, substType, TupleTypeElt(substType));
return;
}
auto substTupleType = cast<TupleType>(substType);
auto substEltTypes = substTupleType.getElementTypes();
// For non-opaque patterns, we have to iterate the original components
// in order to match things up properly, but we'll still end up calling
// once per substituted element.
size_t substEltIndex = 0;
for (size_t origEltIndex : range(getNumTupleElements())) {
auto origEltType = getTupleElementType(origEltIndex);
if (!origEltType.isPackExpansion()) {
handleElement(origEltType, substEltTypes[substEltIndex],
substTupleType->getElement(substEltIndex));
substEltIndex++;
} else {
auto origPatternType = origEltType.getPackExpansionPatternType();
for (auto i : range(origEltType.getNumPackExpandedComponents())) {
(void) i;
auto substEltType = substEltTypes[substEltIndex];
// When the substituted type is a pack expansion, pass down
// the original element type so that it's *also* a pack expansion.
// Clients expect to look through this structure in parallel on
// both types. The count is misleading, but normal usage won't
// access it, and there's nothing we could provide that *wouldn't*
// be misleading in one way or another.
handleElement(isa<PackExpansionType>(substEltType)
? origEltType : origPatternType,
substEltType,
substTupleType->getElement(substEltIndex));
substEltIndex++;
}
}
}
assert(substEltIndex == substEltTypes.size());
}
AbstractionPattern
AbstractionPattern::getPackElementPackType() const {
switch (getKind()) {
case Kind::Invalid:
llvm_unreachable("querying invalid abstraction pattern!");
case Kind::PartialCurriedObjCMethodType:
case Kind::CurriedObjCMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::CFunctionAsMethodType:
case Kind::ObjCMethodType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::OpaqueFunction:
case Kind::OpaqueDerivativeFunction:
case Kind::ClangType:
case Kind::Tuple:
case Kind::ObjCCompletionHandlerArgumentsType:
llvm_unreachable("not a pack type");
case Kind::Opaque:
return *this;
case Kind::Discard:
llvm_unreachable("operation not needed on discarded abstractions yet");
case Kind::Type:
if (isTypeParameterOrOpaqueArchetype())
return AbstractionPattern::getOpaque();
return AbstractionPattern(getGenericSubstitutions(),
getGenericSignature(),
cast<PackElementType>(getType()).getPackType());
}
llvm_unreachable("bad kind");
}
static CanType getCanPackElementType(CanType type, unsigned index) {
return cast<PackType>(type).getElementType(index);
}
static CanType getCanSILPackElementType(CanType type, unsigned index) {
return cast<SILPackType>(type).getElementType(index);
}
static CanType getAnyCanPackElementType(CanType type, unsigned index) {
if (isa<PackType>(type)) {
return getCanPackElementType(type, index);
}
return getCanSILPackElementType(type, index);
}
AbstractionPattern
AbstractionPattern::getPackElementType(unsigned index) const {
switch (getKind()) {
case Kind::Invalid:
llvm_unreachable("querying invalid abstraction pattern!");
case Kind::PartialCurriedObjCMethodType:
case Kind::CurriedObjCMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::CFunctionAsMethodType:
case Kind::ObjCMethodType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::OpaqueFunction:
case Kind::OpaqueDerivativeFunction:
case Kind::ClangType:
case Kind::Tuple:
case Kind::ObjCCompletionHandlerArgumentsType:
llvm_unreachable("not a pack type");
case Kind::Opaque:
return *this;
case Kind::Discard:
llvm_unreachable("operation not needed on discarded abstractions yet");
case Kind::Type:
if (isTypeParameterOrOpaqueArchetype())
return AbstractionPattern::getOpaque();
return AbstractionPattern(getGenericSubstitutions(),
getGenericSignature(),
getAnyCanPackElementType(getType(), index));
}
llvm_unreachable("bad kind");
}
bool AbstractionPattern::matchesPack(CanPackType substType) const {
switch (getKind()) {
case Kind::Invalid:
llvm_unreachable("querying invalid abstraction pattern!");
case Kind::PartialCurriedObjCMethodType:
case Kind::CurriedObjCMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::CFunctionAsMethodType:
case Kind::ObjCMethodType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::OpaqueFunction:
case Kind::OpaqueDerivativeFunction:
case Kind::Tuple:
case Kind::ObjCCompletionHandlerArgumentsType:
case Kind::ClangType:
return false;
case Kind::Opaque:
return true;
case Kind::Type:
case Kind::Discard: {
if (isTypeParameterOrOpaqueArchetype())
return true;
auto type = getType();
if (auto pack = dyn_cast<PackType>(type))
return (pack->getNumElements() == substType->getNumElements());
return false;
}
}
llvm_unreachable("bad kind");
}
void AbstractionPattern::forEachPackElement(CanPackType substType,
llvm::function_ref<void(PackElementGenerator &)> handleElement) const {
PackElementGenerator elt(*this, substType);
for (; !elt.isFinished(); elt.advance()) {
handleElement(elt);
}
elt.finish();
}
void AbstractionPattern::forEachExpandedPackElement(CanPackType substPackType,
llvm::function_ref<void(AbstractionPattern origEltType,
CanType substEltType)>
handleElement) const {
assert(matchesPack(substPackType));
auto substEltTypes = substPackType.getElementTypes();
// Handle opaque patterns by just iterating the substituted components.
if (!isPack()) {
for (auto i : indices(substEltTypes)) {
handleElement(getPackElementType(i), substEltTypes[i]);
}
return;
}
// For non-opaque patterns, we have to iterate the original components
// in order to match things up properly, but we'll still end up calling
// once per substituted element.
size_t substEltIndex = 0;
for (size_t origEltIndex : range(getNumPackElements())) {
auto origEltType = getPackElementType(origEltIndex);
if (!origEltType.isPackExpansion()) {
handleElement(origEltType, substEltTypes[substEltIndex]);
substEltIndex++;
} else {
auto origPatternType = origEltType.getPackExpansionPatternType();
for (auto i : range(origEltType.getNumPackExpandedComponents())) {
(void) i;
auto substEltType = substEltTypes[substEltIndex];
// When the substituted type is a pack expansion, pass down
// the original element type so that it's *also* a pack expansion.
// Clients expect to look through this structure in parallel on
// both types. The count is misleading, but normal usage won't
// access it, and there's nothing we could provide that *wouldn't*
// be misleading in one way or another.
handleElement(isa<PackExpansionType>(substEltType)
? origEltType : origPatternType,
substEltType);
substEltIndex++;
}
}
}
assert(substEltIndex == substEltTypes.size());
}
PackElementGenerator::PackElementGenerator(
AbstractionPattern origPackType,
CanPackType substPackType)
: origPackType(origPackType), substPackType(substPackType) {
assert(origPackType.isPack());
assert(origPackType.matchesPack(substPackType));
numOrigElts = origPackType.getNumPackElements();
if (!isFinished()) loadElement();
}
AbstractionPattern
AbstractionPattern::getPackExpansionComponentType(CanType substType) const {
return getPackExpansionComponentType(isa<PackExpansionType>(substType));
}
AbstractionPattern
AbstractionPattern::getPackExpansionComponentType(bool isExpansion) const {
assert(isPackExpansion());
return isExpansion ? *this : getPackExpansionPatternType();
}
static CanType getPackExpansionPatternType(CanType type) {
return cast<PackExpansionType>(type).getPatternType();
}
AbstractionPattern AbstractionPattern::getPackExpansionPatternType() const {
switch (getKind()) {
case Kind::Invalid:
llvm_unreachable("querying invalid abstraction pattern!");
case Kind::ObjCMethodType:
case Kind::CurriedObjCMethodType:
case Kind::PartialCurriedObjCMethodType:
case Kind::CFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::Tuple:
case Kind::OpaqueFunction:
case Kind::OpaqueDerivativeFunction:
case Kind::ObjCCompletionHandlerArgumentsType:
case Kind::ClangType:
llvm_unreachable("pattern for function or tuple cannot be for "
"pack expansion type");
case Kind::Opaque:
return *this;
case Kind::Type:
if (isTypeParameterOrOpaqueArchetype())
return AbstractionPattern::getOpaque();
return AbstractionPattern(getGenericSubstitutions(),
getGenericSignature(),
::getPackExpansionPatternType(getType()));
case Kind::Discard:
return AbstractionPattern::getDiscard(
getGenericSubstitutions(), getGenericSignature(),
::getPackExpansionPatternType(getType()));
}
llvm_unreachable("bad kind");
}
static CanType getPackExpansionCountType(CanType type) {
return cast<PackExpansionType>(type).getCountType();
}
AbstractionPattern AbstractionPattern::getPackExpansionCountType() const {
switch (getKind()) {
case Kind::Invalid:
llvm_unreachable("querying invalid abstraction pattern!");
case Kind::ObjCMethodType:
case Kind::CurriedObjCMethodType:
case Kind::PartialCurriedObjCMethodType:
case Kind::CFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::Tuple:
case Kind::OpaqueFunction:
case Kind::OpaqueDerivativeFunction:
case Kind::ObjCCompletionHandlerArgumentsType:
case Kind::ClangType:
llvm_unreachable("pattern for function or tuple cannot be for "
"pack expansion type");
case Kind::Opaque:
return *this;
case Kind::Type:
if (isTypeParameterOrOpaqueArchetype())
return AbstractionPattern::getOpaque();
return AbstractionPattern(getGenericSubstitutions(),
getGenericSignature(),
::getPackExpansionCountType(getType()));
case Kind::Discard:
return AbstractionPattern::getDiscard(
getGenericSubstitutions(), getGenericSignature(),
::getPackExpansionCountType(getType()));
}
llvm_unreachable("bad kind");
}
size_t AbstractionPattern::getNumPackExpandedComponents() const {
assert(isPackExpansion());
assert(getKind() == Kind::Type || getKind() == Kind::Discard);
// If we don't have substitutions, we should be walking parallel
// structure; take a single element.
if (!GenericSubs) return 1;
// Otherwise, substitute the expansion shape.
auto origExpansion = cast<PackExpansionType>(getType());
auto substShape = cast<PackType>(
origExpansion.getCountType().subst(GenericSubs)->getCanonicalType());
return substShape->getNumElements();
}
AbstractionPattern AbstractionPattern::getMetatypeInstanceType() const {
assert(getKind() == Kind::Type);