-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenPattern.cpp
1879 lines (1603 loc) · 65.6 KB
/
SILGenPattern.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
//===--- SILGenPattern.cpp - Pattern matching codegen ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "switch-silgen"
#include "SILGen.h"
#include "Scope.h"
#include "Cleanup.h"
#include "Initialization.h"
#include "RValue.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Types.h"
#include "swift/Basic/STLExtras.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/TypeLowering.h"
using namespace swift;
using namespace Lowering;
/// Shallow-dump a pattern node one level deep for debug purposes.
static void dumpPattern(const Pattern *p, llvm::raw_ostream &os) {
if (!p) {
// We use null to represent a synthetic wildcard.
os << '_';
return;
}
p = p->getSemanticsProvidingPattern();
switch (p->getKind()) {
case PatternKind::Any:
os << '_';
return;
case PatternKind::Expr:
os << "<expr>";
return;
case PatternKind::Named:
os << "var " << cast<NamedPattern>(p)->getBoundName();
return;
case PatternKind::Tuple: {
unsigned numFields = cast<TuplePattern>(p)->getNumFields();
if (numFields == 0)
os << "()";
else if (numFields == 1)
os << "(_)";
else {
os << '(';
for (unsigned i = 0; i < numFields - 1; ++i)
os << ',';
os << ')';
}
return;
}
case PatternKind::Isa:
os << "is ";
cast<IsaPattern>(p)->getCastTypeLoc().getType()->print(os);
break;
case PatternKind::NominalType: {
auto np = cast<NominalTypePattern>(p);
np->getType()->print(os);
os << '(';
interleave(np->getElements(),
[&](const NominalTypePattern::Element &elt) {
os << elt.getProperty()->getName() << ":";
},
[&]{ os << ", "; });
os << ')';
return;
}
case PatternKind::EnumElement: {
auto eep = cast<EnumElementPattern>(p);
os << '.' << eep->getName();
return;
}
case PatternKind::Paren:
case PatternKind::Typed:
case PatternKind::Var:
llvm_unreachable("not semantic");
}
}
static void dumpDepth(unsigned depth, llvm::raw_ostream &os) {
for (unsigned d = 0; d < depth; ++d)
os << "| ";
}
/// True if a pattern is a wildcard, meaning it matches any value. '_' and
/// variable patterns are wildcards. We also consider ExprPatterns to be
/// wildcards; we test the match expression as a guard outside of the normal
/// pattern clause matrix. When destructuring wildcard patterns, we also use
/// nullptr to represent newly-constructed wildcards.
static bool isWildcardPattern(const Pattern *p) {
if (!p)
return true;
switch (p->getKind()) {
// Simple wildcards.
case PatternKind::Any:
case PatternKind::Expr:
case PatternKind::Named:
return true;
// Non-wildcards.
case PatternKind::Tuple:
case PatternKind::Isa:
case PatternKind::NominalType:
case PatternKind::EnumElement:
return false;
// Recur into simple wrapping patterns.
case PatternKind::Paren:
case PatternKind::Typed:
case PatternKind::Var:
return isWildcardPattern(p->getSemanticsProvidingPattern());
}
}
/// True if a pattern is a simple variable binding.
static bool isBindingPattern(const Pattern *p) {
return p && isa<NamedPattern>(p->getSemanticsProvidingPattern());
}
namespace {
/// A pair representing a specialization of a clause matrix.
struct SpecializingPattern {
/// The pattern node representing the specialization.
const Pattern *pattern;
/// The number of rows to skip in the specialization.
unsigned row;
};
/// Typedef for the vector of basic blocks and destructured values produced by
/// emitDispatchAndDestructure.
using DispatchedPatternVector
= std::vector<std::pair<SILBasicBlock*, std::vector<SILValue>>>;
}
/// Emit a conditional branch testing if a value matches one of the given
/// pattern nodes.
/// In the case branch for each pattern, destructure the value.
/// On return, the insertion point is cleared.
/// The parts of the value used for dispatch are conceptually consumed, that is,
/// it should be correct to destroy only the destructured values on each branch
/// in order to completely destroy the original subject value.
///
/// \returns null if the set of pattern nodes match every possible value of the
/// type, or else the "default" basic block for the dispatch that will be
/// branched to if no patterns match.
static SILBasicBlock *emitDispatchAndDestructure(SILGenFunction &gen,
ArrayRef<SpecializingPattern> patterns,
SILValue v,
DispatchedPatternVector &dispatches,
SwitchStmt *stmt) {
assert(!patterns.empty() && "no patterns to dispatch on?!");
const Pattern *headPattern = patterns[0].pattern;
PatternKind kind = headPattern->getKind();
CanType type = headPattern->getType()->getCanonicalType();
switch (kind) {
case PatternKind::Any:
case PatternKind::Named:
case PatternKind::Expr:
llvm_unreachable("wildcards shouldn't get here");
case PatternKind::Tuple: {
// Tuples are irrefutable; destructure without branching.
assert(patterns.size() == 1 && "pattern orthogonal to tuple?!");
auto *tp = cast<TuplePattern>(headPattern);
RegularLocation Loc(const_cast<TuplePattern*>(tp));
std::vector<SILValue> destructured;
auto tupleTy = tp->getType()->castTo<TupleType>();
auto tupleSILTy = gen.getLoweredType(tupleTy);
if (tupleSILTy.isAddressOnly(gen.F.getModule())) {
for (unsigned i = 0, e = tupleTy->getFields().size(); i < e; ++i) {
SILType fieldTy = gen.getLoweredType(tupleTy->getElementType(i));
SILValue member = gen.B.createTupleElementAddr(Loc,
v, i, fieldTy.getAddressType());
if (!fieldTy.isAddressOnly(gen.F.getModule()))
member = gen.B.createLoad(Loc, member);
destructured.push_back(member);
}
} else {
for (unsigned i = 0, e = tupleTy->getFields().size(); i < e; ++i) {
auto fieldType = tupleTy->getElementType(i);
SILType fieldTy = gen.getLoweredLoadableType(fieldType);
SILValue member = gen.B.createTupleExtract(Loc, v, i, fieldTy);
destructured.push_back(member);
}
}
dispatches.emplace_back(gen.B.getInsertionBB(), std::move(destructured));
gen.B.clearInsertionPoint();
return nullptr;
}
case PatternKind::Isa: {
auto &origTL = gen.getTypeLowering(headPattern->getType());
auto castTLs
= map<SmallVector<const TypeLowering *,4>>(patterns,
[&](const SpecializingPattern &p) {
return &gen.getTypeLowering(
cast<IsaPattern>(p.pattern)->getCastTypeLoc().getType());
});
/// Emit an abstraction change if any of the casts will require it.
SILValue vAbstract
= gen.emitCheckedCastAbstractionChange(const_cast<Pattern*>(headPattern),
v, origTL, castTLs);
/// Emit all of the 'is' checks.
unsigned i = 0;
for (SpecializingPattern p : patterns) {
auto *ip = cast<IsaPattern>(p.pattern);
RegularLocation Loc(const_cast<IsaPattern*>(ip));
std::vector<SILValue> destructured;
// Perform a conditional cast branch.
SILBasicBlock *trueBB, *falseBB;
std::tie(trueBB, falseBB) = gen.emitCheckedCastBranch(Loc,
v, vAbstract,
origTL, *castTLs[i],
ip->getCastKind());
// On the true branch, we can get the cast value from the BB argument.
SILValue cast = trueBB->bbarg_begin()[0];
// If the cast result is loadable and we cast a value address, load it.
if (cast.getType().isAddress()
&& !cast.getType().isAddressOnly(gen.F.getModule())) {
gen.B.setInsertionPoint(trueBB);
cast = gen.B.createLoad(Loc, cast);
gen.B.clearInsertionPoint();
}
destructured.push_back(cast);
// FIXME: If we cast from an opaque existential, we'll continue using its
// contained value, but we need to deallocate the existential husk.
// Code matching the pattern goes into the "true" block.
dispatches.emplace_back(trueBB, std::move(destructured));
// Dispatch continues on the "false" block.
gen.B.emitBlock(falseBB);
++i;
}
// The current block is now the "default" block.
// Clean up the re-abstracted value, if any; we don't need it anymore.
if (vAbstract) {
// FIXME: different kinds of abstraction change in the future?
auto alloc = cast<AllocStackInst>(vAbstract);
gen.B.createDeallocStack(const_cast<Pattern*>(headPattern),
alloc->getContainerResult());
}
SILBasicBlock *defaultBB = gen.B.getInsertionBB();
gen.B.clearInsertionPoint();
return defaultBB;
}
case PatternKind::EnumElement: {
/// We'll want to know if we matched every case of the enum to see if we
/// need a default block.
///
/// FIXME: If the enum is resilient, then we always need a default block.
llvm::DenseSet<EnumElementDecl*> unmatchedCases;
type->getEnumOrBoundGenericEnum()->getAllElements(unmatchedCases);
SmallVector<std::pair<EnumElementDecl*, SILBasicBlock*>, 4> caseBBs;
bool addressOnlyEnum = v.getType().isAddress();
SILValue voidValue;
SILBasicBlock *bb = gen.B.getInsertionBB();
for (SpecializingPattern p : patterns) {
auto *up = cast<EnumElementPattern>(p.pattern);
RegularLocation Loc(const_cast<EnumElementPattern*>(up));
EnumElementDecl *elt = up->getElementDecl();
assert(unmatchedCases.count(elt)
&& "specializing same enum case twice?!");
unmatchedCases.erase(elt);
SILBasicBlock *caseBB = gen.createBasicBlock();
// Create a BB argument or 'take_enum_data_addr' instruction to receive
// the enum case data if it has any.
SILValue eltValue;
if (elt->hasArgumentType()) {
auto argTy = v.getType().getEnumElementType(elt, gen.SGM.M);
if (!argTy.getSwiftRValueType()->isVoid()) {
gen.B.setInsertionPoint(caseBB);
auto &argLowering = gen.getTypeLowering(argTy);
if (addressOnlyEnum) {
argTy = argTy.getAddressType();
eltValue = gen.B.createTakeEnumDataAddr(Loc, v, elt, argTy);
// Load a loadable data value.
if (argLowering.isLoadable())
eltValue = gen.B.createLoad(Loc, eltValue);
} else {
eltValue = new (gen.F.getModule()) SILArgument(argTy, caseBB);
}
// Reabstract to the substituted type, if needed.
auto substArgTy = v.getType().getSwiftRValueType()
->getTypeOfMember(gen.SGM.M.getSwiftModule(),
elt, nullptr, elt->getArgumentType())
->getCanonicalType();
auto substTy = gen.getLoweredType(substArgTy);
if (substTy != argTy) {
FullExpr reabstractScope(gen.Cleanups,
const_cast<Pattern*>(headPattern));
AbstractionPattern origArgPattern(elt->getArgumentType());
auto origMV
= gen.emitManagedRValueWithCleanup(eltValue);
auto substMV
= gen.emitOrigToSubstValue(const_cast<Pattern*>(headPattern),
origMV, origArgPattern, substArgTy);
eltValue = substMV.forward(gen);
}
gen.B.setInsertionPoint(bb);
}
} else {
// If the element pattern for a void enum element has a subpattern, it
// will bind to a void value.
if (!voidValue)
voidValue = gen.emitEmptyTuple(Loc);
eltValue = voidValue;
}
caseBBs.push_back({elt, caseBB});
dispatches.emplace_back(caseBB, std::vector<SILValue>(1, eltValue));
}
SILBasicBlock *defaultBB = nullptr;
// If we didn't cover every case, then we need a default block.
if (!unmatchedCases.empty())
defaultBB = gen.createBasicBlock();
// Emit the switch instruction.
if (addressOnlyEnum) {
gen.B.createSwitchEnumAddr(stmt, v,
defaultBB, caseBBs);
} else {
gen.B.createSwitchEnum(stmt, v, defaultBB, caseBBs);
}
// Return the default BB.
return defaultBB;
}
case PatternKind::NominalType: {
// Nominal type patterns are irrefutable; destructure without branching.
auto *np = cast<NominalTypePattern>(headPattern);
RegularLocation loc(const_cast<NominalTypePattern*>(np));
// Copy out the needed property values.
std::vector<SILValue> destructured;
for (auto &elt : np->getElements()) {
ManagedValue MV = ManagedValue::forUnmanaged(v);
auto Val = gen.emitRValueForPropertyLoad(loc, MV, false, elt.getProperty(),
// FIXME: No generic substitions.
{}, false,
elt.getSubPattern()->getType(),
// TODO: Avoid copies on
// address-only types.
SGFContext());
destructured.push_back(Val.forward(gen));
}
// Carry the aggregate forward. It may be needed to match against other
// pattern kinds.
destructured.push_back(v);
dispatches.emplace_back(gen.B.getInsertionBB(), std::move(destructured));
gen.B.clearInsertionPoint();
return nullptr;
}
case PatternKind::Paren:
case PatternKind::Typed:
case PatternKind::Var:
llvm_unreachable("pattern node is never semantic");
}
}
/// Destructure a pattern parallel to the specializing pattern of a clause
/// matrix.
/// Destructured wildcards are represented with null Pattern* pointers.
/// p must be non-orthogonal to this pattern constructor.
static void destructurePattern(SILGenFunction &gen,
const Pattern *specializer,
const Pattern *p,
SmallVectorImpl<const Pattern *> &destructured) {
specializer = specializer->getSemanticsProvidingPattern();
assert(p && !isWildcardPattern(p) &&
"wildcard patterns shouldn't be passed here");
p = p->getSemanticsProvidingPattern();
switch (specializer->getKind()) {
case PatternKind::Any:
case PatternKind::Named:
case PatternKind::Expr:
llvm_unreachable("shouldn't specialize on a wildcard pattern");
case PatternKind::Tuple: {
auto specializerTuple = cast<TuplePattern>(specializer);
// Tuples should only match with other tuple patterns. Destructure into
// the tuple fields.
auto tp = cast<TuplePattern>(p);
assert(specializerTuple->getFields().size() == tp->getFields().size()
&& "tuple patterns do not share shape");
(void) specializerTuple;
std::transform(tp->getFields().begin(), tp->getFields().end(),
std::back_inserter(destructured),
[&](const TuplePatternElt &e) -> const Pattern * {
return e.getPattern();
});
return;
}
case PatternKind::Isa: {
auto *specializerIsa = cast<IsaPattern>(specializer);
auto *ip = cast<IsaPattern>(p);
CanType newFromType
= specializerIsa->getCastTypeLoc().getType()->getCanonicalType();
CanType newToType = ip->getCastTypeLoc().getType()->getCanonicalType();
// If a cast pattern casts to the same type, it reduces to its subpattern.
if (newFromType == newToType) {
destructured.push_back(ip->getSubPattern());
return;
}
// If the cast pattern casts to a superclass, it reduces to its subpattern.
if (newToType->isSuperclassOf(newFromType, nullptr)) {
destructured.push_back(ip->getSubPattern());
return;
}
// If a cast pattern is non-orthogonal and not to the same type, then
// we have a cast to a superclass, subclass, or archetype. Produce a
// new checked cast pattern from the destructured type.
CheckedCastKind newKind;
// Determine the new cast kind.
bool fromArchetype = isa<ArchetypeType>(newFromType),
toArchetype = isa<ArchetypeType>(newToType);
if (fromArchetype && toArchetype) {
newKind = CheckedCastKind::ArchetypeToArchetype;
} else if (fromArchetype) {
newKind = CheckedCastKind::ArchetypeToConcrete;
} else if (toArchetype) {
if (newFromType->isExistentialType()) {
newKind = CheckedCastKind::ExistentialToArchetype;
} else if (newFromType->isSuperclassOf(newToType, nullptr)) {
newKind = CheckedCastKind::SuperToArchetype;
} else {
newKind = CheckedCastKind::ConcreteToArchetype;
}
} else {
// We have a class-to-class downcast.
assert(newFromType.getClassOrBoundGenericClass() &&
newToType.getClassOrBoundGenericClass() &&
"non-class, non-archetype cast patterns should be orthogonal!");
newKind = CheckedCastKind::Downcast;
}
// Create the new cast pattern.
auto *newIsa
= new (gen.F.getASTContext()) IsaPattern(p->getLoc(),
ip->getCastTypeLoc(),
const_cast<Pattern*>(ip->getSubPattern()),
newKind);
newIsa->setType(newFromType);
destructured.push_back(newIsa);
return;
}
case PatternKind::EnumElement: {
auto *up = cast<EnumElementPattern>(p);
// If the enum case has a value, but the pattern does not specify a
// subpattern, then treat it like a wildcard.
if (!up->hasSubPattern())
destructured.push_back(nullptr);
else
destructured.push_back(up->getSubPattern());
return;
}
case PatternKind::NominalType: {
auto *specializerNP = cast<NominalTypePattern>(specializer);
// If we're specializing another nominal type pattern, break out
// its subpatterns.
if (auto *np = dyn_cast<NominalTypePattern>(p)) {
assert(np->getType()->isEqual(specializerNP->getType()));
// Extract the property subpatterns in specializer order. If a property
// isn't mentioned in the specializee, it's a wildcard.
size_t base = destructured.size();
// Extend the destructured vector with all wildcards.
// The +1 is for the full aggregate itself, which we don't need to
// match.
destructured.append(specializerNP->getElements().size() + 1, nullptr);
// Figure out the offsets for all the fields from the specializer.
llvm::DenseMap<VarDecl*, size_t> offsets;
size_t i = base;
for (auto &specElt : specializerNP->getElements()) {
offsets.insert({specElt.getProperty(), i});
++i;
}
// Drop in the subpatterns from the specializee.
for (auto &elt : np->getElements()) {
assert(offsets.count(elt.getProperty()));
destructured[offsets[elt.getProperty()]] = elt.getSubPattern();
}
return;
}
// For any other kind of pattern, match it against the original aggregate,
// which is placed after all of the extracted properties of the specializer.
destructured.append(specializerNP->getElements().size(), nullptr);
destructured.push_back(p);
return;
}
case PatternKind::Paren:
case PatternKind::Typed:
case PatternKind::Var:
llvm_unreachable("not semantic");
}
}
/// True if the 'sub' pattern node is subsumed by the 'super' node, that is,
/// all values 'sub' matches are also matched by 'super'.
bool isPatternSubsumed(const Pattern *sub, const Pattern *super) {
// Wildcards subsume everything.
if (!super) return true;
if (isWildcardPattern(super)) return true;
sub = sub->getSemanticsProvidingPattern();
super = super->getSemanticsProvidingPattern();
// A pattern always subsumes itself.
if (sub == super) return true;
switch (super->getKind()) {
case PatternKind::Any:
case PatternKind::Named:
case PatternKind::Expr:
// If super wasn't already handled as a wildcard above, then it can't
// subsume a wildcard.
return false;
case PatternKind::Tuple: {
// Tuples should only match wildcard or same-shaped tuple patterns, which
// are exhaustive so always subsume other tuple patterns of the same type.
auto *tsub = cast<TuplePattern>(sub);
// Wildcard 'super' should have been handled above.
auto *tsup = cast<TuplePattern>(super);
assert(tsub->getType()->isEqual(tsup->getType()) &&
"tuple patterns should match same type");
assert(tsub->getFields().size() == tsup->getFields().size() &&
"tuple patterns should have same shape");
(void)tsub;
(void)tsup;
return true;
}
case PatternKind::Isa: {
auto *isup = cast<IsaPattern>(super);
auto *isub = dyn_cast<IsaPattern>(sub);
// If the "sub" pattern isn't another cast, we can't subsume it.
if (!isub)
return false;
Type subTy = isub->getCastTypeLoc().getType();
Type supTy = isup->getCastTypeLoc().getType();
// Casts to the same type subsume each other.
if (subTy->isEqual(supTy))
return true;
// Superclass casts subsume casts to subclasses or archetypes bounded by the
// superclass.
if (supTy->isSuperclassOf(subTy, nullptr))
return true;
return false;
}
case PatternKind::EnumElement: {
auto *usub = cast<EnumElementPattern>(sub);
// Wildcard 'super' should have been handled above.
auto *usup = cast<EnumElementPattern>(super);
// EnumElements are subsumed by equivalent EnumElements.
return usub->getElementDecl() == usup->getElementDecl();
}
case PatternKind::NominalType: {
// A NominalType pattern subsumes any other pattern matching the same type.
assert(sub->getType()->getCanonicalType()
== super->getType()->getCanonicalType() &&
"nominal type patterns should match same type");
return true;
}
case PatternKind::Paren:
case PatternKind::Typed:
case PatternKind::Var:
llvm_unreachable("not semantic");
}
}
/// Remove patterns in the given range that are subsumed by the given
/// specializing pattern, returning a combined pattern that covers all of them.
/// In most cases, the returned pattern is the same as the specializing pattern,
/// but e.g. nominal type patterns can be combined to match all properties
/// needed by the set of patterns.
static const Pattern *combineAndFilterSubsumedPatterns(
SmallVectorImpl<SpecializingPattern> &patterns,
unsigned beginIndex, unsigned endIndex,
ASTContext &C) {
// For nominal type patterns, we want to combine all the following subsumed
// nominal type patterns into one pattern with all of the necessary properties
// to match all of the patterns together.
auto begin = patterns.begin()+beginIndex, end = patterns.begin()+endIndex;
auto foundSpec = std::find_if(begin, end,
[](SpecializingPattern p) { return isa<NominalTypePattern>(p.pattern); });
if (foundSpec != end) {
auto specNP = cast<NominalTypePattern>(foundSpec->pattern);
llvm::MapVector<VarDecl *, NominalTypePattern::Element> neededProperties;
for (auto &elt : specNP->getElements()) {
neededProperties.insert({elt.getProperty(), elt});
}
// An existing pattern with all of the needed properties, if any.
const NominalTypePattern *superPattern = specNP;
for (auto &sub : make_range(foundSpec + 1,
end)) {
if (auto *subNP = dyn_cast<NominalTypePattern>(sub.pattern)) {
// Count whether this pattern matches all the needed properties.
unsigned propCount = neededProperties.size();
for (auto &elt : subNP->getElements()) {
if (neededProperties.count(elt.getProperty())) {
--propCount;
} else {
// This patterns adds a property. Invalidate superPattern.
neededProperties.insert({elt.getProperty(), elt});
superPattern = nullptr;
}
}
// Use this pattern as the new super-pattern if it has all the needed
// properties.
if (!superPattern && propCount == 0)
superPattern = subNP;
}
}
// If we didn't find an existing "super" pattern, we have to make one.
if (!superPattern) {
SmallVector<NominalTypePattern::Element, 4> superElts;
for (auto &prop : neededProperties)
superElts.push_back(prop.second);
auto newPat = NominalTypePattern::create(specNP->getCastTypeLoc(),
specNP->getLParenLoc(),
superElts,
specNP->getRParenLoc(), C);
newPat->setType(specNP->getType());
superPattern = newPat;
}
// Check that the superPattern is as super as we need it to be.
assert([&]{
for (auto prop : neededProperties) {
for (auto &elt : superPattern->getElements())
if (elt.getProperty() == prop.first)
goto next;
return false;
next:;
}
return true;
}() && "missing properties from subsuming nominal type pattern");
// Subsume all of the patterns.
patterns.erase(begin+1, end);
return superPattern;
}
// Otherwise, specialize on the first pattern.
// NB: Removes elements from 'patterns' mid-loop.
const Pattern *specializer = patterns[beginIndex].pattern;
for (unsigned i = beginIndex+1; i < endIndex; ++i) {
while (isPatternSubsumed(patterns[i].pattern, specializer)) {
patterns.erase(patterns.begin() + i);
--endIndex;
if (i >= endIndex)
break;
}
}
return specializer;
}
/// True if two pattern nodes are orthogonal, that is, they never both match
/// the same value.
static bool arePatternsOrthogonal(const Pattern *a, const Pattern *b) {
// Wildcards are never orthogonal.
if (!a) return false;
if (!b) return false;
if (isWildcardPattern(b)) return false;
a = a->getSemanticsProvidingPattern();
b = b->getSemanticsProvidingPattern();
// A pattern is never orthogonal to itself.
if (a == b) return false;
switch (a->getKind()) {
case PatternKind::Any:
case PatternKind::Named:
case PatternKind::Expr:
return false;
case PatternKind::Tuple: {
// Tuples should only match wildcard or same-shaped tuple patterns, to
// which they are never orthogonal.
auto *ta = cast<TuplePattern>(a);
auto *tb = cast<TuplePattern>(b);
assert(ta->getType()->isEqual(tb->getType()) &&
"tuple patterns should match same type");
assert(ta->getFields().size() == tb->getFields().size() &&
"tuple patterns should have same shape");
(void)ta;
(void)tb;
return false;
}
case PatternKind::Isa: {
auto *ia = cast<IsaPattern>(a);
// 'is' is never orthogonal to a nominal type pattern.
if (isa<NominalTypePattern>(b))
return false;
auto *ib = cast<IsaPattern>(b);
if (!ib)
return true;
// Casts to the same type are parallel.
Type aTy = ia->getCastTypeLoc().getType();
Type bTy = ib->getCastTypeLoc().getType();
if (aTy->isEqual(bTy))
return false;
ArchetypeType *aArchety = aTy->getAs<ArchetypeType>();
ArchetypeType *bArchety = bTy->getAs<ArchetypeType>();
if (aArchety && bArchety) {
// Two archetypes are only conclusively orthogonal if they have unrelated
// superclass constraints.
if (aArchety->getSuperclass() && bArchety->getSuperclass())
return !aArchety->getSuperclass()->isSuperclassOf(bArchety->getSuperclass(),
nullptr)
&& !bArchety->getSuperclass()->isSuperclassOf(bArchety->getSuperclass(),
nullptr);
return false;
}
// An archetype cast is orthogonal if it's class-constrained and the other
// type is not a class or a class unrelated to its superclass constraint.
auto isOrthogonalToArchetype = [&](ArchetypeType *arch, Type ty) -> bool {
if (arch->requiresClass()) {
if (!ty->getClassOrBoundGenericClass())
return true;
if (Type sup = arch->getSuperclass())
return !sup->isSuperclassOf(ty, nullptr);
}
return false;
};
if (aArchety)
return isOrthogonalToArchetype(aArchety, bTy);
if (bArchety)
return isOrthogonalToArchetype(bArchety, aTy);
// Class casts are orthogonal to non-class casts.
bool aClass = aTy->getClassOrBoundGenericClass();
bool bClass = bTy->getClassOrBoundGenericClass();
if (!aClass || !bClass)
return true;
// Class casts are orthogonal to casts to a class without a subtype or
// supertype relationship.
return !aTy->isSuperclassOf(bTy, nullptr)
&& !bTy->isSuperclassOf(aTy, nullptr);
}
case PatternKind::EnumElement: {
auto *ua = cast<EnumElementPattern>(a);
auto *ub = cast<EnumElementPattern>(b);
return ua->getElementDecl() != ub->getElementDecl();
}
case PatternKind::NominalType: {
// Nominal types match all values of their type, so are never orthogonal.
return false;
}
case PatternKind::Paren:
case PatternKind::Typed:
case PatternKind::Var:
llvm_unreachable("not semantic");
}
}
namespace {
/// A CaseMap entry.
struct CaseBlock {
/// The entry BB for the case.
SILBasicBlock *entry = nullptr;
/// The continuation BB for the case.
SILBasicBlock *cont = nullptr;
/// The scope of the case.
CleanupsDepth cleanupsDepth = CleanupsDepth::invalid();
};
/// Map type used to associate CaseStmts to SILBasicBlocks. Filled in as
/// dispatch is resolved.
using CaseMap = llvm::MapVector<CaseStmt*, CaseBlock>;
/// Create the entry point BB for a case block, if necessary, and add it to the
/// CaseMap. Returns the entry point BB emitted for the block.
SILBasicBlock *createCaseBlock(SILGenFunction &gen, CaseMap &caseMap,
CaseStmt *caseBlock,
CleanupsDepth cleanupsDepth,
SILBasicBlock *contBB) {
CaseBlock &dest = caseMap[caseBlock];
// If the block was emitted, sanity check that it was emitted at the same
// scope level we think it should be.
if (dest.entry) {
assert(cleanupsDepth == dest.cleanupsDepth
&& "divergent cleanup depths for case");
assert(contBB == dest.cont
&& "divergent continuation BBs for case");
return dest.entry;
}
// Set up the basic block for the case.
dest.entry = gen.createBasicBlock();
dest.cleanupsDepth = cleanupsDepth;
dest.cont = contBB;
return dest.entry;
}
/// A handle to a row in a clause matrix. Does not own memory; use of the
/// ClauseRow must be dominated by its originating ClauseMatrix.
class ClauseRow {
friend class ClauseMatrix;
/// The in-memory layout of a clause row prefix.
struct Prefix {
/// The CaseStmt corresponding to the patterns in the row.
CaseStmt *caseBlock;
/// The guard expression for the row, or null if there is no guard.
Expr *guardExpr;
/// The cleanup level of the case body.
CleanupsDepth cleanupsDepth;
/// The continuation BB for this case.
SILBasicBlock *cont;
/// The ExprPatterns within the pattern and their matching values.
unsigned firstExprGuard, lastExprGuard;
};
Prefix *row;
unsigned columnCount;
ArrayRef<const ExprPattern*> exprGuards;
// ClauseRows should only be vended by ClauseMatrix::operator[].
ClauseRow(Prefix *row, unsigned columnCount,
ArrayRef<const ExprPattern*> guards)
: row(row), columnCount(columnCount), exprGuards(guards)
{}
public:
ClauseRow() = default;
CaseStmt *getCaseBlock() const {
return row->caseBlock;
}
Expr *getGuard() const {
return row->guardExpr;
}
bool hasGuard() const {
return row->guardExpr;
}
CleanupsDepth getCleanupsDepth() const {
return row->cleanupsDepth;
}
void setCleanupsDepth(CleanupsDepth d) {
row->cleanupsDepth = d;
}
SILBasicBlock *getContBB() const {
return row->cont;
}
ArrayRef<const ExprPattern*> getExprGuards() const {
return exprGuards;
}
/// Create the case block corresponding to this row if necessary. Returns the
/// entry point BB emitted for the block.
SILBasicBlock *createCaseBlock(SILGenFunction &gen, CaseMap &caseMap) const {
return ::createCaseBlock(gen, caseMap,
getCaseBlock(), getCleanupsDepth(), getContBB());
}
ArrayRef<const Pattern *> getColumns() const {
return {reinterpret_cast<const Pattern * const*>(row + 1), columnCount};
}
MutableArrayRef<const Pattern *> getColumns() {
return {reinterpret_cast<const Pattern **>(row + 1), columnCount};
}
const Pattern * const *begin() const {
return getColumns().begin();
}
const Pattern * const *end() const {
return getColumns().end();
}
const Pattern **begin() {
return getColumns().begin();
}
const Pattern **end() {
return getColumns().end();
}
const Pattern *operator[](unsigned column) const {
return getColumns()[column];
}
const Pattern *&operator[](unsigned column) {
return getColumns()[column];
}
unsigned columns() const {
return columnCount;
}
};
/// Get a pattern as an ExprPattern, unwrapping semantically transparent
/// pattern nodes.
static const ExprPattern *getAsExprPattern(const Pattern *p) {
if (!p) return nullptr;