forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SILGenApply.cpp
4809 lines (4117 loc) · 184 KB
/
SILGenApply.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
//===--- SILGenApply.cpp - Constructs call sites for SILGen ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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
//
//===----------------------------------------------------------------------===//
#include "ArgumentSource.h"
#include "LValue.h"
#include "RValue.h"
#include "Scope.h"
#include "Initialization.h"
#include "SpecializedEmitter.h"
#include "Varargs.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/Module.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/Basic/Range.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/PrettyStackTrace.h"
using namespace swift;
using namespace Lowering;
/// Retrieve the type to use for a method found via dynamic lookup.
static CanAnyFunctionType getDynamicMethodFormalType(SILGenModule &SGM,
SILValue proto,
ValueDecl *member,
SILDeclRef methodName,
Type memberType) {
auto &ctx = SGM.getASTContext();
CanType selfTy;
if (member->isInstanceMember()) {
selfTy = ctx.TheUnknownObjectType;
} else {
selfTy = proto->getType().getSwiftType();
}
auto extInfo = FunctionType::ExtInfo()
.withRepresentation(FunctionType::Representation::Thin);
return CanFunctionType::get(selfTy, memberType->getCanonicalType(),
extInfo);
}
/// Replace the 'self' parameter in the given type.
static CanSILFunctionType
replaceSelfTypeForDynamicLookup(ASTContext &ctx,
CanSILFunctionType fnType,
CanType newSelfType,
SILDeclRef methodName) {
auto oldParams = fnType->getParameters();
SmallVector<SILParameterInfo, 4> newParams;
newParams.append(oldParams.begin(), oldParams.end() - 1);
newParams.push_back({newSelfType, oldParams.back().getConvention()});
// If the method returns Self, substitute AnyObject for the result type.
SmallVector<SILResultInfo, 4> newResults;
newResults.append(fnType->getAllResults().begin(),
fnType->getAllResults().end());
if (auto fnDecl = dyn_cast<FuncDecl>(methodName.getDecl())) {
if (fnDecl->hasDynamicSelf()) {
auto anyObjectTy = ctx.getProtocol(KnownProtocolKind::AnyObject)
->getDeclaredType();
for (auto &result : newResults) {
auto newResultTy
= result.getType()->replaceCovariantResultType(anyObjectTy, 0);
result = result.getWithType(newResultTy->getCanonicalType());
}
}
}
return SILFunctionType::get(nullptr,
fnType->getExtInfo(),
fnType->getCalleeConvention(),
newParams,
newResults,
fnType->getOptionalErrorResult(),
ctx);
}
static Type getExistentialArchetype(SILValue existential) {
CanType ty = existential->getType().getSwiftRValueType();
if (ty->is<ArchetypeType>())
return ty;
return cast<ProtocolType>(ty)->getDecl()->getProtocolSelf()->getArchetype();
}
/// Retrieve the type to use for a method found via dynamic lookup.
static CanSILFunctionType getDynamicMethodLoweredType(SILGenFunction &gen,
SILValue proto,
SILDeclRef methodName) {
auto &ctx = gen.getASTContext();
// Determine the opaque 'self' parameter type.
CanType selfTy;
if (methodName.getDecl()->isInstanceMember()) {
selfTy = getExistentialArchetype(proto)->getCanonicalType();
} else {
selfTy = proto->getType().getSwiftType();
}
// Replace the 'self' parameter type in the method type with it.
auto methodTy = gen.SGM.getConstantType(methodName).castTo<SILFunctionType>();
return replaceSelfTypeForDynamicLookup(ctx, methodTy, selfTy, methodName);
}
static bool canUseStaticDispatch(SILGenFunction &gen,
SILDeclRef constant) {
auto *funcDecl = cast<AbstractFunctionDecl>(constant.getDecl());
auto thisModule = gen.SGM.M.getSwiftModule();
return funcDecl->isFinal() || (thisModule == funcDecl->getModuleContext());
}
namespace {
/// Abstractly represents a callee, which may be a constant or function value,
/// and knows how to perform dynamic dispatch and reference the appropriate
/// entry point at any valid uncurry level.
class Callee {
public:
enum class Kind {
/// An indirect function value.
IndirectValue,
/// A direct standalone function call, referenceable by a FunctionRefInst.
StandaloneFunction,
/// Enum case constructor call.
EnumElement,
VirtualMethod_First,
/// A method call using class method dispatch.
ClassMethod = VirtualMethod_First,
/// A method call using super method dispatch.
SuperMethod,
VirtualMethod_Last = SuperMethod,
GenericMethod_First,
/// A method call using archetype dispatch.
WitnessMethod = GenericMethod_First,
/// A method call using dynamic lookup.
DynamicMethod,
GenericMethod_Last = DynamicMethod
};
const Kind kind;
// Move, don't copy.
Callee(const Callee &) = delete;
Callee &operator=(const Callee &) = delete;
private:
union {
ManagedValue IndirectValue;
SILDeclRef Constant;
};
SILValue SelfValue;
ArrayRef<Substitution> Substitutions;
CanType OrigFormalInterfaceType;
CanAnyFunctionType SubstFormalType;
Optional<SILLocation> SpecializeLoc;
bool HasSubstitutions = false;
Optional<SmallVector<ManagedValue, 2>> Captures;
// The pointer back to the AST node that produced the callee.
SILLocation Loc;
private:
Callee(ManagedValue indirectValue,
CanType origFormalType,
CanAnyFunctionType substFormalType,
SILLocation L)
: kind(Kind::IndirectValue),
IndirectValue(indirectValue),
OrigFormalInterfaceType(origFormalType),
SubstFormalType(substFormalType),
Loc(L)
{}
static CanAnyFunctionType getConstantFormalInterfaceType(SILGenFunction &gen,
SILDeclRef fn) {
return gen.SGM.Types.getConstantInfo(fn.atUncurryLevel(0))
.FormalInterfaceType;
}
Callee(SILGenFunction &gen, SILDeclRef standaloneFunction,
CanAnyFunctionType substFormalType,
SILLocation l)
: kind(Kind::StandaloneFunction), Constant(standaloneFunction),
OrigFormalInterfaceType(getConstantFormalInterfaceType(gen,
standaloneFunction)),
SubstFormalType(substFormalType),
Loc(l)
{
}
Callee(Kind methodKind,
SILGenFunction &gen,
SILValue selfValue,
SILDeclRef methodName,
CanAnyFunctionType substFormalType,
SILLocation l)
: kind(methodKind), Constant(methodName), SelfValue(selfValue),
OrigFormalInterfaceType(getConstantFormalInterfaceType(gen, methodName)),
SubstFormalType(substFormalType),
Loc(l)
{
}
/// Build a clause that looks like 'origParamType' but uses 'selfType'
/// in place of the underlying archetype.
static CanType buildSubstSelfType(CanType origParamType, CanType selfType,
ASTContext &ctx) {
assert(!isa<LValueType>(origParamType) && "Self can't be @lvalue");
if (auto lv = dyn_cast<InOutType>(origParamType)) {
selfType = buildSubstSelfType(lv.getObjectType(), selfType, ctx);
return CanInOutType::get(selfType);
}
if (auto tuple = dyn_cast<TupleType>(origParamType)) {
assert(tuple->getNumElements() == 1);
selfType = buildSubstSelfType(tuple.getElementType(0), selfType, ctx);
auto field = tuple->getElement(0).getWithType(selfType);
return CanType(TupleType::get(field, ctx));
}
assert(isa<MetatypeType>(origParamType) == isa<MetatypeType>(selfType));
assert(origParamType->getRValueInstanceType()->isTypeParameter());
assert(selfType->getRValueInstanceType()->is<ArchetypeType>());
return selfType;
}
CanArchetypeType getWitnessMethodSelfType() const {
return cast<ArchetypeType>(SubstFormalType.getInput()
->getRValueInstanceType()
->getCanonicalType());
}
CanSILFunctionType getSubstFunctionType(SILGenModule &SGM,
CanSILFunctionType origFnType) const {
if (!HasSubstitutions) return origFnType;
return origFnType->substGenericArgs(SGM.M, SGM.SwiftModule,
Substitutions);
}
/// Add the 'self' clause back to the substituted formal type of
/// this protocol method.
void addProtocolSelfToFormalType(SILGenModule &SGM, SILDeclRef name,
CanType protocolSelfType) {
// The result types of the expressions yielding protocol values
// (reflected in SubstFormalType) reflect an implicit level of
// function application, including some extra polymorphic
// substitution.
HasSubstitutions = true;
auto &ctx = SGM.getASTContext();
// Add the 'self' parameter back. We want it to look like a
// substitution of the appropriate clause from the original type.
auto origFormalType = cast<AnyFunctionType>(OrigFormalInterfaceType);
auto substSelfType =
buildSubstSelfType(origFormalType.getInput(), protocolSelfType, ctx);
auto extInfo = FunctionType::ExtInfo(FunctionType::Representation::Thin,
/*noreturn*/ false,
/*throws*/ origFormalType->throws());
SubstFormalType = CanFunctionType::get(substSelfType, SubstFormalType,
extInfo);
}
/// Add the 'self' type to the substituted function type of this
/// dynamic callee.
void addDynamicCalleeSelfToFormalType(SILGenModule &SGM) {
assert(kind == Kind::DynamicMethod);
// Drop the original self clause.
CanType methodType = OrigFormalInterfaceType;
methodType = cast<AnyFunctionType>(methodType).getResult();
// Replace it with the dynamic self type.
OrigFormalInterfaceType
= getDynamicMethodFormalType(SGM, SelfValue,
Constant.getDecl(),
Constant, methodType);
assert(!OrigFormalInterfaceType->hasTypeParameter());
// Add a self clause to the substituted type.
auto origFormalType = cast<AnyFunctionType>(OrigFormalInterfaceType);
auto selfType = origFormalType.getInput();
SubstFormalType
= CanFunctionType::get(selfType, SubstFormalType,
origFormalType->getExtInfo());
}
public:
static Callee forIndirect(ManagedValue indirectValue,
CanType origFormalType,
CanAnyFunctionType substFormalType,
SILLocation l) {
return Callee(indirectValue,
origFormalType,
substFormalType,
l);
}
static Callee forDirect(SILGenFunction &gen, SILDeclRef c,
CanAnyFunctionType substFormalType,
SILLocation l) {
return Callee(gen, c, substFormalType, l);
}
static Callee forEnumElement(SILGenFunction &gen, SILDeclRef c,
CanAnyFunctionType substFormalType,
SILLocation l) {
assert(isa<EnumElementDecl>(c.getDecl()));
return Callee(Kind::EnumElement, gen, SILValue(),
c, substFormalType, l);
}
static Callee forClassMethod(SILGenFunction &gen, SILValue selfValue,
SILDeclRef name,
CanAnyFunctionType substFormalType,
SILLocation l) {
return Callee(Kind::ClassMethod, gen, selfValue, name,
substFormalType, l);
}
static Callee forSuperMethod(SILGenFunction &gen, SILValue selfValue,
SILDeclRef name,
CanAnyFunctionType substFormalType,
SILLocation l) {
return Callee(Kind::SuperMethod, gen, selfValue, name,
substFormalType, l);
}
static Callee forArchetype(SILGenFunction &gen,
SILValue optOpeningInstruction,
CanType protocolSelfType,
SILDeclRef name,
CanAnyFunctionType substFormalType,
SILLocation l) {
Callee callee(Kind::WitnessMethod, gen, optOpeningInstruction, name,
substFormalType, l);
callee.addProtocolSelfToFormalType(gen.SGM, name, protocolSelfType);
return callee;
}
static Callee forDynamic(SILGenFunction &gen, SILValue proto,
SILDeclRef name, CanAnyFunctionType substFormalType,
SILLocation l) {
Callee callee(Kind::DynamicMethod, gen, proto, name,
substFormalType, l);
callee.addDynamicCalleeSelfToFormalType(gen.SGM);
return callee;
}
Callee(Callee &&) = default;
Callee &operator=(Callee &&) = default;
void setSubstitutions(SILGenFunction &gen,
SILLocation loc,
ArrayRef<Substitution> newSubs,
unsigned callDepth) {
// Currently generic methods of generic types are the deepest we should
// be able to stack specializations.
// FIXME: Generic local functions can add type parameters to arbitrary
// depth.
assert(callDepth < 2 && "specialization below 'self' or argument depth?!");
assert(Substitutions.empty() && "Already have substitutions?");
Substitutions = newSubs;
assert(getNaturalUncurryLevel() >= callDepth
&& "specializations below uncurry level?!");
SpecializeLoc = loc;
HasSubstitutions = true;
}
void setCaptures(SmallVectorImpl<ManagedValue> &&captures) {
Captures = std::move(captures);
}
ArrayRef<ManagedValue> getCaptures() const {
if (Captures)
return *Captures;
return {};
}
bool hasCaptures() const {
return Captures.hasValue();
}
CanType getOrigFormalType() const {
return OrigFormalInterfaceType;
}
CanAnyFunctionType getSubstFormalType() const {
return SubstFormalType;
}
unsigned getNaturalUncurryLevel() const {
switch (kind) {
case Kind::IndirectValue:
return 0;
case Kind::StandaloneFunction:
case Kind::EnumElement:
case Kind::ClassMethod:
case Kind::SuperMethod:
case Kind::WitnessMethod:
case Kind::DynamicMethod:
return Constant.uncurryLevel;
}
}
EnumElementDecl *getEnumElementDecl() {
assert(kind == Kind::EnumElement);
return cast<EnumElementDecl>(Constant.getDecl());
}
std::tuple<ManagedValue, CanSILFunctionType,
Optional<ForeignErrorConvention>, ApplyOptions>
getAtUncurryLevel(SILGenFunction &gen, unsigned level) const {
ManagedValue mv;
ApplyOptions options = ApplyOptions::None;
SILConstantInfo constantInfo;
Optional<SILDeclRef> constant = None;
switch (kind) {
case Kind::IndirectValue:
assert(level == 0 && "can't curry indirect function");
mv = IndirectValue;
assert(!HasSubstitutions);
break;
case Kind::StandaloneFunction: {
assert(level <= Constant.uncurryLevel
&& "uncurrying past natural uncurry level of standalone function");
constant = Constant.atUncurryLevel(level);
// If we're currying a direct reference to a class-dispatched method,
// make sure we emit the right set of thunks.
if (constant->isCurried && Constant.hasDecl())
if (auto func = Constant.getAbstractFunctionDecl())
if (getMethodDispatch(func) == MethodDispatch::Class)
constant = constant->asDirectReference(true);
constantInfo = gen.getConstantInfo(*constant);
SILValue ref = gen.emitGlobalFunctionRef(Loc, *constant, constantInfo);
mv = ManagedValue::forUnmanaged(ref);
break;
}
case Kind::EnumElement: {
assert(level <= Constant.uncurryLevel
&& "uncurrying past natural uncurry level of enum constructor");
constant = Constant.atUncurryLevel(level);
constantInfo = gen.getConstantInfo(*constant);
// We should not end up here if the enum constructor call is fully
// applied.
assert(constant->isCurried);
SILValue ref = gen.emitGlobalFunctionRef(Loc, *constant, constantInfo);
mv = ManagedValue::forUnmanaged(ref);
break;
}
case Kind::ClassMethod: {
assert(level <= Constant.uncurryLevel
&& "uncurrying past natural uncurry level of method");
constant = Constant.atUncurryLevel(level);
constantInfo = gen.getConstantInfo(*constant);
// If the call is curried, emit a direct call to the curry thunk.
if (level < Constant.uncurryLevel) {
SILValue ref = gen.emitGlobalFunctionRef(Loc, *constant, constantInfo);
mv = ManagedValue::forUnmanaged(ref);
break;
}
// Otherwise, do the dynamic dispatch inline.
SILValue methodVal = gen.B.createClassMethod(Loc,
SelfValue,
*constant,
/*volatile*/
constant->isForeign);
mv = ManagedValue::forUnmanaged(methodVal);
break;
}
case Kind::SuperMethod: {
assert(level <= Constant.uncurryLevel
&& "uncurrying past natural uncurry level of method");
assert(level == getNaturalUncurryLevel() &&
"Currying the self parameter of super method calls should've been emitted");
constant = Constant.atUncurryLevel(level);
constantInfo = gen.getConstantInfo(*constant);
if (SILDeclRef baseConstant = Constant.getBaseOverriddenVTableEntry())
constantInfo = gen.SGM.Types.getConstantOverrideInfo(Constant,
baseConstant);
auto methodVal = gen.B.createSuperMethod(Loc,
SelfValue,
*constant,
constantInfo.getSILType(),
/*volatile*/
constant->isForeign);
mv = ManagedValue::forUnmanaged(methodVal);
break;
}
case Kind::WitnessMethod: {
assert(level <= Constant.uncurryLevel
&& "uncurrying past natural uncurry level of method");
constant = Constant.atUncurryLevel(level);
constantInfo = gen.getConstantInfo(*constant);
// If the call is curried, emit a direct call to the curry thunk.
if (level < Constant.uncurryLevel) {
SILValue ref = gen.emitGlobalFunctionRef(Loc, *constant, constantInfo);
mv = ManagedValue::forUnmanaged(ref);
break;
}
// Look up the witness for the archetype.
auto proto = Constant.getDecl()->getDeclContext()
->getAsProtocolOrProtocolExtensionContext();
auto archetype = getWitnessMethodSelfType();
// Get the openend existential value if the archetype is an opened
// existential type.
SILValue OpenedExistential;
if (!archetype->getOpenedExistentialType().isNull())
OpenedExistential = SelfValue;
SILValue fn = gen.B.createWitnessMethod(Loc,
archetype,
ProtocolConformanceRef(proto),
*constant,
constantInfo.getSILType(),
OpenedExistential,
constant->isForeign);
mv = ManagedValue::forUnmanaged(fn);
break;
}
case Kind::DynamicMethod: {
assert(level >= 1
&& "currying 'self' of dynamic method dispatch not yet supported");
assert(level <= Constant.uncurryLevel
&& "uncurrying past natural uncurry level of method");
auto constant = Constant.atUncurryLevel(level);
constantInfo = gen.getConstantInfo(constant);
auto closureType =
replaceSelfTypeForDynamicLookup(gen.getASTContext(),
constantInfo.SILFnType,
SelfValue->getType().getSwiftRValueType(),
Constant);
SILValue fn = gen.B.createDynamicMethod(Loc,
SelfValue,
constant,
SILType::getPrimitiveObjectType(closureType),
/*volatile*/ constant.isForeign);
mv = ManagedValue::forUnmanaged(fn);
break;
}
}
Optional<ForeignErrorConvention> foreignError;
if (constant && constant->isForeign) {
foreignError = cast<AbstractFunctionDecl>(constant->getDecl())
->getForeignErrorConvention();
}
CanSILFunctionType substFnType =
getSubstFunctionType(gen.SGM, mv.getType().castTo<SILFunctionType>());
return std::make_tuple(mv, substFnType, foreignError, options);
}
ArrayRef<Substitution> getSubstitutions() const {
return Substitutions;
}
SILDeclRef getMethodName() const {
return Constant;
}
/// Return a specialized emission function if this is a function with a known
/// lowering, such as a builtin, or return null if there is no specialized
/// emitter.
Optional<SpecializedEmitter>
getSpecializedEmitter(SILGenModule &SGM, unsigned uncurryLevel) const {
// Currently we have no curried known functions.
if (uncurryLevel != 0)
return None;
switch (kind) {
case Kind::StandaloneFunction: {
return SpecializedEmitter::forDecl(SGM, Constant);
}
case Kind::EnumElement:
case Kind::IndirectValue:
case Kind::ClassMethod:
case Kind::SuperMethod:
case Kind::WitnessMethod:
case Kind::DynamicMethod:
return None;
}
llvm_unreachable("bad callee kind");
}
};
/// Given that we've applied some sort of trivial transform to the
/// value of the given ManagedValue, enter a cleanup for the result if
/// the original had a cleanup.
static ManagedValue maybeEnterCleanupForTransformed(SILGenFunction &gen,
ManagedValue orig,
SILValue result) {
if (orig.hasCleanup()) {
orig.forwardCleanup(gen);
return gen.emitManagedBufferWithCleanup(result);
} else {
return ManagedValue::forUnmanaged(result);
}
}
static Callee prepareArchetypeCallee(SILGenFunction &gen, SILLocation loc,
SILDeclRef constant,
ArgumentSource &selfValue,
CanAnyFunctionType substFnType,
ArrayRef<Substitution> &substitutions) {
auto fd = cast<AbstractFunctionDecl>(constant.getDecl());
auto protocol = cast<ProtocolDecl>(fd->getDeclContext());
// Method calls through ObjC protocols require ObjC dispatch.
constant = constant.asForeign(protocol->isObjC());
CanType selfTy = selfValue.getSubstRValueType();
SILParameterInfo _selfParam;
auto getSelfParameter = [&]() -> SILParameterInfo {
if (_selfParam != SILParameterInfo()) return _selfParam;
auto constantFnType = gen.SGM.Types.getConstantFunctionType(constant);
return (_selfParam = constantFnType->getSelfParameter());
};
auto getSGFContextForSelf = [&]() -> SGFContext {
return (getSelfParameter().isConsumed()
? SGFContext() : SGFContext::AllowGuaranteedPlusZero);
};
auto setSelfValueToAddress = [&](SILLocation loc, ManagedValue address) {
assert(address.getType().isAddress());
assert(address.getType().is<ArchetypeType>());
auto formalTy = address.getType().getSwiftRValueType();
if (getSelfParameter().isIndirectMutating()) {
// Be sure not to consume the cleanup for an inout argument.
auto selfLV = ManagedValue::forLValue(address.getValue());
selfValue = ArgumentSource(loc,
LValue::forAddress(selfLV, AbstractionPattern(formalTy),
formalTy));
} else {
selfValue = ArgumentSource(loc, RValue(address, formalTy));
}
};
// If we're calling a member of a non-class-constrained protocol,
// but our archetype refines it to be class-bound, then
// we have to materialize the value in order to pass it indirectly.
auto materializeSelfIfNecessary = [&] {
// Only an instance method of a non-class protocol is ever passed
// indirectly.
if (!fd->isInstanceMember() ||
protocol->requiresClass() ||
selfValue.hasLValueType() ||
!cast<ArchetypeType>(selfValue.getSubstRValueType())->requiresClass())
return;
auto selfParameter = getSelfParameter();
assert(selfParameter.isIndirect());
(void)selfParameter;
SILLocation selfLoc = selfValue.getLocation();
// Evaluate the reference into memory.
ManagedValue address = [&]() -> ManagedValue {
// Do so at +0 if we can.
auto ref = std::move(selfValue)
.getAsSingleValue(gen, getSGFContextForSelf());
// If we're already in memory for some reason, great.
if (ref.getType().isAddress())
return ref;
// Store the reference into a temporary.
auto temp =
gen.emitTemporaryAllocation(selfLoc, ref.getValue()->getType());
gen.B.createStore(selfLoc, ref.getValue(), temp);
// If we had a cleanup, create a cleanup at the new address.
return maybeEnterCleanupForTransformed(gen, ref, temp);
}();
setSelfValueToAddress(selfLoc, address);
};
// Construct an archetype call.
// Link back to something to create a data dependency if we have
// an opened type.
SILValue openingSite;
auto archetype =
cast<ArchetypeType>(CanType(selfTy->getRValueInstanceType()));
if (archetype->getOpenedExistentialType()) {
openingSite = gen.getArchetypeOpeningSite(archetype);
}
materializeSelfIfNecessary();
// The protocol self is implicitly decurried.
substFnType = cast<AnyFunctionType>(substFnType.getResult());
return Callee::forArchetype(gen, openingSite, selfTy,
constant, substFnType, loc);
}
/// An ASTVisitor for decomposing a nesting of ApplyExprs into an initial
/// Callee and a list of CallSites. The CallEmission class below uses these
/// to generate the actual SIL call.
///
/// Formally, an ApplyExpr in the AST always has a single argument, which may
/// be of tuple type, possibly empty. Also, some callees have a formal type
/// which is curried -- for example, methods have type Self -> Arg -> Result.
///
/// However, SIL functions take zero or more parameters and the natural entry
/// point of a method takes Self as an additional argument, rather than
/// returning a partial application.
///
/// Therefore, nested ApplyExprs applied to a constant are flattened into a
/// single call of the most uncurried entry point fitting the call site.
/// This avoids intermediate closure construction.
///
/// For example, a method reference 'self.method' decomposes into curry thunk
/// as the callee, with a single call site '(self)'.
///
/// On the other hand, a call of a method 'self.method(x)(y)' with a function
/// return type decomposes into the method's natural entry point as the callee,
/// and two call sites, first '(x, self)' then '(y)'.
class SILGenApply : public Lowering::ExprVisitor<SILGenApply> {
public:
/// The SILGenFunction that we are emitting SIL into.
SILGenFunction &SGF;
/// The apply callee that abstractly represents the entry point that is being
/// called.
Optional<Callee> ApplyCallee;
/// The lvalue or rvalue representing the argument source of self.
ArgumentSource SelfParam;
Expr *SelfApplyExpr = nullptr;
Type SelfType;
std::vector<ApplyExpr*> CallSites;
Expr *SideEffect = nullptr;
/// The depth of uncurries that we have seen.
///
/// *NOTE* This counter is incremented *after* we return from visiting a call
/// site's children. This means that it is not valid until we finish visiting
/// the expression.
unsigned CallDepth = 0;
/// When visiting expressions, sometimes we need to emit self before we know
/// what the actual callee is. In such cases, we assume that we are passing
/// self at +0 and then after we know what the callee is, we check if the
/// self is passed at +1. If so, we add an extra retain.
bool AssumedPlusZeroSelf = false;
SILGenApply(SILGenFunction &gen)
: SGF(gen)
{}
void setCallee(Callee &&c) {
assert((SelfParam ? CallDepth == 1 : CallDepth == 0)
&& "setting callee at non-zero call depth?!");
assert(!ApplyCallee && "already set callee!");
ApplyCallee.emplace(std::move(c));
}
void setSideEffect(Expr *sideEffectExpr) {
assert(!SideEffect && "already set side effect!");
SideEffect = sideEffectExpr;
}
void setSelfParam(ArgumentSource &&theSelfParam, Expr *theSelfApplyExpr) {
assert(!SelfParam && "already set this!");
SelfParam = std::move(theSelfParam);
SelfApplyExpr = theSelfApplyExpr;
SelfType = theSelfApplyExpr->getType();
++CallDepth;
}
void setSelfParam(ArgumentSource &&theSelfParam, Type selfType) {
assert(!SelfParam && "already set this!");
SelfParam = std::move(theSelfParam);
SelfApplyExpr = nullptr;
SelfType = selfType;
++CallDepth;
}
void decompose(Expr *e) {
visit(e);
}
/// Get the type of the function for substitution purposes.
///
/// \param otherCtorRefUsesAllocating If true, the OtherConstructorDeclRef
/// refers to the initializing
CanFunctionType getSubstFnType(bool otherCtorRefUsesAllocating = false) {
// TODO: optimize this if there are no specializes in play
auto getSiteType = [&](ApplyExpr *site, bool otherCtorRefUsesAllocating) {
if (otherCtorRefUsesAllocating) {
// We have a reference to an initializing constructor, but we will
// actually be using the allocating constructor. Update the type
// appropriately.
// FIXME: Re-derive the type from the declaration + substitutions?
auto ctorRef = cast<OtherConstructorDeclRefExpr>(
site->getFn()->getSemanticsProvidingExpr());
auto fnType = ctorRef->getType()->castTo<FunctionType>();
auto selfTy = MetatypeType::get(
fnType->getInput()->getInOutObjectType());
return CanFunctionType::get(selfTy->getCanonicalType(),
fnType->getResult()->getCanonicalType(),
fnType->getExtInfo());
}
return cast<FunctionType>(site->getFn()->getType()->getCanonicalType());
};
CanFunctionType fnType;
auto addSite = [&](ApplyExpr *site, bool otherCtorRefUsesAllocating) {
auto siteType = getSiteType(site, otherCtorRefUsesAllocating);
// If this is the first call site, use its formal type directly.
if (!fnType) {
fnType = siteType;
return;
}
fnType = CanFunctionType::get(siteType.getInput(), fnType,
siteType->getExtInfo());
};
for (auto callSite : CallSites) {
addSite(callSite, false);
}
// The self application might be a DynamicMemberRefExpr.
if (auto selfApply = dyn_cast_or_null<ApplyExpr>(SelfApplyExpr)) {
addSite(selfApply, otherCtorRefUsesAllocating);
}
assert(fnType && "found no call sites?");
return fnType;
}
/// Fall back to an unknown, indirect callee.
void visitExpr(Expr *e) {
ManagedValue fn = SGF.emitRValueAsSingleValue(e);
auto origType = cast<AnyFunctionType>(e->getType()->getCanonicalType());
setCallee(Callee::forIndirect(fn, origType, getSubstFnType(), e));
}
void visitLoadExpr(LoadExpr *e) {
// TODO: preserve the function pointer at its original abstraction level
ManagedValue fn = SGF.emitRValueAsSingleValue(e);
auto origType = cast<AnyFunctionType>(e->getType()->getCanonicalType());
setCallee(Callee::forIndirect(fn, origType, getSubstFnType(), e));
}
/// Add a call site to the curry.
void visitApplyExpr(ApplyExpr *e) {
if (e->isSuper()) {
applySuper(e);
} else if (applyInitDelegation(e)) {
// Already done
} else {
CallSites.push_back(e);
visit(e->getFn());
}
++CallDepth;
}
/// Given a metatype value for the type, allocate an Objective-C
/// object (with alloc_ref_dynamic) of that type.
///
/// \returns the self object.
ManagedValue allocateObjCObject(ManagedValue selfMeta, SILLocation loc) {
auto metaType = selfMeta.getType().castTo<AnyMetatypeType>();
CanType type = metaType.getInstanceType();
// Convert to an Objective-C metatype representation, if needed.
ManagedValue selfMetaObjC;
if (metaType->getRepresentation() == MetatypeRepresentation::ObjC) {
selfMetaObjC = selfMeta;
} else {
CanAnyMetatypeType objcMetaType;
if (isa<MetatypeType>(metaType)) {
objcMetaType = CanMetatypeType::get(type, MetatypeRepresentation::ObjC);
} else {
objcMetaType = CanExistentialMetatypeType::get(type,
MetatypeRepresentation::ObjC);
}
selfMetaObjC = ManagedValue(
SGF.B.emitThickToObjCMetatype(
loc, selfMeta.getValue(),
SGF.SGM.getLoweredType(objcMetaType)),
selfMeta.getCleanup());
}
// Allocate the object.
return ManagedValue(SGF.B.createAllocRefDynamic(
loc,
selfMetaObjC.getValue(),
SGF.SGM.getLoweredType(type),
/*objc=*/true),
selfMetaObjC.getCleanup());
}
//
// Known callees.
//
void visitDeclRefExpr(DeclRefExpr *e) {
// If we need to perform dynamic dispatch for the given function,
// emit class_method to do so.
if (auto afd = dyn_cast<AbstractFunctionDecl>(e->getDecl())) {
Optional<SILDeclRef::Kind> kind;
bool isDynamicallyDispatched;
bool requiresAllocRefDynamic = false;
// Determine whether the method is dynamically dispatched.
if (auto *proto = dyn_cast<ProtocolDecl>(afd->getDeclContext())) {
// We have four cases to deal with here:
//
// 1) for a "static" / "type" method, the base is a metatype.
// 2) for a classbound protocol, the base is a class-bound protocol rvalue,
// which is loadable.
// 3) for a mutating method, the base has inout type.
// 4) for a nonmutating method, the base is a general archetype
// rvalue, which is address-only. The base is passed at +0, so it isn't
// consumed.
//
// In the last case, the AST has this call typed as being applied
// to an rvalue, but the witness is actually expecting a pointer
// to the +0 value in memory. We just pass in the address since
// archetypes are address-only.
CanAnyFunctionType substFnType = getSubstFnType();
assert(!CallSites.empty());
ApplyExpr *thisCallSite = CallSites.back();
CallSites.pop_back();
ArgumentSource selfValue = thisCallSite->getArg();
ArrayRef<Substitution> subs = e->getDeclRef().getSubstitutions();
SILDeclRef::Kind kind = SILDeclRef::Kind::Func;
if (isa<ConstructorDecl>(afd)) {
if (proto->isObjC()) {
SILLocation loc = thisCallSite->getArg();
// For Objective-C initializers, we only have an initializing
// initializer. We need to allocate the object ourselves.
kind = SILDeclRef::Kind::Initializer;
auto metatype = std::move(selfValue).getAsSingleValue(SGF);
auto allocated = allocateObjCObject(metatype, loc);
auto allocatedType = allocated.getType().getSwiftRValueType();
selfValue = ArgumentSource(loc, RValue(allocated, allocatedType));
} else {
// For non-Objective-C initializers, we have an allocating
// initializer to call.
kind = SILDeclRef::Kind::Allocator;
}
}
SILDeclRef constant = SILDeclRef(afd, kind);
// Prepare the callee. This can modify both selfValue and subs.
Callee theCallee = prepareArchetypeCallee(SGF, e, constant, selfValue,
substFnType, subs);
setSelfParam(std::move(selfValue), thisCallSite);
setCallee(std::move(theCallee));
// If there are substitutions, add them now.