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