forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathARMLowOverheadLoops.cpp
1879 lines (1647 loc) · 69.8 KB
/
ARMLowOverheadLoops.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
//===-- ARMLowOverheadLoops.cpp - CodeGen Low-overhead Loops ---*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// \file
/// Finalize v8.1-m low-overhead loops by converting the associated pseudo
/// instructions into machine operations.
/// The expectation is that the loop contains three pseudo instructions:
/// - t2*LoopStart - placed in the preheader or pre-preheader. The do-loop
/// form should be in the preheader, whereas the while form should be in the
/// preheaders only predecessor.
/// - t2LoopDec - placed within in the loop body.
/// - t2LoopEnd - the loop latch terminator.
///
/// In addition to this, we also look for the presence of the VCTP instruction,
/// which determines whether we can generated the tail-predicated low-overhead
/// loop form.
///
/// Assumptions and Dependencies:
/// Low-overhead loops are constructed and executed using a setup instruction:
/// DLS, WLS, DLSTP or WLSTP and an instruction that loops back: LE or LETP.
/// WLS(TP) and LE(TP) are branching instructions with a (large) limited range
/// but fixed polarity: WLS can only branch forwards and LE can only branch
/// backwards. These restrictions mean that this pass is dependent upon block
/// layout and block sizes, which is why it's the last pass to run. The same is
/// true for ConstantIslands, but this pass does not increase the size of the
/// basic blocks, nor does it change the CFG. Instructions are mainly removed
/// during the transform and pseudo instructions are replaced by real ones. In
/// some cases, when we have to revert to a 'normal' loop, we have to introduce
/// multiple instructions for a single pseudo (see RevertWhile and
/// RevertLoopEnd). To handle this situation, t2WhileLoopStartLR and t2LoopEnd
/// are defined to be as large as this maximum sequence of replacement
/// instructions.
///
/// A note on VPR.P0 (the lane mask):
/// VPT, VCMP, VPNOT and VCTP won't overwrite VPR.P0 when they update it in a
/// "VPT Active" context (which includes low-overhead loops and vpt blocks).
/// They will simply "and" the result of their calculation with the current
/// value of VPR.P0. You can think of it like this:
/// \verbatim
/// if VPT active: ; Between a DLSTP/LETP, or for predicated instrs
/// VPR.P0 &= Value
/// else
/// VPR.P0 = Value
/// \endverbatim
/// When we're inside the low-overhead loop (between DLSTP and LETP), we always
/// fall in the "VPT active" case, so we can consider that all VPR writes by
/// one of those instruction is actually a "and".
//===----------------------------------------------------------------------===//
#include "ARM.h"
#include "ARMBaseInstrInfo.h"
#include "ARMBaseRegisterInfo.h"
#include "ARMBasicBlockInfo.h"
#include "ARMSubtarget.h"
#include "MVETailPredUtils.h"
#include "Thumb2InstrInfo.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/CodeGen/LivePhysRegs.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineLoopUtils.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/ReachingDefAnalysis.h"
#include "llvm/MC/MCInstrDesc.h"
using namespace llvm;
#define DEBUG_TYPE "arm-low-overhead-loops"
#define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
static cl::opt<bool>
DisableTailPredication("arm-loloops-disable-tailpred", cl::Hidden,
cl::desc("Disable tail-predication in the ARM LowOverheadLoop pass"),
cl::init(false));
static bool isVectorPredicated(MachineInstr *MI) {
int PIdx = llvm::findFirstVPTPredOperandIdx(*MI);
return PIdx != -1 && MI->getOperand(PIdx + 1).getReg() == ARM::VPR;
}
static bool isVectorPredicate(MachineInstr *MI) {
return MI->findRegisterDefOperandIdx(ARM::VPR) != -1;
}
static bool hasVPRUse(MachineInstr &MI) {
return MI.findRegisterUseOperandIdx(ARM::VPR) != -1;
}
static bool isDomainMVE(MachineInstr *MI) {
uint64_t Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
return Domain == ARMII::DomainMVE;
}
static int getVecSize(const MachineInstr &MI) {
const MCInstrDesc &MCID = MI.getDesc();
uint64_t Flags = MCID.TSFlags;
return (Flags & ARMII::VecSize) >> ARMII::VecSizeShift;
}
static bool shouldInspect(MachineInstr &MI) {
if (MI.isDebugInstr())
return false;
return isDomainMVE(&MI) || isVectorPredicate(&MI) || hasVPRUse(MI);
}
namespace {
using InstSet = SmallPtrSetImpl<MachineInstr *>;
class PostOrderLoopTraversal {
MachineLoop &ML;
MachineLoopInfo &MLI;
SmallPtrSet<MachineBasicBlock*, 4> Visited;
SmallVector<MachineBasicBlock*, 4> Order;
public:
PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI)
: ML(ML), MLI(MLI) { }
const SmallVectorImpl<MachineBasicBlock*> &getOrder() const {
return Order;
}
// Visit all the blocks within the loop, as well as exit blocks and any
// blocks properly dominating the header.
void ProcessLoop() {
std::function<void(MachineBasicBlock*)> Search = [this, &Search]
(MachineBasicBlock *MBB) -> void {
if (Visited.count(MBB))
return;
Visited.insert(MBB);
for (auto *Succ : MBB->successors()) {
if (!ML.contains(Succ))
continue;
Search(Succ);
}
Order.push_back(MBB);
};
// Insert exit blocks.
SmallVector<MachineBasicBlock*, 2> ExitBlocks;
ML.getExitBlocks(ExitBlocks);
append_range(Order, ExitBlocks);
// Then add the loop body.
Search(ML.getHeader());
// Then try the preheader and its predecessors.
std::function<void(MachineBasicBlock*)> GetPredecessor =
[this, &GetPredecessor] (MachineBasicBlock *MBB) -> void {
Order.push_back(MBB);
if (MBB->pred_size() == 1)
GetPredecessor(*MBB->pred_begin());
};
if (auto *Preheader = ML.getLoopPreheader())
GetPredecessor(Preheader);
else if (auto *Preheader = MLI.findLoopPreheader(&ML, true, true))
GetPredecessor(Preheader);
}
};
struct PredicatedMI {
MachineInstr *MI = nullptr;
SetVector<MachineInstr*> Predicates;
public:
PredicatedMI(MachineInstr *I, SetVector<MachineInstr *> &Preds) : MI(I) {
assert(I && "Instruction must not be null!");
Predicates.insert(Preds.begin(), Preds.end());
}
};
// Represent the current state of the VPR and hold all instances which
// represent a VPT block, which is a list of instructions that begins with a
// VPT/VPST and has a maximum of four proceeding instructions. All
// instructions within the block are predicated upon the vpr and we allow
// instructions to define the vpr within in the block too.
class VPTState {
friend struct LowOverheadLoop;
SmallVector<MachineInstr *, 4> Insts;
static SmallVector<VPTState, 4> Blocks;
static SetVector<MachineInstr *> CurrentPredicates;
static std::map<MachineInstr *,
std::unique_ptr<PredicatedMI>> PredicatedInsts;
static void CreateVPTBlock(MachineInstr *MI) {
assert((CurrentPredicates.size() || MI->getParent()->isLiveIn(ARM::VPR))
&& "Can't begin VPT without predicate");
Blocks.emplace_back(MI);
// The execution of MI is predicated upon the current set of instructions
// that are AND'ed together to form the VPR predicate value. In the case
// that MI is a VPT, CurrentPredicates will also just be MI.
PredicatedInsts.emplace(
MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates));
}
static void reset() {
Blocks.clear();
PredicatedInsts.clear();
CurrentPredicates.clear();
}
static void addInst(MachineInstr *MI) {
Blocks.back().insert(MI);
PredicatedInsts.emplace(
MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates));
}
static void addPredicate(MachineInstr *MI) {
LLVM_DEBUG(dbgs() << "ARM Loops: Adding VPT Predicate: " << *MI);
CurrentPredicates.insert(MI);
}
static void resetPredicate(MachineInstr *MI) {
LLVM_DEBUG(dbgs() << "ARM Loops: Resetting VPT Predicate: " << *MI);
CurrentPredicates.clear();
CurrentPredicates.insert(MI);
}
public:
// Have we found an instruction within the block which defines the vpr? If
// so, not all the instructions in the block will have the same predicate.
static bool hasUniformPredicate(VPTState &Block) {
return getDivergent(Block) == nullptr;
}
// If it exists, return the first internal instruction which modifies the
// VPR.
static MachineInstr *getDivergent(VPTState &Block) {
SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
for (unsigned i = 1; i < Insts.size(); ++i) {
MachineInstr *Next = Insts[i];
if (isVectorPredicate(Next))
return Next; // Found an instruction altering the vpr.
}
return nullptr;
}
// Return whether the given instruction is predicated upon a VCTP.
static bool isPredicatedOnVCTP(MachineInstr *MI, bool Exclusive = false) {
SetVector<MachineInstr *> &Predicates = PredicatedInsts[MI]->Predicates;
if (Exclusive && Predicates.size() != 1)
return false;
return llvm::any_of(Predicates, isVCTP);
}
// Is the VPST, controlling the block entry, predicated upon a VCTP.
static bool isEntryPredicatedOnVCTP(VPTState &Block,
bool Exclusive = false) {
SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
return isPredicatedOnVCTP(Insts.front(), Exclusive);
}
// If this block begins with a VPT, we can check whether it's using
// at least one predicated input(s), as well as possible loop invariant
// which would result in it being implicitly predicated.
static bool hasImplicitlyValidVPT(VPTState &Block,
ReachingDefAnalysis &RDA) {
SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
MachineInstr *VPT = Insts.front();
assert(isVPTOpcode(VPT->getOpcode()) &&
"Expected VPT block to begin with VPT/VPST");
if (VPT->getOpcode() == ARM::MVE_VPST)
return false;
auto IsOperandPredicated = [&](MachineInstr *MI, unsigned Idx) {
MachineInstr *Op = RDA.getMIOperand(MI, MI->getOperand(Idx));
return Op && PredicatedInsts.count(Op) && isPredicatedOnVCTP(Op);
};
auto IsOperandInvariant = [&](MachineInstr *MI, unsigned Idx) {
MachineOperand &MO = MI->getOperand(Idx);
if (!MO.isReg() || !MO.getReg())
return true;
SmallPtrSet<MachineInstr *, 2> Defs;
RDA.getGlobalReachingDefs(MI, MO.getReg(), Defs);
if (Defs.empty())
return true;
for (auto *Def : Defs)
if (Def->getParent() == VPT->getParent())
return false;
return true;
};
// Check that at least one of the operands is directly predicated on a
// vctp and allow an invariant value too.
return (IsOperandPredicated(VPT, 1) || IsOperandPredicated(VPT, 2)) &&
(IsOperandPredicated(VPT, 1) || IsOperandInvariant(VPT, 1)) &&
(IsOperandPredicated(VPT, 2) || IsOperandInvariant(VPT, 2));
}
static bool isValid(ReachingDefAnalysis &RDA) {
// All predication within the loop should be based on vctp. If the block
// isn't predicated on entry, check whether the vctp is within the block
// and that all other instructions are then predicated on it.
for (auto &Block : Blocks) {
if (isEntryPredicatedOnVCTP(Block, false) ||
hasImplicitlyValidVPT(Block, RDA))
continue;
SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
// We don't know how to convert a block with just a VPT;VCTP into
// anything valid once we remove the VCTP. For now just bail out.
assert(isVPTOpcode(Insts.front()->getOpcode()) &&
"Expected VPT block to start with a VPST or VPT!");
if (Insts.size() == 2 && Insts.front()->getOpcode() != ARM::MVE_VPST &&
isVCTP(Insts.back()))
return false;
for (auto *MI : Insts) {
// Check that any internal VCTPs are 'Then' predicated.
if (isVCTP(MI) && getVPTInstrPredicate(*MI) != ARMVCC::Then)
return false;
// Skip other instructions that build up the predicate.
if (MI->getOpcode() == ARM::MVE_VPST || isVectorPredicate(MI))
continue;
// Check that any other instructions are predicated upon a vctp.
// TODO: We could infer when VPTs are implicitly predicated on the
// vctp (when the operands are predicated).
if (!isPredicatedOnVCTP(MI)) {
LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *MI);
return false;
}
}
}
return true;
}
VPTState(MachineInstr *MI) { Insts.push_back(MI); }
void insert(MachineInstr *MI) {
Insts.push_back(MI);
// VPT/VPST + 4 predicated instructions.
assert(Insts.size() <= 5 && "Too many instructions in VPT block!");
}
bool containsVCTP() const {
return llvm::any_of(Insts, isVCTP);
}
unsigned size() const { return Insts.size(); }
SmallVectorImpl<MachineInstr *> &getInsts() { return Insts; }
};
struct LowOverheadLoop {
MachineLoop &ML;
MachineBasicBlock *Preheader = nullptr;
MachineLoopInfo &MLI;
ReachingDefAnalysis &RDA;
const TargetRegisterInfo &TRI;
const ARMBaseInstrInfo &TII;
MachineFunction *MF = nullptr;
MachineBasicBlock::iterator StartInsertPt;
MachineBasicBlock *StartInsertBB = nullptr;
MachineInstr *Start = nullptr;
MachineInstr *Dec = nullptr;
MachineInstr *End = nullptr;
MachineOperand TPNumElements;
SmallVector<MachineInstr *, 4> VCTPs;
SmallPtrSet<MachineInstr *, 4> ToRemove;
SmallPtrSet<MachineInstr *, 4> BlockMasksToRecompute;
SmallPtrSet<MachineInstr *, 4> DoubleWidthResultInstrs;
SmallPtrSet<MachineInstr *, 4> VMOVCopies;
bool Revert = false;
bool CannotTailPredicate = false;
LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI,
ReachingDefAnalysis &RDA, const TargetRegisterInfo &TRI,
const ARMBaseInstrInfo &TII)
: ML(ML), MLI(MLI), RDA(RDA), TRI(TRI), TII(TII),
TPNumElements(MachineOperand::CreateImm(0)) {
MF = ML.getHeader()->getParent();
if (auto *MBB = ML.getLoopPreheader())
Preheader = MBB;
else if (auto *MBB = MLI.findLoopPreheader(&ML, true, true))
Preheader = MBB;
VPTState::reset();
}
// If this is an MVE instruction, check that we know how to use tail
// predication with it. Record VPT blocks and return whether the
// instruction is valid for tail predication.
bool ValidateMVEInst(MachineInstr *MI);
void AnalyseMVEInst(MachineInstr *MI) {
CannotTailPredicate = !ValidateMVEInst(MI);
}
bool IsTailPredicationLegal() const {
// For now, let's keep things really simple and only support a single
// block for tail predication.
return !Revert && FoundAllComponents() && !VCTPs.empty() &&
!CannotTailPredicate && ML.getNumBlocks() == 1;
}
// Given that MI is a VCTP, check that is equivalent to any other VCTPs
// found.
bool AddVCTP(MachineInstr *MI);
// Check that the predication in the loop will be equivalent once we
// perform the conversion. Also ensure that we can provide the number
// of elements to the loop start instruction.
bool ValidateTailPredicate();
// Check that any values available outside of the loop will be the same
// after tail predication conversion.
bool ValidateLiveOuts();
// Is it safe to define LR with DLS/WLS?
// LR can be defined if it is the operand to start, because it's the same
// value, or if it's going to be equivalent to the operand to Start.
MachineInstr *isSafeToDefineLR();
// Check the branch targets are within range and we satisfy our
// restrictions.
void Validate(ARMBasicBlockUtils *BBUtils);
bool FoundAllComponents() const {
return Start && Dec && End;
}
SmallVectorImpl<VPTState> &getVPTBlocks() {
return VPTState::Blocks;
}
// Return the operand for the loop start instruction. This will be the loop
// iteration count, or the number of elements if we're tail predicating.
MachineOperand &getLoopStartOperand() {
if (IsTailPredicationLegal())
return TPNumElements;
return Start->getOperand(1);
}
unsigned getStartOpcode() const {
bool IsDo = isDoLoopStart(*Start);
if (!IsTailPredicationLegal())
return IsDo ? ARM::t2DLS : ARM::t2WLS;
return VCTPOpcodeToLSTP(VCTPs.back()->getOpcode(), IsDo);
}
void dump() const {
if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start;
if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec;
if (End) dbgs() << "ARM Loops: Found Loop End: " << *End;
if (!VCTPs.empty()) {
dbgs() << "ARM Loops: Found VCTP(s):\n";
for (auto *MI : VCTPs)
dbgs() << " - " << *MI;
}
if (!FoundAllComponents())
dbgs() << "ARM Loops: Not a low-overhead loop.\n";
else if (!(Start && Dec && End))
dbgs() << "ARM Loops: Failed to find all loop components.\n";
}
};
class ARMLowOverheadLoops : public MachineFunctionPass {
MachineFunction *MF = nullptr;
MachineLoopInfo *MLI = nullptr;
ReachingDefAnalysis *RDA = nullptr;
const ARMBaseInstrInfo *TII = nullptr;
MachineRegisterInfo *MRI = nullptr;
const TargetRegisterInfo *TRI = nullptr;
std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
public:
static char ID;
ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
AU.addRequired<MachineLoopInfo>();
AU.addRequired<ReachingDefAnalysis>();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override;
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::NoVRegs).set(
MachineFunctionProperties::Property::TracksLiveness);
}
StringRef getPassName() const override {
return ARM_LOW_OVERHEAD_LOOPS_NAME;
}
private:
bool ProcessLoop(MachineLoop *ML);
bool RevertNonLoops();
void RevertWhile(MachineInstr *MI) const;
void RevertDo(MachineInstr *MI) const;
bool RevertLoopDec(MachineInstr *MI) const;
void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const;
void RevertLoopEndDec(MachineInstr *MI) const;
void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
void Expand(LowOverheadLoop &LoLoop);
void IterationCountDCE(LowOverheadLoop &LoLoop);
};
}
char ARMLowOverheadLoops::ID = 0;
SmallVector<VPTState, 4> VPTState::Blocks;
SetVector<MachineInstr *> VPTState::CurrentPredicates;
std::map<MachineInstr *,
std::unique_ptr<PredicatedMI>> VPTState::PredicatedInsts;
INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME,
false, false)
static bool TryRemove(MachineInstr *MI, ReachingDefAnalysis &RDA,
InstSet &ToRemove, InstSet &Ignore) {
// Check that we can remove all of Killed without having to modify any IT
// blocks.
auto WontCorruptITs = [](InstSet &Killed, ReachingDefAnalysis &RDA) {
// Collect the dead code and the MBBs in which they reside.
SmallPtrSet<MachineBasicBlock*, 2> BasicBlocks;
for (auto *Dead : Killed)
BasicBlocks.insert(Dead->getParent());
// Collect IT blocks in all affected basic blocks.
std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks;
for (auto *MBB : BasicBlocks) {
for (auto &IT : *MBB) {
if (IT.getOpcode() != ARM::t2IT)
continue;
RDA.getReachingLocalUses(&IT, MCRegister::from(ARM::ITSTATE),
ITBlocks[&IT]);
}
}
// If we're removing all of the instructions within an IT block, then
// also remove the IT instruction.
SmallPtrSet<MachineInstr *, 2> ModifiedITs;
SmallPtrSet<MachineInstr *, 2> RemoveITs;
for (auto *Dead : Killed) {
if (MachineOperand *MO = Dead->findRegisterUseOperand(ARM::ITSTATE)) {
MachineInstr *IT = RDA.getMIOperand(Dead, *MO);
RemoveITs.insert(IT);
auto &CurrentBlock = ITBlocks[IT];
CurrentBlock.erase(Dead);
if (CurrentBlock.empty())
ModifiedITs.erase(IT);
else
ModifiedITs.insert(IT);
}
}
if (!ModifiedITs.empty())
return false;
Killed.insert(RemoveITs.begin(), RemoveITs.end());
return true;
};
SmallPtrSet<MachineInstr *, 2> Uses;
if (!RDA.isSafeToRemove(MI, Uses, Ignore))
return false;
if (WontCorruptITs(Uses, RDA)) {
ToRemove.insert(Uses.begin(), Uses.end());
LLVM_DEBUG(dbgs() << "ARM Loops: Able to remove: " << *MI
<< " - can also remove:\n";
for (auto *Use : Uses)
dbgs() << " - " << *Use);
SmallPtrSet<MachineInstr*, 4> Killed;
RDA.collectKilledOperands(MI, Killed);
if (WontCorruptITs(Killed, RDA)) {
ToRemove.insert(Killed.begin(), Killed.end());
LLVM_DEBUG(for (auto *Dead : Killed)
dbgs() << " - " << *Dead);
}
return true;
}
return false;
}
bool LowOverheadLoop::ValidateTailPredicate() {
if (!IsTailPredicationLegal()) {
LLVM_DEBUG(if (VCTPs.empty())
dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
dbgs() << "ARM Loops: Tail-predication is not valid.\n");
return false;
}
assert(!VCTPs.empty() && "VCTP instruction expected but is not set");
assert(ML.getBlocks().size() == 1 &&
"Shouldn't be processing a loop with more than one block");
if (DisableTailPredication) {
LLVM_DEBUG(dbgs() << "ARM Loops: tail-predication is disabled\n");
return false;
}
if (!VPTState::isValid(RDA)) {
LLVM_DEBUG(dbgs() << "ARM Loops: Invalid VPT state.\n");
return false;
}
if (!ValidateLiveOuts()) {
LLVM_DEBUG(dbgs() << "ARM Loops: Invalid live outs.\n");
return false;
}
// For tail predication, we need to provide the number of elements, instead
// of the iteration count, to the loop start instruction. The number of
// elements is provided to the vctp instruction, so we need to check that
// we can use this register at InsertPt.
MachineInstr *VCTP = VCTPs.back();
if (Start->getOpcode() == ARM::t2DoLoopStartTP ||
Start->getOpcode() == ARM::t2WhileLoopStartTP) {
TPNumElements = Start->getOperand(2);
StartInsertPt = Start;
StartInsertBB = Start->getParent();
} else {
TPNumElements = VCTP->getOperand(1);
MCRegister NumElements = TPNumElements.getReg().asMCReg();
// If the register is defined within loop, then we can't perform TP.
// TODO: Check whether this is just a mov of a register that would be
// available.
if (RDA.hasLocalDefBefore(VCTP, NumElements)) {
LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
return false;
}
// The element count register maybe defined after InsertPt, in which case we
// need to try to move either InsertPt or the def so that the [w|d]lstp can
// use the value.
if (StartInsertPt != StartInsertBB->end() &&
!RDA.isReachingDefLiveOut(&*StartInsertPt, NumElements)) {
if (auto *ElemDef =
RDA.getLocalLiveOutMIDef(StartInsertBB, NumElements)) {
if (RDA.isSafeToMoveForwards(ElemDef, &*StartInsertPt)) {
ElemDef->removeFromParent();
StartInsertBB->insert(StartInsertPt, ElemDef);
LLVM_DEBUG(dbgs()
<< "ARM Loops: Moved element count def: " << *ElemDef);
} else if (RDA.isSafeToMoveBackwards(&*StartInsertPt, ElemDef)) {
StartInsertPt->removeFromParent();
StartInsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef),
&*StartInsertPt);
LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef);
} else {
// If we fail to move an instruction and the element count is provided
// by a mov, use the mov operand if it will have the same value at the
// insertion point
MachineOperand Operand = ElemDef->getOperand(1);
if (isMovRegOpcode(ElemDef->getOpcode()) &&
RDA.getUniqueReachingMIDef(ElemDef, Operand.getReg().asMCReg()) ==
RDA.getUniqueReachingMIDef(&*StartInsertPt,
Operand.getReg().asMCReg())) {
TPNumElements = Operand;
NumElements = TPNumElements.getReg();
} else {
LLVM_DEBUG(dbgs()
<< "ARM Loops: Unable to move element count to loop "
<< "start instruction.\n");
return false;
}
}
}
}
// Especially in the case of while loops, InsertBB may not be the
// preheader, so we need to check that the register isn't redefined
// before entering the loop.
auto CannotProvideElements = [this](MachineBasicBlock *MBB,
MCRegister NumElements) {
if (MBB->empty())
return false;
// NumElements is redefined in this block.
if (RDA.hasLocalDefBefore(&MBB->back(), NumElements))
return true;
// Don't continue searching up through multiple predecessors.
if (MBB->pred_size() > 1)
return true;
return false;
};
// Search backwards for a def, until we get to InsertBB.
MachineBasicBlock *MBB = Preheader;
while (MBB && MBB != StartInsertBB) {
if (CannotProvideElements(MBB, NumElements)) {
LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
return false;
}
MBB = *MBB->pred_begin();
}
}
// Could inserting the [W|D]LSTP cause some unintended affects? In a perfect
// world the [w|d]lstp instruction would be last instruction in the preheader
// and so it would only affect instructions within the loop body. But due to
// scheduling, and/or the logic in this pass (above), the insertion point can
// be moved earlier. So if the Loop Start isn't the last instruction in the
// preheader, and if the initial element count is smaller than the vector
// width, the Loop Start instruction will immediately generate one or more
// false lane mask which can, incorrectly, affect the proceeding MVE
// instructions in the preheader.
if (std::any_of(StartInsertPt, StartInsertBB->end(), shouldInspect)) {
LLVM_DEBUG(dbgs() << "ARM Loops: Instruction blocks [W|D]LSTP\n");
return false;
}
// For any DoubleWidthResultInstrs we found whilst scanning instructions, they
// need to compute an output size that is smaller than the VCTP mask operates
// on. The VecSize of the DoubleWidthResult is the larger vector size - the
// size it extends into, so any VCTP VecSize <= is valid.
unsigned VCTPVecSize = getVecSize(*VCTP);
for (MachineInstr *MI : DoubleWidthResultInstrs) {
unsigned InstrVecSize = getVecSize(*MI);
if (InstrVecSize > VCTPVecSize) {
LLVM_DEBUG(dbgs() << "ARM Loops: Double width result larger than VCTP "
<< "VecSize:\n" << *MI);
return false;
}
}
// Check that the value change of the element count is what we expect and
// that the predication will be equivalent. For this we need:
// NumElements = NumElements - VectorWidth. The sub will be a sub immediate
// and we can also allow register copies within the chain too.
auto IsValidSub = [](MachineInstr *MI, int ExpectedVecWidth) {
return -getAddSubImmediate(*MI) == ExpectedVecWidth;
};
MachineBasicBlock *MBB = VCTP->getParent();
// Remove modifications to the element count since they have no purpose in a
// tail predicated loop. Explicitly refer to the vctp operand no matter which
// register NumElements has been assigned to, since that is what the
// modifications will be using
if (auto *Def = RDA.getUniqueReachingMIDef(
&MBB->back(), VCTP->getOperand(1).getReg().asMCReg())) {
SmallPtrSet<MachineInstr*, 2> ElementChain;
SmallPtrSet<MachineInstr*, 2> Ignore;
unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode());
Ignore.insert(VCTPs.begin(), VCTPs.end());
if (TryRemove(Def, RDA, ElementChain, Ignore)) {
bool FoundSub = false;
for (auto *MI : ElementChain) {
if (isMovRegOpcode(MI->getOpcode()))
continue;
if (isSubImmOpcode(MI->getOpcode())) {
if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth)) {
LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
" count: " << *MI);
return false;
}
FoundSub = true;
} else {
LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
" count: " << *MI);
return false;
}
}
ToRemove.insert(ElementChain.begin(), ElementChain.end());
}
}
// If we converted the LoopStart to a t2DoLoopStartTP/t2WhileLoopStartTP, we
// can also remove any extra instructions in the preheader, which often
// includes a now unused MOV.
if ((Start->getOpcode() == ARM::t2DoLoopStartTP ||
Start->getOpcode() == ARM::t2WhileLoopStartTP) &&
Preheader && !Preheader->empty() &&
!RDA.hasLocalDefBefore(VCTP, VCTP->getOperand(1).getReg())) {
if (auto *Def = RDA.getUniqueReachingMIDef(
&Preheader->back(), VCTP->getOperand(1).getReg().asMCReg())) {
SmallPtrSet<MachineInstr*, 2> Ignore;
Ignore.insert(VCTPs.begin(), VCTPs.end());
TryRemove(Def, RDA, ToRemove, Ignore);
}
}
return true;
}
static bool isRegInClass(const MachineOperand &MO,
const TargetRegisterClass *Class) {
return MO.isReg() && MO.getReg() && Class->contains(MO.getReg());
}
// MVE 'narrowing' operate on half a lane, reading from half and writing
// to half, which are referred to has the top and bottom half. The other
// half retains its previous value.
static bool retainsPreviousHalfElement(const MachineInstr &MI) {
const MCInstrDesc &MCID = MI.getDesc();
uint64_t Flags = MCID.TSFlags;
return (Flags & ARMII::RetainsPreviousHalfElement) != 0;
}
// Some MVE instructions read from the top/bottom halves of their operand(s)
// and generate a vector result with result elements that are double the
// width of the input.
static bool producesDoubleWidthResult(const MachineInstr &MI) {
const MCInstrDesc &MCID = MI.getDesc();
uint64_t Flags = MCID.TSFlags;
return (Flags & ARMII::DoubleWidthResult) != 0;
}
static bool isHorizontalReduction(const MachineInstr &MI) {
const MCInstrDesc &MCID = MI.getDesc();
uint64_t Flags = MCID.TSFlags;
return (Flags & ARMII::HorizontalReduction) != 0;
}
// Can this instruction generate a non-zero result when given only zeroed
// operands? This allows us to know that, given operands with false bytes
// zeroed by masked loads, that the result will also contain zeros in those
// bytes.
static bool canGenerateNonZeros(const MachineInstr &MI) {
// Check for instructions which can write into a larger element size,
// possibly writing into a previous zero'd lane.
if (producesDoubleWidthResult(MI))
return true;
switch (MI.getOpcode()) {
default:
break;
// FIXME: VNEG FP and -0? I think we'll need to handle this once we allow
// fp16 -> fp32 vector conversions.
// Instructions that perform a NOT will generate 1s from 0s.
case ARM::MVE_VMVN:
case ARM::MVE_VORN:
// Count leading zeros will do just that!
case ARM::MVE_VCLZs8:
case ARM::MVE_VCLZs16:
case ARM::MVE_VCLZs32:
return true;
}
return false;
}
// Look at its register uses to see if it only can only receive zeros
// into its false lanes which would then produce zeros. Also check that
// the output register is also defined by an FalseLanesZero instruction
// so that if tail-predication happens, the lanes that aren't updated will
// still be zeros.
static bool producesFalseLanesZero(MachineInstr &MI,
const TargetRegisterClass *QPRs,
const ReachingDefAnalysis &RDA,
InstSet &FalseLanesZero) {
if (canGenerateNonZeros(MI))
return false;
bool isPredicated = isVectorPredicated(&MI);
// Predicated loads will write zeros to the falsely predicated bytes of the
// destination register.
if (MI.mayLoad())
return isPredicated;
auto IsZeroInit = [](MachineInstr *Def) {
return !isVectorPredicated(Def) &&
Def->getOpcode() == ARM::MVE_VMOVimmi32 &&
Def->getOperand(1).getImm() == 0;
};
bool AllowScalars = isHorizontalReduction(MI);
for (auto &MO : MI.operands()) {
if (!MO.isReg() || !MO.getReg())
continue;
if (!isRegInClass(MO, QPRs) && AllowScalars)
continue;
// Skip the lr predicate reg
int PIdx = llvm::findFirstVPTPredOperandIdx(MI);
if (PIdx != -1 && (int)MI.getOperandNo(&MO) == PIdx + 2)
continue;
// Check that this instruction will produce zeros in its false lanes:
// - If it only consumes false lanes zero or constant 0 (vmov #0)
// - If it's predicated, it only matters that it's def register already has
// false lane zeros, so we can ignore the uses.
SmallPtrSet<MachineInstr *, 2> Defs;
RDA.getGlobalReachingDefs(&MI, MO.getReg(), Defs);
for (auto *Def : Defs) {
if (Def == &MI || FalseLanesZero.count(Def) || IsZeroInit(Def))
continue;
if (MO.isUse() && isPredicated)
continue;
return false;
}
}
LLVM_DEBUG(dbgs() << "ARM Loops: Always False Zeros: " << MI);
return true;
}
bool LowOverheadLoop::ValidateLiveOuts() {
// We want to find out if the tail-predicated version of this loop will
// produce the same values as the loop in its original form. For this to
// be true, the newly inserted implicit predication must not change the
// the (observable) results.
// We're doing this because many instructions in the loop will not be
// predicated and so the conversion from VPT predication to tail-predication
// can result in different values being produced; due to the tail-predication
// preventing many instructions from updating their falsely predicated
// lanes. This analysis assumes that all the instructions perform lane-wise
// operations and don't perform any exchanges.
// A masked load, whether through VPT or tail predication, will write zeros
// to any of the falsely predicated bytes. So, from the loads, we know that
// the false lanes are zeroed and here we're trying to track that those false
// lanes remain zero, or where they change, the differences are masked away
// by their user(s).
// All MVE stores have to be predicated, so we know that any predicate load
// operands, or stored results are equivalent already. Other explicitly
// predicated instructions will perform the same operation in the original
// loop and the tail-predicated form too. Because of this, we can insert
// loads, stores and other predicated instructions into our Predicated
// set and build from there.
const TargetRegisterClass *QPRs = TRI.getRegClass(ARM::MQPRRegClassID);
SetVector<MachineInstr *> FalseLanesUnknown;
SmallPtrSet<MachineInstr *, 4> FalseLanesZero;
SmallPtrSet<MachineInstr *, 4> Predicated;
MachineBasicBlock *Header = ML.getHeader();
LLVM_DEBUG(dbgs() << "ARM Loops: Validating Live outs\n");
for (auto &MI : *Header) {
if (!shouldInspect(MI))
continue;
if (isVCTP(&MI) || isVPTOpcode(MI.getOpcode()))
continue;
bool isPredicated = isVectorPredicated(&MI);
bool retainsOrReduces =
retainsPreviousHalfElement(MI) || isHorizontalReduction(MI);
if (isPredicated)
Predicated.insert(&MI);
if (producesFalseLanesZero(MI, QPRs, RDA, FalseLanesZero))
FalseLanesZero.insert(&MI);
else if (MI.getNumDefs() == 0)
continue;
else if (!isPredicated && retainsOrReduces) {
LLVM_DEBUG(dbgs() << " Unpredicated instruction that retainsOrReduces: " << MI);
return false;
} else if (!isPredicated && MI.getOpcode() != ARM::MQPRCopy)
FalseLanesUnknown.insert(&MI);
}
LLVM_DEBUG({
dbgs() << " Predicated:\n";
for (auto *I : Predicated)
dbgs() << " " << *I;
dbgs() << " FalseLanesZero:\n";
for (auto *I : FalseLanesZero)
dbgs() << " " << *I;
dbgs() << " FalseLanesUnknown:\n";
for (auto *I : FalseLanesUnknown)
dbgs() << " " << *I;
});
auto HasPredicatedUsers = [this](MachineInstr *MI, const MachineOperand &MO,
SmallPtrSetImpl<MachineInstr *> &Predicated) {
SmallPtrSet<MachineInstr *, 2> Uses;
RDA.getGlobalUses(MI, MO.getReg().asMCReg(), Uses);
for (auto *Use : Uses) {
if (Use != MI && !Predicated.count(Use))
return false;
}
return true;
};