-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathMemAccessUtils.cpp
2858 lines (2512 loc) · 96.4 KB
/
MemAccessUtils.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
//===--- MemAccessUtils.cpp - Utilities for SIL memory access. ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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-access-utils"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/GraphNodeWorklist.h"
#include "swift/SIL/Consumption.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/NodeDatastructures.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/SILBridging.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/Test.h"
#include "llvm/Support/Debug.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// MARK: FindAccessVisitor
//===----------------------------------------------------------------------===//
namespace {
enum StorageCastTy { StopAtStorageCast, IgnoreStorageCast };
// Handle a single phi-web within an access use-def chain.
//
// Recursively calls the useDefVisitor on any operations that aren't recognized
// as storage casts or projections. If the useDefVisitor finds a consistent
// result for all operands, then it's result will remain valid. If the
// useDefVisitor has an invalid result after processing the phi web, then it's
// original result is restored, then the phi reported to the useDefVisitor as a
// NonAccess.
//
// Phi-web's are only allowed to contain casts and projections that do not
// affect the access path. If AccessPhiVisitor reaches an unhandled projection,
// it remembers that as the commonDefinition. If after processing the entire
// web, the commonDefinition is unique, then it calls the original useDefVisitor
// to update its result. Note that visitAccessProjection and setDefinition are
// only used by visitors that process access projections; once the accessed
// address is reached, they are no longer relevant.
template <typename UseDefVisitor>
class AccessPhiVisitor
: public AccessUseDefChainVisitor<AccessPhiVisitor<UseDefVisitor>> {
UseDefVisitor &useDefVisitor;
StorageCastTy storageCastTy;
std::optional<SILValue> commonDefinition;
SmallVector<SILValue, 8> pointerWorklist;
SmallPtrSet<SILPhiArgument *, 4> nestedPhis;
public:
AccessPhiVisitor(UseDefVisitor &useDefVisitor, StorageCastTy storageCastTy)
: useDefVisitor(useDefVisitor), storageCastTy(storageCastTy) {}
// Main entry point.
void findPhiAccess(SILPhiArgument *phiArg) && {
auto savedResult = useDefVisitor.saveResult();
visitPhi(phiArg);
while (!pointerWorklist.empty()) {
this->visit(pointerWorklist.pop_back_val());
}
// If a common path component was found, recursively look for the result.
if (commonDefinition) {
if (commonDefinition.value()) {
useDefVisitor.reenterUseDef(commonDefinition.value());
} else {
// Divergent paths were found; invalidate any previously discovered
// storage.
useDefVisitor.invalidateResult();
}
}
// If the result is now invalid, reset it and process the current phi as an
// unrecognized access instead.
if (!useDefVisitor.isResultValid()) {
useDefVisitor.restoreResult(savedResult);
visitNonAccess(phiArg);
}
}
// Visitor helper.
void setDefinition(SILValue def) {
if (!commonDefinition) {
commonDefinition = def;
return;
}
if (commonDefinition.value() != def)
commonDefinition = SILValue();
}
void checkVisitorResult(SILValue result) {
assert(!result && "must override any visitor that returns a result");
}
// MARK: Visitor implementation.
// Recursively call the original storageVisitor for each base. We can't simply
// look for a common definition on all phi inputs, because the base may be
// cloned on each path. For example, two global_addr instructions may refer to
// the same global storage. Those global_addr instructions may each be
// converted to a RawPointer before being passed into the non-address phi.
void visitBase(SILValue base, AccessStorage::Kind kind) {
checkVisitorResult(useDefVisitor.visitBase(base, kind));
}
void visitNonAccess(SILValue value) {
checkVisitorResult(useDefVisitor.visitNonAccess(value));
}
void visitNestedAccess(BeginAccessInst *access) {
checkVisitorResult(useDefVisitor.visitNestedAccess(access));
}
void visitPhi(SILPhiArgument *phiArg) {
if (nestedPhis.insert(phiArg).second)
phiArg->getIncomingPhiValues(pointerWorklist);
}
void visitStorageCast(SingleValueInstruction *cast, Operand *sourceOper,
AccessStorageCast) {
// Allow conversions to/from pointers and addresses on disjoint phi paths
// only if the underlying useDefVisitor allows it.
if (storageCastTy == IgnoreStorageCast)
pointerWorklist.push_back(sourceOper->get());
else
visitNonAccess(cast);
}
void visitAccessProjection(SingleValueInstruction *projectedAddr,
Operand *sourceOper) {
// An offset index on a phi path is always conservatively considered an
// unknown offset.
if (isa<IndexAddrInst>(projectedAddr) || isa<TailAddrInst>(projectedAddr)) {
useDefVisitor.addUnknownOffset();
pointerWorklist.push_back(sourceOper->get());
return;
}
// No other access projections are expected to occur on disjoint phi
// paths. Stop searching at this projection.
setDefinition(projectedAddr);
}
};
// Find the origin of an access while skipping projections and casts and
// handling phis.
template <typename Impl>
class FindAccessVisitorImpl : public AccessUseDefChainVisitor<Impl, SILValue> {
using SuperTy = AccessUseDefChainVisitor<Impl, SILValue>;
protected:
NestedAccessType nestedAccessTy;
StorageCastTy storageCastTy;
SmallPtrSet<SILPhiArgument *, 4> visitedPhis;
bool hasUnknownOffset = false;
public:
FindAccessVisitorImpl(NestedAccessType nestedAccessTy,
StorageCastTy storageCastTy)
: nestedAccessTy(nestedAccessTy), storageCastTy(storageCastTy) {}
// MARK: AccessPhiVisitor::UseDefVisitor implementation.
//
// Subclasses must implement:
// isResultValid()
// invalidateResult()
// saveResult()
// restoreResult(Result)
// addUnknownOffset()
void reenterUseDef(SILValue sourceAddr) {
SILValue nextAddr = this->visit(sourceAddr);
while (nextAddr) {
checkNextAddressType(nextAddr, sourceAddr);
nextAddr = this->visit(nextAddr);
}
}
// MARK: visitor implementation.
// Override AccessUseDefChainVisitor to ignore access markers and find the
// outer access base.
SILValue visitNestedAccessImpl(BeginAccessInst *access) {
if (nestedAccessTy == NestedAccessType::IgnoreAccessBegin)
return access->getSource();
return SuperTy::visitNestedAccess(access);
}
SILValue visitNestedAccess(BeginAccessInst *access) {
auto value = visitNestedAccessImpl(access);
if (value) {
reenterUseDef(value);
}
return SILValue();
}
SILValue visitPhi(SILPhiArgument *phiArg) {
// Cycles involving phis are only handled within AccessPhiVisitor.
// Path components are not allowed in phi cycles.
if (visitedPhis.insert(phiArg).second) {
AccessPhiVisitor<Impl>(this->asImpl(), storageCastTy)
.findPhiAccess(phiArg);
// Each phi operand was now reentrantly processed. Stop visiting.
return SILValue();
}
// Cannot treat unresolved phis as "unidentified" because they may alias
// with global or class access.
return this->asImpl().visitNonAccess(phiArg);
}
SILValue visitStorageCast(SingleValueInstruction *, Operand *sourceAddr,
AccessStorageCast cast) {
assert(storageCastTy == IgnoreStorageCast);
return sourceAddr->get();
}
SILValue visitAccessProjection(SingleValueInstruction *projectedAddr,
Operand *sourceAddr) {
if (auto *indexAddr = dyn_cast<IndexAddrInst>(projectedAddr)) {
if (!Projection(indexAddr).isValid())
this->asImpl().addUnknownOffset();
} else if (isa<TailAddrInst>(projectedAddr)) {
this->asImpl().addUnknownOffset();
}
return sourceAddr->get();
}
protected:
// Helper for reenterUseDef
void checkNextAddressType(SILValue nextAddr, SILValue sourceAddr) {
#ifdef NDEBUG
return;
#endif
SILType type = nextAddr->getType();
// FIXME: This relatively expensive pointer getAnyPointerElementType check
// is only needed because keypath generation incorrectly produces
// pointer_to_address directly from stdlib Pointer types without a
// struct_extract (as is correctly done in emitAddressorAccessor), and
// the PointerToAddressInst operand type is never verified.
if (type.getASTType()->getAnyPointerElementType())
return;
if (type.isAddress() || isa<SILBoxType>(type.getASTType())
|| isa<BuiltinRawPointerType>(type.getASTType())) {
return;
}
llvm::errs() << "Visiting ";
sourceAddr->print(llvm::errs());
llvm::errs() << " not an address ";
nextAddr->print(llvm::errs());
nextAddr->getFunction()->print(llvm::errs());
assert(false);
}
};
// Implement getAccessAddress, getAccessBegin, and getAccessBase.
class FindAccessBaseVisitor
: public FindAccessVisitorImpl<FindAccessBaseVisitor> {
using SuperTy = FindAccessVisitorImpl<FindAccessBaseVisitor>;
protected:
// If the optional baseVal is set, then a result was found. If the SILValue
// within the optional is invalid, then there are multiple inconsistent base
// addresses (this may currently happen with RawPointer phis).
std::optional<SILValue> baseVal;
// If the kind optional is set, then 'baseVal' is a valid
// AccessBase. 'baseVal' may be a valid SILValue while kind optional has no
// value if an invalid address producer was detected, via a call to
// visitNonAccess.
std::optional<AccessBase::Kind> kindVal;
public:
FindAccessBaseVisitor(NestedAccessType nestedAccessTy,
StorageCastTy storageCastTy)
: FindAccessVisitorImpl(nestedAccessTy, storageCastTy) {}
// Returns the accessed address or an invalid SILValue.
SILValue findPossibleBaseAddress(SILValue sourceAddr) && {
reenterUseDef(sourceAddr);
return baseVal.value_or(SILValue());
}
AccessBase findBase(SILValue sourceAddr) && {
reenterUseDef(sourceAddr);
if (!baseVal || !kindVal)
return AccessBase();
return AccessBase(baseVal.value(), kindVal.value());
}
void setResult(SILValue foundBase) {
if (!baseVal)
baseVal = foundBase;
else if (baseVal.value() != foundBase)
baseVal = SILValue();
}
// MARK: AccessPhiVisitor::UseDefVisitor implementation.
// Keep going as long as baseVal is valid regardless of kindVal.
bool isResultValid() const { return baseVal && bool(baseVal.value()); }
void invalidateResult() {
baseVal = SILValue();
kindVal = std::nullopt;
}
std::optional<SILValue> saveResult() const { return baseVal; }
void restoreResult(std::optional<SILValue> result) { baseVal = result; }
void addUnknownOffset() { return; }
// MARK: visitor implementation.
SILValue visitBase(SILValue base, AccessStorage::Kind kind) {
setResult(base);
if (!baseVal.value()) {
kindVal = std::nullopt;
} else {
assert(!kindVal || kindVal.value() == kind);
kindVal = kind;
}
return SILValue();
}
SILValue visitNonAccess(SILValue value) {
setResult(value);
kindVal = std::nullopt;
return SILValue();
}
// Override visitStorageCast to avoid seeing through arbitrary address casts.
SILValue visitStorageCast(SingleValueInstruction *svi, Operand *sourceAddr,
AccessStorageCast cast) {
if (storageCastTy == StopAtStorageCast)
return visitNonAccess(svi);
return SuperTy::visitStorageCast(svi, sourceAddr, cast);
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// MARK: Standalone API
//===----------------------------------------------------------------------===//
SILValue swift::getTypedAccessAddress(SILValue address) {
assert(address->getType().isAddress());
SILValue accessAddress =
FindAccessBaseVisitor(NestedAccessType::StopAtAccessBegin,
StopAtStorageCast)
.findPossibleBaseAddress(address);
assert(accessAddress->getType().isAddress());
return accessAddress;
}
namespace swift::test {
static FunctionTest
GetTypedAccessAddress("get_typed_access_address",
[](auto &function, auto &arguments, auto &test) {
auto address = arguments.takeValue();
function.print(llvm::outs());
llvm::outs() << "Address: " << address;
auto access = getTypedAccessAddress(address);
llvm::outs() << "Access: " << access;
});
} // end namespace swift::test
// TODO: When the optimizer stops stripping begin_access markers and SILGen
// protects all memory operations with at least an "unsafe" access scope, then
// we should be able to assert that this returns a BeginAccessInst.
SILValue swift::getAccessScope(SILValue address) {
assert(address->getType().isAddress());
return FindAccessBaseVisitor(NestedAccessType::StopAtAccessBegin,
IgnoreStorageCast)
.findPossibleBaseAddress(address);
}
// This is allowed to be called on a non-address pointer type.
SILValue swift::getAccessBase(SILValue address) {
return FindAccessBaseVisitor(NestedAccessType::IgnoreAccessBegin,
IgnoreStorageCast)
.findPossibleBaseAddress(address);
}
namespace swift::test {
static FunctionTest GetAccessBaseTest("get_access_base",
[](auto &function, auto &arguments,
auto &test) {
auto address = arguments.takeValue();
function.print(llvm::outs());
llvm::outs() << "Address: " << address;
auto base = getAccessBase(address);
llvm::outs() << "Base: " << base;
});
} // end namespace swift::test
static bool isLetForBase(SILValue base) {
// Is this an address of a "let" class member?
if (auto *rea = dyn_cast<RefElementAddrInst>(base))
return rea->getField()->isLet();
// Is this an address of a global "let"?
if (auto *gai = dyn_cast<GlobalAddrInst>(base)) {
auto *globalDecl = gai->getReferencedGlobal()->getDecl();
return globalDecl && globalDecl->isLet();
}
return false;
}
bool swift::isLetAddress(SILValue address) {
SILValue base = getAccessBase(address);
if (!base)
return false;
return isLetForBase(base);
}
//===----------------------------------------------------------------------===//
// MARK: Deinitialization barriers.
//===----------------------------------------------------------------------===//
bool swift::mayAccessPointer(SILInstruction *instruction) {
assert(!FullApplySite::isa(instruction) && !isa<EndApplyInst>(instruction) &&
!isa<AbortApplyInst>(instruction));
if (!instruction->mayReadOrWriteMemory())
return false;
if (isa<BuiltinInst>(instruction)) {
// Consider all builtins that read/write memory to access pointers.
return true;
}
bool retval = false;
visitAccessedAddress(instruction, [&retval](Operand *operand) {
auto accessStorage = AccessStorage::compute(operand->get());
auto kind = accessStorage.getKind();
if (kind == AccessRepresentation::Kind::Unidentified ||
kind == AccessRepresentation::Kind::Global)
retval = true;
});
return retval;
}
bool swift::mayLoadWeakOrUnowned(SILInstruction *instruction) {
assert(!FullApplySite::isa(instruction) && !isa<EndApplyInst>(instruction) &&
!isa<AbortApplyInst>(instruction));
if (isa<BuiltinInst>(instruction)) {
return instruction->mayReadOrWriteMemory();
}
return isa<LoadWeakInst>(instruction)
|| isa<LoadUnownedInst>(instruction)
|| isa<StrongCopyUnownedValueInst>(instruction)
|| isa<StrongCopyUnmanagedValueInst>(instruction);
}
/// Conservatively, whether this instruction could involve a synchronization
/// point like a memory barrier, lock or syscall.
bool swift::maySynchronize(SILInstruction *instruction) {
assert(!FullApplySite::isa(instruction) && !isa<EndApplyInst>(instruction) &&
!isa<AbortApplyInst>(instruction));
if (isa<BuiltinInst>(instruction)) {
return instruction->mayReadOrWriteMemory();
}
return isa<HopToExecutorInst>(instruction);
}
bool swift::mayBeDeinitBarrierNotConsideringSideEffects(SILInstruction *instruction) {
if (FullApplySite::isa(instruction) || isa<EndApplyInst>(instruction) ||
isa<AbortApplyInst>(instruction)) {
return true;
}
bool retval = mayAccessPointer(instruction)
|| mayLoadWeakOrUnowned(instruction)
|| maySynchronize(instruction);
assert(!retval || !isa<BranchInst>(instruction) && "br as deinit barrier!?");
return retval;
}
//===----------------------------------------------------------------------===//
// MARK: AccessRepresentation
//===----------------------------------------------------------------------===//
constexpr unsigned AccessRepresentation::TailIndex;
const char *AccessRepresentation::getKindName(AccessStorage::Kind k) {
switch (k) {
case Box:
return "Box";
case Stack:
return "Stack";
case Nested:
return "Nested";
case Unidentified:
return "Unidentified";
case Argument:
return "Argument";
case Yield:
return "Yield";
case Global:
return "Global";
case Class:
return "Class";
case Tail:
return "Tail";
}
llvm_unreachable("unhandled kind");
}
// 'value' remains invalid. AccessBase or AccessStorage must initialize it
// accordingly.
AccessRepresentation::AccessRepresentation(SILValue base, Kind kind) : value() {
Bits.opaqueBits = 0;
// For kind==Unidentified, base may be an invalid, empty, or tombstone value.
initKind(kind, InvalidElementIndex);
switch (kind) {
case Box:
assert(isa<ProjectBoxInst>(base));
break;
case Stack:
assert(isa<AllocStackInst>(base));
break;
case Nested:
assert(isa<BeginAccessInst>(base));
break;
case Yield:
assert(isa<BeginApplyInst>(
cast<MultipleValueInstructionResult>(base)->getParent()));
break;
case Unidentified:
break;
case Global:
break;
case Tail:
assert(isa<RefTailAddrInst>(base));
setElementIndex(TailIndex);
break;
case Argument:
setElementIndex(cast<SILFunctionArgument>(base)->getIndex());
break;
case Class: {
setElementIndex(cast<RefElementAddrInst>(base)->getFieldIndex());
break;
}
}
}
bool AccessRepresentation::
isDistinctFrom(const AccessRepresentation &other) const {
if (isUniquelyIdentified()) {
if (other.isUniquelyIdentified() && !hasIdenticalAccessInfo(other))
return true;
if (other.isObjectAccess())
return true;
// We currently assume that Unidentified storage may overlap with
// Box/Stack storage.
return false;
}
if (other.isUniquelyIdentified())
return other.isDistinctFrom(*this);
// Neither storage is uniquely identified.
if (isObjectAccess()) {
if (other.isObjectAccess()) {
// Property access cannot overlap with Tail access.
if (getKind() != other.getKind())
return true;
// We could also check if the object types are distinct, but that only
// helps if we know the relationships between class types.
return getKind() == Class
&& getPropertyIndex() != other.getPropertyIndex();
}
// Any type of nested/argument address may be within the same object.
//
// We also currently assume Unidentified access may be within an object
// purely to handle KeyPath accesses. The derivation of the KeyPath
// address must separately appear to be a Class access so that all Class
// accesses are accounted for.
return false;
}
if (other.isObjectAccess())
return other.isDistinctFrom(*this);
// Neither storage is from a class or tail.
//
// Unidentified values may alias with each other or with any kind of
// nested/argument access.
return false;
}
// The subclass prints Class and Global values.
void AccessRepresentation::print(raw_ostream &os) const {
if (!*this) {
os << "INVALID\n";
return;
}
os << getKindName(getKind()) << " ";
switch (getKind()) {
case Box:
case Stack:
case Nested:
case Yield:
case Unidentified:
case Tail:
os << value;
break;
case Argument:
os << value;
break;
case Global:
case Class:
break;
}
}
//===----------------------------------------------------------------------===//
// MARK: AccessBase
//===----------------------------------------------------------------------===//
AccessBase AccessBase::compute(SILValue sourceAddress) {
return FindAccessBaseVisitor(NestedAccessType::IgnoreAccessBegin,
IgnoreStorageCast)
.findBase(sourceAddress);
}
AccessBase::AccessBase(SILValue base, Kind kind)
: AccessRepresentation(base, kind)
{
assert(base && "invalid storage base");
value = base;
setLetAccess(isLetForBase(base));
}
static SILValue
getReferenceFromBase(SILValue base, AccessRepresentation::Kind kind) {
switch (kind) {
case AccessBase::Stack:
case AccessBase::Nested:
case AccessBase::Yield:
case AccessBase::Unidentified:
case AccessBase::Argument:
case AccessBase::Global:
llvm_unreachable("Not object storage");
break;
case AccessBase::Box:
return cast<ProjectBoxInst>(base)->getOperand();
case AccessBase::Tail:
return cast<RefTailAddrInst>(base)->getOperand();
case AccessBase::Class:
return cast<RefElementAddrInst>(base)->getOperand();
}
}
SILValue AccessBase::getReference() const {
return getReferenceFromBase(value, getKind());
}
static SILGlobalVariable *getReferencedGlobal(SILInstruction *inst) {
if (auto *gai = dyn_cast<GlobalAddrInst>(inst)) {
return gai->getReferencedGlobal();
}
if (auto apply = FullApplySite::isa(inst)) {
if (auto *funcRef = apply.getReferencedFunctionOrNull()) {
return getVariableOfGlobalInit(funcRef);
}
}
return nullptr;
}
SILGlobalVariable *AccessBase::getGlobal() const {
assert(getKind() == Global);
return getReferencedGlobal(cast<SingleValueInstruction>(value));
}
static const ValueDecl *
getNonRefNonGlobalDecl(SILValue base, AccessRepresentation::Kind kind) {
switch (kind) {
case AccessBase::Box:
case AccessBase::Class:
case AccessBase::Tail:
llvm_unreachable("Cannot handle reference access");
case AccessBase::Global:
llvm_unreachable("Cannot handle global access");
case AccessBase::Stack:
return cast<AllocStackInst>(base)->getDecl();
case AccessBase::Argument:
return cast<SILFunctionArgument>(base)->getDecl();
case AccessBase::Yield:
return nullptr;
case AccessBase::Nested:
return nullptr;
case AccessBase::Unidentified:
return nullptr;
}
llvm_unreachable("unhandled kind");
}
const ValueDecl *AccessBase::getDecl() const {
switch (getKind()) {
case Box:
if (auto *allocBox = dyn_cast<AllocBoxInst>(
findReferenceRoot(getReference()))) {
return allocBox->getLoc().getAsASTNode<VarDecl>();
}
return nullptr;
case Class: {
auto *classDecl = cast<RefElementAddrInst>(value)->getClassDecl();
return getIndexedField(classDecl, getPropertyIndex());
}
case Tail:
return nullptr;
case Global:
return getGlobal()->getDecl();
default:
return getNonRefNonGlobalDecl(value, getKind());
}
}
bool AccessBase::hasLocalOwnershipLifetime() const {
switch (getKind()) {
case AccessBase::Argument:
case AccessBase::Stack:
case AccessBase::Global:
return false;
case AccessBase::Unidentified:
// Unidentified storage may be nested within object access, but this is an
// "escaped pointer", so it is not restricted to the object's borrow scope.
return false;
case AccessBase::Yield:
// Yielded values have a local apply scope, but they never have the same
// storage as yielded values from a different scope, so there is no need to
// consider their local scope during substitution.
return false;
case AccessBase::Box:
case AccessBase::Class:
case AccessBase::Tail:
return getReference()->getOwnershipKind() != OwnershipKind::None;
case AccessBase::Nested:
llvm_unreachable("unexpected storage");
};
}
void AccessBase::print(raw_ostream &os) const {
AccessRepresentation::print(os);
switch (getKind()) {
case Global:
os << *getGlobal();
break;
case Class:
os << getReference();
if (auto *decl = getDecl()) {
os << " Field: ";
decl->print(os);
}
os << " Index: " << getPropertyIndex() << "\n";
break;
default:
break;
}
}
LLVM_ATTRIBUTE_USED void AccessBase::dump() const { print(llvm::dbgs()); }
//===----------------------------------------------------------------------===//
// MARK: FindReferenceRoot
//===----------------------------------------------------------------------===//
bool swift::isIdentityPreservingRefCast(SingleValueInstruction *svi) {
// Ignore both copies and other identity and ownership preserving casts
return isa<CopyValueInst>(svi) || isa<BeginBorrowInst>(svi) ||
isa<EndInitLetRefInst>(svi) || isa<BeginDeallocRefInst>(svi) ||
isa<EndCOWMutationInst>(svi) ||
isIdentityAndOwnershipPreservingRefCast(svi);
}
// On some platforms, casting from a metatype to a reference type dynamically
// allocates a ref-counted box for the metatype. Naturally that is the place
// where RC-identity begins. Considering the source of such a casts to be
// RC-identical would confuse ARC optimization, which might eliminate a retain
// of such an object completely.
//
// The SILVerifier checks that none of these operations cast a trivial value to
// a reference except unconditional_checked_cast[_value], which is checked By
// SILDynamicCastInst::isRCIdentityPreserving().
bool swift::isIdentityAndOwnershipPreservingRefCast(
SingleValueInstruction *svi) {
switch (svi->getKind()) {
default:
return false;
// Ignore class type casts
case SILInstructionKind::UpcastInst:
case SILInstructionKind::UncheckedRefCastInst:
case SILInstructionKind::RefToBridgeObjectInst:
case SILInstructionKind::BridgeObjectToRefInst:
return true;
case SILInstructionKind::UnconditionalCheckedCastInst:
return SILDynamicCastInst(svi).isRCIdentityPreserving();
// Ignore markers
case SILInstructionKind::MarkUninitializedInst:
case SILInstructionKind::MarkDependenceInst:
case SILInstructionKind::MarkUnresolvedReferenceBindingInst:
return true;
}
}
namespace {
// Essentially RC identity where the starting point is already a reference.
class FindReferenceRoot {
SmallPtrSet<SILPhiArgument *, 4> visitedPhis;
public:
SILValue findRoot(SILValue ref) && {
SILValue root = recursiveFindRoot(ref);
assert(root && "all phi inputs must be reachable");
return root;
}
protected:
// Return an invalid value for a phi with no resolved inputs.
SILValue recursiveFindRoot(SILValue ref) {
while (auto *svi = dyn_cast<SingleValueInstruction>(ref)) {
// If preserveOwnership is true, stop at the first owned root
if (!isIdentityPreservingRefCast(svi)) {
break;
}
ref = svi->getOperand(0);
};
auto *phi = dyn_cast<SILPhiArgument>(ref);
if (!phi || !phi->isPhi()) {
return ref;
}
// Handle phis...
if (!visitedPhis.insert(phi).second) {
return SILValue();
}
SILValue commonInput;
phi->visitIncomingPhiOperands([&](Operand *operand) {
SILValue input = recursiveFindRoot(operand->get());
// Ignore "back/cross edges" to previously visited phis.
if (!input)
return true;
if (!commonInput) {
commonInput = input;
return true;
}
if (commonInput == input)
return true;
commonInput = phi;
return false;
});
return commonInput;
}
};
} // end anonymous namespace
SILValue swift::findReferenceRoot(SILValue ref) {
return FindReferenceRoot().findRoot(ref);
}
// This does not handle phis because a phis is either a consume or a
// reborrow. In either case, the phi argument's ownership is independent from
// the phi itself. The client assumes that the returned root is in the same
// lifetime or borrow scope of the access.
SILValue swift::findOwnershipReferenceRoot(SILValue ref) {
while (auto *svi = dyn_cast<SingleValueInstruction>(ref)) {
if (isIdentityAndOwnershipPreservingRefCast(svi)) {
ref = svi->getOperand(0);
continue;
}
break;
}
return ref;
}
void swift::findGuaranteedReferenceRoots(SILValue referenceValue,
bool lookThroughNestedBorrows,
SmallVectorImpl<SILValue> &roots) {
ValueWorklist worklist(referenceValue->getFunction());
worklist.pushIfNotVisited(referenceValue);
while (auto value = worklist.pop()) {
// Instructions may forwarded None ownership to guaranteed.
if (value->getOwnershipKind() != OwnershipKind::Guaranteed)
continue;
if (SILArgument::asPhi(value)) {
roots.push_back(value);
continue;
}
if (visitForwardedGuaranteedOperands(value, [&](Operand *operand) {
worklist.pushIfNotVisited(operand->get());
})) {
// This instruction is not a root if any operands were forwarded,
// regardless of whether they were already visited.
continue;
}
// Found a potential root.
if (lookThroughNestedBorrows) {
if (auto *bbi = dyn_cast<BeginBorrowInst>(value)) {
auto borrowee = bbi->getOperand();
if (borrowee->getOwnershipKind() == OwnershipKind::Guaranteed) {
// A nested borrow, the root guaranteed earlier in the use-def chain.
worklist.pushIfNotVisited(borrowee);
continue;
}
// The borrowee isn't guaranteed or we aren't looking through nested
// borrows. Fall through to add the begin_borrow to roots.
}
}
roots.push_back(value);
}
}
/// Find the first owned aggregate containing the reference, or simply the
/// reference root if no aggregate is found.
///
/// TODO: Add a component path to a ReferenceRoot abstraction and handle
/// that within FindReferenceRoot.
SILValue swift::findOwnershipReferenceAggregate(SILValue ref) {
SILValue root = ref;
while(true) {
root = findOwnershipReferenceRoot(root);
if (!root)
return root;
if (auto *inst = root->getDefiningInstruction()) {
if (auto fwdOp = ForwardingOperation(inst)) {
if (auto *singleForwardingOp = fwdOp.getSingleForwardingOperand()) {
root = singleForwardingOp->get();
continue;
}
}
}
if (auto *termResult = SILArgument::isTerminatorResult(root)) {
if (auto *oper = termResult->forwardedTerminatorResultOperand()) {
root = oper->get();
continue;
}
}
break;
}
return root;
}
//===----------------------------------------------------------------------===//
// MARK: AccessStorage
//===----------------------------------------------------------------------===//
AccessStorage::AccessStorage(SILValue base, Kind kind)
: AccessRepresentation(base, kind)
{
if (isReference()) {
value = findReferenceRoot(getReferenceFromBase(base, kind));
// Class access is a "let" if it's base points to a stored property.
if (getKind() == AccessBase::Class) {
setLetAccess(isLetForBase(base));
}
// Box access is a "let" if it's root is from a "let" VarDecl.
if (getKind() == AccessBase::Box) {
if (auto *decl = dyn_cast_or_null<VarDecl>(getDecl())) {
setLetAccess(decl->isLet());
}
}
return;
}
if (getKind() == AccessBase::Global) {
global = getReferencedGlobal(cast<SingleValueInstruction>(base));
// It's unclear whether a global will ever be missing it's varDecl, but
// technically we only preserve it for debug info. So if we don't have a
// decl, check the flag on SILGlobalVariable, which is guaranteed valid.