-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathSimplifyCFG.cpp
3470 lines (2916 loc) · 114 KB
/
SimplifyCFG.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
//===--- SimplifyCFG.cpp - Clean up the SIL CFG ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-simplify-cfg"
#include "swift/SILPasses/Passes.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SILAnalysis/DominanceAnalysis.h"
#include "swift/SILAnalysis/SimplifyInstruction.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SILPasses/Utils/CFG.h"
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SILPasses/Utils/SILInliner.h"
#include "swift/SILPasses/Utils/SILSSAUpdater.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
STATISTIC(NumBlocksDeleted, "Number of unreachable blocks removed");
STATISTIC(NumBlocksMerged, "Number of blocks merged together");
STATISTIC(NumJumpThreads, "Number of jumps threaded");
STATISTIC(NumConstantFolded, "Number of terminators constant folded");
STATISTIC(NumDeadArguments, "Number of unused arguments removed");
STATISTIC(NumSROAArguments, "Number of aggregate argument levels split by "
"SROA ");
//===----------------------------------------------------------------------===//
// CFG Simplification
//===----------------------------------------------------------------------===//
/// dominatorBasedSimplify iterates between dominator based simplifation of
/// terminator branch condition values and cfg simplification. This is the
/// maximum number of iterations we run. The number is the maximum number of
/// iterations encountered when compiling the stdlib on April 2 2015.
///
static unsigned MaxIterationsOfDominatorBasedSimplify = 10;
namespace {
class SimplifyCFG {
SILFunction &Fn;
SILPassManager *PM;
// WorklistList is the actual list that we iterate over (for determinism).
// Slots may be null, which should be ignored.
SmallVector<SILBasicBlock*, 32> WorklistList;
// WorklistMap keeps track of which slot a BB is in, allowing efficient
// containment query, and allows efficient removal.
llvm::SmallDenseMap<SILBasicBlock*, unsigned, 32> WorklistMap;
// Keep track of loop headers - we don't want to jump-thread through them.
SmallPtrSet<SILBasicBlock *, 32> LoopHeaders;
// Dominance and post-dominance info for the current function
DominanceInfo *DT = nullptr;
PostDominanceInfo *PDT = nullptr;
bool ShouldVerify;
bool EnableJumpThread;
public:
SimplifyCFG(SILFunction &Fn, SILPassManager *PM, bool Verify,
bool EnableJumpThread)
: Fn(Fn), PM(PM), ShouldVerify(Verify),
EnableJumpThread(EnableJumpThread) {}
bool run();
bool simplifyBlockArgs() {
auto *DA = PM->getAnalysis<DominanceAnalysis>();
auto *PDA = PM->getAnalysis<PostDominanceAnalysis>();
DT = DA->get(&Fn);
PDT = PDA->get(&Fn);
bool Changed = false;
for (SILBasicBlock &BB : Fn) {
Changed |= simplifyArgs(&BB);
}
DT = nullptr;
PDT = nullptr;
return Changed;
}
private:
void clearWorklist() {
WorklistMap.clear();
WorklistList.clear();
}
/// popWorklist - Return the next basic block to look at, or null if the
/// worklist is empty. This handles skipping over null entries in the
/// worklist.
SILBasicBlock *popWorklist() {
while (!WorklistList.empty())
if (auto *BB = WorklistList.pop_back_val()) {
WorklistMap.erase(BB);
return BB;
}
return nullptr;
}
/// addToWorklist - Add the specified block to the work list if it isn't
/// already present.
void addToWorklist(SILBasicBlock *BB) {
unsigned &Entry = WorklistMap[BB];
if (Entry != 0) return;
WorklistList.push_back(BB);
Entry = WorklistList.size();
}
/// removeFromWorklist - Remove the specified block from the worklist if
/// present.
void removeFromWorklist(SILBasicBlock *BB) {
assert(BB && "Cannot add null pointer to the worklist");
auto It = WorklistMap.find(BB);
if (It == WorklistMap.end()) return;
// If the BB is in the worklist, null out its entry.
if (It->second) {
assert(WorklistList[It->second-1] == BB && "Consistency error");
WorklistList[It->second-1] = nullptr;
}
// Remove it from the map as well.
WorklistMap.erase(It);
if (LoopHeaders.count(BB))
LoopHeaders.erase(BB);
}
bool simplifyBlocks();
bool canonicalizeSwitchEnums();
bool simplifyThreadedTerminators();
bool dominatorBasedSimplifications(SILFunction &Fn,
DominanceInfo *DT);
bool dominatorBasedSimplify(DominanceAnalysis *DA,
PostDominanceAnalysis *PDA);
/// \brief Remove the basic block if it has no predecessors. Returns true
/// If the block was removed.
bool removeIfDead(SILBasicBlock *BB);
bool tryJumpThreading(BranchInst *BI);
bool tailDuplicateObjCMethodCallSuccessorBlocks();
bool simplifyAfterDroppingPredecessor(SILBasicBlock *BB);
bool simplifyBranchOperands(OperandValueArrayRef Operands);
bool simplifyBranchBlock(BranchInst *BI);
bool simplifyCondBrBlock(CondBranchInst *BI);
bool simplifyCheckedCastBranchBlock(CheckedCastBranchInst *CCBI);
bool simplifyCheckedCastAddrBranchBlock(CheckedCastAddrBranchInst *CCABI);
bool simplifyTryApplyBlock(TryApplyInst *TAI);
bool simplifySwitchValueBlock(SwitchValueInst *SVI);
bool simplifyTermWithIdenticalDestBlocks(SILBasicBlock *BB);
bool simplifySwitchEnumUnreachableBlocks(SwitchEnumInst *SEI);
bool simplifySwitchEnumBlock(SwitchEnumInst *SEI);
bool simplifyUnreachableBlock(UnreachableInst *UI);
bool simplifyArgument(SILBasicBlock *BB, unsigned i);
bool simplifyArgs(SILBasicBlock *BB);
bool trySimplifyCheckedCastBr(TermInst *Term, DominanceInfo *DT);
void findLoopHeaders();
};
class RemoveUnreachable {
SILFunction &Fn;
llvm::SmallSet<SILBasicBlock *, 8> Visited;
public:
RemoveUnreachable(SILFunction &Fn) : Fn(Fn) { }
void visit(SILBasicBlock *BB);
bool run();
};
} // end anonymous namespace
/// Return true if there are any users of V outside the specified block.
static bool isUsedOutsideOfBlock(SILValue V, SILBasicBlock *BB) {
for (auto UI : V.getUses())
if (UI->getUser()->getParent() != BB)
return true;
return false;
}
/// Helper function to perform SSA updates in case of jump threading.
void swift::updateSSAAfterCloning(BaseThreadingCloner &Cloner,
SILBasicBlock *SrcBB, SILBasicBlock *DestBB,
bool NeedToSplitCriticalEdges) {
// We are updating SSA form. This means we need to be able to insert phi
// nodes. To make sure we can do this split all critical edges from
// instructions that don't support block arguments.
if (NeedToSplitCriticalEdges)
splitAllCriticalEdges(*DestBB->getParent(), true, nullptr, nullptr);
SILSSAUpdater SSAUp;
for (auto AvailValPair : Cloner.AvailVals) {
ValueBase *Inst = AvailValPair.first;
if (Inst->use_empty())
continue;
for (unsigned i = 0, e = Inst->getNumTypes(); i != e; ++i) {
// Get the result index for the cloned instruction. This is going to be
// the result index stored in the available value for arguments (we look
// through the phi node) and the same index as the original value
// otherwise.
unsigned ResIdx = i;
if (isa<SILArgument>(Inst))
ResIdx = AvailValPair.second.getResultNumber();
SILValue Res(Inst, i);
SILValue NewRes(AvailValPair.second.getDef(), ResIdx);
SmallVector<UseWrapper, 16> UseList;
// Collect the uses of the value.
for (auto Use : Res.getUses())
UseList.push_back(UseWrapper(Use));
SSAUp.Initialize(Res.getType());
SSAUp.AddAvailableValue(DestBB, Res);
SSAUp.AddAvailableValue(SrcBB, NewRes);
if (UseList.empty())
continue;
// Update all the uses.
for (auto U : UseList) {
Operand *Use = U;
SILInstruction *User = Use->getUser();
assert(User && "Missing user");
// Ignore uses in the same basic block.
if (User->getParent() == DestBB)
continue;
SSAUp.RewriteUse(*Use);
}
}
}
}
/// Perform a dominator-based jump-threading for checked_cast_br [exact]
/// instructions if they use the same condition (modulo upcasts and downcasts).
/// This is very beneficial for code that:
/// - references the same object multiple times (e.g. x.f1() + x.f2())
/// - and for method invocation chaining (e.g. x.f3().f4().f5())
bool
SimplifyCFG::trySimplifyCheckedCastBr(TermInst *Term, DominanceInfo *DT) {
// Ignore unreachable blocks.
if (!DT->getNode(Term->getParent()))
return false;
SmallVector<SILBasicBlock *, 16> BBs;
auto Result = tryCheckedCastBrJumpThreading(Term, DT, BBs);
if (Result) {
for (auto BB: BBs)
addToWorklist(BB);
}
return Result;
}
static SILValue getTerminatorCondition(TermInst *Term) {
if (auto *CondBr = dyn_cast<CondBranchInst>(Term))
return CondBr->getCondition().stripExpectIntrinsic();
if (auto *SEI = dyn_cast<SwitchEnumInst>(Term))
return SEI->getOperand();
return nullptr;
}
/// Is this basic block jump threadable.
static bool isThreadableBlock(SILBasicBlock *BB,
SmallPtrSet<SILBasicBlock *, 32> &LoopHeaders) {
if (isa<ReturnInst>(BB->getTerminator()))
return false;
// We know how to handle cond_br and switch_enum .
if (!isa<CondBranchInst>(BB->getTerminator()) &&
!isa<SwitchEnumInst>(BB->getTerminator()))
return false;
if (LoopHeaders.count(BB))
return false;
unsigned Cost = 0;
for (auto &Inst : *BB) {
if (!Inst.isTriviallyDuplicatable())
return false;
// Don't jumpthread function calls.
if (isa<ApplyInst>(Inst))
return false;
// Only thread 'small blocks'.
if (instructionInlineCost(Inst) != InlineCost::Free)
if (++Cost == 4)
return false;
}
return true;
}
/// A description of an edge leading to a conditionally branching (or switching)
/// block and the successor block to thread to.
///
/// Src:
/// br Dest
/// \
/// \ Edge
/// v
/// Dest:
/// ...
/// switch/cond_br
/// / \
/// ... v
/// EnumCase/ThreadedSuccessorIdx
class ThreadInfo {
SILBasicBlock *Src;
SILBasicBlock *Dest;
EnumElementDecl *EnumCase;
unsigned ThreadedSuccessorIdx;
public:
ThreadInfo(SILBasicBlock *Src, SILBasicBlock *Dest,
unsigned ThreadedBlockSuccessorIdx)
: Src(Src), Dest(Dest), EnumCase(nullptr),
ThreadedSuccessorIdx(ThreadedBlockSuccessorIdx) {}
ThreadInfo(SILBasicBlock *Src, SILBasicBlock *Dest, EnumElementDecl *EnumCase)
: Src(Src), Dest(Dest), EnumCase(EnumCase), ThreadedSuccessorIdx(0) {}
ThreadInfo() = default;
void threadEdge() {
auto *SrcTerm = cast<BranchInst>(Src->getTerminator());
EdgeThreadingCloner Cloner(SrcTerm);
for (auto &I : *Dest)
Cloner.process(&I);
// We have copied the threaded block into the edge.
Src = Cloner.getEdgeBB();
if (auto *CondTerm = dyn_cast<CondBranchInst>(Src->getTerminator())) {
// We know the direction this conditional branch is going to take thread
// it.
assert(Src->getSuccessors().size() > ThreadedSuccessorIdx &&
"Threaded terminator does not have enough successors");
auto *ThreadedSuccessorBlock =
Src->getSuccessors()[ThreadedSuccessorIdx].getBB();
auto Args = ThreadedSuccessorIdx == 0 ? CondTerm->getTrueArgs()
: CondTerm->getFalseArgs();
SILBuilderWithScope(CondTerm)
.createBranch(CondTerm->getLoc(), ThreadedSuccessorBlock, Args);
CondTerm->eraseFromParent();
} else {
// Get the enum element and the destination block of the block we jump
// thread.
auto *SEI = cast<SwitchEnumInst>(Src->getTerminator());
auto *ThreadedSuccessorBlock = SEI->getCaseDestination(EnumCase);
// Instantiate the payload if necessary.
SILBuilderWithScope Builder(SEI);
if (!ThreadedSuccessorBlock->bbarg_empty()) {
auto EnumVal = SEI->getOperand();
auto EnumTy = EnumVal->getType(0);
auto Loc = SEI->getLoc();
auto Ty = EnumTy.getEnumElementType(EnumCase, SEI->getModule());
SILValue UED(
Builder.createUncheckedEnumData(Loc, EnumVal, EnumCase, Ty));
assert(UED.getType() ==
(*ThreadedSuccessorBlock->bbarg_begin())->getType() &&
"Argument types must match");
Builder.createBranch(SEI->getLoc(), ThreadedSuccessorBlock, {UED});
} else
Builder.createBranch(SEI->getLoc(), ThreadedSuccessorBlock, {});
SEI->eraseFromParent();
// Split the edge from 'Dest' to 'ThreadedSuccessorBlock' it is now
// critical. Doing this here safes us from doing it over the whole
// function in updateSSAAfterCloning because we have split all other
// critical edges earlier.
splitEdgesFromTo(Dest, ThreadedSuccessorBlock, nullptr, nullptr);
}
updateSSAAfterCloning(Cloner, Src, Dest, false);
}
};
/// Give a cond_br or switch_enum instruction and one successor block return
/// true if we can infer the value of the condition/enum along the edge to this
/// successor blocks.
static bool isKnownEdgeValue(TermInst *Term, SILBasicBlock *SuccBB,
EnumElementDecl *&EnumCase) {
assert((isa<CondBranchInst>(Term) || isa<SwitchEnumInst>(Term)) &&
"Expect a cond_br or switch_enum");
if (auto *SEI = dyn_cast<SwitchEnumInst>(Term)) {
if (auto Case = SEI->getUniqueCaseForDestination(SuccBB)) {
EnumCase = Case.get();
return SuccBB->getSinglePredecessor() != nullptr;
}
return false;
}
return SuccBB->getSinglePredecessor() != nullptr;
}
/// Create a enum element by extracting the operand of a switch_enum.
static SILInstruction *createEnumElement(SILBuilder &Builder,
SwitchEnumInst *SEI,
EnumElementDecl *EnumElement) {
auto EnumVal = SEI->getOperand();
// Do we have a payload.
auto EnumTy = EnumVal->getType(0);
if (EnumElement->hasArgumentType()) {
auto Ty = EnumTy.getEnumElementType(EnumElement, SEI->getModule());
SILValue UED(Builder.createUncheckedEnumData(SEI->getLoc(), EnumVal,
EnumElement, Ty));
return Builder.createEnum(SEI->getLoc(), UED, EnumElement, EnumTy);
}
return Builder.createEnum(SEI->getLoc(), SILValue(), EnumElement, EnumTy);
}
/// Create a value for the condition of the terminator that flows along the edge
/// with 'EdgeIdx'. Insert it before the 'UserInst'.
static SILInstruction *createValueForEdge(SILInstruction *UserInst,
SILInstruction *DominatingTerminator,
unsigned EdgeIdx) {
SILBuilderWithScope Builder(UserInst);
if (auto *CBI = dyn_cast<CondBranchInst>(DominatingTerminator))
return Builder.createIntegerLiteral(
CBI->getLoc(), CBI->getCondition().getType(), EdgeIdx == 0 ? -1 : 0);
auto *SEI = cast<SwitchEnumInst>(DominatingTerminator);
auto *DstBlock = SEI->getSuccessors()[EdgeIdx].getBB();
auto Case = SEI->getUniqueCaseForDestination(DstBlock);
assert(Case && "No unique case found for destination block");
return createEnumElement(Builder, SEI, Case.get());
}
/// Peform dominator based value simplifications and jump threading on all users
/// of the operand of 'DominatingBB's terminator.
static bool tryDominatorBasedSimplifications(
SILBasicBlock *DominatingBB, DominanceInfo *DT,
SmallPtrSet<SILBasicBlock *, 32> &LoopHeaders,
SmallVectorImpl<ThreadInfo> &JumpThreadableEdges,
llvm::DenseSet<std::pair<SILBasicBlock *, SILBasicBlock *>>
&ThreadedEdgeSet,
bool TryJumpThreading,
llvm::DenseMap<SILBasicBlock *, bool> &CachedThreadable) {
auto *DominatingTerminator = DominatingBB->getTerminator();
// We handle value propagation from cond_br and switch_enum terminators.
bool IsEnumValue = isa<SwitchEnumInst>(DominatingTerminator);
if (!isa<CondBranchInst>(DominatingTerminator) && !IsEnumValue)
return false;
auto DominatingCondition = getTerminatorCondition(DominatingTerminator);
if (!DominatingCondition)
return false;
bool Changed = false;
// We will look at all the outgoing edges from the conditional branch to see
// whether any other uses of the condition or uses of the condition along an
// edge are dominated by said outgoing edges. The outgoing edge carries the
// value on which we switch/cond_branch.
auto Succs = DominatingBB->getSuccessors();
for (unsigned Idx = 0; Idx < Succs.size(); ++Idx) {
auto *DominatingSuccBB = Succs[Idx].getBB();
EnumElementDecl *EnumCase = nullptr;
if (!isKnownEdgeValue(DominatingTerminator, DominatingSuccBB, EnumCase))
continue;
// Look for other uses of DominatingCondition that are either:
// * dominated by the DominatingSuccBB
//
// cond_br %dominating_cond / switch_enum
// /
// /
// /
// DominatingSuccBB:
// ...
// use %dominating_cond
//
// * are a conditional branch that has an incoming edge that is
// dominated by DominatingSuccBB.
//
// cond_br %dominating_cond
// /
// /
// /
//
// DominatingSuccBB:
// ...
// br DestBB
//
// \
// \ E -> %dominating_cond = true
// \
// v
// DestBB
// cond_br %dominating_cond
SmallVector<SILInstruction *, 16> UsersToReplace;
for (auto *Op : ignore_expect_uses(DominatingCondition.getDef())) {
auto *CondUserInst = Op->getUser();
// Ignore the DominatingTerminator itself.
if (CondUserInst->getParent() == DominatingBB)
continue;
// For enum values we are only interested in switch_enum and select_enum
// users.
if (IsEnumValue && !isa<SwitchEnumInst>(CondUserInst) &&
!isa<SelectEnumInst>(CondUserInst))
continue;
// If the use is dominated we can replace this use by the value
// flowing to DominatingSuccBB.
if (DT->dominates(DominatingSuccBB, CondUserInst->getParent())) {
UsersToReplace.push_back(CondUserInst);
continue;
}
// Jump threading is expensive so we don't always do it.
if (!TryJumpThreading)
continue;
auto *DestBB = CondUserInst->getParent();
// The user must be the terminator we are trying to jump thread.
if (CondUserInst != DestBB->getTerminator())
continue;
// Check whether we have seen this destination block already.
auto CacheEntryIt = CachedThreadable.find(DestBB);
bool IsThreadable = CacheEntryIt != CachedThreadable.end()
? CacheEntryIt->second
: (CachedThreadable[DestBB] =
isThreadableBlock(DestBB, LoopHeaders));
// If the use is a conditional branch/switch then look for an incoming
// edge that is dominated by DominatingSuccBB.
if (IsThreadable) {
auto Preds = DestBB->getPreds();
for (SILBasicBlock *PredBB : Preds) {
if (!isa<BranchInst>(PredBB->getTerminator()))
continue;
if (!DT->dominates(DominatingSuccBB, PredBB))
continue;
// Don't jumpthread the same edge twice.
if (!ThreadedEdgeSet.insert(std::make_pair(PredBB, DestBB)).second)
continue;
if (isa<CondBranchInst>(DestBB->getTerminator()))
JumpThreadableEdges.push_back(ThreadInfo(PredBB, DestBB, Idx));
else
JumpThreadableEdges.push_back(ThreadInfo(PredBB, DestBB, EnumCase));
break;
}
}
}
// Replace dominated user instructions.
for (auto *UserInst : UsersToReplace) {
SILInstruction *EdgeValue = nullptr;
for (auto &Op : UserInst->getAllOperands()) {
if (Op.get().stripExpectIntrinsic() == DominatingCondition) {
if (!EdgeValue)
EdgeValue = createValueForEdge(UserInst, DominatingTerminator, Idx);
Op.set(EdgeValue);
Changed = true;
}
}
}
}
return Changed;
}
/// Propagate values of branched upon values along the outgoing edges down the
/// dominator tree.
bool SimplifyCFG::dominatorBasedSimplifications(SILFunction &Fn,
DominanceInfo *DT) {
bool Changed = false;
// Collect jump threadable edges and propagate outgoing edge values of
// conditional branches/switches.
SmallVector<ThreadInfo, 8> JumpThreadableEdges;
llvm::DenseMap<SILBasicBlock *, bool> CachedThreadable;
llvm::DenseSet<std::pair<SILBasicBlock *, SILBasicBlock *>> ThreadedEdgeSet;
for (auto &BB : Fn)
if (DT->getNode(&BB)) // Only handle reachable blocks.
Changed |= tryDominatorBasedSimplifications(
&BB, DT, LoopHeaders, JumpThreadableEdges, ThreadedEdgeSet,
EnableJumpThread, CachedThreadable);
// Nothing to jump thread?
if (JumpThreadableEdges.empty())
return Changed;
for (auto &ThreadInfo : JumpThreadableEdges) {
ThreadInfo.threadEdge();
Changed = true;
}
return Changed;
}
/// Simplify terminators that could have been simplified by threading.
bool SimplifyCFG::simplifyThreadedTerminators() {
bool HaveChangedCFG = false;
for (auto &BB : Fn) {
auto *Term = BB.getTerminator();
// Simplify a switch_enum.
if (auto *SEI = dyn_cast<SwitchEnumInst>(Term)) {
if (auto *EI = dyn_cast<EnumInst>(SEI->getOperand())) {
auto *LiveBlock = SEI->getCaseDestination(EI->getElement());
if (EI->hasOperand() && !LiveBlock->bbarg_empty())
SILBuilderWithScope(SEI)
.createBranch(SEI->getLoc(), LiveBlock, EI->getOperand());
else
SILBuilderWithScope(SEI).createBranch(SEI->getLoc(), LiveBlock);
SEI->eraseFromParent();
if (EI->use_empty())
EI->eraseFromParent();
HaveChangedCFG = true;
}
continue;
} else if (auto *CondBr = dyn_cast<CondBranchInst>(Term)) {
// If the condition is an integer literal, we can constant fold the
// branch.
if (auto *IL = dyn_cast<IntegerLiteralInst>(CondBr->getCondition())) {
SILBasicBlock *TrueSide = CondBr->getTrueBB();
SILBasicBlock *FalseSide = CondBr->getFalseBB();
auto TrueArgs = CondBr->getTrueArgs();
auto FalseArgs = CondBr->getFalseArgs();
bool isFalse = !IL->getValue();
auto LiveArgs = isFalse ? FalseArgs : TrueArgs;
auto *LiveBlock = isFalse ? FalseSide : TrueSide;
SILBuilderWithScope(CondBr)
.createBranch(CondBr->getLoc(), LiveBlock, LiveArgs);
CondBr->eraseFromParent();
if (IL->use_empty())
IL->eraseFromParent();
HaveChangedCFG = true;
}
}
}
return HaveChangedCFG;
}
// Simplifications that walk the dominator tree to prove redundancy in
// conditional branching.
bool SimplifyCFG::dominatorBasedSimplify(DominanceAnalysis *DA,
PostDominanceAnalysis *PDA) {
// Get the dominator tree.
DT = DA->get(&Fn);
// Split all critical edges such that we can move code onto edges. This is
// also required for SSA construction in dominatorBasedSimplifications' jump
// threading. It only splits new critical edges it creates by jump threading.
bool Changed =
EnableJumpThread ? splitAllCriticalEdges(Fn, false, DT, nullptr) : false;
unsigned MaxIter = MaxIterationsOfDominatorBasedSimplify;
bool HasChangedInCurrentIter;
do {
HasChangedInCurrentIter = false;
// Do dominator based simplification of terminator condition. This does not
// and MUST NOT change the CFG without updating the dominator tree to
// reflect such change.
for (auto &BB : Fn) {
// Any method called from this loop should update
// the DT if it changes anything related to dominators.
TermInst *Term = BB.getTerminator();
switch (Term->getKind()) {
case ValueKind::SwitchValueInst:
// TODO: handle switch_value
break;
case ValueKind::CheckedCastBranchInst:
if (trySimplifyCheckedCastBr(BB.getTerminator(), DT)) {
HasChangedInCurrentIter = true;
// FIXME: trySimplifyCheckedCastBr function should preserve the
// dominator tree but its code to do so is buggy.
DT->recalculate(Fn);
}
break;
default:
break;
}
}
if (ShouldVerify)
DT->verify();
// Simplify the block argument list. This is extremely subtle: simplifyArgs
// will not change the CFG iff the PDT is null. Really we should move that
// one optimization out of simplifyArgs ... I am squinting at you
// simplifySwitchEnumToSelectEnum.
// simplifyArgs does use the dominator tree, though.
PDT = nullptr;
for (auto &BB : Fn)
HasChangedInCurrentIter |= simplifyArgs(&BB);
if (ShouldVerify)
DT->verify();
// Jump thread.
if (dominatorBasedSimplifications(Fn, DT)) {
DominanceInfo *InvalidDT = DT;
DT = nullptr;
HasChangedInCurrentIter = true;
// Simplify terminators.
simplifyThreadedTerminators();
DT = InvalidDT;
DT->recalculate(Fn);
}
Changed |= HasChangedInCurrentIter;
} while (HasChangedInCurrentIter && --MaxIter);
// Do the simplification that requires both the dom and postdom tree.
PDT = PDA->get(&Fn);
for (auto &BB : Fn)
Changed |= simplifyArgs(&BB);
if (ShouldVerify)
DT->verify();
// The functions we used to simplify the CFG put things in the worklist. Clear
// it here.
clearWorklist();
return Changed;
}
// If BB is trivially unreachable, remove it from the worklist, add its
// successors to the worklist, and then remove the block.
bool SimplifyCFG::removeIfDead(SILBasicBlock *BB) {
if (!BB->pred_empty() || BB == &*Fn.begin())
return false;
removeFromWorklist(BB);
// Add successor blocks to the worklist since their predecessor list is about
// to change.
for (auto &S : BB->getSuccessors())
addToWorklist(S);
removeDeadBlock(BB);
++NumBlocksDeleted;
return true;
}
/// This is called when a predecessor of a block is dropped, to simplify the
/// block and add it to the worklist.
bool SimplifyCFG::simplifyAfterDroppingPredecessor(SILBasicBlock *BB) {
// TODO: If BB has only one predecessor and has bb args, fold them away, then
// use instsimplify on all the users of those values - even ones outside that
// block.
// Make sure that DestBB is in the worklist, as well as its remaining
// predecessors, since they may not be able to be simplified.
addToWorklist(BB);
for (auto *P : BB->getPreds())
addToWorklist(P);
return false;
}
/// couldSimplifyUsers - Check to see if any simplifications are possible if
/// "Val" is substituted for BBArg. If so, return true, if nothing obvious
/// is possible, return false.
static bool couldSimplifyUsers(SILArgument *BBArg, SILValue Val) {
// If the value being substituted is an enum, check to see if there are any
// switches on it.
auto *EI = dyn_cast<EnumInst>(Val);
if (!EI)
return false;
for (auto UI : BBArg->getUses()) {
auto *User = UI->getUser();
// We only know we can simplify if the switch_enum user is in the block we
// are trying to jump thread.
// The value must not be define in the same basic block as the switch enum
// user. If this is the case we have a single block switch_enum loop.
if (isa<SwitchEnumInst>(User) || isa<SelectEnumInst>(User))
if (BBArg->getParent() == User->getParent() &&
EI->getParent() != BBArg->getParent())
return true;
// Also allow enum of enum, which usually can be combined to a single
// instruction. This helps to simplify the creation of an enum from an
// integer raw value.
if (isa<EnumInst>(User))
if (BBArg->getParent() == User->getParent() &&
EI->getParent() != BBArg->getParent())
return true;
}
return false;
}
void SimplifyCFG::findLoopHeaders() {
/// Find back edges in the CFG. This performs a dfs search and identifies
/// back edges as edges going to an ancestor in the dfs search. If a basic
/// block is the target of such a back edge we will identify it as a header.
LoopHeaders.clear();
SmallPtrSet<SILBasicBlock *, 16> Visited;
SmallPtrSet<SILBasicBlock *, 16> InDFSStack;
SmallVector<std::pair<SILBasicBlock *, SILBasicBlock::succ_iterator>, 16>
DFSStack;
auto EntryBB = &Fn.front();
DFSStack.push_back(std::make_pair(EntryBB, EntryBB->succ_begin()));
Visited.insert(EntryBB);
InDFSStack.insert(EntryBB);
while (!DFSStack.empty()) {
auto &D = DFSStack.back();
// No successors.
if (D.second == D.first->succ_end()) {
// Retreat the dfs search.
DFSStack.pop_back();
InDFSStack.erase(D.first);
} else {
// Visit the next successor.
SILBasicBlock *NextSucc = *(D.second);
++D.second;
if (Visited.insert(NextSucc).second) {
InDFSStack.insert(NextSucc);
DFSStack.push_back(std::make_pair(NextSucc, NextSucc->succ_begin()));
} else if (InDFSStack.count(NextSucc)) {
// We have already visited this node and it is in our dfs search. This
// is a back-edge.
LoopHeaders.insert(NextSucc);
}
}
}
}
/// tryJumpThreading - Check to see if it looks profitable to duplicate the
/// destination of an unconditional jump into the bottom of this block.
bool SimplifyCFG::tryJumpThreading(BranchInst *BI) {
auto *DestBB = BI->getDestBB();
auto *SrcBB = BI->getParent();
// If the destination block ends with a return, we don't want to duplicate it.
// We want to maintain the canonical form of a single return where possible.
if (isa<ReturnInst>(DestBB->getTerminator()))
return false;
// We need to update SSA if a value duplicated is used outside of the
// duplicated block.
bool NeedToUpdateSSA = false;
// Are the arguments to this block used outside of the block.
for (auto Arg : DestBB->getBBArgs())
if ((NeedToUpdateSSA |= isUsedOutsideOfBlock(Arg, DestBB))) {
break;
}
// We don't have a great cost model at the SIL level, so we don't want to
// blissly duplicate tons of code with a goal of improved performance (we'll
// leave that to LLVM). However, doing limited code duplication can lead to
// major second order simplifications. Here we only do it if there are
// "constant" arguments to the branch or if we know how to fold something
// given the duplication.
bool WantToThread = false;
if (isa<CondBranchInst>(DestBB->getTerminator()))
for (auto V : BI->getArgs()) {
if (isa<IntegerLiteralInst>(V) || isa<FloatLiteralInst>(V)) {
WantToThread = true;
break;
}
}
if (!WantToThread) {
for (unsigned i = 0, e = BI->getArgs().size(); i != e; ++i)
if (couldSimplifyUsers(DestBB->getBBArg(i), BI->getArg(i))) {
WantToThread = true;
break;
}
}
// If we don't have anything that we can simplify, don't do it.
if (!WantToThread) return false;
// If it looks potentially interesting, decide whether we *can* do the
// operation and whether the block is small enough to be worth duplicating.
unsigned Cost = 0;
for (auto &Inst : *DestBB) {
if (!Inst.isTriviallyDuplicatable())
return false;
// Don't jumpthread function calls.
if (isa<ApplyInst>(Inst))
return false;
// This is a really trivial cost model, which is only intended as a starting
// point.
if (instructionInlineCost(Inst) != InlineCost::Free)
if (++Cost == 4) return false;
// We need to update ssa if a value is used outside the duplicated block.
if (!NeedToUpdateSSA)
NeedToUpdateSSA |= isUsedOutsideOfBlock(&Inst, DestBB);
}
// Don't jump thread through a potential header - this can produce irreducible
// control flow.
if (!isa<SwitchEnumInst>(DestBB->getTerminator()) &&
LoopHeaders.count(DestBB))
return false;
// Okay, it looks like we want to do this and we can. Duplicate the
// destination block into this one, rewriting uses of the BBArgs to use the
// branch arguments as we go.
EdgeThreadingCloner Cloner(BI);
for (auto &I : *DestBB)
Cloner.process(&I);
// Once all the instructions are copied, we can nuke BI itself. We also add
// the threaded and edge block to the worklist now that they (likely) can be
// simplified.
addToWorklist(SrcBB);
addToWorklist(Cloner.getEdgeBB());
if (NeedToUpdateSSA)
updateSSAAfterCloning(Cloner, Cloner.getEdgeBB(), DestBB);
// We may be able to simplify DestBB now that it has one fewer predecessor.
simplifyAfterDroppingPredecessor(DestBB);
++NumJumpThreads;
return true;
}
/// simplifyBranchOperands - Simplify operands of branches, since it can
/// result in exposing opportunities for CFG simplification.
bool SimplifyCFG::simplifyBranchOperands(OperandValueArrayRef Operands) {
bool Simplified = false;
for (auto O = Operands.begin(), E = Operands.end(); O != E; ++O)
if (auto *I = dyn_cast<SILInstruction>(*O))
if (SILValue Result = simplifyInstruction(I)) {
SILValue(I, 0).replaceAllUsesWith(Result.getDef());
if (isInstructionTriviallyDead(I)) {
eraseFromParentWithDebugInsts(I);
Simplified = true;
}
}
return Simplified;
}
static bool onlyHasTerminatorAndDebugInsts(SILBasicBlock *BB) {
TermInst *Terminator = BB->getTerminator();
SILBasicBlock::iterator Iter = BB->begin();
while (&*Iter != Terminator) {
if (!isDebugInst(&*Iter))
return false;
Iter++;
}
return true;
}
/// \return If this basic blocks has a single br instruction passing all of the
/// arguments in the original order, then returns the destination of that br.
static SILBasicBlock *getTrampolineDest(SILBasicBlock *SBB) {
// Ignore blocks with more than one instruction.
if (!onlyHasTerminatorAndDebugInsts(SBB))
return nullptr;
BranchInst *BI = dyn_cast<BranchInst>(SBB->getTerminator());
if (!BI)
return nullptr;
// Disallow infinite loops.