LLVM 24.0.0git
ARMLowOverheadLoops.cpp
Go to the documentation of this file.
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, t2WhileLoopStartLR 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 "ARMBasicBlockInfo.h"
57#include "ARMSubtarget.h"
58#include "MVETailPredUtils.h"
59#include "Thumb2InstrInfo.h"
60#include "llvm/ADT/SetVector.h"
66#include "llvm/CodeGen/Passes.h"
68#include "llvm/MC/MCInstrDesc.h"
69
70using namespace llvm;
71
72#define DEBUG_TYPE "arm-low-overhead-loops"
73#define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
74
75static cl::opt<bool>
76DisableTailPredication("arm-loloops-disable-tailpred", cl::Hidden,
77 cl::desc("Disable tail-predication in the ARM LowOverheadLoop pass"),
78 cl::init(false));
79
80static cl::opt<bool>
81 DisableOmitDLS("arm-disable-omit-dls", cl::Hidden,
82 cl::desc("Disable omitting 'dls lr, lr' instructions"),
83 cl::init(false));
84
87 return PIdx != -1 && MI->getOperand(PIdx + 1).getReg() == ARM::VPR;
88}
89
91 return MI->findRegisterDefOperandIdx(ARM::VPR, /*TRI=*/nullptr) != -1;
92}
93
94static bool hasVPRUse(MachineInstr &MI) {
95 return MI.findRegisterUseOperandIdx(ARM::VPR, /*TRI=*/nullptr) != -1;
96}
97
99 uint64_t Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
100 return Domain == ARMII::DomainMVE;
101}
102
103static int getVecSize(const MachineInstr &MI) {
104 const MCInstrDesc &MCID = MI.getDesc();
105 uint64_t Flags = MCID.TSFlags;
106 return (Flags & ARMII::VecSize) >> ARMII::VecSizeShift;
107}
108
110 if (MI.isDebugInstr())
111 return false;
112 return isDomainMVE(&MI) || isVectorPredicate(&MI) || hasVPRUse(MI);
113}
114
116 const MCInstrDesc &MCID = MI.getDesc();
117 uint64_t Flags = MCID.TSFlags;
118 return (Flags & ARMII::HorizontalReduction) != 0;
119}
120
121namespace {
122
123 using InstSet = SmallPtrSetImpl<MachineInstr *>;
124
125 class PostOrderLoopTraversal {
126 MachineLoop &ML;
127 MachineLoopInfo &MLI;
128 SmallPtrSet<MachineBasicBlock*, 4> Visited;
129 SmallVector<MachineBasicBlock*, 4> Order;
130
131 public:
132 PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI)
133 : ML(ML), MLI(MLI) { }
134
135 const SmallVectorImpl<MachineBasicBlock*> &getOrder() const {
136 return Order;
137 }
138
139 // Visit all the blocks within the loop, as well as exit blocks and any
140 // blocks properly dominating the header.
141 void ProcessLoop() {
142 std::function<void(MachineBasicBlock *)> Search =
143 [this, &Search](MachineBasicBlock *MBB) -> void {
144 if (!Visited.insert(MBB).second)
145 return;
146
147 for (auto *Succ : MBB->successors()) {
148 if (!ML.contains(Succ))
149 continue;
150 Search(Succ);
151 }
152 Order.push_back(MBB);
153 };
154
155 // Insert exit blocks.
157 ML.getExitBlocks(ExitBlocks);
158 append_range(Order, ExitBlocks);
159
160 // Then add the loop body.
161 Search(ML.getHeader());
162
163 // Then try the preheader and its predecessors.
164 std::function<void(MachineBasicBlock*)> GetPredecessor =
165 [this, &GetPredecessor] (MachineBasicBlock *MBB) -> void {
166 Order.push_back(MBB);
167 if (MBB->pred_size() == 1)
168 GetPredecessor(*MBB->pred_begin());
169 };
170
171 if (auto *Preheader = ML.getLoopPreheader())
172 GetPredecessor(Preheader);
173 else if (auto *Preheader = MLI.findLoopPreheader(&ML, true, true))
174 GetPredecessor(Preheader);
175 }
176 };
177
178 class VPTBlock {
179 SmallVector<MachineInstr *, 4> Insts;
180
181 public:
182 VPTBlock(MachineInstr *MI) { Insts.push_back(MI); }
183
184 // Have we found an instruction within the block which defines the vpr? If
185 // so, not all the instructions in the block will have the same predicate.
186 bool hasUniformPredicate() { return getDivergent() == nullptr; }
187
188 // If it exists, return the first internal instruction which modifies the
189 // VPR.
190 MachineInstr *getDivergent() {
191 SmallVectorImpl<MachineInstr *> &Insts = getInsts();
192 for (unsigned i = 1; i < Insts.size(); ++i) {
193 MachineInstr *Next = Insts[i];
195 return Next; // Found an instruction altering the vpr.
196 }
197 return nullptr;
198 }
199
200 void insert(MachineInstr *MI) {
201 Insts.push_back(MI);
202 // VPT/VPST + 4 predicated instructions.
203 assert(Insts.size() <= 5 && "Too many instructions in VPT block!");
204 }
205
206 bool containsVCTP() const { return llvm::any_of(Insts, isVCTP); }
207
208 unsigned size() const { return Insts.size(); }
209 SmallVectorImpl<MachineInstr *> &getInsts() { return Insts; }
210 };
211
212 // Represent the current state of the VPR and hold all instances which
213 // represent a VPT block, which is a list of instructions that begins with a
214 // VPT/VPST and has a maximum of four proceeding instructions. All
215 // instructions within the block are predicated upon the vpr and we allow
216 // instructions to define the vpr within in the block too.
217 class VPTState {
218 friend struct LowOverheadLoop;
219
221 SetVector<MachineInstr *> CurrentPredicates;
222 std::map<MachineInstr *, SetVector<MachineInstr *>> PredicatedInsts;
223
224 void CreateVPTBlock(MachineInstr *MI) {
225 assert((CurrentPredicates.size() || MI->getParent()->isLiveIn(ARM::VPR))
226 && "Can't begin VPT without predicate");
227 Blocks.emplace_back(MI);
228 // The execution of MI is predicated upon the current set of instructions
229 // that are AND'ed together to form the VPR predicate value. In the case
230 // that MI is a VPT, CurrentPredicates will also just be MI.
231 PredicatedInsts[MI] = CurrentPredicates;
232 }
233
234 void addInst(MachineInstr *MI) {
235 Blocks.back().insert(MI);
236 PredicatedInsts[MI] = CurrentPredicates;
237 }
238
239 void addPredicate(MachineInstr *MI) {
240 LLVM_DEBUG(dbgs() << "ARM Loops: Adding VPT Predicate: " << *MI);
241 CurrentPredicates.insert(MI);
242 }
243
244 void resetPredicate(MachineInstr *MI) {
245 LLVM_DEBUG(dbgs() << "ARM Loops: Resetting VPT Predicate: " << *MI);
246 CurrentPredicates.clear();
247 CurrentPredicates.insert(MI);
248 }
249
250 public:
251 // Return whether the given instruction is predicated upon a VCTP.
252 bool isPredicatedOnVCTP(MachineInstr *MI, bool Exclusive = false) {
253 SetVector<MachineInstr *> &Predicates = PredicatedInsts[MI];
254 if (Exclusive && Predicates.size() != 1)
255 return false;
256 // We do not know how to convert an else predicate of a VCTP.
258 return false;
259 return llvm::any_of(Predicates, isVCTP);
260 }
261
262 // Is the VPST, controlling the block entry, predicated upon a VCTP.
263 bool isEntryPredicatedOnVCTP(VPTBlock &Block, bool Exclusive = false) {
264 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
265 return isPredicatedOnVCTP(Insts.front(), Exclusive);
266 }
267
268 // If this block begins with a VPT, we can check whether it's using
269 // at least one predicated input(s), as well as possible loop invariant
270 // which would result in it being implicitly predicated.
271 bool hasImplicitlyValidVPT(VPTBlock &Block, ReachingDefInfo &RDI) {
272 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
273 MachineInstr *VPT = Insts.front();
274 assert(isVPTOpcode(VPT->getOpcode()) &&
275 "Expected VPT block to begin with VPT/VPST");
276
277 if (VPT->getOpcode() == ARM::MVE_VPST)
278 return false;
279
280 // If the VPT block does not define something that is an "output", then
281 // the tail-predicated version will just perform a subset of the original
282 // vpt block, where the last lanes should not be used.
283 if (isVPTOpcode(VPT->getOpcode()) &&
284 all_of(Block.getInsts(), [](const MachineInstr *MI) {
285 return !MI->mayStore() && !MI->mayLoad() &&
286 !isHorizontalReduction(*MI) && !isVCTP(MI);
287 }))
288 return true;
289
290 auto IsOperandPredicated = [&](MachineInstr *MI, unsigned Idx) {
291 MachineInstr *Op = RDI.getMIOperand(MI, MI->getOperand(Idx));
292 return Op && PredicatedInsts.count(Op) && isPredicatedOnVCTP(Op);
293 };
294
295 auto IsOperandInvariant = [&](MachineInstr *MI, unsigned Idx) {
296 MachineOperand &MO = MI->getOperand(Idx);
297 if (!MO.isReg() || !MO.getReg())
298 return true;
299
300 SmallPtrSet<MachineInstr *, 2> Defs;
301 RDI.getGlobalReachingDefs(MI, MO.getReg(), Defs);
302 if (Defs.empty())
303 return true;
304
305 for (auto *Def : Defs)
306 if (Def->getParent() == VPT->getParent())
307 return false;
308 return true;
309 };
310
311 // Check that at least one of the operands is directly predicated on a
312 // vctp and allow an invariant value too.
313 return (IsOperandPredicated(VPT, 1) || IsOperandPredicated(VPT, 2)) &&
314 (IsOperandPredicated(VPT, 1) || IsOperandInvariant(VPT, 1)) &&
315 (IsOperandPredicated(VPT, 2) || IsOperandInvariant(VPT, 2));
316 }
317
318 bool isValid(ReachingDefInfo &RDI) {
319 // All predication within the loop should be based on vctp. If the block
320 // isn't predicated on entry, check whether the vctp is within the block
321 // and that all other instructions are then predicated on it.
322 for (auto &Block : Blocks) {
323 if (isEntryPredicatedOnVCTP(Block, false) &&
324 !any_of(drop_begin(Block.getInsts()), [](const MachineInstr *MI) {
325 return getVPTInstrPredicate(*MI) == ARMVCC::Else;
326 }))
327 continue;
328 if (hasImplicitlyValidVPT(Block, RDI))
329 continue;
330
331 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
332 // We don't know how to convert a block with just a VPT;VCTP into
333 // anything valid once we remove the VCTP. For now just bail out.
334 assert(isVPTOpcode(Insts.front()->getOpcode()) &&
335 "Expected VPT block to start with a VPST or VPT!");
336 if (Insts.size() == 2 && Insts.front()->getOpcode() != ARM::MVE_VPST &&
337 isVCTP(Insts.back()))
338 return false;
339
340 for (auto *MI : Insts) {
341 // Check that any internal VCTPs are 'Then' predicated.
343 return false;
344 // Skip other instructions that build up the predicate.
345 if (MI->getOpcode() == ARM::MVE_VPST || isVectorPredicate(MI))
346 continue;
347 // Check that any other instructions are predicated upon a vctp.
348 // TODO: We could infer when VPTs are implicitly predicated on the
349 // vctp (when the operands are predicated).
350 if (!isPredicatedOnVCTP(MI)) {
351 LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *MI);
352 return false;
353 }
354 }
355 }
356 return true;
357 }
358 };
359
360 struct LowOverheadLoop {
361
362 MachineLoop &ML;
363 MachineBasicBlock *Preheader = nullptr;
364 MachineLoopInfo &MLI;
365 ReachingDefInfo &RDI;
366 const TargetRegisterInfo &TRI;
367 const ARMBaseInstrInfo &TII;
368 MachineFunction *MF = nullptr;
369 MachineBasicBlock::iterator StartInsertPt;
370 MachineBasicBlock *StartInsertBB = nullptr;
371 MachineInstr *Start = nullptr;
372 MachineInstr *Dec = nullptr;
373 MachineInstr *End = nullptr;
374 MachineOperand TPNumElements;
375 SmallVector<MachineInstr *, 4> VCTPs;
376 SmallPtrSet<MachineInstr *, 4> ToRemove;
377 SmallPtrSet<MachineInstr *, 4> BlockMasksToRecompute;
378 SmallPtrSet<MachineInstr *, 4> DoubleWidthResultInstrs;
379 SmallPtrSet<MachineInstr *, 4> VMOVCopies;
380 bool Revert = false;
381 bool CannotTailPredicate = false;
382 VPTState VPTstate;
383
384 LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI, ReachingDefInfo &RDI,
385 const TargetRegisterInfo &TRI, const ARMBaseInstrInfo &TII)
386 : ML(ML), MLI(MLI), RDI(RDI), TRI(TRI), TII(TII),
387 TPNumElements(MachineOperand::CreateImm(0)) {
388 MF = ML.getHeader()->getParent();
389 if (auto *MBB = ML.getLoopPreheader())
390 Preheader = MBB;
391 else if (auto *MBB = MLI.findLoopPreheader(&ML, true, true))
392 Preheader = MBB;
393 }
394
395 // If this is an MVE instruction, check that we know how to use tail
396 // predication with it. Record VPT blocks and return whether the
397 // instruction is valid for tail predication.
398 bool ValidateMVEInst(MachineInstr *MI);
399
400 void AnalyseMVEInst(MachineInstr *MI) {
401 CannotTailPredicate = !ValidateMVEInst(MI);
402 }
403
404 bool IsTailPredicationLegal() const {
405 // For now, let's keep things really simple and only support a single
406 // block for tail predication.
407 return !Revert && FoundAllComponents() && !VCTPs.empty() &&
408 !CannotTailPredicate && ML.getNumBlocks() == 1;
409 }
410
411 // Given that MI is a VCTP, check that is equivalent to any other VCTPs
412 // found.
413 bool AddVCTP(MachineInstr *MI);
414
415 // Check that the predication in the loop will be equivalent once we
416 // perform the conversion. Also ensure that we can provide the number
417 // of elements to the loop start instruction.
418 bool ValidateTailPredicate();
419
420 // Check that any values available outside of the loop will be the same
421 // after tail predication conversion.
422 bool ValidateLiveOuts();
423
424 // Check the branch targets are within range and we satisfy our
425 // restrictions.
426 void Validate(ARMBasicBlockUtils *BBUtils);
427
428 bool FoundAllComponents() const {
429 return Start && Dec && End;
430 }
431
432 SmallVectorImpl<VPTBlock> &getVPTBlocks() { return VPTstate.Blocks; }
433
434 // Return the operand for the loop start instruction. This will be the loop
435 // iteration count, or the number of elements if we're tail predicating.
436 MachineOperand &getLoopStartOperand() {
437 if (IsTailPredicationLegal())
438 return TPNumElements;
439 return Start->getOperand(1);
440 }
441
442 unsigned getStartOpcode() const {
443 bool IsDo = isDoLoopStart(*Start);
444 if (!IsTailPredicationLegal())
445 return IsDo ? ARM::t2DLS : ARM::t2WLS;
446
447 return VCTPOpcodeToLSTP(VCTPs.back()->getOpcode(), IsDo);
448 }
449
450 void dump() const {
451 if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start;
452 if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec;
453 if (End) dbgs() << "ARM Loops: Found Loop End: " << *End;
454 if (!VCTPs.empty()) {
455 dbgs() << "ARM Loops: Found VCTP(s):\n";
456 for (auto *MI : VCTPs)
457 dbgs() << " - " << *MI;
458 }
459 if (!FoundAllComponents())
460 dbgs() << "ARM Loops: Not a low-overhead loop.\n";
461 else if (!(Start && Dec && End))
462 dbgs() << "ARM Loops: Failed to find all loop components.\n";
463 }
464 };
465
466 class ARMLowOverheadLoops : public MachineFunctionPass {
467 MachineFunction *MF = nullptr;
468 MachineLoopInfo *MLI = nullptr;
469 ReachingDefInfo *RDI = nullptr;
470 const ARMBaseInstrInfo *TII = nullptr;
471 const TargetRegisterInfo *TRI = nullptr;
472 std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
473
474 public:
475 static char ID;
476
477 ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
478
479 void getAnalysisUsage(AnalysisUsage &AU) const override {
480 AU.setPreservesCFG();
481 AU.addRequired<MachineLoopInfoWrapperPass>();
482 AU.addRequired<ReachingDefInfoWrapperPass>();
484 }
485
486 bool runOnMachineFunction(MachineFunction &MF) override;
487
488 MachineFunctionProperties getRequiredProperties() const override {
489 return MachineFunctionProperties().setNoVRegs().setTracksLiveness();
490 }
491
492 StringRef getPassName() const override {
494 }
495
496 private:
497 bool ProcessLoop(MachineLoop *ML);
498
499 bool RevertNonLoops();
500
501 void RevertWhile(MachineInstr *MI) const;
502 void RevertDo(MachineInstr *MI) const;
503
504 bool RevertLoopDec(MachineInstr *MI) const;
505
506 void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const;
507
508 void RevertLoopEndDec(MachineInstr *MI) 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
520char ARMLowOverheadLoops::ID = 0;
521
523 false, false)
524
525static bool TryRemove(MachineInstr *MI, ReachingDefInfo &RDI, InstSet &ToRemove,
526 InstSet &Ignore) {
527
528 // Check that we can remove all of Killed without having to modify any IT
529 // blocks.
530 auto WontCorruptITs = [](InstSet &Killed, ReachingDefInfo &RDI) {
531 // Collect the dead code and the MBBs in which they reside.
533 for (auto *Dead : Killed)
534 BasicBlocks.insert(Dead->getParent());
535
536 // Collect IT blocks in all affected basic blocks.
537 std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks;
538 for (auto *MBB : BasicBlocks) {
539 for (auto &IT : *MBB) {
540 if (IT.getOpcode() != ARM::t2IT)
541 continue;
542 RDI.getReachingLocalUses(&IT, MCRegister::from(ARM::ITSTATE),
543 ITBlocks[&IT]);
544 }
545 }
546
547 // If we're removing all of the instructions within an IT block, then
548 // also remove the IT instruction.
551 for (auto *Dead : Killed) {
552 if (MachineOperand *MO =
553 Dead->findRegisterUseOperand(ARM::ITSTATE, /*TRI=*/nullptr)) {
554 MachineInstr *IT = RDI.getMIOperand(Dead, *MO);
555 RemoveITs.insert(IT);
556 auto &CurrentBlock = ITBlocks[IT];
557 CurrentBlock.erase(Dead);
558 if (CurrentBlock.empty())
559 ModifiedITs.erase(IT);
560 else
561 ModifiedITs.insert(IT);
562 }
563 }
564 if (!ModifiedITs.empty())
565 return false;
566 Killed.insert_range(RemoveITs);
567 return true;
568 };
569
571 if (!RDI.isSafeToRemove(MI, Uses, Ignore))
572 return false;
573
574 if (WontCorruptITs(Uses, RDI)) {
575 ToRemove.insert_range(Uses);
576 LLVM_DEBUG(dbgs() << "ARM Loops: Able to remove: " << *MI
577 << " - can also remove:\n";
578 for (auto *Use : Uses)
579 dbgs() << " - " << *Use);
580
582 RDI.collectKilledOperands(MI, Killed);
583 if (WontCorruptITs(Killed, RDI)) {
584 ToRemove.insert_range(Killed);
585 LLVM_DEBUG(for (auto *Dead : Killed)
586 dbgs() << " - " << *Dead);
587 }
588 return true;
589 }
590 return false;
591}
592
593bool LowOverheadLoop::ValidateTailPredicate() {
594 if (!IsTailPredicationLegal()) {
595 LLVM_DEBUG(if (VCTPs.empty())
596 dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
597 dbgs() << "ARM Loops: Tail-predication is not valid.\n");
598 return false;
599 }
600
601 assert(!VCTPs.empty() && "VCTP instruction expected but is not set");
602 assert(ML.getBlocks().size() == 1 &&
603 "Shouldn't be processing a loop with more than one block");
604
606 LLVM_DEBUG(dbgs() << "ARM Loops: tail-predication is disabled\n");
607 return false;
608 }
609
610 if (!VPTstate.isValid(RDI)) {
611 LLVM_DEBUG(dbgs() << "ARM Loops: Invalid VPT state.\n");
612 return false;
613 }
614
615 if (!ValidateLiveOuts()) {
616 LLVM_DEBUG(dbgs() << "ARM Loops: Invalid live outs.\n");
617 return false;
618 }
619
620 // For tail predication, we need to provide the number of elements, instead
621 // of the iteration count, to the loop start instruction. The number of
622 // elements is provided to the vctp instruction, so we need to check that
623 // we can use this register at InsertPt.
624 MachineInstr *VCTP = VCTPs.back();
625 if (Start->getOpcode() == ARM::t2DoLoopStartTP ||
626 Start->getOpcode() == ARM::t2WhileLoopStartTP) {
627 TPNumElements = Start->getOperand(2);
628 StartInsertPt = Start;
629 StartInsertBB = Start->getParent();
630 } else {
631 TPNumElements = VCTP->getOperand(1);
632 MCRegister NumElements = TPNumElements.getReg().asMCReg();
633
634 // If the register is defined within loop, then we can't perform TP.
635 // TODO: Check whether this is just a mov of a register that would be
636 // available.
637 if (RDI.hasLocalDefBefore(VCTP, NumElements)) {
638 LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
639 return false;
640 }
641
642 // The element count register maybe defined after InsertPt, in which case we
643 // need to try to move either InsertPt or the def so that the [w|d]lstp can
644 // use the value.
645
646 if (StartInsertPt != StartInsertBB->end() &&
647 !RDI.isReachingDefLiveOut(&*StartInsertPt, NumElements)) {
648 if (auto *ElemDef =
649 RDI.getLocalLiveOutMIDef(StartInsertBB, NumElements)) {
650 if (RDI.isSafeToMoveForwards(ElemDef, &*StartInsertPt)) {
651 ElemDef->removeFromParent();
652 StartInsertBB->insert(StartInsertPt, ElemDef);
654 << "ARM Loops: Moved element count def: " << *ElemDef);
655 } else if (RDI.isSafeToMoveBackwards(&*StartInsertPt, ElemDef)) {
656 StartInsertPt->removeFromParent();
657 StartInsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef),
658 &*StartInsertPt);
659 LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef);
660 } else {
661 // If we fail to move an instruction and the element count is provided
662 // by a mov, use the mov operand if it will have the same value at the
663 // insertion point
664 MachineOperand Operand = ElemDef->getOperand(1);
665 if (isMovRegOpcode(ElemDef->getOpcode()) &&
666 RDI.getUniqueReachingMIDef(ElemDef, Operand.getReg().asMCReg()) ==
667 RDI.getUniqueReachingMIDef(&*StartInsertPt,
668 Operand.getReg().asMCReg())) {
669 TPNumElements = Operand;
670 NumElements = TPNumElements.getReg();
671 } else {
673 << "ARM Loops: Unable to move element count to loop "
674 << "start instruction.\n");
675 return false;
676 }
677 }
678 }
679 }
680
681 // Especially in the case of while loops, InsertBB may not be the
682 // preheader, so we need to check that the register isn't redefined
683 // before entering the loop.
684 auto CannotProvideElements = [this](MachineBasicBlock *MBB,
685 MCRegister NumElements) {
686 auto Back = MBB->getLastNonDebugInstr();
687 if (Back == MBB->end())
688 return false;
689 // NumElements is redefined in this block.
690 if (RDI.hasLocalDefBefore(&*Back, NumElements))
691 return true;
692
693 // Don't continue searching up through multiple predecessors.
694 if (MBB->pred_size() > 1)
695 return true;
696
697 return false;
698 };
699
700 // Search backwards for a def, until we get to InsertBB.
701 MachineBasicBlock *MBB = Preheader;
702 while (MBB && MBB != StartInsertBB) {
703 if (CannotProvideElements(MBB, NumElements)) {
704 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
705 return false;
706 }
707 MBB = *MBB->pred_begin();
708 }
709 }
710
711 // Could inserting the [W|D]LSTP cause some unintended affects? In a perfect
712 // world the [w|d]lstp instruction would be last instruction in the preheader
713 // and so it would only affect instructions within the loop body. But due to
714 // scheduling, and/or the logic in this pass (above), the insertion point can
715 // be moved earlier. So if the Loop Start isn't the last instruction in the
716 // preheader, and if the initial element count is smaller than the vector
717 // width, the Loop Start instruction will immediately generate one or more
718 // false lane mask which can, incorrectly, affect the proceeding MVE
719 // instructions in the preheader.
720 if (std::any_of(StartInsertPt, StartInsertBB->end(), shouldInspect)) {
721 LLVM_DEBUG(dbgs() << "ARM Loops: Instruction blocks [W|D]LSTP\n");
722 return false;
723 }
724
725 // For any DoubleWidthResultInstrs we found whilst scanning instructions, they
726 // need to compute an output size that is smaller than the VCTP mask operates
727 // on. The VecSize of the DoubleWidthResult is the larger vector size - the
728 // size it extends into, so any VCTP VecSize <= is valid.
729 unsigned VCTPVecSize = getVecSize(*VCTP);
730 for (MachineInstr *MI : DoubleWidthResultInstrs) {
731 unsigned InstrVecSize = getVecSize(*MI);
732 if (InstrVecSize > VCTPVecSize) {
733 LLVM_DEBUG(dbgs() << "ARM Loops: Double width result larger than VCTP "
734 << "VecSize:\n" << *MI);
735 return false;
736 }
737 }
738
739 // Check that the value change of the element count is what we expect and
740 // that the predication will be equivalent. For this we need:
741 // NumElements = NumElements - VectorWidth. The sub will be a sub immediate
742 // and we can also allow register copies within the chain too.
743 auto IsValidSub = [](MachineInstr *MI, int ExpectedVecWidth) {
744 return -getAddSubImmediate(*MI) == ExpectedVecWidth;
745 };
746
747 MachineBasicBlock *MBB = VCTP->getParent();
748 // Remove modifications to the element count since they have no purpose in a
749 // tail predicated loop. Explicitly refer to the vctp operand no matter which
750 // register NumElements has been assigned to, since that is what the
751 // modifications will be using
752 if (auto *Def = RDI.getUniqueReachingMIDef(
753 &MBB->back(), VCTP->getOperand(1).getReg().asMCReg())) {
754 SmallPtrSet<MachineInstr*, 2> ElementChain;
755 SmallPtrSet<MachineInstr*, 2> Ignore;
756 unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode());
757
758 Ignore.insert_range(VCTPs);
759
760 if (TryRemove(Def, RDI, ElementChain, Ignore)) {
761 bool FoundSub = false;
762
763 for (auto *MI : ElementChain) {
764 if (isMovRegOpcode(MI->getOpcode()))
765 continue;
766
767 if (isSubImmOpcode(MI->getOpcode())) {
768 if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth)) {
769 LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
770 " count: " << *MI);
771 return false;
772 }
773 FoundSub = true;
774 } else {
775 LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
776 " count: " << *MI);
777 return false;
778 }
779 }
780 ToRemove.insert_range(ElementChain);
781 }
782 }
783
784 // If we converted the LoopStart to a t2DoLoopStartTP/t2WhileLoopStartTP, we
785 // can also remove any extra instructions in the preheader, which often
786 // includes a now unused MOV.
787 if ((Start->getOpcode() == ARM::t2DoLoopStartTP ||
788 Start->getOpcode() == ARM::t2WhileLoopStartTP) &&
789 Preheader && !Preheader->empty() &&
790 !RDI.hasLocalDefBefore(VCTP, VCTP->getOperand(1).getReg())) {
791 if (auto *Def = RDI.getUniqueReachingMIDef(
792 &Preheader->back(), VCTP->getOperand(1).getReg().asMCReg())) {
793 SmallPtrSet<MachineInstr *, 2> Ignore(llvm::from_range, VCTPs);
794 TryRemove(Def, RDI, ToRemove, Ignore);
795 }
796 }
797
798 return true;
799}
800
801static bool isRegInClass(const MachineOperand &MO,
802 const TargetRegisterClass *Class) {
803 return MO.isReg() && MO.getReg() && Class->contains(MO.getReg());
804}
805
806// MVE 'narrowing' operate on half a lane, reading from half and writing
807// to half, which are referred to has the top and bottom half. The other
808// half retains its previous value.
810 const MCInstrDesc &MCID = MI.getDesc();
811 uint64_t Flags = MCID.TSFlags;
812 return (Flags & ARMII::RetainsPreviousHalfElement) != 0;
813}
814
815// Some MVE instructions read from the top/bottom halves of their operand(s)
816// and generate a vector result with result elements that are double the
817// width of the input.
819 const MCInstrDesc &MCID = MI.getDesc();
820 uint64_t Flags = MCID.TSFlags;
821 return (Flags & ARMII::DoubleWidthResult) != 0;
822}
823
824// Can this instruction generate a non-zero result when given only zeroed
825// operands? This allows us to know that, given operands with false bytes
826// zeroed by masked loads, that the result will also contain zeros in those
827// bytes.
829
830 // Check for instructions which can write into a larger element size,
831 // possibly writing into a previous zero'd lane.
833 return true;
834
835 switch (MI.getOpcode()) {
836 default:
837 break;
838 // FIXME: VNEG FP and -0? I think we'll need to handle this once we allow
839 // fp16 -> fp32 vector conversions.
840 // Instructions that perform a NOT will generate 1s from 0s.
841 case ARM::MVE_VMVN:
842 case ARM::MVE_VORN:
843 // Count leading zeros will do just that!
844 case ARM::MVE_VCLZs8:
845 case ARM::MVE_VCLZs16:
846 case ARM::MVE_VCLZs32:
847 return true;
848 }
849 return false;
850}
851
852// Look at its register uses to see if it only can only receive zeros
853// into its false lanes which would then produce zeros. Also check that
854// the output register is also defined by an FalseLanesZero instruction
855// so that if tail-predication happens, the lanes that aren't updated will
856// still be zeros.
858 const TargetRegisterClass *QPRs,
859 const ReachingDefInfo &RDI,
860 InstSet &FalseLanesZero) {
862 return false;
863
864 bool isPredicated = isVectorPredicated(&MI);
865 // Predicated loads will write zeros to the falsely predicated bytes of the
866 // destination register.
867 if (MI.mayLoad())
868 return isPredicated;
869
870 auto IsZeroInit = [](MachineInstr *Def) {
871 return !isVectorPredicated(Def) &&
872 Def->getOpcode() == ARM::MVE_VMOVimmi32 &&
873 Def->getOperand(1).getImm() == 0;
874 };
875
876 bool AllowScalars = isHorizontalReduction(MI);
877 for (auto &MO : MI.operands()) {
878 if (!MO.isReg() || !MO.getReg())
879 continue;
880 if (!isRegInClass(MO, QPRs) && AllowScalars)
881 continue;
882 // Skip the lr predicate reg
884 if (PIdx != -1 && MO.getOperandNo() == PIdx + ARM::SUBOP_vpred_n_tp_reg)
885 continue;
886
887 // Check that this instruction will produce zeros in its false lanes:
888 // - If it only consumes false lanes zero or constant 0 (vmov #0)
889 // - If it's predicated, it only matters that it's def register already has
890 // false lane zeros, so we can ignore the uses.
892 RDI.getGlobalReachingDefs(&MI, MO.getReg(), Defs);
893 if (Defs.empty())
894 return false;
895 for (auto *Def : Defs) {
896 if (Def == &MI || FalseLanesZero.count(Def) || IsZeroInit(Def))
897 continue;
898 if (MO.isUse() && isPredicated)
899 continue;
900 return false;
901 }
902 }
903 LLVM_DEBUG(dbgs() << "ARM Loops: Always False Zeros: " << MI);
904 return true;
905}
906
907bool LowOverheadLoop::ValidateLiveOuts() {
908 // We want to find out if the tail-predicated version of this loop will
909 // produce the same values as the loop in its original form. For this to
910 // be true, the newly inserted implicit predication must not change the
911 // the (observable) results.
912 // We're doing this because many instructions in the loop will not be
913 // predicated and so the conversion from VPT predication to tail-predication
914 // can result in different values being produced; due to the tail-predication
915 // preventing many instructions from updating their falsely predicated
916 // lanes. This analysis assumes that all the instructions perform lane-wise
917 // operations and don't perform any exchanges.
918 // A masked load, whether through VPT or tail predication, will write zeros
919 // to any of the falsely predicated bytes. So, from the loads, we know that
920 // the false lanes are zeroed and here we're trying to track that those false
921 // lanes remain zero, or where they change, the differences are masked away
922 // by their user(s).
923 // All MVE stores have to be predicated, so we know that any predicate load
924 // operands, or stored results are equivalent already. Other explicitly
925 // predicated instructions will perform the same operation in the original
926 // loop and the tail-predicated form too. Because of this, we can insert
927 // loads, stores and other predicated instructions into our Predicated
928 // set and build from there.
929 const TargetRegisterClass *QPRs = TRI.getRegClass(ARM::MQPRRegClassID);
930 SetVector<MachineInstr *> FalseLanesUnknown;
931 SmallPtrSet<MachineInstr *, 4> FalseLanesZero;
932 SmallPtrSet<MachineInstr *, 4> Predicated;
933 MachineBasicBlock *Header = ML.getHeader();
934
935 LLVM_DEBUG(dbgs() << "ARM Loops: Validating Live outs\n");
936
937 for (auto &MI : *Header) {
938 if (!shouldInspect(MI))
939 continue;
940
941 if (isVCTP(&MI) || isVPTOpcode(MI.getOpcode()))
942 continue;
943
945 bool retainsOrReduces =
947
948 if (isPredicated)
949 Predicated.insert(&MI);
950 if (producesFalseLanesZero(MI, QPRs, RDI, FalseLanesZero))
951 FalseLanesZero.insert(&MI);
952 else if (MI.getNumDefs() == 0)
953 continue;
954 else if (!isPredicated && retainsOrReduces) {
955 LLVM_DEBUG(dbgs() << " Unpredicated instruction that retainsOrReduces: " << MI);
956 return false;
957 } else if (!isPredicated && MI.getOpcode() != ARM::MQPRCopy)
958 FalseLanesUnknown.insert(&MI);
959 }
960
961 LLVM_DEBUG({
962 dbgs() << " Predicated:\n";
963 for (auto *I : Predicated)
964 dbgs() << " " << *I;
965 dbgs() << " FalseLanesZero:\n";
966 for (auto *I : FalseLanesZero)
967 dbgs() << " " << *I;
968 dbgs() << " FalseLanesUnknown:\n";
969 for (auto *I : FalseLanesUnknown)
970 dbgs() << " " << *I;
971 });
972
973 auto HasPredicatedUsers = [this](MachineInstr *MI, const MachineOperand &MO,
974 SmallPtrSetImpl<MachineInstr *> &Predicated) {
975 SmallPtrSet<MachineInstr *, 2> Uses;
976 RDI.getGlobalUses(MI, MO.getReg().asMCReg(), Uses);
977 for (auto *Use : Uses) {
978 if (Use != MI && !Predicated.count(Use))
979 return false;
980 }
981 return true;
982 };
983
984 // Visit the unknowns in reverse so that we can start at the values being
985 // stored and then we can work towards the leaves, hopefully adding more
986 // instructions to Predicated. Successfully terminating the loop means that
987 // all the unknown values have to found to be masked by predicated user(s).
988 // For any unpredicated values, we store them in NonPredicated so that we
989 // can later check whether these form a reduction.
990 SmallPtrSet<MachineInstr*, 2> NonPredicated;
991 for (auto *MI : reverse(FalseLanesUnknown)) {
992 for (auto &MO : MI->operands()) {
993 if (!isRegInClass(MO, QPRs) || !MO.isDef())
994 continue;
995 if (!HasPredicatedUsers(MI, MO, Predicated)) {
996 LLVM_DEBUG(dbgs() << " Found an unknown def of : "
997 << TRI.getRegAsmName(MO.getReg()) << " at " << *MI);
998 NonPredicated.insert(MI);
999 break;
1000 }
1001 }
1002 // Any unknown false lanes have been masked away by the user(s).
1003 if (!NonPredicated.contains(MI))
1004 Predicated.insert(MI);
1005 }
1006
1007 SmallPtrSet<MachineInstr *, 2> LiveOutMIs;
1009 ML.getExitBlocks(ExitBlocks);
1010 assert(ML.getNumBlocks() == 1 && "Expected single block loop!");
1011 assert(ExitBlocks.size() == 1 && "Expected a single exit block");
1012 MachineBasicBlock *ExitBB = ExitBlocks.front();
1013 for (const MachineBasicBlock::RegisterMaskPair &RegMask : ExitBB->liveins()) {
1014 // TODO: Instead of blocking predication, we could move the vctp to the exit
1015 // block and calculate it's operand there in or the preheader.
1016 if (RegMask.PhysReg == ARM::VPR) {
1017 LLVM_DEBUG(dbgs() << " VPR is live in to the exit block.");
1018 return false;
1019 }
1020 // Check Q-regs that are live in the exit blocks. We don't collect scalars
1021 // because they won't be affected by lane predication.
1022 if (QPRs->contains(RegMask.PhysReg))
1023 if (auto *MI = RDI.getLocalLiveOutMIDef(Header, RegMask.PhysReg))
1024 LiveOutMIs.insert(MI);
1025 }
1026
1027 // We've already validated that any VPT predication within the loop will be
1028 // equivalent when we perform the predication transformation; so we know that
1029 // any VPT predicated instruction is predicated upon VCTP. Any live-out
1030 // instruction needs to be predicated, so check this here. The instructions
1031 // in NonPredicated have been found to be a reduction that we can ensure its
1032 // legality. Any MQPRCopy found will need to validate its input as if it was
1033 // live out.
1034 SmallVector<MachineInstr *> Worklist(LiveOutMIs.begin(), LiveOutMIs.end());
1035 while (!Worklist.empty()) {
1036 MachineInstr *MI = Worklist.pop_back_val();
1037 if (MI->getOpcode() == ARM::MQPRCopy) {
1038 LLVM_DEBUG(dbgs() << " Must generate copy as VMOV: " << *MI);
1039 VMOVCopies.insert(MI);
1040 MachineInstr *CopySrc =
1041 RDI.getUniqueReachingMIDef(MI, MI->getOperand(1).getReg());
1042 if (CopySrc)
1043 Worklist.push_back(CopySrc);
1044 } else if (NonPredicated.count(MI) && FalseLanesUnknown.contains(MI)) {
1045 LLVM_DEBUG(dbgs() << " Unable to handle live out: " << *MI);
1046 VMOVCopies.clear();
1047 return false;
1048 } else if (isVectorPredicated(MI)) {
1049 // If this is a predicated instruction with merging semantics,
1050 // check where it gets its false lanes from, if any.
1051 int InactiveIdx = findVPTInactiveOperandIdx(*MI);
1052 if (InactiveIdx != -1) {
1053 MachineInstr *FalseSrc = RDI.getUniqueReachingMIDef(
1054 MI, MI->getOperand(InactiveIdx).getReg());
1055 if (FalseSrc) {
1057 << " Must check source of false lanes for: " << *MI);
1058 Worklist.push_back(FalseSrc);
1059 }
1060 }
1061 }
1062 }
1063
1064 return true;
1065}
1066
1067void LowOverheadLoop::Validate(ARMBasicBlockUtils *BBUtils) {
1068 if (Revert)
1069 return;
1070
1071 // Check branch target ranges: WLS[TP] can only branch forwards and LE[TP]
1072 // can only jump back.
1073 auto ValidateRanges = [](MachineInstr *Start, MachineInstr *End,
1074 ARMBasicBlockUtils *BBUtils, MachineLoop &ML) {
1075 MachineBasicBlock *TgtBB = End->getOpcode() == ARM::t2LoopEnd
1076 ? End->getOperand(1).getMBB()
1077 : End->getOperand(2).getMBB();
1078 // TODO Maybe there's cases where the target doesn't have to be the header,
1079 // but for now be safe and revert.
1080 if (TgtBB != ML.getHeader()) {
1081 LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targeting header.\n");
1082 return false;
1083 }
1084
1085 // The WLS and LE instructions have 12-bits for the label offset. WLS
1086 // requires a positive offset, while LE uses negative.
1087 if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML.getHeader()) ||
1088 !BBUtils->isBBInRange(End, ML.getHeader(), 4094)) {
1089 LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n");
1090 return false;
1091 }
1092
1093 if (isWhileLoopStart(*Start)) {
1094 MachineBasicBlock *TargetBB = getWhileLoopStartTargetBB(*Start);
1095 if (BBUtils->getOffsetOf(Start) > BBUtils->getOffsetOf(TargetBB) ||
1096 !BBUtils->isBBInRange(Start, TargetBB, 4094)) {
1097 LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n");
1098 return false;
1099 }
1100 }
1101 return true;
1102 };
1103
1104 StartInsertPt = MachineBasicBlock::iterator(Start);
1105 StartInsertBB = Start->getParent();
1106 LLVM_DEBUG(dbgs() << "ARM Loops: Will insert LoopStart at "
1107 << *StartInsertPt);
1108
1109 Revert = !ValidateRanges(Start, End, BBUtils, ML);
1110 CannotTailPredicate = !ValidateTailPredicate();
1111}
1112
1113bool LowOverheadLoop::AddVCTP(MachineInstr *MI) {
1114 LLVM_DEBUG(dbgs() << "ARM Loops: Adding VCTP: " << *MI);
1115 if (VCTPs.empty()) {
1116 VCTPs.push_back(MI);
1117 return true;
1118 }
1119
1120 // If we find another VCTP, check whether it uses the same value as the main VCTP.
1121 // If it does, store it in the VCTPs set, else refuse it.
1122 MachineInstr *Prev = VCTPs.back();
1123 if (!Prev->getOperand(1).isIdenticalTo(MI->getOperand(1)) ||
1124 !RDI.hasSameReachingDef(Prev, MI, MI->getOperand(1).getReg().asMCReg())) {
1125 LLVM_DEBUG(dbgs() << "ARM Loops: Found VCTP with a different reaching "
1126 "definition from the main VCTP");
1127 return false;
1128 }
1129 VCTPs.push_back(MI);
1130 return true;
1131}
1132
1134
1135 auto GetFrameIndex = [](MachineMemOperand *Operand) {
1136 const PseudoSourceValue *PseudoValue = Operand->getPseudoValue();
1137 if (PseudoValue && PseudoValue->kind() == PseudoSourceValue::FixedStack) {
1138 if (const auto *FS = dyn_cast<FixedStackPseudoSourceValue>(PseudoValue)) {
1139 return FS->getFrameIndex();
1140 }
1141 }
1142 return -1;
1143 };
1144
1145 auto IsStackOp = [GetFrameIndex](MachineInstr *I) {
1146 switch (I->getOpcode()) {
1147 case ARM::MVE_VSTRWU32:
1148 case ARM::MVE_VLDRWU32: {
1149 return I->getOperand(1).getReg() == ARM::SP &&
1150 I->memoperands().size() == 1 &&
1151 GetFrameIndex(I->memoperands().front()) >= 0;
1152 }
1153 default:
1154 return false;
1155 }
1156 };
1157
1158 // An unpredicated vector register spill is allowed if all of the uses of the
1159 // stack slot are within the loop
1160 if (MI->getOpcode() != ARM::MVE_VSTRWU32 || !IsStackOp(MI))
1161 return false;
1162
1163 // Search all blocks after the loop for accesses to the same stack slot.
1164 // ReachingDefAnalysis doesn't work for sp as it relies on registers being
1165 // live-out (which sp never is) to know what blocks to look in
1166 if (MI->memoperands().size() == 0)
1167 return false;
1168 int FI = GetFrameIndex(MI->memoperands().front());
1169
1170 auto &FrameInfo = MI->getParent()->getParent()->getFrameInfo();
1171 if (FI == -1 || !FrameInfo.isSpillSlotObjectIndex(FI))
1172 return false;
1173
1175 ML->getExitBlocks(Frontier);
1176 SmallPtrSet<MachineBasicBlock *, 4> Visited{MI->getParent()};
1177 unsigned Idx = 0;
1178 while (Idx < Frontier.size()) {
1179 MachineBasicBlock *BB = Frontier[Idx];
1180 bool LookAtSuccessors = true;
1181 for (auto &I : *BB) {
1182 if (!IsStackOp(&I) || I.memoperands().size() == 0)
1183 continue;
1184 if (GetFrameIndex(I.memoperands().front()) != FI)
1185 continue;
1186 // If this block has a store to the stack slot before any loads then we
1187 // can ignore the block
1188 if (I.getOpcode() == ARM::MVE_VSTRWU32) {
1189 LookAtSuccessors = false;
1190 break;
1191 }
1192 // If the store and the load are using the same stack slot then the
1193 // store isn't valid for tail predication
1194 if (I.getOpcode() == ARM::MVE_VLDRWU32)
1195 return false;
1196 }
1197
1198 if (LookAtSuccessors) {
1199 for (auto *Succ : BB->successors()) {
1200 if (!Visited.contains(Succ) && !is_contained(Frontier, Succ))
1201 Frontier.push_back(Succ);
1202 }
1203 }
1204 Visited.insert(BB);
1205 Idx++;
1206 }
1207
1208 return true;
1209}
1210
1211bool LowOverheadLoop::ValidateMVEInst(MachineInstr *MI) {
1212 if (CannotTailPredicate)
1213 return false;
1214
1215 if (!shouldInspect(*MI))
1216 return true;
1217
1218 if (MI->getOpcode() == ARM::MVE_VPSEL ||
1219 MI->getOpcode() == ARM::MVE_VPNOT) {
1220 // TODO: Allow VPSEL and VPNOT, we currently cannot because:
1221 // 1) It will use the VPR as a predicate operand, but doesn't have to be
1222 // instead a VPT block, which means we can assert while building up
1223 // the VPT block because we don't find another VPT or VPST to being a new
1224 // one.
1225 // 2) VPSEL still requires a VPR operand even after tail predicating,
1226 // which means we can't remove it unless there is another
1227 // instruction, such as vcmp, that can provide the VPR def.
1228 return false;
1229 }
1230
1231 // Record all VCTPs and check that they're equivalent to one another.
1232 if (isVCTP(MI) && !AddVCTP(MI))
1233 return false;
1234
1235 // Inspect uses first so that any instructions that alter the VPR don't
1236 // alter the predicate upon themselves.
1237 const MCInstrDesc &MCID = MI->getDesc();
1238 bool IsUse = false;
1239 unsigned LastOpIdx = MI->getNumOperands() - 1;
1240 for (const auto &Op : enumerate(reverse(MCID.operands()))) {
1241 const MachineOperand &MO = MI->getOperand(LastOpIdx - Op.index());
1242 if (!MO.isReg() || !MO.isUse() || MO.getReg() != ARM::VPR)
1243 continue;
1244
1245 if (ARM::isVpred(Op.value().OperandType)) {
1246 VPTstate.addInst(MI);
1247 IsUse = true;
1248 } else if (MI->getOpcode() != ARM::MVE_VPST) {
1249 LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI);
1250 return false;
1251 }
1252 }
1253
1254 // If we find an instruction that has been marked as not valid for tail
1255 // predication, only allow the instruction if it's contained within a valid
1256 // VPT block.
1257 bool RequiresExplicitPredication =
1259 if (isDomainMVE(MI) && RequiresExplicitPredication) {
1260 if (MI->getOpcode() == ARM::MQPRCopy)
1261 return true;
1262 if (!IsUse && producesDoubleWidthResult(*MI)) {
1263 DoubleWidthResultInstrs.insert(MI);
1264 return true;
1265 }
1266
1267 LLVM_DEBUG(if (!IsUse) dbgs()
1268 << "ARM Loops: Can't tail predicate: " << *MI);
1269 return IsUse;
1270 }
1271
1272 // If the instruction is already explicitly predicated, then the conversion
1273 // will be fine, but ensure that all store operations are predicated.
1274 if (MI->mayStore() && !ValidateMVEStore(MI, &ML))
1275 return IsUse;
1276
1277 // If this instruction defines the VPR, update the predicate for the
1278 // proceeding instructions.
1279 if (isVectorPredicate(MI)) {
1280 // Clear the existing predicate when we're not in VPT Active state,
1281 // otherwise we add to it.
1282 if (!isVectorPredicated(MI))
1283 VPTstate.resetPredicate(MI);
1284 else
1285 VPTstate.addPredicate(MI);
1286 }
1287
1288 // Finally once the predicate has been modified, we can start a new VPT
1289 // block if necessary.
1290 if (isVPTOpcode(MI->getOpcode()))
1291 VPTstate.CreateVPTBlock(MI);
1292
1293 return true;
1294}
1295
1296bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) {
1297 const ARMSubtarget &ST = mf.getSubtarget<ARMSubtarget>();
1298 if (!ST.hasLOB())
1299 return false;
1300
1301 MF = &mf;
1302 LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n");
1303
1304 MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1305 RDI = &getAnalysis<ReachingDefInfoWrapperPass>().getRDI();
1306 MF->getProperties().setTracksLiveness();
1307 TII = ST.getInstrInfo();
1308 TRI = ST.getRegisterInfo();
1309 BBUtils = std::make_unique<ARMBasicBlockUtils>(*MF);
1310 BBUtils->computeAllBlockSizes();
1311 BBUtils->adjustBBOffsetsAfter(&MF->front());
1312
1313 bool Changed = false;
1314 for (auto *ML : *MLI) {
1315 if (ML->isOutermost())
1316 Changed |= ProcessLoop(ML);
1317 }
1318 Changed |= RevertNonLoops();
1319 return Changed;
1320}
1321
1322bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) {
1323 bool Changed = false;
1324
1325 // Process inner loops first.
1326 for (MachineLoop *L : *ML)
1327 Changed |= ProcessLoop(L);
1328
1329 LLVM_DEBUG({
1330 dbgs() << "ARM Loops: Processing loop containing:\n";
1331 if (auto *Preheader = ML->getLoopPreheader())
1332 dbgs() << " - Preheader: " << printMBBReference(*Preheader) << "\n";
1333 else if (auto *Preheader = MLI->findLoopPreheader(ML, true, true))
1334 dbgs() << " - Preheader: " << printMBBReference(*Preheader) << "\n";
1335 for (auto *MBB : ML->getBlocks())
1336 dbgs() << " - Block: " << printMBBReference(*MBB) << "\n";
1337 });
1338
1339 // Search the given block for a loop start instruction. If one isn't found,
1340 // and there's only one predecessor block, search that one too.
1341 std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
1342 [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* {
1343 for (auto &MI : *MBB) {
1344 if (isLoopStart(MI))
1345 return &MI;
1346 }
1347 if (MBB->pred_size() == 1)
1348 return SearchForStart(*MBB->pred_begin());
1349 return nullptr;
1350 };
1351
1352 LowOverheadLoop LoLoop(*ML, *MLI, *RDI, *TRI, *TII);
1353 // Search the preheader for the start intrinsic.
1354 // FIXME: I don't see why we shouldn't be supporting multiple predecessors
1355 // with potentially multiple set.loop.iterations, so we need to enable this.
1356 if (LoLoop.Preheader)
1357 LoLoop.Start = SearchForStart(LoLoop.Preheader);
1358 else
1359 return Changed;
1360
1361 // Find the low-overhead loop components and decide whether or not to fall
1362 // back to a normal loop. Also look for a vctp instructions and decide
1363 // whether we can convert that predicate using tail predication.
1364 for (auto *MBB : reverse(ML->getBlocks())) {
1365 for (auto &MI : *MBB) {
1366 if (MI.isDebugValue())
1367 continue;
1368 else if (MI.getOpcode() == ARM::t2LoopDec)
1369 LoLoop.Dec = &MI;
1370 else if (MI.getOpcode() == ARM::t2LoopEnd)
1371 LoLoop.End = &MI;
1372 else if (MI.getOpcode() == ARM::t2LoopEndDec)
1373 LoLoop.End = LoLoop.Dec = &MI;
1374 else if (isLoopStart(MI))
1375 LoLoop.Start = &MI;
1376 else if (MI.getDesc().isCall()) {
1377 // TODO: Though the call will require LE to execute again, does this
1378 // mean we should revert? Always executing LE hopefully should be
1379 // faster than performing a sub,cmp,br or even subs,br.
1380 LoLoop.Revert = true;
1381 LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
1382 } else {
1383 // Record VPR defs and build up their corresponding vpt blocks.
1384 // Check we know how to tail predicate any mve instructions.
1385 LoLoop.AnalyseMVEInst(&MI);
1386 }
1387 }
1388 }
1389
1390 LLVM_DEBUG(LoLoop.dump());
1391 if (!LoLoop.FoundAllComponents()) {
1392 LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
1393 return Changed;
1394 }
1395
1396 assert(LoLoop.Start->getOpcode() != ARM::t2WhileLoopStart &&
1397 "Expected t2WhileLoopStart to be removed before regalloc!");
1398
1399 // Check that the only instruction using LoopDec is LoopEnd. This can only
1400 // happen when the Dec and End are separate, not a single t2LoopEndDec.
1401 // TODO: Check for copy chains that really have no effect.
1402 if (LoLoop.Dec != LoLoop.End) {
1403 SmallPtrSet<MachineInstr *, 2> Uses;
1404 RDI->getReachingLocalUses(LoLoop.Dec, MCRegister::from(ARM::LR), Uses);
1405 if (Uses.size() > 1 || !Uses.count(LoLoop.End)) {
1406 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n");
1407 LoLoop.Revert = true;
1408 }
1409 }
1410 LoLoop.Validate(BBUtils.get());
1411 Expand(LoLoop);
1412 return true;
1413}
1414
1415// WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
1416// beq that branches to the exit branch.
1417// TODO: We could also try to generate a cbz if the value in LR is also in
1418// another low register.
1419void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const {
1420 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI);
1421 MachineBasicBlock *DestBB = getWhileLoopStartTargetBB(*MI);
1422 unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
1423 ARM::tBcc : ARM::t2Bcc;
1424
1425 RevertWhileLoopStartLR(MI, TII, BrOpc);
1426}
1427
1428void ARMLowOverheadLoops::RevertDo(MachineInstr *MI) const {
1429 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to mov: " << *MI);
1431}
1432
1433bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const {
1434 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI);
1435 MachineBasicBlock *MBB = MI->getParent();
1436 SmallPtrSet<MachineInstr*, 1> Ignore;
1437 for (auto I = MachineBasicBlock::iterator(MI), E = MBB->end(); I != E; ++I) {
1438 if (I->getOpcode() == ARM::t2LoopEnd) {
1439 Ignore.insert(&*I);
1440 break;
1441 }
1442 }
1443
1444 // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
1445 bool SetFlags =
1447
1448 llvm::RevertLoopDec(MI, TII, SetFlags);
1449 return SetFlags;
1450}
1451
1452// Generate a subs, or sub and cmp, and a branch instead of an LE.
1453void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const {
1454 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI);
1455
1456 MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
1457 unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
1458 ARM::tBcc : ARM::t2Bcc;
1459
1460 llvm::RevertLoopEnd(MI, TII, BrOpc, SkipCmp);
1461}
1462
1463// Generate a subs, or sub and cmp, and a branch instead of an LE.
1464void ARMLowOverheadLoops::RevertLoopEndDec(MachineInstr *MI) const {
1465 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to subs, br: " << *MI);
1466 assert(MI->getOpcode() == ARM::t2LoopEndDec && "Expected a t2LoopEndDec!");
1467 MachineBasicBlock *MBB = MI->getParent();
1468
1469 MachineInstrBuilder MIB =
1470 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::t2SUBri));
1471 MIB.addDef(ARM::LR);
1472 MIB.add(MI->getOperand(1));
1473 MIB.addImm(1);
1474 MIB.addImm(ARMCC::AL);
1475 MIB.addReg(Register());
1476 MIB.addReg(ARM::CPSR);
1477 MIB->getOperand(5).setIsDef(true);
1478
1479 MachineBasicBlock *DestBB = MI->getOperand(2).getMBB();
1480 unsigned BrOpc =
1481 BBUtils->isBBInRange(MI, DestBB, 254) ? ARM::tBcc : ARM::t2Bcc;
1482
1483 // Create bne
1484 MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
1485 MIB.add(MI->getOperand(2)); // branch target
1486 MIB.addImm(ARMCC::NE); // condition code
1487 MIB.addReg(ARM::CPSR);
1488
1490}
1491
1492// Perform dead code elimation on the loop iteration count setup expression.
1493// If we are tail-predicating, the number of elements to be processed is the
1494// operand of the VCTP instruction in the vector body, see getCount(), which is
1495// register $r3 in this example:
1496//
1497// $lr = big-itercount-expression
1498// ..
1499// $lr = t2DoLoopStart renamable $lr
1500// vector.body:
1501// ..
1502// $vpr = MVE_VCTP32 renamable $r3
1503// renamable $lr = t2LoopDec killed renamable $lr, 1
1504// t2LoopEnd renamable $lr, %vector.body
1505// tB %end
1506//
1507// What we would like achieve here is to replace the do-loop start pseudo
1508// instruction t2DoLoopStart with:
1509//
1510// $lr = MVE_DLSTP_32 killed renamable $r3
1511//
1512// Thus, $r3 which defines the number of elements, is written to $lr,
1513// and then we want to delete the whole chain that used to define $lr,
1514// see the comment below how this chain could look like.
1515//
1516void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) {
1517 if (!LoLoop.IsTailPredicationLegal())
1518 return;
1519
1520 LLVM_DEBUG(dbgs() << "ARM Loops: Trying DCE on loop iteration count.\n");
1521
1522 MachineInstr *Def = RDI->getMIOperand(LoLoop.Start, 1);
1523 if (!Def) {
1524 LLVM_DEBUG(dbgs() << "ARM Loops: Couldn't find iteration count.\n");
1525 return;
1526 }
1527
1528 // Collect and remove the users of iteration count.
1529 SmallPtrSet<MachineInstr*, 4> Killed = { LoLoop.Start, LoLoop.Dec,
1530 LoLoop.End };
1531 if (!TryRemove(Def, *RDI, LoLoop.ToRemove, Killed))
1532 LLVM_DEBUG(dbgs() << "ARM Loops: Unsafe to remove loop iteration count.\n");
1533}
1534
1535MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
1536 LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n");
1537 // When using tail-predication, try to delete the dead code that was used to
1538 // calculate the number of loop iterations.
1539 IterationCountDCE(LoLoop);
1540
1541 MachineBasicBlock::iterator InsertPt = LoLoop.StartInsertPt;
1542 MachineInstr *Start = LoLoop.Start;
1543 MachineBasicBlock *MBB = LoLoop.StartInsertBB;
1544 unsigned Opc = LoLoop.getStartOpcode();
1545 MachineOperand &Count = LoLoop.getLoopStartOperand();
1546
1547 // A DLS lr, lr we needn't emit
1548 MachineInstr* NewStart;
1549 if (!DisableOmitDLS && Opc == ARM::t2DLS && Count.isReg() &&
1550 Count.getReg() == ARM::LR) {
1551 LLVM_DEBUG(dbgs() << "ARM Loops: Didn't insert start: DLS lr, lr");
1552 NewStart = nullptr;
1553 } else {
1554 MachineInstrBuilder MIB =
1555 BuildMI(*MBB, InsertPt, Start->getDebugLoc(), TII->get(Opc));
1556
1557 MIB.addDef(ARM::LR);
1558 MIB.add(Count);
1559 if (isWhileLoopStart(*Start))
1560 MIB.addMBB(getWhileLoopStartTargetBB(*Start));
1561
1562 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB);
1563 NewStart = &*MIB;
1564 }
1565
1566 LoLoop.ToRemove.insert(Start);
1567 return NewStart;
1568}
1569
1570void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
1571 auto RemovePredicate = [](MachineInstr *MI) {
1572 if (MI->isDebugInstr())
1573 return;
1574 LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI);
1576 assert(PIdx >= 1 && "Trying to unpredicate a non-predicated instruction");
1577 assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then &&
1578 "Expected Then predicate!");
1579 MI->getOperand(PIdx).setImm(ARMVCC::None);
1580 MI->getOperand(PIdx + 1).setReg(0);
1581 };
1582
1583 for (auto &Block : LoLoop.getVPTBlocks()) {
1584 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
1585
1586 auto ReplaceVCMPWithVPT = [&](MachineInstr *&TheVCMP, MachineInstr *At) {
1587 assert(TheVCMP && "Replacing a removed or non-existent VCMP");
1588 // Replace the VCMP with a VPT
1589 MachineInstrBuilder MIB =
1590 BuildMI(*At->getParent(), At, At->getDebugLoc(),
1591 TII->get(VCMPOpcodeToVPT(TheVCMP->getOpcode())));
1592 MIB.addImm(ARMVCC::Then);
1593 // Register one
1594 MIB.add(TheVCMP->getOperand(1));
1595 // Register two
1596 MIB.add(TheVCMP->getOperand(2));
1597 // The comparison code, e.g. ge, eq, lt
1598 MIB.add(TheVCMP->getOperand(3));
1599 LLVM_DEBUG(dbgs() << "ARM Loops: Combining with VCMP to VPT: " << *MIB);
1600 LoLoop.BlockMasksToRecompute.insert(MIB.getInstr());
1601 LoLoop.ToRemove.insert(TheVCMP);
1602 TheVCMP = nullptr;
1603 };
1604
1605 if (LoLoop.VPTstate.isEntryPredicatedOnVCTP(Block, /*exclusive*/ true)) {
1606 MachineInstr *VPST = Insts.front();
1607 if (Block.hasUniformPredicate()) {
1608 // A vpt block starting with VPST, is only predicated upon vctp and has no
1609 // internal vpr defs:
1610 // - Remove vpst.
1611 // - Unpredicate the remaining instructions.
1612 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
1613 for (unsigned i = 1; i < Insts.size(); ++i)
1614 RemovePredicate(Insts[i]);
1615 } else {
1616 // The VPT block has a non-uniform predicate but it uses a vpst and its
1617 // entry is guarded only by a vctp, which means we:
1618 // - Need to remove the original vpst.
1619 // - Then need to unpredicate any following instructions, until
1620 // we come across the divergent vpr def.
1621 // - Insert a new vpst to predicate the instruction(s) that following
1622 // the divergent vpr def.
1623 MachineInstr *Divergent = Block.getDivergent();
1624 MachineBasicBlock *MBB = Divergent->getParent();
1625 auto DivergentNext = ++MachineBasicBlock::iterator(Divergent);
1626 while (DivergentNext != MBB->end() && DivergentNext->isDebugInstr())
1627 ++DivergentNext;
1628
1629 bool DivergentNextIsPredicated =
1630 DivergentNext != MBB->end() &&
1631 getVPTInstrPredicate(*DivergentNext) != ARMVCC::None;
1632
1633 for (auto I = ++MachineBasicBlock::iterator(VPST), E = DivergentNext;
1634 I != E; ++I)
1635 RemovePredicate(&*I);
1636
1637 // Check if the instruction defining vpr is a vcmp so it can be combined
1638 // with the VPST This should be the divergent instruction
1639 MachineInstr *VCMP =
1640 VCMPOpcodeToVPT(Divergent->getOpcode()) != 0 ? Divergent : nullptr;
1641
1642 if (DivergentNextIsPredicated) {
1643 // Insert a VPST at the divergent only if the next instruction
1644 // would actually use it. A VCMP following a VPST can be
1645 // merged into a VPT so do that instead if the VCMP exists.
1646 if (!VCMP) {
1647 // Create a VPST (with a null mask for now, we'll recompute it
1648 // later)
1649 MachineInstrBuilder MIB =
1650 BuildMI(*Divergent->getParent(), Divergent,
1651 Divergent->getDebugLoc(), TII->get(ARM::MVE_VPST));
1652 MIB.addImm(0);
1653 LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB);
1654 LoLoop.BlockMasksToRecompute.insert(MIB.getInstr());
1655 } else {
1656 // No RDI checks are necessary here since the VPST would have been
1657 // directly after the VCMP
1658 ReplaceVCMPWithVPT(VCMP, VCMP);
1659 }
1660 }
1661 }
1662 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
1663 LoLoop.ToRemove.insert(VPST);
1664 } else if (Block.containsVCTP()) {
1665 // The vctp will be removed, so either the entire block will be dead or
1666 // the block mask of the vp(s)t will need to be recomputed.
1667 MachineInstr *VPST = Insts.front();
1668 if (Block.size() == 2) {
1669 assert(VPST->getOpcode() == ARM::MVE_VPST &&
1670 "Found a VPST in an otherwise empty vpt block");
1671 LoLoop.ToRemove.insert(VPST);
1672 } else
1673 LoLoop.BlockMasksToRecompute.insert(VPST);
1674 } else if (Insts.front()->getOpcode() == ARM::MVE_VPST) {
1675 // If this block starts with a VPST then attempt to merge it with the
1676 // preceeding un-merged VCMP into a VPT. This VCMP comes from a VPT
1677 // block that no longer exists
1678 MachineInstr *VPST = Insts.front();
1679 auto Next = ++MachineBasicBlock::iterator(VPST);
1681 "The instruction after a VPST must be predicated");
1682 (void)Next;
1683 MachineInstr *VprDef = RDI->getUniqueReachingMIDef(VPST, ARM::VPR);
1684 if (VprDef && VCMPOpcodeToVPT(VprDef->getOpcode()) &&
1685 !LoLoop.ToRemove.contains(VprDef)) {
1686 MachineInstr *VCMP = VprDef;
1687 // The VCMP and VPST can only be merged if the VCMP's operands will have
1688 // the same values at the VPST.
1689 // If any of the instructions between the VCMP and VPST are predicated
1690 // then a different code path is expected to have merged the VCMP and
1691 // VPST already.
1692 if (std::none_of(++MachineBasicBlock::iterator(VCMP),
1694 RDI->hasSameReachingDef(VCMP, VPST, VCMP->getOperand(1).getReg()) &&
1695 RDI->hasSameReachingDef(VCMP, VPST, VCMP->getOperand(2).getReg())) {
1696 ReplaceVCMPWithVPT(VCMP, VPST);
1697 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
1698 LoLoop.ToRemove.insert(VPST);
1699 }
1700 }
1701 }
1702 }
1703
1704 LoLoop.ToRemove.insert_range(LoLoop.VCTPs);
1705}
1706
1707void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
1708
1709 // Combine the LoopDec and LoopEnd instructions into LE(TP).
1710 auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) {
1711 MachineInstr *End = LoLoop.End;
1712 MachineBasicBlock *MBB = End->getParent();
1713 unsigned Opc = LoLoop.IsTailPredicationLegal() ?
1714 ARM::MVE_LETP : ARM::t2LEUpdate;
1715 MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(),
1716 TII->get(Opc));
1717 MIB.addDef(ARM::LR);
1718 unsigned Off = LoLoop.Dec == LoLoop.End ? 1 : 0;
1719 MIB.add(End->getOperand(Off + 0));
1720 MIB.add(End->getOperand(Off + 1));
1721 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB);
1722 LoLoop.ToRemove.insert(LoLoop.Dec);
1723 LoLoop.ToRemove.insert(End);
1724 return &*MIB;
1725 };
1726
1727 // TODO: We should be able to automatically remove these branches before we
1728 // get here - probably by teaching analyzeBranch about the pseudo
1729 // instructions.
1730 // If there is an unconditional branch, after I, that just branches to the
1731 // next block, remove it.
1732 auto RemoveDeadBranch = [](MachineInstr *I) {
1733 MachineBasicBlock *BB = I->getParent();
1734 MachineInstr *Terminator = &BB->instr_back();
1735 if (Terminator->isUnconditionalBranch() && I != Terminator) {
1736 MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB();
1737 if (BB->isLayoutSuccessor(Succ)) {
1738 LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator);
1739 Terminator->eraseFromParent();
1740 }
1741 }
1742 };
1743
1744 // And VMOVCopies need to become 2xVMOVD for tail predication to be valid.
1745 // Anything other MQPRCopy can be converted to MVE_VORR later on.
1746 auto ExpandVMOVCopies = [this](SmallPtrSet<MachineInstr *, 4> &VMOVCopies) {
1747 for (auto *MI : VMOVCopies) {
1748 LLVM_DEBUG(dbgs() << "Converting copy to VMOVD: " << *MI);
1749 assert(MI->getOpcode() == ARM::MQPRCopy && "Only expected MQPRCOPY!");
1750 MachineBasicBlock *MBB = MI->getParent();
1751 Register Dst = MI->getOperand(0).getReg();
1752 Register Src = MI->getOperand(1).getReg();
1753 auto MIB1 = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::VMOVD),
1754 ARM::D0 + (Dst - ARM::Q0) * 2)
1755 .addReg(ARM::D0 + (Src - ARM::Q0) * 2)
1757 (void)MIB1;
1758 LLVM_DEBUG(dbgs() << " into " << *MIB1);
1759 auto MIB2 = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::VMOVD),
1760 ARM::D0 + (Dst - ARM::Q0) * 2 + 1)
1761 .addReg(ARM::D0 + (Src - ARM::Q0) * 2 + 1)
1763 LLVM_DEBUG(dbgs() << " and " << *MIB2);
1764 (void)MIB2;
1765 MI->eraseFromParent();
1766 }
1767 };
1768
1769 if (LoLoop.Revert) {
1770 if (isWhileLoopStart(*LoLoop.Start))
1771 RevertWhile(LoLoop.Start);
1772 else
1773 RevertDo(LoLoop.Start);
1774 if (LoLoop.Dec == LoLoop.End)
1775 RevertLoopEndDec(LoLoop.End);
1776 else
1777 RevertLoopEnd(LoLoop.End, RevertLoopDec(LoLoop.Dec));
1778 } else {
1779 ExpandVMOVCopies(LoLoop.VMOVCopies);
1780 LoLoop.Start = ExpandLoopStart(LoLoop);
1781 if (LoLoop.Start)
1782 RemoveDeadBranch(LoLoop.Start);
1783 LoLoop.End = ExpandLoopEnd(LoLoop);
1784 RemoveDeadBranch(LoLoop.End);
1785 if (LoLoop.IsTailPredicationLegal())
1786 ConvertVPTBlocks(LoLoop);
1787 for (auto *I : LoLoop.ToRemove) {
1788 LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I);
1789 I->eraseFromParent();
1790 }
1791 for (auto *I : LoLoop.BlockMasksToRecompute) {
1792 LLVM_DEBUG(dbgs() << "ARM Loops: Recomputing VPT/VPST Block Mask: " << *I);
1794 LLVM_DEBUG(dbgs() << " ... done: " << *I);
1795 }
1796 }
1797
1798 PostOrderLoopTraversal DFS(LoLoop.ML, *MLI);
1799 DFS.ProcessLoop();
1800 const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
1801 fullyRecomputeLiveIns(PostOrder);
1802
1803 for (auto *MBB : reverse(PostOrder))
1805
1806 // We've moved, removed and inserted new instructions, so update RDI.
1807 RDI->reset();
1808}
1809
1810bool ARMLowOverheadLoops::RevertNonLoops() {
1811 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
1812 bool Changed = false;
1813
1814 for (auto &MBB : *MF) {
1815 SmallVector<MachineInstr*, 4> Starts;
1816 SmallVector<MachineInstr*, 4> Decs;
1817 SmallVector<MachineInstr*, 4> Ends;
1818 SmallVector<MachineInstr *, 4> EndDecs;
1819 SmallVector<MachineInstr *, 4> MQPRCopies;
1820
1821 for (auto &I : MBB) {
1822 if (isLoopStart(I))
1823 Starts.push_back(&I);
1824 else if (I.getOpcode() == ARM::t2LoopDec)
1825 Decs.push_back(&I);
1826 else if (I.getOpcode() == ARM::t2LoopEnd)
1827 Ends.push_back(&I);
1828 else if (I.getOpcode() == ARM::t2LoopEndDec)
1829 EndDecs.push_back(&I);
1830 else if (I.getOpcode() == ARM::MQPRCopy)
1831 MQPRCopies.push_back(&I);
1832 }
1833
1834 if (Starts.empty() && Decs.empty() && Ends.empty() && EndDecs.empty() &&
1835 MQPRCopies.empty())
1836 continue;
1837
1838 Changed = true;
1839
1840 for (auto *Start : Starts) {
1841 if (isWhileLoopStart(*Start))
1842 RevertWhile(Start);
1843 else
1844 RevertDo(Start);
1845 }
1846 for (auto *Dec : Decs)
1847 RevertLoopDec(Dec);
1848
1849 for (auto *End : Ends)
1851 for (auto *End : EndDecs)
1852 RevertLoopEndDec(End);
1853 for (auto *MI : MQPRCopies) {
1854 LLVM_DEBUG(dbgs() << "Converting copy to VORR: " << *MI);
1855 assert(MI->getOpcode() == ARM::MQPRCopy && "Only expected MQPRCOPY!");
1856 MachineBasicBlock *MBB = MI->getParent();
1857 auto MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::MVE_VORR),
1858 MI->getOperand(0).getReg())
1859 .add(MI->getOperand(1))
1860 .add(MI->getOperand(1));
1861 addUnpredicatedMveVpredROp(MIB, MI->getOperand(0).getReg());
1862 MI->eraseFromParent();
1863 }
1864 }
1865 return Changed;
1866}
1867
1869 return new ARMLowOverheadLoops();
1870}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isRegInClass(const MachineOperand &RegMO, const TargetRegisterClass &Class, const MachineRegisterInfo &MRI)
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
uint64_t uint64_t
static int getVecSize(const AMDGPULibFunc &FInfo)
static bool isDomainMVE(MachineInstr *MI)
static bool isVectorPredicated(MachineInstr *MI)
ReachingDefInfo & RDI
static bool canGenerateNonZeros(const MachineInstr &MI)
static bool isHorizontalReduction(const MachineInstr &MI)
static bool producesDoubleWidthResult(const MachineInstr &MI)
static bool hasVPRUse(MachineInstr &MI)
static bool ValidateMVEStore(MachineInstr *MI, MachineLoop *ML)
static bool isVectorPredicate(MachineInstr *MI)
static bool retainsPreviousHalfElement(const MachineInstr &MI)
static bool shouldInspect(MachineInstr &MI)
static bool producesFalseLanesZero(MachineInstr &MI, const TargetRegisterClass *QPRs, const ReachingDefInfo &RDI, InstSet &FalseLanesZero)
static cl::opt< bool > DisableTailPredication("arm-loloops-disable-tailpred", cl::Hidden, cl::desc("Disable tail-predication in the ARM LowOverheadLoop pass"), cl::init(false))
ReachingDefInfo InstSet InstSet & Ignore
if(!RDI.isSafeToRemove(MI, Uses, Ignore)) return false
static int getVecSize(const MachineInstr &MI)
#define ARM_LOW_OVERHEAD_LOOPS_NAME
static cl::opt< bool > DisableOmitDLS("arm-disable-omit-dls", cl::Hidden, cl::desc("Disable omitting 'dls lr, lr' instructions"), cl::init(false))
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock & MBB
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
static const Function * getParent(const Value *V)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define I(x, y, z)
Definition MD5.cpp:57
static ARM::PredBlockMask CreateVPTBlock(MachineBasicBlock::instr_iterator &Iter, MachineBasicBlock::instr_iterator EndIter, SmallVectorImpl< MachineInstr * > &DeadInstructions)
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
Remove Loads Into Fake Uses
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file implements a set that has insertion order iteration characteristics.
#define LLVM_DEBUG(...)
Definition Debug.h:119
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
Describe properties that are true of each instruction in the target description file.
ArrayRef< MCOperandInfo > operands() const
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
static MCRegister from(unsigned Val)
Check the provided unsigned value is a valid MCRegister.
Definition MCRegister.h:77
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
iterator_range< livein_iterator > liveins() const
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
LLVM_ABI void setIsDef(bool Val=true)
Change a def to a use, or a use to a def.
Special value supplied for machine level alias analysis.
This class provides the reaching def analysis.
LLVM_ABI MachineInstr * getUniqueReachingMIDef(MachineInstr *MI, Register Reg) const
If a single MachineInstr creates the reaching definition, then return it.
LLVM_ABI bool isReachingDefLiveOut(MachineInstr *MI, Register Reg) const
Return whether the reaching def for MI also is live out of its parent block.
LLVM_ABI bool isSafeToMoveForwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved forwards to just before To.
LLVM_ABI void getReachingLocalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Provides the uses, in the same block as MI, of register that MI defines.
LLVM_ABI bool hasLocalDefBefore(MachineInstr *MI, Register Reg) const
Provide whether the register has been defined in the same basic block as, and before,...
LLVM_ABI void reset()
Re-run the analysis.
LLVM_ABI void getGlobalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Collect the users of the value stored in Reg, which is defined by MI.
LLVM_ABI MachineInstr * getMIOperand(MachineInstr *MI, unsigned Idx) const
If a single MachineInstr creates the reaching definition, for MIs operand at Idx, then return it.
LLVM_ABI bool isSafeToMoveBackwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved backwards to just after To.
LLVM_ABI bool hasSameReachingDef(MachineInstr *A, MachineInstr *B, Register Reg) const
Return whether A and B use the same def of Reg.
LLVM_ABI void getGlobalReachingDefs(MachineInstr *MI, Register Reg, InstSet &Defs) const
Collect all possible definitions of the value stored in Reg, which is used by MI.
LLVM_ABI MachineInstr * getLocalLiveOutMIDef(MachineBasicBlock *MBB, Register Reg) const
Return the local MI that produces the live out value for Reg, or nullptr for a non-live out or non-lo...
LLVM_ABI bool isSafeToDefRegAt(MachineInstr *MI, Register Reg) const
Return whether a MachineInstr could be inserted at MI and safely define the given register without af...
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
iterator end() const
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
@ ValidForTailPredication
@ RetainsPreviousHalfElement
bool isPredicated(const MCInst &MI, const MCInstrInfo *MCII)
bool isVpred(OperandType op)
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
static bool isDoLoopStart(const MachineInstr &MI)
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
int findVPTInactiveOperandIdx(const MachineInstr &MI)
int findFirstVPTPredOperandIdx(const MachineInstr &MI)
ARMVCC::VPTCodes getVPTInstrPredicate(const MachineInstr &MI, Register &PredReg)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
static bool isVCTP(const MachineInstr *MI)
@ Dead
Unused definition.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr from_range_t from_range
static bool isVPTOpcode(int Opc)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
static unsigned getTailPredVectorWidth(unsigned Opcode)
static std::array< MachineOperand, 2 > predOps(ARMCC::CondCodes Pred, unsigned PredReg=0)
Get the operands corresponding to the given Pred value.
FunctionPass * createARMLowOverheadLoopsPass()
static bool isMovRegOpcode(int Opc)
static bool isSubImmOpcode(int Opc)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
static bool isLoopStart(const MachineInstr &MI)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
void RevertWhileLoopStartLR(MachineInstr *MI, const TargetInstrInfo *TII, unsigned BrOpc=ARM::t2Bcc, bool UseCmp=false)
LLVM_ABI void recomputeLivenessFlags(MachineBasicBlock &MBB)
Recomputes dead and kill flags in MBB.
static unsigned VCTPOpcodeToLSTP(unsigned Opcode, bool IsDoLoop)
void addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB, Register DestReg)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
void RevertLoopEnd(MachineInstr *MI, const TargetInstrInfo *TII, unsigned BrOpc=ARM::t2Bcc, bool SkipCmp=false)
void RevertLoopDec(MachineInstr *MI, const TargetInstrInfo *TII, bool SetFlags=false)
MachineBasicBlock * getWhileLoopStartTargetBB(const MachineInstr &MI)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
static bool isWhileLoopStart(const MachineInstr &MI)
static unsigned VCMPOpcodeToVPT(unsigned Opcode)
void RevertDoLoopStart(MachineInstr *MI, const TargetInstrInfo *TII)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
int getAddSubImmediate(MachineInstr &MI)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
void recomputeVPTBlockMask(MachineInstr &Instr)
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58