forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCastOptimizer.cpp
1750 lines (1542 loc) · 63 KB
/
CastOptimizer.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
//===--- CastOptimizer.cpp ------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// This file contains local cast optimizations and simplifications.
///
//===----------------------------------------------------------------------===//
#include "swift/SILOptimizer/Utils/CastOptimizer.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Module.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/Analysis.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/Utils/CFG.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include <deque>
using namespace swift;
//===----------------------------------------------------------------------===//
// ObjC -> Swift Bridging Cast Optimization
//===----------------------------------------------------------------------===//
static SILFunction *
getObjCToSwiftBridgingFunction(SILOptFunctionBuilder &funcBuilder,
SILDynamicCastInst dynamicCast) {
// inline constructor.
auto *bridgeFuncDecl = [&]() -> FuncDecl * {
auto &astContext = dynamicCast.getModule().getASTContext();
if (dynamicCast.isConditional()) {
return astContext.getConditionallyBridgeFromObjectiveCBridgeable();
}
return astContext.getForceBridgeFromObjectiveCBridgeable();
}();
assert(bridgeFuncDecl && "Bridging function doesn't exist?!");
SILDeclRef funcDeclRef(bridgeFuncDecl, SILDeclRef::Kind::Func);
// Lookup a function from the stdlib.
return funcBuilder.getOrCreateFunction(dynamicCast.getLocation(), funcDeclRef,
ForDefinition_t::NotForDefinition);
}
static SubstitutionMap lookupBridgeToObjCProtocolSubs(SILModule &mod,
CanType target) {
auto bridgedProto =
mod.getASTContext().getProtocol(KnownProtocolKind::ObjectiveCBridgeable);
auto conf = *mod.getSwiftModule()->lookupConformance(target, bridgedProto);
return SubstitutionMap::getProtocolSubstitutions(conf.getRequirement(),
target, conf);
}
/// Given that our insertion point is at the cast that we are trying to
/// optimize, convert our incoming value to something that can be passed to the
/// bridge call.
static std::pair<SILValue, SILInstruction *>
convertObjectToLoadableBridgeableType(SILBuilderWithScope &builder,
SILDynamicCastInst dynamicCast,
SILValue src) {
auto *f = dynamicCast.getFunction();
auto loc = dynamicCast.getLocation();
bool isConditional = dynamicCast.isConditional();
SILValue load =
builder.emitLoadValueOperation(loc, src, LoadOwnershipQualifier::Take);
SILType silBridgedTy = *dynamicCast.getLoweredBridgedTargetObjectType();
// If we are not conditional...
if (!isConditional) {
// and our loaded type is our bridged type, just return the load as our
// SILValue and signal to our caller that we did not create a new cast
// instruction by returning nullptr as second.
if (load->getType() == silBridgedTy) {
return {load, nullptr};
}
// Otherwise, just perform an unconditional checked cast to the sil bridged
// ty. We return the cast as our value and as our new cast instruction.
auto *cast =
builder.createUnconditionalCheckedCast(loc, load, silBridgedTy);
return {cast, cast};
}
SILBasicBlock *castSuccessBB =
f->createBasicBlockAfter(dynamicCast.getInstruction()->getParent());
castSuccessBB->createPhiArgument(silBridgedTy, ValueOwnershipKind::Owned);
// If we /are/ conditional and we do not need to bridge the load to the sil,
// then we just create our cast success block and branch from the end of the
// cast instruction block to the cast success block. We leave our insertion
// point in the cast success block since when we return, we are going to
// insert the bridge call/switch there. We return the argument of the cast
// success block as the value to be passed to the bridging function.
if (load->getType() == silBridgedTy) {
castSuccessBB->moveAfter(dynamicCast.getInstruction()->getParent());
builder.createBranch(loc, castSuccessBB, load);
builder.setInsertionPoint(castSuccessBB);
return {castSuccessBB->getArgument(0), nullptr};
}
auto *castFailBB = ([&]() -> SILBasicBlock * {
auto *failureBB = dynamicCast.getFailureBlock();
SILBuilderWithScope failureBBBuilder(&(*failureBB->begin()), builder);
return splitBasicBlockAndBranch(failureBBBuilder, &(*failureBB->begin()),
nullptr, nullptr);
}());
// Now that we have created the failure bb, move our cast success block right
// after the checked_cast_br bb.
castSuccessBB->moveAfter(dynamicCast.getInstruction()->getParent());
// Ok, we need to perform the full cast optimization. This means that we are
// going to replace the cast terminator in inst_block with a checked_cast_br.
auto *ccbi = builder.createCheckedCastBranch(loc, false, load, silBridgedTy,
castSuccessBB, castFailBB);
splitEdge(ccbi, /* EdgeIdx to CastFailBB */ 1);
// Now that we have split the edge to cast fail bb, add the default argument
// for the checked_cast_br. Then we need to handle our error conditions,
// namely we destroy on take_always and otherwise store the value back into
// the memory location that we took it out of.
{
auto *newFailureBlock = ccbi->getFailureBB();
SILValue defaultArg;
if (builder.hasOwnership()) {
defaultArg = newFailureBlock->createPhiArgument(
load->getType(), ValueOwnershipKind::Owned);
} else {
defaultArg = ccbi->getOperand();
}
// This block should be properly terminated already due to our method of
// splitting the failure block, so we can use begin() safely.
SILBuilderWithScope failureBuilder(newFailureBlock->begin());
switch (dynamicCast.getBridgedConsumptionKind()) {
case CastConsumptionKind::TakeAlways:
failureBuilder.emitDestroyValueOperation(loc, defaultArg);
break;
case CastConsumptionKind::TakeOnSuccess:
case CastConsumptionKind::CopyOnSuccess:
// Without ownership, we do not need to consume the taken value.
if (failureBuilder.hasOwnership()) {
failureBuilder.emitStoreValueOperation(loc, defaultArg, src,
StoreOwnershipQualifier::Init);
}
break;
case CastConsumptionKind::BorrowAlways:
llvm_unreachable("this should never occur here");
}
}
builder.setInsertionPoint(castSuccessBB);
return {castSuccessBB->getArgument(0), ccbi};
}
/// Create a call of _forceBridgeFromObjectiveC_bridgeable or
/// _conditionallyBridgeFromObjectiveC_bridgeable which converts an ObjC
/// instance into a corresponding Swift type, conforming to
/// _ObjectiveCBridgeable.
///
/// Control Flow Modification Model
/// ===============================
///
/// NOTE: In the following we assume that our src type is not address only. We
/// do not support optimizing such source types today.
///
/// Unconditional Casts
/// -------------------
///
/// In the case of unconditional casts, we do not touch the CFG at all. We
/// perform the following optimizations:
///
/// 1. If the bridged type and the src type equal, we replace the cast with the
/// apply.
///
/// 2. If src is an address and bridged type has the matching object type to
/// src, just load the value and again replace the cast with the apply.
///
/// 3. If src is an address and after loading still doesn't match bridged type,
/// insert an unconditional_checked_cast before calling the apply.
///
/// Conditional Casts
/// -----------------
///
/// In the case of a conditional const (i.e. checked_cast_addr_br), we transform
/// the following CFG:
///
/// ```
/// InstBlock (checked_cast_addr_br) -> FailureBB -> FailureSucc
/// \
/// \----------------------------> SuccessBB -> SuccessSucc
/// ```
///
/// to a CFG of the following form:
///
/// ```
/// InstBlock (checked_cast_br) -> CastFailBB -> FailureBB -> FailureSucc
/// | ^
/// \-> CastSuccessBB (bridge call + switch) --|
/// |
/// \-> BridgeSuccessBB -> SuccessBB -> SuccessSucc
/// ```
///
/// NOTE: That if the underlying src type matches the type of the underlying
/// bridge source object, we can omit the initial checked_cast_br and just load
/// the value + branch to the CastSuccessBB. This results instead in the
/// following CFG:
///
/// ```
/// InstBlock (br) FailureBB -> FailureSucc
/// | ^
/// \-> CastSuccessBB (bridge call + switch) --|
/// |
/// \-> BridgeSuccessBB -> SuccessBB -> SuccessSucc
/// ```
///
SILInstruction *
CastOptimizer::optimizeBridgedObjCToSwiftCast(SILDynamicCastInst dynamicCast) {
auto kind = dynamicCast.getKind();
(void)kind;
assert(((kind == SILDynamicCastKind::CheckedCastAddrBranchInst) ||
(kind == SILDynamicCastKind::UnconditionalCheckedCastAddrInst)) &&
"Unsupported dynamic cast kind");
CanType target = dynamicCast.getTargetType();
auto &mod = dynamicCast.getModule();
// AnyHashable is a special case that we do not handle since we only handle
// objc targets in this function. Bailout early.
if (auto dt = target.getNominalOrBoundGenericNominal()) {
if (dt == mod.getASTContext().getAnyHashableDecl()) {
return nullptr;
}
}
SILValue src = dynamicCast.getSource();
SILInstruction *Inst = dynamicCast.getInstruction();
auto *F = Inst->getFunction();
// Check if we have a source type that is address only. We do not support that
// today.
if (src->getType().isAddressOnly(*F)) {
return nullptr;
}
bool isConditional = dynamicCast.isConditional();
SILValue Dest = dynamicCast.getDest();
SILBasicBlock *SuccessBB = dynamicCast.getSuccessBlock();
SILBasicBlock *FailureBB = dynamicCast.getFailureBlock();
auto Loc = Inst->getLoc();
// The conformance to _BridgedToObjectiveC is statically known.
// Retrieve the bridging operation to be used if a static conformance
// to _BridgedToObjectiveC can be proven.
SILFunction *bridgingFunc =
getObjCToSwiftBridgingFunction(functionBuilder, dynamicCast);
if (!bridgingFunc)
return nullptr;
auto paramTypes = bridgingFunc->getLoweredFunctionType()->getParameters();
(void)paramTypes;
assert(paramTypes[0].getConvention() ==
ParameterConvention::Direct_Guaranteed &&
"Parameter should be @guaranteed");
SILBuilderWithScope Builder(Inst, builderContext);
// Generate a load for the source argument since as part of our optimization
// we are going to promote the cast to work with objects instead of
// addresses. Additionally, if we have an objc object that is not bridgeable,
// but that could be converted to something that is bridgeable, we try to
// convert to the bridgeable type.
SILValue srcOp;
SILInstruction *newI;
std::tie(srcOp, newI) =
convertObjectToLoadableBridgeableType(Builder, dynamicCast, src);
// Now emit the a cast from the casted ObjC object into a target type.
// This is done by means of calling _forceBridgeFromObjectiveC or
// _conditionallyBridgeFromObjectiveC_bridgeable from the Target type.
auto *funcRef = Builder.createFunctionRefFor(Loc, bridgingFunc);
SubstitutionMap subMap = lookupBridgeToObjCProtocolSubs(mod, target);
auto MetaTy = MetatypeType::get(target, MetatypeRepresentation::Thick);
auto SILMetaTy = F->getTypeLowering(MetaTy).getLoweredType();
auto *MetaTyVal = Builder.createMetatype(Loc, SILMetaTy);
// Temporary to hold the intermediate result.
AllocStackInst *Tmp = nullptr;
CanType OptionalTy;
SILValue outOptionalParam;
if (isConditional) {
// Create a temporary
OptionalTy = OptionalType::get(Dest->getType().getASTType())
->getImplementationType()
->getCanonicalType();
Tmp = Builder.createAllocStack(Loc,
SILType::getPrimitiveObjectType(OptionalTy));
outOptionalParam = Tmp;
} else {
outOptionalParam = Dest;
}
// Emit a retain.
SILValue srcArg = Builder.emitCopyValueOperation(Loc, srcOp);
SmallVector<SILValue, 1> Args;
Args.push_back(outOptionalParam);
Args.push_back(srcArg);
Args.push_back(MetaTyVal);
auto *AI = Builder.createApply(Loc, funcRef, subMap, Args);
// If we have guaranteed normal arguments, insert the destroy.
//
// TODO: Is it safe to just eliminate the initial retain?
Builder.emitDestroyOperation(Loc, srcArg);
// If we have an unconditional_checked_cast_addr, return early. We do not need
// to handle any conditional code.
if (isa<UnconditionalCheckedCastAddrInst>(Inst)) {
// Destroy the source value as unconditional_checked_cast_addr would.
Builder.emitDestroyOperation(Loc, srcOp);
eraseInstAction(Inst);
return (newI) ? newI : AI;
}
auto *CCABI = cast<CheckedCastAddrBranchInst>(Inst);
switch (CCABI->getConsumptionKind()) {
case CastConsumptionKind::TakeAlways:
Builder.emitDestroyOperation(Loc, srcOp);
break;
case CastConsumptionKind::TakeOnSuccess: {
{
// Insert a release in the success BB.
SILBuilderWithScope successBuilder(SuccessBB->begin());
successBuilder.emitDestroyOperation(Loc, srcOp);
}
{
// And a store in the failure BB.
if (Builder.hasOwnership()) {
SILBuilderWithScope failureBuilder(FailureBB->begin());
SILValue writeback = srcOp;
SILType srcType = src->getType().getObjectType();
if (writeback->getType() != srcType) {
writeback =
failureBuilder.createUncheckedRefCast(Loc, writeback, srcType);
}
failureBuilder.emitStoreValueOperation(Loc, writeback, src,
StoreOwnershipQualifier::Init);
}
}
break;
}
case CastConsumptionKind::BorrowAlways:
llvm_unreachable("checked_cast_addr_br never has BorrowAlways");
case CastConsumptionKind::CopyOnSuccess:
// If we are performing copy_on_success, store the value back into memory
// here since we loaded it. We may need to cast back to the actual
// underlying type.
if (Builder.hasOwnership()) {
SILValue writeback = srcOp;
SILType srcType = src->getType().getObjectType();
if (writeback->getType() != srcType) {
writeback = Builder.createUncheckedRefCast(Loc, writeback, srcType);
}
Builder.emitStoreValueOperation(Loc, writeback, src,
StoreOwnershipQualifier::Init);
}
break;
}
// Results should be checked in case we process a conditional
// case. E.g. casts from NSArray into [SwiftType] may fail, i.e. return .None.
if (isConditional) {
// Copy the temporary into Dest.
// Load from the optional.
auto *SomeDecl = Builder.getASTContext().getOptionalSomeDecl();
auto *BridgeSuccessBB =
Inst->getFunction()->createBasicBlockAfter(Builder.getInsertionBB());
SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 2> CaseBBs;
CaseBBs.emplace_back(SomeDecl, BridgeSuccessBB);
CaseBBs.emplace_back(mod.getASTContext().getOptionalNoneDecl(), FailureBB);
Builder.createSwitchEnumAddr(Loc, outOptionalParam, nullptr, CaseBBs);
Builder.setInsertionPoint(FailureBB->begin());
Builder.createDeallocStack(Loc, Tmp);
Builder.setInsertionPoint(BridgeSuccessBB);
auto Addr = Builder.createUncheckedTakeEnumDataAddr(Loc, outOptionalParam,
SomeDecl);
Builder.createCopyAddr(Loc, Addr, Dest, IsTake, IsInitialization);
Builder.createDeallocStack(Loc, Tmp);
SmallVector<SILValue, 1> SuccessBBArgs;
Builder.createBranch(Loc, SuccessBB, SuccessBBArgs);
}
eraseInstAction(Inst);
return (newI) ? newI : AI;
}
//===----------------------------------------------------------------------===//
// Swift -> ObjC Bridging Cast Optimization
//===----------------------------------------------------------------------===//
static bool canOptimizeCast(const swift::Type &BridgedTargetTy,
swift::SILModule &M,
swift::SILFunctionConventions &substConv) {
// DestTy is the type which we want to convert to
SILType DestTy =
SILType::getPrimitiveObjectType(BridgedTargetTy->getCanonicalType());
// ConvTy is the return type of the _bridgeToObjectiveCImpl()
auto ConvTy = substConv.getSILResultType().getObjectType();
if (ConvTy == DestTy) {
// Destination is the same type
return true;
}
// Check if a superclass/subclass of the source operand
if (DestTy.isExactSuperclassOf(ConvTy)) {
return true;
}
if (ConvTy.isExactSuperclassOf(DestTy)) {
return true;
}
// check if it is a bridgeable CF type
if (ConvTy.getASTType() ==
getNSBridgedClassOfCFClass(M.getSwiftModule(),
DestTy.getASTType())) {
return true;
}
if (DestTy.getASTType() ==
getNSBridgedClassOfCFClass(M.getSwiftModule(),
ConvTy.getASTType())) {
return true;
}
// All else failed - can't optimize this case
return false;
}
static Optional<std::pair<SILFunction *, SubstitutionMap>>
findBridgeToObjCFunc(SILOptFunctionBuilder &functionBuilder,
SILDynamicCastInst dynamicCast) {
CanType sourceType = dynamicCast.getSourceType();
auto loc = dynamicCast.getLocation();
auto &mod = dynamicCast.getModule();
auto bridgedProto =
mod.getASTContext().getProtocol(KnownProtocolKind::ObjectiveCBridgeable);
auto conf = mod.getSwiftModule()->lookupConformance(sourceType, bridgedProto);
assert(conf && "_ObjectiveCBridgeable conformance should exist");
(void)conf;
// Generate code to invoke _bridgeToObjectiveC
auto *ntd = sourceType.getNominalOrBoundGenericNominal();
assert(ntd);
auto members = ntd->lookupDirect(mod.getASTContext().Id_bridgeToObjectiveC);
if (members.empty()) {
SmallVector<ValueDecl *, 4> foundMembers;
if (ntd->getDeclContext()->lookupQualified(
ntd, mod.getASTContext().Id_bridgeToObjectiveC,
NLOptions::NL_ProtocolMembers, foundMembers)) {
// Returned members are starting with the most specialized ones.
// Thus, the first element is what we are looking for.
members.push_back(foundMembers.front());
}
}
// There should be exactly one implementation of _bridgeToObjectiveC.
if (members.size() != 1)
return None;
auto bridgeFuncDecl = members.front();
ModuleDecl *modDecl =
mod.getASTContext().getLoadedModule(mod.getASTContext().Id_Foundation);
if (!modDecl)
return None;
SmallVector<ValueDecl *, 2> results;
modDecl->lookupMember(results, sourceType.getNominalOrBoundGenericNominal(),
mod.getASTContext().Id_bridgeToObjectiveC,
Identifier());
ArrayRef<ValueDecl *> resultsRef(results);
if (resultsRef.empty()) {
mod.getSwiftModule()->lookupMember(
results, sourceType.getNominalOrBoundGenericNominal(),
mod.getASTContext().Id_bridgeToObjectiveC, Identifier());
resultsRef = results;
}
if (resultsRef.size() != 1)
return None;
auto *resultDecl = results.front();
auto memberDeclRef = SILDeclRef(resultDecl);
auto *bridgedFunc = functionBuilder.getOrCreateFunction(
loc, memberDeclRef, ForDefinition_t::NotForDefinition);
// Get substitutions, if source is a bound generic type.
auto subMap = sourceType->getContextSubstitutionMap(
mod.getSwiftModule(), bridgeFuncDecl->getDeclContext());
// Implementation of _bridgeToObjectiveC could not be found.
if (!bridgedFunc)
return None;
if (dynamicCast.getFunction()->isSerialized() &&
!bridgedFunc->hasValidLinkageForFragileRef())
return None;
if (bridgedFunc->getLoweredFunctionType()
->getSingleResult()
.isFormalIndirect())
return None;
return std::make_pair(bridgedFunc, subMap);
}
static SILValue computeFinalCastedValue(SILBuilderWithScope &builder,
SILDynamicCastInst dynamicCast,
ApplyInst *newAI) {
SILValue dest = dynamicCast.getDest();
auto loc = dynamicCast.getLocation();
auto convTy = newAI->getType();
bool isConditional = dynamicCast.isConditional();
auto destTy = dest->getType().getObjectType();
assert(destTy == dynamicCast.getLoweredBridgedTargetObjectType() &&
"Expected Dest Type to be the same as BridgedTargetTy");
auto &m = dynamicCast.getModule();
if (convTy == destTy) {
return newAI;
}
if (destTy.isExactSuperclassOf(convTy)) {
return builder.createUpcast(loc, newAI, destTy);
}
if (convTy.isExactSuperclassOf(destTy)) {
// If we are not conditional, we are ok with the downcast via checked cast
// fails since we will trap.
if (!isConditional) {
return builder.createUnconditionalCheckedCast(loc, newAI, destTy);
}
// Otherwise if we /are/ emitting a conditional cast, make sure that we
// handle the failure gracefully.
//
// Since we are being returned the value at +1, we need to destroy the
// newAI on failure.
auto *failureBB = dynamicCast.getFailureBlock();
{
SILBuilderWithScope innerBuilder(&*failureBB->begin(), builder);
auto valueToDestroy = ([&]() -> SILValue {
if (!innerBuilder.hasOwnership())
return newAI;
return failureBB->createPhiArgument(newAI->getType(),
ValueOwnershipKind::Owned);
}());
innerBuilder.emitDestroyOperation(loc, valueToDestroy);
}
auto *condBrSuccessBB =
newAI->getFunction()->createBasicBlockAfter(newAI->getParent());
condBrSuccessBB->createPhiArgument(destTy, ValueOwnershipKind::Owned);
builder.createCheckedCastBranch(loc, /* isExact*/ false, newAI, destTy,
condBrSuccessBB, failureBB);
builder.setInsertionPoint(condBrSuccessBB, condBrSuccessBB->begin());
return condBrSuccessBB->getArgument(0);
}
if (convTy.getASTType() ==
getNSBridgedClassOfCFClass(m.getSwiftModule(), destTy.getASTType()) ||
destTy.getASTType() ==
getNSBridgedClassOfCFClass(m.getSwiftModule(), convTy.getASTType())) {
// Handle NS <-> CF toll-free bridging here.
return SILValue(builder.createUncheckedRefCast(loc, newAI, destTy));
}
llvm_unreachable(
"optimizeBridgedSwiftToObjCCast: should never reach this condition: if "
"the Destination does not have the same type, is not a bridgeable CF "
"type and isn't a superclass/subclass of the source operand we should "
"have bailed earlier.");
}
/// Create a call of _bridgeToObjectiveC which converts an _ObjectiveCBridgeable
/// instance into a bridged ObjC type.
SILInstruction *
CastOptimizer::optimizeBridgedSwiftToObjCCast(SILDynamicCastInst dynamicCast) {
SILInstruction *Inst = dynamicCast.getInstruction();
const SILFunction *F = Inst->getFunction();
CastConsumptionKind ConsumptionKind = dynamicCast.getBridgedConsumptionKind();
bool isConditional = dynamicCast.isConditional();
SILValue Src = dynamicCast.getSource();
SILValue Dest = dynamicCast.getDest();
CanType BridgedTargetTy = dynamicCast.getBridgedTargetType();
SILBasicBlock *SuccessBB = dynamicCast.getSuccessBlock();
SILBasicBlock *FailureBB = dynamicCast.getFailureBlock();
auto &M = Inst->getModule();
auto Loc = Inst->getLoc();
bool AddressOnlyType = false;
if (!Src->getType().isLoadable(*F) || !Dest->getType().isLoadable(*F)) {
AddressOnlyType = true;
}
// Find the _BridgedToObjectiveC protocol.
SILFunction *bridgedFunc = nullptr;
SubstitutionMap subMap;
{
auto result = findBridgeToObjCFunc(functionBuilder, dynamicCast);
if (!result)
return nullptr;
std::tie(bridgedFunc, subMap) = result.getValue();
}
SILType SubstFnTy = bridgedFunc->getLoweredType().substGenericArgs(M, subMap);
SILFunctionConventions substConv(SubstFnTy.castTo<SILFunctionType>(), M);
// Check that this is a case that the authors of this code thought it could
// handle.
if (!canOptimizeCast(BridgedTargetTy, M, substConv)) {
return nullptr;
}
SILBuilderWithScope Builder(Inst, builderContext);
auto FnRef = Builder.createFunctionRefFor(Loc, bridgedFunc);
auto ParamTypes = SubstFnTy.castTo<SILFunctionType>()->getParameters();
SILValue oldSrc;
if (Src->getType().isAddress() && !substConv.isSILIndirect(ParamTypes[0])) {
// Create load
oldSrc = Src;
Src =
Builder.emitLoadValueOperation(Loc, Src, LoadOwnershipQualifier::Take);
}
// Compensate different owning conventions of the replaced cast instruction
// and the inserted conversion function.
bool needReleaseAfterCall = false;
bool needReleaseInSuccess = false;
switch (ParamTypes[0].getConvention()) {
case ParameterConvention::Direct_Guaranteed:
case ParameterConvention::Indirect_In_Guaranteed:
switch (ConsumptionKind) {
case CastConsumptionKind::TakeAlways:
needReleaseAfterCall = true;
break;
case CastConsumptionKind::TakeOnSuccess:
needReleaseInSuccess = true;
break;
case CastConsumptionKind::BorrowAlways:
llvm_unreachable("Should never hit this");
case CastConsumptionKind::CopyOnSuccess:
// We assume that our caller is correct and will treat our argument as
// being immutable, so we do not need to do anything here.
break;
}
break;
case ParameterConvention::Direct_Owned:
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_In_Constant:
// Currently this
// cannot appear, because the _bridgeToObjectiveC protocol witness method
// always receives the this pointer (= the source) as guaranteed.
// If it became possible (perhaps with the advent of ownership and
// explicit +1 annotations), the implementation should look something
// like this:
/*
switch (ConsumptionKind) {
case CastConsumptionKind::TakeAlways:
break;
case CastConsumptionKind::TakeOnSuccess:
needRetainBeforeCall = true;
needReleaseInSuccess = true;
break;
case CastConsumptionKind::CopyOnSuccess:
needRetainBeforeCall = true;
break;
}
break;
*/
llvm_unreachable("this should never happen so is currently untestable");
case ParameterConvention::Direct_Unowned:
assert(!AddressOnlyType &&
"AddressOnlyType with Direct_Unowned is not supported");
break;
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_InoutAliasable:
// TODO handle remaining indirect argument types
return nullptr;
}
// Generate a code to invoke the bridging function.
auto *NewAI = Builder.createApply(Loc, FnRef, subMap, Src);
// First if we are going to destroy the value unconditionally, just insert the
// destroy right after the call. This handles some of the conditional cases
// and /all/ of the consuming unconditional cases.
if (needReleaseAfterCall) {
Builder.emitDestroyOperation(Loc, Src);
} else {
if (SuccessBB) {
SILBuilderWithScope succBuilder(&*SuccessBB->begin(), Builder);
if (needReleaseInSuccess) {
succBuilder.emitDestroyOperation(Loc, Src);
} else {
if (oldSrc) {
succBuilder.emitStoreValueOperation(Loc, Src, oldSrc,
StoreOwnershipQualifier::Init);
}
}
SILBuilderWithScope failBuilder(&*FailureBB->begin(), Builder);
if (oldSrc) {
failBuilder.emitStoreValueOperation(Loc, Src, oldSrc,
StoreOwnershipQualifier::Init);
}
} else {
if (oldSrc) {
Builder.emitStoreValueOperation(Loc, Src, oldSrc,
StoreOwnershipQualifier::Init);
}
}
}
if (!Dest)
return NewAI;
// If it is addr cast then store the result into the dest.
//
// NOTE: We assume that dest was uninitialized when passed to us.
SILValue castedValue = computeFinalCastedValue(Builder, dynamicCast, NewAI);
auto qual = Builder.hasOwnership() ? StoreOwnershipQualifier::Init
: StoreOwnershipQualifier::Unqualified;
SILInstruction *NewI = Builder.createStore(Loc, castedValue, Dest, qual);
if (isConditional && NewI->getParent() != NewAI->getParent()) {
Builder.createBranch(Loc, SuccessBB);
}
eraseInstAction(Inst);
return NewI;
}
//===----------------------------------------------------------------------===//
// Top Level Bridge Cast Optimization Entrypoint
//===----------------------------------------------------------------------===//
/// Make use of the fact that some of these casts cannot fail. For
/// example, if the ObjC type is exactly the expected _ObjectiveCType
/// type, then it would always succeed for NSString, NSNumber, etc.
/// Casts from NSArray, NSDictionary and NSSet may fail.
///
/// If ObjC class is not exactly _ObjectiveCType, then its conversion
/// to a required _ObjectiveCType may fail.
SILInstruction *
CastOptimizer::optimizeBridgedCasts(SILDynamicCastInst dynamicCast) {
CanType source = dynamicCast.getSourceType();
CanType target = dynamicCast.getTargetType();
auto &M = dynamicCast.getModule();
// To apply the bridged optimizations, we should ensure that types are not
// existential (and keep in mind that generic parameters can be existentials),
// and that one of the types is a class and another one is a struct.
if (source.isAnyExistentialType() || target.isAnyExistentialType() ||
source->is<ArchetypeType>() || target->is<ArchetypeType>() ||
(source.getClassOrBoundGenericClass() &&
!target.getStructOrBoundGenericStruct()) ||
(target.getClassOrBoundGenericClass() &&
!source.getStructOrBoundGenericStruct()))
return nullptr;
// Casts involving non-bound generic types cannot be optimized.
if (source->hasArchetype() || target->hasArchetype())
return nullptr;
CanType CanBridgedSourceTy = dynamicCast.getBridgedSourceType();
CanType CanBridgedTargetTy = dynamicCast.getBridgedTargetType();
// If we were unable to bridge either of our source/target types, return
// nullptr.
if (!CanBridgedSourceTy || !CanBridgedTargetTy)
return nullptr;
if (CanBridgedSourceTy == source && CanBridgedTargetTy == target) {
// Both source and target type are ObjC types.
return nullptr;
}
if (CanBridgedSourceTy != source && CanBridgedTargetTy != target) {
// Both source and target type are Swift types.
return nullptr;
}
if ((CanBridgedSourceTy && CanBridgedSourceTy->getAnyNominal() ==
M.getASTContext().getNSErrorDecl()) ||
(CanBridgedTargetTy && CanBridgedSourceTy->getAnyNominal() ==
M.getASTContext().getNSErrorDecl())) {
// FIXME: Can't optimize bridging with NSError.
return nullptr;
}
// Check what kind of conversion it is? ObjC->Swift or Swift-ObjC?
if (CanBridgedTargetTy != target) {
// This is an ObjC to Swift cast.
return optimizeBridgedObjCToSwiftCast(dynamicCast);
} else {
// This is a Swift to ObjC cast
return optimizeBridgedSwiftToObjCCast(dynamicCast);
}
llvm_unreachable("Unknown kind of bridging");
}
//===----------------------------------------------------------------------===//
// Cast Optimizer Public API
//===----------------------------------------------------------------------===//
SILInstruction *CastOptimizer::simplifyCheckedCastAddrBranchInst(
CheckedCastAddrBranchInst *Inst) {
if (auto *I = optimizeCheckedCastAddrBranchInst(Inst))
Inst = dyn_cast<CheckedCastAddrBranchInst>(I);
if (!Inst)
return nullptr;
SILDynamicCastInst dynamicCast(Inst);
auto Loc = dynamicCast.getLocation();
auto Src = dynamicCast.getSource();
auto Dest = dynamicCast.getDest();
auto *SuccessBB = dynamicCast.getSuccessBlock();
auto *FailureBB = dynamicCast.getFailureBlock();
SILBuilderWithScope Builder(Inst, builderContext);
// Check if we can statically predict the outcome of the cast.
auto Feasibility =
dynamicCast.classifyFeasibility(true /*allow whole module*/);
if (Feasibility == DynamicCastFeasibility::WillFail) {
if (shouldDestroyOnFailure(Inst->getConsumptionKind())) {
auto &srcTL = Builder.getTypeLowering(Src->getType());
srcTL.emitDestroyAddress(Builder, Loc, Src);
}
auto NewI = Builder.createBranch(Loc, FailureBB);
eraseInstAction(Inst);
willFailAction();
return NewI;
}
bool ResultNotUsed = isa<AllocStackInst>(Dest);
if (ResultNotUsed) {
for (auto Use : Dest->getUses()) {
auto *User = Use->getUser();
if (isa<DeallocStackInst>(User) || User == Inst)
continue;
ResultNotUsed = false;
break;
}
}
auto *BB = Inst->getParent();
SILInstruction *BridgedI = nullptr;
// To apply the bridged optimizations, we should
// ensure that types are not existential,
// and that not both types are classes.
BridgedI = optimizeBridgedCasts(dynamicCast);
if (!BridgedI) {
// If the cast may succeed or fail, and it can't be optimized into a
// bridging operation, then let it be.
if (Feasibility == DynamicCastFeasibility::MaySucceed) {
return nullptr;
}
assert(Feasibility == DynamicCastFeasibility::WillSucceed);
// Replace by unconditional_addr_cast, followed by a branch.
// The unconditional_addr_cast can be skipped, if the result of a cast
// is not used afterwards.
if (ResultNotUsed) {
if (shouldTakeOnSuccess(Inst->getConsumptionKind())) {
auto &srcTL = Builder.getTypeLowering(Src->getType());
srcTL.emitDestroyAddress(Builder, Loc, Src);
}
eraseInstAction(Inst);
Builder.setInsertionPoint(BB);
auto *NewI = Builder.createBranch(Loc, SuccessBB);
willSucceedAction();
return NewI;
}
// Since it is an addr cast, only address types are handled here.
if (!Src->getType().isAddress() || !Dest->getType().isAddress()) {
return nullptr;
}
// For CopyOnSuccess casts, we could insert an explicit copy here, but this
// case does not happen in practice.
//
// Both TakeOnSuccess and TakeAlways can be reduced to an
// UnconditionalCheckedCast, since the failure path is irrelevant.
switch (Inst->getConsumptionKind()) {
case CastConsumptionKind::BorrowAlways:
llvm_unreachable("checked_cast_addr_br never has BorrowAlways");
case CastConsumptionKind::CopyOnSuccess:
return nullptr;
case CastConsumptionKind::TakeAlways:
case CastConsumptionKind::TakeOnSuccess:
break;
}
if (!emitSuccessfulIndirectUnconditionalCast(Builder, Loc, dynamicCast)) {
// No optimization was possible.
return nullptr;
}
eraseInstAction(Inst);
}
SILInstruction *NewI = &BB->back();
if (!isa<TermInst>(NewI)) {
Builder.setInsertionPoint(BB);
NewI = Builder.createBranch(Loc, SuccessBB);
}
willSucceedAction();
return NewI;
}
SILInstruction *
CastOptimizer::simplifyCheckedCastBranchInst(CheckedCastBranchInst *Inst) {
if (Inst->isExact()) {
SILDynamicCastInst dynamicCast(Inst);
auto *ARI = dyn_cast<AllocRefInst>(stripUpCasts(dynamicCast.getSource()));
if (!ARI)
return nullptr;
// We know the dynamic type of the operand.
SILBuilderWithScope Builder(Inst, builderContext);
auto Loc = dynamicCast.getLocation();
if (ARI->getType() == dynamicCast.getLoweredTargetType()) {
// This exact cast will succeed.
SmallVector<SILValue, 1> Args;
Args.push_back(ARI);
auto *NewI =
Builder.createBranch(Loc, dynamicCast.getSuccessBlock(), Args);
eraseInstAction(Inst);
willSucceedAction();
return NewI;
}
// This exact cast will fail. With ownership enabled, we pass a copy of the
// original casts value to the failure block.
TinyPtrVector<SILValue> Args;
if (Builder.hasOwnership())
Args.push_back(dynamicCast.getSource());
auto *NewI = Builder.createBranch(Loc, dynamicCast.getFailureBlock(), Args);
eraseInstAction(Inst);
willFailAction();
return NewI;
}
if (auto *I = optimizeCheckedCastBranchInst(Inst))
Inst = dyn_cast<CheckedCastBranchInst>(I);
if (!Inst)
return nullptr;