-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILMem2Reg.cpp
2305 lines (2011 loc) · 85.6 KB
/
SILMem2Reg.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
//===--- SILMem2Reg.cpp - Promotes AllocStacks to registers ---------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This pass promotes AllocStack instructions into virtual register
// references. It only handles load, store and deallocation
// instructions. The algorithm is based on:
//
// Sreedhar and Gao. A linear time algorithm for placing phi-nodes. POPL '95.
//
//===----------------------------------------------------------------------===//
#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h"
#define DEBUG_TYPE "sil-mem2reg"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/GraphNodeWorklist.h"
#include "swift/Basic/TaggedUnion.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/OSSALifetimeCompletion.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/StackList.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/CanonicalizeBorrowScope.h"
#include "swift/SILOptimizer/Utils/CanonicalizeOSSALifetime.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/OwnershipOptUtils.h"
#include "swift/SILOptimizer/Utils/ScopeOptUtils.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
#include <queue>
using namespace swift;
using namespace swift::siloptimizer;
STATISTIC(NumAllocStackFound, "Number of AllocStack found");
STATISTIC(NumAllocStackCaptured, "Number of AllocStack captured");
STATISTIC(NumInstRemoved, "Number of Instructions removed");
llvm::cl::opt<bool> Mem2RegDisableLifetimeCanonicalization(
"sil-mem2reg-disable-lifetime-canonicalization", llvm::cl::init(false),
llvm::cl::desc("Don't canonicalize any lifetimes during Mem2Reg."));
static bool lexicalLifetimeEnsured(AllocStackInst *asi);
static bool lexicalLifetimeEnsured(AllocStackInst *asi, SILInstruction *store);
static bool isGuaranteedLexicalValue(SILValue src);
namespace {
using DomTreeNode = llvm::DomTreeNodeBase<SILBasicBlock>;
using DomTreeLevelMap = llvm::DenseMap<DomTreeNode *, unsigned>;
/// A transient structure containing the values that are accessible in some
/// context: coming into a block, going out of the block, or within a block
/// (during promoteAllocationInBlock and removeSingleBlockAllocation).
///
/// At block boundaries, these are phi arguments or initializationPoints. As we
/// iterate over a block, a way to keep track of the current (running) value
/// within a block.
class LiveValues {
public:
struct Owned {
SILValue stored = SILValue();
SILValue move = SILValue();
/// Create an instance of the minimum values required to replace a usage of
/// an AllocStackInst. It consists of only one value.
///
/// Whether the one value occupies the stored or the move field depends on
/// whether the alloc_stack is lexical. If it is lexical, then usages of
/// the asi will be replaced with usages of the move field; otherwise,
/// those usages will be replaced with usages of the stored field. The
/// implementation constructs an instance to match those requirements.
static Owned toReplace(AllocStackInst *asi, SILValue replacement) {
if (lexicalLifetimeEnsured(asi))
return {SILValue(), replacement};
return {replacement, SILValue()};
}
/// The value with which usages of the provided AllocStackInst should be
/// replaced.
SILValue replacement(AllocStackInst *asi, SILInstruction *toReplace) {
if (!lexicalLifetimeEnsured(asi)) {
return stored;
}
// We should have created a move of the @owned stored value.
assert(move);
return move;
}
bool canEndLexicalLifetime() {
// If running value originates from a load which was not preceded by a
// store in the same basic block, then we don't have enough information
// to end a lexical lifetime. In that case, the lifetime end will be
// added later, when we have enough information, namely the live in
// values, to end it.
return move;
}
void endLexicalLifetimeBeforeInst(AllocStackInst *asi,
SILInstruction *beforeInstruction,
SILBuilderContext &ctx);
};
struct Guaranteed {
SILValue stored = SILValue();
SILValue borrow = SILValue();
/// Create an instance of the minimum values required to replace a usage of
/// an AllocStackInst. It consists of only one value.
///
/// Whether the one value occupies the stored or the borrow field depends
/// on whether the alloc_stack is lexical. If it is lexical, then usages
/// of \p asi will be replaced with usages of the borrow field; otherwise,
/// those usages will be replaced with usages of the stored field. The
/// implementation constructs an instance to match those requirements.
static Guaranteed toReplace(AllocStackInst *asi, SILValue replacement) {
if (lexicalLifetimeEnsured(asi))
return {SILValue(), replacement};
return {replacement, SILValue()};
}
/// The value with which usages of the provided AllocStackInst should be
/// replaced.
SILValue replacement(AllocStackInst *asi, SILInstruction *toReplace) {
if (!lexicalLifetimeEnsured(asi)) {
return stored;
}
// For guaranteed lexical AllocStackInsts--i.e. those that are
// store_borrow locations--we may have created a borrow if the stored
// value is a non-lexical guaranteed value.
assert(isGuaranteedLexicalValue(stored) || borrow);
return borrow ? borrow : stored;
}
bool canEndLexicalLifetime() {
// There are two different cases when we don't create a lexical lifetime
// end for a guaranteed running value:
//
// If the source of the store_borrow is already lexical, then the running
// value doesn't have a lexical lifetime of its own which could be ended.
//
// If running value originates from a load which was not preceded by a
// store_borrow in the same basic block, then we don't have enough
// information to end a lexical lifetime. In that case, the lifetime end
// will be added later, when we have enough information, namely the live
// in values, to end it.
return borrow;
}
void endLexicalLifetimeBeforeInst(AllocStackInst *asi,
SILInstruction *beforeInstruction,
SILBuilderContext &ctx);
};
struct None {
SILValue stored = SILValue();
static None toReplace(AllocStackInst *asi, SILValue replacement) {
return {replacement};
}
SILValue replacement(AllocStackInst *asi, SILInstruction *toReplace) {
return stored;
}
bool canEndLexicalLifetime() { return false; }
void endLexicalLifetimeBeforeInst(AllocStackInst *asi,
SILInstruction *beforeInstruction,
SILBuilderContext &ctx);
};
private:
using Storage = TaggedUnion<Owned, Guaranteed, None>;
Storage storage;
LiveValues(Storage storage) : storage(storage) {}
static LiveValues forGuaranteed(Guaranteed values) {
return {Storage(values)};
}
static LiveValues forOwned(Owned values) { return {Storage(values)}; }
static LiveValues forNone(None values) { return {Storage(values)}; }
public:
enum class Kind {
Owned,
Guaranteed,
None,
};
Kind getKind() {
if (storage.isa<Owned>()) {
return Kind::Owned;
} else if (storage.isa<Guaranteed>()) {
return Kind::Guaranteed;
}
assert(storage.isa<None>());
return Kind::None;
}
bool isOwned() { return getKind() == Kind::Owned; }
bool isGuaranteed() { return getKind() == Kind::Guaranteed; }
bool isNone() { return getKind() == Kind::None; }
static LiveValues forGuaranteed(SILValue stored, SILValue borrow) {
return LiveValues::forGuaranteed({stored, borrow});
}
static LiveValues forOwned(SILValue stored, SILValue move) {
return LiveValues::forOwned({stored, move});
}
static LiveValues forNone(SILValue stored) {
return LiveValues::forNone(None{stored});
}
static LiveValues toReplace(AllocStackInst *asi, SILValue replacement) {
if (replacement->getOwnershipKind() == OwnershipKind::Guaranteed) {
return LiveValues::forGuaranteed(Guaranteed::toReplace(asi, replacement));
} else if (replacement->getOwnershipKind() == OwnershipKind::None) {
return LiveValues::forNone(None::toReplace(asi, replacement));
}
return LiveValues::forOwned(Owned::toReplace(asi, replacement));
}
Owned getOwned() { return storage.get<Owned>(); }
Guaranteed getGuaranteed() { return storage.get<Guaranteed>(); }
None getNone() { return storage.get<None>(); }
SILValue replacement(AllocStackInst *asi, SILInstruction *toReplace) {
if (auto *owned = storage.dyn_cast<Owned>()) {
return owned->replacement(asi, toReplace);
} else if (auto *none = storage.dyn_cast<None>()) {
return none->replacement(asi, toReplace);
}
auto &guaranteed = storage.get<Guaranteed>();
return guaranteed.replacement(asi, toReplace);
}
SILValue getStored() {
if (auto *owned = storage.dyn_cast<Owned>()) {
return owned->stored;
} else if (auto *none = storage.dyn_cast<None>()) {
return none->stored;
}
auto &guaranteed = storage.get<Guaranteed>();
return guaranteed.stored;
}
bool canEndLexicalLifetime() {
if (auto *owned = storage.dyn_cast<Owned>()) {
return owned->canEndLexicalLifetime();
} else if (auto *none = storage.dyn_cast<None>()) {
return none->canEndLexicalLifetime();
}
auto &guaranteed = storage.get<Guaranteed>();
return guaranteed.canEndLexicalLifetime();
}
void endLexicalLifetimeBeforeInst(AllocStackInst *asi,
SILInstruction *beforeInstruction,
SILBuilderContext &ctx) {
if (auto *owned = storage.dyn_cast<Owned>()) {
return owned->endLexicalLifetimeBeforeInst(asi, beforeInstruction, ctx);
} else if (auto *none = storage.dyn_cast<None>()) {
return none->endLexicalLifetimeBeforeInst(asi, beforeInstruction, ctx);
}
auto &guaranteed = storage.get<Guaranteed>();
return guaranteed.endLexicalLifetimeBeforeInst(asi, beforeInstruction, ctx);
}
bool endLexicalLifetimeBeforeInstIfPossible(AllocStackInst *asi,
SILInstruction *beforeInstruction,
SILBuilderContext &ctx) {
if (!canEndLexicalLifetime())
return false;
endLexicalLifetimeBeforeInst(asi, beforeInstruction, ctx);
return true;
}
};
/// A transient structure used only by promoteAllocationInBlock and
/// removeSingleBlockAllocation.
///
/// A pair of a CFG-position-relative value T and a boolean indicating whether
/// the alloc_stack's storage is valid at the position where that value exists.
template <typename T>
struct StorageStateTracking {
/// The value which exists at some CFG position.
T value;
/// Whether the stack storage is initialized at that position.
bool isStorageValid;
};
} // anonymous namespace
//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//
/// Make the specified instruction cease to be a user of its operands and add it
/// to the list of instructions to delete.
///
/// This both (1) removes the specified instruction from the list of users of
/// its operands, avoiding disrupting logic that examines those users and (2)
/// keeps the specified instruction in place, allowing it to be used for
/// insertion until instructionsToDelete is culled.
static void
prepareForDeletion(SILInstruction *inst,
SmallVectorImpl<SILInstruction *> &instructionsToDelete) {
for (auto &operand : inst->getAllOperands()) {
operand.set(SILUndef::get(operand.get()));
}
instructionsToDelete.push_back(inst);
}
static void
replaceDestroy(DestroyAddrInst *dai, SILValue newValue, SILBuilderContext &ctx,
InstructionDeleter &deleter,
SmallVectorImpl<SILInstruction *> &instructionsToDelete) {
SILFunction *f = dai->getFunction();
auto ty = dai->getOperand()->getType();
assert(ty.isLoadable(*f) && "Unexpected promotion of address-only type!");
assert(newValue ||
(ty.is<TupleType>() && ty.getAs<TupleType>()->getNumElements() == 0));
SILBuilderWithScope builder(dai, ctx);
auto &typeLowering = f->getTypeLowering(ty);
bool expand = shouldExpand(dai->getModule(),
dai->getOperand()->getType().getObjectType());
using TypeExpansionKind = Lowering::TypeLowering::TypeExpansionKind;
auto expansionKind = expand ? TypeExpansionKind::MostDerivedDescendents
: TypeExpansionKind::None;
typeLowering.emitLoweredDestroyValue(builder, dai->getLoc(), newValue,
expansionKind);
prepareForDeletion(dai, instructionsToDelete);
}
/// Returns true if \p I is a load which loads from \p ASI.
static bool isLoadFromStack(SILInstruction *i, AllocStackInst *asi) {
if (!isa<LoadInst>(i) && !isa<LoadBorrowInst>(i))
return false;
// Skip struct and tuple address projections.
ValueBase *op = i->getOperand(0);
while (op != asi) {
if (!isa<UncheckedAddrCastInst>(op) && !isa<StructElementAddrInst>(op) &&
!isa<TupleElementAddrInst>(op) && !isa<StoreBorrowInst>(op))
return false;
if (auto *sbi = dyn_cast<StoreBorrowInst>(op)) {
op = sbi->getDest();
continue;
}
op = cast<SingleValueInstruction>(op)->getOperand(0);
}
return true;
}
/// Collects all load instructions which (transitively) use \p i as address.
static void collectLoads(SILInstruction *i,
SmallVectorImpl<SILInstruction *> &foundLoads) {
if (isa<LoadInst>(i) || isa<LoadBorrowInst>(i)) {
foundLoads.push_back(i);
return;
}
if (!isa<UncheckedAddrCastInst>(i) && !isa<StructElementAddrInst>(i) &&
!isa<TupleElementAddrInst>(i))
return;
// Recursively search for other loads in the instruction's uses.
for (auto *use : cast<SingleValueInstruction>(i)->getUses()) {
collectLoads(use->getUser(), foundLoads);
}
}
/// Returns true if \p I is an address of a LoadInst, skipping struct and
/// tuple address projections. Sets \p singleBlock to null if the load (or
/// it's address is not in \p singleBlock.
/// This function looks for these patterns:
/// 1. (load %ASI)
/// 2. (load (struct_element_addr/tuple_element_addr/unchecked_addr_cast %ASI))
static bool isAddressForLoad(SILInstruction *load, SILBasicBlock *&singleBlock,
bool &involvesUntakableProjection) {
if (auto *li = dyn_cast<LoadInst>(load)) {
// SILMem2Reg is disabled when we find a load [take] of an untakable
// projection. See below for further discussion.
if (involvesUntakableProjection &&
li->getOwnershipQualifier() == LoadOwnershipQualifier::Take) {
return false;
}
return true;
}
if (isa<LoadBorrowInst>(load)) {
if (involvesUntakableProjection) {
return false;
}
return true;
}
if (!isa<UncheckedAddrCastInst>(load) && !isa<StructElementAddrInst>(load) &&
!isa<TupleElementAddrInst>(load))
return false;
// None of the projections are lowered to owned values:
//
// struct_element_addr and tuple_element_addr instructions are lowered to
// struct_extract and tuple_extract instructions respectively. These both
// have guaranteed ownership (since they forward ownership and can only be
// used on a guaranteed value).
//
// unchecked_addr_cast instructions are lowered to unchecked_bitwise_cast
// instructions. These have unowned ownership.
//
// So in no case can a load [take] be lowered into the new projected value
// (some sequence of struct_extract, tuple_extract, and
// unchecked_bitwise_cast instructions) taking over ownership of the original
// value. Without additional changes.
//
// For example, for a sequence of element_addr projections could be
// transformed into a sequence of destructure instructions, followed by a
// sequence of structure instructions where all the original values are
// kept in place but the taken value is "knocked out" and replaced with
// undef. The running value would then be set to the newly structed
// "knockout" value.
//
// Alternatively, a new copy of the running value could be created and a new
// set of destroys placed after its last uses.
involvesUntakableProjection = true;
// Recursively search for other (non-)loads in the instruction's uses.
auto *svi = cast<SingleValueInstruction>(load);
for (auto *use : svi->getUses()) {
SILInstruction *user = use->getUser();
if (user->getParent() != singleBlock)
singleBlock = nullptr;
if (!isAddressForLoad(user, singleBlock, involvesUntakableProjection))
return false;
}
return true;
}
/// Returns true if \p I is a dead struct_element_addr or tuple_element_addr.
static bool isDeadAddrProjection(SILInstruction *inst) {
if (!isa<UncheckedAddrCastInst>(inst) && !isa<StructElementAddrInst>(inst) &&
!isa<TupleElementAddrInst>(inst))
return false;
// Recursively search for uses which are dead themselves.
for (auto UI : cast<SingleValueInstruction>(inst)->getUses()) {
SILInstruction *II = UI->getUser();
if (!isDeadAddrProjection(II))
return false;
}
return true;
}
/// Returns true if this \p def is captured.
/// Sets \p inSingleBlock to true if all uses of \p def are in a single block.
static bool isCaptured(SILValue def, bool *inSingleBlock) {
SILBasicBlock *singleBlock = def->getParentBlock();
// For all users of the def
for (auto *use : def->getUses()) {
SILInstruction *user = use->getUser();
if (user->getParent() != singleBlock)
singleBlock = nullptr;
// Loads are okay.
bool involvesUntakableProjection = false;
if (isAddressForLoad(user, singleBlock, involvesUntakableProjection))
continue;
// We can store into an AllocStack (but not the pointer).
if (auto *si = dyn_cast<StoreInst>(user))
if (si->getDest() == def)
continue;
if (auto *sbi = dyn_cast<StoreBorrowInst>(user)) {
if (sbi->getDest() == def) {
if (isCaptured(sbi, inSingleBlock)) {
return true;
}
continue;
}
}
// Deallocation is also okay, as are DebugValue w/ address value. We will
// promote the latter into normal DebugValue.
if (isa<DeallocStackInst>(user) || DebugValueInst::hasAddrVal(user))
continue;
if (isa<EndBorrowInst>(user))
continue;
// Destroys of loadable types can be rewritten as releases, so
// they are fine.
if (auto *dai = dyn_cast<DestroyAddrInst>(user))
if (dai->getOperand()->getType().isLoadable(*dai->getFunction()))
continue;
// Other instructions are assumed to capture the AllocStack.
LLVM_DEBUG(llvm::dbgs() << "*** AllocStack is captured by: " << *user);
return true;
}
// None of the users capture the AllocStack.
*inSingleBlock = (singleBlock != nullptr);
return false;
}
/// Returns true if the \p def is only stored into.
static bool isWriteOnlyAllocation(SILValue def) {
assert(isa<AllocStackInst>(def) || isa<StoreBorrowInst>(def));
// For all users of the def:
for (auto *use : def->getUses()) {
SILInstruction *user = use->getUser();
// It is okay to store into the AllocStack.
if (auto *si = dyn_cast<StoreInst>(user))
if (!isa<AllocStackInst>(si->getSrc()))
continue;
if (auto *sbi = dyn_cast<StoreBorrowInst>(user)) {
// Since all uses of the alloc_stack will be via store_borrow, check if
// there are any non-writes from the store_borrow location.
if (!isWriteOnlyAllocation(sbi)) {
return false;
}
continue;
}
// Deallocation is also okay.
if (isa<DeallocStackInst>(user))
continue;
if (isa<EndBorrowInst>(user))
continue;
// If we haven't already promoted the AllocStack, we may see
// DebugValue uses.
if (DebugValueInst::hasAddrVal(user))
continue;
if (isDeadAddrProjection(user))
continue;
// Can't do anything else with it.
LLVM_DEBUG(llvm::dbgs() << "*** AllocStack has non-write use: " << *user);
return false;
}
return true;
}
static void
replaceLoad(SILInstruction *inst, SILValue newValue, AllocStackInst *asi,
SILBuilderContext &ctx, InstructionDeleter &deleter,
SmallVectorImpl<SILInstruction *> &instructionsToDelete) {
assert(isa<LoadInst>(inst) || isa<LoadBorrowInst>(inst));
ProjectionPath projections(newValue->getType());
SILValue op = inst->getOperand(0);
SILBuilderWithScope builder(inst, ctx);
SILOptScope scope;
while (op != asi) {
assert(isa<UncheckedAddrCastInst>(op) || isa<StructElementAddrInst>(op) ||
isa<TupleElementAddrInst>(op) ||
isa<StoreBorrowInst>(op) &&
"found instruction that should have been skipped in "
"isLoadFromStack");
if (auto *sbi = dyn_cast<StoreBorrowInst>(op)) {
op = sbi->getDest();
continue;
}
auto *projInst = cast<SingleValueInstruction>(op);
projections.push_back(Projection(projInst));
op = projInst->getOperand(0);
}
for (const auto &proj : llvm::reverse(projections)) {
assert(proj.getKind() == ProjectionKind::BitwiseCast ||
proj.getKind() == ProjectionKind::Struct ||
proj.getKind() == ProjectionKind::Tuple);
// struct_extract and tuple_extract expect guaranteed operand ownership
// non-trivial RunningVal is owned. Insert borrow operation to convert them
// to guaranteed!
if (proj.getKind() == ProjectionKind::Struct ||
proj.getKind() == ProjectionKind::Tuple) {
if (auto opVal = scope.borrowValue(inst, newValue)) {
assert(*opVal != newValue &&
"Valid value should be different from input value");
newValue = *opVal;
}
}
newValue =
proj.createObjectProjection(builder, inst->getLoc(), newValue).get();
}
op = inst->getOperand(0);
if (auto *lbi = dyn_cast<LoadBorrowInst>(inst)) {
if (lexicalLifetimeEnsured(asi) &&
newValue->getOwnershipKind() == OwnershipKind::Guaranteed) {
SmallVector<SILInstruction *, 4> endBorrows;
for (auto *ebi : lbi->getUsersOfType<EndBorrowInst>()) {
endBorrows.push_back(ebi);
}
for (auto *ebi : endBorrows) {
prepareForDeletion(ebi, instructionsToDelete);
}
lbi->replaceAllUsesWith(newValue);
} else {
auto *borrow = SILBuilderWithScope(lbi, ctx).createBeginBorrow(
lbi->getLoc(), newValue, asi->isLexical());
lbi->replaceAllUsesWith(borrow);
}
} else {
auto *li = cast<LoadInst>(inst);
// Replace users of the loaded value with `newValue`
// If we have a load [copy], replace the users with copy_value of `newValue`
if (li->getOwnershipQualifier() == LoadOwnershipQualifier::Copy) {
li->replaceAllUsesWith(builder.createCopyValue(li->getLoc(), newValue));
} else {
li->replaceAllUsesWith(newValue);
}
}
// Pop the scope so that we emit cleanups.
std::move(scope).popAtEndOfScope(&*builder.getInsertionPoint());
// Delete the load
prepareForDeletion(inst, instructionsToDelete);
while (op != asi && op->use_empty()) {
assert(isa<UncheckedAddrCastInst>(op) || isa<StructElementAddrInst>(op) ||
isa<TupleElementAddrInst>(op) || isa<StoreBorrowInst>(op));
if (auto *sbi = dyn_cast<StoreBorrowInst>(op)) {
SILValue next = sbi->getDest();
deleter.forceDelete(sbi);
op = next;
continue;
}
auto *inst = cast<SingleValueInstruction>(op);
SILValue next = inst->getOperand(0);
deleter.forceDelete(inst);
op = next;
}
}
/// Whether lexical lifetimes should be added for the values stored into the
/// alloc_stack.
static bool lexicalLifetimeEnsured(AllocStackInst *asi) {
return asi->getFunction()->hasOwnership() &&
asi->getFunction()
->getModule()
.getASTContext()
.SILOpts.LexicalLifetimes == LexicalLifetimesOption::On &&
asi->isLexical() &&
!asi->getElementType().isTrivial(*asi->getFunction());
}
static bool lexicalLifetimeEnsured(AllocStackInst *asi, SILInstruction *store) {
if (!lexicalLifetimeEnsured(asi))
return false;
if (!store)
return true;
auto stored = store->getOperand(CopyLikeInstruction::Src);
return stored->getOwnershipKind() != OwnershipKind::None;
}
static bool isGuaranteedLexicalValue(SILValue src) {
return src->getOwnershipKind() == OwnershipKind::Guaranteed &&
src->isLexical();
}
static SILValue getLexicalValueForStore(SILInstruction *inst,
AllocStackInst *asi) {
assert(isa<StoreInst>(inst) || isa<StoreBorrowInst>(inst));
SILValue stored = inst->getOperand(CopyLikeInstruction::Src);
LLVM_DEBUG(llvm::dbgs() << "*** Found Store def " << stored);
if (!lexicalLifetimeEnsured(asi)) {
return SILValue();
}
if (stored->getOwnershipKind() == OwnershipKind::None) {
return SILValue();
}
if (isa<StoreBorrowInst>(inst)) {
if (isGuaranteedLexicalValue(stored)) {
return SILValue();
}
auto borrow = cast<BeginBorrowInst>(inst->getNextInstruction());
return borrow;
}
auto move = cast<MoveValueInst>(inst->getNextInstruction());
return move;
}
/// Begin a lexical borrow scope for the value stored into the provided
/// StoreInst after that instruction.
///
/// The beginning of the scope looks like
///
/// %lifetime = move_value [lexical] %original
///
/// Because the value was consumed by the original store instruction, it can
/// be rewritten to be consumed by a lexical move_value.
static StorageStateTracking<LiveValues>
beginOwnedLexicalLifetimeAfterStore(AllocStackInst *asi, StoreInst *inst) {
assert(lexicalLifetimeEnsured(asi));
SILValue stored = inst->getOperand(CopyLikeInstruction::Src);
assert(stored->getOwnershipKind() == OwnershipKind::Owned);
SILLocation loc = RegularLocation::getAutoGeneratedLocation(inst->getLoc());
MoveValueInst *mvi = nullptr;
SILBuilderWithScope::insertAfter(inst, [&](SILBuilder &builder) {
mvi = builder.createMoveValue(loc, stored, IsLexical);
});
StorageStateTracking<LiveValues> vals = {LiveValues::forOwned(stored, mvi),
/*isStorageValid=*/true};
return vals;
}
/// Begin a lexical borrow scope for the value stored via the provided
/// StoreBorrowInst after that instruction. Only do so if the stored value is
/// non-lexical.
static StorageStateTracking<LiveValues>
beginGuaranteedLexicalLifetimeAfterStore(AllocStackInst *asi,
StoreBorrowInst *inst) {
assert(lexicalLifetimeEnsured(asi));
SILValue stored = inst->getOperand(CopyLikeInstruction::Src);
assert(stored->getOwnershipKind() != OwnershipKind::None);
SILLocation loc = RegularLocation::getAutoGeneratedLocation(inst->getLoc());
if (isGuaranteedLexicalValue(stored)) {
return {LiveValues::forGuaranteed(stored, {}), /*isStorageValid*/ true};
}
auto *borrow = SILBuilderWithScope(inst->getNextInstruction())
.createBeginBorrow(loc, stored, IsLexical);
return {LiveValues::forGuaranteed(stored, borrow), /*isStorageValid*/ true};
}
/// End the lexical borrow scope for an @owned stored value described by the
/// provided LiveValues struct before the specified instruction.
///
/// The end of the scope looks like
///
/// destroy_value %lifetime
///
/// This instruction corresponds to the following instructions that begin a
/// lexical borrow scope:
///
/// %lifetime = move_value [lexical] %original
///
/// However, no intervention is required to explicitly end the lifetime because
/// it will already have been ended naturally by destroy_addrs (or equivalent)
/// of the alloc_stack.
void LiveValues::Owned::endLexicalLifetimeBeforeInst(
AllocStackInst *asi, SILInstruction *beforeInstruction,
SILBuilderContext &ctx) {
assert(lexicalLifetimeEnsured(asi));
assert(beforeInstruction);
}
/// End the lexical borrow scope for an @guaranteed stored value described by
/// the provided LiveValues struct before the specified instruction.
void LiveValues::Guaranteed::endLexicalLifetimeBeforeInst(
AllocStackInst *asi, SILInstruction *beforeInstruction,
SILBuilderContext &ctx) {
assert(lexicalLifetimeEnsured(asi));
assert(beforeInstruction);
assert(borrow);
SILBuilderWithScope builder(beforeInstruction);
builder.createEndBorrow(RegularLocation::getAutoGeneratedLocation(), borrow);
}
void LiveValues::None::endLexicalLifetimeBeforeInst(
AllocStackInst *asi, SILInstruction *beforeInstruction,
SILBuilderContext &ctx) {
llvm::report_fatal_error(
"can't have lexical lifetime for ownership none value");
}
//===----------------------------------------------------------------------===//
// Single Stack Allocation Promotion
//===----------------------------------------------------------------------===//
namespace {
/// Promotes a single AllocStackInst into registers..
class StackAllocationPromoter {
using BlockToInstMap = llvm::DenseMap<SILBasicBlock *, SILInstruction *>;
// Use a priority queue keyed on dominator tree level so that inserted nodes
// are handled from the bottom of the dom tree upwards.
using DomTreeNodePair = std::pair<DomTreeNode *, unsigned>;
using NodePriorityQueue =
std::priority_queue<DomTreeNodePair, SmallVector<DomTreeNodePair, 32>,
llvm::less_second>;
/// The AllocStackInst that we are handling.
AllocStackInst *asi;
/// The unique deallocation instruction. This value could be NULL if there are
/// multiple deallocations.
DeallocStackInst *dsi;
/// Dominator info.
DominanceInfo *domInfo;
/// The function's dead-end blocks.
DeadEndBlocksAnalysis *deadEndBlocksAnalysis;
/// Map from dominator tree node to tree level.
DomTreeLevelMap &domTreeLevels;
/// The SIL builder used when creating new instructions during register
/// promotion.
SILBuilderContext &ctx;
InstructionDeleter &deleter;
/// Instructions that could not be deleted immediately with forceDelete until
/// StackAllocationPromoter finishes its run.
///
/// There are two reasons why an instruction might not be deleted:
/// (1) new instructions are inserted before or after it
/// (2) it ensures that an instruction remains used, preventing it from being
/// deleted
SmallVectorImpl<SILInstruction *> &instructionsToDelete;
/// The last instruction in each block that initializes the storage that is
/// not succeeded by an instruction that deinitializes it.
///
/// The live-out values for every block can be derived from these.
///
/// This is either a StoreInst or a StoreBorrowInst.
///
/// If the alloc_stack is non-lexical, the only live-out value is the source
/// operand of the instruction.
///
/// If the alloc_stack is lexical but the stored value is already lexical, no
/// additional lexical lifetime is necessary and as an optimization can be
/// omitted. In that case, the only live-out value is the source operand of
/// the instruction. This optimization has been implemented for guaranteed
/// alloc_stacks.
///
/// If the alloc_stack is lexical and the stored value is not already lexical,
/// a lexical lifetime must be introduced that matches the duration in which
/// the value remains in the alloc_stack:
/// - For owned alloc_stacks, a move_value [lexical] of the stored value is
/// created. That move_value is the instruction after the store, and it is
/// the other running value.
/// - For guaranteed alloc_stacks, a begin_borrow [lexical] of the
/// store_borrow'd value is created. That begin_borrow is the instruction
/// after the store_borrow, and it is the other running value.
BlockToInstMap initializationPoints;
/// The first instruction in each block that deinitializes the storage that is
/// not preceded by an instruction that initializes it.
///
/// That includes:
/// store
/// destroy_addr
/// load [take]
/// Or
/// end_borrow
/// Ending lexical lifetimes before these instructions is one way that the
/// cross-block lexical lifetimes of initializationPoints can be ended in
/// StackAllocationPromoter::endLexicalLifetime.
BlockToInstMap deinitializationPoints;
public:
/// C'tor.
StackAllocationPromoter(
AllocStackInst *inputASI, DominanceInfo *inputDomInfo,
DeadEndBlocksAnalysis *inputDeadEndBlocksAnalysis,
DomTreeLevelMap &inputDomTreeLevels, SILBuilderContext &inputCtx,
InstructionDeleter &deleter,
SmallVectorImpl<SILInstruction *> &instructionsToDelete)
: asi(inputASI), dsi(nullptr), domInfo(inputDomInfo),
deadEndBlocksAnalysis(inputDeadEndBlocksAnalysis),
domTreeLevels(inputDomTreeLevels), ctx(inputCtx), deleter(deleter),
instructionsToDelete(instructionsToDelete) {
// Scan the users in search of a deallocation instruction.
for (auto *use : asi->getUses()) {
if (auto *foundDealloc = dyn_cast<DeallocStackInst>(use->getUser())) {
// Don't record multiple dealloc instructions.
if (dsi) {
dsi = nullptr;
break;
}
// Record the deallocation instruction.
dsi = foundDealloc;
}
}
}
/// Promote the Allocation.
void run(BasicBlockSetVector &livePhiBlocks);
private:
/// Promote AllocStacks into SSA.
void promoteAllocationToPhi(BasicBlockSetVector &livePhiBlocks);
/// Replace the dummy nodes with new block arguments.
void addBlockArguments(BasicBlockSetVector &phiBlocks);
/// Check if \p phi is a proactively added phi by SILMem2Reg
bool isProactivePhi(SILPhiArgument *phi,
const BasicBlockSetVector &phiBlocks);
/// Check if \p proactivePhi is live.
bool isNecessaryProactivePhi(SILPhiArgument *proactivePhi,
const BasicBlockSetVector &phiBlocks);
/// Given a \p proactivePhi that is live, backward propagate liveness to
/// other proactivePhis.
void propagateLiveness(SILPhiArgument *proactivePhi,
const BasicBlockSetVector &phiBlocks,
SmallPtrSetImpl<SILPhiArgument *> &livePhis);
/// End the lexical borrow scope that is introduced for lexical alloc_stack
/// instructions.
void endLexicalLifetime(BasicBlockSetVector &phiBlocks);
/// Fix all of the branch instructions and the uses to use
/// the AllocStack definitions (which include stores and Phis).
void fixBranchesAndUses(BasicBlockSetVector &blocks,
BasicBlockSetVector &liveBlocks);
/// update the branch instructions with the new Phi argument.
/// The blocks in \p PhiBlocks are blocks that define a value, \p Dest is
/// the branch destination, and \p Pred is the predecessors who's branch we
/// modify.
void fixPhiPredBlock(BasicBlockSetVector &phiBlocks, SILBasicBlock *dest,
SILBasicBlock *pred);
/// Get the values for this AllocStack variable that are flowing out of
/// StartBB.
std::optional<LiveValues> getLiveOutValues(BasicBlockSetVector &phiBlocks,
SILBasicBlock *startBlock);
/// Get the values for this AllocStack variable that are flowing out of
/// StartBB or undef if there are none.
LiveValues getEffectiveLiveOutValues(BasicBlockSetVector &phiBlocks,
SILBasicBlock *startBlock);
/// Get the values for this AllocStack variable that are flowing into block.
std::optional<LiveValues> getLiveInValues(BasicBlockSetVector &phiBlocks,
SILBasicBlock *block);
/// Get the values for this AllocStack variable that are flowing into block or
/// undef if there are none.