-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathCapturePromotion.cpp
1660 lines (1445 loc) · 62.9 KB
/
CapturePromotion.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
//===--- CapturePromotion.cpp - Promotes closure captures -----------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Promotes captures from 'inout' (i.e. by-reference) to by-value
/// ==============================================================
///
/// Swift's closure model is that all local variables are capture by reference.
/// This produces a very simple programming model which is great to use, but
/// relies on the optimizer to promote by-ref captures to by-value (i.e.
/// by-copy) captures for decent performance. Consider this simple example:
///
/// func foo(a : () -> ()) {} // assume this has an unknown body
///
/// func bar() {
/// var x = 42
///
/// foo({ print(x) })
/// }
///
/// Since x is captured by-ref by the closure, x must live on the heap. By
/// looking at bar without any knowledge of foo, we can know that it is safe to
/// promote this to a by-value capture, allowing x to live on the stack under
/// the following conditions:
///
/// 1. If x is not modified in the closure body and is only loaded.
/// 2. If we can prove that all mutations to x occur before the closure is
/// formed.
///
/// Under these conditions if x is loadable then we can even load the given
/// value and pass it as a scalar instead of an address.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-capture-promotion"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/FrozenMultiMap.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/SILCloner.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/TypeSubstCloner.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "swift/SILOptimizer/Utils/SpecializationMangler.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include <tuple>
using namespace swift;
STATISTIC(NumCapturesPromoted, "Number of captures promoted");
namespace {
using IndicesSet = llvm::SmallSet<unsigned, 4>;
using PartialApplyIndicesMap = llvm::DenseMap<PartialApplyInst *, IndicesSet>;
} // anonymous namespace
//===----------------------------------------------------------------------===//
// Reachability Utilities
//===----------------------------------------------------------------------===//
namespace {
/// Transient reference to a block set within ReachabilityInfo.
///
/// This is a bitset that conveniently flattens into a matrix allowing bit-wise
/// operations without masking.
///
/// TODO: If this sticks around, maybe we'll make a BitMatrix ADT.
class ReachingBlockSet {
public:
enum { BITWORD_SIZE = (unsigned)sizeof(uint64_t) * CHAR_BIT };
constexpr static size_t numBitWordsForNumBlocks(unsigned NumBlocks) {
return (NumBlocks + BITWORD_SIZE - 1) / BITWORD_SIZE;
}
/// Transient reference to a reaching block matrix.
struct ReachingBlockMatrix {
uint64_t *bits;
unsigned numBitWords; // Words per row.
ReachingBlockMatrix() : bits(nullptr), numBitWords(0) {}
bool empty() const { return !bits; }
};
static ReachingBlockMatrix allocateMatrix(unsigned numBlocks) {
ReachingBlockMatrix m;
m.numBitWords = numBitWordsForNumBlocks(numBlocks);
m.bits = new uint64_t[numBlocks * m.numBitWords];
memset(m.bits, 0, numBlocks * m.numBitWords * sizeof(uint64_t));
return m;
}
static void deallocateMatrix(ReachingBlockMatrix &m) {
delete[] m.bits;
m.bits = nullptr;
m.numBitWords = 0;
}
static ReachingBlockSet allocateSet(unsigned numBlocks) {
ReachingBlockSet s;
s.numBitWords = numBitWordsForNumBlocks(numBlocks);
s.bits = new uint64_t[s.numBitWords];
return s;
}
static void deallocateSet(ReachingBlockSet &s) {
delete[] s.bits;
s.bits = nullptr;
s.numBitWords = 0;
}
private:
uint64_t *bits;
unsigned numBitWords;
public:
ReachingBlockSet() : bits(nullptr), numBitWords(0) {}
ReachingBlockSet(unsigned blockID, ReachingBlockMatrix &m)
: bits(&m.bits[blockID * m.numBitWords]), numBitWords(m.numBitWords) {}
bool test(unsigned id) const {
assert(id / BITWORD_SIZE < numBitWords && "block ID out-of-bounds");
unsigned int modulus = id % BITWORD_SIZE;
long shifted = 1L << modulus;
return bits[id / BITWORD_SIZE] & shifted;
}
void set(unsigned id) {
unsigned int modulus = id % BITWORD_SIZE;
long shifted = 1L << modulus;
assert(id / BITWORD_SIZE < numBitWords && "block ID out-of-bounds");
bits[id / BITWORD_SIZE] |= shifted;
}
ReachingBlockSet &operator|=(const ReachingBlockSet &rhs) {
for (unsigned i : range(numBitWords))
bits[i] |= rhs.bits[i];
return *this;
}
void clear() { memset(bits, 0, numBitWords * sizeof(uint64_t)); }
bool operator==(const ReachingBlockSet &rhs) const {
assert(numBitWords == rhs.numBitWords && "mismatched sets");
for (unsigned i : range(numBitWords))
if (bits[i] != rhs.bits[i])
return false;
return true;
}
bool operator!=(const ReachingBlockSet &rhs) const { return !(*this == rhs); }
ReachingBlockSet(const ReachingBlockSet &rhs)
: bits(rhs.bits), numBitWords(rhs.numBitWords) {}
const ReachingBlockSet &operator=(const ReachingBlockSet &RHS) {
assert(numBitWords == RHS.numBitWords && "mismatched sets");
for (unsigned i : range(numBitWords))
bits[i] = RHS.bits[i];
return *this;
}
};
/// Store the reachability matrix: ToBlock -> FromBlocks.
class ReachabilityInfo {
SILFunction *f;
llvm::DenseMap<SILBasicBlock *, unsigned> blockMap;
ReachingBlockSet::ReachingBlockMatrix matrix;
public:
ReachabilityInfo(SILFunction *f) : f(f) {}
~ReachabilityInfo() { ReachingBlockSet::deallocateMatrix(matrix); }
bool isComputed() const { return !matrix.empty(); }
bool isReachable(SILBasicBlock *From, SILBasicBlock *To);
private:
void compute();
};
} // end anonymous namespace
/// Compute ReachabilityInfo so that it can answer queries about
/// whether a given basic block in a function is reachable from another basic
/// block in the function.
///
/// FIXME: Computing global reachability requires initializing an N^2
/// bitset. This could be avoided by computing reachability on-the-fly
/// for each alloc_box by walking backward from mutations.
void ReachabilityInfo::compute() {
assert(!isComputed() && "already computed");
unsigned n = 0;
for (auto &block : *f)
blockMap.insert({&block, n++});
matrix = ReachingBlockSet::allocateMatrix(n);
ReachingBlockSet newSet = ReachingBlockSet::allocateSet(n);
LLVM_DEBUG(llvm::dbgs() << "Computing Reachability for " << f->getName()
<< " with " << n << " blocks.\n");
// Iterate to a fix point, two times for a topological DAG.
bool madeChange;
do {
madeChange = false;
// Visit all blocks in a predictable order, hopefully close to topological.
for (auto &block : *f) {
ReachingBlockSet curSet(blockMap[&block], matrix);
if (!madeChange) {
// If we have not detected a change yet, then calculate new
// reachabilities into a new bit vector so we can determine if any
// change has occurred.
newSet = curSet;
for (auto pi = block.pred_begin(), pe = block.pred_end(); pi != pe;
++pi) {
unsigned predID = blockMap[*pi];
ReachingBlockSet predSet(predID, matrix);
newSet |= predSet;
newSet.set(predID);
}
if (newSet != curSet) {
curSet = newSet;
madeChange = true;
}
} else {
// Otherwise, just update the existing reachabilities in-place.
for (auto *predBlock : block.getPredecessorBlocks()) {
unsigned predID = blockMap[predBlock];
ReachingBlockSet predSet(predID, matrix);
curSet |= predSet;
curSet.set(predID);
}
}
LLVM_DEBUG(llvm::dbgs()
<< " Block " << blockMap[&block] << " reached by ";
for (unsigned i
: range(n)) {
if (curSet.test(i))
llvm::dbgs() << i << " ";
} llvm::dbgs()
<< "\n");
}
} while (madeChange);
ReachingBlockSet::deallocateSet(newSet);
}
/// Return true if the To basic block is reachable from the From basic
/// block. A block is considered reachable from itself only if its entry can be
/// recursively reached from its own exit.
bool ReachabilityInfo::isReachable(SILBasicBlock *fromBlock,
SILBasicBlock *toBlock) {
if (!isComputed())
compute();
auto fi = blockMap.find(fromBlock), ti = blockMap.find(toBlock);
assert(fi != blockMap.end() && ti != blockMap.end());
ReachingBlockSet fromSet(ti->second, matrix);
return fromSet.test(fi->second);
}
//===----------------------------------------------------------------------===//
// ClosureCloner
//===----------------------------------------------------------------------===//
namespace {
/// A SILCloner subclass which clones a closure function while converting
/// one or more captures from 'inout' (by-reference) to by-value.
class ClosureCloner : public SILClonerWithScopes<ClosureCloner> {
public:
friend class SILInstructionVisitor<ClosureCloner>;
friend class SILCloner<ClosureCloner>;
ClosureCloner(SILOptFunctionBuilder &funcBuilder, SILFunction *orig,
SerializedKind_t serialized, StringRef clonedName,
IndicesSet &promotableIndices, ResilienceExpansion expansion);
void populateCloned();
SILFunction *getCloned() { return &getBuilder().getFunction(); }
static SILFunction *
constructClonedFunction(SILOptFunctionBuilder &funcBuilder,
PartialApplyInst *pai, FunctionRefInst *fri,
IndicesSet &promotableIndices,
ResilienceExpansion resilienceExpansion);
private:
static SILFunction *initCloned(SILOptFunctionBuilder &funcBuilder,
SILFunction *orig, SerializedKind_t serialized,
StringRef clonedName,
IndicesSet &promotableIndices,
ResilienceExpansion expansion);
SILValue getProjectBoxMappedVal(SILValue operandValue);
void visitDebugValueInst(DebugValueInst *inst);
void visitDestroyValueInst(DestroyValueInst *inst);
void visitStructElementAddrInst(StructElementAddrInst *inst);
void visitLoadInst(LoadInst *inst);
void visitLoadBorrowInst(LoadBorrowInst *inst);
void visitEndBorrowInst(EndBorrowInst *inst);
void visitProjectBoxInst(ProjectBoxInst *inst);
void visitBeginAccessInst(BeginAccessInst *inst);
void visitEndAccessInst(EndAccessInst *inst);
ResilienceExpansion resilienceExpansion;
SILFunction *origF;
IndicesSet &promotableIndices;
llvm::DenseMap<SILArgument *, SILValue> boxArgumentMap;
llvm::DenseMap<ProjectBoxInst *, SILValue> projectBoxArgumentMap;
};
} // end anonymous namespace
ClosureCloner::ClosureCloner(SILOptFunctionBuilder &funcBuilder,
SILFunction *orig, SerializedKind_t serialized,
StringRef clonedName,
IndicesSet &promotableIndices,
ResilienceExpansion resilienceExpansion)
: SILClonerWithScopes<ClosureCloner>(
*initCloned(funcBuilder, orig, serialized, clonedName,
promotableIndices, resilienceExpansion)),
origF(orig), promotableIndices(promotableIndices) {
assert(orig->getDebugScope()->Parent != getCloned()->getDebugScope()->Parent);
}
/// Compute the SILParameterInfo list for the new cloned closure.
///
/// Our goal as a result of this transformation is to:
///
/// 1. Let through all arguments not related to a promotable box.
/// 2. Replace container box value arguments for the cloned closure with the
/// transformed address or value argument.
static void
computeNewArgInterfaceTypes(SILFunction *f, IndicesSet &promotableIndices,
SmallVectorImpl<SILParameterInfo> &outTys,
ResilienceExpansion expansion) {
auto fnConv = f->getConventions();
auto parameters = fnConv.funcTy->getParameters();
LLVM_DEBUG(llvm::dbgs() << "Preparing New Args!\n");
auto &types = f->getModule().Types;
// For each parameter in the old function...
for (unsigned index : indices(parameters)) {
auto ¶m = parameters[index];
// The PromotableIndices index is expressed as the argument index (num
// indirect result + param index). Add back the num indirect results to get
// the arg index when working with PromotableIndices.
unsigned argIndex = index + fnConv.getSILArgIndexOfFirstParam();
LLVM_DEBUG(llvm::dbgs()
<< "Index: " << index << "; PromotableIndices: "
<< (promotableIndices.count(argIndex) ? "yes" : "no")
<< " Param: ";
param.print(llvm::dbgs()));
if (!promotableIndices.count(argIndex)) {
outTys.push_back(param);
continue;
}
// Perform the proper conversions and then add it to the new parameter list
// for the type.
assert(!param.isFormalIndirect());
auto paramTy =
param.getSILStorageType(fnConv.silConv.getModule(), fnConv.funcTy,
TypeExpansionContext::minimal());
auto paramBoxTy = paramTy.castTo<SILBoxType>();
assert(paramBoxTy->getLayout()->getFields().size() == 1 &&
"promoting compound box not implemented yet");
auto paramBoxedTy =
getSILBoxFieldType(TypeExpansionContext(*f), paramBoxTy, types, 0);
assert(expansion == f->getResilienceExpansion());
auto ¶mTL = types.getTypeLowering(paramBoxedTy, *f);
ParameterConvention convention;
if (paramTL.isAddressOnly()) {
convention = ParameterConvention::Indirect_In;
} else if (paramTL.isTrivial()) {
convention = ParameterConvention::Direct_Unowned;
} else {
convention = param.isGuaranteedInCallee()
? ParameterConvention::Direct_Guaranteed
: ParameterConvention::Direct_Owned;
}
outTys.push_back(SILParameterInfo(paramBoxedTy.getASTType(), convention,
param.getOptions()));
}
}
static std::string getSpecializedName(SILFunction *f,
SerializedKind_t serialized,
IndicesSet &promotableIndices) {
auto p = Demangle::SpecializationPass::CapturePromotion;
Mangle::FunctionSignatureSpecializationMangler mangler(f->getASTContext(), p, serialized, f);
auto fnConv = f->getConventions();
for (unsigned argIdx = 0, endIdx = fnConv.getNumSILArguments();
argIdx < endIdx; ++argIdx) {
if (!promotableIndices.count(argIdx))
continue;
mangler.setArgumentBoxToValue(argIdx);
}
return mangler.mangle();
}
/// Create the function corresponding to the clone of the original
/// closure with the signature modified to reflect promotable captures (which
/// are given by PromotableIndices, such that each entry in the set is the
/// index of the box containing the variable in the closure's argument list, and
/// the address of the box's contents is the argument immediately following each
/// box argument); does not actually clone the body of the function
///
/// *NOTE* PromotableIndices only contains the container value of the box, not
/// the address value.
SILFunction *
ClosureCloner::initCloned(SILOptFunctionBuilder &functionBuilder,
SILFunction *orig, SerializedKind_t serialized,
StringRef clonedName, IndicesSet &promotableIndices,
ResilienceExpansion resilienceExpansion) {
SILModule &mod = orig->getModule();
// Compute the arguments for our new function.
SmallVector<SILParameterInfo, 4> clonedInterfaceArgTys;
computeNewArgInterfaceTypes(orig, promotableIndices, clonedInterfaceArgTys,
resilienceExpansion);
SILFunctionType *origFTI = orig->getLoweredFunctionType();
// Create the thin function type for the cloned closure.
auto clonedTy = SILFunctionType::get(
origFTI->getInvocationGenericSignature(), origFTI->getExtInfo(),
origFTI->getCoroutineKind(), origFTI->getCalleeConvention(),
clonedInterfaceArgTys, origFTI->getYields(), origFTI->getResults(),
origFTI->getOptionalErrorResult(),
origFTI->getPatternSubstitutions(),
origFTI->getInvocationSubstitutions(),
mod.getASTContext(), origFTI->getWitnessMethodConformanceOrInvalid());
assert((orig->isTransparent() || orig->isBare() || orig->getLocation()) &&
"SILFunction missing location");
assert((orig->isTransparent() || orig->isBare() || orig->getDebugScope()) &&
"SILFunction missing DebugScope");
assert(!orig->isGlobalInit() && "Global initializer cannot be cloned");
auto *fn = functionBuilder.createFunction(
orig->getLinkage(), clonedName, clonedTy, orig->getGenericEnvironment(),
orig->getLocation(), orig->isBare(), IsNotTransparent, serialized,
IsNotDynamic, IsNotDistributed, IsNotRuntimeAccessible,
orig->getEntryCount(), orig->isThunk(), orig->getClassSubclassScope(),
orig->getInlineStrategy(), orig->getEffectsKind(), orig,
orig->getDebugScope());
for (auto &attr : orig->getSemanticsAttrs())
fn->addSemanticsAttr(attr);
return fn;
}
/// Populate the body of the cloned closure, modifying instructions as
/// necessary to take into consideration the promoted capture(s)
void ClosureCloner::populateCloned() {
SILFunction *cloned = getCloned();
// Create arguments for the entry block
SILBasicBlock *origEntryBB = &*origF->begin();
SILBasicBlock *clonedEntryBB = cloned->createBasicBlock();
getBuilder().setInsertionPoint(clonedEntryBB);
SmallVector<SILValue, 4> entryArgs;
entryArgs.reserve(origEntryBB->getArguments().size());
unsigned argNo = 0;
auto ai = origEntryBB->args_begin(), ae = origEntryBB->args_end();
for (; ai != ae; ++argNo, ++ai) {
if (!promotableIndices.count(argNo)) {
// Simply create a new argument which copies the original argument
auto *mappedValue = clonedEntryBB->createFunctionArgument(
(*ai)->getType(), (*ai)->getDecl());
mappedValue->copyFlags(cast<SILFunctionArgument>(*ai));
entryArgs.push_back(mappedValue);
continue;
}
// Handle the case of a promoted capture argument.
auto boxTy = (*ai)->getType().castTo<SILBoxType>();
assert(boxTy->getLayout()->getFields().size() == 1 &&
"promoting compound box not implemented");
auto boxedTy = getSILBoxFieldType(TypeExpansionContext(*cloned), boxTy,
cloned->getModule().Types, 0)
.getObjectType();
auto *newArg =
clonedEntryBB->createFunctionArgument(boxedTy, (*ai)->getDecl());
newArg->copyFlags(cast<SILFunctionArgument>(*ai));
SILValue mappedValue = newArg;
// If SIL ownership is enabled, we need to perform a borrow here if we have
// a non-trivial value. We know that our value is not written to and it does
// not escape. The use of a borrow enforces this.
if (mappedValue->getOwnershipKind() != OwnershipKind::None) {
SILLocation loc(const_cast<ValueDecl *>((*ai)->getDecl()));
mappedValue = getBuilder().emitBeginBorrowOperation(loc, mappedValue);
}
entryArgs.push_back(mappedValue);
boxArgumentMap.insert(std::make_pair(*ai, mappedValue));
// Track the projections of the box.
for (auto *use : (*ai)->getUses()) {
if (auto *pbi = dyn_cast<ProjectBoxInst>(use->getUser())) {
projectBoxArgumentMap.insert(std::make_pair(pbi, mappedValue));
}
}
}
// Visit original BBs in depth-first preorder, starting with the
// entry block, cloning all instructions and terminators.
cloneFunctionBody(origF, clonedEntryBB, entryArgs);
}
SILFunction *ClosureCloner::constructClonedFunction(
SILOptFunctionBuilder &funcBuilder, PartialApplyInst *pai,
FunctionRefInst *fri, IndicesSet &promotableIndices,
ResilienceExpansion resilienceExpansion) {
SILFunction *f = pai->getFunction();
// Create the Cloned Name for the function.
SILFunction *origF = fri->getReferencedFunction();
SerializedKind_t serializedKind = f->getSerializedKind();
auto clonedName = getSpecializedName(origF, serializedKind, promotableIndices);
// If we already have such a cloned function in the module then just use it.
if (auto *prevF = f->getModule().lookUpFunction(clonedName)) {
assert(prevF->getSerializedKind() == serializedKind);
return prevF;
}
// Otherwise, create a new clone.
ClosureCloner cloner(funcBuilder, origF, serializedKind, clonedName,
promotableIndices, resilienceExpansion);
cloner.populateCloned();
return cloner.getCloned();
}
/// If this operand originates from a mapped ProjectBox, return the mapped
/// value. Otherwise return an invalid value.
SILValue ClosureCloner::getProjectBoxMappedVal(SILValue operandValue) {
if (auto *bai = dyn_cast<BeginAccessInst>(operandValue))
operandValue = bai->getSource();
if (auto *pbi = dyn_cast<ProjectBoxInst>(operandValue)) {
auto iter = projectBoxArgumentMap.find(pbi);
if (iter != projectBoxArgumentMap.end())
return iter->second;
}
return SILValue();
}
/// Handle a debug_value instruction during cloning of a closure;
/// if its operand is the promoted address argument then lower it to
/// another debug_value, otherwise it is handled normally.
void ClosureCloner::visitDebugValueInst(DebugValueInst *inst) {
if (inst->hasAddrVal())
if (SILValue value = getProjectBoxMappedVal(inst->getOperand())) {
getBuilder().setCurrentDebugScope(getOpScope(inst->getDebugScope()));
auto varInfo = *inst->getVarInfo();
if (varInfo.Scope)
varInfo.Scope = getOpScope(inst->getDebugScope());
getBuilder().createDebugValue(inst->getLoc(), value, varInfo);
return;
}
SILCloner<ClosureCloner>::visitDebugValueInst(inst);
}
/// Handle a destroy_value instruction during cloning of a closure; if it is a
/// destroy_value of a promoted box argument, then it is replaced with a
/// destroy_value of the new object type argument, otherwise it is handled
/// normally.
void ClosureCloner::visitDestroyValueInst(DestroyValueInst *inst) {
SILValue operand = inst->getOperand();
if (auto *arg = dyn_cast<SILArgument>(operand)) {
auto iter = boxArgumentMap.find(arg);
if (iter != boxArgumentMap.end()) {
// destroy_value of the box arguments get replaced with an end_borrow,
// destroy_value of the new object type argument.
SILFunction &f = getBuilder().getFunction();
auto &typeLowering = f.getTypeLowering(iter->second->getType());
SILBuilderWithPostProcess<ClosureCloner, 1> b(this, inst);
SILValue value = iter->second;
// We must have emitted a begin_borrow for any non-trivial value. Insert
// an end_borrow if so.
if (value->getOwnershipKind() != OwnershipKind::None) {
auto *bbi = cast<BeginBorrowInst>(value);
value = bbi->getOperand();
b.emitEndBorrowOperation(inst->getLoc(), bbi);
}
typeLowering.emitDestroyValue(b, inst->getLoc(), value);
return;
}
}
SILCloner<ClosureCloner>::visitDestroyValueInst(inst);
}
/// Handle an end_borrow instruction during cloning of a closure; if it is a
/// end_borrow from a load_borrow of a promoted box argument, then it is
/// deleted, otherwise it is handled normally.
void ClosureCloner::visitEndBorrowInst(EndBorrowInst *inst) {
SILValue operand = inst->getOperand();
if (auto *lbi = dyn_cast<LoadBorrowInst>(operand)) {
SILValue op = lbi->getOperand();
// When we check if we can do this, we only need to look through a single
// struct_element_addr since when checking if this is safe, we only look
// through a single struct_element_addr.
if (auto *sea = dyn_cast<StructElementAddrInst>(op))
op = sea->getOperand();
// If after optionally looking through a gep, we have our project_box, just
// eliminate the end_borrow.
if (getProjectBoxMappedVal(op))
return;
}
SILCloner<ClosureCloner>::visitEndBorrowInst(inst);
}
/// Handle a struct_element_addr instruction during cloning of a closure.
///
/// If its operand is the promoted address argument then ignore it, otherwise it
/// is handled normally.
void ClosureCloner::visitStructElementAddrInst(StructElementAddrInst *seai) {
if (getProjectBoxMappedVal(seai->getOperand()))
return;
SILCloner<ClosureCloner>::visitStructElementAddrInst(seai);
}
/// project_box of captured boxes can be eliminated.
void ClosureCloner::visitProjectBoxInst(ProjectBoxInst *pbi) {
if (auto *arg = dyn_cast<SILArgument>(pbi->getOperand()))
if (boxArgumentMap.count(arg))
return;
SILCloner<ClosureCloner>::visitProjectBoxInst(pbi);
}
/// If its operand is the promoted address argument then ignore it, otherwise it
/// is handled normally.
void ClosureCloner::visitBeginAccessInst(BeginAccessInst *bai) {
if (getProjectBoxMappedVal(bai->getSource()))
return;
SILCloner<ClosureCloner>::visitBeginAccessInst(bai);
}
/// If its operand is the promoted address argument then ignore it, otherwise it
/// is handled normally.
void ClosureCloner::visitEndAccessInst(EndAccessInst *eai) {
if (getProjectBoxMappedVal(eai->getBeginAccess()))
return;
SILCloner<ClosureCloner>::visitEndAccessInst(eai);
}
/// Handle a load_borrow instruction during cloning of a closure.
///
/// The two relevant cases are a direct load from a promoted address argument or
/// a load of a struct_element_addr of a promoted address argument.
void ClosureCloner::visitLoadBorrowInst(LoadBorrowInst *lbi) {
getBuilder().setCurrentDebugScope(getOpScope(lbi->getDebugScope()));
assert(lbi->getFunction()->hasOwnership() &&
"We should only see a load borrow in ownership qualified SIL");
if (SILValue value = getProjectBoxMappedVal(lbi->getOperand())) {
// Loads of the address argument get eliminated completely; the uses of
// the loads get mapped to uses of the new object type argument.
//
// We assume that the value is already guaranteed.
assert(
value->getOwnershipKind().isCompatibleWith(OwnershipKind::Guaranteed) &&
"Expected argument value to be guaranteed");
recordFoldedValue(lbi, value);
return;
}
auto *seai = dyn_cast<StructElementAddrInst>(lbi->getOperand());
if (!seai) {
SILCloner<ClosureCloner>::visitLoadBorrowInst(lbi);
return;
}
if (SILValue value = getProjectBoxMappedVal(seai->getOperand())) {
// Loads of a struct_element_addr of an argument get replaced with a
// struct_extract of the new passed in value. The value should be borrowed
// already, so we can just extract the value.
assert(
!getBuilder().getFunction().hasOwnership() ||
value->getOwnershipKind().isCompatibleWith(OwnershipKind::Guaranteed));
value = getBuilder().emitStructExtract(lbi->getLoc(), value,
seai->getField(), lbi->getType());
recordFoldedValue(lbi, value);
return;
}
SILCloner<ClosureCloner>::visitLoadBorrowInst(lbi);
return;
}
/// Handle a load instruction during cloning of a closure.
///
/// The two relevant cases are a direct load from a promoted address argument or
/// a load of a struct_element_addr of a promoted address argument.
void ClosureCloner::visitLoadInst(LoadInst *li) {
getBuilder().setCurrentDebugScope(getOpScope(li->getDebugScope()));
if (SILValue value = getProjectBoxMappedVal(li->getOperand())) {
// Loads of the address argument get eliminated completely; the uses of
// the loads get mapped to uses of the new object type argument.
//
// If we are compiling with SIL ownership, we need to take different
// behaviors depending on the type of load. Specifically, if we have a
// load [copy], then we need to add a copy_value here. If we have a take
// or trivial, we just propagate the value through.
if (li->getFunction()->hasOwnership() &&
li->getOwnershipQualifier() == LoadOwnershipQualifier::Copy) {
value = getBuilder().createCopyValue(li->getLoc(), value);
}
recordFoldedValue(li, value);
return;
}
auto *seai = dyn_cast<StructElementAddrInst>(li->getOperand());
if (!seai) {
SILCloner<ClosureCloner>::visitLoadInst(li);
return;
}
if (SILValue value = getProjectBoxMappedVal(seai->getOperand())) {
// Loads of a struct_element_addr of an argument get replaced with a
// struct_extract of the new passed in value. The value should be borrowed
// already, so we can just extract the value.
assert(
!getBuilder().getFunction().hasOwnership() ||
value->getOwnershipKind().isCompatibleWith(OwnershipKind::Guaranteed));
value = getBuilder().emitStructExtract(li->getLoc(), value,
seai->getField(), li->getType());
// If we were performing a load [copy], then we need to a perform a copy
// here since when cloning, we do not eliminate the destroy on the copied
// value.
if (li->getFunction()->hasOwnership() &&
li->getOwnershipQualifier() == LoadOwnershipQualifier::Copy) {
value = getBuilder().createCopyValue(li->getLoc(), value);
}
recordFoldedValue(li, value);
return;
}
SILCloner<ClosureCloner>::visitLoadInst(li);
}
//===----------------------------------------------------------------------===//
// EscapeMutationScanningState
//===----------------------------------------------------------------------===//
namespace {
struct EscapeMutationScanningState {
/// The list of mutations in the partial_apply caller that we found.
SmallVector<Operand *, 8> accumulatedMutations;
/// The list of escapes in the partial_apply caller/callee of the box that we
/// found.
SmallVector<Operand *, 8> accumulatedEscapes;
/// A multimap that maps partial applies to the set of operands in the partial
/// applies referenced function that the pass has identified as being the use
/// that caused the partial apply to capture our box.
///
/// We use a frozen multi-map since our algorithm first accumulates this info
/// and then wants to use it, perfect for the 2-stage frozen multi map.
SmallFrozenMultiMap<PartialApplyInst *, Operand *, 16>
accumulatedCaptureCausingUses;
/// A flag that we use to ensure that we only ever see 1 project_box on an
/// alloc_box.
bool sawProjectBoxInst;
/// The global partial_apply -> index map.
llvm::DenseMap<PartialApplyInst *, unsigned> &globalIndexMap;
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Partial Apply BoxArg Mutation/Escape/Capture Use Analysis
//===----------------------------------------------------------------------===//
static SILArgument *getBoxFromIndex(SILFunction *f, unsigned index) {
assert(f->isDefinition() && "Expected definition not external declaration!");
auto &entry = f->front();
return entry.getArgument(index);
}
static bool isNonMutatingLoad(SILInstruction *inst) {
if (isa<LoadBorrowInst>(inst))
return true;
auto *li = dyn_cast<LoadInst>(inst);
if (!li)
return false;
return li->getOwnershipQualifier() != LoadOwnershipQualifier::Take;
}
/// Given a partial_apply instruction and the argument index into its callee's
/// argument list of a box argument (which is followed by an argument for the
/// address of the box's contents), return true if this box has mutating
/// captures. Return false otherwise. All of the mutating captures that we find
/// are placed into \p accumulatedMutatingUses.
static bool
getPartialApplyArgMutationsAndEscapes(PartialApplyInst *pai,
SILArgument *boxArg,
EscapeMutationScanningState &state) {
SmallVector<ProjectBoxInst *, 2> projectBoxInsts;
// Conservatively do not allow any use of the box argument other than a
// strong_release or projection, since this is the pattern expected from
// SILGen.
SmallVector<Operand *, 32> incrementalEscapes;
SmallVector<Operand *, 32> incrementalCaptureCausingUses;
for (auto *use : boxArg->getUses()) {
if (isa<StrongReleaseInst>(use->getUser()) ||
isa<DestroyValueInst>(use->getUser()))
continue;
if (auto *pbi = dyn_cast<ProjectBoxInst>(use->getUser())) {
projectBoxInsts.push_back(pbi);
continue;
}
incrementalEscapes.push_back(use);
}
// Only allow loads of projections, either directly or via
// struct_element_addr instructions.
//
// TODO: This seems overly limited. Why not projections of tuples and other
// stuff? Also, why not recursive struct elements? This should be a helper
// function that mirrors isNonEscapingUse.
auto checkIfAddrUseMutating = [&](Operand *addrUse) -> bool {
unsigned initSize = incrementalEscapes.size();
auto *addrUser = addrUse->getUser();
if (auto *seai = dyn_cast<StructElementAddrInst>(addrUser)) {
for (auto *seaiUse : seai->getUses()) {
if (isNonMutatingLoad(seaiUse->getUser())) {
incrementalCaptureCausingUses.push_back(seaiUse);
} else {
incrementalEscapes.push_back(seaiUse);
}
}
return incrementalEscapes.size() != initSize;
}
if (isNonMutatingLoad(addrUser)) {
incrementalCaptureCausingUses.push_back(addrUse);
return false;
}
if (DebugValueInst::hasAddrVal(addrUser) ||
isa<MarkFunctionEscapeInst>(addrUser) || isa<EndAccessInst>(addrUser)) {
return false;
}
incrementalEscapes.push_back(addrUse);
return true;
};
for (auto *pbi : projectBoxInsts) {
for (auto *use : pbi->getUses()) {
if (auto *bai = dyn_cast<BeginAccessInst>(use->getUser())) {
for (auto *accessUseOper : bai->getUses()) {
checkIfAddrUseMutating(accessUseOper);
}
continue;
}
checkIfAddrUseMutating(use);
}
}
auto &accCaptureCausingUses = state.accumulatedCaptureCausingUses;
while (!incrementalCaptureCausingUses.empty())
accCaptureCausingUses.insert(pai,
incrementalCaptureCausingUses.pop_back_val());
if (incrementalEscapes.empty())
return false;
while (!incrementalEscapes.empty())
state.accumulatedEscapes.push_back(incrementalEscapes.pop_back_val());
return true;
}
bool isPartialApplyNonEscapingUser(Operand *currentOp, PartialApplyInst *pai,
EscapeMutationScanningState &state) {
LLVM_DEBUG(llvm::dbgs() << " Found partial: " << *pai);
unsigned opNo = currentOp->getOperandNumber();
assert(opNo != 0 && "Alloc box used as callee of partial apply?");
// If we've already seen this partial apply, then it means the same alloc box
// is being captured twice by the same closure, which is odd and unexpected:
// bail instead of trying to handle this case.
if (state.globalIndexMap.count(pai)) {
// TODO: Is it correct to treat this like an escape? We are just currently
// flagging all failures as warnings.
LLVM_DEBUG(llvm::dbgs() << " FAIL! Already seen.\n");
state.accumulatedEscapes.push_back(currentOp);
return false;
}
SILModule &mod = pai->getModule();
SILFunction *f = pai->getFunction();
auto closureType = pai->getType().castTo<SILFunctionType>();
SILFunctionConventions closureConv(closureType, mod);
// Calculate the index into the closure's argument list of the captured
// box pointer (the captured address is always the immediately following
// index so is not stored separately);
unsigned index = opNo - 1 + closureConv.getNumSILArguments();
auto *fn = pai->getReferencedFunctionOrNull();
// It is not safe to look at the content of dynamically replaceable functions
// since this pass looks at the content of Fn.
if (!fn || !fn->isDefinition() || fn->isDynamicallyReplaceable()) {
LLVM_DEBUG(llvm::dbgs() << " FAIL! Not a direct function definition "
"reference.\n");
state.accumulatedEscapes.push_back(currentOp);
return false;
}
SILArgument *boxArg = getBoxFromIndex(fn, index);
// For now, return false is the address argument is an address-only type,
// since we currently handle loadable types only.
// TODO: handle address-only types
// FIXME: Expansion
auto boxTy = boxArg->getType().castTo<SILBoxType>();
assert(boxTy->getLayout()->getFields().size() == 1 &&
"promoting compound box not implemented yet");
if (getSILBoxFieldType(TypeExpansionContext(*fn), boxTy, mod.Types, 0)
.isAddressOnly(*f)) {
LLVM_DEBUG(llvm::dbgs() << " FAIL! Box is an address only "
"argument!\n");
state.accumulatedEscapes.push_back(currentOp);
return false;
}
// Verify that this closure is known not to mutate the captured value; if
// it does, then conservatively refuse to promote any captures of this
// value.
if (getPartialApplyArgMutationsAndEscapes(pai, boxArg, state)) {
LLVM_DEBUG(llvm::dbgs() << " FAIL: Have a mutation or escape of a "
"partial apply arg?!\n");
return false;
}
// Record the index and continue.
LLVM_DEBUG(llvm::dbgs()
<< " Partial apply does not escape, may be optimizable!\n");
LLVM_DEBUG(llvm::dbgs() << " Index: " << index << "\n");
state.globalIndexMap.insert(std::make_pair(pai, index));
return true;
}
//===----------------------------------------------------------------------===//
// Project Box Escaping Use Analysis
//===----------------------------------------------------------------------===//