-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathDevirtualize.cpp
1505 lines (1299 loc) · 56 KB
/
Devirtualize.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
//===--- Devirtualize.cpp - Helper for devirtualizing apply ---------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-devirtualize-utility"
#include "swift/SILOptimizer/Utils/Devirtualize.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/SIL/CalleeCache.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/OptimizationRemark.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILValue.h"
#include "swift/SILOptimizer/Analysis/ClassHierarchyAnalysis.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Casting.h"
using namespace swift;
STATISTIC(NumClassDevirt, "Number of class_method applies devirtualized");
STATISTIC(NumWitnessDevirt, "Number of witness_method applies devirtualized");
//===----------------------------------------------------------------------===//
// Class Method Optimization
//===----------------------------------------------------------------------===//
void swift::getAllSubclasses(ClassHierarchyAnalysis *cha, ClassDecl *cd,
CanType classType, SILModule &module,
ClassHierarchyAnalysis::ClassList &subs) {
// Collect the direct and indirect subclasses for the class.
// Sort these subclasses in the order they should be tested by the
// speculative devirtualization. Different strategies could be used,
// E.g. breadth-first, depth-first, etc.
// Currently, let's use the breadth-first strategy.
// The exact static type of the instance should be tested first.
auto &directSubs = cha->getDirectSubClasses(cd);
auto &indirectSubs = cha->getIndirectSubClasses(cd);
subs.append(directSubs.begin(), directSubs.end());
subs.append(indirectSubs.begin(), indirectSubs.end());
// FIXME: This is wrong -- we could have a non-generic class nested
// inside a generic class
if (isa<BoundGenericClassType>(classType)) {
// Filter out any subclasses that do not inherit from this
// specific bound class.
auto removedIt =
std::remove_if(subs.begin(), subs.end(), [&classType](ClassDecl *sub) {
// FIXME: Add support for generic subclasses.
if (sub->isGenericContext())
return false;
auto subCanTy = sub->getDeclaredInterfaceType()->getCanonicalType();
// Handle the usual case here: the class in question
// should be a real subclass of a bound generic class.
return !classType->isBindableToSuperclassOf(subCanTy);
});
subs.erase(removedIt, subs.end());
}
}
/// Returns true, if a method implementation corresponding to
/// the class_method applied to an instance of the class cd is
/// effectively final, i.e. it is statically known to be not overridden
/// by any subclasses of the class cd.
///
/// \p applySite invocation instruction
/// \p classType type of the instance
/// \p cd static class of the instance whose method is being invoked
/// \p cha class hierarchy analysis
static bool isEffectivelyFinalMethod(FullApplySite applySite, CanType classType,
ClassDecl *cd,
ClassHierarchyAnalysis *cha) {
if (cd && cd->isFinal())
return true;
auto *cmi = cast<MethodInst>(applySite.getCallee());
if (!calleesAreStaticallyKnowable(applySite.getModule(), cmi->getMember()))
return false;
auto *method = cmi->getMember().getAbstractFunctionDecl();
assert(method && "Expected abstract function decl!");
assert(!method->isFinal() && "Unexpected indirect call to final method!");
// If this method is not overridden in the module,
// there is no other implementation.
if (!method->isOverridden())
return true;
// Class declaration may be nullptr, e.g. for cases like:
// func foo<C:Base>(c: C) {}, where C is a class, but
// it does not have a class decl.
if (!cd)
return false;
if (!cha)
return false;
// We can analyze the class hierarchy rooted at this class and
// eventually devirtualize a method call more efficiently.
ClassHierarchyAnalysis::ClassList subs;
getAllSubclasses(cha, cd, classType, applySite.getModule(), subs);
// This is the implementation of the method to be used
// if the exact class of the instance would be cd.
auto *ImplMethod = cd->findImplementingMethod(method);
// First, analyze all direct subclasses.
for (auto S : subs) {
// Check if the subclass overrides a method and provides
// a different implementation.
auto *ImplFD = S->findImplementingMethod(method);
if (ImplFD != ImplMethod)
return false;
}
return true;
}
/// Check if a given class is final in terms of a current
/// compilation, i.e.:
/// - it is really final
/// - or it is private and has not sub-classes
/// - or it is an internal class without sub-classes and
/// it is a whole-module compilation.
static bool isKnownFinalClass(ClassDecl *cd, SILModule &module,
ClassHierarchyAnalysis *cha) {
if (cd->isFinal())
return true;
// Only handle classes defined within the SILModule's associated context.
if (!cd->isChildContextOf(module.getAssociatedContext()))
return false;
if (!cd->hasAccess())
return false;
// Only consider 'private' members, unless we are in whole-module compilation.
switch (cd->getEffectiveAccess()) {
case AccessLevel::Open:
return false;
case AccessLevel::Public:
case AccessLevel::Package:
case AccessLevel::Internal:
if (!module.isWholeModule())
return false;
break;
case AccessLevel::FilePrivate:
case AccessLevel::Private:
break;
}
// Take the ClassHierarchyAnalysis into account.
// If a given class has no subclasses and
// - private
// - or internal and it is a WMO compilation
// then this class can be considered final for the purpose
// of devirtualization.
if (cha) {
if (!cha->hasKnownDirectSubclasses(cd)) {
switch (cd->getEffectiveAccess()) {
case AccessLevel::Open:
return false;
case AccessLevel::Public:
case AccessLevel::Package:
case AccessLevel::Internal:
if (!module.isWholeModule())
return false;
break;
case AccessLevel::FilePrivate:
case AccessLevel::Private:
break;
}
return true;
}
}
return false;
}
// Attempt to get the instance for S, whose static type is the same as
// its exact dynamic type, returning a null SILValue() if we cannot find it.
// The information that a static type is the same as the exact dynamic,
// can be derived e.g.:
// - from a constructor or
// - from a successful outcome of a checked_cast_br [exact] instruction.
SILValue swift::getInstanceWithExactDynamicType(SILValue instance,
ClassHierarchyAnalysis *cha) {
auto *f = instance->getFunction();
auto &module = f->getModule();
while (instance) {
instance = stripCasts(instance);
if (isa<AllocRefInst>(instance) || isa<MetatypeInst>(instance)) {
if (instance->getType().getASTType()->hasDynamicSelfType())
return SILValue();
return instance;
}
auto *arg = dyn_cast<SILArgument>(instance);
if (!arg)
break;
auto *singlePred = arg->getParent()->getSinglePredecessorBlock();
if (!singlePred) {
if (!isa<SILFunctionArgument>(arg))
break;
auto *cd = arg->getType().getClassOrBoundGenericClass();
// Check if this class is effectively final.
if (!cd || !isKnownFinalClass(cd, module, cha))
break;
return arg;
}
// Traverse the chain of predecessors.
if (isa<BranchInst>(singlePred->getTerminator())
|| isa<CondBranchInst>(singlePred->getTerminator())) {
instance = cast<SILPhiArgument>(arg)->getIncomingPhiValue(singlePred);
continue;
}
// If it is a BB argument received on a success branch
// of a checked_cast_br, then we know its exact type.
auto *ccbi = dyn_cast<CheckedCastBranchInst>(singlePred->getTerminator());
if (!ccbi)
break;
if (!ccbi->isExact() || ccbi->getSuccessBB() != arg->getParent())
break;
return instance;
}
return SILValue();
}
/// Try to determine the exact dynamic type of an object.
/// returns the exact dynamic type of the object, or an empty type if the exact
/// type could not be determined.
SILType swift::getExactDynamicType(SILValue instance,
ClassHierarchyAnalysis *cha,
bool forUnderlyingObject) {
auto *f = instance->getFunction();
auto &module = f->getModule();
// Set of values to be checked for their exact types.
SmallVector<SILValue, 8> worklist;
// The detected type of the underlying object.
SILType resultType;
// Set of processed values.
llvm::SmallSet<SILValue, 8> processed;
worklist.push_back(instance);
while (!worklist.empty()) {
auto v = worklist.pop_back_val();
if (!v)
return SILType();
if (processed.count(v))
continue;
processed.insert(v);
// For underlying object strip casts and projections.
// For the object itself, simply strip casts.
v = forUnderlyingObject ? getUnderlyingObject(v) : stripCasts(v);
if (isa<AllocRefInst>(v) || isa<MetatypeInst>(v)) {
if (resultType && resultType != v->getType())
return SILType();
resultType = v->getType();
continue;
}
if (isa<LiteralInst>(v)) {
if (resultType && resultType != v->getType())
return SILType();
resultType = v->getType();
continue;
}
if (isa<StructInst>(v) || isa<TupleInst>(v) || isa<EnumInst>(v)) {
if (resultType && resultType != v->getType())
return SILType();
resultType = v->getType();
continue;
}
if (forUnderlyingObject) {
if (isa<AllocationInst>(v)) {
if (resultType && resultType != v->getType())
return SILType();
resultType = v->getType();
continue;
}
}
auto arg = dyn_cast<SILArgument>(v);
if (!arg) {
// We don't know what it is.
return SILType();
}
if (auto *fArg = dyn_cast<SILFunctionArgument>(arg)) {
// Bail on metatypes for now.
if (fArg->getType().is<AnyMetatypeType>()) {
return SILType();
}
auto *cd = fArg->getType().getClassOrBoundGenericClass();
// If it is not class and it is a trivial type, then it
// should be the exact type.
if (!cd && fArg->getType().isTrivial(*f)) {
if (resultType && resultType != fArg->getType())
return SILType();
resultType = fArg->getType();
continue;
}
if (!cd) {
// It is not a class or a trivial type, so we don't know what it is.
return SILType();
}
// Check if this class is effectively final.
if (!isKnownFinalClass(cd, module, cha)) {
return SILType();
}
if (resultType && resultType != fArg->getType())
return SILType();
resultType = fArg->getType();
continue;
}
auto *singlePred = arg->getParent()->getSinglePredecessorBlock();
if (singlePred) {
// If it is a BB argument received on a success branch
// of a checked_cast_br, then we know its exact type.
auto *ccbi = dyn_cast<CheckedCastBranchInst>(singlePred->getTerminator());
if (ccbi && ccbi->isExact() && ccbi->getSuccessBB() == arg->getParent()) {
if (resultType && resultType != arg->getType())
return SILType();
resultType = arg->getType();
continue;
}
}
// It is a BB argument, look through incoming values. If they all have the
// same exact type, then we consider it to be the type of the BB argument.
SmallVector<SILValue, 4> incomingValues;
if (arg->getSingleTerminatorOperands(incomingValues)) {
for (auto inValue : incomingValues) {
worklist.push_back(inValue);
}
continue;
}
// The exact type is unknown.
return SILType();
}
return resultType;
}
/// Try to determine the exact dynamic type of the underlying object.
/// returns the exact dynamic type of a value, or an empty type if the exact
/// type could not be determined.
SILType
swift::getExactDynamicTypeOfUnderlyingObject(SILValue instance,
ClassHierarchyAnalysis *cha) {
return getExactDynamicType(instance, cha, /* forUnderlyingObject */ true);
}
/// Combine two substitution maps as follows.
///
/// The result is written in terms of the generic parameters of 'genericSig'.
///
/// Generic parameters with a depth less than 'firstDepth'
/// come from 'firstSubMap'.
///
/// Generic parameters with a depth greater than 'firstDepth' come from
/// 'secondSubMap', but are looked up starting with a depth or index of
/// 'secondDepth'.
///
/// The 'how' parameter determines if we're looking at the depth or index.
static SubstitutionMap
combineSubstitutionMaps(SubstitutionMap firstSubMap,
SubstitutionMap secondSubMap,
unsigned firstDepth,
unsigned secondDepth,
GenericSignature genericSig) {
auto &ctx = genericSig->getASTContext();
return SubstitutionMap::get(
genericSig,
[&](SubstitutableType *type) {
auto *gp = cast<GenericTypeParamType>(type);
if (gp->getDepth() < firstDepth)
return QuerySubstitutionMap{firstSubMap}(gp);
auto *replacement = GenericTypeParamType::get(
gp->getParamKind(),
gp->getDepth() + secondDepth - firstDepth,
gp->getIndex(),
gp->getValueType(),
ctx);
return QuerySubstitutionMap{secondSubMap}(replacement);
},
// We might not have enough information in the substitution maps alone.
//
// Eg,
//
// class Base<T1> {
// func foo<U1>(_: U1) where T1 : P {}
// }
//
// class Derived<T2> : Base<Foo<T2>> {
// override func foo<U2>(_: U2) where T2 : Q {}
// }
//
// Suppose we're devirtualizing a call to Base.foo() on a value whose
// type is known to be Derived<Bar>. We start with substitutions written
// in terms of Base.foo()'s generic signature:
//
// <T1, U1 where T1 : P>
// T1 := Foo<Bar>
// T1 : P := Foo<Bar> : P
//
// We want to build substitutions in terms of Derived.foo()'s
// generic signature:
//
// <T2, U2 where T2 : Q>
// T2 := Bar
// T2 : Q := Bar : Q
//
// The conformance Bar : Q is difficult to recover in the general case.
//
// Some combination of storing substitution maps in BoundGenericTypes
// as well as for method overrides would solve this, but for now, just
// punt to global lookup.
LookUpConformanceInModule());
}
// Start with the substitutions from the apply.
// Try to propagate them to find out the real substitutions required
// to invoke the method.
static SubstitutionMap
getSubstitutionsForCallee(SILModule &module, CanSILFunctionType baseCalleeType,
CanType derivedSelfType, FullApplySite applySite) {
// If the base method is not polymorphic, no substitutions are required,
// even if we originally had substitutions for calling the derived method.
if (!baseCalleeType->isPolymorphic())
return SubstitutionMap();
// Add any generic substitutions for the base class.
Type baseSelfType = baseCalleeType->getSelfParameter().getArgumentType(
module, baseCalleeType,
applySite.getFunction()->getTypeExpansionContext());
if (auto metatypeType = baseSelfType->getAs<MetatypeType>())
baseSelfType = metatypeType->getInstanceType();
auto *baseClassDecl = baseSelfType->getClassOrBoundGenericClass();
assert(baseClassDecl && "not a class method");
unsigned baseDepth = 0;
SubstitutionMap baseSubMap;
if (auto baseClassSig = baseClassDecl->getGenericSignatureOfContext()) {
baseDepth = baseClassSig.getNextDepth();
// Compute the type of the base class, starting from the
// derived class type and the type of the method's self
// parameter.
Type derivedClass = derivedSelfType;
if (auto metatypeType = derivedClass->getAs<MetatypeType>())
derivedClass = metatypeType->getInstanceType();
baseSubMap = derivedClass->getContextSubstitutionMap(
baseClassDecl);
}
SubstitutionMap origSubMap = applySite.getSubstitutionMap();
Type calleeSelfType =
applySite.getOrigCalleeType()->getSelfParameter().getArgumentType(
module, applySite.getOrigCalleeType(),
applySite.getFunction()->getTypeExpansionContext());
if (auto metatypeType = calleeSelfType->getAs<MetatypeType>())
calleeSelfType = metatypeType->getInstanceType();
auto *calleeClassDecl = calleeSelfType->getClassOrBoundGenericClass();
assert(calleeClassDecl && "self is not a class type");
// Add generic parameters from the method itself, ignoring any generic
// parameters from the derived class.
unsigned origDepth = calleeClassDecl->getGenericSignature().getNextDepth();
auto baseCalleeSig = baseCalleeType->getInvocationGenericSignature();
return combineSubstitutionMaps(baseSubMap,
origSubMap,
baseDepth,
origDepth,
baseCalleeSig);
}
// Return the new apply and true if a cast required CFG modification.
static std::pair<ApplyInst *, bool /* changedCFG */>
replaceApplyInst(SILBuilder &builder, SILPassManager *pm, SILLocation loc, ApplyInst *oldAI,
SILValue newFn, SubstitutionMap newSubs,
ArrayRef<SILValue> newArgs, ArrayRef<SILValue> newArgBorrows) {
auto *newAI =
builder.createApply(loc, newFn, newSubs, newArgs,
oldAI->getApplyOptions());
if (!newArgBorrows.empty()) {
for (SILValue arg : newArgBorrows) {
builder.createEndBorrow(loc, arg);
}
}
// Check if any casting is required for the return value. newAI cannot be a
// guaranteed value, so this cast cannot generate borrow scopes and it can be
// used anywhere the original oldAI was used.
auto castRes = castValueToABICompatibleType(
&builder, pm, loc, newAI, newAI->getType(), oldAI->getType(), /*usePoints*/ {});
oldAI->replaceAllUsesWith(castRes.first);
return {newAI, castRes.second};
}
// Return the new try_apply and true if a cast required CFG modification.
static std::pair<TryApplyInst *, bool /* changedCFG */>
replaceTryApplyInst(SILBuilder &builder, SILPassManager *pm, SILLocation loc, TryApplyInst *oldTAI,
SILValue newFn, SubstitutionMap newSubs,
ArrayRef<SILValue> newArgs, SILFunctionConventions conv,
ArrayRef<SILValue> newArgBorrows) {
SILBasicBlock *normalBB = oldTAI->getNormalBB();
SILBasicBlock *resultBB = nullptr;
SILType newResultTy =
conv.getSILResultType(builder.getTypeExpansionContext());
// Does the result value need to be casted?
auto oldResultTy = normalBB->getArgument(0)->getType();
bool resultCastRequired = newResultTy != oldResultTy;
// Create a new normal BB only if the result of the new apply differs
// in type from the argument of the original normal BB.
if (!resultCastRequired) {
resultBB = normalBB;
} else {
resultBB = builder.getFunction().createBasicBlockBefore(normalBB);
resultBB->createPhiArgument(newResultTy, OwnershipKind::Owned);
}
// We can always just use the original error BB because we'll be
// deleting the edge to it from the old TAI.
SILBasicBlock *errorBB = oldTAI->getErrorBB();
// Insert a try_apply here.
// Note that this makes this block temporarily double-terminated!
// We won't fix that until deleteDevirtualizedApply.
auto newTAI =
builder.createTryApply(loc, newFn, newSubs, newArgs, resultBB, errorBB,
oldTAI->getApplyOptions());
if (!newArgBorrows.empty()) {
builder.setInsertionPoint(normalBB->begin());
for (SILValue arg : newArgBorrows) {
builder.createEndBorrow(loc, arg);
}
builder.setInsertionPoint(errorBB->begin());
for (SILValue arg : newArgBorrows) {
builder.createEndBorrow(loc, arg);
}
}
if (resultCastRequired) {
builder.setInsertionPoint(resultBB);
SILValue resultValue = resultBB->getArgument(0);
// resultValue cannot be a guaranteed value, so this cast cannot generate
// borrow scopes and it can be used anywhere the original oldAI was
// used--usePoints are not required.
std::tie(resultValue, std::ignore) = castValueToABICompatibleType(
&builder, pm, loc, resultValue, newResultTy, oldResultTy, /*usePoints*/ {});
builder.createBranch(loc, normalBB, {resultValue});
}
builder.setInsertionPoint(normalBB->begin());
return {newTAI, resultCastRequired};
}
// Return the new begin_apply and true if a cast required CFG modification.
static std::pair<BeginApplyInst *, bool /* changedCFG */>
replaceBeginApplyInst(SILBuilder &builder, SILPassManager *pm, SILLocation loc,
BeginApplyInst *oldBAI, SILValue newFn,
SubstitutionMap newSubs, ArrayRef<SILValue> newArgs,
ArrayRef<SILValue> newArgBorrows) {
bool changedCFG = false;
auto *newBAI = builder.createBeginApply(loc, newFn, newSubs, newArgs,
oldBAI->getApplyOptions());
// Forward the token.
oldBAI->getTokenResult()->replaceAllUsesWith(newBAI->getTokenResult());
if (auto *allocation = oldBAI->getCalleeAllocationResult()) {
allocation->replaceAllUsesWith(newBAI->getCalleeAllocationResult());
}
auto oldYields = oldBAI->getYieldedValues();
auto newYields = newBAI->getYieldedValues();
assert(oldYields.size() == newYields.size());
for (auto i : indices(oldYields)) {
auto oldYield = oldYields[i];
auto newYield = newYields[i];
// Insert any end_borrow if the yielded value before the token's uses.
SmallVector<SILInstruction *, 4> users(
makeUserIteratorRange(oldYield->getUses()));
if (!users.empty()) {
auto yieldCastRes = castValueToABICompatibleType(
&builder, pm, loc, newYield, newYield->getType(), oldYield->getType(),
users);
oldYield->replaceAllUsesWith(yieldCastRes.first);
changedCFG |= yieldCastRes.second;
}
}
if (newArgBorrows.empty())
return {newBAI, changedCFG};
// Insert the end_borrows after end_apply and abort_apply users.
for (auto *use : newBAI->getEndApplyUses()) {
SILBuilderWithScope borrowBuilder(
&*std::next(use->getUser()->getIterator()),
builder.getBuilderContext());
for (SILValue borrow : newArgBorrows) {
borrowBuilder.createEndBorrow(loc, borrow);
}
}
return {newBAI, changedCFG};
}
// Return the new partial_apply and true if a cast required CFG modification.
static std::pair<PartialApplyInst *, bool /* changedCFG */>
replacePartialApplyInst(SILBuilder &builder, SILPassManager *pm, SILLocation loc,
PartialApplyInst *oldPAI, SILValue newFn,
SubstitutionMap newSubs, ArrayRef<SILValue> newArgs) {
auto convention = oldPAI->getCalleeConvention();
auto isolation = oldPAI->getResultIsolation();
auto *newPAI =
builder.createPartialApply(loc, newFn, newSubs, newArgs, convention,
isolation);
// Check if any casting is required for the partially-applied function.
// A non-guaranteed cast needs no usePoints.
assert(newPAI->getOwnershipKind() != OwnershipKind::Guaranteed);
auto castRes = castValueToABICompatibleType(
&builder, pm, loc, newPAI, newPAI->getType(), oldPAI->getType(),
/*usePoints*/ {});
oldPAI->replaceAllUsesWith(castRes.first);
return {newPAI, castRes.second};
}
// Return the new apply and true if the CFG was also modified.
static std::pair<ApplySite, bool /* changedCFG */>
replaceApplySite(SILBuilder &builder, SILPassManager *pm, SILLocation loc, ApplySite oldAS,
SILValue newFn, SubstitutionMap newSubs,
ArrayRef<SILValue> newArgs, SILFunctionConventions conv,
ArrayRef<SILValue> newArgBorrows) {
switch (oldAS.getKind()) {
case ApplySiteKind::ApplyInst: {
auto *oldAI = cast<ApplyInst>(oldAS);
return replaceApplyInst(builder, pm, loc, oldAI, newFn, newSubs, newArgs,
newArgBorrows);
}
case ApplySiteKind::TryApplyInst: {
auto *oldTAI = cast<TryApplyInst>(oldAS);
return replaceTryApplyInst(builder, pm, loc, oldTAI, newFn, newSubs, newArgs,
conv, newArgBorrows);
}
case ApplySiteKind::BeginApplyInst: {
auto *oldBAI = dyn_cast<BeginApplyInst>(oldAS);
return replaceBeginApplyInst(builder, pm, loc, oldBAI, newFn, newSubs, newArgs,
newArgBorrows);
}
case ApplySiteKind::PartialApplyInst: {
assert(newArgBorrows.empty());
auto *oldPAI = cast<PartialApplyInst>(oldAS);
return replacePartialApplyInst(builder, pm, loc, oldPAI, newFn, newSubs,
newArgs);
}
}
llvm_unreachable("covered switch");
}
/// Delete an apply site that's been successfully devirtualized.
void swift::deleteDevirtualizedApply(ApplySite old) {
auto *oldApply = old.getInstruction();
recursivelyDeleteTriviallyDeadInstructions(oldApply, true);
}
SILFunction *swift::getTargetClassMethod(SILModule &module, ClassDecl *cd,
CanType classType, MethodInst *mi) {
assert((isa<ClassMethodInst>(mi) || isa<SuperMethodInst>(mi)) &&
"Only class_method and super_method instructions are supported");
SILDeclRef member = mi->getMember();
SILType silType = SILType::getPrimitiveObjectType(classType);
if (auto *vtable = module.lookUpSpecializedVTable(silType)) {
return vtable->getEntry(module, member)->getImplementation();
}
return module.lookUpFunctionInVTable(cd, member);
}
CanType swift::getSelfInstanceType(CanType classOrMetatypeType) {
if (auto metaType = dyn_cast<MetatypeType>(classOrMetatypeType))
classOrMetatypeType = metaType.getInstanceType();
if (auto selfType = dyn_cast<DynamicSelfType>(classOrMetatypeType))
classOrMetatypeType = selfType.getSelfType();
return classOrMetatypeType;
}
/// Check if it is possible to devirtualize an Apply instruction
/// and a class member obtained using the class_method instruction into
/// a direct call to a specific member of a specific class.
///
/// \p applySite is the apply to devirtualize.
/// \p cd is the class declaration we are devirtualizing for.
/// return true if it is possible to devirtualize, false - otherwise.
bool swift::canDevirtualizeClassMethod(FullApplySite applySite, ClassDecl *cd,
CanType classType,
OptRemark::Emitter *ore,
bool isEffectivelyFinalMethod) {
LLVM_DEBUG(llvm::dbgs() << " Trying to devirtualize : "
<< *applySite.getInstruction());
SILModule &module = applySite.getModule();
auto *mi = cast<MethodInst>(applySite.getCallee());
// Find the implementation of the member which should be invoked.
auto *f = getTargetClassMethod(module, cd, classType, mi);
// If we do not find any such function, we have no function to devirtualize
// to... so bail.
if (!f) {
LLVM_DEBUG(llvm::dbgs() << " FAIL: Could not find matching VTable "
"or vtable method for this class.\n");
return false;
}
// We need to disable the “effectively final” opt if a function is inlinable
if (isEffectivelyFinalMethod && applySite.getFunction()->isSerialized()) {
LLVM_DEBUG(llvm::dbgs() << " FAIL: Could not optimize function "
"because it is an effectively-final inlinable: "
<< applySite.getFunction()->getName() << "\n");
return false;
}
// Mandatory inlining does class method devirtualization. I'm not sure if this
// is really needed, but some test rely on this.
// So even for Onone functions we have to do it if the SILStage is raw.
if (f->getModule().getStage() != SILStage::Raw && !f->shouldOptimize()) {
// Do not consider functions that should not be optimized.
LLVM_DEBUG(llvm::dbgs()
<< " FAIL: Could not optimize function "
<< " because it is marked no-opt: " << f->getName() << "\n");
return false;
}
if (applySite.getFunction()->isAnySerialized()) {
// function_ref inside fragile function cannot reference a private or
// hidden symbol.
if (!f->hasValidLinkageForFragileRef(
applySite.getFunction()->getSerializedKind()))
return false;
}
// devirtualizeClassMethod below does not support this case. It currently
// assumes it can try_apply call the target.
if (!f->getLoweredFunctionType()->hasErrorResult()
&& isa<TryApplyInst>(applySite.getInstruction())) {
LLVM_DEBUG(llvm::dbgs() << " FAIL: Trying to devirtualize a "
"try_apply but vtable entry has no error result.\n");
return false;
}
return true;
}
/// Devirtualize an apply of a class method.
///
/// \p applySite is the apply to devirtualize.
/// \p ClassOrMetatype is a class value or metatype value that is the
/// self argument of the apply we will devirtualize.
/// return the result value of the new ApplyInst if created one or null.
///
/// Return the new apply and true if the CFG was also modified.
std::pair<FullApplySite, bool /* changedCFG */>
swift::devirtualizeClassMethod(SILPassManager *pm, FullApplySite applySite,
SILValue classOrMetatype, ClassDecl *cd,
CanType classType, OptRemark::Emitter *ore) {
bool changedCFG = false;
LLVM_DEBUG(llvm::dbgs() << " Trying to devirtualize : "
<< *applySite.getInstruction());
SILModule &module = applySite.getModule();
auto *mi = cast<MethodInst>(applySite.getCallee());
auto *f = getTargetClassMethod(module, cd, classType, mi);
CanSILFunctionType genCalleeType = f->getLoweredFunctionTypeInContext(
TypeExpansionContext(*applySite.getFunction()));
SubstitutionMap subs = getSubstitutionsForCallee(
module, genCalleeType, classOrMetatype->getType().getASTType(),
applySite);
CanSILFunctionType substCalleeType = genCalleeType;
if (genCalleeType->isPolymorphic())
substCalleeType = genCalleeType->substGenericArgs(
module, subs, TypeExpansionContext(*applySite.getFunction()));
SILFunctionConventions substConv(substCalleeType, module);
SILBuilderWithScope builder(applySite.getInstruction());
SILLocation loc = applySite.getLoc();
auto *fri = builder.createFunctionRefFor(loc, f);
// Create the argument list for the new apply, casting when needed
// in order to handle covariant indirect return types and
// contravariant argument types.
SmallVector<SILValue, 8> newArgs;
// If we have a value that is owned, but that we are going to use in as a
// guaranteed argument, we need to borrow/unborrow the argument. Otherwise, we
// will introduce new consuming uses. In contrast, if we have an owned value,
// we are ok due to the forwarding nature of upcasts.
SmallVector<SILValue, 8> newArgBorrows;
auto indirectResultArgIter = applySite.getIndirectSILResults().begin();
for (auto resultTy : substConv.getIndirectSILResultTypes(
applySite.getFunction()->getTypeExpansionContext())) {
auto castRes = castValueToABICompatibleType(
&builder, pm, loc, *indirectResultArgIter, indirectResultArgIter->getType(),
resultTy, {applySite.getInstruction()});
newArgs.push_back(castRes.first);
changedCFG |= castRes.second;
++indirectResultArgIter;
}
if (SILType errorTy = substConv.getIndirectErrorResultType(applySite.getFunction()->getTypeExpansionContext())) {
auto errorArgs = applySite.getIndirectSILErrorResults();
ASSERT(errorArgs.size() == 1);
SILValue errorArg = errorArgs[0];
auto castRes = castValueToABICompatibleType(
&builder, pm, loc, errorArg, errorArg->getType(),
errorTy, {applySite.getInstruction()});
newArgs.push_back(castRes.first);
changedCFG |= castRes.second;
}
auto paramArgIter = applySite.getArgumentsWithoutIndirectResults().begin();
// Skip the last parameter, which is `self`. Add it below.
for (auto param : substConv.getParameters()) {
auto paramType =
substConv.getSILType(param, builder.getTypeExpansionContext());
SILValue arg = *paramArgIter;
if (builder.hasOwnership() && arg->getType().isObject() &&
arg->getOwnershipKind() == OwnershipKind::Owned &&
param.isGuaranteedInCaller()) {
SILBuilderWithScope borrowBuilder(applySite.getInstruction(), builder);
arg = borrowBuilder.createBeginBorrow(loc, arg);
newArgBorrows.push_back(arg);
}
auto argCastRes =
castValueToABICompatibleType(&builder, pm, loc, arg,
paramArgIter->getType(), paramType,
{applySite.getInstruction()});
newArgs.push_back(argCastRes.first);
changedCFG |= argCastRes.second;
++paramArgIter;
}
ApplySite newAS;
bool neededCFGChange;
std::tie(newAS, neededCFGChange) = replaceApplySite(
builder, pm, loc, applySite, fri, subs, newArgs, substConv, newArgBorrows);
changedCFG |= neededCFGChange;
FullApplySite newAI = FullApplySite::isa(newAS.getInstruction());
assert(newAI);
LLVM_DEBUG(llvm::dbgs() << " SUCCESS: " << f->getName() << "\n");
if (ore)
ore->emit([&]() {
using namespace OptRemark;
return RemarkPassed("ClassMethodDevirtualized",
*applySite.getInstruction())
<< "Devirtualized call to class method " << NV("Method", f);
});
++NumClassDevirt;
return {newAI, changedCFG};
}
std::pair<FullApplySite, bool> swift::tryDevirtualizeClassMethod(
SILPassManager *pm, FullApplySite applySite, SILValue classInstance, ClassDecl *cd,
CanType classType, OptRemark::Emitter *ore, bool isEffectivelyFinalMethod) {
if (!canDevirtualizeClassMethod(applySite, cd, classType, ore,
isEffectivelyFinalMethod))
return {FullApplySite(), false};
return devirtualizeClassMethod(pm, applySite, classInstance, cd, classType, ore);
}
//===----------------------------------------------------------------------===//
// Witness Method Optimization
//===----------------------------------------------------------------------===//
/// Compute substitutions for making a direct call to a SIL function with
/// @convention(witness_method) convention.
///
/// Such functions have a substituted generic signature where the
/// abstract `Self` parameter from the original type of the protocol
/// requirement is replaced by a concrete type.
///
/// Thus, the original substitutions of the apply instruction that
/// are written in terms of the requirement's generic signature need
/// to be remapped to substitutions suitable for the witness signature.
///
/// Supported remappings are:
///
/// - (Concrete witness thunk) Original substitutions:
/// [Self := ConcreteType, R0 := X0, R1 := X1, ...]
/// - Requirement generic signature:
/// <Self : P, R0, R1, ...>
/// - Witness thunk generic signature:
/// <W0, W1, ...>
/// - Remapped substitutions:
/// [W0 := X0, W1 := X1, ...]
///
/// - (Class witness thunk) Original substitutions:
/// [Self := C<A0, A1>, T0 := X0, T1 := X1, ...]
/// - Requirement generic signature:
/// <Self : P, R0, R1, ...>
/// - Witness thunk generic signature:
/// <Self : C<B0, B1>, B0, B1, W0, W1, ...>
/// - Remapped substitutions:
/// [Self := C<B0, B1>, B0 := A0, B1 := A1, W0 := X0, W1 := X1]
///
/// - (Default witness thunk) Original substitutions:
/// [Self := ConcreteType, R0 := X0, R1 := X1, ...]
/// - Requirement generic signature:
/// <Self : P, R0, R1, ...>
/// - Witness thunk generic signature:
/// <Self : P, W0, W1, ...>
/// - Remapped substitutions:
/// [Self := ConcreteType, W0 := X0, W1 := X1, ...]
///
/// \param conformanceRef The (possibly-specialized) conformance
/// \param requirementSig The generic signature of the requirement
/// \param witnessThunkSig The generic signature of the witness method
/// \param origSubMap The substitutions from the call instruction
/// \param isSelfAbstract True if the Self type of the witness method is
/// still abstract (i.e., not a concrete type).
/// \param classWitness The ClassDecl if this is a class witness method
static SubstitutionMap
getWitnessMethodSubstitutions(
ASTContext &ctx,
ProtocolConformanceRef conformanceRef,
GenericSignature requirementSig,
GenericSignature witnessThunkSig,
SubstitutionMap origSubMap,
bool isSelfAbstract,
ClassDecl *classWitness) {
if (witnessThunkSig.isNull())
return SubstitutionMap();