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