-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathEscapeAnalysis.cpp
2956 lines (2675 loc) · 109 KB
/
EscapeAnalysis.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
//===--- EscapeAnalysis.cpp - SIL Escape Analysis -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-escape"
#include "swift/SILOptimizer/Analysis/EscapeAnalysis.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SILOptimizer/Analysis/ArraySemantic.h"
#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h"
#include "swift/SILOptimizer/PassManager/PassManager.h"
#include "swift/SILOptimizer/Utils/BasicBlockOptUtils.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
using CGNode = EscapeAnalysis::CGNode;
static llvm::cl::opt<bool> EnableInternalVerify(
"escapes-internal-verify",
llvm::cl::desc("Enable internal verification of escape analysis"),
llvm::cl::init(false));
// Returns the kind of pointer that \p Ty recursively contains.
EscapeAnalysis::PointerKind
EscapeAnalysis::findRecursivePointerKind(SILType Ty,
const SILFunction &F) const {
// An address may be converted into a reference via something like
// raw_pointer_to_ref, but in general we don't know what kind of pointer it
// is.
if (Ty.isAddress())
return EscapeAnalysis::AnyPointer;
// Opaque types may contain a reference. Speculatively track them too.
//
// 1. It may be possible to optimize opaque values based on known mutation
// points.
//
// 2. A specialized function may call a generic function passing a concrete
// reference type via incomplete specialization.
//
// 3. A generic function may call a specialized function taking a concrete
// reference type via devirtualization.
if (Ty.isAddressOnly(F))
return EscapeAnalysis::AnyPointer;
// A raw pointer definitely does not have a reference, but could point
// anywhere. We do track these because critical stdlib data structures often
// use raw pointers under the hood.
if (Ty.getASTType() == F.getModule().getASTContext().TheRawPointerType)
return EscapeAnalysis::AnyPointer;
if (Ty.hasReferenceSemantics())
return EscapeAnalysis::ReferenceOnly;
auto &M = F.getModule();
// Start with the most precise pointer kind
PointerKind aggregateKind = NoPointer;
auto meetAggregateKind = [&](PointerKind otherKind) {
if (otherKind > aggregateKind)
aggregateKind = otherKind;
};
if (auto *Str = Ty.getStructOrBoundGenericStruct()) {
for (auto *Field : Str->getStoredProperties()) {
SILType fieldTy = Ty.getFieldType(Field, M, F.getTypeExpansionContext())
.getObjectType();
meetAggregateKind(findCachedPointerKind(fieldTy, F));
}
return aggregateKind;
}
if (auto TT = Ty.getAs<TupleType>()) {
for (unsigned i = 0, e = TT->getNumElements(); i != e; ++i) {
meetAggregateKind(findCachedPointerKind(Ty.getTupleElementType(i), F));
}
return aggregateKind;
}
if (auto En = Ty.getEnumOrBoundGenericEnum()) {
for (auto *ElemDecl : En->getAllElements()) {
if (!ElemDecl->hasAssociatedValues())
continue;
SILType eltTy =
Ty.getEnumElementType(ElemDecl, M, F.getTypeExpansionContext());
meetAggregateKind(findCachedPointerKind(eltTy, F));
}
return aggregateKind;
}
// FIXME: without a covered switch, this is not robust in the event that new
// reference-holding AST types are invented.
return NoPointer;
}
// Return the PointerKind that summarizes a class's stored properties.
//
// If a class only holds fields of non-pointer types, then it is guaranteed not
// to point to any other objects.
EscapeAnalysis::PointerKind
EscapeAnalysis::findClassPropertiesPointerKind(SILType Ty,
const SILFunction &F) const {
if (Ty.isAddress())
return AnyPointer;
auto *classDecl = Ty.getClassOrBoundGenericClass();
if (!classDecl)
return AnyPointer;
auto &M = F.getModule();
auto expansion = F.getTypeExpansionContext();
// Start with the most precise pointer kind
PointerKind propertiesKind = NoPointer;
auto meetAggregateKind = [&](PointerKind otherKind) {
if (otherKind > propertiesKind)
propertiesKind = otherKind;
};
for (Type classTy = Ty.getASTType(); classTy;
classTy = classTy->getSuperclass()) {
classDecl = classTy->getClassOrBoundGenericClass();
assert(classDecl && "superclass must be a class");
// Return AnyPointer unless we have guaranteed visibility into all class and
// superclass properties. Use Minimal resilience expansion because the cache
// is not per-function.
if (classDecl->isResilient())
return AnyPointer;
// For each field in the class, get the pointer kind for that field. For
// reference-type properties, this will be ReferenceOnly. For aggregates, it
// will be the meet over all aggregate fields.
SILType objTy =
SILType::getPrimitiveObjectType(classTy->getCanonicalType());
for (VarDecl *property : classDecl->getStoredProperties()) {
SILType fieldTy =
objTy.getFieldType(property, M, expansion).getObjectType();
meetAggregateKind(findCachedPointerKind(fieldTy, F));
}
}
return propertiesKind;
}
// Returns the kind of pointer that \p Ty recursively contains.
EscapeAnalysis::PointerKind
EscapeAnalysis::findCachedPointerKind(SILType Ty, const SILFunction &F) const {
auto iter = pointerKindCache.find(Ty);
if (iter != pointerKindCache.end())
return iter->second;
PointerKind pointerKind = findRecursivePointerKind(Ty, F);
const_cast<EscapeAnalysis *>(this)->pointerKindCache[Ty] = pointerKind;
return pointerKind;
}
EscapeAnalysis::PointerKind
EscapeAnalysis::findCachedClassPropertiesKind(SILType Ty,
const SILFunction &F) const {
auto iter = classPropertiesKindCache.find(Ty);
if (iter != classPropertiesKindCache.end())
return iter->second;
PointerKind pointerKind = findClassPropertiesPointerKind(Ty, F);
const_cast<EscapeAnalysis *>(this)
->classPropertiesKindCache[Ty] = pointerKind;
return pointerKind;
}
// If EscapeAnalysis should consider the given value to be a derived address or
// pointer based on one of its address or pointer operands, then return that
// operand value. Otherwise, return an invalid value.
SILValue EscapeAnalysis::getPointerBase(SILValue value) {
switch (value->getKind()) {
case ValueKind::IndexAddrInst:
case ValueKind::IndexRawPointerInst:
case ValueKind::StructElementAddrInst:
case ValueKind::StructExtractInst:
case ValueKind::TupleElementAddrInst:
case ValueKind::InitExistentialAddrInst:
case ValueKind::OpenExistentialAddrInst:
case ValueKind::BeginAccessInst:
case ValueKind::UncheckedTakeEnumDataAddrInst:
case ValueKind::UncheckedEnumDataInst:
case ValueKind::MarkDependenceInst:
case ValueKind::PointerToAddressInst:
case ValueKind::AddressToPointerInst:
case ValueKind::InitEnumDataAddrInst:
case ValueKind::UncheckedRefCastInst:
case ValueKind::ConvertFunctionInst:
case ValueKind::UpcastInst:
case ValueKind::InitExistentialRefInst:
case ValueKind::OpenExistentialRefInst:
case ValueKind::RawPointerToRefInst:
case ValueKind::RefToRawPointerInst:
case ValueKind::RefToBridgeObjectInst:
case ValueKind::BridgeObjectToRefInst:
return cast<SingleValueInstruction>(value)->getOperand(0);
case ValueKind::UnconditionalCheckedCastInst:
case ValueKind::UncheckedAddrCastInst:
// DO NOT use LOADABLE_REF_STORAGE because unchecked references don't have
// retain/release instructions that trigger the 'default' case.
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
case ValueKind::RefTo##Name##Inst: \
case ValueKind::Name##ToRefInst:
#include "swift/AST/ReferenceStorage.def"
{
auto *svi = cast<SingleValueInstruction>(value);
SILValue op = svi->getOperand(0);
SILType srcTy = op->getType().getObjectType();
SILType destTy = value->getType().getObjectType();
SILFunction *f = svi->getFunction();
// If the source and destination of the cast don't agree on being a pointer,
// we bail. Otherwise we would miss important edges in the connection graph:
// e.g. loads of non-pointers are ignored, while it could be an escape of
// the value (which could be a pointer before the cast).
if (findCachedPointerKind(srcTy, *f) != findCachedPointerKind(destTy, *f))
return SILValue();
return op;
}
case ValueKind::TupleExtractInst: {
auto *TEI = cast<TupleExtractInst>(value);
// Special handling for extracting the pointer-result from an
// array construction. See createArrayUninitializedSubgraph.
if (canOptimizeArrayUninitializedResult(TEI))
return SILValue();
return TEI->getOperand();
}
case ValueKind::StructInst:
case ValueKind::TupleInst:
case ValueKind::EnumInst: {
// Allow a single-operand aggregate to share its operand's node.
auto *SVI = cast<SingleValueInstruction>(value);
SILValue pointerOperand;
for (SILValue opV : SVI->getOperandValues()) {
if (!isPointer(opV))
continue;
if (pointerOperand)
return SILValue();
pointerOperand = opV;
}
return pointerOperand;
}
case ValueKind::MultipleValueInstructionResult: {
if (auto *dt = dyn_cast<DestructureTupleInst>(value)) {
if (canOptimizeArrayUninitializedResult(dt))
return SILValue();
return dt->getOperand();
}
return SILValue();
}
default:
return SILValue();
}
}
// Recursively find the given value's pointer base. If the value cannot be
// represented in EscapeAnalysis as one of its operands, then return the same
// value.
SILValue EscapeAnalysis::getPointerRoot(SILValue value) {
while (true) {
if (SILValue v2 = getPointerBase(value))
value = v2;
else
break;
}
return value;
}
static bool isNonWritableMemoryAddress(SILValue V) {
switch (V->getKind()) {
case ValueKind::FunctionRefInst:
case ValueKind::DynamicFunctionRefInst:
case ValueKind::PreviousDynamicFunctionRefInst:
case ValueKind::WitnessMethodInst:
case ValueKind::ClassMethodInst:
case ValueKind::SuperMethodInst:
case ValueKind::ObjCMethodInst:
case ValueKind::ObjCSuperMethodInst:
case ValueKind::StringLiteralInst:
case ValueKind::ThinToThickFunctionInst:
// These instructions return pointers to memory which can't be a
// destination of a store.
return true;
default:
return false;
}
}
// Implement an intrusive worklist of CGNode. Only one may be in use at a time.
struct EscapeAnalysis::CGNodeWorklist {
llvm::SmallVector<CGNode *, 8> nodeVector;
EscapeAnalysis::ConnectionGraph *conGraph;
CGNodeWorklist(const CGNodeWorklist &) = delete;
CGNodeWorklist(EscapeAnalysis::ConnectionGraph *conGraph)
: conGraph(conGraph) {
conGraph->activeWorklist = this;
}
~CGNodeWorklist() { reset(); }
// Clear the intrusive isInWorkList flags, but leave the nodeVector vector in
// place for subsequent iteration.
void reset() {
ConnectionGraph::clearWorkListFlags(nodeVector);
conGraph->activeWorklist = nullptr;
}
unsigned size() const { return nodeVector.size(); }
bool empty() const { return nodeVector.empty(); }
bool contains(CGNode *node) const {
assert(conGraph->activeWorklist == this);
return node->isInWorkList;
}
CGNode *operator[](unsigned idx) const {
assert(idx < size());
return nodeVector[idx];
}
bool tryPush(CGNode *node) {
assert(conGraph->activeWorklist == this);
if (node->isInWorkList)
return false;
node->isInWorkList = true;
nodeVector.push_back(node);
return true;
}
void push(CGNode *node) {
assert(conGraph->activeWorklist == this);
assert(!node->isInWorkList);
node->isInWorkList = true;
nodeVector.push_back(node);
}
};
/// Mapping from nodes in a callee-graph to nodes in a caller-graph.
class EscapeAnalysis::CGNodeMap {
/// The map itself.
llvm::DenseMap<CGNode *, CGNode *> Map;
/// The list of source nodes (= keys in Map), which is used as a work-list.
CGNodeWorklist MappedNodes;
public:
CGNodeMap(ConnectionGraph *conGraph) : MappedNodes(conGraph) {}
CGNodeMap(const CGNodeMap &) = delete;
/// Adds a mapping and pushes the \p From node into the work-list
/// MappedNodes.
void add(CGNode *From, CGNode *To) {
assert(From && To && !From->isMerged && !To->isMerged);
Map[From] = To;
MappedNodes.tryPush(From);
}
/// Looks up a node in the mapping.
CGNode *get(CGNode *From) const {
auto Iter = Map.find(From);
if (Iter == Map.end())
return nullptr;
return Iter->second->getMergeTarget();
}
CGNodeWorklist &getMappedNodes() { return MappedNodes; }
};
//===----------------------------------------------------------------------===//
// ConnectionGraph Implementation
//===----------------------------------------------------------------------===//
std::pair<const CGNode *, unsigned> EscapeAnalysis::CGNode::getRepNode(
SmallPtrSetImpl<const CGNode *> &visited) const {
if (!isContent() || mappedValue)
return {this, 0};
for (Predecessor pred : Preds) {
if (!pred.is(EdgeType::PointsTo))
continue;
if (!visited.insert(pred.getPredNode()).second)
continue;
auto repNodeAndDepth = pred.getPredNode()->getRepNode(visited);
if (repNodeAndDepth.first)
return {repNodeAndDepth.first, repNodeAndDepth.second + 1};
// If a representative node was not found on this pointsTo node, recursion
// must have hit a cycle. Try the next pointsTo edge.
}
return {nullptr, 0};
}
EscapeAnalysis::CGNode::RepValue EscapeAnalysis::CGNode::getRepValue() const {
// We don't use CGNodeWorklist because CGNode::dump() should be callable
// anywhere, even while another worklist is active, and getRepValue() itself
// is not on any critical path.
SmallPtrSet<const CGNode *, 4> visited({this});
const CGNode *repNode;
unsigned depth;
std::tie(repNode, depth) = getRepNode(visited);
return {{repNode ? SILValue(repNode->mappedValue) : SILValue(),
repNode && repNode->Type == EscapeAnalysis::NodeType::Return},
depth};
}
void EscapeAnalysis::CGNode::mergeFlags(bool isInterior,
bool hasReferenceOnly) {
// isInterior is conservatively preserved from either node unless two content
// nodes are being merged and one is the interior node's content.
isInteriorFlag |= isInterior;
// hasReferenceOnly is always conservatively merged.
hasReferenceOnlyFlag &= hasReferenceOnly;
}
void EscapeAnalysis::CGNode::mergeProperties(CGNode *fromNode) {
// isInterior is conservatively preserved from either node unless the other
// node is the interior node's content.
bool isInterior = fromNode->isInteriorFlag;
if (fromNode == pointsTo)
this->isInteriorFlag = isInterior;
else if (this == fromNode->pointsTo)
isInterior = this->isInteriorFlag;
mergeFlags(isInterior, fromNode->hasReferenceOnlyFlag);
}
template <typename Visitor>
bool EscapeAnalysis::CGNode::visitSuccessors(Visitor &&visitor) const {
if (CGNode *pointsToSucc = getPointsToEdge()) {
// Visit pointsTo, even if pointsTo == this.
if (!visitor(pointsToSucc))
return false;
}
for (CGNode *def : defersTo) {
if (!visitor(def))
return false;
}
return true;
}
template <typename Visitor>
bool EscapeAnalysis::CGNode::visitDefers(Visitor &&visitor) const {
// Save predecessors before calling `visitor` which may assign pointsTo edges
// which invalidates the predecessor iterator.
SmallVector<Predecessor, 4> predVector(Preds.begin(), Preds.end());
for (Predecessor pred : predVector) {
if (!pred.is(EdgeType::Defer))
continue;
if (!visitor(pred.getPredNode(), false))
return false;
}
for (auto *deferred : defersTo) {
if (!visitor(deferred, true))
return false;
}
return true;
}
void EscapeAnalysis::ConnectionGraph::clear() {
Values2Nodes.clear();
Nodes.clear();
ReturnNode = nullptr;
UsePoints.clear();
UsePointTable.clear();
NodeAllocator.DestroyAll();
valid = true;
assert(ToMerge.empty());
}
// This never returns an interior node. It should never be called directly on an
// address projection of a reference. To get the interior node for an address
// projection, always ask for the content of the projection's base instead using
// getValueContent() or getReferenceContent().
//
// Address phis are not allowed, so merging an unknown address with a reference
// address projection is rare. If that happens, then the projection's node loses
// it's interior property.
EscapeAnalysis::CGNode *
EscapeAnalysis::ConnectionGraph::getNode(SILValue V) {
if (!isValid())
return nullptr;
// Early filter obvious non-pointer opcodes.
if (isa<FunctionRefInst>(V) || isa<DynamicFunctionRefInst>(V) ||
isa<PreviousDynamicFunctionRefInst>(V))
return nullptr;
// Create the node flags based on the derived value's kind. If the pointer
// base type has non-reference pointers but they are never accessed in the
// current function, then ignore them.
PointerKind pointerKind = EA->getPointerKind(V);
if (pointerKind == EscapeAnalysis::NoPointer)
return nullptr;
// Look past address projections, pointer casts, and the like within the same
// object. Does not look past a dereference such as ref_element_addr, or
// project_box.
SILValue ptrBase = EA->getPointerRoot(V);
// Do not create a node for undef values so we can verify that node values
// have the correct pointer kind.
if (!ptrBase->getFunction())
return nullptr;
assert(EA->isPointer(ptrBase) &&
"The base for derived pointer must also be a pointer type");
bool hasReferenceOnly = canOnlyContainReferences(pointerKind);
// Update the value-to-node map.
CGNode *&Node = Values2Nodes[ptrBase];
if (Node) {
CGNode *targetNode = Node->getMergeTarget();
targetNode->mergeFlags(false /*isInterior*/, hasReferenceOnly);
// Update the node in Values2Nodes, so that next time we don't need to find
// the final merge target.
Node = targetNode;
return targetNode;
}
if (isa<SILFunctionArgument>(ptrBase)) {
Node = allocNode(ptrBase, NodeType::Argument, false, hasReferenceOnly);
if (!isSummaryGraph)
Node->mergeEscapeState(EscapeState::Arguments);
} else
Node = allocNode(ptrBase, NodeType::Value, false, hasReferenceOnly);
return Node;
}
/// Adds an argument/instruction in which the node's memory is released.
int EscapeAnalysis::ConnectionGraph::addUsePoint(CGNode *Node,
SILInstruction *User) {
// Use points are never consulted for escaping nodes, but still need to
// propagate to other nodes in a defer web. Even if this node is escaping,
// some defer predecessors may not be escaping. Only checking if this node has
// defer predecessors is insufficient because a defer successor of this node
// may have defer predecessors.
if (Node->getEscapeState() >= EscapeState::Global)
return -1;
int Idx = (int)UsePoints.size();
assert(UsePoints.count(User) == 0 && "value is already a use-point");
UsePoints[User] = Idx;
UsePointTable.push_back(User);
assert(UsePoints.size() == UsePointTable.size());
Node->setUsePointBit(Idx);
return Idx;
}
CGNode *EscapeAnalysis::ConnectionGraph::defer(CGNode *From, CGNode *To,
bool &Changed) {
if (!From->canAddDeferred(To))
return From;
CGNode *FromPointsTo = From->pointsTo;
CGNode *ToPointsTo = To->pointsTo;
// If necessary, merge nodes while the graph is still in a valid state.
if (FromPointsTo && ToPointsTo && FromPointsTo != ToPointsTo) {
// We are adding an edge between two pointers which point to different
// content nodes. This will require merging the content nodes (and maybe
// other content nodes as well), because of the graph invariance 4).
//
// Once the pointee's are merged, the defer edge can be added without
// creating an inconsistency.
scheduleToMerge(FromPointsTo, ToPointsTo);
mergeAllScheduledNodes();
Changed = true;
}
// 'From' and 'To' may have been merged, so addDeferred may no longer succeed.
if (From->getMergeTarget()->addDeferred(To->getMergeTarget()))
Changed = true;
// If pointsTo on either side of the defer was uninitialized, initialize that
// side of the defer web. Do this after adding the new edge to avoid creating
// useless pointsTo edges.
if (!FromPointsTo && ToPointsTo)
initializePointsTo(From, ToPointsTo);
else if (FromPointsTo && !ToPointsTo)
initializePointsTo(To, FromPointsTo);
return From->getMergeTarget();
}
// Precondition: The pointsTo fields of all nodes in initializeNode's defer web
// are either uninitialized or already initialized to newPointsTo.
void EscapeAnalysis::ConnectionGraph::initializePointsTo(CGNode *initialNode,
CGNode *newPointsTo,
bool createEdge) {
// Track nodes that require pointsTo edges.
llvm::SmallVector<CGNode *, 4> pointsToEdgeNodes;
if (createEdge)
pointsToEdgeNodes.push_back(initialNode);
// Step 1: Visit each node that reaches or is reachable via defer edges until
// reaching a node with the newPointsTo or with a proper pointsTo edge.
// A worklist to gather updated nodes in the defer web.
CGNodeWorklist updatedNodes(this);
unsigned updateCount = 0;
auto visitDeferTarget = [&](CGNode *node, bool /*isSuccessor*/) {
if (updatedNodes.contains(node))
return true;
if (node->pointsTo) {
assert(node->pointsTo == newPointsTo);
// Since this node already had a pointsTo, it must reach a pointsTo
// edge. Stop traversing the defer-web here--this is complete becaused
// nodes are initialized one at a time, each time a new defer edge is
// created. If this were not complete, then the backward traversal below
// in Step 2 could reach uninitialized nodes not seen here in Step 1.
pointsToEdgeNodes.push_back(node);
return true;
}
++updateCount;
if (node->defersTo.empty()) {
// If this node is the end of a defer-edge path with no pointsTo
// edge. Create a "fake" pointsTo edge to maintain the graph invariant
// (this changes the structure of the graph but adding this edge has no
// effect on the process of merging nodes or creating new defer edges).
pointsToEdgeNodes.push_back(node);
}
updatedNodes.push(node);
return true;
};
// Seed updatedNodes with initialNode.
visitDeferTarget(initialNode, true);
// updatedNodes may grow during this loop.
for (unsigned idx = 0; idx < updatedNodes.size(); ++idx)
updatedNodes[idx]->visitDefers(visitDeferTarget);
// Reset this worklist so others can be used, but updateNode.nodeVector still
// holds all the nodes found by step 1.
updatedNodes.reset();
// Step 2: Update pointsTo fields by propagating backward from nodes that
// already have a pointsTo edge.
do {
while (!pointsToEdgeNodes.empty()) {
CGNode *edgeNode = pointsToEdgeNodes.pop_back_val();
if (!edgeNode->pointsTo) {
// This node is either (1) a leaf node in the defer web (identified in
// step 1) or (2) an arbitrary node in a defer-cycle (identified in a
// previous iteration of the outer loop).
edgeNode->setPointsToEdge(newPointsTo);
newPointsTo->mergeUsePoints(edgeNode);
assert(updateCount--);
}
// If edgeNode is already set to newPointsTo, it either was already
// up-to-date before calling initializePointsTo, or it was visited during
// a previous iteration of the backward traversal below. Rather than
// distinguish these cases, always retry backward traversal--it just won't
// revisit any edges in the later case.
backwardTraverse(edgeNode, [&](Predecessor pred) {
if (!pred.is(EdgeType::Defer))
return Traversal::Backtrack;
CGNode *predNode = pred.getPredNode();
if (predNode->pointsTo) {
assert(predNode->pointsTo->getMergeTarget()
== newPointsTo->getMergeTarget());
return Traversal::Backtrack;
}
predNode->pointsTo = newPointsTo;
newPointsTo->mergeUsePoints(predNode);
assert(updateCount--);
return Traversal::Follow;
});
}
// For all nodes visited in step 1, pick a single node that was not
// backward-reachable from a pointsTo edge, create an edge for it and
// restart traversal. This only happens when step 1 fails to find leaves in
// the defer web because of defer edge cycles.
while (!updatedNodes.empty()) {
CGNode *node = updatedNodes.nodeVector.pop_back_val();
if (!node->pointsTo) {
pointsToEdgeNodes.push_back(node);
break;
}
}
// This outer loop is exceedingly unlikely to execute more than twice.
} while (!pointsToEdgeNodes.empty());
assert(updateCount == 0);
}
void EscapeAnalysis::ConnectionGraph::mergeAllScheduledNodes() {
// Each merge step is self contained and verifiable, with one exception. When
// merging a node that points to itself with a node points to another node,
// multiple merge steps are necessary to make the defer web consistent.
// Example:
// NodeA pointsTo-> From
// From defersTo-> NodeA (an indirect self-cycle)
// To pointsTo-> NodeB
// Merged:
// NodeA pointsTo-> To
// To defersTo-> NodeA (To *should* pointTo itself)
// To pointsTo-> NodeB (but still has a pointsTo edge to NodeB)
while (!ToMerge.empty()) {
if (EnableInternalVerify)
verifyStructure(true /*allowMerge*/);
CGNode *From = ToMerge.pop_back_val();
CGNode *To = From->getMergeTarget();
assert(To != From && "Node scheduled to merge but no merge target set");
assert(!From->isMerged && "Merge source is already merged");
assert(From->Type == NodeType::Content && "Can only merge content nodes");
assert(To->Type == NodeType::Content && "Can only merge content nodes");
// Redirect the incoming pointsTo edge and unlink the defer predecessors.
//
// Don't redirect the defer-edges because it may trigger mergePointsTo() or
// initializePointsTo(). By ensuring that 'From' is unreachable first, the
// graph appears consistent during those operations.
for (Predecessor Pred : From->Preds) {
CGNode *PredNode = Pred.getPredNode();
if (Pred.is(EdgeType::PointsTo)) {
assert(PredNode->getPointsToEdge() == From
&& "Incoming pointsTo edge not set in predecessor");
if (PredNode != From)
PredNode->setPointsToEdge(To);
} else {
assert(PredNode != From);
auto Iter = PredNode->findDeferred(From);
assert(Iter != PredNode->defersTo.end()
&& "Incoming defer-edge not found in predecessor's defer list");
PredNode->defersTo.erase(Iter);
}
}
// Unlink the outgoing defer edges.
for (CGNode *Defers : From->defersTo) {
assert(Defers != From && "defer edge may not form a self-cycle");
Defers->removeFromPreds(Predecessor(From, EdgeType::Defer));
}
// Handle self-cycles on From by creating a self-cycle at To.
auto redirectPointsTo = [&](CGNode *pointsTo) {
return (pointsTo == From) ? To : pointsTo;
};
// Redirect the outgoing From -> pointsTo edge.
if (From->pointsToIsEdge) {
From->pointsTo->removeFromPreds(Predecessor(From, EdgeType::PointsTo));
if (To->pointsToIsEdge) {
// If 'To' had a pointsTo edge to 'From', then it was redirected above.
// Otherwise FromPT and ToPT will be merged below; nothing to do here.
assert(To->pointsTo != From);
} else {
// If 'To' has no pointsTo at all, initialize its defer web.
if (!To->pointsTo)
initializePointsToEdge(To, redirectPointsTo(From->pointsTo));
else {
// Upgrade 'To's pointsTo to an edge to preserve the fact that 'From'
// had a pointsTo edge.
To->pointsToIsEdge = true;
To->pointsTo = redirectPointsTo(To->pointsTo);
To->pointsTo->Preds.push_back(Predecessor(To, EdgeType::PointsTo));
}
}
}
// Merge 'From->pointsTo' and 'To->pointsTo' if needed, regardless of
// whether either is a proper edge. Merging may be needed because other
// nodes may have points-to edges to From->PointsTo that won't be visited
// when updating 'From's defer web.
//
// If To doesn't already have a points-to, it will simply be initialized
// when updating the merged defer web below.
if (CGNode *toPT = To->pointsTo) {
// If 'To' already points to 'From', then it will already point to 'From's
// pointTo after merging. An additional merge would be too conservative.
if (From->pointsTo && toPT != From)
scheduleToMerge(redirectPointsTo(From->pointsTo), toPT);
}
// Redirect adjacent defer edges, and immediately update all points-to
// fields in the defer web.
//
// Calling initializePointsTo may create new pointsTo edges from nodes in
// the defer-web. It is unsafe to mutate or query the graph in its currently
// inconsistent state. However, this particular case is safe because:
// - The graph is only locally inconsistent w.r.t. nodes still connected to
// 'From' via defer edges.
// - 'From' itself is no longer reachable via graph edges (it may only be
// referenced in points-to fields which haven't all been updated).
// - Calling initializePointsTo on one from 'From's deferred nodes implies
// that all nodes in 'From's defer web had a null pointsTo.
// - 'To's defer web remains consistent each time a new defer edge is
// added below. Any of 'To's existing deferred nodes either still need to
// be initialized or have already been initialized to the same pointsTo.
//
// Start by updating 'To's own pointsTo field.
if (To->pointsTo == From)
mergePointsTo(To, To);
auto mergeDeferPointsTo = [&](CGNode *deferred, bool isSuccessor) {
assert(From != deferred && "defer edge may not form a self-cycle");
if (To == deferred)
return true;
// In case 'deferred' points to 'From', update its pointsTo before
// exposing it to 'To's defer web.
if (deferred->pointsTo == From)
mergePointsTo(deferred, To);
if (isSuccessor)
To->addDeferred(deferred);
else
deferred->addDeferred(To);
if (deferred->pointsTo && To->pointsTo)
mergePointsTo(deferred, To->pointsTo);
else if (deferred->pointsTo)
initializePointsTo(To, deferred->pointsTo);
else if (To->pointsTo)
initializePointsTo(deferred, To->pointsTo);
return true;
};
// Redirect the adjacent defer edges.
From->visitDefers(mergeDeferPointsTo);
// Update the web of nodes that originally pointed to 'From' via 'From's old
// pointsTo predecessors (which are now attached to 'To').
for (unsigned PredIdx = 0; PredIdx < To->Preds.size(); ++PredIdx) {
auto predEdge = To->Preds[PredIdx];
if (!predEdge.is(EdgeType::PointsTo))
continue;
predEdge.getPredNode()->visitDefers(
[&](CGNode *deferred, bool /*isSucc*/) {
mergePointsTo(deferred, To);
return true;
});
}
To->mergeEscapeState(From->State);
// Cleanup the merged node.
From->isMerged = true;
if (From->mappedValue) {
// values previously mapped to 'From' but not transferred to 'To's
// mappedValue must remain mapped to 'From'. Lookups on those values will
// find 'To' via the mergeTarget and will remap those values to 'To'
// on-the-fly for efficiency. Dropping a value's mapping is illegal
// because it could cause a node to be recreated without the edges that
// have already been discovered.
if (!To->mappedValue) {
To->mappedValue = From->mappedValue;
Values2Nodes[To->mappedValue] = To;
}
From->mappedValue = nullptr;
}
From->Preds.clear();
From->defersTo.clear();
From->pointsTo = nullptr;
}
if (EnableInternalVerify)
verifyStructure(true /*allowMerge*/);
}
// As a result of a merge, update the pointsTo field of initialNode and
// everything in its defer web to newPointsTo.
//
// This may modify the graph by redirecting a pointsTo edges.
void EscapeAnalysis::ConnectionGraph::mergePointsTo(CGNode *initialNode,
CGNode *newPointsTo) {
CGNode *oldPointsTo = initialNode->pointsTo;
assert(oldPointsTo && "merging content should not initialize any pointsTo");
// newPointsTo may already be scheduled for a merge. Only create new edges to
// unmerged nodes. This may create a temporary pointsTo mismatch in the defer
// web, but Graph verification takes merged nodes into consideration.
newPointsTo = newPointsTo->getMergeTarget();
if (oldPointsTo == newPointsTo)
return;
CGNodeWorklist updateNodes(this);
auto updatePointsTo = [&](CGNode *node) {
if (node->pointsTo == newPointsTo)
return;
// If the original graph was: 'node->From->To->newPointsTo' or
// 'node->From->From', then node is already be updated to point to
// 'To' and 'To' must be merged with newPointsTo. We must still update
// pointsTo so that all nodes in the defer web have the same pointsTo.
assert(node->pointsTo == oldPointsTo
|| node->pointsTo->getMergeTarget() == newPointsTo);
if (node->pointsToIsEdge) {
node->pointsTo->removeFromPreds(Predecessor(node, EdgeType::PointsTo));
node->setPointsToEdge(newPointsTo);
} else
node->pointsTo = newPointsTo;
updateNodes.push(node);
};
updatePointsTo(initialNode);
// Visit each node that reaches or is reachable via defer edges until reaching
// a node with the newPointsTo.
auto visitDeferTarget = [&](CGNode *node, bool /*isSuccessor*/) {
if (!updateNodes.contains(node))
updatePointsTo(node);
return true;
};
for (unsigned Idx = 0; Idx < updateNodes.size(); ++Idx)
updateNodes[Idx]->visitDefers(visitDeferTarget);
}
void EscapeAnalysis::ConnectionGraph::propagateEscapeStates() {
bool Changed = false;
do {
Changed = false;
for (CGNode *Node : Nodes) {
// Propagate the state to all pointsTo nodes. It would be sufficient to
// only follow proper pointsTo edges, since this loop also follows defer
// edges, but this may converge faster.
if (Node->pointsTo) {
Changed |= Node->pointsTo->mergeEscapeState(Node->State);
}
// Note: Propagating along defer edges may be interesting from an SSA
// standpoint, but it is entirely irrelevant alias analysis.
for (CGNode *Def : Node->defersTo) {
Changed |= Def->mergeEscapeState(Node->State);
}
}
} while (Changed);
}
void EscapeAnalysis::ConnectionGraph::computeUsePoints() {
#ifndef NDEBUG
for (CGNode *Nd : Nodes)
assert(Nd->UsePoints.empty() && "premature use point computation");
#endif
// First scan the whole function and add relevant instructions as use-points.
for (auto &BB : *F) {
for (auto &I : BB) {
switch (I.getKind()) {
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
case SILInstructionKind::Name##ReleaseInst:
#include "swift/AST/ReferenceStorage.def"
case SILInstructionKind::StrongReleaseInst:
case SILInstructionKind::ReleaseValueInst:
case SILInstructionKind::DestroyValueInst:
case SILInstructionKind::ApplyInst:
case SILInstructionKind::TryApplyInst: {
/// Actually we only add instructions which may release a reference.
/// We need the use points only for getting the end of a reference's
/// liferange. And that must be a releasing instruction.
int ValueIdx = -1;
for (const Operand &Op : I.getAllOperands()) {
CGNode *content = getValueContent(Op.get());
if (!content)
continue;
if (ValueIdx < 0)
ValueIdx = addUsePoint(content, &I);
else
content->setUsePointBit(ValueIdx);
}
break;
}
default:
break;
}
}
}
// Second, we propagate the use-point information through the graph.
bool Changed = false;
do {
Changed = false;
for (CGNode *Node : Nodes) {
// Propagate the bits to pointsTo. A release of a node may also release
// any content pointed to be the node.
if (Node->pointsTo)
Changed |= Node->pointsTo->mergeUsePoints(Node);
}
} while (Changed);
}
CGNode *EscapeAnalysis::ConnectionGraph::createContentNode(
CGNode *addrNode, bool isInterior, bool hasReferenceOnly) {
CGNode *newContent =
allocNode(nullptr, NodeType::Content, isInterior, hasReferenceOnly);
initializePointsToEdge(addrNode, newContent);
return newContent;
}
CGNode *EscapeAnalysis::ConnectionGraph::getOrCreateContentNode(
CGNode *addrNode, bool isInterior, bool hasReferenceOnly) {
if (CGNode *content = addrNode->getContentNodeOrNull()) {
content->mergeFlags(isInterior, hasReferenceOnly);
return content;
}
CGNode *content = createContentNode(addrNode, isInterior, hasReferenceOnly);
// getValueContent may be called after the graph is built and escape states
// are propagated. Keep the escape state and use points consistent here.
content->mergeEscapeState(addrNode->State);
content->mergeUsePoints(addrNode);
return content;
}
// Create a content node for merging based on an address node in the destination