-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathSILCodeMotion.cpp
1665 lines (1380 loc) · 59.3 KB
/
SILCodeMotion.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
//===--- SILCodeMotion.cpp - Code Motion Optimizations --------------------===//
//
// 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-codemotion"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Basic/BlotMapVector.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h"
#include "swift/SILOptimizer/Analysis/RCIdentityAnalysis.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
STATISTIC(NumSunk, "Number of instructions sunk");
STATISTIC(NumRefCountOpsSimplified, "Number of enum ref count ops simplified");
STATISTIC(NumHoisted, "Number of instructions hoisted");
STATISTIC(NumSILArgumentReleaseHoisted, "Number of silargument release instructions hoisted");
llvm::cl::opt<bool> DisableSILRRCodeMotion("disable-sil-cm-rr-cm", llvm::cl::init(true));
using namespace swift;
namespace {
//===----------------------------------------------------------------------===//
// Utility
//===----------------------------------------------------------------------===//
static void createRefCountOpForPayload(SILBuilder &Builder, SILInstruction *I,
EnumElementDecl *EnumDecl,
SILValue DefOfEnum = SILValue()) {
assert(EnumDecl->getArgumentInterfaceType() &&
"We assume enumdecl has an argument type");
SILModule &Mod = I->getModule();
// The enum value is either passed as an extra argument if we are moving an
// retain that does not refer to the enum typed value - otherwise it is the
// argument to the refcount instruction.
SILValue EnumVal = DefOfEnum ? DefOfEnum : I->getOperand(0);
SILType ArgType = EnumVal->getType().getEnumElementType(EnumDecl, Mod);
auto *UEDI =
Builder.createUncheckedEnumData(I->getLoc(), EnumVal, EnumDecl, ArgType);
SILType UEDITy = UEDI->getType();
// If our payload is trivial, we do not need to insert any retain or release
// operations.
if (UEDITy.isTrivial(Mod))
return;
++NumRefCountOpsSimplified;
auto *RCI = cast<RefCountingInst>(I);
// If we have a retain value...
if (isa<RetainValueInst>(I)) {
// And our payload is refcounted, insert a strong_retain onto the
// payload.
if (UEDITy.isReferenceCounted(Mod)) {
Builder.createStrongRetain(I->getLoc(), UEDI, RCI->getAtomicity());
return;
}
// Otherwise, insert a retain_value on the payload.
Builder.createRetainValue(I->getLoc(), UEDI, RCI->getAtomicity());
return;
}
// At this point we know that we must have a release_value and a non-trivial
// payload.
assert(isa<ReleaseValueInst>(I) && "If I is not a retain value here, it must "
"be a release value since enums do not have reference semantics.");
// If our payload has reference semantics, insert the strong release.
if (UEDITy.isReferenceCounted(Mod)) {
Builder.createStrongRelease(I->getLoc(), UEDI, RCI->getAtomicity());
return;
}
// Otherwise if our payload is non-trivial but lacking reference semantics,
// insert the release_value.
Builder.createReleaseValue(I->getLoc(), UEDI, RCI->getAtomicity());
}
//===----------------------------------------------------------------------===//
// Generic Sinking Code
//===----------------------------------------------------------------------===//
/// \brief Hoist release on a SILArgument to its predecessors.
static bool hoistSILArgumentReleaseInst(SILBasicBlock *BB) {
// There is no block to hoist releases to.
if (BB->pred_empty())
return false;
// Only try to hoist the first instruction. RRCM should have hoisted the release
// to the beginning of the block if it can.
auto Head = &*BB->begin();
// Make sure it is a release instruction.
if (!isReleaseInstruction(&*Head))
return false;
// Make sure it is a release on a SILArgument of the current basic block..
SILArgument *SA = dyn_cast<SILArgument>(Head->getOperand(0));
if (!SA || SA->getParent() != BB)
return false;
// Make sure the release will not be blocked by the terminator instructions
// Make sure the terminator does not block, nor is a branch with multiple targets.
for (auto P : BB->getPredecessorBlocks()) {
if (!isa<BranchInst>(P->getTerminator()))
return false;
}
// Make sure we can get all the incoming values.
llvm::SmallVector<SILValue , 4> PredValues;
if (!SA->getIncomingValues(PredValues))
return false;
// Ok, we can get all the incoming values and create releases for them.
unsigned indices = 0;
for (auto P : BB->getPredecessorBlocks()) {
createDecrementBefore(PredValues[indices++], P->getTerminator());
}
// Erase the old instruction.
Head->eraseFromParent();
++NumSILArgumentReleaseHoisted;
return true;
}
static const int SinkSearchWindow = 6;
/// \brief Returns True if we can sink this instruction to another basic block.
static bool canSinkInstruction(SILInstruction *Inst) {
return Inst->use_empty() && !isa<TermInst>(Inst);
}
/// \brief Returns true if this instruction is a skip barrier, which means that
/// we can't sink other instructions past it.
static bool isSinkBarrier(SILInstruction *Inst) {
if (isa<TermInst>(Inst))
return false;
if (Inst->mayHaveSideEffects())
return true;
return false;
}
using ValueInBlock = std::pair<SILValue, SILBasicBlock *>;
using ValueToBBArgIdxMap = llvm::DenseMap<ValueInBlock, int>;
enum OperandRelation {
/// Uninitialized state.
NotDeterminedYet,
/// The original operand values are equal.
AlwaysEqual,
/// The operand values are equal after replacing with the successor block
/// arguments.
EqualAfterMove
};
/// \brief Find a root value for operand \p In. This function inspects a sil
/// value and strips trivial conversions such as values that are passed
/// as arguments to basic blocks with a single predecessor or type casts.
/// This is a shallow one-step search and not a deep recursive search.
///
/// For example, in the SIL code below, the root of %10 is %3, because it is
/// the only possible incoming value.
///
/// bb1:
/// %3 = unchecked_enum_data %0 : $Optional<X>, #Optional.Some!enumelt.1
/// checked_cast_br [exact] %3 : $X to $X, bb4, bb5 // id: %4
///
/// bb4(%10 : $X): // Preds: bb1
/// strong_release %10 : $X
/// br bb2
///
static SILValue findValueShallowRoot(const SILValue &In) {
// If this is a basic block argument with a single caller
// then we know exactly which value is passed to the argument.
if (SILArgument *Arg = dyn_cast<SILArgument>(In)) {
SILBasicBlock *Parent = Arg->getParent();
SILBasicBlock *Pred = Parent->getSinglePredecessorBlock();
if (!Pred) return In;
// If the terminator is a cast instruction then use the pre-cast value.
if (auto CCBI = dyn_cast<CheckedCastBranchInst>(Pred->getTerminator())) {
assert(CCBI->getSuccessBB() == Parent && "Inspecting the wrong block");
// In swift it is legal to cast non reference-counted references into
// object references. For example: func f(x : C.Type) -> Any {return x}
// Here we check that the uncasted reference is reference counted.
SILValue V = CCBI->getOperand();
if (V->getType().isReferenceCounted(Pred->getParent()->getModule())) {
return V;
}
}
// If the single predecessor terminator is a branch then the root is
// the argument to the terminator.
if (auto BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
assert(BI->getDestBB() == Parent && "Invalid terminator");
unsigned Idx = Arg->getIndex();
return BI->getArg(Idx);
}
if (auto CBI = dyn_cast<CondBranchInst>(Pred->getTerminator())) {
return CBI->getArgForDestBB(Parent, Arg);
}
}
return In;
}
/// \brief Search for an instruction that is identical to \p Iden by scanning
/// \p BB starting at the end of the block, stopping on sink barriers.
/// The \p opRelation must be consistent for all operand comparisons.
SILInstruction *findIdenticalInBlock(SILBasicBlock *BB, SILInstruction *Iden,
const ValueToBBArgIdxMap &valueToArgIdxMap,
OperandRelation &opRelation) {
int SkipBudget = SinkSearchWindow;
SILBasicBlock::iterator InstToSink = BB->getTerminator()->getIterator();
SILBasicBlock *IdenBlock = Iden->getParent();
// The compare function for instruction operands.
auto operandCompare = [&](const SILValue &Op1, const SILValue &Op2) -> bool {
if (opRelation != EqualAfterMove && Op1 == Op2) {
// The trivial case.
opRelation = AlwaysEqual;
return true;
}
// Check if both operand values are passed to the same block argument in the
// successor block. This means that the operands are equal after we move the
// instruction into the successor block.
if (opRelation != AlwaysEqual) {
auto Iter1 = valueToArgIdxMap.find({Op1, IdenBlock});
if (Iter1 != valueToArgIdxMap.end()) {
auto Iter2 = valueToArgIdxMap.find({Op2, BB});
if (Iter2 != valueToArgIdxMap.end() && Iter1->second == Iter2->second) {
opRelation = EqualAfterMove;
return true;
}
}
}
return false;
};
while (SkipBudget) {
// If we found a sinkable instruction that is identical to our goal
// then return it.
if (canSinkInstruction(&*InstToSink) &&
Iden->isIdenticalTo(&*InstToSink, operandCompare)) {
DEBUG(llvm::dbgs() << "Found an identical instruction.");
return &*InstToSink;
}
// If this instruction is a skip-barrier end the scan.
if (isSinkBarrier(&*InstToSink))
return nullptr;
// If this is the first instruction in the block then we are done.
if (InstToSink == BB->begin())
return nullptr;
SkipBudget--;
InstToSink = std::prev(InstToSink);
DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink);
}
return nullptr;
}
/// The 2 instructions given are not identical, but are passed as arguments
/// to a common successor. It may be cheaper to pass one of their operands
/// to the successor instead of the whole instruction.
/// Return None if no such operand could be found, otherwise return the index
/// of a suitable operand.
static llvm::Optional<unsigned>
cheaperToPassOperandsAsArguments(SILInstruction *First,
SILInstruction *Second) {
// This will further enable to sink strong_retain_unowned instructions,
// which provides more opportunities for the unowned-optimization in
// LLVMARCOpts.
UnownedToRefInst *UTORI1 = dyn_cast<UnownedToRefInst>(First);
UnownedToRefInst *UTORI2 = dyn_cast<UnownedToRefInst>(Second);
if (UTORI1 && UTORI2) {
return 0;
}
// TODO: Add more cases than Struct
StructInst *FirstStruct = dyn_cast<StructInst>(First);
StructInst *SecondStruct = dyn_cast<StructInst>(Second);
if (!FirstStruct || !SecondStruct)
return None;
assert(First->getNumOperands() == Second->getNumOperands() &&
First->getType() == Second->getType() &&
"Types should be identical");
llvm::Optional<unsigned> DifferentOperandIndex;
// Check operands.
for (unsigned i = 0, e = First->getNumOperands(); i != e; ++i) {
if (First->getOperand(i) != Second->getOperand(i)) {
// Only track one different operand for now
if (DifferentOperandIndex)
return None;
DifferentOperandIndex = i;
}
}
if (!DifferentOperandIndex)
return None;
// Found a different operand, now check to see if its type is something
// cheap enough to sink.
// TODO: Sink more than just integers.
const auto &ArgTy = First->getOperand(*DifferentOperandIndex)->getType();
if (!ArgTy.is<BuiltinIntegerType>())
return None;
return *DifferentOperandIndex;
}
/// Return the value that's passed from block \p From to block \p To
/// (if there is a branch between From and To) as the Nth argument.
SILValue getArgForBlock(SILBasicBlock *From, SILBasicBlock *To,
unsigned ArgNum) {
TermInst *Term = From->getTerminator();
if (auto *CondBr = dyn_cast<CondBranchInst>(Term)) {
if (CondBr->getFalseBB() == To)
return CondBr->getFalseArgs()[ArgNum];
if (CondBr->getTrueBB() == To)
return CondBr->getTrueArgs()[ArgNum];
}
if (auto *Br = dyn_cast<BranchInst>(Term))
return Br->getArg(ArgNum);
return SILValue();
}
// Try to sink values from the Nth argument \p ArgNum.
static bool sinkLiteralArguments(SILBasicBlock *BB, unsigned ArgNum) {
assert(ArgNum < BB->getNumArguments() && "Invalid argument");
// Check if the argument passed to the first predecessor is a literal inst.
SILBasicBlock *FirstPred = *BB->pred_begin();
SILValue FirstArg = getArgForBlock(FirstPred, BB, ArgNum);
LiteralInst *FirstLiteral = dyn_cast_or_null<LiteralInst>(FirstArg);
if (!FirstLiteral)
return false;
// Check if the Nth argument in all predecessors is identical.
for (auto P : BB->getPredecessorBlocks()) {
if (P == FirstPred)
continue;
// Check that the incoming value is identical to the first literal.
SILValue PredArg = getArgForBlock(P, BB, ArgNum);
LiteralInst *PredLiteral = dyn_cast_or_null<LiteralInst>(PredArg);
if (!PredLiteral || !PredLiteral->isIdenticalTo(FirstLiteral))
return false;
}
// Replace the use of the argument with the cloned literal.
auto Cloned = FirstLiteral->clone(&*BB->begin());
BB->getArgument(ArgNum)->replaceAllUsesWith(Cloned);
return true;
}
// Try to sink values from the Nth argument \p ArgNum.
static bool sinkArgument(SILBasicBlock *BB, unsigned ArgNum) {
assert(ArgNum < BB->getNumArguments() && "Invalid argument");
// Find the first predecessor, the first terminator and the Nth argument.
SILBasicBlock *FirstPred = *BB->pred_begin();
TermInst *FirstTerm = FirstPred->getTerminator();
auto FirstPredArg = FirstTerm->getOperand(ArgNum);
SILInstruction *FSI = dyn_cast<SILInstruction>(FirstPredArg);
// The list of identical instructions.
SmallVector<SILValue, 8> Clones;
Clones.push_back(FirstPredArg);
// We only move instructions with a single use.
if (!FSI || !hasOneNonDebugUse(FSI))
return false;
// Don't move instructions that are sensitive to their location.
//
// If this instruction can read memory, we try to be conservatively not to
// move it, as there may be instructions that can clobber the read memory
// from current place to the place where it is moved to.
if (FSI->mayReadFromMemory() || (FSI->mayHaveSideEffects() &&
!isa<AllocationInst>(FSI)))
return false;
// If the instructions are different, but only in terms of a cheap operand
// then we can still sink it, and create new arguments for this operand.
llvm::Optional<unsigned> DifferentOperandIndex;
// Check if the Nth argument in all predecessors is identical.
for (auto P : BB->getPredecessorBlocks()) {
if (P == FirstPred)
continue;
// Only handle branch or conditional branch instructions.
TermInst *TI = P->getTerminator();
if (!isa<BranchInst>(TI) && !isa<CondBranchInst>(TI))
return false;
// Find the Nth argument passed to BB.
SILValue Arg = TI->getOperand(ArgNum);
SILInstruction *SI = dyn_cast<SILInstruction>(Arg);
if (!SI || !hasOneNonDebugUse(SI))
return false;
if (SI->isIdenticalTo(FSI)) {
Clones.push_back(SI);
continue;
}
// If the instructions are close enough, then we should sink them anyway.
// For example, we should sink 'struct S(%0)' if %0 is small, eg, an integer
auto MaybeDifferentOp = cheaperToPassOperandsAsArguments(FSI, SI);
// Couldn't find a suitable operand, so bail.
if (!MaybeDifferentOp)
return false;
unsigned DifferentOp = *MaybeDifferentOp;
// Make sure we found the same operand as prior iterations.
if (DifferentOperandIndex && DifferentOp != *DifferentOperandIndex)
return false;
DifferentOperandIndex = DifferentOp;
Clones.push_back(SI);
}
if (!FSI)
return false;
auto *Undef = SILUndef::get(FirstPredArg->getType(), BB->getModule());
// Delete the debug info of the instruction that we are about to sink.
deleteAllDebugUses(FSI);
if (DifferentOperandIndex) {
// Sink one of the instructions to BB
FSI->moveBefore(&*BB->begin());
// The instruction we are lowering has an argument which is different
// for each predecessor. We need to sink the instruction, then add
// arguments for each predecessor.
BB->getArgument(ArgNum)->replaceAllUsesWith(FSI);
const auto &ArgType = FSI->getOperand(*DifferentOperandIndex)->getType();
BB->replacePHIArgument(ArgNum, ArgType, ValueOwnershipKind::Owned);
// Update all branch instructions in the predecessors to pass the new
// argument to this BB.
auto CloneIt = Clones.begin();
for (auto P : BB->getPredecessorBlocks()) {
// Only handle branch or conditional branch instructions.
TermInst *TI = P->getTerminator();
assert((isa<BranchInst>(TI) || isa<CondBranchInst>(TI)) &&
"Branch instruction required");
SILInstruction *CloneInst = dyn_cast<SILInstruction>(*CloneIt);
TI->setOperand(ArgNum, CloneInst->getOperand(*DifferentOperandIndex));
// Now delete the clone as we only needed it operand.
if (CloneInst != FSI)
recursivelyDeleteTriviallyDeadInstructions(CloneInst);
++CloneIt;
}
assert(CloneIt == Clones.end() && "Clone/pred mismatch");
// The sunk instruction should now read from the argument of the BB it
// was moved to.
FSI->setOperand(*DifferentOperandIndex, BB->getArgument(ArgNum));
return true;
}
// Sink one of the copies of the instruction.
FirstPredArg->replaceAllUsesWith(Undef);
FSI->moveBefore(&*BB->begin());
BB->getArgument(ArgNum)->replaceAllUsesWith(FirstPredArg);
// The argument is no longer in use. Replace all incoming inputs with undef
// and try to delete the instruction.
for (auto S : Clones)
if (S != FSI) {
deleteAllDebugUses(S);
S->replaceAllUsesWith(Undef);
auto DeadArgInst = cast<SILInstruction>(S);
recursivelyDeleteTriviallyDeadInstructions(DeadArgInst);
}
return true;
}
/// Try to sink literals that are passed to arguments that are coming from
/// multiple predecessors.
/// Notice that unlike other sinking methods in this file we do allow sinking
/// of literals from blocks with multiple successors.
static bool sinkLiteralsFromPredecessors(SILBasicBlock *BB) {
if (BB->pred_empty() || BB->getSinglePredecessorBlock())
return false;
// Try to sink values from each of the arguments to the basic block.
bool Changed = false;
for (int i = 0, e = BB->getNumArguments(); i < e; ++i)
Changed |= sinkLiteralArguments(BB, i);
return Changed;
}
/// Try to sink identical arguments coming from multiple predecessors.
static bool sinkArgumentsFromPredecessors(SILBasicBlock *BB) {
if (BB->pred_empty() || BB->getSinglePredecessorBlock())
return false;
// This block must be the only successor of all the predecessors.
for (auto P : BB->getPredecessorBlocks())
if (P->getSingleSuccessorBlock() != BB)
return false;
// Try to sink values from each of the arguments to the basic block.
bool Changed = false;
for (int i = 0, e = BB->getNumArguments(); i < e; ++i)
Changed |= sinkArgument(BB, i);
return Changed;
}
/// \brief canonicalize retain/release instructions and make them amenable to
/// sinking by selecting canonical pointers. We reduce the number of possible
/// inputs by replacing values that are unlikely to be a canonical values.
/// Reducing the search space increases the chances of matching ref count
/// instructions to one another and the chance of sinking them. We replace
/// values that come from basic block arguments with the caller values and
/// strip casts.
static bool canonicalizeRefCountInstrs(SILBasicBlock *BB) {
bool Changed = false;
for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
if (!isa<StrongReleaseInst>(I) && !isa<StrongRetainInst>(I))
continue;
SILValue Ref = I->getOperand(0);
SILValue Root = findValueShallowRoot(Ref);
if (Ref != Root) {
I->setOperand(0, Root);
Changed = true;
}
}
return Changed;
}
static bool sinkCodeFromPredecessors(SILBasicBlock *BB) {
bool Changed = false;
if (BB->pred_empty())
return Changed;
// This block must be the only successor of all the predecessors.
for (auto P : BB->getPredecessorBlocks())
if (P->getSingleSuccessorBlock() != BB)
return Changed;
SILBasicBlock *FirstPred = *BB->pred_begin();
// The first Pred must have at least one non-terminator.
if (FirstPred->getTerminator() == &*FirstPred->begin())
return Changed;
DEBUG(llvm::dbgs() << " Sinking values from predecessors.\n");
// Map values in predecessor blocks to argument indices of the successor
// block. For example:
//
// bb1:
// br bb3(%a, %b) // %a -> 0, %b -> 1
// bb2:
// br bb3(%c, %d) // %c -> 0, %d -> 1
// bb3(%x, %y):
// ...
ValueToBBArgIdxMap valueToArgIdxMap;
for (auto P : BB->getPredecessorBlocks()) {
if (auto *BI = dyn_cast<BranchInst>(P->getTerminator())) {
auto Args = BI->getArgs();
for (size_t idx = 0, size = Args.size(); idx < size; idx++) {
valueToArgIdxMap[{Args[idx], P}] = idx;
}
}
}
unsigned SkipBudget = SinkSearchWindow;
// Start scanning backwards from the terminator.
auto InstToSink = FirstPred->getTerminator()->getIterator();
while (SkipBudget) {
DEBUG(llvm::dbgs() << "Processing: " << *InstToSink);
// Save the duplicated instructions in case we need to remove them.
SmallVector<SILInstruction *, 4> Dups;
if (canSinkInstruction(&*InstToSink)) {
OperandRelation opRelation = NotDeterminedYet;
// For all preds:
for (auto P : BB->getPredecessorBlocks()) {
if (P == FirstPred)
continue;
// Search the duplicated instruction in the predecessor.
if (SILInstruction *DupInst = findIdenticalInBlock(
P, &*InstToSink, valueToArgIdxMap, opRelation)) {
Dups.push_back(DupInst);
} else {
DEBUG(llvm::dbgs() << "Instruction mismatch.\n");
Dups.clear();
break;
}
}
// If we found duplicated instructions, sink one of the copies and delete
// the rest.
if (Dups.size()) {
DEBUG(llvm::dbgs() << "Moving: " << *InstToSink);
InstToSink->moveBefore(&*BB->begin());
if (opRelation == EqualAfterMove) {
// Replace operand values (which are passed to the successor block)
// with corresponding block arguments.
for (size_t idx = 0, numOps = InstToSink->getNumOperands();
idx < numOps; idx++) {
ValueInBlock OpInFirstPred(InstToSink->getOperand(idx), FirstPred);
assert(valueToArgIdxMap.count(OpInFirstPred) != 0);
int argIdx = valueToArgIdxMap[OpInFirstPred];
InstToSink->setOperand(idx, BB->getArgument(argIdx));
}
}
Changed = true;
for (auto I : Dups) {
I->replaceAllUsesWith(&*InstToSink);
I->eraseFromParent();
NumSunk++;
}
// Restart the scan.
InstToSink = FirstPred->getTerminator()->getIterator();
DEBUG(llvm::dbgs() << "Restarting scan. Next inst: " << *InstToSink);
continue;
}
}
// If this instruction was a barrier then we can't sink anything else.
if (isSinkBarrier(&*InstToSink)) {
DEBUG(llvm::dbgs() << "Aborting on barrier: " << *InstToSink);
return Changed;
}
// This is the first instruction, we are done.
if (InstToSink == FirstPred->begin()) {
DEBUG(llvm::dbgs() << "Reached the first instruction.");
return Changed;
}
SkipBudget--;
InstToSink = std::prev(InstToSink);
DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink);
}
return Changed;
}
/// Sink retain_value, release_value before switch_enum to be retain_value,
/// release_value on the payload of the switch_enum in the destination BBs. We
/// only do this if the destination BBs have only the switch enum as its
/// predecessor.
static bool tryToSinkRefCountAcrossSwitch(SwitchEnumInst *Switch,
SILBasicBlock::iterator RV,
AliasAnalysis *AA,
RCIdentityFunctionInfo *RCIA) {
// If this instruction is not a retain_value, there is nothing left for us to
// do... bail...
if (!isa<RetainValueInst>(RV))
return false;
SILValue Ptr = RV->getOperand(0);
// Next go over all instructions after I in the basic block. If none of them
// can decrement our ptr value, we can move the retain over the ref count
// inst. If any of them do potentially decrement the ref count of Ptr, we can
// not move it.
auto SwitchIter = Switch->getIterator();
if (auto B = valueHasARCDecrementOrCheckInInstructionRange(Ptr, RV,
SwitchIter,
AA)) {
RV->moveBefore(&**B);
return true;
}
// If the retain value's argument is not the switch's argument, we can't do
// anything with our simplistic analysis... bail...
if (RCIA->getRCIdentityRoot(Ptr) !=
RCIA->getRCIdentityRoot(Switch->getOperand()))
return false;
// If S has a default case bail since the default case could represent
// multiple cases.
//
// TODO: I am currently just disabling this behavior so we can get this out
// for Seed 5. After Seed 5, we should be able to recognize if a switch_enum
// handles all cases except for 1 and has a default case. We might be able to
// stick code into SILBuilder that has this behavior.
if (Switch->hasDefault())
return false;
// Ok, we have a ref count instruction, sink it!
SILBuilderWithScope Builder(Switch, &*RV);
for (unsigned i = 0, e = Switch->getNumCases(); i != e; ++i) {
auto Case = Switch->getCase(i);
EnumElementDecl *Enum = Case.first;
SILBasicBlock *Succ = Case.second;
Builder.setInsertionPoint(&*Succ->begin());
if (Enum->getArgumentInterfaceType())
createRefCountOpForPayload(Builder, &*RV, Enum, Switch->getOperand());
}
RV->eraseFromParent();
NumSunk++;
return true;
}
/// Sink retain_value, release_value before select_enum to be retain_value,
/// release_value on the payload of the switch_enum in the destination BBs. We
/// only do this if the destination BBs have only the switch enum as its
/// predecessor.
static bool tryToSinkRefCountAcrossSelectEnum(CondBranchInst *CondBr,
SILBasicBlock::iterator I,
AliasAnalysis *AA,
RCIdentityFunctionInfo *RCIA) {
// If this instruction is not a retain_value, there is nothing left for us to
// do... bail...
if (!isa<RetainValueInst>(I))
return false;
// Make sure the condition comes from a select_enum
auto *SEI = dyn_cast<SelectEnumInst>(CondBr->getCondition());
if (!SEI)
return false;
// Try to find a single literal "true" case.
// TODO: More general conditions in which we can relate the BB to a single
// case, such as when there's a single literal "false" case.
NullablePtr<EnumElementDecl> TrueElement = SEI->getSingleTrueElement();
if (TrueElement.isNull())
return false;
// Next go over all instructions after I in the basic block. If none of them
// can decrement our ptr value, we can move the retain over the ref count
// inst. If any of them do potentially decrement the ref count of Ptr, we can
// not move it.
SILValue Ptr = I->getOperand(0);
auto CondBrIter = CondBr->getIterator();
if (auto B = valueHasARCDecrementOrCheckInInstructionRange(Ptr, std::next(I),
CondBrIter, AA)) {
I->moveBefore(&**B);
return false;
}
// If the retain value's argument is not the cond_br's argument, we can't do
// anything with our simplistic analysis... bail...
if (RCIA->getRCIdentityRoot(Ptr) !=
RCIA->getRCIdentityRoot(SEI->getEnumOperand()))
return false;
// Work out which enum element is the true branch, and which is false.
// If the enum only has 2 values and its tag isn't the true branch, then we
// know the true branch must be the other tag.
EnumElementDecl *Elts[2] = {TrueElement.get(), nullptr};
EnumDecl *E = SEI->getEnumOperand()->getType().getEnumOrBoundGenericEnum();
if (!E)
return false;
// Look for a single other element on this enum.
EnumElementDecl *OtherElt = nullptr;
for (EnumElementDecl *Elt : E->getAllElements()) {
// Skip the case where we find the select_enum element
if (Elt == TrueElement.get())
continue;
// If we find another element, then we must have more than 2, so bail.
if (OtherElt)
return false;
OtherElt = Elt;
}
// Only a single enum element? How would this even get here? We should
// handle it in SILCombine.
if (!OtherElt)
return false;
Elts[1] = OtherElt;
SILBuilderWithScope Builder(SEI, &*I);
// Ok, we have a ref count instruction, sink it!
for (unsigned i = 0; i != 2; ++i) {
EnumElementDecl *Enum = Elts[i];
SILBasicBlock *Succ = i == 0 ? CondBr->getTrueBB() : CondBr->getFalseBB();
Builder.setInsertionPoint(&*Succ->begin());
if (Enum->getArgumentInterfaceType())
createRefCountOpForPayload(Builder, &*I, Enum, SEI->getEnumOperand());
}
I->eraseFromParent();
NumSunk++;
return true;
}
static bool tryTosinkIncrementsIntoSwitchRegions(SILBasicBlock::iterator T,
SILBasicBlock::iterator I,
bool CanSinkToSuccessors,
AliasAnalysis *AA,
RCIdentityFunctionInfo *RCIA) {
// The following methods should only be attempted if we can sink to our
// successor.
if (CanSinkToSuccessors) {
// If we have a switch, try to sink ref counts across it and then return
// that result. We do not keep processing since the code below cannot
// properly sink ref counts over switch_enums so we might as well exit
// early.
if (auto *S = dyn_cast<SwitchEnumInst>(T))
return tryToSinkRefCountAcrossSwitch(S, I, AA, RCIA);
// In contrast, even if we do not sink ref counts across a cond_br from a
// select_enum, we may be able to sink anyways. So we do not return on a
// failure case.
if (auto *CondBr = dyn_cast<CondBranchInst>(T))
if (tryToSinkRefCountAcrossSelectEnum(CondBr, I, AA, RCIA))
return true;
}
// At this point, this is a retain on a regular SSA value, leave it to retain
// release code motion to sink.
return false;
}
/// Try sink a retain as far as possible. This is either to successor BBs,
/// or as far down the current BB as possible
static bool sinkIncrementsIntoSwitchRegions(SILBasicBlock *BB, AliasAnalysis *AA,
RCIdentityFunctionInfo *RCIA) {
// Make sure that each one of our successors only has one predecessor,
// us.
// If that condition is not true, we can still sink to the end of this BB,
// but not to successors.
bool CanSinkToSuccessor = std::none_of(BB->succ_begin(), BB->succ_end(),
[](const SILSuccessor &S) -> bool {
SILBasicBlock *SuccBB = S.getBB();
return !SuccBB || !SuccBB->getSinglePredecessorBlock();
});
SILInstruction *S = BB->getTerminator();
auto SI = S->getIterator(), SE = BB->begin();
if (SI == SE)
return false;
bool Changed = false;
// Walk from the terminator up the BB. Try move retains either to the next
// BB, or the end of this BB. Note that ordering is maintained of retains
// within this BB.
SI = std::prev(SI);
while (SI != SE) {
SILInstruction *Inst = &*SI;
SI = std::prev(SI);
// Try to:
//
// 1. If there are no decrements between our ref count inst and
// terminator, sink the ref count inst into either our successors.
// 2. If there are such decrements, move the retain right before that
// decrement.
Changed |= tryTosinkIncrementsIntoSwitchRegions(S->getIterator(),
Inst->getIterator(),
CanSinkToSuccessor,
AA, RCIA);
}
// Handle the first instruction in the BB.
Changed |=
tryTosinkIncrementsIntoSwitchRegions(S->getIterator(), SI,
CanSinkToSuccessor, AA, RCIA);
return Changed;
}
//===----------------------------------------------------------------------===//
// Enum Tag Dataflow
//===----------------------------------------------------------------------===//
namespace {
class BBToDataflowStateMap;
using EnumBBCaseList = llvm::SmallVector<std::pair<SILBasicBlock *,
EnumElementDecl *>, 2>;
/// Class that performs enum tag state dataflow on the given BB.
class BBEnumTagDataflowState
: public SILInstructionVisitor<BBEnumTagDataflowState, bool> {
NullablePtr<SILBasicBlock> BB;
using ValueToCaseSmallBlotMapVectorTy =
SmallBlotMapVector<SILValue, EnumElementDecl *, 4>;
ValueToCaseSmallBlotMapVectorTy ValueToCaseMap;
using EnumToEnumBBCaseListMapTy =
SmallBlotMapVector<SILValue, EnumBBCaseList, 4>;
EnumToEnumBBCaseListMapTy EnumToEnumBBCaseListMap;
public:
BBEnumTagDataflowState() = default;
BBEnumTagDataflowState(const BBEnumTagDataflowState &Other) = default;
~BBEnumTagDataflowState() = default;
bool init(SILBasicBlock *NewBB) {
assert(NewBB && "NewBB should not be null");
BB = NewBB;
return true;
}
SILBasicBlock *getBB() { return BB.get(); }
using iterator = decltype(ValueToCaseMap)::iterator;
iterator begin() { return ValueToCaseMap.getItems().begin(); }
iterator end() { return ValueToCaseMap.getItems().begin(); }
void clear() { ValueToCaseMap.clear(); }
bool visitValueBase(ValueBase *V) { return false; }
bool visitEnumInst(EnumInst *EI) {
DEBUG(llvm::dbgs() << " Storing enum into map: " << *EI);
ValueToCaseMap[SILValue(EI)] = EI->getElement();
return false;
}
bool visitUncheckedEnumDataInst(UncheckedEnumDataInst *UEDI) {
DEBUG(
llvm::dbgs() << " Storing unchecked enum data into map: " << *UEDI);
ValueToCaseMap[SILValue(UEDI->getOperand())] = UEDI->getElement();
return false;
}
bool visitRetainValueInst(RetainValueInst *RVI);
bool visitReleaseValueInst(ReleaseValueInst *RVI);
bool process();
bool hoistDecrementsIntoSwitchRegions(AliasAnalysis *AA);
bool sinkIncrementsOutOfSwitchRegions(AliasAnalysis *AA,
RCIdentityFunctionInfo *RCIA);
void handlePredSwitchEnum(SwitchEnumInst *S);
void handlePredCondSelectEnum(CondBranchInst *CondBr);
/// Helper method which initializes this state map with the data from the
/// first predecessor BB.
///
/// We will be performing an intersection in a later step of the merging.