-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenApply.cpp
5834 lines (5015 loc) · 224 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 - 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
//
//===----------------------------------------------------------------------===//
#include "ArgumentSource.h"
#include "FormalEvaluation.h"
#include "Initialization.h"
#include "LValue.h"
#include "RValue.h"
#include "Scope.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/AST/SubstitutionMap.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/Unicode.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "llvm/Support/Compiler.h"
using namespace swift;
using namespace Lowering;
/// Retrieve the type to use for a method found via dynamic lookup.
static CanAnyFunctionType getDynamicMethodFormalType(SILValue proto,
ValueDecl *member,
Type memberType) {
auto &ctx = member->getASTContext();
CanType selfTy;
if (member->isInstanceMember()) {
selfTy = ctx.TheUnknownObjectType;
} else {
selfTy = proto->getType().getSwiftRValueType();
}
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->getResults().begin(), fnType->getResults().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);
}
/// Retrieve the type to use for a method found via dynamic lookup.
static CanSILFunctionType getDynamicMethodLoweredType(SILGenFunction &SGF,
SILValue proto,
SILDeclRef methodName,
CanAnyFunctionType substMemberTy) {
auto &ctx = SGF.getASTContext();
// Determine the opaque 'self' parameter type.
CanType selfTy;
if (methodName.getDecl()->isInstanceMember()) {
selfTy = proto->getType().getSwiftRValueType();
assert(selfTy->is<ArchetypeType>() && "Dynamic lookup needs an archetype");
} else {
selfTy = proto->getType().getSwiftRValueType();
}
// Replace the 'self' parameter type in the method type with it.
auto objcFormalTy = substMemberTy.withExtInfo(substMemberTy->getExtInfo()
.withSILRepresentation(SILFunctionTypeRepresentation::ObjCMethod));
auto methodTy = SGF.SGM.M.Types
.getUncachedSILFunctionTypeForConstant(methodName, objcFormalTy);
return replaceSelfTypeForDynamicLookup(ctx, methodTy, selfTy, methodName);
}
/// Check if we can perform a dynamic dispatch on a super method call.
static bool canUseStaticDispatch(SILGenFunction &SGF,
SILDeclRef constant) {
auto *funcDecl = cast<AbstractFunctionDecl>(constant.getDecl());
if (funcDecl->isFinal())
return true;
// Extension methods currently must be statically dispatched, unless they're
// @objc or dynamic.
if (funcDecl->getDeclContext()->isExtensionContext()
&& !constant.isForeign)
return true;
// We cannot form a direct reference to a method body defined in
// Objective-C.
if (constant.isForeign)
return false;
// If we cannot form a direct reference due to resilience constraints,
// we have to dynamic dispatch.
if (SGF.F.isFragile() && !constant.isFragile())
return false;
// If the method is defined in the same module, we can reference it
// directly.
auto thisModule = SGF.SGM.M.getSwiftModule();
if (thisModule == funcDecl->getModuleContext())
return true;
// Otherwise, we must dynamic dispatch.
return false;
}
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;
SubstitutionList Substitutions;
CanAnyFunctionType OrigFormalInterfaceType;
Optional<SmallVector<ManagedValue, 2>> Captures;
// The pointer back to the AST node that produced the callee.
SILLocation Loc;
private:
Callee(ManagedValue indirectValue,
CanAnyFunctionType origFormalType,
SILLocation L)
: kind(Kind::IndirectValue),
IndirectValue(indirectValue),
OrigFormalInterfaceType(origFormalType),
Loc(L)
{}
static CanAnyFunctionType getConstantFormalInterfaceType(SILGenFunction &SGF,
SILDeclRef fn) {
return SGF.SGM.Types.getConstantInfo(fn.atUncurryLevel(0))
.FormalInterfaceType;
}
Callee(SILGenFunction &SGF, SILDeclRef standaloneFunction,
SILLocation l)
: kind(Kind::StandaloneFunction), Constant(standaloneFunction),
OrigFormalInterfaceType(getConstantFormalInterfaceType(SGF,
standaloneFunction)),
Loc(l)
{
}
Callee(Kind methodKind,
SILGenFunction &SGF,
SILValue selfValue,
SILDeclRef methodName,
SILLocation l)
: kind(methodKind), Constant(methodName), SelfValue(selfValue),
OrigFormalInterfaceType(getConstantFormalInterfaceType(SGF, methodName)),
Loc(l)
{
}
CanArchetypeType getWitnessMethodSelfType() const {
return cast<ArchetypeType>(getSubstFormalType().getInput()
->getRValueInstanceType()
->getCanonicalType());
}
CanSILFunctionType getSubstFunctionType(SILGenModule &SGM,
CanSILFunctionType origFnType) const {
return origFnType->substGenericArgs(SGM.M, Substitutions);
}
/// Add the 'self' type to the substituted function type of this
/// dynamic callee.
void addDynamicCalleeSelfToFormalType(Type substFormalType) {
assert(kind == Kind::DynamicMethod);
OrigFormalInterfaceType
= getDynamicMethodFormalType(SelfValue,
Constant.getDecl(),
substFormalType);
assert(!OrigFormalInterfaceType->hasTypeParameter());
}
public:
static Callee forIndirect(ManagedValue indirectValue,
CanAnyFunctionType origFormalType,
SILLocation l) {
return Callee(indirectValue, origFormalType, l);
}
static Callee forDirect(SILGenFunction &SGF, SILDeclRef c,
SILLocation l) {
return Callee(SGF, c, l);
}
static Callee forEnumElement(SILGenFunction &SGF, SILDeclRef c,
SILLocation l) {
assert(isa<EnumElementDecl>(c.getDecl()));
return Callee(Kind::EnumElement, SGF, SILValue(), c, l);
}
static Callee forClassMethod(SILGenFunction &SGF, SILValue selfValue,
SILDeclRef name,
SILLocation l) {
return Callee(Kind::ClassMethod, SGF, selfValue, name, l);
}
static Callee forSuperMethod(SILGenFunction &SGF, SILValue selfValue,
SILDeclRef name,
SILLocation l) {
while (auto *UI = dyn_cast<UpcastInst>(selfValue))
selfValue = UI->getOperand();
return Callee(Kind::SuperMethod, SGF, selfValue, name, l);
}
static Callee forArchetype(SILGenFunction &SGF,
SILValue optOpeningInstruction,
CanType protocolSelfType,
SILDeclRef name,
SILLocation l) {
Callee callee(Kind::WitnessMethod, SGF, optOpeningInstruction, name, l);
return callee;
}
static Callee forDynamic(SILGenFunction &SGF, SILValue proto,
SILDeclRef name, Type substFormalType,
SILLocation l) {
Callee callee(Kind::DynamicMethod, SGF, proto, name, l);
callee.addDynamicCalleeSelfToFormalType(substFormalType);
return callee;
}
Callee(Callee &&) = default;
Callee &operator=(Callee &&) = default;
void setSubstitutions(SubstitutionList newSubs) {
assert(Substitutions.empty() && "Already have substitutions?");
Substitutions = newSubs;
}
void setCaptures(SmallVectorImpl<ManagedValue> &&captures) {
Captures = std::move(captures);
}
ArrayRef<ManagedValue> getCaptures() const {
if (Captures)
return *Captures;
return {};
}
bool hasCaptures() const {
return Captures.hasValue();
}
CanAnyFunctionType getOrigFormalType() const {
return OrigFormalInterfaceType;
}
CanFunctionType getSubstFormalType() const {
if (auto *gft = OrigFormalInterfaceType->getAs<GenericFunctionType>()) {
return cast<FunctionType>(
gft->substGenericArgs(getSubstitutions())
->getCanonicalType());
}
return cast<FunctionType>(OrigFormalInterfaceType);
}
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;
}
llvm_unreachable("Unhandled Kind in switch.");
}
EnumElementDecl *getEnumElementDecl() {
assert(kind == Kind::EnumElement);
return cast<EnumElementDecl>(Constant.getDecl());
}
std::tuple<ManagedValue, CanSILFunctionType,
Optional<ForeignErrorConvention>, ImportAsMemberStatus, ApplyOptions>
getAtUncurryLevel(SILGenFunction &SGF, unsigned level) const {
ManagedValue mv;
ApplyOptions options = ApplyOptions::None;
Optional<SILDeclRef> constant = None;
switch (kind) {
case Kind::IndirectValue:
assert(level == 0 && "can't curry indirect function");
mv = IndirectValue;
assert(Substitutions.empty());
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);
auto constantInfo = SGF.getConstantInfo(*constant);
SILValue ref = SGF.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);
auto constantInfo = SGF.getConstantInfo(*constant);
// We should not end up here if the enum constructor call is fully
// applied.
assert(constant->isCurried);
SILValue ref = SGF.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);
auto constantInfo = SGF.getConstantInfo(*constant);
// If the call is curried, emit a direct call to the curry thunk.
if (level < Constant.uncurryLevel) {
SILValue ref = SGF.emitGlobalFunctionRef(Loc, *constant, constantInfo);
mv = ManagedValue::forUnmanaged(ref);
break;
}
// Otherwise, do the dynamic dispatch inline.
SILValue methodVal = SGF.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);
auto constantInfo = SGF.getConstantInfo(*constant);
if (SILDeclRef baseConstant = Constant.getBaseOverriddenVTableEntry())
constantInfo = SGF.SGM.Types.getConstantOverrideInfo(Constant,
baseConstant);
auto methodVal = SGF.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);
auto constantInfo = SGF.getConstantInfo(*constant);
// If the call is curried, emit a direct call to the curry thunk.
if (level < Constant.uncurryLevel) {
SILValue ref = SGF.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();
SILValue fn = SGF.B.createWitnessMethod(Loc,
archetype,
ProtocolConformanceRef(proto),
*constant,
constantInfo.getSILType(),
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");
constant = Constant.atUncurryLevel(level);
// Lower the substituted type from the AST, which should have any generic
// parameters in the original signature erased to their upper bounds.
auto substFormalType = getSubstFormalType();
auto objcFormalType = substFormalType.withExtInfo(
substFormalType->getExtInfo()
.withSILRepresentation(SILFunctionTypeRepresentation::ObjCMethod));
auto fnType = SGF.SGM.M.Types
.getUncachedSILFunctionTypeForConstant(*constant, objcFormalType);
auto closureType =
replaceSelfTypeForDynamicLookup(SGF.getASTContext(), fnType,
SelfValue->getType().getSwiftRValueType(),
Constant);
SILValue fn = SGF.B.createDynamicMethod(Loc,
SelfValue,
*constant,
SILType::getPrimitiveObjectType(closureType),
/*volatile*/ Constant.isForeign);
mv = ManagedValue::forUnmanaged(fn);
break;
}
}
Optional<ForeignErrorConvention> foreignError;
ImportAsMemberStatus foreignSelf;
if (constant && constant->isForeign) {
auto func = cast<AbstractFunctionDecl>(constant->getDecl());
foreignError = func->getForeignErrorConvention();
foreignSelf = func->getImportAsMemberStatus();
}
CanSILFunctionType substFnType =
getSubstFunctionType(SGF.SGM, mv.getType().castTo<SILFunctionType>());
return std::make_tuple(mv, substFnType, foreignError, foreignSelf, options);
}
SubstitutionList 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 &SGF,
ManagedValue orig,
SILValue result,
SILLocation loc) {
if (orig.hasCleanup()) {
orig.forwardCleanup(SGF);
return SGF.emitFormalAccessManagedBufferWithCleanup(loc, result);
} else {
return ManagedValue::forUnmanaged(result);
}
}
namespace {
class ArchetypeCalleeBuilder {
SILGenFunction &SGF;
SILLocation loc;
ArgumentSource &selfValue;
SILParameterInfo selfParam;
AbstractFunctionDecl *fd;
ProtocolDecl *protocol;
SILDeclRef constant;
public:
ArchetypeCalleeBuilder(SILGenFunction &SGF, SILLocation loc,
SILDeclRef inputConstant, ArgumentSource &selfValue)
: SGF(SGF), loc(loc), selfValue(selfValue),
selfParam(), fd(cast<AbstractFunctionDecl>(inputConstant.getDecl())),
protocol(cast<ProtocolDecl>(fd->getDeclContext())),
constant(inputConstant.asForeign(protocol->isObjC())) {}
Callee build() {
// Link back to something to create a data dependency if we have
// an opened type.
SILValue openingSite;
auto archetype =
cast<ArchetypeType>(CanType(getSelfType()->getRValueInstanceType()));
if (archetype->getOpenedExistentialType()) {
openingSite = SGF.getArchetypeOpeningSite(archetype);
}
// Then if we need to materialize self into memory, do so.
if (shouldMaterializeSelf()) {
SILLocation selfLoc = selfValue.getLocation();
ManagedValue address = evaluateAddressIntoMemory(selfLoc);
setSelfValueToAddress(selfLoc, address);
}
return Callee::forArchetype(SGF, openingSite, getSelfType(), constant, loc);
}
private:
CanType getSelfType() const { return selfValue.getSubstRValueType(); }
SILParameterInfo getSelfParameterInfo() const {
if (selfParam == SILParameterInfo()) {
auto &Self = const_cast<ArchetypeCalleeBuilder &>(*this);
auto constantFnType = SGF.SGM.Types.getConstantFunctionType(constant);
Self.selfParam = constantFnType->getSelfParameter();
}
return selfParam;
}
SGFContext getSGFContextForSelf() {
if (getSelfParameterInfo().isConsumed())
return SGFContext();
return SGFContext::AllowGuaranteedPlusZero;
}
void setSelfValueToAddress(SILLocation loc, ManagedValue address) {
assert(address.getType().isAddress());
assert(address.getType().is<ArchetypeType>());
auto formalTy = address.getType().getSwiftRValueType();
if (getSelfParameterInfo().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(SGF, loc, formalTy, address));
}
}
bool shouldMaterializeSelf() const {
// 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 false;
assert(SGF.silConv.useLoweredAddresses() ==
SGF.silConv.isSILIndirect(getSelfParameterInfo()));
if (!SGF.silConv.useLoweredAddresses())
return false;
return true;
}
// 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.
ManagedValue evaluateAddressIntoMemory(SILLocation selfLoc) {
// Do so at +0 if we can.
ManagedValue ref =
std::move(selfValue).getAsSingleValue(SGF, getSGFContextForSelf());
// If we're already in memory for some reason, great.
if (ref.getType().isAddress())
return ref;
// Store the reference into a temporary.
SILValue temp =
SGF.emitTemporaryAllocation(selfLoc, ref.getValue()->getType());
SGF.B.emitStoreValueOperation(selfLoc, ref.getValue(), temp,
StoreOwnershipQualifier::Init);
// If we had a cleanup, create a cleanup at the new address.
return maybeEnterCleanupForTransformed(SGF, ref, temp, selfLoc);
}
};
} // end anonymous namespace
static Callee prepareArchetypeCallee(SILGenFunction &SGF, SILLocation loc,
SILDeclRef constant,
ArgumentSource &selfValue) {
// Construct an archetype call.
ArchetypeCalleeBuilder Builder{SGF, loc, constant, selfValue};
return Builder.build();
}
/// For ObjC init methods, we generate a shared-linkage Swift allocating entry
/// point that does the [[T alloc] init] dance. We want to use this native
/// thunk where we expect to be calling an allocating entry point for an ObjC
/// constructor.
static bool isConstructorWithGeneratedAllocatorThunk(ValueDecl *vd) {
return vd->isObjC() && isa<ConstructorDecl>(vd);
}
/// 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;
/// 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 &SGF)
: SGF(SGF)
{}
void setCallee(Callee &&c) {
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();
}
void setSelfParam(ArgumentSource &&theSelfParam, Type selfType) {
assert(!SelfParam && "already set this!");
SelfParam = std::move(theSelfParam);
SelfApplyExpr = nullptr;
SelfType = selfType;
}
void decompose(Expr *e) {
visit(e);
}
/// 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, 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, 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());
}
}
/// 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);
}
// ObjC metatypes are trivial and thus do not have a cleanup. Only if we
// convert them to an object do they become non-trivial.
assert(!selfMeta.hasCleanup());
selfMetaObjC = ManagedValue::forUnmanaged(SGF.B.emitThickToObjCMetatype(
loc, selfMeta.getValue(), SGF.SGM.getLoweredType(objcMetaType)));
}
// 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.
assert(!CallSites.empty());
ApplyExpr *thisCallSite = CallSites.back();
CallSites.pop_back();
ArgumentSource selfValue = thisCallSite->getArg();
SubstitutionList 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(SGF, loc,
allocatedType, allocated));
} 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);
AssumedPlusZeroSelf = selfValue.isRValue()
&& selfValue.forceAndPeekRValue(SGF).peekIsPlusZeroRValueOrTrivial();
setSelfParam(std::move(selfValue), thisCallSite);
setCallee(std::move(theCallee));
// If there are substitutions, add them now.
if (!subs.empty())
ApplyCallee->setSubstitutions(subs);
return;
}
if (e->getAccessSemantics() != AccessSemantics::Ordinary) {
isDynamicallyDispatched = false;
} else {
switch (getMethodDispatch(afd)) {
case MethodDispatch::Class:
isDynamicallyDispatched = true;
break;
case MethodDispatch::Static:
isDynamicallyDispatched = false;
break;
}
}
if (isa<FuncDecl>(afd) && isDynamicallyDispatched) {
kind = SILDeclRef::Kind::Func;
} else if (auto ctor = dyn_cast<ConstructorDecl>(afd)) {
ApplyExpr *thisCallSite = CallSites.back();
// Required constructors are dynamically dispatched when the 'self'
// value is not statically derived.
if (ctor->isRequired() &&
thisCallSite->getArg()->getType()->is<AnyMetatypeType>() &&
!thisCallSite->getArg()->isStaticallyDerivedMetatype()) {
if (requiresForeignEntryPoint(afd)) {
// When we're performing Objective-C dispatch, we don't have an
// allocating constructor to call. So, perform an alloc_ref_dynamic
// and pass that along to the initializer.
requiresAllocRefDynamic = true;
kind = SILDeclRef::Kind::Initializer;
} else {
kind = SILDeclRef::Kind::Allocator;
}
} else {
isDynamicallyDispatched = false;
}
}
if (isDynamicallyDispatched) {
ApplyExpr *thisCallSite = CallSites.back();
CallSites.pop_back();
// Emit the rvalue for self, allowing for guaranteed plus zero if we
// have a func.
bool AllowPlusZero = kind && *kind == SILDeclRef::Kind::Func;
RValue self =
SGF.emitRValue(thisCallSite->getArg(),
AllowPlusZero ? SGFContext::AllowGuaranteedPlusZero :
SGFContext());
// If we allowed for PlusZero and we *did* get the value back at +0,
// then we assumed that self could be passed at +0. We will check later
// if the actual callee passes self at +1 later when we know its actual
// type.
AssumedPlusZeroSelf =
AllowPlusZero && self.peekIsPlusZeroRValueOrTrivial();
// If we require a dynamic allocation of the object here, do so now.
if (requiresAllocRefDynamic) {
SILLocation loc = thisCallSite->getArg();
auto selfValue = allocateObjCObject(
std::move(self).getAsSingleValue(SGF, loc),
loc);
self = RValue(SGF, loc, selfValue.getType().getSwiftRValueType(),
selfValue);
}
auto selfValue = self.peekScalarValue();
setSelfParam(ArgumentSource(thisCallSite->getArg(), std::move(self)),
thisCallSite);
SILDeclRef constant(afd, kind.getValue(),
SILDeclRef::ConstructAtBestResilienceExpansion,
SILDeclRef::ConstructAtNaturalUncurryLevel,
requiresForeignEntryPoint(afd));
setCallee(Callee::forClassMethod(SGF, selfValue, constant, e));
// If there are substitutions, add them.
if (e->getDeclRef().isSpecialized()) {
ApplyCallee->setSubstitutions(e->getDeclRef().getSubstitutions());
}
return;
}
}
// If this is a direct reference to a vardecl, just emit its value directly.
// Recursive references to callable declarations are allowed.
if (isa<VarDecl>(e->getDecl())) {
visitExpr(e);
return;
}