xref: /llvm-project/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp (revision ac30ea2f877ed82911fd1e3fd9f9d86c8072d05f)
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 = nullptr;
179     MachineLoopInfo *MLI = nullptr;
180     ReachingDefAnalysis *RDA = nullptr;
181     MachineFunction *MF = nullptr;
182     MachineInstr *InsertPt = nullptr;
183     MachineInstr *Start = nullptr;
184     MachineInstr *Dec = nullptr;
185     MachineInstr *End = nullptr;
186     MachineInstr *VCTP = nullptr;
187     VPTBlock *CurrentBlock = nullptr;
188     SetVector<MachineInstr*> CurrentPredicate;
189     SmallVector<VPTBlock, 4> VPTBlocks;
190     SmallPtrSet<MachineInstr*, 4> ToRemove;
191     bool Revert = false;
192     bool CannotTailPredicate = false;
193 
194     LowOverheadLoop(MachineLoop *ML, MachineLoopInfo *MLI,
195                     ReachingDefAnalysis *RDA) : ML(ML), MLI(MLI), RDA(RDA) {
196       MF = ML->getHeader()->getParent();
197     }
198 
199     // If this is an MVE instruction, check that we know how to use tail
200     // predication with it. Record VPT blocks and return whether the
201     // instruction is valid for tail predication.
202     bool ValidateMVEInst(MachineInstr *MI);
203 
204     void AnalyseMVEInst(MachineInstr *MI) {
205       CannotTailPredicate = !ValidateMVEInst(MI);
206     }
207 
208     bool IsTailPredicationLegal() const {
209       // For now, let's keep things really simple and only support a single
210       // block for tail predication.
211       return !Revert && FoundAllComponents() && VCTP &&
212              !CannotTailPredicate && ML->getNumBlocks() == 1;
213     }
214 
215     bool ValidateTailPredicate(MachineInstr *StartInsertPt);
216 
217     // Is it safe to define LR with DLS/WLS?
218     // LR can be defined if it is the operand to start, because it's the same
219     // value, or if it's going to be equivalent to the operand to Start.
220     MachineInstr *isSafeToDefineLR();
221 
222     // Check the branch targets are within range and we satisfy our
223     // restrictions.
224     void CheckLegality(ARMBasicBlockUtils *BBUtils);
225 
226     bool FoundAllComponents() const {
227       return Start && Dec && End;
228     }
229 
230     SmallVectorImpl<VPTBlock> &getVPTBlocks() { return VPTBlocks; }
231 
232     // Return the loop iteration count, or the number of elements if we're tail
233     // predicating.
234     MachineOperand &getCount() {
235       return IsTailPredicationLegal() ?
236         VCTP->getOperand(1) : Start->getOperand(0);
237     }
238 
239     unsigned getStartOpcode() const {
240       bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
241       if (!IsTailPredicationLegal())
242         return IsDo ? ARM::t2DLS : ARM::t2WLS;
243 
244       return VCTPOpcodeToLSTP(VCTP->getOpcode(), IsDo);
245     }
246 
247     void dump() const {
248       if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start;
249       if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec;
250       if (End) dbgs() << "ARM Loops: Found Loop End: " << *End;
251       if (VCTP) dbgs() << "ARM Loops: Found VCTP: " << *VCTP;
252       if (!FoundAllComponents())
253         dbgs() << "ARM Loops: Not a low-overhead loop.\n";
254       else if (!(Start && Dec && End))
255         dbgs() << "ARM Loops: Failed to find all loop components.\n";
256     }
257   };
258 
259   class ARMLowOverheadLoops : public MachineFunctionPass {
260     MachineFunction           *MF = nullptr;
261     MachineLoopInfo           *MLI = nullptr;
262     ReachingDefAnalysis       *RDA = nullptr;
263     const ARMBaseInstrInfo    *TII = nullptr;
264     MachineRegisterInfo       *MRI = nullptr;
265     const TargetRegisterInfo  *TRI = nullptr;
266     std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
267 
268   public:
269     static char ID;
270 
271     ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
272 
273     void getAnalysisUsage(AnalysisUsage &AU) const override {
274       AU.setPreservesCFG();
275       AU.addRequired<MachineLoopInfo>();
276       AU.addRequired<ReachingDefAnalysis>();
277       MachineFunctionPass::getAnalysisUsage(AU);
278     }
279 
280     bool runOnMachineFunction(MachineFunction &MF) override;
281 
282     MachineFunctionProperties getRequiredProperties() const override {
283       return MachineFunctionProperties().set(
284           MachineFunctionProperties::Property::NoVRegs).set(
285           MachineFunctionProperties::Property::TracksLiveness);
286     }
287 
288     StringRef getPassName() const override {
289       return ARM_LOW_OVERHEAD_LOOPS_NAME;
290     }
291 
292   private:
293     bool ProcessLoop(MachineLoop *ML);
294 
295     bool RevertNonLoops();
296 
297     void RevertWhile(MachineInstr *MI) const;
298 
299     bool RevertLoopDec(MachineInstr *MI) const;
300 
301     void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const;
302 
303     void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
304 
305     MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
306 
307     void Expand(LowOverheadLoop &LoLoop);
308 
309   };
310 }
311 
312 char ARMLowOverheadLoops::ID = 0;
313 
314 INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME,
315                 false, false)
316 
317 MachineInstr *LowOverheadLoop::isSafeToDefineLR() {
318   // We can define LR because LR already contains the same value.
319   if (Start->getOperand(0).getReg() == ARM::LR)
320     return Start;
321 
322   unsigned CountReg = Start->getOperand(0).getReg();
323   auto IsMoveLR = [&CountReg](MachineInstr *MI) {
324     return MI->getOpcode() == ARM::tMOVr &&
325            MI->getOperand(0).getReg() == ARM::LR &&
326            MI->getOperand(1).getReg() == CountReg &&
327            MI->getOperand(2).getImm() == ARMCC::AL;
328    };
329 
330   MachineBasicBlock *MBB = Start->getParent();
331 
332   // Find an insertion point:
333   // - Is there a (mov lr, Count) before Start? If so, and nothing else writes
334   //   to Count before Start, we can insert at that mov.
335   if (auto *LRDef = RDA->getReachingMIDef(Start, ARM::LR))
336     if (IsMoveLR(LRDef) && RDA->hasSameReachingDef(Start, LRDef, CountReg))
337       return LRDef;
338 
339   // - Is there a (mov lr, Count) after Start? If so, and nothing else writes
340   //   to Count after Start, we can insert at that mov.
341   if (auto *LRDef = RDA->getLocalLiveOutMIDef(MBB, ARM::LR))
342     if (IsMoveLR(LRDef) && RDA->hasSameReachingDef(Start, LRDef, CountReg))
343       return LRDef;
344 
345   // We've found no suitable LR def and Start doesn't use LR directly. Can we
346   // just define LR anyway?
347   return RDA->isSafeToDefRegAt(Start, ARM::LR) ? Start : nullptr;
348 }
349 
350 bool LowOverheadLoop::ValidateTailPredicate(MachineInstr *StartInsertPt) {
351   assert(VCTP && "VCTP instruction expected but is not set");
352   // All predication within the loop should be based on vctp. If the block
353   // isn't predicated on entry, check whether the vctp is within the block
354   // and that all other instructions are then predicated on it.
355   for (auto &Block : VPTBlocks) {
356     if (Block.IsPredicatedOn(VCTP))
357       continue;
358     if (!Block.HasNonUniformPredicate() || !isVCTP(Block.getDivergent()->MI)) {
359       LLVM_DEBUG(dbgs() << "ARM Loops: Found unsupported diverging predicate: "
360                  << *Block.getDivergent()->MI);
361       return false;
362     }
363     SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts();
364     for (auto &PredMI : Insts) {
365       if (PredMI.Predicates.count(VCTP) || isVCTP(PredMI.MI))
366         continue;
367       LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *PredMI.MI
368                  << " - which is predicated on:\n";
369                  for (auto *MI : PredMI.Predicates)
370                    dbgs() << "   - " << *MI);
371       return false;
372     }
373   }
374 
375   // For tail predication, we need to provide the number of elements, instead
376   // of the iteration count, to the loop start instruction. The number of
377   // elements is provided to the vctp instruction, so we need to check that
378   // we can use this register at InsertPt.
379   Register NumElements = VCTP->getOperand(1).getReg();
380 
381   // If the register is defined within loop, then we can't perform TP.
382   // TODO: Check whether this is just a mov of a register that would be
383   // available.
384   if (RDA->hasLocalDefBefore(VCTP, NumElements)) {
385     LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
386     return false;
387   }
388 
389   // The element count register maybe defined after InsertPt, in which case we
390   // need to try to move either InsertPt or the def so that the [w|d]lstp can
391   // use the value.
392   MachineBasicBlock *InsertBB = StartInsertPt->getParent();
393   if (!RDA->isReachingDefLiveOut(StartInsertPt, NumElements)) {
394     if (auto *ElemDef = RDA->getLocalLiveOutMIDef(InsertBB, NumElements)) {
395       if (RDA->isSafeToMoveForwards(ElemDef, StartInsertPt)) {
396         ElemDef->removeFromParent();
397         InsertBB->insert(MachineBasicBlock::iterator(StartInsertPt), ElemDef);
398         LLVM_DEBUG(dbgs() << "ARM Loops: Moved element count def: "
399                    << *ElemDef);
400       } else if (RDA->isSafeToMoveBackwards(StartInsertPt, ElemDef)) {
401         StartInsertPt->removeFromParent();
402         InsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef),
403                               StartInsertPt);
404         LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef);
405       } else {
406         LLVM_DEBUG(dbgs() << "ARM Loops: Unable to move element count to loop "
407                    << "start instruction.\n");
408         return false;
409       }
410     }
411   }
412 
413   // Especially in the case of while loops, InsertBB may not be the
414   // preheader, so we need to check that the register isn't redefined
415   // before entering the loop.
416   auto CannotProvideElements = [this](MachineBasicBlock *MBB,
417                                       Register NumElements) {
418     // NumElements is redefined in this block.
419     if (RDA->hasLocalDefBefore(&MBB->back(), NumElements))
420       return true;
421 
422     // Don't continue searching up through multiple predecessors.
423     if (MBB->pred_size() > 1)
424       return true;
425 
426     return false;
427   };
428 
429   // First, find the block that looks like the preheader.
430   MachineBasicBlock *MBB = MLI->findLoopPreheader(ML, true);
431   if (!MBB) {
432     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find preheader.\n");
433     return false;
434   }
435 
436   // Then search backwards for a def, until we get to InsertBB.
437   while (MBB != InsertBB) {
438     if (CannotProvideElements(MBB, NumElements)) {
439       LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
440       return false;
441     }
442     MBB = *MBB->pred_begin();
443   }
444 
445   // Check that the value change of the element count is what we expect and
446   // that the predication will be equivalent. For this we need:
447   // NumElements = NumElements - VectorWidth. The sub will be a sub immediate
448   // and we can also allow register copies within the chain too.
449   auto IsValidSub = [](MachineInstr *MI, unsigned ExpectedVecWidth) {
450     unsigned ImmOpIdx = 0;
451     switch (MI->getOpcode()) {
452     default:
453       llvm_unreachable("unhandled sub opcode");
454     case ARM::tSUBi3:
455     case ARM::tSUBi8:
456       ImmOpIdx = 3;
457       break;
458     case ARM::t2SUBri:
459     case ARM::t2SUBri12:
460       ImmOpIdx = 2;
461       break;
462     }
463     return MI->getOperand(ImmOpIdx).getImm() == ExpectedVecWidth;
464   };
465 
466   MBB = VCTP->getParent();
467   if (MachineInstr *Def = RDA->getReachingMIDef(&MBB->back(), NumElements)) {
468     SmallPtrSet<MachineInstr*, 2> ElementChain;
469     SmallPtrSet<MachineInstr*, 2> Ignore = { VCTP };
470     unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode());
471 
472     if (RDA->isSafeToRemove(Def, ElementChain, Ignore)) {
473       bool FoundSub = false;
474 
475       for (auto *MI : ElementChain) {
476         if (isMovRegOpcode(MI->getOpcode()))
477           continue;
478 
479         if (isSubImmOpcode(MI->getOpcode())) {
480           if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth))
481             return false;
482           FoundSub = true;
483         } else
484           return false;
485       }
486 
487       LLVM_DEBUG(dbgs() << "ARM Loops: Will remove element count chain:\n";
488                  for (auto *MI : ElementChain)
489                    dbgs() << " - " << *MI);
490       ToRemove.insert(ElementChain.begin(), ElementChain.end());
491     }
492   }
493   return true;
494 }
495 
496 void LowOverheadLoop::CheckLegality(ARMBasicBlockUtils *BBUtils) {
497   if (Revert)
498     return;
499 
500   if (!End->getOperand(1).isMBB())
501     report_fatal_error("Expected LoopEnd to target basic block");
502 
503   // TODO Maybe there's cases where the target doesn't have to be the header,
504   // but for now be safe and revert.
505   if (End->getOperand(1).getMBB() != ML->getHeader()) {
506     LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targetting header.\n");
507     Revert = true;
508     return;
509   }
510 
511   // The WLS and LE instructions have 12-bits for the label offset. WLS
512   // requires a positive offset, while LE uses negative.
513   if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML->getHeader()) ||
514       !BBUtils->isBBInRange(End, ML->getHeader(), 4094)) {
515     LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n");
516     Revert = true;
517     return;
518   }
519 
520   if (Start->getOpcode() == ARM::t2WhileLoopStart &&
521       (BBUtils->getOffsetOf(Start) >
522        BBUtils->getOffsetOf(Start->getOperand(1).getMBB()) ||
523        !BBUtils->isBBInRange(Start, Start->getOperand(1).getMBB(), 4094))) {
524     LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n");
525     Revert = true;
526     return;
527   }
528 
529   InsertPt = Revert ? nullptr : isSafeToDefineLR();
530   if (!InsertPt) {
531     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to find safe insertion point.\n");
532     Revert = true;
533     return;
534   } else
535     LLVM_DEBUG(dbgs() << "ARM Loops: Start insertion point: " << *InsertPt);
536 
537   if (!IsTailPredicationLegal()) {
538     LLVM_DEBUG(if (!VCTP)
539                  dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
540                dbgs() << "ARM Loops: Tail-predication is not valid.\n");
541     return;
542   }
543 
544   assert(ML->getBlocks().size() == 1 &&
545          "Shouldn't be processing a loop with more than one block");
546   CannotTailPredicate = !ValidateTailPredicate(InsertPt);
547   LLVM_DEBUG(if (CannotTailPredicate)
548              dbgs() << "ARM Loops: Couldn't validate tail predicate.\n");
549 }
550 
551 bool LowOverheadLoop::ValidateMVEInst(MachineInstr* MI) {
552   if (CannotTailPredicate)
553     return false;
554 
555   // Only support a single vctp.
556   if (isVCTP(MI) && VCTP)
557     return false;
558 
559   // Start a new vpt block when we discover a vpt.
560   if (MI->getOpcode() == ARM::MVE_VPST) {
561     VPTBlocks.emplace_back(MI, CurrentPredicate);
562     CurrentBlock = &VPTBlocks.back();
563     return true;
564   } else if (isVCTP(MI))
565     VCTP = MI;
566   else if (MI->getOpcode() == ARM::MVE_VPSEL ||
567            MI->getOpcode() == ARM::MVE_VPNOT)
568     return false;
569 
570   // TODO: Allow VPSEL and VPNOT, we currently cannot because:
571   // 1) It will use the VPR as a predicate operand, but doesn't have to be
572   //    instead a VPT block, which means we can assert while building up
573   //    the VPT block because we don't find another VPST to being a new
574   //    one.
575   // 2) VPSEL still requires a VPR operand even after tail predicating,
576   //    which means we can't remove it unless there is another
577   //    instruction, such as vcmp, that can provide the VPR def.
578 
579   bool IsUse = false;
580   bool IsDef = false;
581   const MCInstrDesc &MCID = MI->getDesc();
582   for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
583     const MachineOperand &MO = MI->getOperand(i);
584     if (!MO.isReg() || MO.getReg() != ARM::VPR)
585       continue;
586 
587     if (MO.isDef()) {
588       CurrentPredicate.insert(MI);
589       IsDef = true;
590     } else if (ARM::isVpred(MCID.OpInfo[i].OperandType)) {
591       CurrentBlock->addInst(MI, CurrentPredicate);
592       IsUse = true;
593     } else {
594       LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI);
595       return false;
596     }
597   }
598 
599   // If we find a vpr def that is not already predicated on the vctp, we've
600   // got disjoint predicates that may not be equivalent when we do the
601   // conversion.
602   if (IsDef && !IsUse && VCTP && !isVCTP(MI)) {
603     LLVM_DEBUG(dbgs() << "ARM Loops: Found disjoint vpr def: " << *MI);
604     return false;
605   }
606 
607   uint64_t Flags = MCID.TSFlags;
608   if ((Flags & ARMII::DomainMask) != ARMII::DomainMVE)
609     return true;
610 
611   // If we find an instruction that has been marked as not valid for tail
612   // predication, only allow the instruction if it's contained within a valid
613   // VPT block.
614   if ((Flags & ARMII::ValidForTailPredication) == 0 && !IsUse) {
615     LLVM_DEBUG(dbgs() << "ARM Loops: Can't tail predicate: " << *MI);
616     return false;
617   }
618 
619   return true;
620 }
621 
622 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) {
623   const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget());
624   if (!ST.hasLOB())
625     return false;
626 
627   MF = &mf;
628   LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n");
629 
630   MLI = &getAnalysis<MachineLoopInfo>();
631   RDA = &getAnalysis<ReachingDefAnalysis>();
632   MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
633   MRI = &MF->getRegInfo();
634   TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo());
635   TRI = ST.getRegisterInfo();
636   BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF));
637   BBUtils->computeAllBlockSizes();
638   BBUtils->adjustBBOffsetsAfter(&MF->front());
639 
640   bool Changed = false;
641   for (auto ML : *MLI) {
642     if (!ML->getParentLoop())
643       Changed |= ProcessLoop(ML);
644   }
645   Changed |= RevertNonLoops();
646   return Changed;
647 }
648 
649 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) {
650 
651   bool Changed = false;
652 
653   // Process inner loops first.
654   for (auto I = ML->begin(), E = ML->end(); I != E; ++I)
655     Changed |= ProcessLoop(*I);
656 
657   LLVM_DEBUG(dbgs() << "ARM Loops: Processing loop containing:\n";
658              if (auto *Preheader = ML->getLoopPreheader())
659                dbgs() << " - " << Preheader->getName() << "\n";
660              else if (auto *Preheader = MLI->findLoopPreheader(ML))
661                dbgs() << " - " << Preheader->getName() << "\n";
662              else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
663                dbgs() << " - " << Preheader->getName() << "\n";
664              for (auto *MBB : ML->getBlocks())
665                dbgs() << " - " << MBB->getName() << "\n";
666             );
667 
668   // Search the given block for a loop start instruction. If one isn't found,
669   // and there's only one predecessor block, search that one too.
670   std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
671     [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* {
672     for (auto &MI : *MBB) {
673       if (isLoopStart(MI))
674         return &MI;
675     }
676     if (MBB->pred_size() == 1)
677       return SearchForStart(*MBB->pred_begin());
678     return nullptr;
679   };
680 
681   LowOverheadLoop LoLoop(ML, MLI, RDA);
682   // Search the preheader for the start intrinsic.
683   // FIXME: I don't see why we shouldn't be supporting multiple predecessors
684   // with potentially multiple set.loop.iterations, so we need to enable this.
685   if (auto *Preheader = ML->getLoopPreheader())
686     LoLoop.Start = SearchForStart(Preheader);
687   else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
688     LoLoop.Start = SearchForStart(Preheader);
689   else
690     return false;
691 
692   // Find the low-overhead loop components and decide whether or not to fall
693   // back to a normal loop. Also look for a vctp instructions and decide
694   // whether we can convert that predicate using tail predication.
695   for (auto *MBB : reverse(ML->getBlocks())) {
696     for (auto &MI : *MBB) {
697       if (MI.getOpcode() == ARM::t2LoopDec)
698         LoLoop.Dec = &MI;
699       else if (MI.getOpcode() == ARM::t2LoopEnd)
700         LoLoop.End = &MI;
701       else if (isLoopStart(MI))
702         LoLoop.Start = &MI;
703       else if (MI.getDesc().isCall()) {
704         // TODO: Though the call will require LE to execute again, does this
705         // mean we should revert? Always executing LE hopefully should be
706         // faster than performing a sub,cmp,br or even subs,br.
707         LoLoop.Revert = true;
708         LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
709       } else {
710         // Record VPR defs and build up their corresponding vpt blocks.
711         // Check we know how to tail predicate any mve instructions.
712         LoLoop.AnalyseMVEInst(&MI);
713       }
714     }
715   }
716 
717   LLVM_DEBUG(LoLoop.dump());
718   if (!LoLoop.FoundAllComponents()) {
719     LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
720     return false;
721   }
722 
723   SmallPtrSet<MachineInstr*, 2> Ignore = { LoLoop.End };
724   SmallPtrSet<MachineInstr*, 4> Remove;
725   if (!RDA->isSafeToRemove(LoLoop.Dec, Remove, Ignore)) {
726     LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove loop count chain.\n");
727     LoLoop.Revert = true;
728   } else {
729     LLVM_DEBUG(dbgs() << "ARM Loops: Will need to remove:\n";
730                for (auto *I : Remove)
731                  dbgs() << " - " << *I);
732     LoLoop.ToRemove.insert(Remove.begin(), Remove.end());
733   }
734 
735   LoLoop.CheckLegality(BBUtils.get());
736   Expand(LoLoop);
737   return true;
738 }
739 
740 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
741 // beq that branches to the exit branch.
742 // TODO: We could also try to generate a cbz if the value in LR is also in
743 // another low register.
744 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const {
745   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI);
746   MachineBasicBlock *MBB = MI->getParent();
747   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
748                                     TII->get(ARM::t2CMPri));
749   MIB.add(MI->getOperand(0));
750   MIB.addImm(0);
751   MIB.addImm(ARMCC::AL);
752   MIB.addReg(ARM::NoRegister);
753 
754   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
755   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
756     ARM::tBcc : ARM::t2Bcc;
757 
758   MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
759   MIB.add(MI->getOperand(1));   // branch target
760   MIB.addImm(ARMCC::EQ);        // condition code
761   MIB.addReg(ARM::CPSR);
762   MI->eraseFromParent();
763 }
764 
765 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const {
766   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI);
767   MachineBasicBlock *MBB = MI->getParent();
768   MachineInstr *Last = &MBB->back();
769   SmallPtrSet<MachineInstr*, 1> Ignore;
770   if (Last->getOpcode() == ARM::t2LoopEnd)
771     Ignore.insert(Last);
772 
773   // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
774   bool SetFlags = RDA->isSafeToDefRegAt(MI, ARM::CPSR, Ignore);
775 
776   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
777                                     TII->get(ARM::t2SUBri));
778   MIB.addDef(ARM::LR);
779   MIB.add(MI->getOperand(1));
780   MIB.add(MI->getOperand(2));
781   MIB.addImm(ARMCC::AL);
782   MIB.addReg(0);
783 
784   if (SetFlags) {
785     MIB.addReg(ARM::CPSR);
786     MIB->getOperand(5).setIsDef(true);
787   } else
788     MIB.addReg(0);
789 
790   MI->eraseFromParent();
791   return SetFlags;
792 }
793 
794 // Generate a subs, or sub and cmp, and a branch instead of an LE.
795 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const {
796   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI);
797 
798   MachineBasicBlock *MBB = MI->getParent();
799   // Create cmp
800   if (!SkipCmp) {
801     MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
802                                       TII->get(ARM::t2CMPri));
803     MIB.addReg(ARM::LR);
804     MIB.addImm(0);
805     MIB.addImm(ARMCC::AL);
806     MIB.addReg(ARM::NoRegister);
807   }
808 
809   MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
810   unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
811     ARM::tBcc : ARM::t2Bcc;
812 
813   // Create bne
814   MachineInstrBuilder MIB =
815     BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
816   MIB.add(MI->getOperand(1));   // branch target
817   MIB.addImm(ARMCC::NE);        // condition code
818   MIB.addReg(ARM::CPSR);
819   MI->eraseFromParent();
820 }
821 
822 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
823   LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n");
824   // When using tail-predication, try to delete the dead code that was used to
825   // calculate the number of loop iterations.
826   if (LoLoop.IsTailPredicationLegal()) {
827     SmallVector<MachineInstr*, 4> Killed;
828     SmallVector<MachineInstr*, 4> Dead;
829     if (auto *Def = RDA->getReachingMIDef(LoLoop.Start,
830                                       LoLoop.Start->getOperand(0).getReg())) {
831       SmallPtrSet<MachineInstr*, 4> Remove;
832       SmallPtrSet<MachineInstr*, 4> Ignore = { LoLoop.Start, LoLoop.Dec,
833                                                LoLoop.End, LoLoop.InsertPt };
834       SmallVector<MachineInstr*, 4> Chain = { Def };
835       while (!Chain.empty()) {
836         MachineInstr *MI = Chain.back();
837         Chain.pop_back();
838         if (RDA->isSafeToRemove(MI, Remove, Ignore)) {
839           for (auto &MO : MI->operands()) {
840             if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
841               continue;
842             if (auto *Op = RDA->getReachingMIDef(MI, MO.getReg()))
843               Chain.push_back(Op);
844           }
845           Ignore.insert(MI);
846         }
847       }
848       LoLoop.ToRemove.insert(Remove.begin(), Remove.end());
849     }
850   }
851 
852   MachineInstr *InsertPt = LoLoop.InsertPt;
853   MachineInstr *Start = LoLoop.Start;
854   MachineBasicBlock *MBB = InsertPt->getParent();
855   bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
856   unsigned Opc = LoLoop.getStartOpcode();
857   MachineOperand &Count = LoLoop.getCount();
858 
859   MachineInstrBuilder MIB =
860     BuildMI(*MBB, InsertPt, InsertPt->getDebugLoc(), TII->get(Opc));
861 
862   MIB.addDef(ARM::LR);
863   MIB.add(Count);
864   if (!IsDo)
865     MIB.add(Start->getOperand(1));
866 
867   // If we're inserting at a mov lr, then remove it as it's redundant.
868   if (InsertPt != Start)
869     LoLoop.ToRemove.insert(InsertPt);
870   LoLoop.ToRemove.insert(Start);
871   LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB);
872   return &*MIB;
873 }
874 
875 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
876   auto RemovePredicate = [](MachineInstr *MI) {
877     LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI);
878     if (int PIdx = llvm::findFirstVPTPredOperandIdx(*MI)) {
879       assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then &&
880              "Expected Then predicate!");
881       MI->getOperand(PIdx).setImm(ARMVCC::None);
882       MI->getOperand(PIdx+1).setReg(0);
883     } else
884       llvm_unreachable("trying to unpredicate a non-predicated instruction");
885   };
886 
887   // There are a few scenarios which we have to fix up:
888   // 1) A VPT block with is only predicated by the vctp and has no internal vpr
889   //    defs.
890   // 2) A VPT block which is only predicated by the vctp but has an internal
891   //    vpr def.
892   // 3) A VPT block which is predicated upon the vctp as well as another vpr
893   //    def.
894   // 4) A VPT block which is not predicated upon a vctp, but contains it and
895   //    all instructions within the block are predicated upon in.
896 
897   for (auto &Block : LoLoop.getVPTBlocks()) {
898     SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts();
899     if (Block.HasNonUniformPredicate()) {
900       PredicatedMI *Divergent = Block.getDivergent();
901       if (isVCTP(Divergent->MI)) {
902         // The vctp will be removed, so the size of the vpt block needs to be
903         // modified.
904         uint64_t Size = getARMVPTBlockMask(Block.size() - 1);
905         Block.getVPST()->getOperand(0).setImm(Size);
906         LLVM_DEBUG(dbgs() << "ARM Loops: Modified VPT block mask.\n");
907       } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) {
908         // The VPT block has a non-uniform predicate but it's entry is guarded
909         // only by a vctp, which means we:
910         // - Need to remove the original vpst.
911         // - Then need to unpredicate any following instructions, until
912         //   we come across the divergent vpr def.
913         // - Insert a new vpst to predicate the instruction(s) that following
914         //   the divergent vpr def.
915         // TODO: We could be producing more VPT blocks than necessary and could
916         // fold the newly created one into a proceeding one.
917         for (auto I = ++MachineBasicBlock::iterator(Block.getVPST()),
918              E = ++MachineBasicBlock::iterator(Divergent->MI); I != E; ++I)
919           RemovePredicate(&*I);
920 
921         unsigned Size = 0;
922         auto E = MachineBasicBlock::reverse_iterator(Divergent->MI);
923         auto I = MachineBasicBlock::reverse_iterator(Insts.back().MI);
924         MachineInstr *InsertAt = nullptr;
925         while (I != E) {
926           InsertAt = &*I;
927           ++Size;
928           ++I;
929         }
930         MachineInstrBuilder MIB = BuildMI(*InsertAt->getParent(), InsertAt,
931                                           InsertAt->getDebugLoc(),
932                                           TII->get(ARM::MVE_VPST));
933         MIB.addImm(getARMVPTBlockMask(Size));
934         LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST());
935         LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB);
936         LoLoop.ToRemove.insert(Block.getVPST());
937       }
938     } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) {
939       // A vpt block which is only predicated upon vctp and has no internal vpr
940       // defs:
941       // - Remove vpst.
942       // - Unpredicate the remaining instructions.
943       LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST());
944       LoLoop.ToRemove.insert(Block.getVPST());
945       for (auto &PredMI : Insts)
946         RemovePredicate(PredMI.MI);
947     }
948   }
949   LLVM_DEBUG(dbgs() << "ARM Loops: Removing VCTP: " << *LoLoop.VCTP);
950   LoLoop.ToRemove.insert(LoLoop.VCTP);
951 }
952 
953 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
954 
955   // Combine the LoopDec and LoopEnd instructions into LE(TP).
956   auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) {
957     MachineInstr *End = LoLoop.End;
958     MachineBasicBlock *MBB = End->getParent();
959     unsigned Opc = LoLoop.IsTailPredicationLegal() ?
960       ARM::MVE_LETP : ARM::t2LEUpdate;
961     MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(),
962                                       TII->get(Opc));
963     MIB.addDef(ARM::LR);
964     MIB.add(End->getOperand(0));
965     MIB.add(End->getOperand(1));
966     LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB);
967     End->eraseFromParent();
968     return &*MIB;
969   };
970 
971   // TODO: We should be able to automatically remove these branches before we
972   // get here - probably by teaching analyzeBranch about the pseudo
973   // instructions.
974   // If there is an unconditional branch, after I, that just branches to the
975   // next block, remove it.
976   auto RemoveDeadBranch = [](MachineInstr *I) {
977     MachineBasicBlock *BB = I->getParent();
978     MachineInstr *Terminator = &BB->instr_back();
979     if (Terminator->isUnconditionalBranch() && I != Terminator) {
980       MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB();
981       if (BB->isLayoutSuccessor(Succ)) {
982         LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator);
983         Terminator->eraseFromParent();
984       }
985     }
986   };
987 
988   if (LoLoop.Revert) {
989     if (LoLoop.Start->getOpcode() == ARM::t2WhileLoopStart)
990       RevertWhile(LoLoop.Start);
991     else
992       LoLoop.Start->eraseFromParent();
993     bool FlagsAlreadySet = RevertLoopDec(LoLoop.Dec);
994     RevertLoopEnd(LoLoop.End, FlagsAlreadySet);
995   } else {
996     LoLoop.Start = ExpandLoopStart(LoLoop);
997     RemoveDeadBranch(LoLoop.Start);
998     LoLoop.End = ExpandLoopEnd(LoLoop);
999     RemoveDeadBranch(LoLoop.End);
1000     if (LoLoop.IsTailPredicationLegal())
1001       ConvertVPTBlocks(LoLoop);
1002     for (auto *I : LoLoop.ToRemove) {
1003       LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I);
1004       I->eraseFromParent();
1005     }
1006   }
1007 
1008   PostOrderLoopTraversal DFS(*LoLoop.ML, *MLI);
1009   DFS.ProcessLoop();
1010   const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
1011   for (auto *MBB : PostOrder) {
1012     recomputeLiveIns(*MBB);
1013     // FIXME: For some reason, the live-in print order is non-deterministic for
1014     // our tests and I can't out why... So just sort them.
1015     MBB->sortUniqueLiveIns();
1016   }
1017 
1018   for (auto *MBB : reverse(PostOrder))
1019     recomputeLivenessFlags(*MBB);
1020 }
1021 
1022 bool ARMLowOverheadLoops::RevertNonLoops() {
1023   LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
1024   bool Changed = false;
1025 
1026   for (auto &MBB : *MF) {
1027     SmallVector<MachineInstr*, 4> Starts;
1028     SmallVector<MachineInstr*, 4> Decs;
1029     SmallVector<MachineInstr*, 4> Ends;
1030 
1031     for (auto &I : MBB) {
1032       if (isLoopStart(I))
1033         Starts.push_back(&I);
1034       else if (I.getOpcode() == ARM::t2LoopDec)
1035         Decs.push_back(&I);
1036       else if (I.getOpcode() == ARM::t2LoopEnd)
1037         Ends.push_back(&I);
1038     }
1039 
1040     if (Starts.empty() && Decs.empty() && Ends.empty())
1041       continue;
1042 
1043     Changed = true;
1044 
1045     for (auto *Start : Starts) {
1046       if (Start->getOpcode() == ARM::t2WhileLoopStart)
1047         RevertWhile(Start);
1048       else
1049         Start->eraseFromParent();
1050     }
1051     for (auto *Dec : Decs)
1052       RevertLoopDec(Dec);
1053 
1054     for (auto *End : Ends)
1055       RevertLoopEnd(End);
1056   }
1057   return Changed;
1058 }
1059 
1060 FunctionPass *llvm::createARMLowOverheadLoopsPass() {
1061   return new ARMLowOverheadLoops();
1062 }
1063