-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathRegionAnalysis.cpp
3905 lines (3345 loc) · 148 KB
/
RegionAnalysis.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
//===--- RegionAnalysis.cpp -----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 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 "send-non-sendable"
#include "swift/SILOptimizer/Analysis/RegionAnalysis.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Type.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/FrozenMultiMap.h"
#include "swift/Basic/ImmutablePointerSet.h"
#include "swift/Basic/SmallBitVector.h"
#include "swift/SIL/BasicBlockData.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/NodeDatastructures.h"
#include "swift/SIL/OperandDatastructures.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/PatternMatch.h"
#include "swift/SIL/PrunedLiveness.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/Test.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/PartitionUtils.h"
#include "swift/SILOptimizer/Utils/VariableNameUtils.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace swift::PartitionPrimitives;
using namespace swift::PatternMatch;
using namespace swift::regionanalysisimpl;
bool swift::regionanalysisimpl::AbortOnUnknownPatternMatchError = false;
static llvm::cl::opt<bool, true> AbortOnUnknownPatternMatchErrorCmdLine(
"sil-region-isolation-assert-on-unknown-pattern",
llvm::cl::desc("Abort if SIL region isolation detects an unknown pattern. "
"Intended only to be used when debugging the compiler!"),
llvm::cl::Hidden,
llvm::cl::location(
swift::regionanalysisimpl::AbortOnUnknownPatternMatchError));
//===----------------------------------------------------------------------===//
// MARK: Utilities
//===----------------------------------------------------------------------===//
namespace {
using OperandRefRangeTransform = std::function<Operand *(Operand &)>;
using OperandRefRange =
iterator_range<llvm::mapped_iterator<MutableArrayRef<Operand>::iterator,
OperandRefRangeTransform>>;
} // anonymous namespace
static OperandRefRange makeOperandRefRange(MutableArrayRef<Operand> input) {
auto toOperand = [](Operand &operand) { return &operand; };
auto baseRange = llvm::make_range(input.begin(), input.end());
return llvm::map_range(baseRange, OperandRefRangeTransform(toOperand));
}
std::optional<ApplyIsolationCrossing>
regionanalysisimpl::getApplyIsolationCrossing(SILInstruction *inst) {
if (ApplyExpr *apply = inst->getLoc().getAsASTNode<ApplyExpr>())
if (auto crossing = apply->getIsolationCrossing())
return crossing;
if (auto fas = FullApplySite::isa(inst)) {
if (auto crossing = fas.getIsolationCrossing())
return crossing;
}
return {};
}
namespace {
struct UseDefChainVisitor
: public AccessUseDefChainVisitor<UseDefChainVisitor, SILValue> {
bool isMerge = false;
/// The actor isolation that we found while walking from use->def. Always set
/// to the first one encountered.
std::optional<ActorIsolation> actorIsolation;
SILValue visitAll(SILValue sourceAddr) {
SILValue result = visit(sourceAddr);
if (!result)
return sourceAddr;
while (SILValue nextAddr = visit(result))
result = nextAddr;
return result;
}
SILValue visitBase(SILValue base, AccessStorage::Kind kind) {
// If we are passed a project_box, we want to return the box itself. The
// reason for this is that the project_box is considered to be non-aliasing
// memory. We want to treat it as part of the box which is
// aliasing... meaning that we need to merge.
if (kind == AccessStorage::Box)
return cast<ProjectBoxInst>(base)->getOperand();
return SILValue();
}
SILValue visitNonAccess(SILValue) { return SILValue(); }
SILValue visitPhi(SILPhiArgument *phi) {
llvm_unreachable("Should never hit this");
}
// Override AccessUseDefChainVisitor to ignore access markers and find the
// outer access base.
SILValue visitNestedAccess(BeginAccessInst *access) {
return visitAll(access->getSource());
}
SILValue visitStorageCast(SingleValueInstruction *cast, Operand *sourceAddr,
AccessStorageCast castType) {
// If this is a type case, see if the result of the cast is sendable. In
// such a case, we do not want to look through this cast.
if (castType == AccessStorageCast::Type &&
!SILIsolationInfo::isNonSendableType(cast->getType(),
cast->getFunction()))
return SILValue();
// Do not look through begin_borrow [var_decl]. They are start new semantic
// values.
//
// This only comes up if a codegen pattern occurs where the debug
// information is place on a debug_value instead of the alloc_box.
if (auto *bbi = dyn_cast<BeginBorrowInst>(cast)) {
if (bbi->isFromVarDecl())
return SILValue();
}
// If we do not have an identity cast, mark this as a merge.
isMerge |= castType != AccessStorageCast::Identity;
return sourceAddr->get();
}
SILValue visitAccessProjection(SingleValueInstruction *inst,
Operand *sourceAddr) {
// See if this access projection is into a single element value. If so, we
// do not want to treat this as a merge.
if (auto p = Projection(inst)) {
switch (p.getKind()) {
// Currently if we load and then project_box from a memory location,
// we treat that as a projection. This follows the semantics/notes in
// getAccessProjectionOperand.
case ProjectionKind::Box:
return cast<ProjectBoxInst>(inst)->getOperand();
case ProjectionKind::Upcast:
case ProjectionKind::RefCast:
case ProjectionKind::BlockStorageCast:
case ProjectionKind::BitwiseCast:
case ProjectionKind::Class:
case ProjectionKind::TailElems:
llvm_unreachable("Shouldn't see this here");
case ProjectionKind::Index:
// Index is always a merge.
isMerge = true;
break;
case ProjectionKind::Enum: {
auto op = cast<UncheckedTakeEnumDataAddrInst>(inst)->getOperand();
// See if our operand type is a sendable type. In such a case, we do not
// want to look through our operand.
if (!SILIsolationInfo::isNonSendableType(op->getType(),
op->getFunction()))
return SILValue();
break;
}
case ProjectionKind::Tuple: {
// These are merges if we have multiple fields.
auto op = cast<TupleElementAddrInst>(inst)->getOperand();
if (!SILIsolationInfo::isNonSendableType(op->getType(),
op->getFunction()))
return SILValue();
isMerge |= op->getType().getNumTupleElements() > 1;
break;
}
case ProjectionKind::Struct:
auto op = cast<StructElementAddrInst>(inst)->getOperand();
// See if our result type is a sendable type. In such a case, we do not
// want to look through the struct_element_addr since we do not want to
// identify the sendable type with the non-sendable operand. These we
// are always going to ignore anyways since a sendable let/var field of
// a struct can always be used.
if (!SILIsolationInfo::isNonSendableType(op->getType(),
op->getFunction()))
return SILValue();
// These are merges if we have multiple fields.
isMerge |= op->getType().getNumNominalFields() > 1;
break;
}
}
return sourceAddr->get();
}
};
} // namespace
/// Classify an instructions as look through when we are looking through
/// values. We assert that all instructions that are CONSTANT_TRANSLATION
/// LookThrough to make sure they stay in sync.
static bool isStaticallyLookThroughInst(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::BeginAccessInst:
case SILInstructionKind::BeginCOWMutationInst:
case SILInstructionKind::BeginDeallocRefInst:
case SILInstructionKind::BridgeObjectToRefInst:
case SILInstructionKind::CopyValueInst:
case SILInstructionKind::CopyableToMoveOnlyWrapperAddrInst:
case SILInstructionKind::CopyableToMoveOnlyWrapperValueInst:
case SILInstructionKind::DestructureStructInst:
case SILInstructionKind::DestructureTupleInst:
case SILInstructionKind::DifferentiableFunctionExtractInst:
case SILInstructionKind::DropDeinitInst:
case SILInstructionKind::EndCOWMutationInst:
case SILInstructionKind::EndInitLetRefInst:
case SILInstructionKind::ExplicitCopyValueInst:
case SILInstructionKind::InitEnumDataAddrInst:
case SILInstructionKind::LinearFunctionExtractInst:
case SILInstructionKind::MarkDependenceInst:
case SILInstructionKind::MarkUninitializedInst:
case SILInstructionKind::MarkUnresolvedNonCopyableValueInst:
case SILInstructionKind::MarkUnresolvedReferenceBindingInst:
case SILInstructionKind::MoveOnlyWrapperToCopyableAddrInst:
case SILInstructionKind::MoveOnlyWrapperToCopyableBoxInst:
case SILInstructionKind::MoveOnlyWrapperToCopyableValueInst:
case SILInstructionKind::OpenExistentialAddrInst:
case SILInstructionKind::OpenExistentialValueInst:
case SILInstructionKind::ProjectBlockStorageInst:
case SILInstructionKind::ProjectBoxInst:
case SILInstructionKind::RefToBridgeObjectInst:
case SILInstructionKind::RefToUnownedInst:
case SILInstructionKind::UncheckedRefCastInst:
case SILInstructionKind::UncheckedTakeEnumDataAddrInst:
case SILInstructionKind::UnownedCopyValueInst:
case SILInstructionKind::UnownedToRefInst:
case SILInstructionKind::UpcastInst:
case SILInstructionKind::ValueToBridgeObjectInst:
case SILInstructionKind::WeakCopyValueInst:
case SILInstructionKind::StrongCopyWeakValueInst:
case SILInstructionKind::StrongCopyUnmanagedValueInst:
case SILInstructionKind::RefToUnmanagedInst:
case SILInstructionKind::UnmanagedToRefInst:
case SILInstructionKind::InitExistentialValueInst:
return true;
case SILInstructionKind::MoveValueInst:
// Look through if it isn't from a var decl.
return !cast<MoveValueInst>(inst)->isFromVarDecl();
case SILInstructionKind::BeginBorrowInst:
// Look through if it isn't from a var decl.
return !cast<BeginBorrowInst>(inst)->isFromVarDecl();
case SILInstructionKind::UnconditionalCheckedCastInst: {
auto cast = SILDynamicCastInst::getAs(inst);
assert(cast);
if (cast.isRCIdentityPreserving())
return true;
return false;
}
}
}
static bool isLookThroughIfResultNonSendable(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::RawPointerToRefInst:
return true;
}
}
static bool isLookThroughIfOperandNonSendable(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::RefToRawPointerInst:
return true;
}
}
static bool isLookThroughIfOperandAndResultNonSendable(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::UncheckedTrivialBitCastInst:
case SILInstructionKind::UncheckedBitwiseCastInst:
case SILInstructionKind::UncheckedValueCastInst:
case SILInstructionKind::StructElementAddrInst:
case SILInstructionKind::TupleElementAddrInst:
case SILInstructionKind::UncheckedTakeEnumDataAddrInst:
return true;
}
}
namespace {
struct TermArgSources {
SmallFrozenMultiMap<SILValue, Operand *, 8> argSources;
template <typename ValueRangeTy = ArrayRef<Operand *>>
void addValues(ValueRangeTy valueRange, SILBasicBlock *destBlock) {
for (auto pair : llvm::enumerate(valueRange))
argSources.insert(destBlock->getArgument(pair.index()), pair.value());
}
TermArgSources() {}
void init(SILInstruction *inst) {
switch (cast<TermInst>(inst)->getTermKind()) {
case TermKind::UnreachableInst:
case TermKind::ReturnInst:
case TermKind::ThrowInst:
case TermKind::ThrowAddrInst:
case TermKind::YieldInst:
case TermKind::UnwindInst:
case TermKind::TryApplyInst:
case TermKind::SwitchValueInst:
case TermKind::SwitchEnumInst:
case TermKind::SwitchEnumAddrInst:
case TermKind::AwaitAsyncContinuationInst:
case TermKind::CheckedCastAddrBranchInst:
llvm_unreachable("Unsupported?!");
case TermKind::BranchInst:
return init(cast<BranchInst>(inst));
case TermKind::CondBranchInst:
return init(cast<CondBranchInst>(inst));
case TermKind::DynamicMethodBranchInst:
return init(cast<DynamicMethodBranchInst>(inst));
case TermKind::CheckedCastBranchInst:
return init(cast<CheckedCastBranchInst>(inst));
}
llvm_unreachable("Covered switch isn't covered?!");
}
private:
void init(BranchInst *bi) {
addValues(makeOperandRefRange(bi->getAllOperands()), bi->getDestBB());
}
void init(CondBranchInst *cbi) {
addValues(makeOperandRefRange(cbi->getTrueOperands()), cbi->getTrueBB());
addValues(makeOperandRefRange(cbi->getFalseOperands()), cbi->getFalseBB());
}
void init(DynamicMethodBranchInst *dmBranchInst) {
addValues({&dmBranchInst->getAllOperands()[0]},
dmBranchInst->getHasMethodBB());
}
void init(CheckedCastBranchInst *ccbi) {
addValues({&ccbi->getAllOperands()[0]}, ccbi->getSuccessBB());
}
};
} // namespace
static bool isProjectedFromAggregate(SILValue value) {
assert(value->getType().isAddress());
UseDefChainVisitor visitor;
visitor.visitAll(value);
return visitor.isMerge;
}
namespace {
using AsyncLetSourceValue =
llvm::PointerUnion<PartialApplyInst *, ThinToThickFunctionInst *>;
} // namespace
static std::optional<AsyncLetSourceValue>
findAsyncLetPartialApplyFromStart(SILValue value) {
// If our operand is Sendable then we want to return nullptr. We only want to
// return a value if we are not
auto fType = value->getType().castTo<SILFunctionType>();
if (fType->isSendable())
return {};
SILValue temp = value;
while (true) {
if (isa<ConvertEscapeToNoEscapeInst>(temp) ||
isa<ConvertFunctionInst>(temp)) {
temp = cast<SingleValueInstruction>(temp)->getOperand(0);
}
if (temp == value)
break;
value = temp;
}
// We can also get a thin_to_thick_function here if we do not capture
// anything. In such a case, we just do not process the partial apply get
if (auto *ttfi = dyn_cast<ThinToThickFunctionInst>(value))
return {{ttfi}};
// Ok, we could still have a reabstraction thunk. In such a case, we want the
// partial_apply that we process to be the original partial_apply (or
// thin_to_thick)... so in that case process recursively.
auto *pai = cast<PartialApplyInst>(value);
if (auto *calleeFunction = pai->getCalleeFunction()) {
if (calleeFunction->isThunk() == IsReabstractionThunk) {
return findAsyncLetPartialApplyFromStart(pai->getArgument(0));
}
}
// Otherwise, this is the right partial_apply... apply it!
return {{pai}};
}
/// This recurses through reabstraction thunks.
static std::optional<AsyncLetSourceValue>
findAsyncLetPartialApplyFromStart(BuiltinInst *bi) {
return findAsyncLetPartialApplyFromStart(bi->getOperand(1));
}
/// This recurses through reabstraction thunks.
static std::optional<AsyncLetSourceValue>
findAsyncLetPartialApplyFromGet(ApplyInst *ai) {
auto *bi = cast<BuiltinInst>(FullApplySite(ai).getArgument(0));
assert(*bi->getBuiltinKind() ==
BuiltinValueKind::StartAsyncLetWithLocalBuffer);
return findAsyncLetPartialApplyFromStart(bi);
}
static bool isAsyncLetBeginPartialApply(PartialApplyInst *pai) {
if (auto *fas = pai->getCalleeFunction())
if (fas->isThunk())
return false;
// Look through reabstraction thunks.
SILValue result = pai;
while (true) {
SILValue iter = result;
if (auto *use = iter->getSingleUse()) {
if (auto *maybeThunk = dyn_cast<PartialApplyInst>(use->getUser())) {
if (auto *fas = maybeThunk->getCalleeFunction()) {
if (fas->isThunk()) {
iter = maybeThunk;
}
}
}
}
if (auto *cfi = iter->getSingleUserOfType<ConvertFunctionInst>())
iter = cfi;
if (auto *cvt = iter->getSingleUserOfType<ConvertEscapeToNoEscapeInst>())
iter = cvt;
if (iter == result)
break;
result = iter;
}
auto *bi = result->getSingleUserOfType<BuiltinInst>();
if (!bi)
return false;
auto kind = bi->getBuiltinKind();
if (!kind)
return false;
return *kind == BuiltinValueKind::StartAsyncLetWithLocalBuffer;
}
/// Returns true if this is a function argument that is able to be sent in the
/// body of our function.
static bool canFunctionArgumentBeSent(SILFunctionArgument *arg) {
// Indirect out parameters can never be sent.
if (arg->isIndirectResult() || arg->isIndirectErrorResult())
return false;
// If we have a function argument that is closure captured by a Sendable
// closure, allow for the argument to be sent.
//
// DISCUSSION: The reason that we do this is that in the case of us
// having an actual Sendable closure there are two cases we can see:
//
// 1. If we have an actual Sendable closure, the AST will emit an
// earlier error saying that we are capturing a non-Sendable value in a
// Sendable closure. So we want to squelch the error that we would emit
// otherwise. This only occurs when we are not in swift-6 mode since in
// swift-6 mode we will error on the earlier error... but in the case of
// us not being in swift 6 mode lets not emit extra errors.
//
// 2. If we have an async-let based Sendable closure, we want to allow
// for the argument to be sent in the async let's statement and
// not emit an error.
//
// TODO: Once the async let refactoring change this will no longer be needed
// since closure captures will have sending parameters and be
// non-Sendable.
if (arg->isClosureCapture() &&
arg->getFunction()->getLoweredFunctionType()->isSendable())
return true;
// Otherwise, we only allow for the argument to be sent if it is explicitly
// marked as a 'sending' parameter.
return arg->isSending();
}
//===----------------------------------------------------------------------===//
// MARK: RegionAnalysisValueMap
//===----------------------------------------------------------------------===//
SILInstruction *RegionAnalysisValueMap::maybeGetActorIntroducingInst(
Element trackableValueID) const {
if (auto value = getValueForId(trackableValueID)) {
auto rep = value->getRepresentative();
if (rep.hasRegionIntroducingInst())
return rep.getActorRegionIntroducingInst();
}
return nullptr;
}
std::optional<TrackableValue>
RegionAnalysisValueMap::getValueForId(Element id) const {
auto iter = stateIndexToEquivalenceClass.find(id);
if (iter == stateIndexToEquivalenceClass.end())
return {};
auto iter2 = equivalenceClassValuesToState.find(iter->second);
if (iter2 == equivalenceClassValuesToState.end())
return {};
return {{iter2->first, iter2->second}};
}
SILValue
RegionAnalysisValueMap::getRepresentative(Element trackableValueID) const {
return getValueForId(trackableValueID)->getRepresentative().getValue();
}
SILValue
RegionAnalysisValueMap::maybeGetRepresentative(Element trackableValueID) const {
return getValueForId(trackableValueID)->getRepresentative().maybeGetValue();
}
RepresentativeValue
RegionAnalysisValueMap::getRepresentativeValue(Element trackableValueID) const {
return getValueForId(trackableValueID)->getRepresentative();
}
SILIsolationInfo
RegionAnalysisValueMap::getIsolationRegion(Element trackableValueID) const {
auto iter = getValueForId(trackableValueID);
if (!iter)
return {};
return iter->getValueState().getIsolationRegionInfo();
}
SILIsolationInfo
RegionAnalysisValueMap::getIsolationRegion(SILValue value) const {
auto iter = equivalenceClassValuesToState.find(RepresentativeValue(value));
if (iter == equivalenceClassValuesToState.end())
return {};
return iter->getSecond().getIsolationRegionInfo();
}
std::pair<TrackableValue, bool>
RegionAnalysisValueMap::initializeTrackableValue(
SILValue value, SILIsolationInfo newInfo) const {
auto info = getUnderlyingTrackedValue(value);
value = info.value;
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.try_emplace(
value, TrackableValueState(equivalenceClassValuesToState.size()));
// If we did not insert, just return the already stored value.
if (!iter.second) {
return {{iter.first->first, iter.first->second}, false};
}
// If we did not insert, just return the already stored value.
self->stateIndexToEquivalenceClass[iter.first->second.getID()] = value;
// Before we do anything, see if we have a Sendable value.
if (!SILIsolationInfo::isNonSendableType(value->getType(), fn)) {
iter.first->getSecond().addFlag(TrackableValueFlag::isSendable);
return {{iter.first->first, iter.first->second}, true};
}
// Otherwise, we have a non-Sendable type... so wire up the isolation.
iter.first->getSecond().setIsolationRegionInfo(newInfo);
return {{iter.first->first, iter.first->second}, true};
}
/// If \p isAddressCapturedByPartialApply is set to true, then this value is
/// an address that is captured by a partial_apply and we want to treat it as
/// may alias.
TrackableValue RegionAnalysisValueMap::getTrackableValue(
SILValue value, bool isAddressCapturedByPartialApply) const {
auto info = getUnderlyingTrackedValue(value);
value = info.value;
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.try_emplace(
value, TrackableValueState(equivalenceClassValuesToState.size()));
// If we did not insert, just return the already stored value.
if (!iter.second) {
return {iter.first->first, iter.first->second};
}
// If we did not insert, just return the already stored value.
self->stateIndexToEquivalenceClass[iter.first->second.getID()] = value;
// Otherwise, we need to compute our flags.
// Treat function ref and class method as either actor isolated or
// sendable. Formally they are non-Sendable, so we do the check before we
// check the oracle.
if (isa<FunctionRefInst, ClassMethodInst>(value)) {
if (auto isolation = SILIsolationInfo::get(value)) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
return {iter.first->first, iter.first->second};
}
iter.first->getSecond().addFlag(TrackableValueFlag::isSendable);
return {iter.first->first, iter.first->second};
}
// Then check our oracle to see if the value is actually sendable. If we have
// a Sendable value, just return early.
if (!SILIsolationInfo::isNonSendableType(value->getType(), fn)) {
iter.first->getSecond().addFlag(TrackableValueFlag::isSendable);
return {iter.first->first, iter.first->second};
}
// Ok, at this point we have a non-Sendable value. First process addresses.
if (value->getType().isAddress()) {
// If we were able to find this was actor isolated from finding our
// underlying object, use that. It is never wrong.
if (info.actorIsolation) {
SILIsolationInfo isolation;
if (info.value->getType().isAnyActor()) {
isolation = SILIsolationInfo::getActorInstanceIsolated(
value, info.value, info.actorIsolation->getActor());
} else if (info.actorIsolation->isGlobalActor()) {
isolation = SILIsolationInfo::getGlobalActorIsolated(
value, info.actorIsolation->getGlobalActor());
}
if (isolation) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
}
}
auto storage = AccessStorageWithBase::compute(value);
if (storage.storage) {
// Check if we have a uniquely identified address that was not captured
// by a partial apply... in such a case, we treat it as no-alias.
if (storage.storage.isUniquelyIdentified() &&
!isAddressCapturedByPartialApply) {
iter.first->getSecond().removeFlag(TrackableValueFlag::isMayAlias);
}
if (auto isolation = SILIsolationInfo::get(storage.base)) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
}
}
}
// Check if we have a load or load_borrow from an address. In that case, we
// want to look through the load and find a better root from the address we
// loaded from.
if (isa<LoadInst, LoadBorrowInst>(iter.first->first.getValue())) {
auto *svi = cast<SingleValueInstruction>(iter.first->first.getValue());
// See if we can use get underlying tracked value to find if it is actor
// isolated.
//
// TODO: Instead of using AccessStorageBase, just use our own visitor
// everywhere. Just haven't done it due to possible perturbations.
auto parentAddrInfo = getUnderlyingTrackedValue(svi);
if (parentAddrInfo.actorIsolation) {
iter.first->getSecond().setIsolationRegionInfo(
SILIsolationInfo::getActorInstanceIsolated(
svi, parentAddrInfo.value,
parentAddrInfo.actorIsolation->getActor()));
}
auto storage = AccessStorageWithBase::compute(svi->getOperand(0));
if (storage.storage) {
if (auto isolation = SILIsolationInfo::get(storage.base)) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
}
}
return {iter.first->first, iter.first->second};
}
// Ok, we have a non-Sendable type, see if we do not have any isolation
// yet. If we don't, attempt to infer its isolation.
if (!iter.first->getSecond().hasIsolationRegionInfo()) {
if (auto isolation = SILIsolationInfo::get(iter.first->first.getValue())) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
return {iter.first->first, iter.first->second};
}
}
return {iter.first->first, iter.first->second};
}
std::optional<TrackableValue>
RegionAnalysisValueMap::getTrackableValueForActorIntroducingInst(
SILInstruction *inst) const {
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.find(inst);
if (iter == self->equivalenceClassValuesToState.end())
return {};
// Otherwise, we need to compute our flags.
return {{iter->first, iter->second}};
}
std::optional<TrackableValue>
RegionAnalysisValueMap::tryToTrackValue(SILValue value) const {
auto state = getTrackableValue(value);
if (state.isNonSendable())
return state;
return {};
}
TrackableValue RegionAnalysisValueMap::getActorIntroducingRepresentative(
SILInstruction *introducingInst, SILIsolationInfo actorIsolation) const {
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.try_emplace(
introducingInst,
TrackableValueState(equivalenceClassValuesToState.size()));
// If we did not insert, just return the already stored value.
if (!iter.second) {
return {iter.first->first, iter.first->second};
}
// Otherwise, wire up the value.
self->stateIndexToEquivalenceClass[iter.first->second.getID()] =
introducingInst;
iter.first->getSecond().setIsolationRegionInfo(actorIsolation);
return {iter.first->first, iter.first->second};
}
bool RegionAnalysisValueMap::valueHasID(SILValue value, bool dumpIfHasNoID) {
assert(getTrackableValue(value).isNonSendable() &&
"Can only accept non-Sendable values");
bool hasID = equivalenceClassValuesToState.count(value);
if (!hasID && dumpIfHasNoID) {
llvm::errs() << "FAILURE: valueHasID of ";
value->print(llvm::errs());
llvm::report_fatal_error("standard compiler error");
}
return hasID;
}
Element RegionAnalysisValueMap::lookupValueID(SILValue value) {
auto state = getTrackableValue(value);
assert(state.isNonSendable() &&
"only non-Sendable values should be entered in the map");
return state.getID();
}
void RegionAnalysisValueMap::print(llvm::raw_ostream &os) const {
#ifndef NDEBUG
// Since this is just used for debug output, be inefficient to make nicer
// output.
std::vector<std::pair<unsigned, RepresentativeValue>> temp;
for (auto p : stateIndexToEquivalenceClass) {
temp.emplace_back(p.first, p.second);
}
std::sort(temp.begin(), temp.end());
for (auto p : temp) {
os << "%%" << p.first << ": ";
auto value = getValueForId(Element(p.first));
value->print(os);
}
#endif
}
static SILValue getUnderlyingTrackedObjectValue(SILValue value) {
auto *fn = value->getFunction();
SILValue result = value;
while (true) {
SILValue temp = result;
if (auto *svi = dyn_cast<SingleValueInstruction>(temp)) {
if (isStaticallyLookThroughInst(svi)) {
temp = svi->getOperand(0);
}
// If we have a cast and our operand and result are non-Sendable, treat it
// as a look through.
if (isLookThroughIfOperandAndResultNonSendable(svi)) {
if (SILIsolationInfo::isNonSendableType(svi->getType(), fn) &&
SILIsolationInfo::isNonSendableType(svi->getOperand(0)->getType(),
fn)) {
temp = svi->getOperand(0);
}
}
if (isLookThroughIfResultNonSendable(svi)) {
if (SILIsolationInfo::isNonSendableType(svi->getType(), fn)) {
temp = svi->getOperand(0);
}
}
if (isLookThroughIfOperandNonSendable(svi)) {
// If our operand is a non-Sendable type, look through this instruction.
if (SILIsolationInfo::isNonSendableType(svi->getOperand(0)->getType(),
fn)) {
temp = svi->getOperand(0);
}
}
}
if (auto *inst = temp->getDefiningInstruction()) {
if (isStaticallyLookThroughInst(inst)) {
temp = inst->getOperand(0);
}
}
if (temp != result) {
result = temp;
continue;
}
return result;
}
}
RegionAnalysisValueMap::UnderlyingTrackedValueInfo
RegionAnalysisValueMap::getUnderlyingTrackedValueHelper(SILValue value) const {
// Before a check if the value we are attempting to access is Sendable. In
// such a case, just return early.
if (!SILIsolationInfo::isNonSendableType(value))
return UnderlyingTrackedValueInfo(value);
// Look through a project_box, so that we process it like its operand object.
if (auto *pbi = dyn_cast<ProjectBoxInst>(value)) {
value = pbi->getOperand();
}
if (!value->getType().isAddress()) {
SILValue underlyingValue = getUnderlyingTrackedObjectValue(value);
// If we do not have a load inst, just return the value.
if (!isa<LoadInst, LoadBorrowInst>(underlyingValue)) {
return UnderlyingTrackedValueInfo(underlyingValue);
}
// If we got an address, lets see if we can do even better by looking at the
// address.
value = cast<SingleValueInstruction>(underlyingValue)->getOperand(0);
}
assert(value->getType().isAddress());
UseDefChainVisitor visitor;
SILValue base = visitor.visitAll(value);
assert(base);
if (base->getType().isObject()) {
// NOTE: We purposely recurse into the cached version of our computation
// rather than recurse into getUnderlyingTrackedObjectValueHelper. This is
// safe since we know that value was previously an address so if our base is
// an object, it cannot be the same object.
return {getUnderlyingTrackedValue(base).value, visitor.actorIsolation};
}
return {base, visitor.actorIsolation};
}
//===----------------------------------------------------------------------===//
// MARK: TrackableValue
//===----------------------------------------------------------------------===//
bool TrackableValue::isSendingParameter() const {
// First get our alloc_stack.
//
// TODO: We should just put a flag on the alloc_stack, so we /know/ 100% that
// it is from a consuming parameter. We don't have that so we pattern match.
auto *asi =
dyn_cast_or_null<AllocStackInst>(representativeValue.maybeGetValue());
if (!asi)
return false;
if (asi->getParent() != asi->getFunction()->getEntryBlock())
return false;
// See if we are initialized from a 'sending' parameter and are the only
// use of the parameter.
OperandWorklist worklist(asi->getFunction());
worklist.pushResultOperandsIfNotVisited(asi);
while (auto *use = worklist.pop()) {
auto *user = use->getUser();
// Look through instructions that we don't care about.
if (isa<MarkUnresolvedNonCopyableValueInst,
MoveOnlyWrapperToCopyableAddrInst>(user)) {
worklist.pushResultOperandsIfNotVisited(user);
}
if (auto *si = dyn_cast<StoreInst>(user)) {
// Check if our store inst is from a 'sending' function argument and for
// which the store is the only use of the function argument.
auto *fArg = dyn_cast<SILFunctionArgument>(si->getSrc());
if (!fArg || !fArg->isSending())
return false;
return fArg->getSingleUse();
}
if (auto *copyAddr = dyn_cast<CopyAddrInst>(user)) {
// Check if our copy_addr is from a 'sending' function argument and for
// which the copy_addr is the only use of the function argument.
auto *fArg = dyn_cast<SILFunctionArgument>(copyAddr->getSrc());
if (!fArg || !fArg->isSending())
return false;
return fArg->getSingleUse();
}
}
// Otherwise, this isn't a consuming parameter.
return false;
}
//===----------------------------------------------------------------------===//
// MARK: Partial Apply Reachability
//===----------------------------------------------------------------------===//
namespace {
/// We need to be able to know if instructions that extract sendable fields from
/// non-sendable addresses are reachable from a partial_apply that captures the
/// non-sendable value or its underlying object by reference. In such a case, we
/// need to require the value to not be sent when the extraction happens since
/// we could race on extracting the value.
///
/// The reason why we use a dataflow to do this is that:
///
/// 1. We do not want to recompute this for each individual instruction that
/// might be reachable from the partial apply.
///
/// 2. Just computing reachability early is a very easy way to do this.
struct PartialApplyReachabilityDataflow {
RegionAnalysisValueMap &valueMap;
PostOrderFunctionInfo *pofi;
llvm::DenseMap<SILValue, unsigned> valueToBit;
std::vector<std::pair<SILValue, SILInstruction *>> valueToGenInsts;
struct BlockState {
SmallBitVector entry;
SmallBitVector exit;
SmallBitVector gen;
bool needsUpdate = true;
};
BasicBlockData<BlockState> blockData;
bool propagatedReachability = false;
PartialApplyReachabilityDataflow(SILFunction *fn,
RegionAnalysisValueMap &valueMap,
PostOrderFunctionInfo *pofi)
: valueMap(valueMap), pofi(pofi), blockData(fn) {}
/// Begin tracking an operand of a partial apply.