forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleLoopUnswitch.cpp
3263 lines (2886 loc) · 135 KB
/
SimpleLoopUnswitch.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
///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/CodeMetrics.h"
#include "llvm/Analysis/GuardUtils.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LoopAnalysisManager.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/LoopIterator.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/MustExecute.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/GenericDomTree.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <numeric>
#include <utility>
#define DEBUG_TYPE "simple-loop-unswitch"
using namespace llvm;
using namespace llvm::PatternMatch;
STATISTIC(NumBranches, "Number of branches unswitched");
STATISTIC(NumSwitches, "Number of switches unswitched");
STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
STATISTIC(NumTrivial, "Number of unswitches that are trivial");
STATISTIC(
NumCostMultiplierSkipped,
"Number of unswitch candidates that had their cost multiplier skipped");
static cl::opt<bool> EnableNonTrivialUnswitch(
"enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
cl::desc("Forcibly enables non-trivial loop unswitching rather than "
"following the configuration passed into the pass."));
static cl::opt<int>
UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
cl::ZeroOrMore,
cl::desc("The cost threshold for unswitching a loop."));
static cl::opt<bool> EnableUnswitchCostMultiplier(
"enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
cl::desc("Enable unswitch cost multiplier that prohibits exponential "
"explosion in nontrivial unswitch."));
static cl::opt<int> UnswitchSiblingsToplevelDiv(
"unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
cl::desc("Toplevel siblings divisor for cost multiplier."));
static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
"unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
cl::desc("Number of unswitch candidates that are ignored when calculating "
"cost multiplier."));
static cl::opt<bool> UnswitchGuards(
"simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
cl::desc("If enabled, simple loop unswitching will also consider "
"llvm.experimental.guard intrinsics as unswitch candidates."));
static cl::opt<bool> DropNonTrivialImplicitNullChecks(
"simple-loop-unswitch-drop-non-trivial-implicit-null-checks",
cl::init(false), cl::Hidden,
cl::desc("If enabled, drop make.implicit metadata in unswitched implicit "
"null checks to save time analyzing if we can keep it."));
static cl::opt<unsigned>
MSSAThreshold("simple-loop-unswitch-memoryssa-threshold",
cl::desc("Max number of memory uses to explore during "
"partial unswitching analysis"),
cl::init(100), cl::Hidden);
static cl::opt<bool> FreezeLoopUnswitchCond(
"freeze-loop-unswitch-cond", cl::init(false), cl::Hidden,
cl::desc("If enabled, the freeze instruction will be added to condition "
"of loop unswitch to prevent miscompilation."));
/// Collect all of the loop invariant input values transitively used by the
/// homogeneous instruction graph from a given root.
///
/// This essentially walks from a root recursively through loop variant operands
/// which have the exact same opcode and finds all inputs which are loop
/// invariant. For some operations these can be re-associated and unswitched out
/// of the loop entirely.
static TinyPtrVector<Value *>
collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
LoopInfo &LI) {
assert(!L.isLoopInvariant(&Root) &&
"Only need to walk the graph if root itself is not invariant.");
TinyPtrVector<Value *> Invariants;
bool IsRootAnd = match(&Root, m_LogicalAnd());
bool IsRootOr = match(&Root, m_LogicalOr());
// Build a worklist and recurse through operators collecting invariants.
SmallVector<Instruction *, 4> Worklist;
SmallPtrSet<Instruction *, 8> Visited;
Worklist.push_back(&Root);
Visited.insert(&Root);
do {
Instruction &I = *Worklist.pop_back_val();
for (Value *OpV : I.operand_values()) {
// Skip constants as unswitching isn't interesting for them.
if (isa<Constant>(OpV))
continue;
// Add it to our result if loop invariant.
if (L.isLoopInvariant(OpV)) {
Invariants.push_back(OpV);
continue;
}
// If not an instruction with the same opcode, nothing we can do.
Instruction *OpI = dyn_cast<Instruction>(OpV);
if (OpI && ((IsRootAnd && match(OpI, m_LogicalAnd())) ||
(IsRootOr && match(OpI, m_LogicalOr())))) {
// Visit this operand.
if (Visited.insert(OpI).second)
Worklist.push_back(OpI);
}
}
} while (!Worklist.empty());
return Invariants;
}
static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
Constant &Replacement) {
assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
// Replace uses of LIC in the loop with the given constant.
// We use make_early_inc_range as set invalidates the iterator.
for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
Instruction *UserI = dyn_cast<Instruction>(U.getUser());
// Replace this use within the loop body.
if (UserI && L.contains(UserI))
U.set(&Replacement);
}
}
/// Check that all the LCSSA PHI nodes in the loop exit block have trivial
/// incoming values along this edge.
static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
BasicBlock &ExitBB) {
for (Instruction &I : ExitBB) {
auto *PN = dyn_cast<PHINode>(&I);
if (!PN)
// No more PHIs to check.
return true;
// If the incoming value for this edge isn't loop invariant the unswitch
// won't be trivial.
if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
return false;
}
llvm_unreachable("Basic blocks should never be empty!");
}
/// Copy a set of loop invariant values \p ToDuplicate and insert them at the
/// end of \p BB and conditionally branch on the copied condition. We only
/// branch on a single value.
static void buildPartialUnswitchConditionalBranch(
BasicBlock &BB, ArrayRef<Value *> Invariants, bool Direction,
BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, bool InsertFreeze) {
IRBuilder<> IRB(&BB);
Value *Cond = Direction ? IRB.CreateOr(Invariants) :
IRB.CreateAnd(Invariants);
if (InsertFreeze)
Cond = IRB.CreateFreeze(Cond, Cond->getName() + ".fr");
IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
Direction ? &NormalSucc : &UnswitchedSucc);
}
/// Copy a set of loop invariant values, and conditionally branch on them.
static void buildPartialInvariantUnswitchConditionalBranch(
BasicBlock &BB, ArrayRef<Value *> ToDuplicate, bool Direction,
BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, Loop &L,
MemorySSAUpdater *MSSAU) {
ValueToValueMapTy VMap;
for (auto *Val : reverse(ToDuplicate)) {
Instruction *Inst = cast<Instruction>(Val);
Instruction *NewInst = Inst->clone();
BB.getInstList().insert(BB.end(), NewInst);
RemapInstruction(NewInst, VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
VMap[Val] = NewInst;
if (!MSSAU)
continue;
MemorySSA *MSSA = MSSAU->getMemorySSA();
if (auto *MemUse =
dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(Inst))) {
auto *DefiningAccess = MemUse->getDefiningAccess();
// Get the first defining access before the loop.
while (L.contains(DefiningAccess->getBlock())) {
// If the defining access is a MemoryPhi, get the incoming
// value for the pre-header as defining access.
if (auto *MemPhi = dyn_cast<MemoryPhi>(DefiningAccess))
DefiningAccess =
MemPhi->getIncomingValueForBlock(L.getLoopPreheader());
else
DefiningAccess = cast<MemoryDef>(DefiningAccess)->getDefiningAccess();
}
MSSAU->createMemoryAccessInBB(NewInst, DefiningAccess,
NewInst->getParent(),
MemorySSA::BeforeTerminator);
}
}
IRBuilder<> IRB(&BB);
Value *Cond = VMap[ToDuplicate[0]];
IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
Direction ? &NormalSucc : &UnswitchedSucc);
}
/// Rewrite the PHI nodes in an unswitched loop exit basic block.
///
/// Requires that the loop exit and unswitched basic block are the same, and
/// that the exiting block was a unique predecessor of that block. Rewrites the
/// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
/// PHI nodes from the old preheader that now contains the unswitched
/// terminator.
static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
BasicBlock &OldExitingBB,
BasicBlock &OldPH) {
for (PHINode &PN : UnswitchedBB.phis()) {
// When the loop exit is directly unswitched we just need to update the
// incoming basic block. We loop to handle weird cases with repeated
// incoming blocks, but expect to typically only have one operand here.
for (auto i : seq<int>(0, PN.getNumOperands())) {
assert(PN.getIncomingBlock(i) == &OldExitingBB &&
"Found incoming block different from unique predecessor!");
PN.setIncomingBlock(i, &OldPH);
}
}
}
/// Rewrite the PHI nodes in the loop exit basic block and the split off
/// unswitched block.
///
/// Because the exit block remains an exit from the loop, this rewrites the
/// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
/// nodes into the unswitched basic block to select between the value in the
/// old preheader and the loop exit.
static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
BasicBlock &UnswitchedBB,
BasicBlock &OldExitingBB,
BasicBlock &OldPH,
bool FullUnswitch) {
assert(&ExitBB != &UnswitchedBB &&
"Must have different loop exit and unswitched blocks!");
Instruction *InsertPt = &*UnswitchedBB.begin();
for (PHINode &PN : ExitBB.phis()) {
auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
PN.getName() + ".split", InsertPt);
// Walk backwards over the old PHI node's inputs to minimize the cost of
// removing each one. We have to do this weird loop manually so that we
// create the same number of new incoming edges in the new PHI as we expect
// each case-based edge to be included in the unswitched switch in some
// cases.
// FIXME: This is really, really gross. It would be much cleaner if LLVM
// allowed us to create a single entry for a predecessor block without
// having separate entries for each "edge" even though these edges are
// required to produce identical results.
for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
if (PN.getIncomingBlock(i) != &OldExitingBB)
continue;
Value *Incoming = PN.getIncomingValue(i);
if (FullUnswitch)
// No more edge from the old exiting block to the exit block.
PN.removeIncomingValue(i);
NewPN->addIncoming(Incoming, &OldPH);
}
// Now replace the old PHI with the new one and wire the old one in as an
// input to the new one.
PN.replaceAllUsesWith(NewPN);
NewPN->addIncoming(&PN, &ExitBB);
}
}
/// Hoist the current loop up to the innermost loop containing a remaining exit.
///
/// Because we've removed an exit from the loop, we may have changed the set of
/// loops reachable and need to move the current loop up the loop nest or even
/// to an entirely separate nest.
static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
DominatorTree &DT, LoopInfo &LI,
MemorySSAUpdater *MSSAU, ScalarEvolution *SE) {
// If the loop is already at the top level, we can't hoist it anywhere.
Loop *OldParentL = L.getParentLoop();
if (!OldParentL)
return;
SmallVector<BasicBlock *, 4> Exits;
L.getExitBlocks(Exits);
Loop *NewParentL = nullptr;
for (auto *ExitBB : Exits)
if (Loop *ExitL = LI.getLoopFor(ExitBB))
if (!NewParentL || NewParentL->contains(ExitL))
NewParentL = ExitL;
if (NewParentL == OldParentL)
return;
// The new parent loop (if different) should always contain the old one.
if (NewParentL)
assert(NewParentL->contains(OldParentL) &&
"Can only hoist this loop up the nest!");
// The preheader will need to move with the body of this loop. However,
// because it isn't in this loop we also need to update the primary loop map.
assert(OldParentL == LI.getLoopFor(&Preheader) &&
"Parent loop of this loop should contain this loop's preheader!");
LI.changeLoopFor(&Preheader, NewParentL);
// Remove this loop from its old parent.
OldParentL->removeChildLoop(&L);
// Add the loop either to the new parent or as a top-level loop.
if (NewParentL)
NewParentL->addChildLoop(&L);
else
LI.addTopLevelLoop(&L);
// Remove this loops blocks from the old parent and every other loop up the
// nest until reaching the new parent. Also update all of these
// no-longer-containing loops to reflect the nesting change.
for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
OldContainingL = OldContainingL->getParentLoop()) {
llvm::erase_if(OldContainingL->getBlocksVector(),
[&](const BasicBlock *BB) {
return BB == &Preheader || L.contains(BB);
});
OldContainingL->getBlocksSet().erase(&Preheader);
for (BasicBlock *BB : L.blocks())
OldContainingL->getBlocksSet().erase(BB);
// Because we just hoisted a loop out of this one, we have essentially
// created new exit paths from it. That means we need to form LCSSA PHI
// nodes for values used in the no-longer-nested loop.
formLCSSA(*OldContainingL, DT, &LI, SE);
// We shouldn't need to form dedicated exits because the exit introduced
// here is the (just split by unswitching) preheader. However, after trivial
// unswitching it is possible to get new non-dedicated exits out of parent
// loop so let's conservatively form dedicated exit blocks and figure out
// if we can optimize later.
formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
/*PreserveLCSSA*/ true);
}
}
// Return the top-most loop containing ExitBB and having ExitBB as exiting block
// or the loop containing ExitBB, if there is no parent loop containing ExitBB
// as exiting block.
static Loop *getTopMostExitingLoop(BasicBlock *ExitBB, LoopInfo &LI) {
Loop *TopMost = LI.getLoopFor(ExitBB);
Loop *Current = TopMost;
while (Current) {
if (Current->isLoopExiting(ExitBB))
TopMost = Current;
Current = Current->getParentLoop();
}
return TopMost;
}
/// Unswitch a trivial branch if the condition is loop invariant.
///
/// This routine should only be called when loop code leading to the branch has
/// been validated as trivial (no side effects). This routine checks if the
/// condition is invariant and one of the successors is a loop exit. This
/// allows us to unswitch without duplicating the loop, making it trivial.
///
/// If this routine fails to unswitch the branch it returns false.
///
/// If the branch can be unswitched, this routine splits the preheader and
/// hoists the branch above that split. Preserves loop simplified form
/// (splitting the exit block as necessary). It simplifies the branch within
/// the loop to an unconditional branch but doesn't remove it entirely. Further
/// cleanup can be done with some simplifycfg like pass.
///
/// If `SE` is not null, it will be updated based on the potential loop SCEVs
/// invalidated by this.
static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
LoopInfo &LI, ScalarEvolution *SE,
MemorySSAUpdater *MSSAU) {
assert(BI.isConditional() && "Can only unswitch a conditional branch!");
LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n");
// The loop invariant values that we want to unswitch.
TinyPtrVector<Value *> Invariants;
// When true, we're fully unswitching the branch rather than just unswitching
// some input conditions to the branch.
bool FullUnswitch = false;
if (L.isLoopInvariant(BI.getCondition())) {
Invariants.push_back(BI.getCondition());
FullUnswitch = true;
} else {
if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
if (Invariants.empty()) {
LLVM_DEBUG(dbgs() << " Couldn't find invariant inputs!\n");
return false;
}
}
// Check that one of the branch's successors exits, and which one.
bool ExitDirection = true;
int LoopExitSuccIdx = 0;
auto *LoopExitBB = BI.getSuccessor(0);
if (L.contains(LoopExitBB)) {
ExitDirection = false;
LoopExitSuccIdx = 1;
LoopExitBB = BI.getSuccessor(1);
if (L.contains(LoopExitBB)) {
LLVM_DEBUG(dbgs() << " Branch doesn't exit the loop!\n");
return false;
}
}
auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
auto *ParentBB = BI.getParent();
if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) {
LLVM_DEBUG(dbgs() << " Loop exit PHI's aren't loop-invariant!\n");
return false;
}
// When unswitching only part of the branch's condition, we need the exit
// block to be reached directly from the partially unswitched input. This can
// be done when the exit block is along the true edge and the branch condition
// is a graph of `or` operations, or the exit block is along the false edge
// and the condition is a graph of `and` operations.
if (!FullUnswitch) {
if (ExitDirection ? !match(BI.getCondition(), m_LogicalOr())
: !match(BI.getCondition(), m_LogicalAnd())) {
LLVM_DEBUG(dbgs() << " Branch condition is in improper form for "
"non-full unswitch!\n");
return false;
}
}
LLVM_DEBUG({
dbgs() << " unswitching trivial invariant conditions for: " << BI
<< "\n";
for (Value *Invariant : Invariants) {
dbgs() << " " << *Invariant << " == true";
if (Invariant != Invariants.back())
dbgs() << " ||";
dbgs() << "\n";
}
});
// If we have scalar evolutions, we need to invalidate them including this
// loop, the loop containing the exit block and the topmost parent loop
// exiting via LoopExitBB.
if (SE) {
if (Loop *ExitL = getTopMostExitingLoop(LoopExitBB, LI))
SE->forgetLoop(ExitL);
else
// Forget the entire nest as this exits the entire nest.
SE->forgetTopmostLoop(&L);
}
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
// Split the preheader, so that we know that there is a safe place to insert
// the conditional branch. We will change the preheader to have a conditional
// branch on LoopCond.
BasicBlock *OldPH = L.getLoopPreheader();
BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
// Now that we have a place to insert the conditional branch, create a place
// to branch to: this is the exit block out of the loop that we are
// unswitching. We need to split this if there are other loop predecessors.
// Because the loop is in simplified form, *any* other predecessor is enough.
BasicBlock *UnswitchedBB;
if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
"A branch's parent isn't a predecessor!");
UnswitchedBB = LoopExitBB;
} else {
UnswitchedBB =
SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
}
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
// Actually move the invariant uses into the unswitched position. If possible,
// we do this by moving the instructions, but when doing partial unswitching
// we do it by building a new merge of the values in the unswitched position.
OldPH->getTerminator()->eraseFromParent();
if (FullUnswitch) {
// If fully unswitching, we can use the existing branch instruction.
// Splice it into the old PH to gate reaching the new preheader and re-point
// its successors.
OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
BI);
if (MSSAU) {
// Temporarily clone the terminator, to make MSSA update cheaper by
// separating "insert edge" updates from "remove edge" ones.
ParentBB->getInstList().push_back(BI.clone());
} else {
// Create a new unconditional branch that will continue the loop as a new
// terminator.
BranchInst::Create(ContinueBB, ParentBB);
}
BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
} else {
// Only unswitching a subset of inputs to the condition, so we will need to
// build a new branch that merges the invariant inputs.
if (ExitDirection)
assert(match(BI.getCondition(), m_LogicalOr()) &&
"Must have an `or` of `i1`s or `select i1 X, true, Y`s for the "
"condition!");
else
assert(match(BI.getCondition(), m_LogicalAnd()) &&
"Must have an `and` of `i1`s or `select i1 X, Y, false`s for the"
" condition!");
buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
*UnswitchedBB, *NewPH, false);
}
// Update the dominator tree with the added edge.
DT.insertEdge(OldPH, UnswitchedBB);
// After the dominator tree was updated with the added edge, update MemorySSA
// if available.
if (MSSAU) {
SmallVector<CFGUpdate, 1> Updates;
Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
MSSAU->applyInsertUpdates(Updates, DT);
}
// Finish updating dominator tree and memory ssa for full unswitch.
if (FullUnswitch) {
if (MSSAU) {
// Remove the cloned branch instruction.
ParentBB->getTerminator()->eraseFromParent();
// Create unconditional branch now.
BranchInst::Create(ContinueBB, ParentBB);
MSSAU->removeEdge(ParentBB, LoopExitBB);
}
DT.deleteEdge(ParentBB, LoopExitBB);
}
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
// Rewrite the relevant PHI nodes.
if (UnswitchedBB == LoopExitBB)
rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
else
rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
*ParentBB, *OldPH, FullUnswitch);
// The constant we can replace all of our invariants with inside the loop
// body. If any of the invariants have a value other than this the loop won't
// be entered.
ConstantInt *Replacement = ExitDirection
? ConstantInt::getFalse(BI.getContext())
: ConstantInt::getTrue(BI.getContext());
// Since this is an i1 condition we can also trivially replace uses of it
// within the loop with a constant.
for (Value *Invariant : Invariants)
replaceLoopInvariantUses(L, Invariant, *Replacement);
// If this was full unswitching, we may have changed the nesting relationship
// for this loop so hoist it to its correct parent if needed.
if (FullUnswitch)
hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n");
++NumTrivial;
++NumBranches;
return true;
}
/// Unswitch a trivial switch if the condition is loop invariant.
///
/// This routine should only be called when loop code leading to the switch has
/// been validated as trivial (no side effects). This routine checks if the
/// condition is invariant and that at least one of the successors is a loop
/// exit. This allows us to unswitch without duplicating the loop, making it
/// trivial.
///
/// If this routine fails to unswitch the switch it returns false.
///
/// If the switch can be unswitched, this routine splits the preheader and
/// copies the switch above that split. If the default case is one of the
/// exiting cases, it copies the non-exiting cases and points them at the new
/// preheader. If the default case is not exiting, it copies the exiting cases
/// and points the default at the preheader. It preserves loop simplified form
/// (splitting the exit blocks as necessary). It simplifies the switch within
/// the loop by removing now-dead cases. If the default case is one of those
/// unswitched, it replaces its destination with a new basic block containing
/// only unreachable. Such basic blocks, while technically loop exits, are not
/// considered for unswitching so this is a stable transform and the same
/// switch will not be revisited. If after unswitching there is only a single
/// in-loop successor, the switch is further simplified to an unconditional
/// branch. Still more cleanup can be done with some simplifycfg like pass.
///
/// If `SE` is not null, it will be updated based on the potential loop SCEVs
/// invalidated by this.
static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
LoopInfo &LI, ScalarEvolution *SE,
MemorySSAUpdater *MSSAU) {
LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n");
Value *LoopCond = SI.getCondition();
// If this isn't switching on an invariant condition, we can't unswitch it.
if (!L.isLoopInvariant(LoopCond))
return false;
auto *ParentBB = SI.getParent();
// The same check must be used both for the default and the exit cases. We
// should never leave edges from the switch instruction to a basic block that
// we are unswitching, hence the condition used to determine the default case
// needs to also be used to populate ExitCaseIndices, which is then used to
// remove cases from the switch.
auto IsTriviallyUnswitchableExitBlock = [&](BasicBlock &BBToCheck) {
// BBToCheck is not an exit block if it is inside loop L.
if (L.contains(&BBToCheck))
return false;
// BBToCheck is not trivial to unswitch if its phis aren't loop invariant.
if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, BBToCheck))
return false;
// We do not unswitch a block that only has an unreachable statement, as
// it's possible this is a previously unswitched block. Only unswitch if
// either the terminator is not unreachable, or, if it is, it's not the only
// instruction in the block.
auto *TI = BBToCheck.getTerminator();
bool isUnreachable = isa<UnreachableInst>(TI);
return !isUnreachable ||
(isUnreachable && (BBToCheck.getFirstNonPHIOrDbg() != TI));
};
SmallVector<int, 4> ExitCaseIndices;
for (auto Case : SI.cases())
if (IsTriviallyUnswitchableExitBlock(*Case.getCaseSuccessor()))
ExitCaseIndices.push_back(Case.getCaseIndex());
BasicBlock *DefaultExitBB = nullptr;
SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight =
SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0);
if (IsTriviallyUnswitchableExitBlock(*SI.getDefaultDest())) {
DefaultExitBB = SI.getDefaultDest();
} else if (ExitCaseIndices.empty())
return false;
LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n");
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
// We may need to invalidate SCEVs for the outermost loop reached by any of
// the exits.
Loop *OuterL = &L;
if (DefaultExitBB) {
// Clear out the default destination temporarily to allow accurate
// predecessor lists to be examined below.
SI.setDefaultDest(nullptr);
// Check the loop containing this exit.
Loop *ExitL = LI.getLoopFor(DefaultExitBB);
if (!ExitL || ExitL->contains(OuterL))
OuterL = ExitL;
}
// Store the exit cases into a separate data structure and remove them from
// the switch.
SmallVector<std::tuple<ConstantInt *, BasicBlock *,
SwitchInstProfUpdateWrapper::CaseWeightOpt>,
4> ExitCases;
ExitCases.reserve(ExitCaseIndices.size());
SwitchInstProfUpdateWrapper SIW(SI);
// We walk the case indices backwards so that we remove the last case first
// and don't disrupt the earlier indices.
for (unsigned Index : reverse(ExitCaseIndices)) {
auto CaseI = SI.case_begin() + Index;
// Compute the outer loop from this exit.
Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
if (!ExitL || ExitL->contains(OuterL))
OuterL = ExitL;
// Save the value of this case.
auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex());
ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
// Delete the unswitched cases.
SIW.removeCase(CaseI);
}
if (SE) {
if (OuterL)
SE->forgetLoop(OuterL);
else
SE->forgetTopmostLoop(&L);
}
// Check if after this all of the remaining cases point at the same
// successor.
BasicBlock *CommonSuccBB = nullptr;
if (SI.getNumCases() > 0 &&
all_of(drop_begin(SI.cases()), [&SI](const SwitchInst::CaseHandle &Case) {
return Case.getCaseSuccessor() == SI.case_begin()->getCaseSuccessor();
}))
CommonSuccBB = SI.case_begin()->getCaseSuccessor();
if (!DefaultExitBB) {
// If we're not unswitching the default, we need it to match any cases to
// have a common successor or if we have no cases it is the common
// successor.
if (SI.getNumCases() == 0)
CommonSuccBB = SI.getDefaultDest();
else if (SI.getDefaultDest() != CommonSuccBB)
CommonSuccBB = nullptr;
}
// Split the preheader, so that we know that there is a safe place to insert
// the switch.
BasicBlock *OldPH = L.getLoopPreheader();
BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
OldPH->getTerminator()->eraseFromParent();
// Now add the unswitched switch.
auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
SwitchInstProfUpdateWrapper NewSIW(*NewSI);
// Rewrite the IR for the unswitched basic blocks. This requires two steps.
// First, we split any exit blocks with remaining in-loop predecessors. Then
// we update the PHIs in one of two ways depending on if there was a split.
// We walk in reverse so that we split in the same order as the cases
// appeared. This is purely for convenience of reading the resulting IR, but
// it doesn't cost anything really.
SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
// Handle the default exit if necessary.
// FIXME: It'd be great if we could merge this with the loop below but LLVM's
// ranges aren't quite powerful enough yet.
if (DefaultExitBB) {
if (pred_empty(DefaultExitBB)) {
UnswitchedExitBBs.insert(DefaultExitBB);
rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
} else {
auto *SplitBB =
SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
*ParentBB, *OldPH,
/*FullUnswitch*/ true);
DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
}
}
// Note that we must use a reference in the for loop so that we update the
// container.
for (auto &ExitCase : reverse(ExitCases)) {
// Grab a reference to the exit block in the pair so that we can update it.
BasicBlock *ExitBB = std::get<1>(ExitCase);
// If this case is the last edge into the exit block, we can simply reuse it
// as it will no longer be a loop exit. No mapping necessary.
if (pred_empty(ExitBB)) {
// Only rewrite once.
if (UnswitchedExitBBs.insert(ExitBB).second)
rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
continue;
}
// Otherwise we need to split the exit block so that we retain an exit
// block from the loop and a target for the unswitched condition.
BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
if (!SplitExitBB) {
// If this is the first time we see this, do the split and remember it.
SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
*ParentBB, *OldPH,
/*FullUnswitch*/ true);
}
// Update the case pair to point to the split block.
std::get<1>(ExitCase) = SplitExitBB;
}
// Now add the unswitched cases. We do this in reverse order as we built them
// in reverse order.
for (auto &ExitCase : reverse(ExitCases)) {
ConstantInt *CaseVal = std::get<0>(ExitCase);
BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
}
// If the default was unswitched, re-point it and add explicit cases for
// entering the loop.
if (DefaultExitBB) {
NewSIW->setDefaultDest(DefaultExitBB);
NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
// We removed all the exit cases, so we just copy the cases to the
// unswitched switch.
for (const auto &Case : SI.cases())
NewSIW.addCase(Case.getCaseValue(), NewPH,
SIW.getSuccessorWeight(Case.getSuccessorIndex()));
} else if (DefaultCaseWeight) {
// We have to set branch weight of the default case.
uint64_t SW = *DefaultCaseWeight;
for (const auto &Case : SI.cases()) {
auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex());
assert(W &&
"case weight must be defined as default case weight is defined");
SW += *W;
}
NewSIW.setSuccessorWeight(0, SW);
}
// If we ended up with a common successor for every path through the switch
// after unswitching, rewrite it to an unconditional branch to make it easy
// to recognize. Otherwise we potentially have to recognize the default case
// pointing at unreachable and other complexity.
if (CommonSuccBB) {
BasicBlock *BB = SI.getParent();
// We may have had multiple edges to this common successor block, so remove
// them as predecessors. We skip the first one, either the default or the
// actual first case.
bool SkippedFirst = DefaultExitBB == nullptr;
for (auto Case : SI.cases()) {
assert(Case.getCaseSuccessor() == CommonSuccBB &&
"Non-common successor!");
(void)Case;
if (!SkippedFirst) {
SkippedFirst = true;
continue;
}
CommonSuccBB->removePredecessor(BB,
/*KeepOneInputPHIs*/ true);
}
// Now nuke the switch and replace it with a direct branch.
SIW.eraseFromParent();
BranchInst::Create(CommonSuccBB, BB);
} else if (DefaultExitBB) {
assert(SI.getNumCases() > 0 &&
"If we had no cases we'd have a common successor!");
// Move the last case to the default successor. This is valid as if the
// default got unswitched it cannot be reached. This has the advantage of
// being simple and keeping the number of edges from this switch to
// successors the same, and avoiding any PHI update complexity.
auto LastCaseI = std::prev(SI.case_end());
SI.setDefaultDest(LastCaseI->getCaseSuccessor());
SIW.setSuccessorWeight(
0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex()));
SIW.removeCase(LastCaseI);
}
// Walk the unswitched exit blocks and the unswitched split blocks and update
// the dominator tree based on the CFG edits. While we are walking unordered
// containers here, the API for applyUpdates takes an unordered list of
// updates and requires them to not contain duplicates.
SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
}
for (auto SplitUnswitchedPair : SplitExitBBMap) {
DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
}
if (MSSAU) {
MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
if (VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
} else {
DT.applyUpdates(DTUpdates);
}
assert(DT.verify(DominatorTree::VerificationLevel::Fast));
// We may have changed the nesting relationship for this loop so hoist it to
// its correct parent if needed.
hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
++NumTrivial;
++NumSwitches;
LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n");
return true;
}
/// This routine scans the loop to find a branch or switch which occurs before
/// any side effects occur. These can potentially be unswitched without
/// duplicating the loop. If a branch or switch is successfully unswitched the
/// scanning continues to see if subsequent branches or switches have become
/// trivial. Once all trivial candidates have been unswitched, this routine
/// returns.
///
/// The return value indicates whether anything was unswitched (and therefore
/// changed).
///
/// If `SE` is not null, it will be updated based on the potential loop SCEVs
/// invalidated by this.
static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
LoopInfo &LI, ScalarEvolution *SE,
MemorySSAUpdater *MSSAU) {
bool Changed = false;
// If loop header has only one reachable successor we should keep looking for
// trivial condition candidates in the successor as well. An alternative is
// to constant fold conditions and merge successors into loop header (then we
// only need to check header's terminator). The reason for not doing this in
// LoopUnswitch pass is that it could potentially break LoopPassManager's
// invariants. Folding dead branches could either eliminate the current loop
// or make other loops unreachable. LCSSA form might also not be preserved
// after deleting branches. The following code keeps traversing loop header's
// successors until it finds the trivial condition candidate (condition that
// is not a constant). Since unswitching generates branches with constant
// conditions, this scenario could be very common in practice.
BasicBlock *CurrentBB = L.getHeader();
SmallPtrSet<BasicBlock *, 8> Visited;
Visited.insert(CurrentBB);
do {
// Check if there are any side-effecting instructions (e.g. stores, calls,
// volatile loads) in the part of the loop that the code *would* execute
// without unswitching.
if (MSSAU) // Possible early exit with MSSA
if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
return Changed;
if (llvm::any_of(*CurrentBB,
[](Instruction &I) { return I.mayHaveSideEffects(); }))
return Changed;
Instruction *CurrentTerm = CurrentBB->getTerminator();
if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
// Don't bother trying to unswitch past a switch with a constant
// condition. This should be removed prior to running this pass by
// simplifycfg.
if (isa<Constant>(SI->getCondition()))
return Changed;
if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
// Couldn't unswitch this one so we're done.
return Changed;
// Mark that we managed to unswitch something.
Changed = true;