xref: /llvm-project/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp (revision 02cd8a6b915a9dab32fdd91167f875ce5f67ebd4)
1 //===-- ARMLowOverheadLoops.cpp - CodeGen Low-overhead Loops ---*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
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.
17 ///
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
20 /// loop form.
21 ///
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
36 /// instructions.
37 ///
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:
43 /// \verbatim
44 /// if VPT active:    ; Between a DLSTP/LETP, or for predicated instrs
45 ///   VPR.P0 &= Value
46 /// else
47 ///   VPR.P0 = Value
48 /// \endverbatim
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 //===----------------------------------------------------------------------===//
53 
54 #include "ARM.h"
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"
71 
72 using namespace llvm;
73 
74 #define DEBUG_TYPE "arm-low-overhead-loops"
75 #define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
76 
77 static cl::opt<bool>
78 DisableTailPredication("arm-loloops-disable-tailpred", cl::Hidden,
79     cl::desc("Disable tail-predication in the ARM LowOverheadLoop pass"),
80     cl::init(false));
81 
82 static bool isVectorPredicated(MachineInstr *MI) {
83   int PIdx = llvm::findFirstVPTPredOperandIdx(*MI);
84   return PIdx != -1 && MI->getOperand(PIdx + 1).getReg() == ARM::VPR;
85 }
86 
87 static bool isVectorPredicate(MachineInstr *MI) {
88   return MI->findRegisterDefOperandIdx(ARM::VPR) != -1;
89 }
90 
91 static bool hasVPRUse(MachineInstr &MI) {
92   return MI.findRegisterUseOperandIdx(ARM::VPR) != -1;
93 }
94 
95 static bool isDomainMVE(MachineInstr *MI) {
96   uint64_t Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
97   return Domain == ARMII::DomainMVE;
98 }
99 
100 static int getVecSize(const MachineInstr &MI) {
101   const MCInstrDesc &MCID = MI.getDesc();
102   uint64_t Flags = MCID.TSFlags;
103   return (Flags & ARMII::VecSize) >> ARMII::VecSizeShift;
104 }
105 
106 static bool shouldInspect(MachineInstr &MI) {
107   if (MI.isDebugInstr())
108     return false;
109   return isDomainMVE(&MI) || isVectorPredicate(&MI) || hasVPRUse(MI);
110 }
111 
112 namespace {
113 
114   using InstSet = SmallPtrSetImpl<MachineInstr *>;
115 
116   class PostOrderLoopTraversal {
117     MachineLoop &ML;
118     MachineLoopInfo &MLI;
119     SmallPtrSet<MachineBasicBlock*, 4> Visited;
120     SmallVector<MachineBasicBlock*, 4> Order;
121 
122   public:
123     PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI)
124       : ML(ML), MLI(MLI) { }
125 
126     const SmallVectorImpl<MachineBasicBlock*> &getOrder() const {
127       return Order;
128     }
129 
130     // Visit all the blocks within the loop, as well as exit blocks and any
131     // blocks properly dominating the header.
132     void ProcessLoop() {
133       std::function<void(MachineBasicBlock*)> Search = [this, &Search]
134         (MachineBasicBlock *MBB) -> void {
135         if (Visited.count(MBB))
136           return;
137 
138         Visited.insert(MBB);
139         for (auto *Succ : MBB->successors()) {
140           if (!ML.contains(Succ))
141             continue;
142           Search(Succ);
143         }
144         Order.push_back(MBB);
145       };
146 
147       // Insert exit blocks.
148       SmallVector<MachineBasicBlock*, 2> ExitBlocks;
149       ML.getExitBlocks(ExitBlocks);
150       append_range(Order, ExitBlocks);
151 
152       // Then add the loop body.
153       Search(ML.getHeader());
154 
155       // Then try the preheader and its predecessors.
156       std::function<void(MachineBasicBlock*)> GetPredecessor =
157         [this, &GetPredecessor] (MachineBasicBlock *MBB) -> void {
158         Order.push_back(MBB);
159         if (MBB->pred_size() == 1)
160           GetPredecessor(*MBB->pred_begin());
161       };
162 
163       if (auto *Preheader = ML.getLoopPreheader())
164         GetPredecessor(Preheader);
165       else if (auto *Preheader = MLI.findLoopPreheader(&ML, true, true))
166         GetPredecessor(Preheader);
167     }
168   };
169 
170   struct PredicatedMI {
171     MachineInstr *MI = nullptr;
172     SetVector<MachineInstr*> Predicates;
173 
174   public:
175     PredicatedMI(MachineInstr *I, SetVector<MachineInstr *> &Preds) : MI(I) {
176       assert(I && "Instruction must not be null!");
177       Predicates.insert(Preds.begin(), Preds.end());
178     }
179   };
180 
181   // Represent the current state of the VPR and hold all instances which
182   // represent a VPT block, which is a list of instructions that begins with a
183   // VPT/VPST and has a maximum of four proceeding instructions. All
184   // instructions within the block are predicated upon the vpr and we allow
185   // instructions to define the vpr within in the block too.
186   class VPTState {
187     friend struct LowOverheadLoop;
188 
189     SmallVector<MachineInstr *, 4> Insts;
190 
191     static SmallVector<VPTState, 4> Blocks;
192     static SetVector<MachineInstr *> CurrentPredicates;
193     static std::map<MachineInstr *,
194       std::unique_ptr<PredicatedMI>> PredicatedInsts;
195 
196     static void CreateVPTBlock(MachineInstr *MI) {
197       assert((CurrentPredicates.size() || MI->getParent()->isLiveIn(ARM::VPR))
198              && "Can't begin VPT without predicate");
199       Blocks.emplace_back(MI);
200       // The execution of MI is predicated upon the current set of instructions
201       // that are AND'ed together to form the VPR predicate value. In the case
202       // that MI is a VPT, CurrentPredicates will also just be MI.
203       PredicatedInsts.emplace(
204         MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates));
205     }
206 
207     static void reset() {
208       Blocks.clear();
209       PredicatedInsts.clear();
210       CurrentPredicates.clear();
211     }
212 
213     static void addInst(MachineInstr *MI) {
214       Blocks.back().insert(MI);
215       PredicatedInsts.emplace(
216         MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates));
217     }
218 
219     static void addPredicate(MachineInstr *MI) {
220       LLVM_DEBUG(dbgs() << "ARM Loops: Adding VPT Predicate: " << *MI);
221       CurrentPredicates.insert(MI);
222     }
223 
224     static void resetPredicate(MachineInstr *MI) {
225       LLVM_DEBUG(dbgs() << "ARM Loops: Resetting VPT Predicate: " << *MI);
226       CurrentPredicates.clear();
227       CurrentPredicates.insert(MI);
228     }
229 
230   public:
231     // Have we found an instruction within the block which defines the vpr? If
232     // so, not all the instructions in the block will have the same predicate.
233     static bool hasUniformPredicate(VPTState &Block) {
234       return getDivergent(Block) == nullptr;
235     }
236 
237     // If it exists, return the first internal instruction which modifies the
238     // VPR.
239     static MachineInstr *getDivergent(VPTState &Block) {
240       SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
241       for (unsigned i = 1; i < Insts.size(); ++i) {
242         MachineInstr *Next = Insts[i];
243         if (isVectorPredicate(Next))
244           return Next; // Found an instruction altering the vpr.
245       }
246       return nullptr;
247     }
248 
249     // Return whether the given instruction is predicated upon a VCTP.
250     static bool isPredicatedOnVCTP(MachineInstr *MI, bool Exclusive = false) {
251       SetVector<MachineInstr *> &Predicates = PredicatedInsts[MI]->Predicates;
252       if (Exclusive && Predicates.size() != 1)
253         return false;
254       for (auto *PredMI : Predicates)
255         if (isVCTP(PredMI))
256           return true;
257       return false;
258     }
259 
260     // Is the VPST, controlling the block entry, predicated upon a VCTP.
261     static bool isEntryPredicatedOnVCTP(VPTState &Block,
262                                         bool Exclusive = false) {
263       SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
264       return isPredicatedOnVCTP(Insts.front(), Exclusive);
265     }
266 
267     // If this block begins with a VPT, we can check whether it's using
268     // at least one predicated input(s), as well as possible loop invariant
269     // which would result in it being implicitly predicated.
270     static bool hasImplicitlyValidVPT(VPTState &Block,
271                                       ReachingDefAnalysis &RDA) {
272       SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
273       MachineInstr *VPT = Insts.front();
274       assert(isVPTOpcode(VPT->getOpcode()) &&
275              "Expected VPT block to begin with VPT/VPST");
276 
277       if (VPT->getOpcode() == ARM::MVE_VPST)
278         return false;
279 
280       auto IsOperandPredicated = [&](MachineInstr *MI, unsigned Idx) {
281         MachineInstr *Op = RDA.getMIOperand(MI, MI->getOperand(Idx));
282         return Op && PredicatedInsts.count(Op) && isPredicatedOnVCTP(Op);
283       };
284 
285       auto IsOperandInvariant = [&](MachineInstr *MI, unsigned Idx) {
286         MachineOperand &MO = MI->getOperand(Idx);
287         if (!MO.isReg() || !MO.getReg())
288           return true;
289 
290         SmallPtrSet<MachineInstr *, 2> Defs;
291         RDA.getGlobalReachingDefs(MI, MO.getReg(), Defs);
292         if (Defs.empty())
293           return true;
294 
295         for (auto *Def : Defs)
296           if (Def->getParent() == VPT->getParent())
297             return false;
298         return true;
299       };
300 
301       // Check that at least one of the operands is directly predicated on a
302       // vctp and allow an invariant value too.
303       return (IsOperandPredicated(VPT, 1) || IsOperandPredicated(VPT, 2)) &&
304              (IsOperandPredicated(VPT, 1) || IsOperandInvariant(VPT, 1)) &&
305              (IsOperandPredicated(VPT, 2) || IsOperandInvariant(VPT, 2));
306     }
307 
308     static bool isValid(ReachingDefAnalysis &RDA) {
309       // All predication within the loop should be based on vctp. If the block
310       // isn't predicated on entry, check whether the vctp is within the block
311       // and that all other instructions are then predicated on it.
312       for (auto &Block : Blocks) {
313         if (isEntryPredicatedOnVCTP(Block, false) ||
314             hasImplicitlyValidVPT(Block, RDA))
315           continue;
316 
317         SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
318         // We don't know how to convert a block with just a VPT;VCTP into
319         // anything valid once we remove the VCTP. For now just bail out.
320         assert(isVPTOpcode(Insts.front()->getOpcode()) &&
321                "Expected VPT block to start with a VPST or VPT!");
322         if (Insts.size() == 2 && Insts.front()->getOpcode() != ARM::MVE_VPST &&
323             isVCTP(Insts.back()))
324           return false;
325 
326         for (auto *MI : Insts) {
327           // Check that any internal VCTPs are 'Then' predicated.
328           if (isVCTP(MI) && getVPTInstrPredicate(*MI) != ARMVCC::Then)
329             return false;
330           // Skip other instructions that build up the predicate.
331           if (MI->getOpcode() == ARM::MVE_VPST || isVectorPredicate(MI))
332             continue;
333           // Check that any other instructions are predicated upon a vctp.
334           // TODO: We could infer when VPTs are implicitly predicated on the
335           // vctp (when the operands are predicated).
336           if (!isPredicatedOnVCTP(MI)) {
337             LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *MI);
338             return false;
339           }
340         }
341       }
342       return true;
343     }
344 
345     VPTState(MachineInstr *MI) { Insts.push_back(MI); }
346 
347     void insert(MachineInstr *MI) {
348       Insts.push_back(MI);
349       // VPT/VPST + 4 predicated instructions.
350       assert(Insts.size() <= 5 && "Too many instructions in VPT block!");
351     }
352 
353     bool containsVCTP() const {
354       for (auto *MI : Insts)
355         if (isVCTP(MI))
356           return true;
357       return false;
358     }
359 
360     unsigned size() const { return Insts.size(); }
361     SmallVectorImpl<MachineInstr *> &getInsts() { return Insts; }
362   };
363 
364   struct LowOverheadLoop {
365 
366     MachineLoop &ML;
367     MachineBasicBlock *Preheader = nullptr;
368     MachineLoopInfo &MLI;
369     ReachingDefAnalysis &RDA;
370     const TargetRegisterInfo &TRI;
371     const ARMBaseInstrInfo &TII;
372     MachineFunction *MF = nullptr;
373     MachineBasicBlock::iterator StartInsertPt;
374     MachineBasicBlock *StartInsertBB = nullptr;
375     MachineInstr *Start = nullptr;
376     MachineInstr *Dec = nullptr;
377     MachineInstr *End = nullptr;
378     MachineOperand TPNumElements;
379     SmallVector<MachineInstr*, 4> VCTPs;
380     SmallPtrSet<MachineInstr*, 4> ToRemove;
381     SmallPtrSet<MachineInstr*, 4> BlockMasksToRecompute;
382     SmallPtrSet<MachineInstr*, 4> DoubleWidthResultInstrs;
383     bool Revert = false;
384     bool CannotTailPredicate = false;
385 
386     LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI,
387                     ReachingDefAnalysis &RDA, const TargetRegisterInfo &TRI,
388                     const ARMBaseInstrInfo &TII)
389         : ML(ML), MLI(MLI), RDA(RDA), TRI(TRI), TII(TII),
390           TPNumElements(MachineOperand::CreateImm(0)) {
391       MF = ML.getHeader()->getParent();
392       if (auto *MBB = ML.getLoopPreheader())
393         Preheader = MBB;
394       else if (auto *MBB = MLI.findLoopPreheader(&ML, true, true))
395         Preheader = MBB;
396       VPTState::reset();
397     }
398 
399     // If this is an MVE instruction, check that we know how to use tail
400     // predication with it. Record VPT blocks and return whether the
401     // instruction is valid for tail predication.
402     bool ValidateMVEInst(MachineInstr *MI);
403 
404     void AnalyseMVEInst(MachineInstr *MI) {
405       CannotTailPredicate = !ValidateMVEInst(MI);
406     }
407 
408     bool IsTailPredicationLegal() const {
409       // For now, let's keep things really simple and only support a single
410       // block for tail predication.
411       return !Revert && FoundAllComponents() && !VCTPs.empty() &&
412              !CannotTailPredicate && ML.getNumBlocks() == 1;
413     }
414 
415     // Given that MI is a VCTP, check that is equivalent to any other VCTPs
416     // found.
417     bool AddVCTP(MachineInstr *MI);
418 
419     // Check that the predication in the loop will be equivalent once we
420     // perform the conversion. Also ensure that we can provide the number
421     // of elements to the loop start instruction.
422     bool ValidateTailPredicate();
423 
424     // Check that any values available outside of the loop will be the same
425     // after tail predication conversion.
426     bool ValidateLiveOuts();
427 
428     // Is it safe to define LR with DLS/WLS?
429     // LR can be defined if it is the operand to start, because it's the same
430     // value, or if it's going to be equivalent to the operand to Start.
431     MachineInstr *isSafeToDefineLR();
432 
433     // Check the branch targets are within range and we satisfy our
434     // restrictions.
435     void Validate(ARMBasicBlockUtils *BBUtils);
436 
437     bool FoundAllComponents() const {
438       return Start && Dec && End;
439     }
440 
441     SmallVectorImpl<VPTState> &getVPTBlocks() {
442       return VPTState::Blocks;
443     }
444 
445     // Return the operand for the loop start instruction. This will be the loop
446     // iteration count, or the number of elements if we're tail predicating.
447     MachineOperand &getLoopStartOperand() {
448       if (IsTailPredicationLegal())
449         return TPNumElements;
450       return Start->getOperand(1);
451     }
452 
453     unsigned getStartOpcode() const {
454       bool IsDo = isDoLoopStart(*Start);
455       if (!IsTailPredicationLegal())
456         return IsDo ? ARM::t2DLS : ARM::t2WLS;
457 
458       return VCTPOpcodeToLSTP(VCTPs.back()->getOpcode(), IsDo);
459     }
460 
461     void dump() const {
462       if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start;
463       if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec;
464       if (End) dbgs() << "ARM Loops: Found Loop End: " << *End;
465       if (!VCTPs.empty()) {
466         dbgs() << "ARM Loops: Found VCTP(s):\n";
467         for (auto *MI : VCTPs)
468           dbgs() << " - " << *MI;
469       }
470       if (!FoundAllComponents())
471         dbgs() << "ARM Loops: Not a low-overhead loop.\n";
472       else if (!(Start && Dec && End))
473         dbgs() << "ARM Loops: Failed to find all loop components.\n";
474     }
475   };
476 
477   class ARMLowOverheadLoops : public MachineFunctionPass {
478     MachineFunction           *MF = nullptr;
479     MachineLoopInfo           *MLI = nullptr;
480     ReachingDefAnalysis       *RDA = nullptr;
481     const ARMBaseInstrInfo    *TII = nullptr;
482     MachineRegisterInfo       *MRI = nullptr;
483     const TargetRegisterInfo  *TRI = nullptr;
484     std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
485 
486   public:
487     static char ID;
488 
489     ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
490 
491     void getAnalysisUsage(AnalysisUsage &AU) const override {
492       AU.setPreservesCFG();
493       AU.addRequired<MachineLoopInfo>();
494       AU.addRequired<ReachingDefAnalysis>();
495       MachineFunctionPass::getAnalysisUsage(AU);
496     }
497 
498     bool runOnMachineFunction(MachineFunction &MF) override;
499 
500     MachineFunctionProperties getRequiredProperties() const override {
501       return MachineFunctionProperties().set(
502           MachineFunctionProperties::Property::NoVRegs).set(
503           MachineFunctionProperties::Property::TracksLiveness);
504     }
505 
506     StringRef getPassName() const override {
507       return ARM_LOW_OVERHEAD_LOOPS_NAME;
508     }
509 
510   private:
511     bool ProcessLoop(MachineLoop *ML);
512 
513     bool RevertNonLoops();
514 
515     void RevertWhile(MachineInstr *MI) const;
516     void RevertDo(MachineInstr *MI) const;
517 
518     bool RevertLoopDec(MachineInstr *MI) const;
519 
520     void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const;
521 
522     void RevertLoopEndDec(MachineInstr *MI) const;
523 
524     void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
525 
526     MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
527 
528     void Expand(LowOverheadLoop &LoLoop);
529 
530     void IterationCountDCE(LowOverheadLoop &LoLoop);
531   };
532 }
533 
534 char ARMLowOverheadLoops::ID = 0;
535 
536 SmallVector<VPTState, 4> VPTState::Blocks;
537 SetVector<MachineInstr *> VPTState::CurrentPredicates;
538 std::map<MachineInstr *,
539          std::unique_ptr<PredicatedMI>> VPTState::PredicatedInsts;
540 
541 INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME,
542                 false, false)
543 
544 static bool TryRemove(MachineInstr *MI, ReachingDefAnalysis &RDA,
545                       InstSet &ToRemove, InstSet &Ignore) {
546 
547   // Check that we can remove all of Killed without having to modify any IT
548   // blocks.
549   auto WontCorruptITs = [](InstSet &Killed, ReachingDefAnalysis &RDA) {
550     // Collect the dead code and the MBBs in which they reside.
551     SmallPtrSet<MachineBasicBlock*, 2> BasicBlocks;
552     for (auto *Dead : Killed)
553       BasicBlocks.insert(Dead->getParent());
554 
555     // Collect IT blocks in all affected basic blocks.
556     std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks;
557     for (auto *MBB : BasicBlocks) {
558       for (auto &IT : *MBB) {
559         if (IT.getOpcode() != ARM::t2IT)
560           continue;
561         RDA.getReachingLocalUses(&IT, MCRegister::from(ARM::ITSTATE),
562                                  ITBlocks[&IT]);
563       }
564     }
565 
566     // If we're removing all of the instructions within an IT block, then
567     // also remove the IT instruction.
568     SmallPtrSet<MachineInstr *, 2> ModifiedITs;
569     SmallPtrSet<MachineInstr *, 2> RemoveITs;
570     for (auto *Dead : Killed) {
571       if (MachineOperand *MO = Dead->findRegisterUseOperand(ARM::ITSTATE)) {
572         MachineInstr *IT = RDA.getMIOperand(Dead, *MO);
573         RemoveITs.insert(IT);
574         auto &CurrentBlock = ITBlocks[IT];
575         CurrentBlock.erase(Dead);
576         if (CurrentBlock.empty())
577           ModifiedITs.erase(IT);
578         else
579           ModifiedITs.insert(IT);
580       }
581     }
582     if (!ModifiedITs.empty())
583       return false;
584     Killed.insert(RemoveITs.begin(), RemoveITs.end());
585     return true;
586   };
587 
588   SmallPtrSet<MachineInstr *, 2> Uses;
589   if (!RDA.isSafeToRemove(MI, Uses, Ignore))
590     return false;
591 
592   if (WontCorruptITs(Uses, RDA)) {
593     ToRemove.insert(Uses.begin(), Uses.end());
594     LLVM_DEBUG(dbgs() << "ARM Loops: Able to remove: " << *MI
595                << " - can also remove:\n";
596                for (auto *Use : Uses)
597                  dbgs() << "   - " << *Use);
598 
599     SmallPtrSet<MachineInstr*, 4> Killed;
600     RDA.collectKilledOperands(MI, Killed);
601     if (WontCorruptITs(Killed, RDA)) {
602       ToRemove.insert(Killed.begin(), Killed.end());
603       LLVM_DEBUG(for (auto *Dead : Killed)
604                    dbgs() << "   - " << *Dead);
605     }
606     return true;
607   }
608   return false;
609 }
610 
611 bool LowOverheadLoop::ValidateTailPredicate() {
612   if (!IsTailPredicationLegal()) {
613     LLVM_DEBUG(if (VCTPs.empty())
614                  dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
615                dbgs() << "ARM Loops: Tail-predication is not valid.\n");
616     return false;
617   }
618 
619   assert(!VCTPs.empty() && "VCTP instruction expected but is not set");
620   assert(ML.getBlocks().size() == 1 &&
621          "Shouldn't be processing a loop with more than one block");
622 
623   if (DisableTailPredication) {
624     LLVM_DEBUG(dbgs() << "ARM Loops: tail-predication is disabled\n");
625     return false;
626   }
627 
628   if (!VPTState::isValid(RDA)) {
629     LLVM_DEBUG(dbgs() << "ARM Loops: Invalid VPT state.\n");
630     return false;
631   }
632 
633   if (!ValidateLiveOuts()) {
634     LLVM_DEBUG(dbgs() << "ARM Loops: Invalid live outs.\n");
635     return false;
636   }
637 
638   // For tail predication, we need to provide the number of elements, instead
639   // of the iteration count, to the loop start instruction. The number of
640   // elements is provided to the vctp instruction, so we need to check that
641   // we can use this register at InsertPt.
642   MachineInstr *VCTP = VCTPs.back();
643   if (Start->getOpcode() == ARM::t2DoLoopStartTP ||
644       Start->getOpcode() == ARM::t2WhileLoopStartTP) {
645     TPNumElements = Start->getOperand(2);
646     StartInsertPt = Start;
647     StartInsertBB = Start->getParent();
648   } else {
649     TPNumElements = VCTP->getOperand(1);
650     MCRegister NumElements = TPNumElements.getReg().asMCReg();
651 
652     // If the register is defined within loop, then we can't perform TP.
653     // TODO: Check whether this is just a mov of a register that would be
654     // available.
655     if (RDA.hasLocalDefBefore(VCTP, NumElements)) {
656       LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
657       return false;
658     }
659 
660     // The element count register maybe defined after InsertPt, in which case we
661     // need to try to move either InsertPt or the def so that the [w|d]lstp can
662     // use the value.
663 
664     if (StartInsertPt != StartInsertBB->end() &&
665         !RDA.isReachingDefLiveOut(&*StartInsertPt, NumElements)) {
666       if (auto *ElemDef =
667               RDA.getLocalLiveOutMIDef(StartInsertBB, NumElements)) {
668         if (RDA.isSafeToMoveForwards(ElemDef, &*StartInsertPt)) {
669           ElemDef->removeFromParent();
670           StartInsertBB->insert(StartInsertPt, ElemDef);
671           LLVM_DEBUG(dbgs()
672                      << "ARM Loops: Moved element count def: " << *ElemDef);
673         } else if (RDA.isSafeToMoveBackwards(&*StartInsertPt, ElemDef)) {
674           StartInsertPt->removeFromParent();
675           StartInsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef),
676                                      &*StartInsertPt);
677           LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef);
678         } else {
679           // If we fail to move an instruction and the element count is provided
680           // by a mov, use the mov operand if it will have the same value at the
681           // insertion point
682           MachineOperand Operand = ElemDef->getOperand(1);
683           if (isMovRegOpcode(ElemDef->getOpcode()) &&
684               RDA.getUniqueReachingMIDef(ElemDef, Operand.getReg().asMCReg()) ==
685                   RDA.getUniqueReachingMIDef(&*StartInsertPt,
686                                              Operand.getReg().asMCReg())) {
687             TPNumElements = Operand;
688             NumElements = TPNumElements.getReg();
689           } else {
690             LLVM_DEBUG(dbgs()
691                        << "ARM Loops: Unable to move element count to loop "
692                        << "start instruction.\n");
693             return false;
694           }
695         }
696       }
697     }
698 
699     // Especially in the case of while loops, InsertBB may not be the
700     // preheader, so we need to check that the register isn't redefined
701     // before entering the loop.
702     auto CannotProvideElements = [this](MachineBasicBlock *MBB,
703                                         MCRegister NumElements) {
704       if (MBB->empty())
705         return false;
706       // NumElements is redefined in this block.
707       if (RDA.hasLocalDefBefore(&MBB->back(), NumElements))
708         return true;
709 
710       // Don't continue searching up through multiple predecessors.
711       if (MBB->pred_size() > 1)
712         return true;
713 
714       return false;
715     };
716 
717     // Search backwards for a def, until we get to InsertBB.
718     MachineBasicBlock *MBB = Preheader;
719     while (MBB && MBB != StartInsertBB) {
720       if (CannotProvideElements(MBB, NumElements)) {
721         LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
722         return false;
723       }
724       MBB = *MBB->pred_begin();
725     }
726   }
727 
728   // Could inserting the [W|D]LSTP cause some unintended affects? In a perfect
729   // world the [w|d]lstp instruction would be last instruction in the preheader
730   // and so it would only affect instructions within the loop body. But due to
731   // scheduling, and/or the logic in this pass (above), the insertion point can
732   // be moved earlier. So if the Loop Start isn't the last instruction in the
733   // preheader, and if the initial element count is smaller than the vector
734   // width, the Loop Start instruction will immediately generate one or more
735   // false lane mask which can, incorrectly, affect the proceeding MVE
736   // instructions in the preheader.
737   if (std::any_of(StartInsertPt, StartInsertBB->end(), shouldInspect)) {
738     LLVM_DEBUG(dbgs() << "ARM Loops: Instruction blocks [W|D]LSTP\n");
739     return false;
740   }
741 
742   // For any DoubleWidthResultInstrs we found whilst scanning instructions, they
743   // need to compute an output size that is smaller than the VCTP mask operates
744   // on. The VecSize of the DoubleWidthResult is the larger vector size - the
745   // size it extends into, so any VCTP VecSize <= is valid.
746   unsigned VCTPVecSize = getVecSize(*VCTP);
747   for (MachineInstr *MI : DoubleWidthResultInstrs) {
748     unsigned InstrVecSize = getVecSize(*MI);
749     if (InstrVecSize > VCTPVecSize) {
750       LLVM_DEBUG(dbgs() << "ARM Loops: Double width result larger than VCTP "
751                         << "VecSize:\n" << *MI);
752       return false;
753     }
754   }
755 
756   // Check that the value change of the element count is what we expect and
757   // that the predication will be equivalent. For this we need:
758   // NumElements = NumElements - VectorWidth. The sub will be a sub immediate
759   // and we can also allow register copies within the chain too.
760   auto IsValidSub = [](MachineInstr *MI, int ExpectedVecWidth) {
761     return -getAddSubImmediate(*MI) == ExpectedVecWidth;
762   };
763 
764   MachineBasicBlock *MBB = VCTP->getParent();
765   // Remove modifications to the element count since they have no purpose in a
766   // tail predicated loop. Explicitly refer to the vctp operand no matter which
767   // register NumElements has been assigned to, since that is what the
768   // modifications will be using
769   if (auto *Def = RDA.getUniqueReachingMIDef(
770           &MBB->back(), VCTP->getOperand(1).getReg().asMCReg())) {
771     SmallPtrSet<MachineInstr*, 2> ElementChain;
772     SmallPtrSet<MachineInstr*, 2> Ignore;
773     unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode());
774 
775     Ignore.insert(VCTPs.begin(), VCTPs.end());
776 
777     if (TryRemove(Def, RDA, ElementChain, Ignore)) {
778       bool FoundSub = false;
779 
780       for (auto *MI : ElementChain) {
781         if (isMovRegOpcode(MI->getOpcode()))
782           continue;
783 
784         if (isSubImmOpcode(MI->getOpcode())) {
785           if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth)) {
786             LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
787                        " count: " << *MI);
788             return false;
789           }
790           FoundSub = true;
791         } else {
792           LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
793                      " count: " << *MI);
794           return false;
795         }
796       }
797       ToRemove.insert(ElementChain.begin(), ElementChain.end());
798     }
799   }
800 
801   // If we converted the LoopStart to a t2DoLoopStartTP/t2WhileLoopStartTP, we
802   // can also remove any extra instructions in the preheader, which often
803   // includes a now unused MOV.
804   if ((Start->getOpcode() == ARM::t2DoLoopStartTP ||
805        Start->getOpcode() == ARM::t2WhileLoopStartTP) &&
806       Preheader && !Preheader->empty() &&
807       !RDA.hasLocalDefBefore(VCTP, VCTP->getOperand(1).getReg())) {
808     if (auto *Def = RDA.getUniqueReachingMIDef(
809             &Preheader->back(), VCTP->getOperand(1).getReg().asMCReg())) {
810       SmallPtrSet<MachineInstr*, 2> Ignore;
811       Ignore.insert(VCTPs.begin(), VCTPs.end());
812       TryRemove(Def, RDA, ToRemove, Ignore);
813     }
814   }
815 
816   return true;
817 }
818 
819 static bool isRegInClass(const MachineOperand &MO,
820                          const TargetRegisterClass *Class) {
821   return MO.isReg() && MO.getReg() && Class->contains(MO.getReg());
822 }
823 
824 // MVE 'narrowing' operate on half a lane, reading from half and writing
825 // to half, which are referred to has the top and bottom half. The other
826 // half retains its previous value.
827 static bool retainsPreviousHalfElement(const MachineInstr &MI) {
828   const MCInstrDesc &MCID = MI.getDesc();
829   uint64_t Flags = MCID.TSFlags;
830   return (Flags & ARMII::RetainsPreviousHalfElement) != 0;
831 }
832 
833 // Some MVE instructions read from the top/bottom halves of their operand(s)
834 // and generate a vector result with result elements that are double the
835 // width of the input.
836 static bool producesDoubleWidthResult(const MachineInstr &MI) {
837   const MCInstrDesc &MCID = MI.getDesc();
838   uint64_t Flags = MCID.TSFlags;
839   return (Flags & ARMII::DoubleWidthResult) != 0;
840 }
841 
842 static bool isHorizontalReduction(const MachineInstr &MI) {
843   const MCInstrDesc &MCID = MI.getDesc();
844   uint64_t Flags = MCID.TSFlags;
845   return (Flags & ARMII::HorizontalReduction) != 0;
846 }
847 
848 // Can this instruction generate a non-zero result when given only zeroed
849 // operands? This allows us to know that, given operands with false bytes
850 // zeroed by masked loads, that the result will also contain zeros in those
851 // bytes.
852 static bool canGenerateNonZeros(const MachineInstr &MI) {
853 
854   // Check for instructions which can write into a larger element size,
855   // possibly writing into a previous zero'd lane.
856   if (producesDoubleWidthResult(MI))
857     return true;
858 
859   switch (MI.getOpcode()) {
860   default:
861     break;
862   // FIXME: VNEG FP and -0? I think we'll need to handle this once we allow
863   // fp16 -> fp32 vector conversions.
864   // Instructions that perform a NOT will generate 1s from 0s.
865   case ARM::MVE_VMVN:
866   case ARM::MVE_VORN:
867   // Count leading zeros will do just that!
868   case ARM::MVE_VCLZs8:
869   case ARM::MVE_VCLZs16:
870   case ARM::MVE_VCLZs32:
871     return true;
872   }
873   return false;
874 }
875 
876 // Look at its register uses to see if it only can only receive zeros
877 // into its false lanes which would then produce zeros. Also check that
878 // the output register is also defined by an FalseLanesZero instruction
879 // so that if tail-predication happens, the lanes that aren't updated will
880 // still be zeros.
881 static bool producesFalseLanesZero(MachineInstr &MI,
882                                    const TargetRegisterClass *QPRs,
883                                    const ReachingDefAnalysis &RDA,
884                                    InstSet &FalseLanesZero) {
885   if (canGenerateNonZeros(MI))
886     return false;
887 
888   bool isPredicated = isVectorPredicated(&MI);
889   // Predicated loads will write zeros to the falsely predicated bytes of the
890   // destination register.
891   if (MI.mayLoad())
892     return isPredicated;
893 
894   auto IsZeroInit = [](MachineInstr *Def) {
895     return !isVectorPredicated(Def) &&
896            Def->getOpcode() == ARM::MVE_VMOVimmi32 &&
897            Def->getOperand(1).getImm() == 0;
898   };
899 
900   bool AllowScalars = isHorizontalReduction(MI);
901   for (auto &MO : MI.operands()) {
902     if (!MO.isReg() || !MO.getReg())
903       continue;
904     if (!isRegInClass(MO, QPRs) && AllowScalars)
905       continue;
906     // Skip the lr predicate reg
907     int PIdx = llvm::findFirstVPTPredOperandIdx(MI);
908     if (PIdx != -1 && (int)MI.getOperandNo(&MO) == PIdx + 2)
909       continue;
910 
911     // Check that this instruction will produce zeros in its false lanes:
912     // - If it only consumes false lanes zero or constant 0 (vmov #0)
913     // - If it's predicated, it only matters that it's def register already has
914     //   false lane zeros, so we can ignore the uses.
915     SmallPtrSet<MachineInstr *, 2> Defs;
916     RDA.getGlobalReachingDefs(&MI, MO.getReg(), Defs);
917     for (auto *Def : Defs) {
918       if (Def == &MI || FalseLanesZero.count(Def) || IsZeroInit(Def))
919         continue;
920       if (MO.isUse() && isPredicated)
921         continue;
922       return false;
923     }
924   }
925   LLVM_DEBUG(dbgs() << "ARM Loops: Always False Zeros: " << MI);
926   return true;
927 }
928 
929 bool LowOverheadLoop::ValidateLiveOuts() {
930   // We want to find out if the tail-predicated version of this loop will
931   // produce the same values as the loop in its original form. For this to
932   // be true, the newly inserted implicit predication must not change the
933   // the (observable) results.
934   // We're doing this because many instructions in the loop will not be
935   // predicated and so the conversion from VPT predication to tail-predication
936   // can result in different values being produced; due to the tail-predication
937   // preventing many instructions from updating their falsely predicated
938   // lanes. This analysis assumes that all the instructions perform lane-wise
939   // operations and don't perform any exchanges.
940   // A masked load, whether through VPT or tail predication, will write zeros
941   // to any of the falsely predicated bytes. So, from the loads, we know that
942   // the false lanes are zeroed and here we're trying to track that those false
943   // lanes remain zero, or where they change, the differences are masked away
944   // by their user(s).
945   // All MVE stores have to be predicated, so we know that any predicate load
946   // operands, or stored results are equivalent already. Other explicitly
947   // predicated instructions will perform the same operation in the original
948   // loop and the tail-predicated form too. Because of this, we can insert
949   // loads, stores and other predicated instructions into our Predicated
950   // set and build from there.
951   const TargetRegisterClass *QPRs = TRI.getRegClass(ARM::MQPRRegClassID);
952   SetVector<MachineInstr *> FalseLanesUnknown;
953   SmallPtrSet<MachineInstr *, 4> FalseLanesZero;
954   SmallPtrSet<MachineInstr *, 4> Predicated;
955   MachineBasicBlock *Header = ML.getHeader();
956 
957   LLVM_DEBUG(dbgs() << "ARM Loops: Validating Live outs\n");
958 
959   for (auto &MI : *Header) {
960     if (!shouldInspect(MI))
961       continue;
962 
963     if (isVCTP(&MI) || isVPTOpcode(MI.getOpcode()))
964       continue;
965 
966     bool isPredicated = isVectorPredicated(&MI);
967     bool retainsOrReduces =
968       retainsPreviousHalfElement(MI) || isHorizontalReduction(MI);
969 
970     if (isPredicated)
971       Predicated.insert(&MI);
972     if (producesFalseLanesZero(MI, QPRs, RDA, FalseLanesZero))
973       FalseLanesZero.insert(&MI);
974     else if (MI.getNumDefs() == 0)
975       continue;
976     else if (!isPredicated && retainsOrReduces) {
977       LLVM_DEBUG(dbgs() << "  Unpredicated instruction that retainsOrReduces: " << MI);
978       return false;
979     }
980     else if (!isPredicated)
981       FalseLanesUnknown.insert(&MI);
982   }
983 
984   LLVM_DEBUG({
985     dbgs() << "  Predicated:\n";
986     for (auto *I : Predicated)
987       dbgs() << "  " << *I;
988     dbgs() << "  FalseLanesZero:\n";
989     for (auto *I : FalseLanesZero)
990       dbgs() << "  " << *I;
991     dbgs() << "  FalseLanesUnknown:\n";
992     for (auto *I : FalseLanesUnknown)
993       dbgs() << "  " << *I;
994   });
995 
996   auto HasPredicatedUsers = [this](MachineInstr *MI, const MachineOperand &MO,
997                               SmallPtrSetImpl<MachineInstr *> &Predicated) {
998     SmallPtrSet<MachineInstr *, 2> Uses;
999     RDA.getGlobalUses(MI, MO.getReg().asMCReg(), Uses);
1000     for (auto *Use : Uses) {
1001       if (Use != MI && !Predicated.count(Use))
1002         return false;
1003     }
1004     return true;
1005   };
1006 
1007   // Visit the unknowns in reverse so that we can start at the values being
1008   // stored and then we can work towards the leaves, hopefully adding more
1009   // instructions to Predicated. Successfully terminating the loop means that
1010   // all the unknown values have to found to be masked by predicated user(s).
1011   // For any unpredicated values, we store them in NonPredicated so that we
1012   // can later check whether these form a reduction.
1013   SmallPtrSet<MachineInstr*, 2> NonPredicated;
1014   for (auto *MI : reverse(FalseLanesUnknown)) {
1015     for (auto &MO : MI->operands()) {
1016       if (!isRegInClass(MO, QPRs) || !MO.isDef())
1017         continue;
1018       if (!HasPredicatedUsers(MI, MO, Predicated)) {
1019         LLVM_DEBUG(dbgs() << "  Found an unknown def of : "
1020                           << TRI.getRegAsmName(MO.getReg()) << " at " << *MI);
1021         NonPredicated.insert(MI);
1022         break;
1023       }
1024     }
1025     // Any unknown false lanes have been masked away by the user(s).
1026     if (!NonPredicated.contains(MI))
1027       Predicated.insert(MI);
1028   }
1029 
1030   SmallPtrSet<MachineInstr *, 2> LiveOutMIs;
1031   SmallVector<MachineBasicBlock *, 2> ExitBlocks;
1032   ML.getExitBlocks(ExitBlocks);
1033   assert(ML.getNumBlocks() == 1 && "Expected single block loop!");
1034   assert(ExitBlocks.size() == 1 && "Expected a single exit block");
1035   MachineBasicBlock *ExitBB = ExitBlocks.front();
1036   for (const MachineBasicBlock::RegisterMaskPair &RegMask : ExitBB->liveins()) {
1037     // TODO: Instead of blocking predication, we could move the vctp to the exit
1038     // block and calculate it's operand there in or the preheader.
1039     if (RegMask.PhysReg == ARM::VPR) {
1040       LLVM_DEBUG(dbgs() << "  VPR is live in to the exit block.");
1041       return false;
1042     }
1043     // Check Q-regs that are live in the exit blocks. We don't collect scalars
1044     // because they won't be affected by lane predication.
1045     if (QPRs->contains(RegMask.PhysReg))
1046       if (auto *MI = RDA.getLocalLiveOutMIDef(Header, RegMask.PhysReg))
1047         LiveOutMIs.insert(MI);
1048   }
1049 
1050   // We've already validated that any VPT predication within the loop will be
1051   // equivalent when we perform the predication transformation; so we know that
1052   // any VPT predicated instruction is predicated upon VCTP. Any live-out
1053   // instruction needs to be predicated, so check this here. The instructions
1054   // in NonPredicated have been found to be a reduction that we can ensure its
1055   // legality.
1056   for (auto *MI : LiveOutMIs) {
1057     if (NonPredicated.count(MI) && FalseLanesUnknown.contains(MI)) {
1058       LLVM_DEBUG(dbgs() << "  Unable to handle live out: " << *MI);
1059       return false;
1060     }
1061   }
1062 
1063   return true;
1064 }
1065 
1066 void LowOverheadLoop::Validate(ARMBasicBlockUtils *BBUtils) {
1067   if (Revert)
1068     return;
1069 
1070   // Check branch target ranges: WLS[TP] can only branch forwards and LE[TP]
1071   // can only jump back.
1072   auto ValidateRanges = [](MachineInstr *Start, MachineInstr *End,
1073                            ARMBasicBlockUtils *BBUtils, MachineLoop &ML) {
1074     MachineBasicBlock *TgtBB = End->getOpcode() == ARM::t2LoopEnd
1075                                    ? End->getOperand(1).getMBB()
1076                                    : End->getOperand(2).getMBB();
1077     // TODO Maybe there's cases where the target doesn't have to be the header,
1078     // but for now be safe and revert.
1079     if (TgtBB != ML.getHeader()) {
1080       LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targeting header.\n");
1081       return false;
1082     }
1083 
1084     // The WLS and LE instructions have 12-bits for the label offset. WLS
1085     // requires a positive offset, while LE uses negative.
1086     if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML.getHeader()) ||
1087         !BBUtils->isBBInRange(End, ML.getHeader(), 4094)) {
1088       LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n");
1089       return false;
1090     }
1091 
1092     if (isWhileLoopStart(*Start)) {
1093       MachineBasicBlock *TargetBB = getWhileLoopStartTargetBB(*Start);
1094       if (BBUtils->getOffsetOf(Start) > BBUtils->getOffsetOf(TargetBB) ||
1095           !BBUtils->isBBInRange(Start, TargetBB, 4094)) {
1096         LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n");
1097         return false;
1098       }
1099     }
1100     return true;
1101   };
1102 
1103   StartInsertPt = MachineBasicBlock::iterator(Start);
1104   StartInsertBB = Start->getParent();
1105   LLVM_DEBUG(dbgs() << "ARM Loops: Will insert LoopStart at "
1106                     << *StartInsertPt);
1107 
1108   Revert = !ValidateRanges(Start, End, BBUtils, ML);
1109   CannotTailPredicate = !ValidateTailPredicate();
1110 }
1111 
1112 bool LowOverheadLoop::AddVCTP(MachineInstr *MI) {
1113   LLVM_DEBUG(dbgs() << "ARM Loops: Adding VCTP: " << *MI);
1114   if (VCTPs.empty()) {
1115     VCTPs.push_back(MI);
1116     return true;
1117   }
1118 
1119   // If we find another VCTP, check whether it uses the same value as the main VCTP.
1120   // If it does, store it in the VCTPs set, else refuse it.
1121   MachineInstr *Prev = VCTPs.back();
1122   if (!Prev->getOperand(1).isIdenticalTo(MI->getOperand(1)) ||
1123       !RDA.hasSameReachingDef(Prev, MI, MI->getOperand(1).getReg().asMCReg())) {
1124     LLVM_DEBUG(dbgs() << "ARM Loops: Found VCTP with a different reaching "
1125                          "definition from the main VCTP");
1126     return false;
1127   }
1128   VCTPs.push_back(MI);
1129   return true;
1130 }
1131 
1132 static bool ValidateMVEStore(MachineInstr *MI, MachineLoop *ML) {
1133 
1134   auto GetFrameIndex = [](MachineMemOperand *Operand) {
1135     const PseudoSourceValue *PseudoValue = Operand->getPseudoValue();
1136     if (PseudoValue && PseudoValue->kind() == PseudoSourceValue::FixedStack) {
1137       if (const auto *FS = dyn_cast<FixedStackPseudoSourceValue>(PseudoValue)) {
1138         return FS->getFrameIndex();
1139       }
1140     }
1141     return -1;
1142   };
1143 
1144   auto IsStackOp = [GetFrameIndex](MachineInstr *I) {
1145     switch (I->getOpcode()) {
1146     case ARM::MVE_VSTRWU32:
1147     case ARM::MVE_VLDRWU32: {
1148       return I->getOperand(1).getReg() == ARM::SP &&
1149              I->memoperands().size() == 1 &&
1150              GetFrameIndex(I->memoperands().front()) >= 0;
1151     }
1152     default:
1153       return false;
1154     }
1155   };
1156 
1157   // An unpredicated vector register spill is allowed if all of the uses of the
1158   // stack slot are within the loop
1159   if (MI->getOpcode() != ARM::MVE_VSTRWU32 || !IsStackOp(MI))
1160     return false;
1161 
1162   // Search all blocks after the loop for accesses to the same stack slot.
1163   // ReachingDefAnalysis doesn't work for sp as it relies on registers being
1164   // live-out (which sp never is) to know what blocks to look in
1165   if (MI->memoperands().size() == 0)
1166     return false;
1167   int FI = GetFrameIndex(MI->memoperands().front());
1168 
1169   auto &FrameInfo = MI->getParent()->getParent()->getFrameInfo();
1170   if (FI == -1 || !FrameInfo.isSpillSlotObjectIndex(FI))
1171     return false;
1172 
1173   SmallVector<MachineBasicBlock *> Frontier;
1174   ML->getExitBlocks(Frontier);
1175   SmallPtrSet<MachineBasicBlock *, 4> Visited{MI->getParent()};
1176   unsigned Idx = 0;
1177   while (Idx < Frontier.size()) {
1178     MachineBasicBlock *BB = Frontier[Idx];
1179     bool LookAtSuccessors = true;
1180     for (auto &I : *BB) {
1181       if (!IsStackOp(&I) || I.memoperands().size() == 0)
1182         continue;
1183       if (GetFrameIndex(I.memoperands().front()) != FI)
1184         continue;
1185       // If this block has a store to the stack slot before any loads then we
1186       // can ignore the block
1187       if (I.getOpcode() == ARM::MVE_VSTRWU32) {
1188         LookAtSuccessors = false;
1189         break;
1190       }
1191       // If the store and the load are using the same stack slot then the
1192       // store isn't valid for tail predication
1193       if (I.getOpcode() == ARM::MVE_VLDRWU32)
1194         return false;
1195     }
1196 
1197     if (LookAtSuccessors) {
1198       for (auto Succ : BB->successors()) {
1199         if (!Visited.contains(Succ) && !is_contained(Frontier, Succ))
1200           Frontier.push_back(Succ);
1201       }
1202     }
1203     Visited.insert(BB);
1204     Idx++;
1205   }
1206 
1207   return true;
1208 }
1209 
1210 bool LowOverheadLoop::ValidateMVEInst(MachineInstr *MI) {
1211   if (CannotTailPredicate)
1212     return false;
1213 
1214   if (!shouldInspect(*MI))
1215     return true;
1216 
1217   if (MI->getOpcode() == ARM::MVE_VPSEL ||
1218       MI->getOpcode() == ARM::MVE_VPNOT) {
1219     // TODO: Allow VPSEL and VPNOT, we currently cannot because:
1220     // 1) It will use the VPR as a predicate operand, but doesn't have to be
1221     //    instead a VPT block, which means we can assert while building up
1222     //    the VPT block because we don't find another VPT or VPST to being a new
1223     //    one.
1224     // 2) VPSEL still requires a VPR operand even after tail predicating,
1225     //    which means we can't remove it unless there is another
1226     //    instruction, such as vcmp, that can provide the VPR def.
1227     return false;
1228   }
1229 
1230   // Record all VCTPs and check that they're equivalent to one another.
1231   if (isVCTP(MI) && !AddVCTP(MI))
1232     return false;
1233 
1234   // Inspect uses first so that any instructions that alter the VPR don't
1235   // alter the predicate upon themselves.
1236   const MCInstrDesc &MCID = MI->getDesc();
1237   bool IsUse = false;
1238   unsigned LastOpIdx = MI->getNumOperands() - 1;
1239   for (auto &Op : enumerate(reverse(MCID.operands()))) {
1240     const MachineOperand &MO = MI->getOperand(LastOpIdx - Op.index());
1241     if (!MO.isReg() || !MO.isUse() || MO.getReg() != ARM::VPR)
1242       continue;
1243 
1244     if (ARM::isVpred(Op.value().OperandType)) {
1245       VPTState::addInst(MI);
1246       IsUse = true;
1247     } else if (MI->getOpcode() != ARM::MVE_VPST) {
1248       LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI);
1249       return false;
1250     }
1251   }
1252 
1253   // If we find an instruction that has been marked as not valid for tail
1254   // predication, only allow the instruction if it's contained within a valid
1255   // VPT block.
1256   bool RequiresExplicitPredication =
1257     (MCID.TSFlags & ARMII::ValidForTailPredication) == 0;
1258   if (isDomainMVE(MI) && RequiresExplicitPredication) {
1259     if (!IsUse && producesDoubleWidthResult(*MI)) {
1260       DoubleWidthResultInstrs.insert(MI);
1261       return true;
1262     }
1263 
1264     LLVM_DEBUG(if (!IsUse) dbgs()
1265                << "ARM Loops: Can't tail predicate: " << *MI);
1266     return IsUse;
1267   }
1268 
1269   // If the instruction is already explicitly predicated, then the conversion
1270   // will be fine, but ensure that all store operations are predicated.
1271   if (MI->mayStore() && !ValidateMVEStore(MI, &ML))
1272     return IsUse;
1273 
1274   // If this instruction defines the VPR, update the predicate for the
1275   // proceeding instructions.
1276   if (isVectorPredicate(MI)) {
1277     // Clear the existing predicate when we're not in VPT Active state,
1278     // otherwise we add to it.
1279     if (!isVectorPredicated(MI))
1280       VPTState::resetPredicate(MI);
1281     else
1282       VPTState::addPredicate(MI);
1283   }
1284 
1285   // Finally once the predicate has been modified, we can start a new VPT
1286   // block if necessary.
1287   if (isVPTOpcode(MI->getOpcode()))
1288     VPTState::CreateVPTBlock(MI);
1289 
1290   return true;
1291 }
1292 
1293 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) {
1294   const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget());
1295   if (!ST.hasLOB())
1296     return false;
1297 
1298   MF = &mf;
1299   LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n");
1300 
1301   MLI = &getAnalysis<MachineLoopInfo>();
1302   RDA = &getAnalysis<ReachingDefAnalysis>();
1303   MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
1304   MRI = &MF->getRegInfo();
1305   TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo());
1306   TRI = ST.getRegisterInfo();
1307   BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF));
1308   BBUtils->computeAllBlockSizes();
1309   BBUtils->adjustBBOffsetsAfter(&MF->front());
1310 
1311   bool Changed = false;
1312   for (auto ML : *MLI) {
1313     if (ML->isOutermost())
1314       Changed |= ProcessLoop(ML);
1315   }
1316   Changed |= RevertNonLoops();
1317   return Changed;
1318 }
1319 
1320 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) {
1321 
1322   bool Changed = false;
1323 
1324   // Process inner loops first.
1325   for (auto I = ML->begin(), E = ML->end(); I != E; ++I)
1326     Changed |= ProcessLoop(*I);
1327 
1328   LLVM_DEBUG({
1329     dbgs() << "ARM Loops: Processing loop containing:\n";
1330     if (auto *Preheader = ML->getLoopPreheader())
1331       dbgs() << " - Preheader: " << printMBBReference(*Preheader) << "\n";
1332     else if (auto *Preheader = MLI->findLoopPreheader(ML, true, true))
1333       dbgs() << " - Preheader: " << printMBBReference(*Preheader) << "\n";
1334     for (auto *MBB : ML->getBlocks())
1335       dbgs() << " - Block: " << printMBBReference(*MBB) << "\n";
1336   });
1337 
1338   // Search the given block for a loop start instruction. If one isn't found,
1339   // and there's only one predecessor block, search that one too.
1340   std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
1341     [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* {
1342     for (auto &MI : *MBB) {
1343       if (isLoopStart(MI))
1344         return &MI;
1345     }
1346     if (MBB->pred_size() == 1)
1347       return SearchForStart(*MBB->pred_begin());
1348     return nullptr;
1349   };
1350 
1351   LowOverheadLoop LoLoop(*ML, *MLI, *RDA, *TRI, *TII);
1352   // Search the preheader for the start intrinsic.
1353   // FIXME: I don't see why we shouldn't be supporting multiple predecessors
1354   // with potentially multiple set.loop.iterations, so we need to enable this.
1355   if (LoLoop.Preheader)
1356     LoLoop.Start = SearchForStart(LoLoop.Preheader);
1357   else
1358     return Changed;
1359 
1360   // Find the low-overhead loop components and decide whether or not to fall
1361   // back to a normal loop. Also look for a vctp instructions and decide
1362   // whether we can convert that predicate using tail predication.
1363   for (auto *MBB : reverse(ML->getBlocks())) {
1364     for (auto &MI : *MBB) {
1365       if (MI.isDebugValue())
1366         continue;
1367       else if (MI.getOpcode() == ARM::t2LoopDec)
1368         LoLoop.Dec = &MI;
1369       else if (MI.getOpcode() == ARM::t2LoopEnd)
1370         LoLoop.End = &MI;
1371       else if (MI.getOpcode() == ARM::t2LoopEndDec)
1372         LoLoop.End = LoLoop.Dec = &MI;
1373       else if (isLoopStart(MI))
1374         LoLoop.Start = &MI;
1375       else if (MI.getDesc().isCall()) {
1376         // TODO: Though the call will require LE to execute again, does this
1377         // mean we should revert? Always executing LE hopefully should be
1378         // faster than performing a sub,cmp,br or even subs,br.
1379         LoLoop.Revert = true;
1380         LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
1381       } else {
1382         // Record VPR defs and build up their corresponding vpt blocks.
1383         // Check we know how to tail predicate any mve instructions.
1384         LoLoop.AnalyseMVEInst(&MI);
1385       }
1386     }
1387   }
1388 
1389   LLVM_DEBUG(LoLoop.dump());
1390   if (!LoLoop.FoundAllComponents()) {
1391     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
1392     return Changed;
1393   }
1394 
1395   assert(LoLoop.Start->getOpcode() != ARM::t2WhileLoopStart &&
1396          "Expected t2WhileLoopStart to be removed before regalloc!");
1397 
1398   // Check that the only instruction using LoopDec is LoopEnd. This can only
1399   // happen when the Dec and End are separate, not a single t2LoopEndDec.
1400   // TODO: Check for copy chains that really have no effect.
1401   if (LoLoop.Dec != LoLoop.End) {
1402     SmallPtrSet<MachineInstr *, 2> Uses;
1403     RDA->getReachingLocalUses(LoLoop.Dec, MCRegister::from(ARM::LR), Uses);
1404     if (Uses.size() > 1 || !Uses.count(LoLoop.End)) {
1405       LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n");
1406       LoLoop.Revert = true;
1407     }
1408   }
1409   LoLoop.Validate(BBUtils.get());
1410   Expand(LoLoop);
1411   return true;
1412 }
1413 
1414 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
1415 // beq that branches to the exit branch.
1416 // TODO: We could also try to generate a cbz if the value in LR is also in
1417 // another low register.
1418 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const {
1419   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI);
1420   MachineBasicBlock *DestBB = getWhileLoopStartTargetBB(*MI);
1421   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
1422     ARM::tBcc : ARM::t2Bcc;
1423 
1424   RevertWhileLoopStartLR(MI, TII, BrOpc);
1425 }
1426 
1427 void ARMLowOverheadLoops::RevertDo(MachineInstr *MI) const {
1428   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to mov: " << *MI);
1429   RevertDoLoopStart(MI, TII);
1430 }
1431 
1432 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const {
1433   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI);
1434   MachineBasicBlock *MBB = MI->getParent();
1435   SmallPtrSet<MachineInstr*, 1> Ignore;
1436   for (auto I = MachineBasicBlock::iterator(MI), E = MBB->end(); I != E; ++I) {
1437     if (I->getOpcode() == ARM::t2LoopEnd) {
1438       Ignore.insert(&*I);
1439       break;
1440     }
1441   }
1442 
1443   // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
1444   bool SetFlags =
1445       RDA->isSafeToDefRegAt(MI, MCRegister::from(ARM::CPSR), Ignore);
1446 
1447   llvm::RevertLoopDec(MI, TII, SetFlags);
1448   return SetFlags;
1449 }
1450 
1451 // Generate a subs, or sub and cmp, and a branch instead of an LE.
1452 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const {
1453   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI);
1454 
1455   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
1456   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
1457     ARM::tBcc : ARM::t2Bcc;
1458 
1459   llvm::RevertLoopEnd(MI, TII, BrOpc, SkipCmp);
1460 }
1461 
1462 // Generate a subs, or sub and cmp, and a branch instead of an LE.
1463 void ARMLowOverheadLoops::RevertLoopEndDec(MachineInstr *MI) const {
1464   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to subs, br: " << *MI);
1465   assert(MI->getOpcode() == ARM::t2LoopEndDec && "Expected a t2LoopEndDec!");
1466   MachineBasicBlock *MBB = MI->getParent();
1467 
1468   MachineInstrBuilder MIB =
1469       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::t2SUBri));
1470   MIB.addDef(ARM::LR);
1471   MIB.add(MI->getOperand(1));
1472   MIB.addImm(1);
1473   MIB.addImm(ARMCC::AL);
1474   MIB.addReg(ARM::NoRegister);
1475   MIB.addReg(ARM::CPSR);
1476   MIB->getOperand(5).setIsDef(true);
1477 
1478   MachineBasicBlock *DestBB = MI->getOperand(2).getMBB();
1479   unsigned BrOpc =
1480       BBUtils->isBBInRange(MI, DestBB, 254) ? ARM::tBcc : ARM::t2Bcc;
1481 
1482   // Create bne
1483   MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
1484   MIB.add(MI->getOperand(2)); // branch target
1485   MIB.addImm(ARMCC::NE);      // condition code
1486   MIB.addReg(ARM::CPSR);
1487 
1488   MI->eraseFromParent();
1489 }
1490 
1491 // Perform dead code elimation on the loop iteration count setup expression.
1492 // If we are tail-predicating, the number of elements to be processed is the
1493 // operand of the VCTP instruction in the vector body, see getCount(), which is
1494 // register $r3 in this example:
1495 //
1496 //   $lr = big-itercount-expression
1497 //   ..
1498 //   $lr = t2DoLoopStart renamable $lr
1499 //   vector.body:
1500 //     ..
1501 //     $vpr = MVE_VCTP32 renamable $r3
1502 //     renamable $lr = t2LoopDec killed renamable $lr, 1
1503 //     t2LoopEnd renamable $lr, %vector.body
1504 //     tB %end
1505 //
1506 // What we would like achieve here is to replace the do-loop start pseudo
1507 // instruction t2DoLoopStart with:
1508 //
1509 //    $lr = MVE_DLSTP_32 killed renamable $r3
1510 //
1511 // Thus, $r3 which defines the number of elements, is written to $lr,
1512 // and then we want to delete the whole chain that used to define $lr,
1513 // see the comment below how this chain could look like.
1514 //
1515 void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) {
1516   if (!LoLoop.IsTailPredicationLegal())
1517     return;
1518 
1519   LLVM_DEBUG(dbgs() << "ARM Loops: Trying DCE on loop iteration count.\n");
1520 
1521   MachineInstr *Def = RDA->getMIOperand(LoLoop.Start, 1);
1522   if (!Def) {
1523     LLVM_DEBUG(dbgs() << "ARM Loops: Couldn't find iteration count.\n");
1524     return;
1525   }
1526 
1527   // Collect and remove the users of iteration count.
1528   SmallPtrSet<MachineInstr*, 4> Killed  = { LoLoop.Start, LoLoop.Dec,
1529                                             LoLoop.End };
1530   if (!TryRemove(Def, *RDA, LoLoop.ToRemove, Killed))
1531     LLVM_DEBUG(dbgs() << "ARM Loops: Unsafe to remove loop iteration count.\n");
1532 }
1533 
1534 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
1535   LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n");
1536   // When using tail-predication, try to delete the dead code that was used to
1537   // calculate the number of loop iterations.
1538   IterationCountDCE(LoLoop);
1539 
1540   MachineBasicBlock::iterator InsertPt = LoLoop.StartInsertPt;
1541   MachineInstr *Start = LoLoop.Start;
1542   MachineBasicBlock *MBB = LoLoop.StartInsertBB;
1543   unsigned Opc = LoLoop.getStartOpcode();
1544   MachineOperand &Count = LoLoop.getLoopStartOperand();
1545 
1546   // A DLS lr, lr we needn't emit
1547   MachineInstr* NewStart;
1548   if (Opc == ARM::t2DLS && Count.isReg() && Count.getReg() == ARM::LR) {
1549     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't insert start: DLS lr, lr");
1550     NewStart = nullptr;
1551   } else {
1552     MachineInstrBuilder MIB =
1553       BuildMI(*MBB, InsertPt, Start->getDebugLoc(), TII->get(Opc));
1554 
1555     MIB.addDef(ARM::LR);
1556     MIB.add(Count);
1557     if (isWhileLoopStart(*Start))
1558       MIB.addMBB(getWhileLoopStartTargetBB(*Start));
1559 
1560     LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB);
1561     NewStart = &*MIB;
1562   }
1563 
1564   LoLoop.ToRemove.insert(Start);
1565   return NewStart;
1566 }
1567 
1568 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
1569   auto RemovePredicate = [](MachineInstr *MI) {
1570     if (MI->isDebugInstr())
1571       return;
1572     LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI);
1573     int PIdx = llvm::findFirstVPTPredOperandIdx(*MI);
1574     assert(PIdx >= 1 && "Trying to unpredicate a non-predicated instruction");
1575     assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then &&
1576            "Expected Then predicate!");
1577     MI->getOperand(PIdx).setImm(ARMVCC::None);
1578     MI->getOperand(PIdx + 1).setReg(0);
1579   };
1580 
1581   for (auto &Block : LoLoop.getVPTBlocks()) {
1582     SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
1583 
1584     auto ReplaceVCMPWithVPT = [&](MachineInstr *&TheVCMP, MachineInstr *At) {
1585       assert(TheVCMP && "Replacing a removed or non-existent VCMP");
1586       // Replace the VCMP with a VPT
1587       MachineInstrBuilder MIB =
1588           BuildMI(*At->getParent(), At, At->getDebugLoc(),
1589                   TII->get(VCMPOpcodeToVPT(TheVCMP->getOpcode())));
1590       MIB.addImm(ARMVCC::Then);
1591       // Register one
1592       MIB.add(TheVCMP->getOperand(1));
1593       // Register two
1594       MIB.add(TheVCMP->getOperand(2));
1595       // The comparison code, e.g. ge, eq, lt
1596       MIB.add(TheVCMP->getOperand(3));
1597       LLVM_DEBUG(dbgs() << "ARM Loops: Combining with VCMP to VPT: " << *MIB);
1598       LoLoop.BlockMasksToRecompute.insert(MIB.getInstr());
1599       LoLoop.ToRemove.insert(TheVCMP);
1600       TheVCMP = nullptr;
1601     };
1602 
1603     if (VPTState::isEntryPredicatedOnVCTP(Block, /*exclusive*/ true)) {
1604       MachineInstr *VPST = Insts.front();
1605       if (VPTState::hasUniformPredicate(Block)) {
1606         // A vpt block starting with VPST, is only predicated upon vctp and has no
1607         // internal vpr defs:
1608         // - Remove vpst.
1609         // - Unpredicate the remaining instructions.
1610         LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
1611         for (unsigned i = 1; i < Insts.size(); ++i)
1612           RemovePredicate(Insts[i]);
1613       } else {
1614         // The VPT block has a non-uniform predicate but it uses a vpst and its
1615         // entry is guarded only by a vctp, which means we:
1616         // - Need to remove the original vpst.
1617         // - Then need to unpredicate any following instructions, until
1618         //   we come across the divergent vpr def.
1619         // - Insert a new vpst to predicate the instruction(s) that following
1620         //   the divergent vpr def.
1621         MachineInstr *Divergent = VPTState::getDivergent(Block);
1622         MachineBasicBlock *MBB = Divergent->getParent();
1623         auto DivergentNext = ++MachineBasicBlock::iterator(Divergent);
1624         while (DivergentNext != MBB->end() && DivergentNext->isDebugInstr())
1625           ++DivergentNext;
1626 
1627         bool DivergentNextIsPredicated =
1628             DivergentNext != MBB->end() &&
1629             getVPTInstrPredicate(*DivergentNext) != ARMVCC::None;
1630 
1631         for (auto I = ++MachineBasicBlock::iterator(VPST), E = DivergentNext;
1632              I != E; ++I)
1633           RemovePredicate(&*I);
1634 
1635         // Check if the instruction defining vpr is a vcmp so it can be combined
1636         // with the VPST This should be the divergent instruction
1637         MachineInstr *VCMP =
1638             VCMPOpcodeToVPT(Divergent->getOpcode()) != 0 ? Divergent : nullptr;
1639 
1640         if (DivergentNextIsPredicated) {
1641           // Insert a VPST at the divergent only if the next instruction
1642           // would actually use it. A VCMP following a VPST can be
1643           // merged into a VPT so do that instead if the VCMP exists.
1644           if (!VCMP) {
1645             // Create a VPST (with a null mask for now, we'll recompute it
1646             // later)
1647             MachineInstrBuilder MIB =
1648                 BuildMI(*Divergent->getParent(), Divergent,
1649                         Divergent->getDebugLoc(), TII->get(ARM::MVE_VPST));
1650             MIB.addImm(0);
1651             LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB);
1652             LoLoop.BlockMasksToRecompute.insert(MIB.getInstr());
1653           } else {
1654             // No RDA checks are necessary here since the VPST would have been
1655             // directly after the VCMP
1656             ReplaceVCMPWithVPT(VCMP, VCMP);
1657           }
1658         }
1659       }
1660       LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
1661       LoLoop.ToRemove.insert(VPST);
1662     } else if (Block.containsVCTP()) {
1663       // The vctp will be removed, so either the entire block will be dead or
1664       // the block mask of the vp(s)t will need to be recomputed.
1665       MachineInstr *VPST = Insts.front();
1666       if (Block.size() == 2) {
1667         assert(VPST->getOpcode() == ARM::MVE_VPST &&
1668                "Found a VPST in an otherwise empty vpt block");
1669         LoLoop.ToRemove.insert(VPST);
1670       } else
1671         LoLoop.BlockMasksToRecompute.insert(VPST);
1672     } else if (Insts.front()->getOpcode() == ARM::MVE_VPST) {
1673       // If this block starts with a VPST then attempt to merge it with the
1674       // preceeding un-merged VCMP into a VPT. This VCMP comes from a VPT
1675       // block that no longer exists
1676       MachineInstr *VPST = Insts.front();
1677       auto Next = ++MachineBasicBlock::iterator(VPST);
1678       assert(getVPTInstrPredicate(*Next) != ARMVCC::None &&
1679              "The instruction after a VPST must be predicated");
1680       (void)Next;
1681       MachineInstr *VprDef = RDA->getUniqueReachingMIDef(VPST, ARM::VPR);
1682       if (VprDef && VCMPOpcodeToVPT(VprDef->getOpcode()) &&
1683           !LoLoop.ToRemove.contains(VprDef)) {
1684         MachineInstr *VCMP = VprDef;
1685         // The VCMP and VPST can only be merged if the VCMP's operands will have
1686         // the same values at the VPST.
1687         // If any of the instructions between the VCMP and VPST are predicated
1688         // then a different code path is expected to have merged the VCMP and
1689         // VPST already.
1690         if (!std::any_of(++MachineBasicBlock::iterator(VCMP),
1691                          MachineBasicBlock::iterator(VPST), hasVPRUse) &&
1692             RDA->hasSameReachingDef(VCMP, VPST, VCMP->getOperand(1).getReg()) &&
1693             RDA->hasSameReachingDef(VCMP, VPST, VCMP->getOperand(2).getReg())) {
1694           ReplaceVCMPWithVPT(VCMP, VPST);
1695           LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
1696           LoLoop.ToRemove.insert(VPST);
1697         }
1698       }
1699     }
1700   }
1701 
1702   LoLoop.ToRemove.insert(LoLoop.VCTPs.begin(), LoLoop.VCTPs.end());
1703 }
1704 
1705 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
1706 
1707   // Combine the LoopDec and LoopEnd instructions into LE(TP).
1708   auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) {
1709     MachineInstr *End = LoLoop.End;
1710     MachineBasicBlock *MBB = End->getParent();
1711     unsigned Opc = LoLoop.IsTailPredicationLegal() ?
1712       ARM::MVE_LETP : ARM::t2LEUpdate;
1713     MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(),
1714                                       TII->get(Opc));
1715     MIB.addDef(ARM::LR);
1716     unsigned Off = LoLoop.Dec == LoLoop.End ? 1 : 0;
1717     MIB.add(End->getOperand(Off + 0));
1718     MIB.add(End->getOperand(Off + 1));
1719     LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB);
1720     LoLoop.ToRemove.insert(LoLoop.Dec);
1721     LoLoop.ToRemove.insert(End);
1722     return &*MIB;
1723   };
1724 
1725   // TODO: We should be able to automatically remove these branches before we
1726   // get here - probably by teaching analyzeBranch about the pseudo
1727   // instructions.
1728   // If there is an unconditional branch, after I, that just branches to the
1729   // next block, remove it.
1730   auto RemoveDeadBranch = [](MachineInstr *I) {
1731     MachineBasicBlock *BB = I->getParent();
1732     MachineInstr *Terminator = &BB->instr_back();
1733     if (Terminator->isUnconditionalBranch() && I != Terminator) {
1734       MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB();
1735       if (BB->isLayoutSuccessor(Succ)) {
1736         LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator);
1737         Terminator->eraseFromParent();
1738       }
1739     }
1740   };
1741 
1742   if (LoLoop.Revert) {
1743     if (isWhileLoopStart(*LoLoop.Start))
1744       RevertWhile(LoLoop.Start);
1745     else
1746       RevertDo(LoLoop.Start);
1747     if (LoLoop.Dec == LoLoop.End)
1748       RevertLoopEndDec(LoLoop.End);
1749     else
1750       RevertLoopEnd(LoLoop.End, RevertLoopDec(LoLoop.Dec));
1751   } else {
1752     LoLoop.Start = ExpandLoopStart(LoLoop);
1753     if (LoLoop.Start)
1754       RemoveDeadBranch(LoLoop.Start);
1755     LoLoop.End = ExpandLoopEnd(LoLoop);
1756     RemoveDeadBranch(LoLoop.End);
1757     if (LoLoop.IsTailPredicationLegal())
1758       ConvertVPTBlocks(LoLoop);
1759     for (auto *I : LoLoop.ToRemove) {
1760       LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I);
1761       I->eraseFromParent();
1762     }
1763     for (auto *I : LoLoop.BlockMasksToRecompute) {
1764       LLVM_DEBUG(dbgs() << "ARM Loops: Recomputing VPT/VPST Block Mask: " << *I);
1765       recomputeVPTBlockMask(*I);
1766       LLVM_DEBUG(dbgs() << "           ... done: " << *I);
1767     }
1768   }
1769 
1770   PostOrderLoopTraversal DFS(LoLoop.ML, *MLI);
1771   DFS.ProcessLoop();
1772   const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
1773   for (auto *MBB : PostOrder) {
1774     recomputeLiveIns(*MBB);
1775     // FIXME: For some reason, the live-in print order is non-deterministic for
1776     // our tests and I can't out why... So just sort them.
1777     MBB->sortUniqueLiveIns();
1778   }
1779 
1780   for (auto *MBB : reverse(PostOrder))
1781     recomputeLivenessFlags(*MBB);
1782 
1783   // We've moved, removed and inserted new instructions, so update RDA.
1784   RDA->reset();
1785 }
1786 
1787 bool ARMLowOverheadLoops::RevertNonLoops() {
1788   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
1789   bool Changed = false;
1790 
1791   for (auto &MBB : *MF) {
1792     SmallVector<MachineInstr*, 4> Starts;
1793     SmallVector<MachineInstr*, 4> Decs;
1794     SmallVector<MachineInstr*, 4> Ends;
1795     SmallVector<MachineInstr *, 4> EndDecs;
1796 
1797     for (auto &I : MBB) {
1798       if (isLoopStart(I))
1799         Starts.push_back(&I);
1800       else if (I.getOpcode() == ARM::t2LoopDec)
1801         Decs.push_back(&I);
1802       else if (I.getOpcode() == ARM::t2LoopEnd)
1803         Ends.push_back(&I);
1804       else if (I.getOpcode() == ARM::t2LoopEndDec)
1805         EndDecs.push_back(&I);
1806     }
1807 
1808     if (Starts.empty() && Decs.empty() && Ends.empty() && EndDecs.empty())
1809       continue;
1810 
1811     Changed = true;
1812 
1813     for (auto *Start : Starts) {
1814       if (isWhileLoopStart(*Start))
1815         RevertWhile(Start);
1816       else
1817         RevertDo(Start);
1818     }
1819     for (auto *Dec : Decs)
1820       RevertLoopDec(Dec);
1821 
1822     for (auto *End : Ends)
1823       RevertLoopEnd(End);
1824     for (auto *End : EndDecs)
1825       RevertLoopEndDec(End);
1826   }
1827   return Changed;
1828 }
1829 
1830 FunctionPass *llvm::createARMLowOverheadLoopsPass() {
1831   return new ARMLowOverheadLoops();
1832 }
1833