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 //===----------------------------------------------------------------------===//
39 
40 #include "ARM.h"
41 #include "ARMBaseInstrInfo.h"
42 #include "ARMBaseRegisterInfo.h"
43 #include "ARMBasicBlockInfo.h"
44 #include "ARMSubtarget.h"
45 #include "Thumb2InstrInfo.h"
46 #include "llvm/ADT/SetOperations.h"
47 #include "llvm/ADT/SmallSet.h"
48 #include "llvm/CodeGen/LivePhysRegs.h"
49 #include "llvm/CodeGen/MachineFunctionPass.h"
50 #include "llvm/CodeGen/MachineLoopInfo.h"
51 #include "llvm/CodeGen/MachineLoopUtils.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/Passes.h"
54 #include "llvm/CodeGen/ReachingDefAnalysis.h"
55 #include "llvm/MC/MCInstrDesc.h"
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "arm-low-overhead-loops"
60 #define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
61 
62 namespace {
63 
64   class PostOrderLoopTraversal {
65     MachineLoop &ML;
66     MachineLoopInfo &MLI;
67     SmallPtrSet<MachineBasicBlock*, 4> Visited;
68     SmallVector<MachineBasicBlock*, 4> Order;
69 
70   public:
71     PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI)
72       : ML(ML), MLI(MLI) { }
73 
74     const SmallVectorImpl<MachineBasicBlock*> &getOrder() const {
75       return Order;
76     }
77 
78     // Visit all the blocks within the loop, as well as exit blocks and any
79     // blocks properly dominating the header.
80     void ProcessLoop() {
81       std::function<void(MachineBasicBlock*)> Search = [this, &Search]
82         (MachineBasicBlock *MBB) -> void {
83         if (Visited.count(MBB))
84           return;
85 
86         Visited.insert(MBB);
87         for (auto *Succ : MBB->successors()) {
88           if (!ML.contains(Succ))
89             continue;
90           Search(Succ);
91         }
92         Order.push_back(MBB);
93       };
94 
95       // Insert exit blocks.
96       SmallVector<MachineBasicBlock*, 2> ExitBlocks;
97       ML.getExitBlocks(ExitBlocks);
98       for (auto *MBB : ExitBlocks)
99         Order.push_back(MBB);
100 
101       // Then add the loop body.
102       Search(ML.getHeader());
103 
104       // Then try the preheader and its predecessors.
105       std::function<void(MachineBasicBlock*)> GetPredecessor =
106         [this, &GetPredecessor] (MachineBasicBlock *MBB) -> void {
107         Order.push_back(MBB);
108         if (MBB->pred_size() == 1)
109           GetPredecessor(*MBB->pred_begin());
110       };
111 
112       if (auto *Preheader = ML.getLoopPreheader())
113         GetPredecessor(Preheader);
114       else if (auto *Preheader = MLI.findLoopPreheader(&ML, true))
115         GetPredecessor(Preheader);
116     }
117   };
118 
119   struct PredicatedMI {
120     MachineInstr *MI = nullptr;
121     SetVector<MachineInstr*> Predicates;
122 
123   public:
124     PredicatedMI(MachineInstr *I, SetVector<MachineInstr*> &Preds) :
125       MI(I) { Predicates.insert(Preds.begin(), Preds.end()); }
126   };
127 
128   // Represent a VPT block, a list of instructions that begins with a VPST and
129   // has a maximum of four proceeding instructions. All instructions within the
130   // block are predicated upon the vpr and we allow instructions to define the
131   // vpr within in the block too.
132   class VPTBlock {
133     std::unique_ptr<PredicatedMI> VPST;
134     PredicatedMI *Divergent = nullptr;
135     SmallVector<PredicatedMI, 4> Insts;
136 
137   public:
138     VPTBlock(MachineInstr *MI, SetVector<MachineInstr*> &Preds) {
139       VPST = std::make_unique<PredicatedMI>(MI, Preds);
140     }
141 
142     void addInst(MachineInstr *MI, SetVector<MachineInstr*> &Preds) {
143       LLVM_DEBUG(dbgs() << "ARM Loops: Adding predicated MI: " << *MI);
144       if (!Divergent && !set_difference(Preds, VPST->Predicates).empty()) {
145         Divergent = &Insts.back();
146         LLVM_DEBUG(dbgs() << " - has divergent predicate: " << *Divergent->MI);
147       }
148       Insts.emplace_back(MI, Preds);
149       assert(Insts.size() <= 4 && "Too many instructions in VPT block!");
150     }
151 
152     // Have we found an instruction within the block which defines the vpr? If
153     // so, not all the instructions in the block will have the same predicate.
154     bool HasNonUniformPredicate() const {
155       return Divergent != nullptr;
156     }
157 
158     // Is the given instruction part of the predicate set controlling the entry
159     // to the block.
160     bool IsPredicatedOn(MachineInstr *MI) const {
161       return VPST->Predicates.count(MI);
162     }
163 
164     // Is the given instruction the only predicate which controls the entry to
165     // the block.
166     bool IsOnlyPredicatedOn(MachineInstr *MI) const {
167       return IsPredicatedOn(MI) && VPST->Predicates.size() == 1;
168     }
169 
170     unsigned size() const { return Insts.size(); }
171     SmallVectorImpl<PredicatedMI> &getInsts() { return Insts; }
172     MachineInstr *getVPST() const { return VPST->MI; }
173     PredicatedMI *getDivergent() const { return Divergent; }
174   };
175 
176   struct LowOverheadLoop {
177 
178     MachineLoop &ML;
179     MachineLoopInfo &MLI;
180     ReachingDefAnalysis &RDA;
181     const TargetRegisterInfo &TRI;
182     MachineFunction *MF = nullptr;
183     MachineInstr *InsertPt = nullptr;
184     MachineInstr *Start = nullptr;
185     MachineInstr *Dec = nullptr;
186     MachineInstr *End = nullptr;
187     MachineInstr *VCTP = nullptr;
188     VPTBlock *CurrentBlock = nullptr;
189     SetVector<MachineInstr*> CurrentPredicate;
190     SmallVector<VPTBlock, 4> VPTBlocks;
191     SmallPtrSet<MachineInstr*, 4> ToRemove;
192     bool Revert = false;
193     bool CannotTailPredicate = false;
194 
195     LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI,
196                     ReachingDefAnalysis &RDA, const TargetRegisterInfo &TRI)
197       : ML(ML), MLI(MLI), RDA(RDA), TRI(TRI) {
198       MF = ML.getHeader()->getParent();
199     }
200 
201     // If this is an MVE instruction, check that we know how to use tail
202     // predication with it. Record VPT blocks and return whether the
203     // instruction is valid for tail predication.
204     bool ValidateMVEInst(MachineInstr *MI);
205 
206     void AnalyseMVEInst(MachineInstr *MI) {
207       CannotTailPredicate = !ValidateMVEInst(MI);
208     }
209 
210     bool IsTailPredicationLegal() const {
211       // For now, let's keep things really simple and only support a single
212       // block for tail predication.
213       return !Revert && FoundAllComponents() && VCTP &&
214              !CannotTailPredicate && ML.getNumBlocks() == 1;
215     }
216 
217     // Check that the predication in the loop will be equivalent once we
218     // perform the conversion. Also ensure that we can provide the number
219     // of elements to the loop start instruction.
220     bool ValidateTailPredicate(MachineInstr *StartInsertPt);
221 
222     // Check that any values available outside of the loop will be the same
223     // after tail predication conversion.
224     bool ValidateLiveOuts() const;
225 
226     // Is it safe to define LR with DLS/WLS?
227     // LR can be defined if it is the operand to start, because it's the same
228     // value, or if it's going to be equivalent to the operand to Start.
229     MachineInstr *isSafeToDefineLR();
230 
231     // Check the branch targets are within range and we satisfy our
232     // restrictions.
233     void CheckLegality(ARMBasicBlockUtils *BBUtils);
234 
235     bool FoundAllComponents() const {
236       return Start && Dec && End;
237     }
238 
239     SmallVectorImpl<VPTBlock> &getVPTBlocks() { return VPTBlocks; }
240 
241     // Return the loop iteration count, or the number of elements if we're tail
242     // predicating.
243     MachineOperand &getCount() {
244       return IsTailPredicationLegal() ?
245         VCTP->getOperand(1) : Start->getOperand(0);
246     }
247 
248     unsigned getStartOpcode() const {
249       bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
250       if (!IsTailPredicationLegal())
251         return IsDo ? ARM::t2DLS : ARM::t2WLS;
252 
253       return VCTPOpcodeToLSTP(VCTP->getOpcode(), IsDo);
254     }
255 
256     void dump() const {
257       if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start;
258       if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec;
259       if (End) dbgs() << "ARM Loops: Found Loop End: " << *End;
260       if (VCTP) dbgs() << "ARM Loops: Found VCTP: " << *VCTP;
261       if (!FoundAllComponents())
262         dbgs() << "ARM Loops: Not a low-overhead loop.\n";
263       else if (!(Start && Dec && End))
264         dbgs() << "ARM Loops: Failed to find all loop components.\n";
265     }
266   };
267 
268   class ARMLowOverheadLoops : public MachineFunctionPass {
269     MachineFunction           *MF = nullptr;
270     MachineLoopInfo           *MLI = nullptr;
271     ReachingDefAnalysis       *RDA = nullptr;
272     const ARMBaseInstrInfo    *TII = nullptr;
273     MachineRegisterInfo       *MRI = nullptr;
274     const TargetRegisterInfo  *TRI = nullptr;
275     std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
276 
277   public:
278     static char ID;
279 
280     ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
281 
282     void getAnalysisUsage(AnalysisUsage &AU) const override {
283       AU.setPreservesCFG();
284       AU.addRequired<MachineLoopInfo>();
285       AU.addRequired<ReachingDefAnalysis>();
286       MachineFunctionPass::getAnalysisUsage(AU);
287     }
288 
289     bool runOnMachineFunction(MachineFunction &MF) override;
290 
291     MachineFunctionProperties getRequiredProperties() const override {
292       return MachineFunctionProperties().set(
293           MachineFunctionProperties::Property::NoVRegs).set(
294           MachineFunctionProperties::Property::TracksLiveness);
295     }
296 
297     StringRef getPassName() const override {
298       return ARM_LOW_OVERHEAD_LOOPS_NAME;
299     }
300 
301   private:
302     bool ProcessLoop(MachineLoop *ML);
303 
304     bool RevertNonLoops();
305 
306     void RevertWhile(MachineInstr *MI) const;
307 
308     bool RevertLoopDec(MachineInstr *MI) const;
309 
310     void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const;
311 
312     void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
313 
314     MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
315 
316     void Expand(LowOverheadLoop &LoLoop);
317 
318     void IterationCountDCE(LowOverheadLoop &LoLoop);
319   };
320 }
321 
322 char ARMLowOverheadLoops::ID = 0;
323 
324 INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME,
325                 false, false)
326 
327 MachineInstr *LowOverheadLoop::isSafeToDefineLR() {
328   // We can define LR because LR already contains the same value.
329   if (Start->getOperand(0).getReg() == ARM::LR)
330     return Start;
331 
332   unsigned CountReg = Start->getOperand(0).getReg();
333   auto IsMoveLR = [&CountReg](MachineInstr *MI) {
334     return MI->getOpcode() == ARM::tMOVr &&
335            MI->getOperand(0).getReg() == ARM::LR &&
336            MI->getOperand(1).getReg() == CountReg &&
337            MI->getOperand(2).getImm() == ARMCC::AL;
338    };
339 
340   MachineBasicBlock *MBB = Start->getParent();
341 
342   // Find an insertion point:
343   // - Is there a (mov lr, Count) before Start? If so, and nothing else writes
344   //   to Count before Start, we can insert at that mov.
345   if (auto *LRDef = RDA.getUniqueReachingMIDef(Start, ARM::LR))
346     if (IsMoveLR(LRDef) && RDA.hasSameReachingDef(Start, LRDef, CountReg))
347       return LRDef;
348 
349   // - Is there a (mov lr, Count) after Start? If so, and nothing else writes
350   //   to Count after Start, we can insert at that mov.
351   if (auto *LRDef = RDA.getLocalLiveOutMIDef(MBB, ARM::LR))
352     if (IsMoveLR(LRDef) && RDA.hasSameReachingDef(Start, LRDef, CountReg))
353       return LRDef;
354 
355   // We've found no suitable LR def and Start doesn't use LR directly. Can we
356   // just define LR anyway?
357   return RDA.isSafeToDefRegAt(Start, ARM::LR) ? Start : nullptr;
358 }
359 
360 bool LowOverheadLoop::ValidateTailPredicate(MachineInstr *StartInsertPt) {
361   assert(VCTP && "VCTP instruction expected but is not set");
362   // All predication within the loop should be based on vctp. If the block
363   // isn't predicated on entry, check whether the vctp is within the block
364   // and that all other instructions are then predicated on it.
365   for (auto &Block : VPTBlocks) {
366     if (Block.IsPredicatedOn(VCTP))
367       continue;
368     if (!Block.HasNonUniformPredicate() || !isVCTP(Block.getDivergent()->MI)) {
369       LLVM_DEBUG(dbgs() << "ARM Loops: Found unsupported diverging predicate: "
370                  << *Block.getDivergent()->MI);
371       return false;
372     }
373     SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts();
374     for (auto &PredMI : Insts) {
375       if (PredMI.Predicates.count(VCTP) || isVCTP(PredMI.MI))
376         continue;
377       LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *PredMI.MI
378                  << " - which is predicated on:\n";
379                  for (auto *MI : PredMI.Predicates)
380                    dbgs() << "   - " << *MI);
381       return false;
382     }
383   }
384 
385   if (!ValidateLiveOuts())
386     return false;
387 
388   // For tail predication, we need to provide the number of elements, instead
389   // of the iteration count, to the loop start instruction. The number of
390   // elements is provided to the vctp instruction, so we need to check that
391   // we can use this register at InsertPt.
392   Register NumElements = VCTP->getOperand(1).getReg();
393 
394   // If the register is defined within loop, then we can't perform TP.
395   // TODO: Check whether this is just a mov of a register that would be
396   // available.
397   if (RDA.hasLocalDefBefore(VCTP, NumElements)) {
398     LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
399     return false;
400   }
401 
402   // The element count register maybe defined after InsertPt, in which case we
403   // need to try to move either InsertPt or the def so that the [w|d]lstp can
404   // use the value.
405   // TODO: On failing to move an instruction, check if the count is provided by
406   // a mov and whether we can use the mov operand directly.
407   MachineBasicBlock *InsertBB = StartInsertPt->getParent();
408   if (!RDA.isReachingDefLiveOut(StartInsertPt, NumElements)) {
409     if (auto *ElemDef = RDA.getLocalLiveOutMIDef(InsertBB, NumElements)) {
410       if (RDA.isSafeToMoveForwards(ElemDef, StartInsertPt)) {
411         ElemDef->removeFromParent();
412         InsertBB->insert(MachineBasicBlock::iterator(StartInsertPt), ElemDef);
413         LLVM_DEBUG(dbgs() << "ARM Loops: Moved element count def: "
414                    << *ElemDef);
415       } else if (RDA.isSafeToMoveBackwards(StartInsertPt, ElemDef)) {
416         StartInsertPt->removeFromParent();
417         InsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef),
418                               StartInsertPt);
419         LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef);
420       } else {
421         LLVM_DEBUG(dbgs() << "ARM Loops: Unable to move element count to loop "
422                    << "start instruction.\n");
423         return false;
424       }
425     }
426   }
427 
428   // Especially in the case of while loops, InsertBB may not be the
429   // preheader, so we need to check that the register isn't redefined
430   // before entering the loop.
431   auto CannotProvideElements = [this](MachineBasicBlock *MBB,
432                                       Register NumElements) {
433     // NumElements is redefined in this block.
434     if (RDA.hasLocalDefBefore(&MBB->back(), NumElements))
435       return true;
436 
437     // Don't continue searching up through multiple predecessors.
438     if (MBB->pred_size() > 1)
439       return true;
440 
441     return false;
442   };
443 
444   // First, find the block that looks like the preheader.
445   MachineBasicBlock *MBB = MLI.findLoopPreheader(&ML, true);
446   if (!MBB) {
447     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find preheader.\n");
448     return false;
449   }
450 
451   // Then search backwards for a def, until we get to InsertBB.
452   while (MBB != InsertBB) {
453     if (CannotProvideElements(MBB, NumElements)) {
454       LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
455       return false;
456     }
457     MBB = *MBB->pred_begin();
458   }
459 
460   // Check that the value change of the element count is what we expect and
461   // that the predication will be equivalent. For this we need:
462   // NumElements = NumElements - VectorWidth. The sub will be a sub immediate
463   // and we can also allow register copies within the chain too.
464   auto IsValidSub = [](MachineInstr *MI, unsigned ExpectedVecWidth) {
465     unsigned ImmOpIdx = 0;
466     switch (MI->getOpcode()) {
467     default:
468       llvm_unreachable("unhandled sub opcode");
469     case ARM::tSUBi3:
470     case ARM::tSUBi8:
471       ImmOpIdx = 3;
472       break;
473     case ARM::t2SUBri:
474     case ARM::t2SUBri12:
475       ImmOpIdx = 2;
476       break;
477     }
478     return MI->getOperand(ImmOpIdx).getImm() == ExpectedVecWidth;
479   };
480 
481   MBB = VCTP->getParent();
482   if (auto *Def = RDA.getUniqueReachingMIDef(&MBB->back(), NumElements)) {
483     SmallPtrSet<MachineInstr*, 2> ElementChain;
484     SmallPtrSet<MachineInstr*, 2> Ignore = { VCTP };
485     unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode());
486 
487     if (RDA.isSafeToRemove(Def, ElementChain, Ignore)) {
488       bool FoundSub = false;
489 
490       for (auto *MI : ElementChain) {
491         if (isMovRegOpcode(MI->getOpcode()))
492           continue;
493 
494         if (isSubImmOpcode(MI->getOpcode())) {
495           if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth))
496             return false;
497           FoundSub = true;
498         } else
499           return false;
500       }
501 
502       LLVM_DEBUG(dbgs() << "ARM Loops: Will remove element count chain:\n";
503                  for (auto *MI : ElementChain)
504                    dbgs() << " - " << *MI);
505       ToRemove.insert(ElementChain.begin(), ElementChain.end());
506     }
507   }
508   return true;
509 }
510 
511 static bool isVectorPredicated(MachineInstr *MI) {
512   int PIdx = llvm::findFirstVPTPredOperandIdx(*MI);
513   return PIdx != -1 && MI->getOperand(PIdx + 1).getReg() == ARM::VPR;
514 }
515 
516 static bool isRegInClass(const MachineOperand &MO,
517                          const TargetRegisterClass *Class) {
518   return MO.isReg() && MO.getReg() && Class->contains(MO.getReg());
519 }
520 
521 bool LowOverheadLoop::ValidateLiveOuts() const {
522   // We want to find out if the tail-predicated version of this loop will
523   // produce the same values as the loop in its original form. For this to
524   // be true, the newly inserted implicit predication must not change the
525   // the (observable) results.
526   // We're doing this because many instructions in the loop will not be
527   // predicated and so the conversion from VPT predication to tail-predication
528   // can result in different values being produced; due to the tail-predication
529   // preventing many instructions from updating their falsely predicated
530   // lanes. This analysis assumes that all the instructions perform lane-wise
531   // operations and don't perform any exchanges.
532   // A masked load, whether through VPT or tail predication, will write zeros
533   // to any of the falsely predicated bytes. So, from the loads, we know that
534   // the false lanes are zeroed and here we're trying to track that those false
535   // lanes remain zero, or where they change, the differences are masked away
536   // by their user(s).
537   // All MVE loads and stores have to be predicated, so we know that any load
538   // operands, or stored results are equivalent already. Other explicitly
539   // predicated instructions will perform the same operation in the original
540   // loop and the tail-predicated form too. Because of this, we can insert
541   // loads, stores and other predicated instructions into our KnownFalseZeros
542   // set and build from there.
543   const TargetRegisterClass *QPRs = TRI.getRegClass(ARM::MQPRRegClassID);
544   SetVector<MachineInstr *> UnknownFalseLanes;
545   SmallPtrSet<MachineInstr *, 4> KnownFalseZeros;
546   MachineBasicBlock *MBB = ML.getHeader();
547   for (auto &MI : *MBB) {
548     const MCInstrDesc &MCID = MI.getDesc();
549     uint64_t Flags = MCID.TSFlags;
550     if ((Flags & ARMII::DomainMask) != ARMII::DomainMVE)
551       continue;
552 
553     if (isVectorPredicated(&MI)) {
554       KnownFalseZeros.insert(&MI);
555       continue;
556     }
557 
558     if (MI.getNumDefs() == 0)
559       continue;
560 
561     // Only evaluate instructions which produce a single value.
562     assert((MI.getNumDefs() == 1 && MI.defs().begin()->isReg()) &&
563            "Expected no more than one register def");
564 
565     Register DefReg = MI.defs().begin()->getReg();
566     for (auto &MO : MI.operands()) {
567       if (!isRegInClass(MO, QPRs) || !MO.isUse() || MO.getReg() != DefReg)
568         continue;
569 
570       // If this instruction overwrites one of its operands, and that register
571       // has known lanes, then this instruction also has known predicated false
572       // lanes.
573       if (auto *OpDef = RDA.getMIOperand(&MI, MO)) {
574         if (KnownFalseZeros.count(OpDef)) {
575           KnownFalseZeros.insert(&MI);
576           break;
577         }
578       }
579     }
580     if (!KnownFalseZeros.count(&MI))
581       UnknownFalseLanes.insert(&MI);
582   }
583 
584   auto HasKnownUsers = [this](MachineInstr *MI, const MachineOperand &MO,
585                               SmallPtrSetImpl<MachineInstr *> &Knowns) {
586     SmallPtrSet<MachineInstr *, 2> Uses;
587     RDA.getGlobalUses(MI, MO.getReg(), Uses);
588     for (auto *Use : Uses) {
589       if (Use != MI && !Knowns.count(Use))
590         return false;
591     }
592     return true;
593   };
594 
595   // Now for all the unknown values, see if they're only consumed by known
596   // instructions. Visit in reverse so that we can start at the values being
597   // stored and then we can work towards the leaves, hopefully adding more
598   // instructions to KnownFalseZeros.
599   for (auto *MI : reverse(UnknownFalseLanes)) {
600     for (auto &MO : MI->operands()) {
601       if (!isRegInClass(MO, QPRs) || !MO.isDef())
602         continue;
603       if (!HasKnownUsers(MI, MO, KnownFalseZeros)) {
604         LLVM_DEBUG(dbgs() << "ARM Loops: Found an unknown def of : "
605                           << TRI.getRegAsmName(MO.getReg()) << " at " << *MI);
606         return false;
607       }
608     }
609     // Any unknown false lanes have been masked away by the user(s).
610     KnownFalseZeros.insert(MI);
611   }
612 
613   // Collect Q-regs that are live in the exit blocks. We don't collect scalars
614   // because they won't be affected by lane predication.
615   SmallSet<Register, 2> LiveOuts;
616   SmallVector<MachineBasicBlock *, 2> ExitBlocks;
617   ML.getExitBlocks(ExitBlocks);
618   for (auto *MBB : ExitBlocks)
619     for (const MachineBasicBlock::RegisterMaskPair &RegMask : MBB->liveins())
620       if (QPRs->contains(RegMask.PhysReg))
621         LiveOuts.insert(RegMask.PhysReg);
622 
623   // Collect the instructions in the loop body that define the live-out values.
624   SmallPtrSet<MachineInstr *, 2> LiveMIs;
625   assert(ML.getNumBlocks() == 1 && "Expected single block loop!");
626   for (auto Reg : LiveOuts)
627     if (auto *MI = RDA.getLocalLiveOutMIDef(MBB, Reg))
628       LiveMIs.insert(MI);
629 
630   LLVM_DEBUG(dbgs() << "ARM Loops: Found loop live-outs:\n";
631              for (auto *MI : LiveMIs)
632                dbgs() << " - " << *MI);
633   // We've already validated that any VPT predication within the loop will be
634   // equivalent when we perform the predication transformation; so we know that
635   // any VPT predicated instruction is predicated upon VCTP. Any live-out
636   // instruction needs to be predicated, so check this here.
637   for (auto *MI : LiveMIs)
638     if (!isVectorPredicated(MI))
639       return false;
640 
641   return true;
642 }
643 
644 void LowOverheadLoop::CheckLegality(ARMBasicBlockUtils *BBUtils) {
645   if (Revert)
646     return;
647 
648   if (!End->getOperand(1).isMBB())
649     report_fatal_error("Expected LoopEnd to target basic block");
650 
651   // TODO Maybe there's cases where the target doesn't have to be the header,
652   // but for now be safe and revert.
653   if (End->getOperand(1).getMBB() != ML.getHeader()) {
654     LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targetting header.\n");
655     Revert = true;
656     return;
657   }
658 
659   // The WLS and LE instructions have 12-bits for the label offset. WLS
660   // requires a positive offset, while LE uses negative.
661   if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML.getHeader()) ||
662       !BBUtils->isBBInRange(End, ML.getHeader(), 4094)) {
663     LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n");
664     Revert = true;
665     return;
666   }
667 
668   if (Start->getOpcode() == ARM::t2WhileLoopStart &&
669       (BBUtils->getOffsetOf(Start) >
670        BBUtils->getOffsetOf(Start->getOperand(1).getMBB()) ||
671        !BBUtils->isBBInRange(Start, Start->getOperand(1).getMBB(), 4094))) {
672     LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n");
673     Revert = true;
674     return;
675   }
676 
677   InsertPt = Revert ? nullptr : isSafeToDefineLR();
678   if (!InsertPt) {
679     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to find safe insertion point.\n");
680     Revert = true;
681     return;
682   } else
683     LLVM_DEBUG(dbgs() << "ARM Loops: Start insertion point: " << *InsertPt);
684 
685   if (!IsTailPredicationLegal()) {
686     LLVM_DEBUG(if (!VCTP)
687                  dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
688                dbgs() << "ARM Loops: Tail-predication is not valid.\n");
689     return;
690   }
691 
692   assert(ML.getBlocks().size() == 1 &&
693          "Shouldn't be processing a loop with more than one block");
694   CannotTailPredicate = !ValidateTailPredicate(InsertPt);
695   LLVM_DEBUG(if (CannotTailPredicate)
696              dbgs() << "ARM Loops: Couldn't validate tail predicate.\n");
697 }
698 
699 bool LowOverheadLoop::ValidateMVEInst(MachineInstr* MI) {
700   if (CannotTailPredicate)
701     return false;
702 
703   // Only support a single vctp.
704   if (isVCTP(MI) && VCTP)
705     return false;
706 
707   // Start a new vpt block when we discover a vpt.
708   if (MI->getOpcode() == ARM::MVE_VPST) {
709     VPTBlocks.emplace_back(MI, CurrentPredicate);
710     CurrentBlock = &VPTBlocks.back();
711     return true;
712   } else if (isVCTP(MI))
713     VCTP = MI;
714   else if (MI->getOpcode() == ARM::MVE_VPSEL ||
715            MI->getOpcode() == ARM::MVE_VPNOT)
716     return false;
717 
718   // TODO: Allow VPSEL and VPNOT, we currently cannot because:
719   // 1) It will use the VPR as a predicate operand, but doesn't have to be
720   //    instead a VPT block, which means we can assert while building up
721   //    the VPT block because we don't find another VPST to being a new
722   //    one.
723   // 2) VPSEL still requires a VPR operand even after tail predicating,
724   //    which means we can't remove it unless there is another
725   //    instruction, such as vcmp, that can provide the VPR def.
726 
727   bool IsUse = false;
728   bool IsDef = false;
729   const MCInstrDesc &MCID = MI->getDesc();
730   for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
731     const MachineOperand &MO = MI->getOperand(i);
732     if (!MO.isReg() || MO.getReg() != ARM::VPR)
733       continue;
734 
735     if (MO.isDef()) {
736       CurrentPredicate.insert(MI);
737       IsDef = true;
738     } else if (ARM::isVpred(MCID.OpInfo[i].OperandType)) {
739       CurrentBlock->addInst(MI, CurrentPredicate);
740       IsUse = true;
741     } else {
742       LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI);
743       return false;
744     }
745   }
746 
747   // If we find a vpr def that is not already predicated on the vctp, we've
748   // got disjoint predicates that may not be equivalent when we do the
749   // conversion.
750   if (IsDef && !IsUse && VCTP && !isVCTP(MI)) {
751     LLVM_DEBUG(dbgs() << "ARM Loops: Found disjoint vpr def: " << *MI);
752     return false;
753   }
754 
755   uint64_t Flags = MCID.TSFlags;
756   if ((Flags & ARMII::DomainMask) != ARMII::DomainMVE)
757     return true;
758 
759   // If we find an instruction that has been marked as not valid for tail
760   // predication, only allow the instruction if it's contained within a valid
761   // VPT block.
762   if ((Flags & ARMII::ValidForTailPredication) == 0 && !IsUse) {
763     LLVM_DEBUG(dbgs() << "ARM Loops: Can't tail predicate: " << *MI);
764     return false;
765   }
766 
767   // If the instruction is already explicitly predicated, then the conversion
768   // will be fine, but ensure that all memory operations are predicated.
769   return !IsUse && MI->mayLoadOrStore() ? false : true;
770 }
771 
772 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) {
773   const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget());
774   if (!ST.hasLOB())
775     return false;
776 
777   MF = &mf;
778   LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n");
779 
780   MLI = &getAnalysis<MachineLoopInfo>();
781   RDA = &getAnalysis<ReachingDefAnalysis>();
782   MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
783   MRI = &MF->getRegInfo();
784   TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo());
785   TRI = ST.getRegisterInfo();
786   BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF));
787   BBUtils->computeAllBlockSizes();
788   BBUtils->adjustBBOffsetsAfter(&MF->front());
789 
790   bool Changed = false;
791   for (auto ML : *MLI) {
792     if (!ML->getParentLoop())
793       Changed |= ProcessLoop(ML);
794   }
795   Changed |= RevertNonLoops();
796   return Changed;
797 }
798 
799 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) {
800 
801   bool Changed = false;
802 
803   // Process inner loops first.
804   for (auto I = ML->begin(), E = ML->end(); I != E; ++I)
805     Changed |= ProcessLoop(*I);
806 
807   LLVM_DEBUG(dbgs() << "ARM Loops: Processing loop containing:\n";
808              if (auto *Preheader = ML->getLoopPreheader())
809                dbgs() << " - " << Preheader->getName() << "\n";
810              else if (auto *Preheader = MLI->findLoopPreheader(ML))
811                dbgs() << " - " << Preheader->getName() << "\n";
812              else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
813                dbgs() << " - " << Preheader->getName() << "\n";
814              for (auto *MBB : ML->getBlocks())
815                dbgs() << " - " << MBB->getName() << "\n";
816             );
817 
818   // Search the given block for a loop start instruction. If one isn't found,
819   // and there's only one predecessor block, search that one too.
820   std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
821     [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* {
822     for (auto &MI : *MBB) {
823       if (isLoopStart(MI))
824         return &MI;
825     }
826     if (MBB->pred_size() == 1)
827       return SearchForStart(*MBB->pred_begin());
828     return nullptr;
829   };
830 
831   LowOverheadLoop LoLoop(*ML, *MLI, *RDA, *TRI);
832   // Search the preheader for the start intrinsic.
833   // FIXME: I don't see why we shouldn't be supporting multiple predecessors
834   // with potentially multiple set.loop.iterations, so we need to enable this.
835   if (auto *Preheader = ML->getLoopPreheader())
836     LoLoop.Start = SearchForStart(Preheader);
837   else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
838     LoLoop.Start = SearchForStart(Preheader);
839   else
840     return false;
841 
842   // Find the low-overhead loop components and decide whether or not to fall
843   // back to a normal loop. Also look for a vctp instructions and decide
844   // whether we can convert that predicate using tail predication.
845   for (auto *MBB : reverse(ML->getBlocks())) {
846     for (auto &MI : *MBB) {
847       if (MI.isDebugValue())
848         continue;
849       else if (MI.getOpcode() == ARM::t2LoopDec)
850         LoLoop.Dec = &MI;
851       else if (MI.getOpcode() == ARM::t2LoopEnd)
852         LoLoop.End = &MI;
853       else if (isLoopStart(MI))
854         LoLoop.Start = &MI;
855       else if (MI.getDesc().isCall()) {
856         // TODO: Though the call will require LE to execute again, does this
857         // mean we should revert? Always executing LE hopefully should be
858         // faster than performing a sub,cmp,br or even subs,br.
859         LoLoop.Revert = true;
860         LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
861       } else {
862         // Record VPR defs and build up their corresponding vpt blocks.
863         // Check we know how to tail predicate any mve instructions.
864         LoLoop.AnalyseMVEInst(&MI);
865       }
866     }
867   }
868 
869   LLVM_DEBUG(LoLoop.dump());
870   if (!LoLoop.FoundAllComponents()) {
871     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
872     return false;
873   }
874 
875   // Check that the only instruction using LoopDec is LoopEnd.
876   // TODO: Check for copy chains that really have no effect.
877   SmallPtrSet<MachineInstr*, 2> Uses;
878   RDA->getReachingLocalUses(LoLoop.Dec, ARM::LR, Uses);
879   if (Uses.size() > 1 || !Uses.count(LoLoop.End)) {
880     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n");
881     LoLoop.Revert = true;
882   }
883   LoLoop.CheckLegality(BBUtils.get());
884   Expand(LoLoop);
885   return true;
886 }
887 
888 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
889 // beq that branches to the exit branch.
890 // TODO: We could also try to generate a cbz if the value in LR is also in
891 // another low register.
892 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const {
893   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI);
894   MachineBasicBlock *MBB = MI->getParent();
895   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
896                                     TII->get(ARM::t2CMPri));
897   MIB.add(MI->getOperand(0));
898   MIB.addImm(0);
899   MIB.addImm(ARMCC::AL);
900   MIB.addReg(ARM::NoRegister);
901 
902   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
903   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
904     ARM::tBcc : ARM::t2Bcc;
905 
906   MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
907   MIB.add(MI->getOperand(1));   // branch target
908   MIB.addImm(ARMCC::EQ);        // condition code
909   MIB.addReg(ARM::CPSR);
910   MI->eraseFromParent();
911 }
912 
913 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const {
914   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI);
915   MachineBasicBlock *MBB = MI->getParent();
916   SmallPtrSet<MachineInstr*, 1> Ignore;
917   for (auto I = MachineBasicBlock::iterator(MI), E = MBB->end(); I != E; ++I) {
918     if (I->getOpcode() == ARM::t2LoopEnd) {
919       Ignore.insert(&*I);
920       break;
921     }
922   }
923 
924   // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
925   bool SetFlags = RDA->isSafeToDefRegAt(MI, ARM::CPSR, Ignore);
926 
927   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
928                                     TII->get(ARM::t2SUBri));
929   MIB.addDef(ARM::LR);
930   MIB.add(MI->getOperand(1));
931   MIB.add(MI->getOperand(2));
932   MIB.addImm(ARMCC::AL);
933   MIB.addReg(0);
934 
935   if (SetFlags) {
936     MIB.addReg(ARM::CPSR);
937     MIB->getOperand(5).setIsDef(true);
938   } else
939     MIB.addReg(0);
940 
941   MI->eraseFromParent();
942   return SetFlags;
943 }
944 
945 // Generate a subs, or sub and cmp, and a branch instead of an LE.
946 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const {
947   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI);
948 
949   MachineBasicBlock *MBB = MI->getParent();
950   // Create cmp
951   if (!SkipCmp) {
952     MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
953                                       TII->get(ARM::t2CMPri));
954     MIB.addReg(ARM::LR);
955     MIB.addImm(0);
956     MIB.addImm(ARMCC::AL);
957     MIB.addReg(ARM::NoRegister);
958   }
959 
960   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
961   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
962     ARM::tBcc : ARM::t2Bcc;
963 
964   // Create bne
965   MachineInstrBuilder MIB =
966     BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
967   MIB.add(MI->getOperand(1));   // branch target
968   MIB.addImm(ARMCC::NE);        // condition code
969   MIB.addReg(ARM::CPSR);
970   MI->eraseFromParent();
971 }
972 
973 // Perform dead code elimation on the loop iteration count setup expression.
974 // If we are tail-predicating, the number of elements to be processed is the
975 // operand of the VCTP instruction in the vector body, see getCount(), which is
976 // register $r3 in this example:
977 //
978 //   $lr = big-itercount-expression
979 //   ..
980 //   t2DoLoopStart renamable $lr
981 //   vector.body:
982 //     ..
983 //     $vpr = MVE_VCTP32 renamable $r3
984 //     renamable $lr = t2LoopDec killed renamable $lr, 1
985 //     t2LoopEnd renamable $lr, %vector.body
986 //     tB %end
987 //
988 // What we would like achieve here is to replace the do-loop start pseudo
989 // instruction t2DoLoopStart with:
990 //
991 //    $lr = MVE_DLSTP_32 killed renamable $r3
992 //
993 // Thus, $r3 which defines the number of elements, is written to $lr,
994 // and then we want to delete the whole chain that used to define $lr,
995 // see the comment below how this chain could look like.
996 //
997 void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) {
998   if (!LoLoop.IsTailPredicationLegal())
999     return;
1000 
1001   LLVM_DEBUG(dbgs() << "ARM Loops: Trying DCE on loop iteration count.\n");
1002 
1003   MachineInstr *Def = RDA->getMIOperand(LoLoop.Start, 0);
1004   if (!Def) {
1005     LLVM_DEBUG(dbgs() << "ARM Loops: Couldn't find iteration count.\n");
1006     return;
1007   }
1008 
1009   // Collect and remove the users of iteration count.
1010   SmallPtrSet<MachineInstr*, 4> Killed  = { LoLoop.Start, LoLoop.Dec,
1011                                             LoLoop.End, LoLoop.InsertPt };
1012   SmallPtrSet<MachineInstr*, 2> Remove;
1013   if (RDA->isSafeToRemove(Def, Remove, Killed))
1014     LoLoop.ToRemove.insert(Remove.begin(), Remove.end());
1015   else {
1016     LLVM_DEBUG(dbgs() << "ARM Loops: Unsafe to remove loop iteration count.\n");
1017     return;
1018   }
1019 
1020   // Collect the dead code and the MBBs in which they reside.
1021   RDA->collectKilledOperands(Def, Killed);
1022   SmallPtrSet<MachineBasicBlock*, 2> BasicBlocks;
1023   for (auto *MI : Killed)
1024     BasicBlocks.insert(MI->getParent());
1025 
1026   // Collect IT blocks in all affected basic blocks.
1027   std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks;
1028   for (auto *MBB : BasicBlocks) {
1029     for (auto &MI : *MBB) {
1030       if (MI.getOpcode() != ARM::t2IT)
1031         continue;
1032       RDA->getReachingLocalUses(&MI, ARM::ITSTATE, ITBlocks[&MI]);
1033     }
1034   }
1035 
1036   // If we're removing all of the instructions within an IT block, then
1037   // also remove the IT instruction.
1038   SmallPtrSet<MachineInstr*, 2> ModifiedITs;
1039   for (auto *MI : Killed) {
1040     if (MachineOperand *MO = MI->findRegisterUseOperand(ARM::ITSTATE)) {
1041       MachineInstr *IT = RDA->getMIOperand(MI, *MO);
1042       auto &CurrentBlock = ITBlocks[IT];
1043       CurrentBlock.erase(MI);
1044       if (CurrentBlock.empty())
1045         ModifiedITs.erase(IT);
1046       else
1047         ModifiedITs.insert(IT);
1048     }
1049   }
1050 
1051   // Delete the killed instructions only if we don't have any IT blocks that
1052   // need to be modified because we need to fixup the mask.
1053   // TODO: Handle cases where IT blocks are modified.
1054   if (ModifiedITs.empty()) {
1055     LLVM_DEBUG(dbgs() << "ARM Loops: Will remove iteration count:\n";
1056                for (auto *MI : Killed)
1057                  dbgs() << " - " << *MI);
1058     LoLoop.ToRemove.insert(Killed.begin(), Killed.end());
1059   } else
1060     LLVM_DEBUG(dbgs() << "ARM Loops: Would need to modify IT block(s).\n");
1061 }
1062 
1063 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
1064   LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n");
1065   // When using tail-predication, try to delete the dead code that was used to
1066   // calculate the number of loop iterations.
1067   IterationCountDCE(LoLoop);
1068 
1069   MachineInstr *InsertPt = LoLoop.InsertPt;
1070   MachineInstr *Start = LoLoop.Start;
1071   MachineBasicBlock *MBB = InsertPt->getParent();
1072   bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
1073   unsigned Opc = LoLoop.getStartOpcode();
1074   MachineOperand &Count = LoLoop.getCount();
1075 
1076   MachineInstrBuilder MIB =
1077     BuildMI(*MBB, InsertPt, InsertPt->getDebugLoc(), TII->get(Opc));
1078 
1079   MIB.addDef(ARM::LR);
1080   MIB.add(Count);
1081   if (!IsDo)
1082     MIB.add(Start->getOperand(1));
1083 
1084   // If we're inserting at a mov lr, then remove it as it's redundant.
1085   if (InsertPt != Start)
1086     LoLoop.ToRemove.insert(InsertPt);
1087   LoLoop.ToRemove.insert(Start);
1088   LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB);
1089   return &*MIB;
1090 }
1091 
1092 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
1093   auto RemovePredicate = [](MachineInstr *MI) {
1094     LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI);
1095     if (int PIdx = llvm::findFirstVPTPredOperandIdx(*MI)) {
1096       assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then &&
1097              "Expected Then predicate!");
1098       MI->getOperand(PIdx).setImm(ARMVCC::None);
1099       MI->getOperand(PIdx+1).setReg(0);
1100     } else
1101       llvm_unreachable("trying to unpredicate a non-predicated instruction");
1102   };
1103 
1104   // There are a few scenarios which we have to fix up:
1105   // 1) A VPT block with is only predicated by the vctp and has no internal vpr
1106   //    defs.
1107   // 2) A VPT block which is only predicated by the vctp but has an internal
1108   //    vpr def.
1109   // 3) A VPT block which is predicated upon the vctp as well as another vpr
1110   //    def.
1111   // 4) A VPT block which is not predicated upon a vctp, but contains it and
1112   //    all instructions within the block are predicated upon in.
1113 
1114   for (auto &Block : LoLoop.getVPTBlocks()) {
1115     SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts();
1116     if (Block.HasNonUniformPredicate()) {
1117       PredicatedMI *Divergent = Block.getDivergent();
1118       if (isVCTP(Divergent->MI)) {
1119         // The vctp will be removed, so the size of the vpt block needs to be
1120         // modified.
1121         uint64_t Size = getARMVPTBlockMask(Block.size() - 1);
1122         Block.getVPST()->getOperand(0).setImm(Size);
1123         LLVM_DEBUG(dbgs() << "ARM Loops: Modified VPT block mask.\n");
1124       } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) {
1125         // The VPT block has a non-uniform predicate but it's entry is guarded
1126         // only by a vctp, which means we:
1127         // - Need to remove the original vpst.
1128         // - Then need to unpredicate any following instructions, until
1129         //   we come across the divergent vpr def.
1130         // - Insert a new vpst to predicate the instruction(s) that following
1131         //   the divergent vpr def.
1132         // TODO: We could be producing more VPT blocks than necessary and could
1133         // fold the newly created one into a proceeding one.
1134         for (auto I = ++MachineBasicBlock::iterator(Block.getVPST()),
1135              E = ++MachineBasicBlock::iterator(Divergent->MI); I != E; ++I)
1136           RemovePredicate(&*I);
1137 
1138         unsigned Size = 0;
1139         auto E = MachineBasicBlock::reverse_iterator(Divergent->MI);
1140         auto I = MachineBasicBlock::reverse_iterator(Insts.back().MI);
1141         MachineInstr *InsertAt = nullptr;
1142         while (I != E) {
1143           InsertAt = &*I;
1144           ++Size;
1145           ++I;
1146         }
1147         MachineInstrBuilder MIB = BuildMI(*InsertAt->getParent(), InsertAt,
1148                                           InsertAt->getDebugLoc(),
1149                                           TII->get(ARM::MVE_VPST));
1150         MIB.addImm(getARMVPTBlockMask(Size));
1151         LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST());
1152         LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB);
1153         LoLoop.ToRemove.insert(Block.getVPST());
1154       }
1155     } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) {
1156       // A vpt block which is only predicated upon vctp and has no internal vpr
1157       // defs:
1158       // - Remove vpst.
1159       // - Unpredicate the remaining instructions.
1160       LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST());
1161       LoLoop.ToRemove.insert(Block.getVPST());
1162       for (auto &PredMI : Insts)
1163         RemovePredicate(PredMI.MI);
1164     }
1165   }
1166   LLVM_DEBUG(dbgs() << "ARM Loops: Removing VCTP: " << *LoLoop.VCTP);
1167   LoLoop.ToRemove.insert(LoLoop.VCTP);
1168 }
1169 
1170 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
1171 
1172   // Combine the LoopDec and LoopEnd instructions into LE(TP).
1173   auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) {
1174     MachineInstr *End = LoLoop.End;
1175     MachineBasicBlock *MBB = End->getParent();
1176     unsigned Opc = LoLoop.IsTailPredicationLegal() ?
1177       ARM::MVE_LETP : ARM::t2LEUpdate;
1178     MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(),
1179                                       TII->get(Opc));
1180     MIB.addDef(ARM::LR);
1181     MIB.add(End->getOperand(0));
1182     MIB.add(End->getOperand(1));
1183     LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB);
1184     LoLoop.ToRemove.insert(LoLoop.Dec);
1185     LoLoop.ToRemove.insert(End);
1186     return &*MIB;
1187   };
1188 
1189   // TODO: We should be able to automatically remove these branches before we
1190   // get here - probably by teaching analyzeBranch about the pseudo
1191   // instructions.
1192   // If there is an unconditional branch, after I, that just branches to the
1193   // next block, remove it.
1194   auto RemoveDeadBranch = [](MachineInstr *I) {
1195     MachineBasicBlock *BB = I->getParent();
1196     MachineInstr *Terminator = &BB->instr_back();
1197     if (Terminator->isUnconditionalBranch() && I != Terminator) {
1198       MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB();
1199       if (BB->isLayoutSuccessor(Succ)) {
1200         LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator);
1201         Terminator->eraseFromParent();
1202       }
1203     }
1204   };
1205 
1206   if (LoLoop.Revert) {
1207     if (LoLoop.Start->getOpcode() == ARM::t2WhileLoopStart)
1208       RevertWhile(LoLoop.Start);
1209     else
1210       LoLoop.Start->eraseFromParent();
1211     bool FlagsAlreadySet = RevertLoopDec(LoLoop.Dec);
1212     RevertLoopEnd(LoLoop.End, FlagsAlreadySet);
1213   } else {
1214     LoLoop.Start = ExpandLoopStart(LoLoop);
1215     RemoveDeadBranch(LoLoop.Start);
1216     LoLoop.End = ExpandLoopEnd(LoLoop);
1217     RemoveDeadBranch(LoLoop.End);
1218     if (LoLoop.IsTailPredicationLegal())
1219       ConvertVPTBlocks(LoLoop);
1220     for (auto *I : LoLoop.ToRemove) {
1221       LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I);
1222       I->eraseFromParent();
1223     }
1224   }
1225 
1226   PostOrderLoopTraversal DFS(LoLoop.ML, *MLI);
1227   DFS.ProcessLoop();
1228   const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
1229   for (auto *MBB : PostOrder) {
1230     recomputeLiveIns(*MBB);
1231     // FIXME: For some reason, the live-in print order is non-deterministic for
1232     // our tests and I can't out why... So just sort them.
1233     MBB->sortUniqueLiveIns();
1234   }
1235 
1236   for (auto *MBB : reverse(PostOrder))
1237     recomputeLivenessFlags(*MBB);
1238 
1239   // We've moved, removed and inserted new instructions, so update RDA.
1240   RDA->reset();
1241 }
1242 
1243 bool ARMLowOverheadLoops::RevertNonLoops() {
1244   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
1245   bool Changed = false;
1246 
1247   for (auto &MBB : *MF) {
1248     SmallVector<MachineInstr*, 4> Starts;
1249     SmallVector<MachineInstr*, 4> Decs;
1250     SmallVector<MachineInstr*, 4> Ends;
1251 
1252     for (auto &I : MBB) {
1253       if (isLoopStart(I))
1254         Starts.push_back(&I);
1255       else if (I.getOpcode() == ARM::t2LoopDec)
1256         Decs.push_back(&I);
1257       else if (I.getOpcode() == ARM::t2LoopEnd)
1258         Ends.push_back(&I);
1259     }
1260 
1261     if (Starts.empty() && Decs.empty() && Ends.empty())
1262       continue;
1263 
1264     Changed = true;
1265 
1266     for (auto *Start : Starts) {
1267       if (Start->getOpcode() == ARM::t2WhileLoopStart)
1268         RevertWhile(Start);
1269       else
1270         Start->eraseFromParent();
1271     }
1272     for (auto *Dec : Decs)
1273       RevertLoopDec(Dec);
1274 
1275     for (auto *End : Ends)
1276       RevertLoopEnd(End);
1277   }
1278   return Changed;
1279 }
1280 
1281 FunctionPass *llvm::createARMLowOverheadLoopsPass() {
1282   return new ARMLowOverheadLoops();
1283 }
1284