1 //===-- ARMLowOverheadLoops.cpp - CodeGen Low-overhead Loops ---*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 /// Finalize v8.1-m low-overhead loops by converting the associated pseudo
10 /// instructions into machine operations.
11 /// The expectation is that the loop contains three pseudo instructions:
12 /// - t2*LoopStart - placed in the preheader or pre-preheader. The do-loop
13 /// form should be in the preheader, whereas the while form should be in the
14 /// preheaders only predecessor.
15 /// - t2LoopDec - placed within in the loop body.
16 /// - t2LoopEnd - the loop latch terminator.
18 /// In addition to this, we also look for the presence of the VCTP instruction,
19 /// which determines whether we can generated the tail-predicated low-overhead
22 /// Assumptions and Dependencies:
23 /// Low-overhead loops are constructed and executed using a setup instruction:
24 /// DLS, WLS, DLSTP or WLSTP and an instruction that loops back: LE or LETP.
25 /// WLS(TP) and LE(TP) are branching instructions with a (large) limited range
26 /// but fixed polarity: WLS can only branch forwards and LE can only branch
27 /// backwards. These restrictions mean that this pass is dependent upon block
28 /// layout and block sizes, which is why it's the last pass to run. The same is
29 /// true for ConstantIslands, but this pass does not increase the size of the
30 /// basic blocks, nor does it change the CFG. Instructions are mainly removed
31 /// during the transform and pseudo instructions are replaced by real ones. In
32 /// some cases, when we have to revert to a 'normal' loop, we have to introduce
33 /// multiple instructions for a single pseudo (see RevertWhile and
34 /// RevertLoopEnd). To handle this situation, t2WhileLoopStartLR and t2LoopEnd
35 /// are defined to be as large as this maximum sequence of replacement
38 /// A note on VPR.P0 (the lane mask):
39 /// VPT, VCMP, VPNOT and VCTP won't overwrite VPR.P0 when they update it in a
40 /// "VPT Active" context (which includes low-overhead loops and vpt blocks).
41 /// They will simply "and" the result of their calculation with the current
42 /// value of VPR.P0. You can think of it like this:
44 /// if VPT active: ; Between a DLSTP/LETP, or for predicated instrs
49 /// When we're inside the low-overhead loop (between DLSTP and LETP), we always
50 /// fall in the "VPT active" case, so we can consider that all VPR writes by
51 /// one of those instruction is actually a "and".
52 //===----------------------------------------------------------------------===//
55 #include "ARMBaseInstrInfo.h"
56 #include "ARMBaseRegisterInfo.h"
57 #include "ARMBasicBlockInfo.h"
58 #include "ARMSubtarget.h"
59 #include "MVETailPredUtils.h"
60 #include "Thumb2InstrInfo.h"
61 #include "llvm/ADT/SetOperations.h"
62 #include "llvm/ADT/SmallSet.h"
63 #include "llvm/CodeGen/LivePhysRegs.h"
64 #include "llvm/CodeGen/MachineFunctionPass.h"
65 #include "llvm/CodeGen/MachineLoopInfo.h"
66 #include "llvm/CodeGen/MachineLoopUtils.h"
67 #include "llvm/CodeGen/MachineRegisterInfo.h"
68 #include "llvm/CodeGen/Passes.h"
69 #include "llvm/CodeGen/ReachingDefAnalysis.h"
70 #include "llvm/MC/MCInstrDesc.h"
74 #define DEBUG_TYPE "arm-low-overhead-loops"
75 #define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
78 DisableTailPredication("arm-loloops-disable-tailpred", cl::Hidden
,
79 cl::desc("Disable tail-predication in the ARM LowOverheadLoop pass"),
82 static bool isVectorPredicated(MachineInstr
*MI
) {
83 int PIdx
= llvm::findFirstVPTPredOperandIdx(*MI
);
84 return PIdx
!= -1 && MI
->getOperand(PIdx
+ 1).getReg() == ARM::VPR
;
87 static bool isVectorPredicate(MachineInstr
*MI
) {
88 return MI
->findRegisterDefOperandIdx(ARM::VPR
) != -1;
91 static bool hasVPRUse(MachineInstr
&MI
) {
92 return MI
.findRegisterUseOperandIdx(ARM::VPR
) != -1;
95 static bool isDomainMVE(MachineInstr
*MI
) {
96 uint64_t Domain
= MI
->getDesc().TSFlags
& ARMII::DomainMask
;
97 return Domain
== ARMII::DomainMVE
;
100 static bool shouldInspect(MachineInstr
&MI
) {
101 return isDomainMVE(&MI
) || isVectorPredicate(&MI
) || hasVPRUse(MI
);
106 using InstSet
= SmallPtrSetImpl
<MachineInstr
*>;
108 class PostOrderLoopTraversal
{
110 MachineLoopInfo
&MLI
;
111 SmallPtrSet
<MachineBasicBlock
*, 4> Visited
;
112 SmallVector
<MachineBasicBlock
*, 4> Order
;
115 PostOrderLoopTraversal(MachineLoop
&ML
, MachineLoopInfo
&MLI
)
116 : ML(ML
), MLI(MLI
) { }
118 const SmallVectorImpl
<MachineBasicBlock
*> &getOrder() const {
122 // Visit all the blocks within the loop, as well as exit blocks and any
123 // blocks properly dominating the header.
125 std::function
<void(MachineBasicBlock
*)> Search
= [this, &Search
]
126 (MachineBasicBlock
*MBB
) -> void {
127 if (Visited
.count(MBB
))
131 for (auto *Succ
: MBB
->successors()) {
132 if (!ML
.contains(Succ
))
136 Order
.push_back(MBB
);
139 // Insert exit blocks.
140 SmallVector
<MachineBasicBlock
*, 2> ExitBlocks
;
141 ML
.getExitBlocks(ExitBlocks
);
142 append_range(Order
, ExitBlocks
);
144 // Then add the loop body.
145 Search(ML
.getHeader());
147 // Then try the preheader and its predecessors.
148 std::function
<void(MachineBasicBlock
*)> GetPredecessor
=
149 [this, &GetPredecessor
] (MachineBasicBlock
*MBB
) -> void {
150 Order
.push_back(MBB
);
151 if (MBB
->pred_size() == 1)
152 GetPredecessor(*MBB
->pred_begin());
155 if (auto *Preheader
= ML
.getLoopPreheader())
156 GetPredecessor(Preheader
);
157 else if (auto *Preheader
= MLI
.findLoopPreheader(&ML
, true, true))
158 GetPredecessor(Preheader
);
162 struct PredicatedMI
{
163 MachineInstr
*MI
= nullptr;
164 SetVector
<MachineInstr
*> Predicates
;
167 PredicatedMI(MachineInstr
*I
, SetVector
<MachineInstr
*> &Preds
) : MI(I
) {
168 assert(I
&& "Instruction must not be null!");
169 Predicates
.insert(Preds
.begin(), Preds
.end());
173 // Represent the current state of the VPR and hold all instances which
174 // represent a VPT block, which is a list of instructions that begins with a
175 // VPT/VPST and has a maximum of four proceeding instructions. All
176 // instructions within the block are predicated upon the vpr and we allow
177 // instructions to define the vpr within in the block too.
179 friend struct LowOverheadLoop
;
181 SmallVector
<MachineInstr
*, 4> Insts
;
183 static SmallVector
<VPTState
, 4> Blocks
;
184 static SetVector
<MachineInstr
*> CurrentPredicates
;
185 static std::map
<MachineInstr
*,
186 std::unique_ptr
<PredicatedMI
>> PredicatedInsts
;
188 static void CreateVPTBlock(MachineInstr
*MI
) {
189 assert((CurrentPredicates
.size() || MI
->getParent()->isLiveIn(ARM::VPR
))
190 && "Can't begin VPT without predicate");
191 Blocks
.emplace_back(MI
);
192 // The execution of MI is predicated upon the current set of instructions
193 // that are AND'ed together to form the VPR predicate value. In the case
194 // that MI is a VPT, CurrentPredicates will also just be MI.
195 PredicatedInsts
.emplace(
196 MI
, std::make_unique
<PredicatedMI
>(MI
, CurrentPredicates
));
199 static void reset() {
201 PredicatedInsts
.clear();
202 CurrentPredicates
.clear();
205 static void addInst(MachineInstr
*MI
) {
206 Blocks
.back().insert(MI
);
207 PredicatedInsts
.emplace(
208 MI
, std::make_unique
<PredicatedMI
>(MI
, CurrentPredicates
));
211 static void addPredicate(MachineInstr
*MI
) {
212 LLVM_DEBUG(dbgs() << "ARM Loops: Adding VPT Predicate: " << *MI
);
213 CurrentPredicates
.insert(MI
);
216 static void resetPredicate(MachineInstr
*MI
) {
217 LLVM_DEBUG(dbgs() << "ARM Loops: Resetting VPT Predicate: " << *MI
);
218 CurrentPredicates
.clear();
219 CurrentPredicates
.insert(MI
);
223 // Have we found an instruction within the block which defines the vpr? If
224 // so, not all the instructions in the block will have the same predicate.
225 static bool hasUniformPredicate(VPTState
&Block
) {
226 return getDivergent(Block
) == nullptr;
229 // If it exists, return the first internal instruction which modifies the
231 static MachineInstr
*getDivergent(VPTState
&Block
) {
232 SmallVectorImpl
<MachineInstr
*> &Insts
= Block
.getInsts();
233 for (unsigned i
= 1; i
< Insts
.size(); ++i
) {
234 MachineInstr
*Next
= Insts
[i
];
235 if (isVectorPredicate(Next
))
236 return Next
; // Found an instruction altering the vpr.
241 // Return whether the given instruction is predicated upon a VCTP.
242 static bool isPredicatedOnVCTP(MachineInstr
*MI
, bool Exclusive
= false) {
243 SetVector
<MachineInstr
*> &Predicates
= PredicatedInsts
[MI
]->Predicates
;
244 if (Exclusive
&& Predicates
.size() != 1)
246 for (auto *PredMI
: Predicates
)
252 // Is the VPST, controlling the block entry, predicated upon a VCTP.
253 static bool isEntryPredicatedOnVCTP(VPTState
&Block
,
254 bool Exclusive
= false) {
255 SmallVectorImpl
<MachineInstr
*> &Insts
= Block
.getInsts();
256 return isPredicatedOnVCTP(Insts
.front(), Exclusive
);
259 // If this block begins with a VPT, we can check whether it's using
260 // at least one predicated input(s), as well as possible loop invariant
261 // which would result in it being implicitly predicated.
262 static bool hasImplicitlyValidVPT(VPTState
&Block
,
263 ReachingDefAnalysis
&RDA
) {
264 SmallVectorImpl
<MachineInstr
*> &Insts
= Block
.getInsts();
265 MachineInstr
*VPT
= Insts
.front();
266 assert(isVPTOpcode(VPT
->getOpcode()) &&
267 "Expected VPT block to begin with VPT/VPST");
269 if (VPT
->getOpcode() == ARM::MVE_VPST
)
272 auto IsOperandPredicated
= [&](MachineInstr
*MI
, unsigned Idx
) {
273 MachineInstr
*Op
= RDA
.getMIOperand(MI
, MI
->getOperand(Idx
));
274 return Op
&& PredicatedInsts
.count(Op
) && isPredicatedOnVCTP(Op
);
277 auto IsOperandInvariant
= [&](MachineInstr
*MI
, unsigned Idx
) {
278 MachineOperand
&MO
= MI
->getOperand(Idx
);
279 if (!MO
.isReg() || !MO
.getReg())
282 SmallPtrSet
<MachineInstr
*, 2> Defs
;
283 RDA
.getGlobalReachingDefs(MI
, MO
.getReg(), Defs
);
287 for (auto *Def
: Defs
)
288 if (Def
->getParent() == VPT
->getParent())
293 // Check that at least one of the operands is directly predicated on a
294 // vctp and allow an invariant value too.
295 return (IsOperandPredicated(VPT
, 1) || IsOperandPredicated(VPT
, 2)) &&
296 (IsOperandPredicated(VPT
, 1) || IsOperandInvariant(VPT
, 1)) &&
297 (IsOperandPredicated(VPT
, 2) || IsOperandInvariant(VPT
, 2));
300 static bool isValid(ReachingDefAnalysis
&RDA
) {
301 // All predication within the loop should be based on vctp. If the block
302 // isn't predicated on entry, check whether the vctp is within the block
303 // and that all other instructions are then predicated on it.
304 for (auto &Block
: Blocks
) {
305 if (isEntryPredicatedOnVCTP(Block
, false) ||
306 hasImplicitlyValidVPT(Block
, RDA
))
309 SmallVectorImpl
<MachineInstr
*> &Insts
= Block
.getInsts();
310 // We don't know how to convert a block with just a VPT;VCTP into
311 // anything valid once we remove the VCTP. For now just bail out.
312 assert(isVPTOpcode(Insts
.front()->getOpcode()) &&
313 "Expected VPT block to start with a VPST or VPT!");
314 if (Insts
.size() == 2 && Insts
.front()->getOpcode() != ARM::MVE_VPST
&&
315 isVCTP(Insts
.back()))
318 for (auto *MI
: Insts
) {
319 // Check that any internal VCTPs are 'Then' predicated.
320 if (isVCTP(MI
) && getVPTInstrPredicate(*MI
) != ARMVCC::Then
)
322 // Skip other instructions that build up the predicate.
323 if (MI
->getOpcode() == ARM::MVE_VPST
|| isVectorPredicate(MI
))
325 // Check that any other instructions are predicated upon a vctp.
326 // TODO: We could infer when VPTs are implicitly predicated on the
327 // vctp (when the operands are predicated).
328 if (!isPredicatedOnVCTP(MI
)) {
329 LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *MI
);
337 VPTState(MachineInstr
*MI
) { Insts
.push_back(MI
); }
339 void insert(MachineInstr
*MI
) {
341 // VPT/VPST + 4 predicated instructions.
342 assert(Insts
.size() <= 5 && "Too many instructions in VPT block!");
345 bool containsVCTP() const {
346 for (auto *MI
: Insts
)
352 unsigned size() const { return Insts
.size(); }
353 SmallVectorImpl
<MachineInstr
*> &getInsts() { return Insts
; }
356 struct LowOverheadLoop
{
359 MachineBasicBlock
*Preheader
= nullptr;
360 MachineLoopInfo
&MLI
;
361 ReachingDefAnalysis
&RDA
;
362 const TargetRegisterInfo
&TRI
;
363 const ARMBaseInstrInfo
&TII
;
364 MachineFunction
*MF
= nullptr;
365 MachineBasicBlock::iterator StartInsertPt
;
366 MachineBasicBlock
*StartInsertBB
= nullptr;
367 MachineInstr
*Start
= nullptr;
368 MachineInstr
*Dec
= nullptr;
369 MachineInstr
*End
= nullptr;
370 MachineOperand TPNumElements
;
371 SmallVector
<MachineInstr
*, 4> VCTPs
;
372 SmallPtrSet
<MachineInstr
*, 4> ToRemove
;
373 SmallPtrSet
<MachineInstr
*, 4> BlockMasksToRecompute
;
375 bool CannotTailPredicate
= false;
377 LowOverheadLoop(MachineLoop
&ML
, MachineLoopInfo
&MLI
,
378 ReachingDefAnalysis
&RDA
, const TargetRegisterInfo
&TRI
,
379 const ARMBaseInstrInfo
&TII
)
380 : ML(ML
), MLI(MLI
), RDA(RDA
), TRI(TRI
), TII(TII
),
381 TPNumElements(MachineOperand::CreateImm(0)) {
382 MF
= ML
.getHeader()->getParent();
383 if (auto *MBB
= ML
.getLoopPreheader())
385 else if (auto *MBB
= MLI
.findLoopPreheader(&ML
, true, true))
390 // If this is an MVE instruction, check that we know how to use tail
391 // predication with it. Record VPT blocks and return whether the
392 // instruction is valid for tail predication.
393 bool ValidateMVEInst(MachineInstr
*MI
);
395 void AnalyseMVEInst(MachineInstr
*MI
) {
396 CannotTailPredicate
= !ValidateMVEInst(MI
);
399 bool IsTailPredicationLegal() const {
400 // For now, let's keep things really simple and only support a single
401 // block for tail predication.
402 return !Revert
&& FoundAllComponents() && !VCTPs
.empty() &&
403 !CannotTailPredicate
&& ML
.getNumBlocks() == 1;
406 // Given that MI is a VCTP, check that is equivalent to any other VCTPs
408 bool AddVCTP(MachineInstr
*MI
);
410 // Check that the predication in the loop will be equivalent once we
411 // perform the conversion. Also ensure that we can provide the number
412 // of elements to the loop start instruction.
413 bool ValidateTailPredicate();
415 // Check that any values available outside of the loop will be the same
416 // after tail predication conversion.
417 bool ValidateLiveOuts();
419 // Is it safe to define LR with DLS/WLS?
420 // LR can be defined if it is the operand to start, because it's the same
421 // value, or if it's going to be equivalent to the operand to Start.
422 MachineInstr
*isSafeToDefineLR();
424 // Check the branch targets are within range and we satisfy our
426 void Validate(ARMBasicBlockUtils
*BBUtils
);
428 bool FoundAllComponents() const {
429 return Start
&& Dec
&& End
;
432 SmallVectorImpl
<VPTState
> &getVPTBlocks() {
433 return VPTState::Blocks
;
436 // Return the operand for the loop start instruction. This will be the loop
437 // iteration count, or the number of elements if we're tail predicating.
438 MachineOperand
&getLoopStartOperand() {
439 if (IsTailPredicationLegal())
440 return TPNumElements
;
441 return Start
->getOperand(1);
444 unsigned getStartOpcode() const {
445 bool IsDo
= isDoLoopStart(*Start
);
446 if (!IsTailPredicationLegal())
447 return IsDo
? ARM::t2DLS
: ARM::t2WLS
;
449 return VCTPOpcodeToLSTP(VCTPs
.back()->getOpcode(), IsDo
);
453 if (Start
) dbgs() << "ARM Loops: Found Loop Start: " << *Start
;
454 if (Dec
) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec
;
455 if (End
) dbgs() << "ARM Loops: Found Loop End: " << *End
;
456 if (!VCTPs
.empty()) {
457 dbgs() << "ARM Loops: Found VCTP(s):\n";
458 for (auto *MI
: VCTPs
)
459 dbgs() << " - " << *MI
;
461 if (!FoundAllComponents())
462 dbgs() << "ARM Loops: Not a low-overhead loop.\n";
463 else if (!(Start
&& Dec
&& End
))
464 dbgs() << "ARM Loops: Failed to find all loop components.\n";
468 class ARMLowOverheadLoops
: public MachineFunctionPass
{
469 MachineFunction
*MF
= nullptr;
470 MachineLoopInfo
*MLI
= nullptr;
471 ReachingDefAnalysis
*RDA
= nullptr;
472 const ARMBaseInstrInfo
*TII
= nullptr;
473 MachineRegisterInfo
*MRI
= nullptr;
474 const TargetRegisterInfo
*TRI
= nullptr;
475 std::unique_ptr
<ARMBasicBlockUtils
> BBUtils
= nullptr;
480 ARMLowOverheadLoops() : MachineFunctionPass(ID
) { }
482 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
483 AU
.setPreservesCFG();
484 AU
.addRequired
<MachineLoopInfo
>();
485 AU
.addRequired
<ReachingDefAnalysis
>();
486 MachineFunctionPass::getAnalysisUsage(AU
);
489 bool runOnMachineFunction(MachineFunction
&MF
) override
;
491 MachineFunctionProperties
getRequiredProperties() const override
{
492 return MachineFunctionProperties().set(
493 MachineFunctionProperties::Property::NoVRegs
).set(
494 MachineFunctionProperties::Property::TracksLiveness
);
497 StringRef
getPassName() const override
{
498 return ARM_LOW_OVERHEAD_LOOPS_NAME
;
502 bool ProcessLoop(MachineLoop
*ML
);
504 bool RevertNonLoops();
506 void RevertWhile(MachineInstr
*MI
) const;
507 void RevertDo(MachineInstr
*MI
) const;
509 bool RevertLoopDec(MachineInstr
*MI
) const;
511 void RevertLoopEnd(MachineInstr
*MI
, bool SkipCmp
= false) const;
513 void RevertLoopEndDec(MachineInstr
*MI
) const;
515 void ConvertVPTBlocks(LowOverheadLoop
&LoLoop
);
517 MachineInstr
*ExpandLoopStart(LowOverheadLoop
&LoLoop
);
519 void Expand(LowOverheadLoop
&LoLoop
);
521 void IterationCountDCE(LowOverheadLoop
&LoLoop
);
525 char ARMLowOverheadLoops::ID
= 0;
527 SmallVector
<VPTState
, 4> VPTState::Blocks
;
528 SetVector
<MachineInstr
*> VPTState::CurrentPredicates
;
529 std::map
<MachineInstr
*,
530 std::unique_ptr
<PredicatedMI
>> VPTState::PredicatedInsts
;
532 INITIALIZE_PASS(ARMLowOverheadLoops
, DEBUG_TYPE
, ARM_LOW_OVERHEAD_LOOPS_NAME
,
535 static bool TryRemove(MachineInstr
*MI
, ReachingDefAnalysis
&RDA
,
536 InstSet
&ToRemove
, InstSet
&Ignore
) {
538 // Check that we can remove all of Killed without having to modify any IT
540 auto WontCorruptITs
= [](InstSet
&Killed
, ReachingDefAnalysis
&RDA
) {
541 // Collect the dead code and the MBBs in which they reside.
542 SmallPtrSet
<MachineBasicBlock
*, 2> BasicBlocks
;
543 for (auto *Dead
: Killed
)
544 BasicBlocks
.insert(Dead
->getParent());
546 // Collect IT blocks in all affected basic blocks.
547 std::map
<MachineInstr
*, SmallPtrSet
<MachineInstr
*, 2>> ITBlocks
;
548 for (auto *MBB
: BasicBlocks
) {
549 for (auto &IT
: *MBB
) {
550 if (IT
.getOpcode() != ARM::t2IT
)
552 RDA
.getReachingLocalUses(&IT
, MCRegister::from(ARM::ITSTATE
),
557 // If we're removing all of the instructions within an IT block, then
558 // also remove the IT instruction.
559 SmallPtrSet
<MachineInstr
*, 2> ModifiedITs
;
560 SmallPtrSet
<MachineInstr
*, 2> RemoveITs
;
561 for (auto *Dead
: Killed
) {
562 if (MachineOperand
*MO
= Dead
->findRegisterUseOperand(ARM::ITSTATE
)) {
563 MachineInstr
*IT
= RDA
.getMIOperand(Dead
, *MO
);
564 RemoveITs
.insert(IT
);
565 auto &CurrentBlock
= ITBlocks
[IT
];
566 CurrentBlock
.erase(Dead
);
567 if (CurrentBlock
.empty())
568 ModifiedITs
.erase(IT
);
570 ModifiedITs
.insert(IT
);
573 if (!ModifiedITs
.empty())
575 Killed
.insert(RemoveITs
.begin(), RemoveITs
.end());
579 SmallPtrSet
<MachineInstr
*, 2> Uses
;
580 if (!RDA
.isSafeToRemove(MI
, Uses
, Ignore
))
583 if (WontCorruptITs(Uses
, RDA
)) {
584 ToRemove
.insert(Uses
.begin(), Uses
.end());
585 LLVM_DEBUG(dbgs() << "ARM Loops: Able to remove: " << *MI
586 << " - can also remove:\n";
587 for (auto *Use
: Uses
)
588 dbgs() << " - " << *Use
);
590 SmallPtrSet
<MachineInstr
*, 4> Killed
;
591 RDA
.collectKilledOperands(MI
, Killed
);
592 if (WontCorruptITs(Killed
, RDA
)) {
593 ToRemove
.insert(Killed
.begin(), Killed
.end());
594 LLVM_DEBUG(for (auto *Dead
: Killed
)
595 dbgs() << " - " << *Dead
);
602 bool LowOverheadLoop::ValidateTailPredicate() {
603 if (!IsTailPredicationLegal()) {
604 LLVM_DEBUG(if (VCTPs
.empty())
605 dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
606 dbgs() << "ARM Loops: Tail-predication is not valid.\n");
610 assert(!VCTPs
.empty() && "VCTP instruction expected but is not set");
611 assert(ML
.getBlocks().size() == 1 &&
612 "Shouldn't be processing a loop with more than one block");
614 if (DisableTailPredication
) {
615 LLVM_DEBUG(dbgs() << "ARM Loops: tail-predication is disabled\n");
619 if (!VPTState::isValid(RDA
)) {
620 LLVM_DEBUG(dbgs() << "ARM Loops: Invalid VPT state.\n");
624 if (!ValidateLiveOuts()) {
625 LLVM_DEBUG(dbgs() << "ARM Loops: Invalid live outs.\n");
629 // For tail predication, we need to provide the number of elements, instead
630 // of the iteration count, to the loop start instruction. The number of
631 // elements is provided to the vctp instruction, so we need to check that
632 // we can use this register at InsertPt.
633 MachineInstr
*VCTP
= VCTPs
.back();
634 if (Start
->getOpcode() == ARM::t2DoLoopStartTP
||
635 Start
->getOpcode() == ARM::t2WhileLoopStartTP
) {
636 TPNumElements
= Start
->getOperand(2);
637 StartInsertPt
= Start
;
638 StartInsertBB
= Start
->getParent();
640 TPNumElements
= VCTP
->getOperand(1);
641 MCRegister NumElements
= TPNumElements
.getReg().asMCReg();
643 // If the register is defined within loop, then we can't perform TP.
644 // TODO: Check whether this is just a mov of a register that would be
646 if (RDA
.hasLocalDefBefore(VCTP
, NumElements
)) {
647 LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
651 // The element count register maybe defined after InsertPt, in which case we
652 // need to try to move either InsertPt or the def so that the [w|d]lstp can
655 if (StartInsertPt
!= StartInsertBB
->end() &&
656 !RDA
.isReachingDefLiveOut(&*StartInsertPt
, NumElements
)) {
658 RDA
.getLocalLiveOutMIDef(StartInsertBB
, NumElements
)) {
659 if (RDA
.isSafeToMoveForwards(ElemDef
, &*StartInsertPt
)) {
660 ElemDef
->removeFromParent();
661 StartInsertBB
->insert(StartInsertPt
, ElemDef
);
663 << "ARM Loops: Moved element count def: " << *ElemDef
);
664 } else if (RDA
.isSafeToMoveBackwards(&*StartInsertPt
, ElemDef
)) {
665 StartInsertPt
->removeFromParent();
666 StartInsertBB
->insertAfter(MachineBasicBlock::iterator(ElemDef
),
668 LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef
);
670 // If we fail to move an instruction and the element count is provided
671 // by a mov, use the mov operand if it will have the same value at the
673 MachineOperand Operand
= ElemDef
->getOperand(1);
674 if (isMovRegOpcode(ElemDef
->getOpcode()) &&
675 RDA
.getUniqueReachingMIDef(ElemDef
, Operand
.getReg().asMCReg()) ==
676 RDA
.getUniqueReachingMIDef(&*StartInsertPt
,
677 Operand
.getReg().asMCReg())) {
678 TPNumElements
= Operand
;
679 NumElements
= TPNumElements
.getReg();
682 << "ARM Loops: Unable to move element count to loop "
683 << "start instruction.\n");
690 // Especially in the case of while loops, InsertBB may not be the
691 // preheader, so we need to check that the register isn't redefined
692 // before entering the loop.
693 auto CannotProvideElements
= [this](MachineBasicBlock
*MBB
,
694 MCRegister NumElements
) {
697 // NumElements is redefined in this block.
698 if (RDA
.hasLocalDefBefore(&MBB
->back(), NumElements
))
701 // Don't continue searching up through multiple predecessors.
702 if (MBB
->pred_size() > 1)
708 // Search backwards for a def, until we get to InsertBB.
709 MachineBasicBlock
*MBB
= Preheader
;
710 while (MBB
&& MBB
!= StartInsertBB
) {
711 if (CannotProvideElements(MBB
, NumElements
)) {
712 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
715 MBB
= *MBB
->pred_begin();
719 // Could inserting the [W|D]LSTP cause some unintended affects? In a perfect
720 // world the [w|d]lstp instruction would be last instruction in the preheader
721 // and so it would only affect instructions within the loop body. But due to
722 // scheduling, and/or the logic in this pass (above), the insertion point can
723 // be moved earlier. So if the Loop Start isn't the last instruction in the
724 // preheader, and if the initial element count is smaller than the vector
725 // width, the Loop Start instruction will immediately generate one or more
726 // false lane mask which can, incorrectly, affect the proceeding MVE
727 // instructions in the preheader.
728 if (std::any_of(StartInsertPt
, StartInsertBB
->end(), shouldInspect
)) {
729 LLVM_DEBUG(dbgs() << "ARM Loops: Instruction blocks [W|D]LSTP\n");
733 // Check that the value change of the element count is what we expect and
734 // that the predication will be equivalent. For this we need:
735 // NumElements = NumElements - VectorWidth. The sub will be a sub immediate
736 // and we can also allow register copies within the chain too.
737 auto IsValidSub
= [](MachineInstr
*MI
, int ExpectedVecWidth
) {
738 return -getAddSubImmediate(*MI
) == ExpectedVecWidth
;
741 MachineBasicBlock
*MBB
= VCTP
->getParent();
742 // Remove modifications to the element count since they have no purpose in a
743 // tail predicated loop. Explicitly refer to the vctp operand no matter which
744 // register NumElements has been assigned to, since that is what the
745 // modifications will be using
746 if (auto *Def
= RDA
.getUniqueReachingMIDef(
747 &MBB
->back(), VCTP
->getOperand(1).getReg().asMCReg())) {
748 SmallPtrSet
<MachineInstr
*, 2> ElementChain
;
749 SmallPtrSet
<MachineInstr
*, 2> Ignore
;
750 unsigned ExpectedVectorWidth
= getTailPredVectorWidth(VCTP
->getOpcode());
752 Ignore
.insert(VCTPs
.begin(), VCTPs
.end());
754 if (TryRemove(Def
, RDA
, ElementChain
, Ignore
)) {
755 bool FoundSub
= false;
757 for (auto *MI
: ElementChain
) {
758 if (isMovRegOpcode(MI
->getOpcode()))
761 if (isSubImmOpcode(MI
->getOpcode())) {
762 if (FoundSub
|| !IsValidSub(MI
, ExpectedVectorWidth
)) {
763 LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
769 LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
774 ToRemove
.insert(ElementChain
.begin(), ElementChain
.end());
778 // If we converted the LoopStart to a t2DoLoopStartTP/t2WhileLoopStartTP, we
779 // can also remove any extra instructions in the preheader, which often
780 // includes a now unused MOV.
781 if ((Start
->getOpcode() == ARM::t2DoLoopStartTP
||
782 Start
->getOpcode() == ARM::t2WhileLoopStartTP
) &&
783 Preheader
&& !Preheader
->empty() &&
784 !RDA
.hasLocalDefBefore(VCTP
, VCTP
->getOperand(1).getReg())) {
785 if (auto *Def
= RDA
.getUniqueReachingMIDef(
786 &Preheader
->back(), VCTP
->getOperand(1).getReg().asMCReg())) {
787 SmallPtrSet
<MachineInstr
*, 2> Ignore
;
788 Ignore
.insert(VCTPs
.begin(), VCTPs
.end());
789 TryRemove(Def
, RDA
, ToRemove
, Ignore
);
796 static bool isRegInClass(const MachineOperand
&MO
,
797 const TargetRegisterClass
*Class
) {
798 return MO
.isReg() && MO
.getReg() && Class
->contains(MO
.getReg());
801 // MVE 'narrowing' operate on half a lane, reading from half and writing
802 // to half, which are referred to has the top and bottom half. The other
803 // half retains its previous value.
804 static bool retainsPreviousHalfElement(const MachineInstr
&MI
) {
805 const MCInstrDesc
&MCID
= MI
.getDesc();
806 uint64_t Flags
= MCID
.TSFlags
;
807 return (Flags
& ARMII::RetainsPreviousHalfElement
) != 0;
810 // Some MVE instructions read from the top/bottom halves of their operand(s)
811 // and generate a vector result with result elements that are double the
812 // width of the input.
813 static bool producesDoubleWidthResult(const MachineInstr
&MI
) {
814 const MCInstrDesc
&MCID
= MI
.getDesc();
815 uint64_t Flags
= MCID
.TSFlags
;
816 return (Flags
& ARMII::DoubleWidthResult
) != 0;
819 static bool isHorizontalReduction(const MachineInstr
&MI
) {
820 const MCInstrDesc
&MCID
= MI
.getDesc();
821 uint64_t Flags
= MCID
.TSFlags
;
822 return (Flags
& ARMII::HorizontalReduction
) != 0;
825 // Can this instruction generate a non-zero result when given only zeroed
826 // operands? This allows us to know that, given operands with false bytes
827 // zeroed by masked loads, that the result will also contain zeros in those
829 static bool canGenerateNonZeros(const MachineInstr
&MI
) {
831 // Check for instructions which can write into a larger element size,
832 // possibly writing into a previous zero'd lane.
833 if (producesDoubleWidthResult(MI
))
836 switch (MI
.getOpcode()) {
839 // FIXME: VNEG FP and -0? I think we'll need to handle this once we allow
840 // fp16 -> fp32 vector conversions.
841 // Instructions that perform a NOT will generate 1s from 0s.
844 // Count leading zeros will do just that!
845 case ARM::MVE_VCLZs8
:
846 case ARM::MVE_VCLZs16
:
847 case ARM::MVE_VCLZs32
:
853 // Look at its register uses to see if it only can only receive zeros
854 // into its false lanes which would then produce zeros. Also check that
855 // the output register is also defined by an FalseLanesZero instruction
856 // so that if tail-predication happens, the lanes that aren't updated will
858 static bool producesFalseLanesZero(MachineInstr
&MI
,
859 const TargetRegisterClass
*QPRs
,
860 const ReachingDefAnalysis
&RDA
,
861 InstSet
&FalseLanesZero
) {
862 if (canGenerateNonZeros(MI
))
865 bool isPredicated
= isVectorPredicated(&MI
);
866 // Predicated loads will write zeros to the falsely predicated bytes of the
867 // destination register.
871 auto IsZeroInit
= [](MachineInstr
*Def
) {
872 return !isVectorPredicated(Def
) &&
873 Def
->getOpcode() == ARM::MVE_VMOVimmi32
&&
874 Def
->getOperand(1).getImm() == 0;
877 bool AllowScalars
= isHorizontalReduction(MI
);
878 for (auto &MO
: MI
.operands()) {
879 if (!MO
.isReg() || !MO
.getReg())
881 if (!isRegInClass(MO
, QPRs
) && AllowScalars
)
884 // Check that this instruction will produce zeros in its false lanes:
885 // - If it only consumes false lanes zero or constant 0 (vmov #0)
886 // - If it's predicated, it only matters that it's def register already has
887 // false lane zeros, so we can ignore the uses.
888 SmallPtrSet
<MachineInstr
*, 2> Defs
;
889 RDA
.getGlobalReachingDefs(&MI
, MO
.getReg(), Defs
);
890 for (auto *Def
: Defs
) {
891 if (Def
== &MI
|| FalseLanesZero
.count(Def
) || IsZeroInit(Def
))
893 if (MO
.isUse() && isPredicated
)
898 LLVM_DEBUG(dbgs() << "ARM Loops: Always False Zeros: " << MI
);
902 bool LowOverheadLoop::ValidateLiveOuts() {
903 // We want to find out if the tail-predicated version of this loop will
904 // produce the same values as the loop in its original form. For this to
905 // be true, the newly inserted implicit predication must not change the
906 // the (observable) results.
907 // We're doing this because many instructions in the loop will not be
908 // predicated and so the conversion from VPT predication to tail-predication
909 // can result in different values being produced; due to the tail-predication
910 // preventing many instructions from updating their falsely predicated
911 // lanes. This analysis assumes that all the instructions perform lane-wise
912 // operations and don't perform any exchanges.
913 // A masked load, whether through VPT or tail predication, will write zeros
914 // to any of the falsely predicated bytes. So, from the loads, we know that
915 // the false lanes are zeroed and here we're trying to track that those false
916 // lanes remain zero, or where they change, the differences are masked away
918 // All MVE stores have to be predicated, so we know that any predicate load
919 // operands, or stored results are equivalent already. Other explicitly
920 // predicated instructions will perform the same operation in the original
921 // loop and the tail-predicated form too. Because of this, we can insert
922 // loads, stores and other predicated instructions into our Predicated
923 // set and build from there.
924 const TargetRegisterClass
*QPRs
= TRI
.getRegClass(ARM::MQPRRegClassID
);
925 SetVector
<MachineInstr
*> FalseLanesUnknown
;
926 SmallPtrSet
<MachineInstr
*, 4> FalseLanesZero
;
927 SmallPtrSet
<MachineInstr
*, 4> Predicated
;
928 MachineBasicBlock
*Header
= ML
.getHeader();
930 LLVM_DEBUG(dbgs() << "ARM Loops: Validating Live outs\n");
932 for (auto &MI
: *Header
) {
933 if (!shouldInspect(MI
))
936 if (isVCTP(&MI
) || isVPTOpcode(MI
.getOpcode()))
939 bool isPredicated
= isVectorPredicated(&MI
);
940 bool retainsOrReduces
=
941 retainsPreviousHalfElement(MI
) || isHorizontalReduction(MI
);
944 Predicated
.insert(&MI
);
945 if (producesFalseLanesZero(MI
, QPRs
, RDA
, FalseLanesZero
))
946 FalseLanesZero
.insert(&MI
);
947 else if (MI
.getNumDefs() == 0)
949 else if (!isPredicated
&& retainsOrReduces
) {
950 LLVM_DEBUG(dbgs() << " Unpredicated instruction that retainsOrReduces: " << MI
);
953 else if (!isPredicated
)
954 FalseLanesUnknown
.insert(&MI
);
958 dbgs() << " Predicated:\n";
959 for (auto *I
: Predicated
)
961 dbgs() << " FalseLanesZero:\n";
962 for (auto *I
: FalseLanesZero
)
964 dbgs() << " FalseLanesUnknown:\n";
965 for (auto *I
: FalseLanesUnknown
)
969 auto HasPredicatedUsers
= [this](MachineInstr
*MI
, const MachineOperand
&MO
,
970 SmallPtrSetImpl
<MachineInstr
*> &Predicated
) {
971 SmallPtrSet
<MachineInstr
*, 2> Uses
;
972 RDA
.getGlobalUses(MI
, MO
.getReg().asMCReg(), Uses
);
973 for (auto *Use
: Uses
) {
974 if (Use
!= MI
&& !Predicated
.count(Use
))
980 // Visit the unknowns in reverse so that we can start at the values being
981 // stored and then we can work towards the leaves, hopefully adding more
982 // instructions to Predicated. Successfully terminating the loop means that
983 // all the unknown values have to found to be masked by predicated user(s).
984 // For any unpredicated values, we store them in NonPredicated so that we
985 // can later check whether these form a reduction.
986 SmallPtrSet
<MachineInstr
*, 2> NonPredicated
;
987 for (auto *MI
: reverse(FalseLanesUnknown
)) {
988 for (auto &MO
: MI
->operands()) {
989 if (!isRegInClass(MO
, QPRs
) || !MO
.isDef())
991 if (!HasPredicatedUsers(MI
, MO
, Predicated
)) {
992 LLVM_DEBUG(dbgs() << " Found an unknown def of : "
993 << TRI
.getRegAsmName(MO
.getReg()) << " at " << *MI
);
994 NonPredicated
.insert(MI
);
998 // Any unknown false lanes have been masked away by the user(s).
999 if (!NonPredicated
.contains(MI
))
1000 Predicated
.insert(MI
);
1003 SmallPtrSet
<MachineInstr
*, 2> LiveOutMIs
;
1004 SmallVector
<MachineBasicBlock
*, 2> ExitBlocks
;
1005 ML
.getExitBlocks(ExitBlocks
);
1006 assert(ML
.getNumBlocks() == 1 && "Expected single block loop!");
1007 assert(ExitBlocks
.size() == 1 && "Expected a single exit block");
1008 MachineBasicBlock
*ExitBB
= ExitBlocks
.front();
1009 for (const MachineBasicBlock::RegisterMaskPair
&RegMask
: ExitBB
->liveins()) {
1010 // TODO: Instead of blocking predication, we could move the vctp to the exit
1011 // block and calculate it's operand there in or the preheader.
1012 if (RegMask
.PhysReg
== ARM::VPR
) {
1013 LLVM_DEBUG(dbgs() << " VPR is live in to the exit block.");
1016 // Check Q-regs that are live in the exit blocks. We don't collect scalars
1017 // because they won't be affected by lane predication.
1018 if (QPRs
->contains(RegMask
.PhysReg
))
1019 if (auto *MI
= RDA
.getLocalLiveOutMIDef(Header
, RegMask
.PhysReg
))
1020 LiveOutMIs
.insert(MI
);
1023 // We've already validated that any VPT predication within the loop will be
1024 // equivalent when we perform the predication transformation; so we know that
1025 // any VPT predicated instruction is predicated upon VCTP. Any live-out
1026 // instruction needs to be predicated, so check this here. The instructions
1027 // in NonPredicated have been found to be a reduction that we can ensure its
1029 for (auto *MI
: LiveOutMIs
) {
1030 if (NonPredicated
.count(MI
) && FalseLanesUnknown
.contains(MI
)) {
1031 LLVM_DEBUG(dbgs() << " Unable to handle live out: " << *MI
);
1039 void LowOverheadLoop::Validate(ARMBasicBlockUtils
*BBUtils
) {
1043 // Check branch target ranges: WLS[TP] can only branch forwards and LE[TP]
1044 // can only jump back.
1045 auto ValidateRanges
= [](MachineInstr
*Start
, MachineInstr
*End
,
1046 ARMBasicBlockUtils
*BBUtils
, MachineLoop
&ML
) {
1047 MachineBasicBlock
*TgtBB
= End
->getOpcode() == ARM::t2LoopEnd
1048 ? End
->getOperand(1).getMBB()
1049 : End
->getOperand(2).getMBB();
1050 // TODO Maybe there's cases where the target doesn't have to be the header,
1051 // but for now be safe and revert.
1052 if (TgtBB
!= ML
.getHeader()) {
1053 LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targeting header.\n");
1057 // The WLS and LE instructions have 12-bits for the label offset. WLS
1058 // requires a positive offset, while LE uses negative.
1059 if (BBUtils
->getOffsetOf(End
) < BBUtils
->getOffsetOf(ML
.getHeader()) ||
1060 !BBUtils
->isBBInRange(End
, ML
.getHeader(), 4094)) {
1061 LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n");
1065 if (isWhileLoopStart(*Start
)) {
1066 MachineBasicBlock
*TargetBB
= getWhileLoopStartTargetBB(*Start
);
1067 if (BBUtils
->getOffsetOf(Start
) > BBUtils
->getOffsetOf(TargetBB
) ||
1068 !BBUtils
->isBBInRange(Start
, TargetBB
, 4094)) {
1069 LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n");
1076 StartInsertPt
= MachineBasicBlock::iterator(Start
);
1077 StartInsertBB
= Start
->getParent();
1078 LLVM_DEBUG(dbgs() << "ARM Loops: Will insert LoopStart at "
1081 Revert
= !ValidateRanges(Start
, End
, BBUtils
, ML
);
1082 CannotTailPredicate
= !ValidateTailPredicate();
1085 bool LowOverheadLoop::AddVCTP(MachineInstr
*MI
) {
1086 LLVM_DEBUG(dbgs() << "ARM Loops: Adding VCTP: " << *MI
);
1087 if (VCTPs
.empty()) {
1088 VCTPs
.push_back(MI
);
1092 // If we find another VCTP, check whether it uses the same value as the main VCTP.
1093 // If it does, store it in the VCTPs set, else refuse it.
1094 MachineInstr
*Prev
= VCTPs
.back();
1095 if (!Prev
->getOperand(1).isIdenticalTo(MI
->getOperand(1)) ||
1096 !RDA
.hasSameReachingDef(Prev
, MI
, MI
->getOperand(1).getReg().asMCReg())) {
1097 LLVM_DEBUG(dbgs() << "ARM Loops: Found VCTP with a different reaching "
1098 "definition from the main VCTP");
1101 VCTPs
.push_back(MI
);
1105 static bool ValidateMVEStore(MachineInstr
*MI
, MachineLoop
*ML
) {
1107 auto GetFrameIndex
= [](MachineMemOperand
*Operand
) {
1108 const PseudoSourceValue
*PseudoValue
= Operand
->getPseudoValue();
1109 if (PseudoValue
&& PseudoValue
->kind() == PseudoSourceValue::FixedStack
) {
1110 if (const auto *FS
= dyn_cast
<FixedStackPseudoSourceValue
>(PseudoValue
)) {
1111 return FS
->getFrameIndex();
1117 auto IsStackOp
= [GetFrameIndex
](MachineInstr
*I
) {
1118 switch (I
->getOpcode()) {
1119 case ARM::MVE_VSTRWU32
:
1120 case ARM::MVE_VLDRWU32
: {
1121 return I
->getOperand(1).getReg() == ARM::SP
&&
1122 I
->memoperands().size() == 1 &&
1123 GetFrameIndex(I
->memoperands().front()) >= 0;
1130 // An unpredicated vector register spill is allowed if all of the uses of the
1131 // stack slot are within the loop
1132 if (MI
->getOpcode() != ARM::MVE_VSTRWU32
|| !IsStackOp(MI
))
1135 // Search all blocks after the loop for accesses to the same stack slot.
1136 // ReachingDefAnalysis doesn't work for sp as it relies on registers being
1137 // live-out (which sp never is) to know what blocks to look in
1138 if (MI
->memoperands().size() == 0)
1140 int FI
= GetFrameIndex(MI
->memoperands().front());
1142 auto &FrameInfo
= MI
->getParent()->getParent()->getFrameInfo();
1143 if (FI
== -1 || !FrameInfo
.isSpillSlotObjectIndex(FI
))
1146 SmallVector
<MachineBasicBlock
*> Frontier
;
1147 ML
->getExitBlocks(Frontier
);
1148 SmallPtrSet
<MachineBasicBlock
*, 4> Visited
{MI
->getParent()};
1150 while (Idx
< Frontier
.size()) {
1151 MachineBasicBlock
*BB
= Frontier
[Idx
];
1152 bool LookAtSuccessors
= true;
1153 for (auto &I
: *BB
) {
1154 if (!IsStackOp(&I
) || I
.memoperands().size() == 0)
1156 if (GetFrameIndex(I
.memoperands().front()) != FI
)
1158 // If this block has a store to the stack slot before any loads then we
1159 // can ignore the block
1160 if (I
.getOpcode() == ARM::MVE_VSTRWU32
) {
1161 LookAtSuccessors
= false;
1164 // If the store and the load are using the same stack slot then the
1165 // store isn't valid for tail predication
1166 if (I
.getOpcode() == ARM::MVE_VLDRWU32
)
1170 if (LookAtSuccessors
) {
1171 for (auto Succ
: BB
->successors()) {
1172 if (!Visited
.contains(Succ
) && !is_contained(Frontier
, Succ
))
1173 Frontier
.push_back(Succ
);
1183 bool LowOverheadLoop::ValidateMVEInst(MachineInstr
*MI
) {
1184 if (CannotTailPredicate
)
1187 if (!shouldInspect(*MI
))
1190 if (MI
->getOpcode() == ARM::MVE_VPSEL
||
1191 MI
->getOpcode() == ARM::MVE_VPNOT
) {
1192 // TODO: Allow VPSEL and VPNOT, we currently cannot because:
1193 // 1) It will use the VPR as a predicate operand, but doesn't have to be
1194 // instead a VPT block, which means we can assert while building up
1195 // the VPT block because we don't find another VPT or VPST to being a new
1197 // 2) VPSEL still requires a VPR operand even after tail predicating,
1198 // which means we can't remove it unless there is another
1199 // instruction, such as vcmp, that can provide the VPR def.
1203 // Record all VCTPs and check that they're equivalent to one another.
1204 if (isVCTP(MI
) && !AddVCTP(MI
))
1207 // Inspect uses first so that any instructions that alter the VPR don't
1208 // alter the predicate upon themselves.
1209 const MCInstrDesc
&MCID
= MI
->getDesc();
1211 unsigned LastOpIdx
= MI
->getNumOperands() - 1;
1212 for (auto &Op
: enumerate(reverse(MCID
.operands()))) {
1213 const MachineOperand
&MO
= MI
->getOperand(LastOpIdx
- Op
.index());
1214 if (!MO
.isReg() || !MO
.isUse() || MO
.getReg() != ARM::VPR
)
1217 if (ARM::isVpred(Op
.value().OperandType
)) {
1218 VPTState::addInst(MI
);
1220 } else if (MI
->getOpcode() != ARM::MVE_VPST
) {
1221 LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI
);
1226 // If we find an instruction that has been marked as not valid for tail
1227 // predication, only allow the instruction if it's contained within a valid
1229 bool RequiresExplicitPredication
=
1230 (MCID
.TSFlags
& ARMII::ValidForTailPredication
) == 0;
1231 if (isDomainMVE(MI
) && RequiresExplicitPredication
) {
1232 LLVM_DEBUG(if (!IsUse
)
1233 dbgs() << "ARM Loops: Can't tail predicate: " << *MI
);
1237 // If the instruction is already explicitly predicated, then the conversion
1238 // will be fine, but ensure that all store operations are predicated.
1239 if (MI
->mayStore() && !ValidateMVEStore(MI
, &ML
))
1242 // If this instruction defines the VPR, update the predicate for the
1243 // proceeding instructions.
1244 if (isVectorPredicate(MI
)) {
1245 // Clear the existing predicate when we're not in VPT Active state,
1246 // otherwise we add to it.
1247 if (!isVectorPredicated(MI
))
1248 VPTState::resetPredicate(MI
);
1250 VPTState::addPredicate(MI
);
1253 // Finally once the predicate has been modified, we can start a new VPT
1254 // block if necessary.
1255 if (isVPTOpcode(MI
->getOpcode()))
1256 VPTState::CreateVPTBlock(MI
);
1261 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction
&mf
) {
1262 const ARMSubtarget
&ST
= static_cast<const ARMSubtarget
&>(mf
.getSubtarget());
1267 LLVM_DEBUG(dbgs() << "ARM Loops on " << MF
->getName() << " ------------- \n");
1269 MLI
= &getAnalysis
<MachineLoopInfo
>();
1270 RDA
= &getAnalysis
<ReachingDefAnalysis
>();
1271 MF
->getProperties().set(MachineFunctionProperties::Property::TracksLiveness
);
1272 MRI
= &MF
->getRegInfo();
1273 TII
= static_cast<const ARMBaseInstrInfo
*>(ST
.getInstrInfo());
1274 TRI
= ST
.getRegisterInfo();
1275 BBUtils
= std::unique_ptr
<ARMBasicBlockUtils
>(new ARMBasicBlockUtils(*MF
));
1276 BBUtils
->computeAllBlockSizes();
1277 BBUtils
->adjustBBOffsetsAfter(&MF
->front());
1279 bool Changed
= false;
1280 for (auto ML
: *MLI
) {
1281 if (ML
->isOutermost())
1282 Changed
|= ProcessLoop(ML
);
1284 Changed
|= RevertNonLoops();
1288 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop
*ML
) {
1290 bool Changed
= false;
1292 // Process inner loops first.
1293 for (auto I
= ML
->begin(), E
= ML
->end(); I
!= E
; ++I
)
1294 Changed
|= ProcessLoop(*I
);
1297 dbgs() << "ARM Loops: Processing loop containing:\n";
1298 if (auto *Preheader
= ML
->getLoopPreheader())
1299 dbgs() << " - Preheader: " << printMBBReference(*Preheader
) << "\n";
1300 else if (auto *Preheader
= MLI
->findLoopPreheader(ML
, true, true))
1301 dbgs() << " - Preheader: " << printMBBReference(*Preheader
) << "\n";
1302 for (auto *MBB
: ML
->getBlocks())
1303 dbgs() << " - Block: " << printMBBReference(*MBB
) << "\n";
1306 // Search the given block for a loop start instruction. If one isn't found,
1307 // and there's only one predecessor block, search that one too.
1308 std::function
<MachineInstr
*(MachineBasicBlock
*)> SearchForStart
=
1309 [&SearchForStart
](MachineBasicBlock
*MBB
) -> MachineInstr
* {
1310 for (auto &MI
: *MBB
) {
1311 if (isLoopStart(MI
))
1314 if (MBB
->pred_size() == 1)
1315 return SearchForStart(*MBB
->pred_begin());
1319 LowOverheadLoop
LoLoop(*ML
, *MLI
, *RDA
, *TRI
, *TII
);
1320 // Search the preheader for the start intrinsic.
1321 // FIXME: I don't see why we shouldn't be supporting multiple predecessors
1322 // with potentially multiple set.loop.iterations, so we need to enable this.
1323 if (LoLoop
.Preheader
)
1324 LoLoop
.Start
= SearchForStart(LoLoop
.Preheader
);
1328 // Find the low-overhead loop components and decide whether or not to fall
1329 // back to a normal loop. Also look for a vctp instructions and decide
1330 // whether we can convert that predicate using tail predication.
1331 for (auto *MBB
: reverse(ML
->getBlocks())) {
1332 for (auto &MI
: *MBB
) {
1333 if (MI
.isDebugValue())
1335 else if (MI
.getOpcode() == ARM::t2LoopDec
)
1337 else if (MI
.getOpcode() == ARM::t2LoopEnd
)
1339 else if (MI
.getOpcode() == ARM::t2LoopEndDec
)
1340 LoLoop
.End
= LoLoop
.Dec
= &MI
;
1341 else if (isLoopStart(MI
))
1343 else if (MI
.getDesc().isCall()) {
1344 // TODO: Though the call will require LE to execute again, does this
1345 // mean we should revert? Always executing LE hopefully should be
1346 // faster than performing a sub,cmp,br or even subs,br.
1347 LoLoop
.Revert
= true;
1348 LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
1350 // Record VPR defs and build up their corresponding vpt blocks.
1351 // Check we know how to tail predicate any mve instructions.
1352 LoLoop
.AnalyseMVEInst(&MI
);
1357 LLVM_DEBUG(LoLoop
.dump());
1358 if (!LoLoop
.FoundAllComponents()) {
1359 LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
1363 assert(LoLoop
.Start
->getOpcode() != ARM::t2WhileLoopStart
&&
1364 "Expected t2WhileLoopStart to be removed before regalloc!");
1366 // Check that the only instruction using LoopDec is LoopEnd. This can only
1367 // happen when the Dec and End are separate, not a single t2LoopEndDec.
1368 // TODO: Check for copy chains that really have no effect.
1369 if (LoLoop
.Dec
!= LoLoop
.End
) {
1370 SmallPtrSet
<MachineInstr
*, 2> Uses
;
1371 RDA
->getReachingLocalUses(LoLoop
.Dec
, MCRegister::from(ARM::LR
), Uses
);
1372 if (Uses
.size() > 1 || !Uses
.count(LoLoop
.End
)) {
1373 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n");
1374 LoLoop
.Revert
= true;
1377 LoLoop
.Validate(BBUtils
.get());
1382 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
1383 // beq that branches to the exit branch.
1384 // TODO: We could also try to generate a cbz if the value in LR is also in
1385 // another low register.
1386 void ARMLowOverheadLoops::RevertWhile(MachineInstr
*MI
) const {
1387 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI
);
1388 MachineBasicBlock
*DestBB
= getWhileLoopStartTargetBB(*MI
);
1389 unsigned BrOpc
= BBUtils
->isBBInRange(MI
, DestBB
, 254) ?
1390 ARM::tBcc
: ARM::t2Bcc
;
1392 RevertWhileLoopStartLR(MI
, TII
, BrOpc
);
1395 void ARMLowOverheadLoops::RevertDo(MachineInstr
*MI
) const {
1396 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to mov: " << *MI
);
1397 RevertDoLoopStart(MI
, TII
);
1400 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr
*MI
) const {
1401 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI
);
1402 MachineBasicBlock
*MBB
= MI
->getParent();
1403 SmallPtrSet
<MachineInstr
*, 1> Ignore
;
1404 for (auto I
= MachineBasicBlock::iterator(MI
), E
= MBB
->end(); I
!= E
; ++I
) {
1405 if (I
->getOpcode() == ARM::t2LoopEnd
) {
1411 // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
1413 RDA
->isSafeToDefRegAt(MI
, MCRegister::from(ARM::CPSR
), Ignore
);
1415 llvm::RevertLoopDec(MI
, TII
, SetFlags
);
1419 // Generate a subs, or sub and cmp, and a branch instead of an LE.
1420 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr
*MI
, bool SkipCmp
) const {
1421 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI
);
1423 MachineBasicBlock
*DestBB
= MI
->getOperand(1).getMBB();
1424 unsigned BrOpc
= BBUtils
->isBBInRange(MI
, DestBB
, 254) ?
1425 ARM::tBcc
: ARM::t2Bcc
;
1427 llvm::RevertLoopEnd(MI
, TII
, BrOpc
, SkipCmp
);
1430 // Generate a subs, or sub and cmp, and a branch instead of an LE.
1431 void ARMLowOverheadLoops::RevertLoopEndDec(MachineInstr
*MI
) const {
1432 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to subs, br: " << *MI
);
1433 assert(MI
->getOpcode() == ARM::t2LoopEndDec
&& "Expected a t2LoopEndDec!");
1434 MachineBasicBlock
*MBB
= MI
->getParent();
1436 MachineInstrBuilder MIB
=
1437 BuildMI(*MBB
, MI
, MI
->getDebugLoc(), TII
->get(ARM::t2SUBri
));
1438 MIB
.addDef(ARM::LR
);
1439 MIB
.add(MI
->getOperand(1));
1441 MIB
.addImm(ARMCC::AL
);
1442 MIB
.addReg(ARM::NoRegister
);
1443 MIB
.addReg(ARM::CPSR
);
1444 MIB
->getOperand(5).setIsDef(true);
1446 MachineBasicBlock
*DestBB
= MI
->getOperand(2).getMBB();
1448 BBUtils
->isBBInRange(MI
, DestBB
, 254) ? ARM::tBcc
: ARM::t2Bcc
;
1451 MIB
= BuildMI(*MBB
, MI
, MI
->getDebugLoc(), TII
->get(BrOpc
));
1452 MIB
.add(MI
->getOperand(2)); // branch target
1453 MIB
.addImm(ARMCC::NE
); // condition code
1454 MIB
.addReg(ARM::CPSR
);
1456 MI
->eraseFromParent();
1459 // Perform dead code elimation on the loop iteration count setup expression.
1460 // If we are tail-predicating, the number of elements to be processed is the
1461 // operand of the VCTP instruction in the vector body, see getCount(), which is
1462 // register $r3 in this example:
1464 // $lr = big-itercount-expression
1466 // $lr = t2DoLoopStart renamable $lr
1469 // $vpr = MVE_VCTP32 renamable $r3
1470 // renamable $lr = t2LoopDec killed renamable $lr, 1
1471 // t2LoopEnd renamable $lr, %vector.body
1474 // What we would like achieve here is to replace the do-loop start pseudo
1475 // instruction t2DoLoopStart with:
1477 // $lr = MVE_DLSTP_32 killed renamable $r3
1479 // Thus, $r3 which defines the number of elements, is written to $lr,
1480 // and then we want to delete the whole chain that used to define $lr,
1481 // see the comment below how this chain could look like.
1483 void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop
&LoLoop
) {
1484 if (!LoLoop
.IsTailPredicationLegal())
1487 LLVM_DEBUG(dbgs() << "ARM Loops: Trying DCE on loop iteration count.\n");
1489 MachineInstr
*Def
= RDA
->getMIOperand(LoLoop
.Start
, 1);
1491 LLVM_DEBUG(dbgs() << "ARM Loops: Couldn't find iteration count.\n");
1495 // Collect and remove the users of iteration count.
1496 SmallPtrSet
<MachineInstr
*, 4> Killed
= { LoLoop
.Start
, LoLoop
.Dec
,
1498 if (!TryRemove(Def
, *RDA
, LoLoop
.ToRemove
, Killed
))
1499 LLVM_DEBUG(dbgs() << "ARM Loops: Unsafe to remove loop iteration count.\n");
1502 MachineInstr
* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop
&LoLoop
) {
1503 LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n");
1504 // When using tail-predication, try to delete the dead code that was used to
1505 // calculate the number of loop iterations.
1506 IterationCountDCE(LoLoop
);
1508 MachineBasicBlock::iterator InsertPt
= LoLoop
.StartInsertPt
;
1509 MachineInstr
*Start
= LoLoop
.Start
;
1510 MachineBasicBlock
*MBB
= LoLoop
.StartInsertBB
;
1511 unsigned Opc
= LoLoop
.getStartOpcode();
1512 MachineOperand
&Count
= LoLoop
.getLoopStartOperand();
1514 // A DLS lr, lr we needn't emit
1515 MachineInstr
* NewStart
;
1516 if (Opc
== ARM::t2DLS
&& Count
.isReg() && Count
.getReg() == ARM::LR
) {
1517 LLVM_DEBUG(dbgs() << "ARM Loops: Didn't insert start: DLS lr, lr");
1520 MachineInstrBuilder MIB
=
1521 BuildMI(*MBB
, InsertPt
, Start
->getDebugLoc(), TII
->get(Opc
));
1523 MIB
.addDef(ARM::LR
);
1525 if (isWhileLoopStart(*Start
))
1526 MIB
.addMBB(getWhileLoopStartTargetBB(*Start
));
1528 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB
);
1532 LoLoop
.ToRemove
.insert(Start
);
1536 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop
&LoLoop
) {
1537 auto RemovePredicate
= [](MachineInstr
*MI
) {
1538 if (MI
->isDebugInstr())
1540 LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI
);
1541 int PIdx
= llvm::findFirstVPTPredOperandIdx(*MI
);
1542 assert(PIdx
>= 1 && "Trying to unpredicate a non-predicated instruction");
1543 assert(MI
->getOperand(PIdx
).getImm() == ARMVCC::Then
&&
1544 "Expected Then predicate!");
1545 MI
->getOperand(PIdx
).setImm(ARMVCC::None
);
1546 MI
->getOperand(PIdx
+ 1).setReg(0);
1549 for (auto &Block
: LoLoop
.getVPTBlocks()) {
1550 SmallVectorImpl
<MachineInstr
*> &Insts
= Block
.getInsts();
1552 auto ReplaceVCMPWithVPT
= [&](MachineInstr
*&TheVCMP
, MachineInstr
*At
) {
1553 assert(TheVCMP
&& "Replacing a removed or non-existent VCMP");
1554 // Replace the VCMP with a VPT
1555 MachineInstrBuilder MIB
=
1556 BuildMI(*At
->getParent(), At
, At
->getDebugLoc(),
1557 TII
->get(VCMPOpcodeToVPT(TheVCMP
->getOpcode())));
1558 MIB
.addImm(ARMVCC::Then
);
1560 MIB
.add(TheVCMP
->getOperand(1));
1562 MIB
.add(TheVCMP
->getOperand(2));
1563 // The comparison code, e.g. ge, eq, lt
1564 MIB
.add(TheVCMP
->getOperand(3));
1565 LLVM_DEBUG(dbgs() << "ARM Loops: Combining with VCMP to VPT: " << *MIB
);
1566 LoLoop
.BlockMasksToRecompute
.insert(MIB
.getInstr());
1567 LoLoop
.ToRemove
.insert(TheVCMP
);
1571 if (VPTState::isEntryPredicatedOnVCTP(Block
, /*exclusive*/ true)) {
1572 MachineInstr
*VPST
= Insts
.front();
1573 if (VPTState::hasUniformPredicate(Block
)) {
1574 // A vpt block starting with VPST, is only predicated upon vctp and has no
1575 // internal vpr defs:
1577 // - Unpredicate the remaining instructions.
1578 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST
);
1579 for (unsigned i
= 1; i
< Insts
.size(); ++i
)
1580 RemovePredicate(Insts
[i
]);
1582 // The VPT block has a non-uniform predicate but it uses a vpst and its
1583 // entry is guarded only by a vctp, which means we:
1584 // - Need to remove the original vpst.
1585 // - Then need to unpredicate any following instructions, until
1586 // we come across the divergent vpr def.
1587 // - Insert a new vpst to predicate the instruction(s) that following
1588 // the divergent vpr def.
1589 MachineInstr
*Divergent
= VPTState::getDivergent(Block
);
1590 MachineBasicBlock
*MBB
= Divergent
->getParent();
1591 auto DivergentNext
= ++MachineBasicBlock::iterator(Divergent
);
1592 while (DivergentNext
!= MBB
->end() && DivergentNext
->isDebugInstr())
1595 bool DivergentNextIsPredicated
=
1596 DivergentNext
!= MBB
->end() &&
1597 getVPTInstrPredicate(*DivergentNext
) != ARMVCC::None
;
1599 for (auto I
= ++MachineBasicBlock::iterator(VPST
), E
= DivergentNext
;
1601 RemovePredicate(&*I
);
1603 // Check if the instruction defining vpr is a vcmp so it can be combined
1604 // with the VPST This should be the divergent instruction
1605 MachineInstr
*VCMP
=
1606 VCMPOpcodeToVPT(Divergent
->getOpcode()) != 0 ? Divergent
: nullptr;
1608 if (DivergentNextIsPredicated
) {
1609 // Insert a VPST at the divergent only if the next instruction
1610 // would actually use it. A VCMP following a VPST can be
1611 // merged into a VPT so do that instead if the VCMP exists.
1613 // Create a VPST (with a null mask for now, we'll recompute it
1615 MachineInstrBuilder MIB
=
1616 BuildMI(*Divergent
->getParent(), Divergent
,
1617 Divergent
->getDebugLoc(), TII
->get(ARM::MVE_VPST
));
1619 LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB
);
1620 LoLoop
.BlockMasksToRecompute
.insert(MIB
.getInstr());
1622 // No RDA checks are necessary here since the VPST would have been
1623 // directly after the VCMP
1624 ReplaceVCMPWithVPT(VCMP
, VCMP
);
1628 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST
);
1629 LoLoop
.ToRemove
.insert(VPST
);
1630 } else if (Block
.containsVCTP()) {
1631 // The vctp will be removed, so either the entire block will be dead or
1632 // the block mask of the vp(s)t will need to be recomputed.
1633 MachineInstr
*VPST
= Insts
.front();
1634 if (Block
.size() == 2) {
1635 assert(VPST
->getOpcode() == ARM::MVE_VPST
&&
1636 "Found a VPST in an otherwise empty vpt block");
1637 LoLoop
.ToRemove
.insert(VPST
);
1639 LoLoop
.BlockMasksToRecompute
.insert(VPST
);
1640 } else if (Insts
.front()->getOpcode() == ARM::MVE_VPST
) {
1641 // If this block starts with a VPST then attempt to merge it with the
1642 // preceeding un-merged VCMP into a VPT. This VCMP comes from a VPT
1643 // block that no longer exists
1644 MachineInstr
*VPST
= Insts
.front();
1645 auto Next
= ++MachineBasicBlock::iterator(VPST
);
1646 assert(getVPTInstrPredicate(*Next
) != ARMVCC::None
&&
1647 "The instruction after a VPST must be predicated");
1649 MachineInstr
*VprDef
= RDA
->getUniqueReachingMIDef(VPST
, ARM::VPR
);
1650 if (VprDef
&& VCMPOpcodeToVPT(VprDef
->getOpcode()) &&
1651 !LoLoop
.ToRemove
.contains(VprDef
)) {
1652 MachineInstr
*VCMP
= VprDef
;
1653 // The VCMP and VPST can only be merged if the VCMP's operands will have
1654 // the same values at the VPST.
1655 // If any of the instructions between the VCMP and VPST are predicated
1656 // then a different code path is expected to have merged the VCMP and
1658 if (!std::any_of(++MachineBasicBlock::iterator(VCMP
),
1659 MachineBasicBlock::iterator(VPST
), hasVPRUse
) &&
1660 RDA
->hasSameReachingDef(VCMP
, VPST
, VCMP
->getOperand(1).getReg()) &&
1661 RDA
->hasSameReachingDef(VCMP
, VPST
, VCMP
->getOperand(2).getReg())) {
1662 ReplaceVCMPWithVPT(VCMP
, VPST
);
1663 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST
);
1664 LoLoop
.ToRemove
.insert(VPST
);
1670 LoLoop
.ToRemove
.insert(LoLoop
.VCTPs
.begin(), LoLoop
.VCTPs
.end());
1673 void ARMLowOverheadLoops::Expand(LowOverheadLoop
&LoLoop
) {
1675 // Combine the LoopDec and LoopEnd instructions into LE(TP).
1676 auto ExpandLoopEnd
= [this](LowOverheadLoop
&LoLoop
) {
1677 MachineInstr
*End
= LoLoop
.End
;
1678 MachineBasicBlock
*MBB
= End
->getParent();
1679 unsigned Opc
= LoLoop
.IsTailPredicationLegal() ?
1680 ARM::MVE_LETP
: ARM::t2LEUpdate
;
1681 MachineInstrBuilder MIB
= BuildMI(*MBB
, End
, End
->getDebugLoc(),
1683 MIB
.addDef(ARM::LR
);
1684 unsigned Off
= LoLoop
.Dec
== LoLoop
.End
? 1 : 0;
1685 MIB
.add(End
->getOperand(Off
+ 0));
1686 MIB
.add(End
->getOperand(Off
+ 1));
1687 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB
);
1688 LoLoop
.ToRemove
.insert(LoLoop
.Dec
);
1689 LoLoop
.ToRemove
.insert(End
);
1693 // TODO: We should be able to automatically remove these branches before we
1694 // get here - probably by teaching analyzeBranch about the pseudo
1696 // If there is an unconditional branch, after I, that just branches to the
1697 // next block, remove it.
1698 auto RemoveDeadBranch
= [](MachineInstr
*I
) {
1699 MachineBasicBlock
*BB
= I
->getParent();
1700 MachineInstr
*Terminator
= &BB
->instr_back();
1701 if (Terminator
->isUnconditionalBranch() && I
!= Terminator
) {
1702 MachineBasicBlock
*Succ
= Terminator
->getOperand(0).getMBB();
1703 if (BB
->isLayoutSuccessor(Succ
)) {
1704 LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator
);
1705 Terminator
->eraseFromParent();
1710 if (LoLoop
.Revert
) {
1711 if (isWhileLoopStart(*LoLoop
.Start
))
1712 RevertWhile(LoLoop
.Start
);
1714 RevertDo(LoLoop
.Start
);
1715 if (LoLoop
.Dec
== LoLoop
.End
)
1716 RevertLoopEndDec(LoLoop
.End
);
1718 RevertLoopEnd(LoLoop
.End
, RevertLoopDec(LoLoop
.Dec
));
1720 LoLoop
.Start
= ExpandLoopStart(LoLoop
);
1722 RemoveDeadBranch(LoLoop
.Start
);
1723 LoLoop
.End
= ExpandLoopEnd(LoLoop
);
1724 RemoveDeadBranch(LoLoop
.End
);
1725 if (LoLoop
.IsTailPredicationLegal())
1726 ConvertVPTBlocks(LoLoop
);
1727 for (auto *I
: LoLoop
.ToRemove
) {
1728 LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I
);
1729 I
->eraseFromParent();
1731 for (auto *I
: LoLoop
.BlockMasksToRecompute
) {
1732 LLVM_DEBUG(dbgs() << "ARM Loops: Recomputing VPT/VPST Block Mask: " << *I
);
1733 recomputeVPTBlockMask(*I
);
1734 LLVM_DEBUG(dbgs() << " ... done: " << *I
);
1738 PostOrderLoopTraversal
DFS(LoLoop
.ML
, *MLI
);
1740 const SmallVectorImpl
<MachineBasicBlock
*> &PostOrder
= DFS
.getOrder();
1741 for (auto *MBB
: PostOrder
) {
1742 recomputeLiveIns(*MBB
);
1743 // FIXME: For some reason, the live-in print order is non-deterministic for
1744 // our tests and I can't out why... So just sort them.
1745 MBB
->sortUniqueLiveIns();
1748 for (auto *MBB
: reverse(PostOrder
))
1749 recomputeLivenessFlags(*MBB
);
1751 // We've moved, removed and inserted new instructions, so update RDA.
1755 bool ARMLowOverheadLoops::RevertNonLoops() {
1756 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
1757 bool Changed
= false;
1759 for (auto &MBB
: *MF
) {
1760 SmallVector
<MachineInstr
*, 4> Starts
;
1761 SmallVector
<MachineInstr
*, 4> Decs
;
1762 SmallVector
<MachineInstr
*, 4> Ends
;
1763 SmallVector
<MachineInstr
*, 4> EndDecs
;
1765 for (auto &I
: MBB
) {
1767 Starts
.push_back(&I
);
1768 else if (I
.getOpcode() == ARM::t2LoopDec
)
1770 else if (I
.getOpcode() == ARM::t2LoopEnd
)
1772 else if (I
.getOpcode() == ARM::t2LoopEndDec
)
1773 EndDecs
.push_back(&I
);
1776 if (Starts
.empty() && Decs
.empty() && Ends
.empty() && EndDecs
.empty())
1781 for (auto *Start
: Starts
) {
1782 if (isWhileLoopStart(*Start
))
1787 for (auto *Dec
: Decs
)
1790 for (auto *End
: Ends
)
1792 for (auto *End
: EndDecs
)
1793 RevertLoopEndDec(End
);
1798 FunctionPass
*llvm::createARMLowOverheadLoopsPass() {
1799 return new ARMLowOverheadLoops();