LLVM 24.0.0git
HexagonVLIWPacketizer.cpp
Go to the documentation of this file.
1//===- HexagonPacketizer.cpp - VLIW packetizer ----------------------------===//
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//
9// This implements a simple VLIW packetizer using DFA. The packetizer works on
10// machine basic blocks. For each instruction I in BB, the packetizer consults
11// the DFA to see if machine resources are available to execute I. If so, the
12// packetizer checks if I depends on any instruction J in the current packet.
13// If no dependency is found, I is added to current packet and machine resource
14// is marked as taken. If any dependency is found, a target API call is made to
15// prune the dependence.
16//
17//===----------------------------------------------------------------------===//
18
20#include "Hexagon.h"
21#include "HexagonInstrInfo.h"
22#include "HexagonRegisterInfo.h"
23#include "HexagonSubtarget.h"
24#include "llvm/ADT/BitVector.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/STLExtras.h"
42#include "llvm/IR/DebugLoc.h"
44#include "llvm/MC/MCInstrDesc.h"
45#include "llvm/Pass.h"
47#include "llvm/Support/Debug.h"
50#include <cassert>
51#include <cstdint>
52#include <iterator>
53
54using namespace llvm;
55
56#define DEBUG_TYPE "packets"
57
59 cl::desc("Disable Hexagon packetizer pass"));
60
61static cl::opt<bool> Slot1Store("slot1-store-slot0-load", cl::Hidden,
62 cl::init(true),
63 cl::desc("Allow slot1 store and slot0 load"));
64
66 "hexagon-packetize-volatiles", cl::Hidden, cl::init(true),
67 cl::desc("Allow non-solo packetization of volatile memory references"));
68
69static cl::opt<bool>
71 cl::desc("Generate all instruction with TC"));
72
73static cl::opt<bool>
74 DisableVecDblNVStores("disable-vecdbl-nv-stores", cl::Hidden,
75 cl::desc("Disable vector double new-value-stores"));
76
78
79namespace {
80
81 class HexagonPacketizer : public MachineFunctionPass {
82 public:
83 static char ID;
84
85 HexagonPacketizer(bool Min = false)
86 : MachineFunctionPass(ID), Minimal(Min) {}
87
88 void getAnalysisUsage(AnalysisUsage &AU) const override {
89 AU.setPreservesCFG();
90 AU.addRequired<AAResultsWrapperPass>();
91 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
92 AU.addRequired<MachineLoopInfoWrapperPass>();
94 }
95
96 StringRef getPassName() const override { return "Hexagon Packetizer"; }
97 bool runOnMachineFunction(MachineFunction &Fn) override;
98
99 MachineFunctionProperties getRequiredProperties() const override {
100 return MachineFunctionProperties().setNoVRegs();
101 }
102
103 private:
104 const HexagonInstrInfo *HII = nullptr;
105 const HexagonRegisterInfo *HRI = nullptr;
106 const bool Minimal = false;
107 };
108
109} // end anonymous namespace
110
111char HexagonPacketizer::ID = 0;
112
113INITIALIZE_PASS_BEGIN(HexagonPacketizer, "hexagon-packetizer",
114 "Hexagon Packetizer", false, false)
119INITIALIZE_PASS_END(HexagonPacketizer, "hexagon-packetizer",
120 "Hexagon Packetizer", false, false)
121
126 Minimal(Minimal) {
127 HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
128 HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
129
130 addMutation(std::make_unique<HexagonSubtarget::UsrOverflowMutation>());
131 addMutation(std::make_unique<HexagonSubtarget::HVXMemLatencyMutation>());
132 addMutation(std::make_unique<HexagonSubtarget::BankConflictMutation>());
133 addMutation(std::make_unique<HexagonSubtarget::HLXPseudoMutation>());
134}
135
136// Check if FirstI modifies a register that SecondI reads.
137static bool hasWriteToReadDep(const MachineInstr &FirstI,
138 const MachineInstr &SecondI,
139 const TargetRegisterInfo *TRI) {
140 for (auto &MO : FirstI.operands()) {
141 if (!MO.isReg() || !MO.isDef())
142 continue;
143 Register R = MO.getReg();
144 if (SecondI.readsRegister(R, TRI))
145 return true;
146 }
147 return false;
148}
149
150
152 MachineBasicBlock::iterator BundleIt, bool Before) {
154 if (Before)
155 InsertPt = BundleIt.getInstrIterator();
156 else
157 InsertPt = std::next(BundleIt).getInstrIterator();
158
159 MachineBasicBlock &B = *MI.getParent();
160 // The instruction should at least be bundled with the preceding instruction
161 // (there will always be one, i.e. BUNDLE, if nothing else).
162 assert(MI.isBundledWithPred());
163 if (MI.isBundledWithSucc()) {
164 MI.clearFlag(MachineInstr::BundledSucc);
165 MI.clearFlag(MachineInstr::BundledPred);
166 } else {
167 // If it's not bundled with the successor (i.e. it is the last one
168 // in the bundle), then we can simply unbundle it from the predecessor,
169 // which will take care of updating the predecessor's flag.
170 MI.unbundleFromPred();
171 }
172 B.splice(InsertPt, &B, MI.getIterator());
173
174 // Get the size of the bundle without asserting.
177 unsigned Size = 0;
178 for (++I; I != E && I->isBundledWithPred(); ++I)
179 ++Size;
180
181 // If there are still two or more instructions, then there is nothing
182 // else to be done.
183 if (Size > 1)
184 return BundleIt;
185
186 // Otherwise, extract the single instruction out and delete the bundle.
187 MachineBasicBlock::iterator NextIt = std::next(BundleIt);
188 MachineInstr &SingleI = *BundleIt->getNextNode();
189 SingleI.unbundleFromPred();
190 assert(!SingleI.isBundledWithSucc());
191 BundleIt->eraseFromParent();
192 return NextIt;
193}
194
195bool HexagonPacketizer::runOnMachineFunction(MachineFunction &MF) {
196 // FIXME: This pass causes verification failures.
197 MF.getProperties().setFailsVerification();
198
199 auto &HST = MF.getSubtarget<HexagonSubtarget>();
200 HII = HST.getInstrInfo();
201 HRI = HST.getRegisterInfo();
202 auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
203 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
204 auto *MBPI =
205 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
206
208 HII->genAllInsnTimingClasses(MF);
209
210 // Instantiate the packetizer.
211 bool MinOnly = Minimal || DisablePacketizer || !HST.usePackets() ||
212 skipFunction(MF.getFunction());
213 HexagonPacketizerList Packetizer(MF, MLI, AA, MBPI, MinOnly);
214
215 // DFA state table should not be empty.
216 assert(Packetizer.getResourceTracker() && "Empty DFA table!");
217
218 // Loop over all basic blocks and remove KILL pseudo-instructions
219 // These instructions confuse the dependence analysis. Consider:
220 // D0 = ... (Insn 0)
221 // R0 = KILL R0, D0 (Insn 1)
222 // R0 = ... (Insn 2)
223 // Here, Insn 1 will result in the dependence graph not emitting an output
224 // dependence between Insn 0 and Insn 2. This can lead to incorrect
225 // packetization
226 for (MachineBasicBlock &MB : MF) {
227 for (MachineInstr &MI : llvm::make_early_inc_range(MB))
228 if (MI.isKill())
229 MB.erase(&MI);
230 }
231
232 // TinyCore with Duplexes: Translate to big-instructions.
233 if (HST.isTinyCoreWithDuplex())
234 HII->translateInstrsForDup(MF, true);
235
236 // Loop over all of the basic blocks.
237 for (auto &MB : MF) {
238 auto Begin = MB.begin(), End = MB.end();
239 while (Begin != End) {
240 // Find the first non-boundary starting from the end of the last
241 // scheduling region.
243 while (RB != End && HII->isSchedulingBoundary(*RB, &MB, MF))
244 ++RB;
245 // Find the first boundary starting from the beginning of the new
246 // region.
248 while (RE != End && !HII->isSchedulingBoundary(*RE, &MB, MF))
249 ++RE;
250 // Add the scheduling boundary if it's not block end.
251 if (RE != End)
252 ++RE;
253 // If RB == End, then RE == End.
254 if (RB != End)
255 Packetizer.PacketizeMIs(&MB, RB, RE);
256
257 Begin = RE;
258 }
259 }
260
261 // TinyCore with Duplexes: Translate to tiny-instructions.
262 if (HST.isTinyCoreWithDuplex())
263 HII->translateInstrsForDup(MF, false);
264
265 Packetizer.unpacketizeSoloInstrs(MF);
266 return true;
267}
268
269// Reserve resources for a constant extender. Trigger an assertion if the
270// reservation fails.
275
279
280// Allocate resources (i.e. 4 bytes) for constant extender. If succeeded,
281// return true, otherwise, return false.
283 auto *ExtMI = MF.CreateMachineInstr(HII->get(Hexagon::A4_ext), DebugLoc());
284 bool Avail = ResourceTracker->canReserveResources(*ExtMI);
285 if (Reserve && Avail)
286 ResourceTracker->reserveResources(*ExtMI);
287 MF.deleteMachineInstr(ExtMI);
288 return Avail;
289}
290
292 SDep::Kind DepType, unsigned DepReg) {
293 // Check for LR dependence.
294 if (DepReg == HRI->getRARegister())
295 return true;
296
297 if (HII->isDeallocRet(MI))
298 if (DepReg == HRI->getFrameRegister() || DepReg == HRI->getStackRegister())
299 return true;
300
301 // Call-like instructions can be packetized with preceding instructions
302 // that define registers implicitly used or modified by the call. Explicit
303 // uses are still prohibited, as in the case of indirect calls:
304 // r0 = ...
305 // J2_jumpr r0
306 if (DepType == SDep::Data) {
307 for (const MachineOperand &MO : MI.operands())
308 if (MO.isReg() && MO.getReg() == DepReg && !MO.isImplicit())
309 return true;
310 }
311
312 return false;
313}
314
315static bool isRegDependence(const SDep::Kind DepType) {
316 return DepType == SDep::Data || DepType == SDep::Anti ||
317 DepType == SDep::Output;
318}
319
320static bool isDirectJump(const MachineInstr &MI) {
321 return MI.getOpcode() == Hexagon::J2_jump;
322}
323
324static bool isSchedBarrier(const MachineInstr &MI) {
325 switch (MI.getOpcode()) {
326 case Hexagon::Y2_barrier:
327 return true;
328 }
329 return false;
330}
331
332static bool isControlFlow(const MachineInstr &MI) {
333 return MI.getDesc().isTerminator() || MI.getDesc().isCall();
334}
335
336/// Returns true if the instruction modifies a callee-saved register.
338 const TargetRegisterInfo *TRI) {
339 const MachineFunction &MF = *MI.getParent()->getParent();
340 for (auto *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
341 if (MI.modifiesRegister(*CSR, TRI))
342 return true;
343 return false;
344}
345
346// Returns true if an instruction can be promoted to .new predicate or
347// new-value store.
349 const TargetRegisterClass *NewRC) {
350 // Vector stores can be predicated, and can be new-value stores, but
351 // they cannot be predicated on a .new predicate value.
352 if (NewRC == &Hexagon::PredRegsRegClass) {
353 if (HII->isHVXVec(MI) && MI.mayStore())
354 return false;
355 return HII->isPredicated(MI) && HII->getDotNewPredOp(MI, nullptr) > 0;
356 }
357 // If the class is not PredRegs, it could only apply to new-value stores.
358 return HII->mayBeNewStore(MI);
359}
360
361// Promote an instructiont to its .cur form.
362// At this time, we have already made a call to canPromoteToDotCur and made
363// sure that it can *indeed* be promoted.
366 const TargetRegisterClass* RC) {
367 assert(DepType == SDep::Data);
368 int CurOpcode = HII->getDotCurOp(MI);
369 MI.setDesc(HII->get(CurOpcode));
370 return true;
371}
372
374 MachineInstr *MI = nullptr;
375 for (auto *BI : CurrentPacketMIs) {
376 LLVM_DEBUG(dbgs() << "Cleanup packet has "; BI->dump(););
377 if (HII->isDotCurInst(*BI)) {
378 MI = BI;
379 continue;
380 }
381 if (MI) {
382 for (auto &MO : BI->operands())
383 if (MO.isReg() && MO.getReg() == MI->getOperand(0).getReg())
384 return;
385 }
386 }
387 if (!MI)
388 return;
389 // We did not find a use of the CUR, so de-cur it.
390 MI->setDesc(HII->get(HII->getNonDotCurOp(*MI)));
391 LLVM_DEBUG(dbgs() << "Demoted CUR "; MI->dump(););
392}
393
394// Check to see if an instruction can be dot cur.
396 const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII,
397 const TargetRegisterClass *RC) {
398 if (!HII->isHVXVec(MI))
399 return false;
400 if (!HII->isHVXVec(*MII))
401 return false;
402
403 // Already a dot new instruction.
404 if (HII->isDotCurInst(MI) && !HII->mayBeCurLoad(MI))
405 return false;
406
407 if (!HII->mayBeCurLoad(MI))
408 return false;
409
410 // The "cur value" cannot come from inline asm.
411 if (PacketSU->getInstr()->isInlineAsm())
412 return false;
413
414 // Make sure candidate instruction uses cur.
415 LLVM_DEBUG(dbgs() << "Can we DOT Cur Vector MI\n"; MI.dump();
416 dbgs() << "in packet\n";);
417 MachineInstr &MJ = *MII;
418 LLVM_DEBUG({
419 dbgs() << "Checking CUR against ";
420 MJ.dump();
421 });
422 Register DestReg = MI.getOperand(0).getReg();
423 bool FoundMatch = false;
424 for (auto &MO : MJ.operands())
425 if (MO.isReg() && MO.getReg() == DestReg)
426 FoundMatch = true;
427 if (!FoundMatch)
428 return false;
429
430 // Check for existing uses of a vector register within the packet which
431 // would be affected by converting a vector load into .cur format.
432 for (auto *BI : CurrentPacketMIs) {
433 LLVM_DEBUG(dbgs() << "packet has "; BI->dump(););
434 if (BI->readsRegister(DepReg, MF.getSubtarget().getRegisterInfo()))
435 return false;
436 }
437
438 LLVM_DEBUG(dbgs() << "Can Dot CUR MI\n"; MI.dump(););
439 // We can convert the opcode into a .cur.
440 return true;
441}
442
443// Promote an instruction to its .new form. At this time, we have already
444// made a call to canPromoteToDotNew and made sure that it can *indeed* be
445// promoted.
448 const TargetRegisterClass* RC) {
449 assert(DepType == SDep::Data);
450 int NewOpcode;
451 if (RC == &Hexagon::PredRegsRegClass)
452 NewOpcode = HII->getDotNewPredOp(MI, MBPI);
453 else
454 NewOpcode = HII->getDotNewOp(MI);
455 MI.setDesc(HII->get(NewOpcode));
456 return true;
457}
458
460 int NewOpcode = HII->getDotOldOp(MI);
461 MI.setDesc(HII->get(NewOpcode));
462 return true;
463}
464
466 unsigned Opc = MI.getOpcode();
467 switch (Opc) {
468 case Hexagon::S2_storerd_io:
469 case Hexagon::S2_storeri_io:
470 case Hexagon::S2_storerh_io:
471 case Hexagon::S2_storerb_io:
472 break;
473 default:
474 llvm_unreachable("Unexpected instruction");
475 }
476 unsigned FrameSize = MF.getFrameInfo().getStackSize();
477 MachineOperand &Off = MI.getOperand(1);
478 int64_t NewOff = Off.getImm() - (FrameSize + HEXAGON_LRFP_SIZE);
479 if (HII->isValidOffset(Opc, NewOff)) {
480 Off.setImm(NewOff);
481 return true;
482 }
483 return false;
484}
485
487 unsigned Opc = MI.getOpcode();
488 switch (Opc) {
489 case Hexagon::S2_storerd_io:
490 case Hexagon::S2_storeri_io:
491 case Hexagon::S2_storerh_io:
492 case Hexagon::S2_storerb_io:
493 break;
494 default:
495 llvm_unreachable("Unexpected instruction");
496 }
497 unsigned FrameSize = MF.getFrameInfo().getStackSize();
498 MachineOperand &Off = MI.getOperand(1);
499 Off.setImm(Off.getImm() + FrameSize + HEXAGON_LRFP_SIZE);
500}
501
502/// Return true if we can update the offset in MI so that MI and MJ
503/// can be packetized together.
505 assert(SUI->getInstr() && SUJ->getInstr());
506 MachineInstr &MI = *SUI->getInstr();
507 MachineInstr &MJ = *SUJ->getInstr();
508
509 unsigned BPI, OPI;
510 if (!HII->getBaseAndOffsetPosition(MI, BPI, OPI))
511 return false;
512 unsigned BPJ, OPJ;
513 if (!HII->getBaseAndOffsetPosition(MJ, BPJ, OPJ))
514 return false;
515 Register Reg = MI.getOperand(BPI).getReg();
516 if (Reg != MJ.getOperand(BPJ).getReg())
517 return false;
518 // Make sure that the dependences do not restrict adding MI to the packet.
519 // That is, ignore anti dependences, and make sure the only data dependence
520 // involves the specific register.
521 for (const auto &PI : SUI->Preds)
522 if (PI.getKind() != SDep::Anti &&
523 (PI.getKind() != SDep::Data || PI.getReg() != Reg))
524 return false;
525 int Incr;
526 if (!HII->getIncrementValue(MJ, Incr))
527 return false;
528
529 int64_t Offset = MI.getOperand(OPI).getImm();
530 if (!HII->isValidOffset(MI.getOpcode(), Offset + Incr))
531 return false;
532
533 MI.getOperand(OPI).setImm(Offset + Incr);
534 ChangedOffset = Offset;
535 return true;
536}
537
538/// Undo the changed offset. This is needed if the instruction cannot be
539/// added to the current packet due to a different instruction.
541 unsigned BP, OP;
542 if (!HII->getBaseAndOffsetPosition(MI, BP, OP))
543 llvm_unreachable("Unable to find base and offset operands.");
544 MI.getOperand(OP).setImm(ChangedOffset);
545}
546
552
553/// Returns true if an instruction is predicated on p0 and false if it's
554/// predicated on !p0.
556 const HexagonInstrInfo *HII) {
557 if (!HII->isPredicated(MI))
558 return PK_Unknown;
559 if (HII->isPredicatedTrue(MI))
560 return PK_True;
561 return PK_False;
562}
563
565 const HexagonInstrInfo *HII) {
566 assert(HII->isPostIncrement(MI) && "Not a post increment operation.");
567#ifndef NDEBUG
568 // Post Increment means duplicates. Use dense map to find duplicates in the
569 // list. Caution: Densemap initializes with the minimum of 64 buckets,
570 // whereas there are at most 5 operands in the post increment.
571 DenseSet<unsigned> DefRegsSet;
572 for (auto &MO : MI.operands())
573 if (MO.isReg() && MO.isDef())
574 DefRegsSet.insert(MO.getReg());
575
576 for (auto &MO : MI.operands())
577 if (MO.isReg() && MO.isUse() && DefRegsSet.count(MO.getReg()))
578 return MO;
579#else
580 if (MI.mayLoad()) {
581 const MachineOperand &Op1 = MI.getOperand(1);
582 // The 2nd operand is always the post increment operand in load.
583 assert(Op1.isReg() && "Post increment operand has be to a register.");
584 return Op1;
585 }
586 if (MI.getDesc().mayStore()) {
587 const MachineOperand &Op0 = MI.getOperand(0);
588 // The 1st operand is always the post increment operand in store.
589 assert(Op0.isReg() && "Post increment operand has be to a register.");
590 return Op0;
591 }
592#endif
593 // we should never come here.
594 llvm_unreachable("mayLoad or mayStore not set for Post Increment operation");
595}
596
597// Get the value being stored.
599 // value being stored is always the last operand.
600 return MI.getOperand(MI.getNumOperands()-1);
601}
602
603static bool isLoadAbsSet(const MachineInstr &MI) {
604 unsigned Opc = MI.getOpcode();
605 switch (Opc) {
606 case Hexagon::L4_loadrd_ap:
607 case Hexagon::L4_loadrb_ap:
608 case Hexagon::L4_loadrh_ap:
609 case Hexagon::L4_loadrub_ap:
610 case Hexagon::L4_loadruh_ap:
611 case Hexagon::L4_loadri_ap:
612 return true;
613 }
614 return false;
615}
616
619 return MI.getOperand(1);
620}
621
622// Can be new value store?
623// Following restrictions are to be respected in convert a store into
624// a new value store.
625// 1. If an instruction uses auto-increment, its address register cannot
626// be a new-value register. Arch Spec 5.4.2.1
627// 2. If an instruction uses absolute-set addressing mode, its address
628// register cannot be a new-value register. Arch Spec 5.4.2.1.
629// 3. If an instruction produces a 64-bit result, its registers cannot be used
630// as new-value registers. Arch Spec 5.4.2.2.
631// 4. If the instruction that sets the new-value register is conditional, then
632// the instruction that uses the new-value register must also be conditional,
633// and both must always have their predicates evaluate identically.
634// Arch Spec 5.4.2.3.
635// 5. There is an implied restriction that a packet cannot have another store,
636// if there is a new value store in the packet. Corollary: if there is
637// already a store in a packet, there can not be a new value store.
638// Arch Spec: 3.4.4.2
640 const MachineInstr &PacketMI, unsigned DepReg) {
641 // Make sure we are looking at the store, that can be promoted.
642 if (!HII->mayBeNewStore(MI))
643 return false;
644
645 // Make sure there is dependency and can be new value'd.
647 if (Val.isReg() && Val.getReg() != DepReg)
648 return false;
649
650 const MCInstrDesc& MCID = PacketMI.getDesc();
651
652 // First operand is always the result.
653 const TargetRegisterClass *PacketRC = HII->getRegClass(MCID, 0);
654 // Double regs can not feed into new value store: PRM section: 5.4.2.2.
655 if (PacketRC == &Hexagon::DoubleRegsRegClass)
656 return false;
657
658 // New-value stores are of class NV (slot 0), dual stores require class ST
659 // in slot 0 (PRM 5.5).
660 for (auto *I : CurrentPacketMIs) {
661 SUnit *PacketSU = MIToSUnit.find(I)->second;
662 if (PacketSU->getInstr()->mayStore())
663 return false;
664 }
665
666 // Make sure it's NOT the post increment register that we are going to
667 // new value.
668 if (HII->isPostIncrement(MI) &&
669 getPostIncrementOperand(MI, HII).getReg() == DepReg) {
670 return false;
671 }
672
673 if (HII->isPostIncrement(PacketMI) && PacketMI.mayLoad() &&
674 getPostIncrementOperand(PacketMI, HII).getReg() == DepReg) {
675 // If source is post_inc, or absolute-set addressing, it can not feed
676 // into new value store
677 // r3 = memw(r2++#4)
678 // memw(r30 + #-1404) = r2.new -> can not be new value store
679 // arch spec section: 5.4.2.1.
680 return false;
681 }
682
683 if (isLoadAbsSet(PacketMI) && getAbsSetOperand(PacketMI).getReg() == DepReg)
684 return false;
685
686 // If the source that feeds the store is predicated, new value store must
687 // also be predicated.
688 if (HII->isPredicated(PacketMI)) {
689 if (!HII->isPredicated(MI))
690 return false;
691
692 // Check to make sure that they both will have their predicates
693 // evaluate identically.
694 unsigned predRegNumSrc = 0;
695 unsigned predRegNumDst = 0;
696 const TargetRegisterClass* predRegClass = nullptr;
697
698 // Get predicate register used in the source instruction.
699 for (auto &MO : PacketMI.operands()) {
700 if (!MO.isReg())
701 continue;
702 predRegNumSrc = MO.getReg();
703 predRegClass = HRI->getMinimalPhysRegClass(predRegNumSrc);
704 if (predRegClass == &Hexagon::PredRegsRegClass)
705 break;
706 }
707 assert((predRegClass == &Hexagon::PredRegsRegClass) &&
708 "predicate register not found in a predicated PacketMI instruction");
709
710 // Get predicate register used in new-value store instruction.
711 for (auto &MO : MI.operands()) {
712 if (!MO.isReg())
713 continue;
714 predRegNumDst = MO.getReg();
715 predRegClass = HRI->getMinimalPhysRegClass(predRegNumDst);
716 if (predRegClass == &Hexagon::PredRegsRegClass)
717 break;
718 }
719 assert((predRegClass == &Hexagon::PredRegsRegClass) &&
720 "predicate register not found in a predicated MI instruction");
721
722 // New-value register producer and user (store) need to satisfy these
723 // constraints:
724 // 1) Both instructions should be predicated on the same register.
725 // 2) If producer of the new-value register is .new predicated then store
726 // should also be .new predicated and if producer is not .new predicated
727 // then store should not be .new predicated.
728 // 3) Both new-value register producer and user should have same predicate
729 // sense, i.e, either both should be negated or both should be non-negated.
730 if (predRegNumDst != predRegNumSrc ||
731 HII->isDotNewInst(PacketMI) != HII->isDotNewInst(MI) ||
732 getPredicateSense(MI, HII) != getPredicateSense(PacketMI, HII))
733 return false;
734 }
735
736 // Make sure that other than the new-value register no other store instruction
737 // register has been modified in the same packet. Predicate registers can be
738 // modified by they should not be modified between the producer and the store
739 // instruction as it will make them both conditional on different values.
740 // We already know this to be true for all the instructions before and
741 // including PacketMI. However, we need to perform the check for the
742 // remaining instructions in the packet.
743
744 unsigned StartCheck = 0;
745
746 for (auto *I : CurrentPacketMIs) {
747 SUnit *TempSU = MIToSUnit.find(I)->second;
748 MachineInstr &TempMI = *TempSU->getInstr();
749
750 // Following condition is true for all the instructions until PacketMI is
751 // reached (StartCheck is set to 0 before the for loop).
752 // StartCheck flag is 1 for all the instructions after PacketMI.
753 if (&TempMI != &PacketMI && !StartCheck) // Start processing only after
754 continue; // encountering PacketMI.
755
756 StartCheck = 1;
757 if (&TempMI == &PacketMI) // We don't want to check PacketMI for dependence.
758 continue;
759
760 for (auto &MO : MI.operands())
761 if (MO.isReg() && TempSU->getInstr()->modifiesRegister(MO.getReg(), HRI))
762 return false;
763 }
764
765 // Make sure that for non-POST_INC stores:
766 // 1. The only use of reg is DepReg and no other registers.
767 // This handles base+index registers.
768 // The following store can not be dot new.
769 // Eg. r0 = add(r0, #3)
770 // memw(r1+r0<<#2) = r0
771 if (!HII->isPostIncrement(MI)) {
772 for (unsigned opNum = 0; opNum < MI.getNumOperands()-1; opNum++) {
773 const MachineOperand &MO = MI.getOperand(opNum);
774 if (MO.isReg() && MO.getReg() == DepReg)
775 return false;
776 }
777 }
778
779 // If data definition is because of implicit definition of the register,
780 // do not newify the store. Eg.
781 // %r9 = ZXTH %r12, implicit %d6, implicit-def %r12
782 // S2_storerh_io %r8, 2, killed %r12; mem:ST2[%scevgep343]
783 for (auto &MO : PacketMI.operands()) {
784 if (MO.isRegMask() && MO.clobbersPhysReg(DepReg))
785 return false;
786 if (!MO.isReg() || !MO.isDef() || !MO.isImplicit())
787 continue;
788 Register R = MO.getReg();
789 if (R == DepReg || HRI->isSuperRegister(DepReg, R))
790 return false;
791 }
792
793 // Handle imp-use of super reg case. There is a target independent side
794 // change that should prevent this situation but I am handling it for
795 // just-in-case. For example, we cannot newify R2 in the following case:
796 // %r3 = A2_tfrsi 0;
797 // S2_storeri_io killed %r0, 0, killed %r2, implicit killed %d1;
798 for (auto &MO : MI.operands()) {
799 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == DepReg)
800 return false;
801 }
802
803 // Can be dot new store.
804 return true;
805}
806
807// Can this MI to promoted to either new value store or new value jump.
809 const SUnit *PacketSU, unsigned DepReg,
811 if (!HII->mayBeNewStore(MI))
812 return false;
813
814 // Check to see the store can be new value'ed.
815 MachineInstr &PacketMI = *PacketSU->getInstr();
816 if (canPromoteToNewValueStore(MI, PacketMI, DepReg))
817 return true;
818
819 // Check to see the compare/jump can be new value'ed.
820 // This is done as a pass on its own. Don't need to check it here.
821 return false;
822}
823
824static bool isImplicitDependency(const MachineInstr &I, bool CheckDef,
825 unsigned DepReg) {
826 for (auto &MO : I.operands()) {
827 if (CheckDef && MO.isRegMask() && MO.clobbersPhysReg(DepReg))
828 return true;
829 if (!MO.isReg() || MO.getReg() != DepReg || !MO.isImplicit())
830 continue;
831 if (CheckDef == MO.isDef())
832 return true;
833 }
834 return false;
835}
836
837// Check to see if an instruction can be dot new.
839 const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII,
840 const TargetRegisterClass* RC) {
841 // Already a dot new instruction.
842 if (HII->isDotNewInst(MI) && !HII->mayBeNewStore(MI))
843 return false;
844
845 if (!isNewifiable(MI, RC))
846 return false;
847
848 const MachineInstr &PI = *PacketSU->getInstr();
849
850 // The "new value" cannot come from inline asm.
851 if (PI.isInlineAsm())
852 return false;
853
854 // IMPLICIT_DEFs won't materialize as real instructions, so .new makes no
855 // sense.
856 if (PI.isImplicitDef())
857 return false;
858
859 // If dependency is through an implicitly defined register, we should not
860 // newify the use.
861 if (isImplicitDependency(PI, true, DepReg) ||
862 isImplicitDependency(MI, false, DepReg))
863 return false;
864
865 const MCInstrDesc& MCID = PI.getDesc();
866 const TargetRegisterClass *VecRC = HII->getRegClass(MCID, 0);
867 if (DisableVecDblNVStores && VecRC == &Hexagon::HvxWRRegClass)
868 return false;
869
870 // predicate .new
871 if (RC == &Hexagon::PredRegsRegClass)
872 return HII->predCanBeUsedAsDotNew(PI, DepReg);
873
874 if (RC != &Hexagon::PredRegsRegClass && !HII->mayBeNewStore(MI))
875 return false;
876
877 // Create a dot new machine instruction to see if resources can be
878 // allocated. If not, bail out now.
879 int NewOpcode = (RC != &Hexagon::PredRegsRegClass) ? HII->getDotNewOp(MI) :
880 HII->getDotNewPredOp(MI, MBPI);
881 const MCInstrDesc &D = HII->get(NewOpcode);
882 MachineInstr *NewMI = MF.CreateMachineInstr(D, DebugLoc());
883 bool ResourcesAvailable = ResourceTracker->canReserveResources(*NewMI);
884 MF.deleteMachineInstr(NewMI);
885 if (!ResourcesAvailable)
886 return false;
887
888 // New Value Store only. New Value Jump generated as a separate pass.
889 if (!canPromoteToNewValue(MI, PacketSU, DepReg, MII))
890 return false;
891
892 return true;
893}
894
895// Go through the packet instructions and search for an anti dependency between
896// them and DepReg from MI. Consider this case:
897// Trying to add
898// a) %r1 = TFRI_cdNotPt %p3, 2
899// to this packet:
900// {
901// b) %p0 = C2_or killed %p3, killed %p0
902// c) %p3 = C2_tfrrp %r23
903// d) %r1 = C2_cmovenewit %p3, 4
904// }
905// The P3 from a) and d) will be complements after
906// a)'s P3 is converted to .new form
907// Anti-dep between c) and b) is irrelevant for this case
909 unsigned DepReg) {
910 SUnit *PacketSUDep = MIToSUnit.find(&MI)->second;
911
912 for (auto *I : CurrentPacketMIs) {
913 // We only care for dependencies to predicated instructions
914 if (!HII->isPredicated(*I))
915 continue;
916
917 // Scheduling Unit for current insn in the packet
918 SUnit *PacketSU = MIToSUnit.find(I)->second;
919
920 // Look at dependencies between current members of the packet and
921 // predicate defining instruction MI. Make sure that dependency is
922 // on the exact register we care about.
923 if (PacketSU->isSucc(PacketSUDep)) {
924 for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) {
925 auto &Dep = PacketSU->Succs[i];
926 if (Dep.getSUnit() == PacketSUDep && Dep.getKind() == SDep::Anti &&
927 Dep.getReg() == DepReg)
928 return true;
929 }
930 }
931 }
932
933 return false;
934}
935
936/// Gets the predicate register of a predicated instruction.
938 const HexagonInstrInfo *QII) {
939 /// We use the following rule: The first predicate register that is a use is
940 /// the predicate register of a predicated instruction.
941 assert(QII->isPredicated(MI) && "Must be predicated instruction");
942
943 for (auto &Op : MI.operands()) {
944 if (Op.isReg() && Op.getReg() && Op.isUse() &&
945 Hexagon::PredRegsRegClass.contains(Op.getReg()))
946 return Op.getReg();
947 }
948
949 llvm_unreachable("Unknown instruction operand layout");
950 return 0;
951}
952
953// Given two predicated instructions, this function detects whether
954// the predicates are complements.
956 MachineInstr &MI2) {
957 // If we don't know the predicate sense of the instructions bail out early, we
958 // need it later.
959 if (getPredicateSense(MI1, HII) == PK_Unknown ||
960 getPredicateSense(MI2, HII) == PK_Unknown)
961 return false;
962
963 // Scheduling unit for candidate.
964 SUnit *SU = MIToSUnit[&MI1];
965
966 // One corner case deals with the following scenario:
967 // Trying to add
968 // a) %r24 = A2_tfrt %p0, %r25
969 // to this packet:
970 // {
971 // b) %r25 = A2_tfrf %p0, %r24
972 // c) %p0 = C2_cmpeqi %r26, 1
973 // }
974 //
975 // On general check a) and b) are complements, but presence of c) will
976 // convert a) to .new form, and then it is not a complement.
977 // We attempt to detect it by analyzing existing dependencies in the packet.
978
979 // Analyze relationships between all existing members of the packet.
980 // Look for Anti dependency on the same predicate reg as used in the
981 // candidate.
982 for (auto *I : CurrentPacketMIs) {
983 // Scheduling Unit for current insn in the packet.
984 SUnit *PacketSU = MIToSUnit.find(I)->second;
985
986 // If this instruction in the packet is succeeded by the candidate...
987 if (PacketSU->isSucc(SU)) {
988 for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) {
989 auto Dep = PacketSU->Succs[i];
990 // The corner case exist when there is true data dependency between
991 // candidate and one of current packet members, this dep is on
992 // predicate reg, and there already exist anti dep on the same pred in
993 // the packet.
994 if (Dep.getSUnit() == SU && Dep.getKind() == SDep::Data &&
995 Hexagon::PredRegsRegClass.contains(Dep.getReg())) {
996 // Here I know that I is predicate setting instruction with true
997 // data dep to candidate on the register we care about - c) in the
998 // above example. Now I need to see if there is an anti dependency
999 // from c) to any other instruction in the same packet on the pred
1000 // reg of interest.
1001 if (restrictingDepExistInPacket(*I, Dep.getReg()))
1002 return false;
1003 }
1004 }
1005 }
1006 }
1007
1008 // If the above case does not apply, check regular complement condition.
1009 // Check that the predicate register is the same and that the predicate
1010 // sense is different We also need to differentiate .old vs. .new: !p0
1011 // is not complementary to p0.new.
1012 unsigned PReg1 = getPredicatedRegister(MI1, HII);
1013 unsigned PReg2 = getPredicatedRegister(MI2, HII);
1014 return PReg1 == PReg2 &&
1015 Hexagon::PredRegsRegClass.contains(PReg1) &&
1016 Hexagon::PredRegsRegClass.contains(PReg2) &&
1017 getPredicateSense(MI1, HII) != getPredicateSense(MI2, HII) &&
1018 HII->isDotNewInst(MI1) == HII->isDotNewInst(MI2);
1019}
1020
1021// Initialize packetizer flags.
1023 Dependence = false;
1024 PromotedToDotNew = false;
1025 GlueToNewValueJump = false;
1026 GlueAllocframeStore = false;
1027 FoundSequentialDependence = false;
1028 ChangedOffset = INT64_MAX;
1029}
1030
1031// Ignore bundling of pseudo instructions.
1033 const MachineBasicBlock *) {
1034 if (MI.isDebugInstr())
1035 return true;
1036
1037 if (MI.isCFIInstruction())
1038 return false;
1039
1040 // We must print out inline assembly.
1041 if (MI.isInlineAsm())
1042 return false;
1043
1044 if (MI.isImplicitDef())
1045 return false;
1046
1047 // We check if MI has any functional units mapped to it. If it doesn't,
1048 // we ignore the instruction.
1049 const MCInstrDesc& TID = MI.getDesc();
1050 auto *IS = ResourceTracker->getInstrItins()->beginStage(TID.getSchedClass());
1051 return !IS->getUnits();
1052}
1053
1055 // Ensure any bundles created by gather packetize remain separate.
1056 if (MI.isBundle())
1057 return true;
1058
1059 if (MI.isEHLabel() || MI.isCFIInstruction())
1060 return true;
1061
1062 // Consider inline asm to not be a solo instruction by default.
1063 // Inline asm will be put in a packet temporarily, but then it will be
1064 // removed, and placed outside of the packet (before or after, depending
1065 // on dependencies). This is to reduce the impact of inline asm as a
1066 // "packet splitting" instruction.
1067 if (MI.isInlineAsm() && !ScheduleInlineAsm)
1068 return true;
1069
1070 if (isSchedBarrier(MI))
1071 return true;
1072
1073 if (HII->isSolo(MI))
1074 return true;
1075
1076 if (MI.getOpcode() == Hexagon::PATCHABLE_FUNCTION_ENTER ||
1077 MI.getOpcode() == Hexagon::PATCHABLE_FUNCTION_EXIT ||
1078 MI.getOpcode() == Hexagon::PATCHABLE_TAIL_CALL ||
1079 MI.getOpcode() == Hexagon::PATCHABLE_EVENT_CALL ||
1080 MI.getOpcode() == Hexagon::PATCHABLE_TYPED_EVENT_CALL)
1081 return true;
1082
1083 if (MI.getOpcode() == Hexagon::A2_nop)
1084 return true;
1085
1086 return false;
1087}
1088
1089// Quick check if instructions MI and MJ cannot coexist in the same packet.
1090// Limit the tests to be "one-way", e.g. "if MI->isBranch and MJ->isInlineAsm",
1091// but not the symmetric case: "if MJ->isBranch and MI->isInlineAsm".
1092// For full test call this function twice:
1093// cannotCoexistAsymm(MI, MJ) || cannotCoexistAsymm(MJ, MI)
1094// Doing the test only one way saves the amount of code in this function,
1095// since every test would need to be repeated with the MI and MJ reversed.
1096static bool cannotCoexistAsymm(const MachineInstr &MI, const MachineInstr &MJ,
1097 const HexagonInstrInfo &HII) {
1098 const MachineFunction *MF = MI.getParent()->getParent();
1100 HII.isHVXMemWithAIndirect(MI, MJ))
1101 return true;
1102
1103 // Don't allow a store and an instruction that must be in slot0 and
1104 // doesn't allow a slot1 instruction.
1105 if (MI.mayStore() && HII.isRestrictNoSlot1Store(MJ) && HII.isPureSlot0(MJ))
1106 return true;
1107
1108 // An inline asm cannot be together with a branch, because we may not be
1109 // able to remove the asm out after packetizing (i.e. if the asm must be
1110 // moved past the bundle). Similarly, two asms cannot be together to avoid
1111 // complications when determining their relative order outside of a bundle.
1112 if (MI.isInlineAsm())
1113 return MJ.isInlineAsm() || MJ.isBranch() || MJ.isBarrier() ||
1114 MJ.isCall() || MJ.isTerminator();
1115
1116 // New-value stores cannot coexist with any other stores.
1117 if (HII.isNewValueStore(MI) && MJ.mayStore())
1118 return true;
1119
1120 // An HLX instruction with a 64-bit scalar source cannot be paired with
1121 // another HLX instruction using a scalar or immediate source. Loads and
1122 // stores are exempt because they do not use the shared scalar resource.
1123 if (HII.isHLXVec(MI) && HII.isHLXVec(MJ) && !MJ.mayLoad() && !MJ.mayStore()) {
1124 auto getScalarUses = [](const MachineInstr &MI) {
1125 unsigned Uses = 0;
1126 for (const MachineOperand &MO : MI.explicit_uses()) {
1127 if (MO.isImm())
1128 Uses |= 1;
1129 else if (MO.isReg() && Hexagon::IntRegsRegClass.contains(MO.getReg()))
1130 Uses |= 2;
1131 else if (MO.isReg() &&
1132 Hexagon::DoubleRegsRegClass.contains(MO.getReg()))
1133 Uses |= 4;
1134 }
1135 return Uses;
1136 };
1137
1138 if ((getScalarUses(MI) & 4) && getScalarUses(MJ))
1139 return true;
1140 }
1141
1142 switch (MI.getOpcode()) {
1143 case Hexagon::S2_storew_locked:
1144 case Hexagon::S4_stored_locked:
1145 case Hexagon::L2_loadw_locked:
1146 case Hexagon::L4_loadd_locked:
1147 case Hexagon::Y2_dccleana:
1148 case Hexagon::Y2_dccleaninva:
1149 case Hexagon::Y2_dcinva:
1150 case Hexagon::Y2_dczeroa:
1151 case Hexagon::Y4_l2fetch:
1152 case Hexagon::Y5_l2fetch: {
1153 // These instructions can only be grouped with ALU32 or non-floating-point
1154 // XTYPE instructions. Since there is no convenient way of identifying fp
1155 // XTYPE instructions, only allow grouping with ALU32 for now.
1156 unsigned TJ = HII.getType(MJ);
1157 if (TJ != HexagonII::TypeALU32_2op &&
1160 return true;
1161 break;
1162 }
1163 case Hexagon::LX_S16b_pseudo: {
1164 // The store pseudo expands to a copy of the stored register followed by a
1165 // new-value store. Do not packetize it with an instruction defining that
1166 // register, otherwise the packet would have two definitions of it.
1167 Register StReg = MI.getOperand(1).getReg();
1168 const HexagonRegisterInfo &HRI = HII.getRegisterInfo();
1169 if (any_of(MJ.all_defs(), [&](const MachineOperand &Def) {
1170 return HRI.isSuperRegisterEq(StReg, Def.getReg());
1171 }))
1172 return true;
1173 break;
1174 }
1175 default:
1176 break;
1177 }
1178
1179 // "False" really means that the quick check failed to determine if
1180 // I and J cannot coexist.
1181 return false;
1182}
1183
1184// Full, symmetric check.
1186 const MachineInstr &MJ) {
1187 return cannotCoexistAsymm(MI, MJ, *HII) || cannotCoexistAsymm(MJ, MI, *HII);
1188}
1189
1191 for (auto &B : MF) {
1193 for (MachineInstr &MI : llvm::make_early_inc_range(B.instrs())) {
1194 if (MI.isBundle())
1195 BundleIt = MI.getIterator();
1196 if (!MI.isInsideBundle())
1197 continue;
1198
1199 // Decide on where to insert the instruction that we are pulling out.
1200 // Debug instructions always go before the bundle, but the placement of
1201 // INLINE_ASM depends on potential dependencies. By default, try to
1202 // put it before the bundle, but if the asm writes to a register that
1203 // other instructions in the bundle read, then we need to place it
1204 // after the bundle (to preserve the bundle semantics).
1205 bool InsertBeforeBundle;
1206 if (MI.isInlineAsm())
1207 InsertBeforeBundle = !hasWriteToReadDep(MI, *BundleIt, HRI);
1208 else if (MI.isDebugInstr())
1209 InsertBeforeBundle = true;
1210 else
1211 continue;
1212
1213 BundleIt = moveInstrOut(MI, BundleIt, InsertBeforeBundle);
1214 }
1215 }
1216}
1217
1218// Check if a given instruction is of class "system".
1219static bool isSystemInstr(const MachineInstr &MI) {
1220 unsigned Opc = MI.getOpcode();
1221 switch (Opc) {
1222 case Hexagon::Y2_barrier:
1223 case Hexagon::Y2_dcfetchbo:
1224 case Hexagon::Y4_l2fetch:
1225 case Hexagon::Y5_l2fetch:
1226 return true;
1227 }
1228 return false;
1229}
1230
1232 const MachineInstr &J) {
1233 // The dependence graph may not include edges between dead definitions,
1234 // so without extra checks, we could end up packetizing two instruction
1235 // defining the same (dead) register.
1236 if (I.isCall() || J.isCall())
1237 return false;
1238 if (HII->isPredicated(I) || HII->isPredicated(J))
1239 return false;
1240
1241 BitVector DeadDefs(Hexagon::NUM_TARGET_REGS);
1242 for (auto &MO : I.operands()) {
1243 if (!MO.isReg() || !MO.isDef() || !MO.isDead())
1244 continue;
1245 DeadDefs[MO.getReg()] = true;
1246 }
1247
1248 for (auto &MO : J.operands()) {
1249 if (!MO.isReg() || !MO.isDef() || !MO.isDead())
1250 continue;
1251 Register R = MO.getReg();
1252 if (R != Hexagon::USR_OVF && DeadDefs[R])
1253 return true;
1254 }
1255 return false;
1256}
1257
1259 const MachineInstr &J) {
1260 // A save callee-save register function call can only be in a packet
1261 // with instructions that don't write to the callee-save registers.
1262 if ((HII->isSaveCalleeSavedRegsCall(I) &&
1263 doesModifyCalleeSavedReg(J, HRI)) ||
1264 (HII->isSaveCalleeSavedRegsCall(J) &&
1266 return true;
1267
1268 // Two control flow instructions cannot go in the same packet.
1269 if (isControlFlow(I) && isControlFlow(J))
1270 return true;
1271
1272 // \ref-manual (7.3.4) A loop setup packet in loopN or spNloop0 cannot
1273 // contain a speculative indirect jump,
1274 // a new-value compare jump or a dealloc_return.
1275 auto isBadForLoopN = [this] (const MachineInstr &MI) -> bool {
1276 if (MI.isCall() || HII->isDeallocRet(MI) || HII->isNewValueJump(MI))
1277 return true;
1278 if (HII->isPredicated(MI) && HII->isPredicatedNew(MI) && HII->isJumpR(MI))
1279 return true;
1280 return false;
1281 };
1282
1283 if (HII->isLoopN(I) && isBadForLoopN(J))
1284 return true;
1285 if (HII->isLoopN(J) && isBadForLoopN(I))
1286 return true;
1287
1288 // dealloc_return cannot appear in the same packet as a conditional or
1289 // unconditional jump.
1290 return HII->isDeallocRet(I) &&
1291 (J.isBranch() || J.isCall() || J.isBarrier());
1292}
1293
1295 const MachineInstr &J) {
1296 // Adding I to a packet that has J.
1297
1298 // Regmasks are not reflected in the scheduling dependency graph, so
1299 // we need to check them manually. This code assumes that regmasks only
1300 // occur on calls, and the problematic case is when we add an instruction
1301 // defining a register R to a packet that has a call that clobbers R via
1302 // a regmask. Those cannot be packetized together, because the call will
1303 // be executed last. That's also a reason why it is ok to add a call
1304 // clobbering R to a packet that defines R.
1305
1306 // Look for regmasks in J.
1307 for (const MachineOperand &OpJ : J.operands()) {
1308 if (!OpJ.isRegMask())
1309 continue;
1310 assert((J.isCall() || HII->isTailCall(J)) && "Regmask on a non-call");
1311 for (const MachineOperand &OpI : I.operands()) {
1312 if (OpI.isReg()) {
1313 if (OpJ.clobbersPhysReg(OpI.getReg()))
1314 return true;
1315 } else if (OpI.isRegMask()) {
1316 // Both are regmasks. Assume that they intersect.
1317 return true;
1318 }
1319 }
1320 }
1321 return false;
1322}
1323
1325 const MachineInstr &J) {
1326 bool SysI = isSystemInstr(I), SysJ = isSystemInstr(J);
1327 bool StoreI = I.mayStore(), StoreJ = J.mayStore();
1328 if ((SysI && StoreJ) || (SysJ && StoreI))
1329 return true;
1330
1331 if (StoreI && StoreJ) {
1332 if (HII->isNewValueInst(J) || HII->isMemOp(J) || HII->isMemOp(I))
1333 return true;
1334 } else {
1335 // A memop cannot be in the same packet with another memop or a store.
1336 // Two stores can be together, but here I and J cannot both be stores.
1337 bool MopStI = HII->isMemOp(I) || StoreI;
1338 bool MopStJ = HII->isMemOp(J) || StoreJ;
1339 if (MopStI && MopStJ)
1340 return true;
1341 }
1342
1343 return (StoreJ && HII->isDeallocRet(I)) || (StoreI && HII->isDeallocRet(J));
1344}
1345
1346// SUI is the current instruction that is outside of the current packet.
1347// SUJ is the current instruction inside the current packet against which that
1348// SUI will be packetized.
1350 assert(SUI->getInstr() && SUJ->getInstr());
1351 MachineInstr &I = *SUI->getInstr();
1352 MachineInstr &J = *SUJ->getInstr();
1353
1354 // Clear IgnoreDepMIs when Packet starts.
1355 if (CurrentPacketMIs.size() == 1)
1356 IgnoreDepMIs.clear();
1357
1358 MachineBasicBlock::iterator II = I.getIterator();
1359
1360 // Solo instructions cannot go in the packet.
1361 assert(!isSoloInstruction(I) && "Unexpected solo instr!");
1362
1363 if (cannotCoexist(I, J))
1364 return false;
1365
1366 Dependence = hasDeadDependence(I, J) || hasControlDependence(I, J);
1367 if (Dependence)
1368 return false;
1369
1370 // Regmasks are not accounted for in the scheduling graph, so we need
1371 // to explicitly check for dependencies caused by them. They should only
1372 // appear on calls, so it's not too pessimistic to reject all regmask
1373 // dependencies.
1374 Dependence = hasRegMaskDependence(I, J);
1375 if (Dependence)
1376 return false;
1377
1378 // Dual-store does not allow second store, if the first store is not
1379 // in SLOT0. New value store, new value jump, dealloc_return and memop
1380 // always take SLOT0. Arch spec 3.4.4.2.
1381 Dependence = hasDualStoreDependence(I, J);
1382 if (Dependence)
1383 return false;
1384
1385 // If an instruction feeds new value jump, glue it.
1386 MachineBasicBlock::iterator NextMII = I.getIterator();
1387 ++NextMII;
1388 if (NextMII != I.getParent()->end() && HII->isNewValueJump(*NextMII)) {
1389 MachineInstr &NextMI = *NextMII;
1390
1391 bool secondRegMatch = false;
1392 const MachineOperand &NOp0 = NextMI.getOperand(0);
1393 const MachineOperand &NOp1 = NextMI.getOperand(1);
1394
1395 if (NOp1.isReg() && I.getOperand(0).getReg() == NOp1.getReg())
1396 secondRegMatch = true;
1397
1398 for (MachineInstr *PI : CurrentPacketMIs) {
1399 // NVJ can not be part of the dual jump - Arch Spec: section 7.8.
1400 if (PI->isCall()) {
1401 Dependence = true;
1402 break;
1403 }
1404 // Validate:
1405 // 1. Packet does not have a store in it.
1406 // 2. If the first operand of the nvj is newified, and the second
1407 // operand is also a reg, it (second reg) is not defined in
1408 // the same packet.
1409 // 3. If the second operand of the nvj is newified, (which means
1410 // first operand is also a reg), first reg is not defined in
1411 // the same packet.
1412 if (PI->getOpcode() == Hexagon::S2_allocframe || PI->mayStore() ||
1413 HII->isLoopN(*PI)) {
1414 Dependence = true;
1415 break;
1416 }
1417 // Check #2/#3.
1418 const MachineOperand &OpR = secondRegMatch ? NOp0 : NOp1;
1419 if (OpR.isReg() && PI->modifiesRegister(OpR.getReg(), HRI)) {
1420 Dependence = true;
1421 break;
1422 }
1423 }
1424
1425 GlueToNewValueJump = true;
1426 if (Dependence)
1427 return false;
1428 }
1429
1430 // There no dependency between a prolog instruction and its successor.
1431 if (!SUJ->isSucc(SUI))
1432 return true;
1433
1434 for (unsigned i = 0; i < SUJ->Succs.size(); ++i) {
1435 if (FoundSequentialDependence)
1436 break;
1437
1438 if (SUJ->Succs[i].getSUnit() != SUI)
1439 continue;
1440
1441 SDep::Kind DepType = SUJ->Succs[i].getKind();
1442 // For direct calls:
1443 // Ignore register dependences for call instructions for packetization
1444 // purposes except for those due to r31 and predicate registers.
1445 //
1446 // For indirect calls:
1447 // Same as direct calls + check for true dependences to the register
1448 // used in the indirect call.
1449 //
1450 // We completely ignore Order dependences for call instructions.
1451 //
1452 // For returns:
1453 // Ignore register dependences for return instructions like jumpr,
1454 // dealloc return unless we have dependencies on the explicit uses
1455 // of the registers used by jumpr (like r31) or dealloc return
1456 // (like r29 or r30).
1457 unsigned DepReg = 0;
1458 const TargetRegisterClass *RC = nullptr;
1459 if (DepType == SDep::Data) {
1460 DepReg = SUJ->Succs[i].getReg();
1461 RC = HRI->getMinimalPhysRegClass(DepReg);
1462 }
1463
1464 if (I.isCall() || HII->isJumpR(I) || I.isReturn() || HII->isTailCall(I)) {
1465 if (!isRegDependence(DepType))
1466 continue;
1467 if (!isCallDependent(I, DepType, SUJ->Succs[i].getReg()))
1468 continue;
1469 }
1470
1471 if (DepType == SDep::Data) {
1472 if (canPromoteToDotCur(J, SUJ, DepReg, II, RC))
1473 if (promoteToDotCur(J, DepType, II, RC))
1474 continue;
1475 }
1476
1477 // Data dependence ok if we have load.cur.
1478 if (DepType == SDep::Data && HII->isDotCurInst(J)) {
1479 if (HII->isHVXVec(I))
1480 continue;
1481 }
1482
1483 // For instructions that can be promoted to dot-new, try to promote.
1484 if (DepType == SDep::Data) {
1485 if (canPromoteToDotNew(I, SUJ, DepReg, II, RC)) {
1486 if (promoteToDotNew(I, DepType, II, RC)) {
1487 PromotedToDotNew = true;
1488 if (cannotCoexist(I, J))
1489 FoundSequentialDependence = true;
1490 continue;
1491 }
1492 }
1493 if (HII->isNewValueJump(I))
1494 continue;
1495 }
1496
1497 // For predicated instructions, if the predicates are complements then
1498 // there can be no dependence.
1499 if (HII->isPredicated(I) && HII->isPredicated(J) &&
1501 // Not always safe to do this translation.
1502 // DAG Builder attempts to reduce dependence edges using transitive
1503 // nature of dependencies. Here is an example:
1504 //
1505 // r0 = tfr_pt ... (1)
1506 // r0 = tfr_pf ... (2)
1507 // r0 = tfr_pt ... (3)
1508 //
1509 // There will be an output dependence between (1)->(2) and (2)->(3).
1510 // However, there is no dependence edge between (1)->(3). This results
1511 // in all 3 instructions going in the same packet. We ignore dependce
1512 // only once to avoid this situation.
1513 auto Itr = find(IgnoreDepMIs, &J);
1514 if (Itr != IgnoreDepMIs.end()) {
1515 Dependence = true;
1516 return false;
1517 }
1518 IgnoreDepMIs.push_back(&I);
1519 continue;
1520 }
1521
1522 // Ignore Order dependences between unconditional direct branches
1523 // and non-control-flow instructions.
1524 if (isDirectJump(I) && !J.isBranch() && !J.isCall() &&
1525 DepType == SDep::Order)
1526 continue;
1527
1528 // Ignore all dependences for jumps except for true and output
1529 // dependences.
1530 if (I.isConditionalBranch() && DepType != SDep::Data &&
1531 DepType != SDep::Output)
1532 continue;
1533
1534 if (DepType == SDep::Output) {
1535 FoundSequentialDependence = true;
1536 break;
1537 }
1538
1539 // For Order dependences:
1540 // 1. Volatile loads/stores can be packetized together, unless other
1541 // rules prevent is.
1542 // 2. Store followed by a load is not allowed.
1543 // 3. Store followed by a store is valid.
1544 // 4. Load followed by any memory operation is allowed.
1545 if (DepType == SDep::Order) {
1546 if (!PacketizeVolatiles) {
1547 bool OrdRefs = I.hasOrderedMemoryRef() || J.hasOrderedMemoryRef();
1548 if (OrdRefs) {
1549 FoundSequentialDependence = true;
1550 break;
1551 }
1552 }
1553 // J is first, I is second.
1554 bool LoadJ = J.mayLoad(), StoreJ = J.mayStore();
1555 bool LoadI = I.mayLoad(), StoreI = I.mayStore();
1556 bool NVStoreJ = HII->isNewValueStore(J);
1557 bool NVStoreI = HII->isNewValueStore(I);
1558 bool IsVecJ = HII->isHVXVec(J) || HII->isHLXVec(J);
1559 bool IsVecI = HII->isHVXVec(I) || HII->isHLXVec(I);
1560
1561 // Don't reorder the loads if there is an order dependence. This would
1562 // occur if the first instruction must go in slot0.
1563 if (LoadJ && LoadI && HII->isPureSlot0(J)) {
1564 FoundSequentialDependence = true;
1565 break;
1566 }
1567
1568 if (Slot1Store && MF.getSubtarget<HexagonSubtarget>().hasV65Ops() &&
1569 ((LoadJ && StoreI && !NVStoreI) ||
1570 (StoreJ && LoadI && !NVStoreJ)) &&
1571 (J.getOpcode() != Hexagon::S2_allocframe &&
1572 I.getOpcode() != Hexagon::S2_allocframe) &&
1573 (J.getOpcode() != Hexagon::L2_deallocframe &&
1574 I.getOpcode() != Hexagon::L2_deallocframe) &&
1575 (!HII->isMemOp(J) && !HII->isMemOp(I)) && (!IsVecJ && !IsVecI))
1576 setmemShufDisabled(true);
1577 else
1578 if (StoreJ && LoadI && alias(J, I)) {
1579 FoundSequentialDependence = true;
1580 break;
1581 }
1582
1583 if (!StoreJ)
1584 if (!LoadJ || (!LoadI && !StoreI)) {
1585 // If J is neither load nor store, assume a dependency.
1586 // If J is a load, but I is neither, also assume a dependency.
1587 FoundSequentialDependence = true;
1588 break;
1589 }
1590 // Store followed by store: not OK on V2.
1591 // Store followed by load: not OK on all.
1592 // Load followed by store: OK on all.
1593 // Load followed by load: OK on all.
1594 continue;
1595 }
1596
1597 // Special case for ALLOCFRAME: even though there is dependency
1598 // between ALLOCFRAME and subsequent store, allow it to be packetized
1599 // in a same packet. This implies that the store is using the caller's
1600 // SP. Hence, offset needs to be updated accordingly.
1601 if (DepType == SDep::Data && J.getOpcode() == Hexagon::S2_allocframe) {
1602 unsigned Opc = I.getOpcode();
1603 switch (Opc) {
1604 case Hexagon::S2_storerd_io:
1605 case Hexagon::S2_storeri_io:
1606 case Hexagon::S2_storerh_io:
1607 case Hexagon::S2_storerb_io:
1608 if (I.getOperand(0).getReg() == HRI->getStackRegister()) {
1609 // Since this store is to be glued with allocframe in the same
1610 // packet, it will use SP of the previous stack frame, i.e.
1611 // caller's SP. Therefore, we need to recalculate offset
1612 // according to this change.
1613 GlueAllocframeStore = useCallersSP(I);
1614 if (GlueAllocframeStore)
1615 continue;
1616 }
1617 break;
1618 default:
1619 break;
1620 }
1621 }
1622
1623 // There are certain anti-dependencies that cannot be ignored.
1624 // Specifically:
1625 // J2_call ... implicit-def %r0 ; SUJ
1626 // R0 = ... ; SUI
1627 // Those cannot be packetized together, since the call will observe
1628 // the effect of the assignment to R0.
1629 if ((DepType == SDep::Anti || DepType == SDep::Output) && J.isCall()) {
1630 // Check if I defines any volatile register. We should also check
1631 // registers that the call may read, but these happen to be a
1632 // subset of the volatile register set.
1633 for (const MachineOperand &Op : I.operands()) {
1634 if (Op.isReg() && Op.isDef()) {
1635 Register R = Op.getReg();
1636 if (!J.readsRegister(R, HRI) && !J.modifiesRegister(R, HRI))
1637 continue;
1638 } else if (!Op.isRegMask()) {
1639 // If I has a regmask assume dependency.
1640 continue;
1641 }
1642 FoundSequentialDependence = true;
1643 break;
1644 }
1645 }
1646
1647 // Skip over remaining anti-dependences. Two instructions that are
1648 // anti-dependent can share a packet, since in most such cases all
1649 // operands are read before any modifications take place.
1650 // The exceptions are branch and call instructions, since they are
1651 // executed after all other instructions have completed (at least
1652 // conceptually).
1653 // Another exception is the HLX load pseudo, which expands to a temporary
1654 // load and a copy of the loaded value. An instruction it is anti-dependent
1655 // on would read the new value if both were in the same packet.
1656 if (DepType != SDep::Anti || I.getOpcode() == Hexagon::LX_L16b_pseudo) {
1657 FoundSequentialDependence = true;
1658 break;
1659 }
1660 }
1661
1662 if (FoundSequentialDependence) {
1663 Dependence = true;
1664 return false;
1665 }
1666
1667 return true;
1668}
1669
1671 assert(SUI->getInstr() && SUJ->getInstr());
1672 MachineInstr &I = *SUI->getInstr();
1673 MachineInstr &J = *SUJ->getInstr();
1674
1675 bool Coexist = !cannotCoexist(I, J);
1676
1677 if (Coexist && !Dependence)
1678 return true;
1679
1680 // Check if the instruction was promoted to a dot-new. If so, demote it
1681 // back into a dot-old.
1682 if (PromotedToDotNew)
1684
1685 cleanUpDotCur();
1686 // Check if the instruction (must be a store) was glued with an allocframe
1687 // instruction. If so, restore its offset to its original value, i.e. use
1688 // current SP instead of caller's SP.
1689 if (GlueAllocframeStore) {
1690 useCalleesSP(I);
1691 GlueAllocframeStore = false;
1692 }
1693
1694 if (ChangedOffset != INT64_MAX)
1696
1697 if (GlueToNewValueJump) {
1698 // Putting I and J together would prevent the new-value jump from being
1699 // packetized with the producer. In that case I and J must be separated.
1700 GlueToNewValueJump = false;
1701 return false;
1702 }
1703
1704 if (!Coexist)
1705 return false;
1706
1707 if (ChangedOffset == INT64_MAX && updateOffset(SUI, SUJ)) {
1708 FoundSequentialDependence = false;
1709 Dependence = false;
1710 return true;
1711 }
1712
1713 return false;
1714}
1715
1716
1718 bool FoundLoad = false;
1719 bool FoundStore = false;
1720
1721 for (auto *MJ : CurrentPacketMIs) {
1722 unsigned Opc = MJ->getOpcode();
1723 if (Opc == Hexagon::S2_allocframe || Opc == Hexagon::L2_deallocframe)
1724 continue;
1725 if (HII->isMemOp(*MJ))
1726 continue;
1727 if (MJ->mayLoad())
1728 FoundLoad = true;
1729 if (MJ->mayStore() && !HII->isNewValueStore(*MJ))
1730 FoundStore = true;
1731 }
1732 return FoundLoad && FoundStore;
1733}
1734
1735
1738 MachineBasicBlock::iterator MII = MI.getIterator();
1739 MachineBasicBlock *MBB = MI.getParent();
1740
1741 if (CurrentPacketMIs.empty()) {
1742 PacketStalls = false;
1743 PacketStallCycles = 0;
1744 }
1745 PacketStalls |= producesStall(MI);
1746 PacketStallCycles = std::max(PacketStallCycles, calcStall(MI));
1747
1748 if (MI.isImplicitDef()) {
1749 // Add to the packet to allow subsequent instructions to be checked
1750 // properly.
1751 CurrentPacketMIs.push_back(&MI);
1752 return MII;
1753 }
1754 assert(ResourceTracker->canReserveResources(MI));
1755
1756 bool ExtMI = HII->isExtended(MI) || HII->isConstExtended(MI);
1757 bool Good = true;
1758
1759 if (GlueToNewValueJump) {
1760 MachineInstr &NvjMI = *++MII;
1761 // We need to put both instructions in the same packet: MI and NvjMI.
1762 // Either of them can require a constant extender. Try to add both to
1763 // the current packet, and if that fails, end the packet and start a
1764 // new one.
1765 ResourceTracker->reserveResources(MI);
1766 if (ExtMI)
1768
1769 bool ExtNvjMI = HII->isExtended(NvjMI) || HII->isConstExtended(NvjMI);
1770 if (Good) {
1771 if (ResourceTracker->canReserveResources(NvjMI))
1772 ResourceTracker->reserveResources(NvjMI);
1773 else
1774 Good = false;
1775 }
1776 if (Good && ExtNvjMI)
1778
1779 if (!Good) {
1780 endPacket(MBB, MI);
1781 assert(ResourceTracker->canReserveResources(MI));
1782 ResourceTracker->reserveResources(MI);
1783 if (ExtMI) {
1786 }
1787 assert(ResourceTracker->canReserveResources(NvjMI));
1788 ResourceTracker->reserveResources(NvjMI);
1789 if (ExtNvjMI) {
1792 }
1793 }
1794 CurrentPacketMIs.push_back(&MI);
1795 CurrentPacketMIs.push_back(&NvjMI);
1796 return MII;
1797 }
1798
1799 ResourceTracker->reserveResources(MI);
1800 if (ExtMI && !tryAllocateResourcesForConstExt(true)) {
1801 endPacket(MBB, MI);
1802 if (PromotedToDotNew)
1804 if (GlueAllocframeStore) {
1806 GlueAllocframeStore = false;
1807 }
1808 ResourceTracker->reserveResources(MI);
1810 }
1811
1812 CurrentPacketMIs.push_back(&MI);
1813 return MII;
1814}
1815
1818 // Replace VLIWPacketizerList::endPacket(MBB, EndMI).
1819 LLVM_DEBUG({
1820 if (!CurrentPacketMIs.empty()) {
1821 dbgs() << "Finalizing packet:\n";
1822 unsigned Idx = 0;
1824 unsigned R = ResourceTracker->getUsedResources(Idx++);
1825 dbgs() << " * [res:0x" << utohexstr(R) << "] " << *MI;
1826 }
1827 }
1828 });
1829
1830 bool memShufDisabled = getmemShufDisabled();
1831 if (memShufDisabled && !foundLSInPacket()) {
1832 setmemShufDisabled(false);
1833 LLVM_DEBUG(dbgs() << " Not added to NoShufPacket\n");
1834 }
1835 memShufDisabled = getmemShufDisabled();
1836
1837 OldPacketMIs.clear();
1839 MachineBasicBlock::instr_iterator NextMI = std::next(MI->getIterator());
1840 for (auto &I : make_range(HII->expandVGatherPseudo(*MI), NextMI))
1841 OldPacketMIs.push_back(&I);
1842 }
1843 CurrentPacketMIs.clear();
1844
1845 if (OldPacketMIs.size() > 1) {
1846 MachineBasicBlock::instr_iterator FirstMI(OldPacketMIs.front());
1848 finalizeBundle(*MBB, FirstMI, LastMI);
1849 auto BundleMII = std::prev(FirstMI);
1850 if (memShufDisabled)
1851 HII->setBundleNoShuf(BundleMII);
1852
1853 setmemShufDisabled(false);
1854 }
1855
1856 PacketHasDuplex = false;
1857 PacketHasSLOT0OnlyInsn = false;
1858 ResourceTracker->clearResources();
1859 LLVM_DEBUG(dbgs() << "End packet\n");
1860}
1861
1863 if (Minimal)
1864 return false;
1865
1866 if (producesStall(MI))
1867 return false;
1868
1869 // If TinyCore with Duplexes is enabled, check if this MI can form a Duplex
1870 // with any other instruction in the existing packet.
1871 auto &HST = MI.getParent()->getParent()->getSubtarget<HexagonSubtarget>();
1872 // Constraint 1: Only one duplex allowed per packet.
1873 // Constraint 2: Consider duplex checks only if there is at least one
1874 // instruction in a packet.
1875 // Constraint 3: If one of the existing instructions in the packet has a
1876 // SLOT0 only instruction that can not be duplexed, do not attempt to form
1877 // duplexes. (TODO: This will invalidate the L4_return* instructions to form a
1878 // duplex)
1879 if (HST.isTinyCoreWithDuplex() && CurrentPacketMIs.size() > 0 &&
1880 !PacketHasDuplex) {
1881 // Check for SLOT0 only non-duplexable instruction in packet.
1882 for (auto &MJ : CurrentPacketMIs)
1883 PacketHasSLOT0OnlyInsn |= HII->isPureSlot0(*MJ);
1884 // Get the Big Core Opcode (dup_*).
1885 int Opcode = HII->getDuplexOpcode(MI, false);
1886 if (Opcode >= 0) {
1887 // We now have an instruction that can be duplexed.
1888 for (auto &MJ : CurrentPacketMIs) {
1889 if (HII->isDuplexPair(MI, *MJ) && !PacketHasSLOT0OnlyInsn) {
1890 PacketHasDuplex = true;
1891 return true;
1892 }
1893 }
1894 // If it can not be duplexed, check if there is a valid transition in DFA
1895 // with the original opcode.
1896 MachineInstr &MIRef = const_cast<MachineInstr &>(MI);
1897 MIRef.setDesc(HII->get(Opcode));
1898 return ResourceTracker->canReserveResources(MIRef);
1899 }
1900 }
1901
1902 // An HLX load/store pseudo expands to two instructions in its packet. With
1903 // one more instruction in the packet, there is no room left for a
1904 // constant-extended instruction and its extender within the four-word
1905 // packet limit.
1906 if (HST.useHLXOps() && CurrentPacketMIs.size() > 1) {
1907 auto IsHLXLdStPseudo = [this](const MachineInstr &I) {
1908 return HII->isTmpLoadPseudo(I) || HII->isNewStorePseudo(I);
1909 };
1910 bool HasConstExt = HII->isConstExtended(MI);
1911 bool HasPseudo = IsHLXLdStPseudo(MI);
1912 for (const MachineInstr *MJ : CurrentPacketMIs) {
1913 HasConstExt |= HII->isConstExtended(*MJ);
1914 HasPseudo |= IsHLXLdStPseudo(*MJ);
1915 }
1916 if (HasConstExt && HasPseudo)
1917 return false;
1918 }
1919
1920 return true;
1921}
1922
1923// V60 forward scheduling.
1925 // Check whether the previous packet is in a different loop. If this is the
1926 // case, there is little point in trying to avoid a stall because that would
1927 // favor the rare case (loop entry) over the common case (loop iteration).
1928 //
1929 // TODO: We should really be able to check all the incoming edges if this is
1930 // the first packet in a basic block, so we can avoid stalls from the loop
1931 // backedge.
1932 if (!OldPacketMIs.empty()) {
1933 auto *OldBB = OldPacketMIs.front()->getParent();
1934 auto *ThisBB = I.getParent();
1935 if (MLI->getLoopFor(OldBB) != MLI->getLoopFor(ThisBB))
1936 return 0;
1937 }
1938
1939 SUnit *SUI = MIToSUnit[const_cast<MachineInstr *>(&I)];
1940 if (!SUI)
1941 return 0;
1942
1943 // If the latency is 0 and there is a data dependence between this
1944 // instruction and any instruction in the current packet, we disregard any
1945 // potential stalls due to the instructions in the previous packet. Most of
1946 // the instruction pairs that can go together in the same packet have 0
1947 // latency between them. The exceptions are
1948 // 1. NewValueJumps as they're generated much later and the latencies can't
1949 // be changed at that point.
1950 // 2. .cur instructions, if its consumer has a 0 latency successor (such as
1951 // .new). In this case, the latency between .cur and the consumer stays
1952 // non-zero even though we can have both .cur and .new in the same packet.
1953 // Changing the latency to 0 is not an option as it causes software pipeliner
1954 // to not pipeline in some cases.
1955
1956 // For Example:
1957 // {
1958 // I1: v6.cur = vmem(r0++#1)
1959 // I2: v7 = valign(v6,v4,r2)
1960 // I3: vmem(r5++#1) = v7.new
1961 // }
1962 // Here I2 and I3 has 0 cycle latency, but I1 and I2 has 2.
1963
1964 for (auto *J : CurrentPacketMIs) {
1965 SUnit *SUJ = MIToSUnit[J];
1966 for (auto &Pred : SUI->Preds)
1967 if (Pred.getSUnit() == SUJ)
1968 if ((Pred.getLatency() == 0 && Pred.isAssignedRegDep()) ||
1969 HII->isNewValueJump(I) || HII->isToBeScheduledASAP(*J, I))
1970 return 0;
1971 }
1972
1973 // Check if the latency is greater than one between this instruction and any
1974 // instruction in the previous packet.
1975 for (auto *J : OldPacketMIs) {
1976 SUnit *SUJ = MIToSUnit[J];
1977 for (auto &Pred : SUI->Preds)
1978 if (Pred.getSUnit() == SUJ && Pred.getLatency() > 1)
1979 return Pred.getLatency();
1980 }
1981
1982 return 0;
1983}
1984
1986 unsigned int Latency = calcStall(I);
1987 if (Latency == 0)
1988 return false;
1989 // Ignore stall unless it stalls more than previous instruction in packet
1990 if (PacketStalls)
1991 return Latency > PacketStallCycles;
1992 return true;
1993}
1994
1995//===----------------------------------------------------------------------===//
1996// Public Constructor Functions
1997//===----------------------------------------------------------------------===//
1998
2000 return new HexagonPacketizer(Minimal);
2001}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock & MBB
This file implements the BitVector class.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
cl::opt< bool > ScheduleInlineAsm("hexagon-sched-inline-asm", cl::Hidden, cl::init(false), cl::desc("Do not consider inline-asm a scheduling/" "packetization boundary."))
#define HEXAGON_LRFP_SIZE
cl::opt< bool > DisablePacketizer
static bool cannotCoexistAsymm(const MachineInstr &MI, const MachineInstr &MJ, const HexagonInstrInfo &HII)
static bool isDirectJump(const MachineInstr &MI)
static MachineBasicBlock::iterator moveInstrOut(MachineInstr &MI, MachineBasicBlock::iterator BundleIt, bool Before)
static bool isRegDependence(const SDep::Kind DepType)
static const MachineOperand & getStoreValueOperand(const MachineInstr &MI)
static cl::opt< bool > EnableGenAllInsnClass("enable-gen-insn", cl::Hidden, cl::desc("Generate all instruction with TC"))
static bool isControlFlow(const MachineInstr &MI)
static cl::opt< bool > DisableVecDblNVStores("disable-vecdbl-nv-stores", cl::Hidden, cl::desc("Disable vector double new-value-stores"))
static PredicateKind getPredicateSense(const MachineInstr &MI, const HexagonInstrInfo *HII)
Returns true if an instruction is predicated on p0 and false if it's predicated on !...
static unsigned getPredicatedRegister(MachineInstr &MI, const HexagonInstrInfo *QII)
Gets the predicate register of a predicated instruction.
cl::opt< bool > DisablePacketizer("disable-packetizer", cl::Hidden, cl::desc("Disable Hexagon packetizer pass"))
static cl::opt< bool > Slot1Store("slot1-store-slot0-load", cl::Hidden, cl::init(true), cl::desc("Allow slot1 store and slot0 load"))
static cl::opt< bool > PacketizeVolatiles("hexagon-packetize-volatiles", cl::Hidden, cl::init(true), cl::desc("Allow non-solo packetization of volatile memory references"))
static bool hasWriteToReadDep(const MachineInstr &FirstI, const MachineInstr &SecondI, const TargetRegisterInfo *TRI)
static bool doesModifyCalleeSavedReg(const MachineInstr &MI, const TargetRegisterInfo *TRI)
Returns true if the instruction modifies a callee-saved register.
static bool isLoadAbsSet(const MachineInstr &MI)
static const MachineOperand & getAbsSetOperand(const MachineInstr &MI)
static const MachineOperand & getPostIncrementOperand(const MachineInstr &MI, const HexagonInstrInfo *HII)
static bool isImplicitDependency(const MachineInstr &I, bool CheckDef, unsigned DepReg)
static bool isSchedBarrier(const MachineInstr &MI)
static bool isSystemInstr(const MachineInstr &MI)
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Packetizer
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
#define OP(OPC)
Definition Instruction.h:46
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool isHLXVec(const MachineInstr &MI) const
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool isHVXMemWithAIndirect(const MachineInstr &I, const MachineInstr &J) const
bool isRestrictNoSlot1Store(const MachineInstr &MI) const
bool isPureSlot0(const MachineInstr &MI) const
const HexagonRegisterInfo & getRegisterInfo() const
bool isPostIncrement(const MachineInstr &MI) const override
Return true for post-incremented instructions.
uint64_t getType(const MachineInstr &MI) const
bool isPredicatedTrue(const MachineInstr &MI) const
bool isNewValueStore(const MachineInstr &MI) const
bool arePredicatesComplements(MachineInstr &MI1, MachineInstr &MI2)
bool updateOffset(SUnit *SUI, SUnit *SUJ)
Return true if we can update the offset in MI so that MI and MJ can be packetized together.
void endPacket(MachineBasicBlock *MBB, MachineBasicBlock::iterator MI) override
HexagonPacketizerList(MachineFunction &MF, MachineLoopInfo &MLI, AAResults *AA, const MachineBranchProbabilityInfo *MBPI, bool Minimal)
bool isCallDependent(const MachineInstr &MI, SDep::Kind DepType, unsigned DepReg)
bool promoteToDotCur(MachineInstr &MI, SDep::Kind DepType, MachineBasicBlock::iterator &MII, const TargetRegisterClass *RC)
bool promoteToDotNew(MachineInstr &MI, SDep::Kind DepType, MachineBasicBlock::iterator &MII, const TargetRegisterClass *RC)
bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) override
bool canPromoteToDotCur(const MachineInstr &MI, const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII, const TargetRegisterClass *RC)
bool demoteToDotOld(MachineInstr &MI)
bool cannotCoexist(const MachineInstr &MI, const MachineInstr &MJ)
bool isSoloInstruction(const MachineInstr &MI) override
bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) override
bool hasControlDependence(const MachineInstr &I, const MachineInstr &J)
bool restrictingDepExistInPacket(MachineInstr &, unsigned)
bool producesStall(const MachineInstr &MI)
void undoChangedOffset(MachineInstr &MI)
Undo the changed offset.
bool hasDualStoreDependence(const MachineInstr &I, const MachineInstr &J)
unsigned int calcStall(const MachineInstr &MI)
bool canPromoteToDotNew(const MachineInstr &MI, const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII, const TargetRegisterClass *RC)
bool canPromoteToNewValue(const MachineInstr &MI, const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII)
bool ignorePseudoInstruction(const MachineInstr &MI, const MachineBasicBlock *MBB) override
void unpacketizeSoloInstrs(MachineFunction &MF)
const MachineBranchProbabilityInfo * MBPI
A handle to the branch probability pass.
bool shouldAddToPacket(const MachineInstr &MI) override
bool canPromoteToNewValueStore(const MachineInstr &MI, const MachineInstr &PacketMI, unsigned DepReg)
bool tryAllocateResourcesForConstExt(bool Reserve)
MachineBasicBlock::iterator addToPacket(MachineInstr &MI) override
bool hasDeadDependence(const MachineInstr &I, const MachineInstr &J)
bool isNewifiable(const MachineInstr &MI, const TargetRegisterClass *NewRC)
bool hasRegMaskDependence(const MachineInstr &I, const MachineInstr &J)
const HexagonInstrInfo * getInstrInfo() const override
const HexagonRegisterInfo * getRegisterInfo() const override
Describe properties that are true of each instruction in the target description file.
unsigned getSchedClass() const
Return the scheduling class for this instruction.
Instructions::iterator instr_iterator
Instructions::const_iterator const_instr_iterator
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
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.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool isImplicitDef() const
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
bool isBarrier(QueryType Type=AnyInBundle) const
Returns true if the specified instruction stops control flow from executing the instruction immediate...
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool isCall(QueryType Type=AnyInBundle) const
bool isInlineAsm() const
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register.
LLVM_ABI void unbundleFromPred()
Break bundle above this instruction.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
mop_range operands()
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Kind
These are the different kinds of scheduling dependencies.
Definition ScheduleDAG.h:57
@ Output
A register output-dependence (aka WAW).
Definition ScheduleDAG.h:60
@ Order
Any other ordering dependency.
Definition ScheduleDAG.h:61
@ Anti
A register anti-dependence (aka WAR).
Definition ScheduleDAG.h:59
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:58
Scheduling unit. This is a node in the scheduling DAG.
bool isSucc(const SUnit *N) const
Tests if node N is a successor of this node.
SmallVector< SDep, 4 > Succs
All sunit successors.
SmallVector< SDep, 4 > Preds
All sunit predecessors.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
VLIWPacketizerList(MachineFunction &MF, MachineLoopInfo &MLI, AAResults *AA)
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
bool alias(const MachineInstr &MI1, const MachineInstr &MI2, bool UseTBAA=true) const
std::vector< MachineInstr * > CurrentPacketMIs
std::map< MachineInstr *, SUnit * > MIToSUnit
DFAPacketizer * ResourceTracker
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
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
FunctionPass * createHexagonPacketizer(bool Minimal)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
DWARFExpression::Operation Op
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58