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