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