1 //===----- HexagonPacketizer.cpp - vliw packetizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements a simple VLIW packetizer using DFA. The packetizer works on
11 // machine basic blocks. For each instruction I in BB, the packetizer consults
12 // the DFA to see if machine resources are available to execute I. If so, the
13 // packetizer checks if I depends on any instruction J in the current packet.
14 // If no dependency is found, I is added to current packet and machine resource
15 // is marked as taken. If any dependency is found, a target API call is made to
16 // prune the dependence.
18 //===----------------------------------------------------------------------===//
19 #include "HexagonRegisterInfo.h"
20 #include "HexagonSubtarget.h"
21 #include "HexagonTargetMachine.h"
22 #include "HexagonVLIWPacketizer.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
34 #define DEBUG_TYPE "packets"
36 static cl::opt<bool> DisablePacketizer("disable-packetizer", cl::Hidden,
37 cl::ZeroOrMore, cl::init(false),
38 cl::desc("Disable Hexagon packetizer pass"));
40 static cl::opt<bool> PacketizeVolatiles("hexagon-packetize-volatiles",
41 cl::ZeroOrMore, cl::Hidden, cl::init(true),
42 cl::desc("Allow non-solo packetization of volatile memory references"));
44 static cl::opt<bool> EnableGenAllInsnClass("enable-gen-insn", cl::init(false),
45 cl::Hidden, cl::ZeroOrMore, cl::desc("Generate all instruction with TC"));
47 static cl::opt<bool> DisableVecDblNVStores("disable-vecdbl-nv-stores",
48 cl::init(false), cl::Hidden, cl::ZeroOrMore,
49 cl::desc("Disable vector double new-value-stores"));
51 extern cl::opt<bool> ScheduleInlineAsm;
54 FunctionPass *createHexagonPacketizer();
55 void initializeHexagonPacketizerPass(PassRegistry&);
60 class HexagonPacketizer : public MachineFunctionPass {
63 HexagonPacketizer() : MachineFunctionPass(ID) {
64 initializeHexagonPacketizerPass(*PassRegistry::getPassRegistry());
67 void getAnalysisUsage(AnalysisUsage &AU) const override {
69 AU.addRequired<AAResultsWrapperPass>();
70 AU.addRequired<MachineBranchProbabilityInfo>();
71 AU.addRequired<MachineDominatorTree>();
72 AU.addRequired<MachineLoopInfo>();
73 AU.addPreserved<MachineDominatorTree>();
74 AU.addPreserved<MachineLoopInfo>();
75 MachineFunctionPass::getAnalysisUsage(AU);
77 StringRef getPassName() const override { return "Hexagon Packetizer"; }
78 bool runOnMachineFunction(MachineFunction &Fn) override;
79 MachineFunctionProperties getRequiredProperties() const override {
80 return MachineFunctionProperties().set(
81 MachineFunctionProperties::Property::NoVRegs);
85 const HexagonInstrInfo *HII;
86 const HexagonRegisterInfo *HRI;
89 char HexagonPacketizer::ID = 0;
92 INITIALIZE_PASS_BEGIN(HexagonPacketizer, "packets", "Hexagon Packetizer",
94 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
95 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
96 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
97 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
98 INITIALIZE_PASS_END(HexagonPacketizer, "packets", "Hexagon Packetizer",
101 HexagonPacketizerList::HexagonPacketizerList(MachineFunction &MF,
102 MachineLoopInfo &MLI, AliasAnalysis *AA,
103 const MachineBranchProbabilityInfo *MBPI)
104 : VLIWPacketizerList(MF, MLI, AA), MBPI(MBPI), MLI(&MLI) {
105 HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
106 HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
108 addMutation(make_unique<HexagonSubtarget::HexagonDAGMutation>());
111 // Check if FirstI modifies a register that SecondI reads.
112 static bool hasWriteToReadDep(const MachineInstr &FirstI,
113 const MachineInstr &SecondI,
114 const TargetRegisterInfo *TRI) {
115 for (auto &MO : FirstI.operands()) {
116 if (!MO.isReg() || !MO.isDef())
118 unsigned R = MO.getReg();
119 if (SecondI.readsRegister(R, TRI))
126 static MachineBasicBlock::iterator moveInstrOut(MachineInstr &MI,
127 MachineBasicBlock::iterator BundleIt, bool Before) {
128 MachineBasicBlock::instr_iterator InsertPt;
130 InsertPt = BundleIt.getInstrIterator();
132 InsertPt = std::next(BundleIt).getInstrIterator();
134 MachineBasicBlock &B = *MI.getParent();
135 // The instruction should at least be bundled with the preceding instruction
136 // (there will always be one, i.e. BUNDLE, if nothing else).
137 assert(MI.isBundledWithPred());
138 if (MI.isBundledWithSucc()) {
139 MI.clearFlag(MachineInstr::BundledSucc);
140 MI.clearFlag(MachineInstr::BundledPred);
142 // If it's not bundled with the successor (i.e. it is the last one
143 // in the bundle), then we can simply unbundle it from the predecessor,
144 // which will take care of updating the predecessor's flag.
145 MI.unbundleFromPred();
147 B.splice(InsertPt, &B, MI.getIterator());
149 // Get the size of the bundle without asserting.
150 MachineBasicBlock::const_instr_iterator I = BundleIt.getInstrIterator();
151 MachineBasicBlock::const_instr_iterator E = B.instr_end();
153 for (++I; I != E && I->isBundledWithPred(); ++I)
156 // If there are still two or more instructions, then there is nothing
161 // Otherwise, extract the single instruction out and delete the bundle.
162 MachineBasicBlock::iterator NextIt = std::next(BundleIt);
163 MachineInstr &SingleI = *BundleIt->getNextNode();
164 SingleI.unbundleFromPred();
165 assert(!SingleI.isBundledWithSucc());
166 BundleIt->eraseFromParent();
171 bool HexagonPacketizer::runOnMachineFunction(MachineFunction &MF) {
172 if (DisablePacketizer || skipFunction(*MF.getFunction()))
175 HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
176 HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
177 auto &MLI = getAnalysis<MachineLoopInfo>();
178 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
179 auto *MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
181 if (EnableGenAllInsnClass)
182 HII->genAllInsnTimingClasses(MF);
184 // Instantiate the packetizer.
185 HexagonPacketizerList Packetizer(MF, MLI, AA, MBPI);
187 // DFA state table should not be empty.
188 assert(Packetizer.getResourceTracker() && "Empty DFA table!");
191 // Loop over all basic blocks and remove KILL pseudo-instructions
192 // These instructions confuse the dependence analysis. Consider:
194 // R0 = KILL R0, D0 (Insn 1)
196 // Here, Insn 1 will result in the dependence graph not emitting an output
197 // dependence between Insn 0 and Insn 2. This can lead to incorrect
200 for (auto &MB : MF) {
202 auto MI = MB.begin();
204 auto NextI = std::next(MI);
213 // Loop over all of the basic blocks.
214 for (auto &MB : MF) {
215 auto Begin = MB.begin(), End = MB.end();
216 while (Begin != End) {
217 // Find the first non-boundary starting from the end of the last
218 // scheduling region.
219 MachineBasicBlock::iterator RB = Begin;
220 while (RB != End && HII->isSchedulingBoundary(*RB, &MB, MF))
222 // Find the first boundary starting from the beginning of the new
224 MachineBasicBlock::iterator RE = RB;
225 while (RE != End && !HII->isSchedulingBoundary(*RE, &MB, MF))
227 // Add the scheduling boundary if it's not block end.
230 // If RB == End, then RE == End.
232 Packetizer.PacketizeMIs(&MB, RB, RE);
238 Packetizer.unpacketizeSoloInstrs(MF);
243 // Reserve resources for a constant extender. Trigger an assertion if the
244 // reservation fails.
245 void HexagonPacketizerList::reserveResourcesForConstExt() {
246 if (!tryAllocateResourcesForConstExt(true))
247 llvm_unreachable("Resources not available");
250 bool HexagonPacketizerList::canReserveResourcesForConstExt() {
251 return tryAllocateResourcesForConstExt(false);
254 // Allocate resources (i.e. 4 bytes) for constant extender. If succeeded,
255 // return true, otherwise, return false.
256 bool HexagonPacketizerList::tryAllocateResourcesForConstExt(bool Reserve) {
257 auto *ExtMI = MF.CreateMachineInstr(HII->get(Hexagon::A4_ext), DebugLoc());
258 bool Avail = ResourceTracker->canReserveResources(*ExtMI);
259 if (Reserve && Avail)
260 ResourceTracker->reserveResources(*ExtMI);
261 MF.DeleteMachineInstr(ExtMI);
266 bool HexagonPacketizerList::isCallDependent(const MachineInstr &MI,
267 SDep::Kind DepType, unsigned DepReg) {
268 // Check for LR dependence.
269 if (DepReg == HRI->getRARegister())
272 if (HII->isDeallocRet(MI))
273 if (DepReg == HRI->getFrameRegister() || DepReg == HRI->getStackRegister())
276 // Call-like instructions can be packetized with preceding instructions
277 // that define registers implicitly used or modified by the call. Explicit
278 // uses are still prohibited, as in the case of indirect calls:
281 if (DepType == SDep::Data) {
282 for (const MachineOperand MO : MI.operands())
283 if (MO.isReg() && MO.getReg() == DepReg && !MO.isImplicit())
290 static bool isRegDependence(const SDep::Kind DepType) {
291 return DepType == SDep::Data || DepType == SDep::Anti ||
292 DepType == SDep::Output;
295 static bool isDirectJump(const MachineInstr &MI) {
296 return MI.getOpcode() == Hexagon::J2_jump;
299 static bool isSchedBarrier(const MachineInstr &MI) {
300 switch (MI.getOpcode()) {
301 case Hexagon::Y2_barrier:
307 static bool isControlFlow(const MachineInstr &MI) {
308 return MI.getDesc().isTerminator() || MI.getDesc().isCall();
312 /// Returns true if the instruction modifies a callee-saved register.
313 static bool doesModifyCalleeSavedReg(const MachineInstr &MI,
314 const TargetRegisterInfo *TRI) {
315 const MachineFunction &MF = *MI.getParent()->getParent();
316 for (auto *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
317 if (MI.modifiesRegister(*CSR, TRI))
322 // Returns true if an instruction can be promoted to .new predicate or
324 bool HexagonPacketizerList::isNewifiable(const MachineInstr &MI,
325 const TargetRegisterClass *NewRC) {
326 // Vector stores can be predicated, and can be new-value stores, but
327 // they cannot be predicated on a .new predicate value.
328 if (NewRC == &Hexagon::PredRegsRegClass) {
329 if (HII->isHVXVec(MI) && MI.mayStore())
331 return HII->isPredicated(MI) && HII->getDotNewPredOp(MI, nullptr) > 0;
333 // If the class is not PredRegs, it could only apply to new-value stores.
334 return HII->mayBeNewStore(MI);
337 // Promote an instructiont to its .cur form.
338 // At this time, we have already made a call to canPromoteToDotCur and made
339 // sure that it can *indeed* be promoted.
340 bool HexagonPacketizerList::promoteToDotCur(MachineInstr &MI,
341 SDep::Kind DepType, MachineBasicBlock::iterator &MII,
342 const TargetRegisterClass* RC) {
343 assert(DepType == SDep::Data);
344 int CurOpcode = HII->getDotCurOp(MI);
345 MI.setDesc(HII->get(CurOpcode));
349 void HexagonPacketizerList::cleanUpDotCur() {
350 MachineInstr *MI = nullptr;
351 for (auto BI : CurrentPacketMIs) {
352 DEBUG(dbgs() << "Cleanup packet has "; BI->dump(););
353 if (HII->isDotCurInst(*BI)) {
358 for (auto &MO : BI->operands())
359 if (MO.isReg() && MO.getReg() == MI->getOperand(0).getReg())
365 // We did not find a use of the CUR, so de-cur it.
366 MI->setDesc(HII->get(HII->getNonDotCurOp(*MI)));
367 DEBUG(dbgs() << "Demoted CUR "; MI->dump(););
370 // Check to see if an instruction can be dot cur.
371 bool HexagonPacketizerList::canPromoteToDotCur(const MachineInstr &MI,
372 const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII,
373 const TargetRegisterClass *RC) {
374 if (!HII->isHVXVec(MI))
376 if (!HII->isHVXVec(*MII))
379 // Already a dot new instruction.
380 if (HII->isDotCurInst(MI) && !HII->mayBeCurLoad(MI))
383 if (!HII->mayBeCurLoad(MI))
386 // The "cur value" cannot come from inline asm.
387 if (PacketSU->getInstr()->isInlineAsm())
390 // Make sure candidate instruction uses cur.
391 DEBUG(dbgs() << "Can we DOT Cur Vector MI\n";
393 dbgs() << "in packet\n";);
394 MachineInstr &MJ = *MII;
396 dbgs() << "Checking CUR against ";
399 unsigned DestReg = MI.getOperand(0).getReg();
400 bool FoundMatch = false;
401 for (auto &MO : MJ.operands())
402 if (MO.isReg() && MO.getReg() == DestReg)
407 // Check for existing uses of a vector register within the packet which
408 // would be affected by converting a vector load into .cur formt.
409 for (auto BI : CurrentPacketMIs) {
410 DEBUG(dbgs() << "packet has "; BI->dump(););
411 if (BI->readsRegister(DepReg, MF.getSubtarget().getRegisterInfo()))
415 DEBUG(dbgs() << "Can Dot CUR MI\n"; MI.dump(););
416 // We can convert the opcode into a .cur.
420 // Promote an instruction to its .new form. At this time, we have already
421 // made a call to canPromoteToDotNew and made sure that it can *indeed* be
423 bool HexagonPacketizerList::promoteToDotNew(MachineInstr &MI,
424 SDep::Kind DepType, MachineBasicBlock::iterator &MII,
425 const TargetRegisterClass* RC) {
426 assert (DepType == SDep::Data);
428 if (RC == &Hexagon::PredRegsRegClass)
429 NewOpcode = HII->getDotNewPredOp(MI, MBPI);
431 NewOpcode = HII->getDotNewOp(MI);
432 MI.setDesc(HII->get(NewOpcode));
436 bool HexagonPacketizerList::demoteToDotOld(MachineInstr &MI) {
437 int NewOpcode = HII->getDotOldOp(MI);
438 MI.setDesc(HII->get(NewOpcode));
442 bool HexagonPacketizerList::useCallersSP(MachineInstr &MI) {
443 unsigned Opc = MI.getOpcode();
445 case Hexagon::S2_storerd_io:
446 case Hexagon::S2_storeri_io:
447 case Hexagon::S2_storerh_io:
448 case Hexagon::S2_storerb_io:
451 llvm_unreachable("Unexpected instruction");
453 unsigned FrameSize = MF.getFrameInfo().getStackSize();
454 MachineOperand &Off = MI.getOperand(1);
455 int64_t NewOff = Off.getImm() - (FrameSize + HEXAGON_LRFP_SIZE);
456 if (HII->isValidOffset(Opc, NewOff)) {
463 void HexagonPacketizerList::useCalleesSP(MachineInstr &MI) {
464 unsigned Opc = MI.getOpcode();
466 case Hexagon::S2_storerd_io:
467 case Hexagon::S2_storeri_io:
468 case Hexagon::S2_storerh_io:
469 case Hexagon::S2_storerb_io:
472 llvm_unreachable("Unexpected instruction");
474 unsigned FrameSize = MF.getFrameInfo().getStackSize();
475 MachineOperand &Off = MI.getOperand(1);
476 Off.setImm(Off.getImm() + FrameSize + HEXAGON_LRFP_SIZE);
485 /// Returns true if an instruction is predicated on p0 and false if it's
486 /// predicated on !p0.
487 static PredicateKind getPredicateSense(const MachineInstr &MI,
488 const HexagonInstrInfo *HII) {
489 if (!HII->isPredicated(MI))
491 if (HII->isPredicatedTrue(MI))
496 static const MachineOperand &getPostIncrementOperand(const MachineInstr &MI,
497 const HexagonInstrInfo *HII) {
498 assert(HII->isPostIncrement(MI) && "Not a post increment operation.");
500 // Post Increment means duplicates. Use dense map to find duplicates in the
501 // list. Caution: Densemap initializes with the minimum of 64 buckets,
502 // whereas there are at most 5 operands in the post increment.
503 DenseSet<unsigned> DefRegsSet;
504 for (auto &MO : MI.operands())
505 if (MO.isReg() && MO.isDef())
506 DefRegsSet.insert(MO.getReg());
508 for (auto &MO : MI.operands())
509 if (MO.isReg() && MO.isUse() && DefRegsSet.count(MO.getReg()))
513 const MachineOperand &Op1 = MI.getOperand(1);
514 // The 2nd operand is always the post increment operand in load.
515 assert(Op1.isReg() && "Post increment operand has be to a register.");
518 if (MI.getDesc().mayStore()) {
519 const MachineOperand &Op0 = MI.getOperand(0);
520 // The 1st operand is always the post increment operand in store.
521 assert(Op0.isReg() && "Post increment operand has be to a register.");
525 // we should never come here.
526 llvm_unreachable("mayLoad or mayStore not set for Post Increment operation");
529 // Get the value being stored.
530 static const MachineOperand& getStoreValueOperand(const MachineInstr &MI) {
531 // value being stored is always the last operand.
532 return MI.getOperand(MI.getNumOperands()-1);
535 static bool isLoadAbsSet(const MachineInstr &MI) {
536 unsigned Opc = MI.getOpcode();
538 case Hexagon::L4_loadrd_ap:
539 case Hexagon::L4_loadrb_ap:
540 case Hexagon::L4_loadrh_ap:
541 case Hexagon::L4_loadrub_ap:
542 case Hexagon::L4_loadruh_ap:
543 case Hexagon::L4_loadri_ap:
549 static const MachineOperand &getAbsSetOperand(const MachineInstr &MI) {
550 assert(isLoadAbsSet(MI));
551 return MI.getOperand(1);
555 // Can be new value store?
556 // Following restrictions are to be respected in convert a store into
557 // a new value store.
558 // 1. If an instruction uses auto-increment, its address register cannot
559 // be a new-value register. Arch Spec 5.4.2.1
560 // 2. If an instruction uses absolute-set addressing mode, its address
561 // register cannot be a new-value register. Arch Spec 5.4.2.1.
562 // 3. If an instruction produces a 64-bit result, its registers cannot be used
563 // as new-value registers. Arch Spec 5.4.2.2.
564 // 4. If the instruction that sets the new-value register is conditional, then
565 // the instruction that uses the new-value register must also be conditional,
566 // and both must always have their predicates evaluate identically.
567 // Arch Spec 5.4.2.3.
568 // 5. There is an implied restriction that a packet cannot have another store,
569 // if there is a new value store in the packet. Corollary: if there is
570 // already a store in a packet, there can not be a new value store.
571 // Arch Spec: 3.4.4.2
572 bool HexagonPacketizerList::canPromoteToNewValueStore(const MachineInstr &MI,
573 const MachineInstr &PacketMI, unsigned DepReg) {
574 // Make sure we are looking at the store, that can be promoted.
575 if (!HII->mayBeNewStore(MI))
578 // Make sure there is dependency and can be new value'd.
579 const MachineOperand &Val = getStoreValueOperand(MI);
580 if (Val.isReg() && Val.getReg() != DepReg)
583 const MCInstrDesc& MCID = PacketMI.getDesc();
585 // First operand is always the result.
586 const TargetRegisterClass *PacketRC = HII->getRegClass(MCID, 0, HRI, MF);
587 // Double regs can not feed into new value store: PRM section: 5.4.2.2.
588 if (PacketRC == &Hexagon::DoubleRegsRegClass)
591 // New-value stores are of class NV (slot 0), dual stores require class ST
592 // in slot 0 (PRM 5.5).
593 for (auto I : CurrentPacketMIs) {
594 SUnit *PacketSU = MIToSUnit.find(I)->second;
595 if (PacketSU->getInstr()->mayStore())
599 // Make sure it's NOT the post increment register that we are going to
601 if (HII->isPostIncrement(MI) &&
602 getPostIncrementOperand(MI, HII).getReg() == DepReg) {
606 if (HII->isPostIncrement(PacketMI) && PacketMI.mayLoad() &&
607 getPostIncrementOperand(PacketMI, HII).getReg() == DepReg) {
608 // If source is post_inc, or absolute-set addressing, it can not feed
609 // into new value store
611 // memw(r30 + #-1404) = r2.new -> can not be new value store
612 // arch spec section: 5.4.2.1.
616 if (isLoadAbsSet(PacketMI) && getAbsSetOperand(PacketMI).getReg() == DepReg)
619 // If the source that feeds the store is predicated, new value store must
620 // also be predicated.
621 if (HII->isPredicated(PacketMI)) {
622 if (!HII->isPredicated(MI))
625 // Check to make sure that they both will have their predicates
626 // evaluate identically.
627 unsigned predRegNumSrc = 0;
628 unsigned predRegNumDst = 0;
629 const TargetRegisterClass* predRegClass = nullptr;
631 // Get predicate register used in the source instruction.
632 for (auto &MO : PacketMI.operands()) {
635 predRegNumSrc = MO.getReg();
636 predRegClass = HRI->getMinimalPhysRegClass(predRegNumSrc);
637 if (predRegClass == &Hexagon::PredRegsRegClass)
640 assert((predRegClass == &Hexagon::PredRegsRegClass) &&
641 "predicate register not found in a predicated PacketMI instruction");
643 // Get predicate register used in new-value store instruction.
644 for (auto &MO : MI.operands()) {
647 predRegNumDst = MO.getReg();
648 predRegClass = HRI->getMinimalPhysRegClass(predRegNumDst);
649 if (predRegClass == &Hexagon::PredRegsRegClass)
652 assert((predRegClass == &Hexagon::PredRegsRegClass) &&
653 "predicate register not found in a predicated MI instruction");
655 // New-value register producer and user (store) need to satisfy these
657 // 1) Both instructions should be predicated on the same register.
658 // 2) If producer of the new-value register is .new predicated then store
659 // should also be .new predicated and if producer is not .new predicated
660 // then store should not be .new predicated.
661 // 3) Both new-value register producer and user should have same predicate
662 // sense, i.e, either both should be negated or both should be non-negated.
663 if (predRegNumDst != predRegNumSrc ||
664 HII->isDotNewInst(PacketMI) != HII->isDotNewInst(MI) ||
665 getPredicateSense(MI, HII) != getPredicateSense(PacketMI, HII))
669 // Make sure that other than the new-value register no other store instruction
670 // register has been modified in the same packet. Predicate registers can be
671 // modified by they should not be modified between the producer and the store
672 // instruction as it will make them both conditional on different values.
673 // We already know this to be true for all the instructions before and
674 // including PacketMI. Howerver, we need to perform the check for the
675 // remaining instructions in the packet.
677 unsigned StartCheck = 0;
679 for (auto I : CurrentPacketMIs) {
680 SUnit *TempSU = MIToSUnit.find(I)->second;
681 MachineInstr &TempMI = *TempSU->getInstr();
683 // Following condition is true for all the instructions until PacketMI is
684 // reached (StartCheck is set to 0 before the for loop).
685 // StartCheck flag is 1 for all the instructions after PacketMI.
686 if (&TempMI != &PacketMI && !StartCheck) // Start processing only after
687 continue; // encountering PacketMI.
690 if (&TempMI == &PacketMI) // We don't want to check PacketMI for dependence.
693 for (auto &MO : MI.operands())
694 if (MO.isReg() && TempSU->getInstr()->modifiesRegister(MO.getReg(), HRI))
698 // Make sure that for non-POST_INC stores:
699 // 1. The only use of reg is DepReg and no other registers.
700 // This handles V4 base+index registers.
701 // The following store can not be dot new.
702 // Eg. r0 = add(r0, #3)
703 // memw(r1+r0<<#2) = r0
704 if (!HII->isPostIncrement(MI)) {
705 for (unsigned opNum = 0; opNum < MI.getNumOperands()-1; opNum++) {
706 const MachineOperand &MO = MI.getOperand(opNum);
707 if (MO.isReg() && MO.getReg() == DepReg)
712 // If data definition is because of implicit definition of the register,
713 // do not newify the store. Eg.
714 // %R9<def> = ZXTH %R12, %D6<imp-use>, %R12<imp-def>
715 // S2_storerh_io %R8, 2, %R12<kill>; mem:ST2[%scevgep343]
716 for (auto &MO : PacketMI.operands()) {
717 if (MO.isRegMask() && MO.clobbersPhysReg(DepReg))
719 if (!MO.isReg() || !MO.isDef() || !MO.isImplicit())
721 unsigned R = MO.getReg();
722 if (R == DepReg || HRI->isSuperRegister(DepReg, R))
726 // Handle imp-use of super reg case. There is a target independent side
727 // change that should prevent this situation but I am handling it for
728 // just-in-case. For example, we cannot newify R2 in the following case:
729 // %R3<def> = A2_tfrsi 0;
730 // S2_storeri_io %R0<kill>, 0, %R2<kill>, %D1<imp-use,kill>;
731 for (auto &MO : MI.operands()) {
732 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == DepReg)
736 // Can be dot new store.
740 // Can this MI to promoted to either new value store or new value jump.
741 bool HexagonPacketizerList::canPromoteToNewValue(const MachineInstr &MI,
742 const SUnit *PacketSU, unsigned DepReg,
743 MachineBasicBlock::iterator &MII) {
744 if (!HII->mayBeNewStore(MI))
747 // Check to see the store can be new value'ed.
748 MachineInstr &PacketMI = *PacketSU->getInstr();
749 if (canPromoteToNewValueStore(MI, PacketMI, DepReg))
752 // Check to see the compare/jump can be new value'ed.
753 // This is done as a pass on its own. Don't need to check it here.
757 static bool isImplicitDependency(const MachineInstr &I, bool CheckDef,
759 for (auto &MO : I.operands()) {
760 if (CheckDef && MO.isRegMask() && MO.clobbersPhysReg(DepReg))
762 if (!MO.isReg() || MO.getReg() != DepReg || !MO.isImplicit())
764 if (CheckDef == MO.isDef())
770 // Check to see if an instruction can be dot new
771 // There are three kinds.
772 // 1. dot new on predicate - V2/V3/V4
773 // 2. dot new on stores NV/ST - V4
774 // 3. dot new on jump NV/J - V4 -- This is generated in a pass.
775 bool HexagonPacketizerList::canPromoteToDotNew(const MachineInstr &MI,
776 const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII,
777 const TargetRegisterClass* RC) {
778 // Already a dot new instruction.
779 if (HII->isDotNewInst(MI) && !HII->mayBeNewStore(MI))
782 if (!isNewifiable(MI, RC))
785 const MachineInstr &PI = *PacketSU->getInstr();
787 // The "new value" cannot come from inline asm.
788 if (PI.isInlineAsm())
791 // IMPLICIT_DEFs won't materialize as real instructions, so .new makes no
793 if (PI.isImplicitDef())
796 // If dependency is trough an implicitly defined register, we should not
798 if (isImplicitDependency(PI, true, DepReg) ||
799 isImplicitDependency(MI, false, DepReg))
802 const MCInstrDesc& MCID = PI.getDesc();
803 const TargetRegisterClass *VecRC = HII->getRegClass(MCID, 0, HRI, MF);
804 if (DisableVecDblNVStores && VecRC == &Hexagon::VecDblRegsRegClass)
808 if (RC == &Hexagon::PredRegsRegClass)
809 return HII->predCanBeUsedAsDotNew(PI, DepReg);
811 if (RC != &Hexagon::PredRegsRegClass && !HII->mayBeNewStore(MI))
814 // Create a dot new machine instruction to see if resources can be
815 // allocated. If not, bail out now.
816 int NewOpcode = HII->getDotNewOp(MI);
817 const MCInstrDesc &D = HII->get(NewOpcode);
818 MachineInstr *NewMI = MF.CreateMachineInstr(D, DebugLoc());
819 bool ResourcesAvailable = ResourceTracker->canReserveResources(*NewMI);
820 MF.DeleteMachineInstr(NewMI);
821 if (!ResourcesAvailable)
824 // New Value Store only. New Value Jump generated as a separate pass.
825 if (!canPromoteToNewValue(MI, PacketSU, DepReg, MII))
831 // Go through the packet instructions and search for an anti dependency between
832 // them and DepReg from MI. Consider this case:
834 // a) %R1<def> = TFRI_cdNotPt %P3, 2
837 // b) %P0<def> = C2_or %P3<kill>, %P0<kill>
838 // c) %P3<def> = C2_tfrrp %R23
839 // d) %R1<def> = C2_cmovenewit %P3, 4
841 // The P3 from a) and d) will be complements after
842 // a)'s P3 is converted to .new form
843 // Anti-dep between c) and b) is irrelevant for this case
844 bool HexagonPacketizerList::restrictingDepExistInPacket(MachineInstr &MI,
846 SUnit *PacketSUDep = MIToSUnit.find(&MI)->second;
848 for (auto I : CurrentPacketMIs) {
849 // We only care for dependencies to predicated instructions
850 if (!HII->isPredicated(*I))
853 // Scheduling Unit for current insn in the packet
854 SUnit *PacketSU = MIToSUnit.find(I)->second;
856 // Look at dependencies between current members of the packet and
857 // predicate defining instruction MI. Make sure that dependency is
858 // on the exact register we care about.
859 if (PacketSU->isSucc(PacketSUDep)) {
860 for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) {
861 auto &Dep = PacketSU->Succs[i];
862 if (Dep.getSUnit() == PacketSUDep && Dep.getKind() == SDep::Anti &&
863 Dep.getReg() == DepReg)
873 /// Gets the predicate register of a predicated instruction.
874 static unsigned getPredicatedRegister(MachineInstr &MI,
875 const HexagonInstrInfo *QII) {
876 /// We use the following rule: The first predicate register that is a use is
877 /// the predicate register of a predicated instruction.
878 assert(QII->isPredicated(MI) && "Must be predicated instruction");
880 for (auto &Op : MI.operands()) {
881 if (Op.isReg() && Op.getReg() && Op.isUse() &&
882 Hexagon::PredRegsRegClass.contains(Op.getReg()))
886 llvm_unreachable("Unknown instruction operand layout");
890 // Given two predicated instructions, this function detects whether
891 // the predicates are complements.
892 bool HexagonPacketizerList::arePredicatesComplements(MachineInstr &MI1,
894 // If we don't know the predicate sense of the instructions bail out early, we
896 if (getPredicateSense(MI1, HII) == PK_Unknown ||
897 getPredicateSense(MI2, HII) == PK_Unknown)
900 // Scheduling unit for candidate.
901 SUnit *SU = MIToSUnit[&MI1];
903 // One corner case deals with the following scenario:
905 // a) %R24<def> = A2_tfrt %P0, %R25
908 // b) %R25<def> = A2_tfrf %P0, %R24
909 // c) %P0<def> = C2_cmpeqi %R26, 1
912 // On general check a) and b) are complements, but presence of c) will
913 // convert a) to .new form, and then it is not a complement.
914 // We attempt to detect it by analyzing existing dependencies in the packet.
916 // Analyze relationships between all existing members of the packet.
917 // Look for Anti dependecy on the same predicate reg as used in the
919 for (auto I : CurrentPacketMIs) {
920 // Scheduling Unit for current insn in the packet.
921 SUnit *PacketSU = MIToSUnit.find(I)->second;
923 // If this instruction in the packet is succeeded by the candidate...
924 if (PacketSU->isSucc(SU)) {
925 for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) {
926 auto Dep = PacketSU->Succs[i];
927 // The corner case exist when there is true data dependency between
928 // candidate and one of current packet members, this dep is on
929 // predicate reg, and there already exist anti dep on the same pred in
931 if (Dep.getSUnit() == SU && Dep.getKind() == SDep::Data &&
932 Hexagon::PredRegsRegClass.contains(Dep.getReg())) {
933 // Here I know that I is predicate setting instruction with true
934 // data dep to candidate on the register we care about - c) in the
935 // above example. Now I need to see if there is an anti dependency
936 // from c) to any other instruction in the same packet on the pred
938 if (restrictingDepExistInPacket(*I, Dep.getReg()))
945 // If the above case does not apply, check regular complement condition.
946 // Check that the predicate register is the same and that the predicate
947 // sense is different We also need to differentiate .old vs. .new: !p0
948 // is not complementary to p0.new.
949 unsigned PReg1 = getPredicatedRegister(MI1, HII);
950 unsigned PReg2 = getPredicatedRegister(MI2, HII);
951 return PReg1 == PReg2 &&
952 Hexagon::PredRegsRegClass.contains(PReg1) &&
953 Hexagon::PredRegsRegClass.contains(PReg2) &&
954 getPredicateSense(MI1, HII) != getPredicateSense(MI2, HII) &&
955 HII->isDotNewInst(MI1) == HII->isDotNewInst(MI2);
958 // Initialize packetizer flags.
959 void HexagonPacketizerList::initPacketizerState() {
961 PromotedToDotNew = false;
962 GlueToNewValueJump = false;
963 GlueAllocframeStore = false;
964 FoundSequentialDependence = false;
967 // Ignore bundling of pseudo instructions.
968 bool HexagonPacketizerList::ignorePseudoInstruction(const MachineInstr &MI,
969 const MachineBasicBlock *) {
970 if (MI.isDebugValue())
973 if (MI.isCFIInstruction())
976 // We must print out inline assembly.
977 if (MI.isInlineAsm())
980 if (MI.isImplicitDef())
983 // We check if MI has any functional units mapped to it. If it doesn't,
984 // we ignore the instruction.
985 const MCInstrDesc& TID = MI.getDesc();
986 auto *IS = ResourceTracker->getInstrItins()->beginStage(TID.getSchedClass());
987 unsigned FuncUnits = IS->getUnits();
991 bool HexagonPacketizerList::isSoloInstruction(const MachineInstr &MI) {
992 if (MI.isEHLabel() || MI.isCFIInstruction())
995 // Consider inline asm to not be a solo instruction by default.
996 // Inline asm will be put in a packet temporarily, but then it will be
997 // removed, and placed outside of the packet (before or after, depending
998 // on dependencies). This is to reduce the impact of inline asm as a
999 // "packet splitting" instruction.
1000 if (MI.isInlineAsm() && !ScheduleInlineAsm)
1003 // From Hexagon V4 Programmer's Reference Manual 3.4.4 Grouping constraints:
1004 // trap, pause, barrier, icinva, isync, and syncht are solo instructions.
1005 // They must not be grouped with other instructions in a packet.
1006 if (isSchedBarrier(MI))
1009 if (HII->isSolo(MI))
1012 if (MI.getOpcode() == Hexagon::A2_nop)
1019 // Quick check if instructions MI and MJ cannot coexist in the same packet.
1020 // Limit the tests to be "one-way", e.g. "if MI->isBranch and MJ->isInlineAsm",
1021 // but not the symmetric case: "if MJ->isBranch and MI->isInlineAsm".
1022 // For full test call this function twice:
1023 // cannotCoexistAsymm(MI, MJ) || cannotCoexistAsymm(MJ, MI)
1024 // Doing the test only one way saves the amount of code in this function,
1025 // since every test would need to be repeated with the MI and MJ reversed.
1026 static bool cannotCoexistAsymm(const MachineInstr &MI, const MachineInstr &MJ,
1027 const HexagonInstrInfo &HII) {
1028 const MachineFunction *MF = MI.getParent()->getParent();
1029 if (MF->getSubtarget<HexagonSubtarget>().hasV60TOpsOnly() &&
1030 HII.isHVXMemWithAIndirect(MI, MJ))
1033 // An inline asm cannot be together with a branch, because we may not be
1034 // able to remove the asm out after packetizing (i.e. if the asm must be
1035 // moved past the bundle). Similarly, two asms cannot be together to avoid
1036 // complications when determining their relative order outside of a bundle.
1037 if (MI.isInlineAsm())
1038 return MJ.isInlineAsm() || MJ.isBranch() || MJ.isBarrier() ||
1039 MJ.isCall() || MJ.isTerminator();
1041 switch (MI.getOpcode()) {
1042 case (Hexagon::S2_storew_locked):
1043 case (Hexagon::S4_stored_locked):
1044 case (Hexagon::L2_loadw_locked):
1045 case (Hexagon::L4_loadd_locked):
1046 case (Hexagon::Y4_l2fetch): {
1047 // These instructions can only be grouped with ALU32 or non-floating-point
1048 // XTYPE instructions. Since there is no convenient way of identifying fp
1049 // XTYPE instructions, only allow grouping with ALU32 for now.
1050 unsigned TJ = HII.getType(MJ);
1051 if (TJ != HexagonII::TypeALU32_2op &&
1052 TJ != HexagonII::TypeALU32_3op &&
1053 TJ != HexagonII::TypeALU32_ADDI)
1061 // "False" really means that the quick check failed to determine if
1062 // I and J cannot coexist.
1067 // Full, symmetric check.
1068 bool HexagonPacketizerList::cannotCoexist(const MachineInstr &MI,
1069 const MachineInstr &MJ) {
1070 return cannotCoexistAsymm(MI, MJ, *HII) || cannotCoexistAsymm(MJ, MI, *HII);
1073 void HexagonPacketizerList::unpacketizeSoloInstrs(MachineFunction &MF) {
1074 for (auto &B : MF) {
1075 MachineBasicBlock::iterator BundleIt;
1076 MachineBasicBlock::instr_iterator NextI;
1077 for (auto I = B.instr_begin(), E = B.instr_end(); I != E; I = NextI) {
1078 NextI = std::next(I);
1079 MachineInstr &MI = *I;
1082 if (!MI.isInsideBundle())
1085 // Decide on where to insert the instruction that we are pulling out.
1086 // Debug instructions always go before the bundle, but the placement of
1087 // INLINE_ASM depends on potential dependencies. By default, try to
1088 // put it before the bundle, but if the asm writes to a register that
1089 // other instructions in the bundle read, then we need to place it
1090 // after the bundle (to preserve the bundle semantics).
1091 bool InsertBeforeBundle;
1092 if (MI.isInlineAsm())
1093 InsertBeforeBundle = !hasWriteToReadDep(MI, *BundleIt, HRI);
1094 else if (MI.isDebugValue())
1095 InsertBeforeBundle = true;
1099 BundleIt = moveInstrOut(MI, BundleIt, InsertBeforeBundle);
1104 // Check if a given instruction is of class "system".
1105 static bool isSystemInstr(const MachineInstr &MI) {
1106 unsigned Opc = MI.getOpcode();
1108 case Hexagon::Y2_barrier:
1109 case Hexagon::Y2_dcfetchbo:
1115 bool HexagonPacketizerList::hasDeadDependence(const MachineInstr &I,
1116 const MachineInstr &J) {
1117 // The dependence graph may not include edges between dead definitions,
1118 // so without extra checks, we could end up packetizing two instruction
1119 // defining the same (dead) register.
1120 if (I.isCall() || J.isCall())
1122 if (HII->isPredicated(I) || HII->isPredicated(J))
1125 BitVector DeadDefs(Hexagon::NUM_TARGET_REGS);
1126 for (auto &MO : I.operands()) {
1127 if (!MO.isReg() || !MO.isDef() || !MO.isDead())
1129 DeadDefs[MO.getReg()] = true;
1132 for (auto &MO : J.operands()) {
1133 if (!MO.isReg() || !MO.isDef() || !MO.isDead())
1135 unsigned R = MO.getReg();
1136 if (R != Hexagon::USR_OVF && DeadDefs[R])
1142 bool HexagonPacketizerList::hasControlDependence(const MachineInstr &I,
1143 const MachineInstr &J) {
1144 // A save callee-save register function call can only be in a packet
1145 // with instructions that don't write to the callee-save registers.
1146 if ((HII->isSaveCalleeSavedRegsCall(I) &&
1147 doesModifyCalleeSavedReg(J, HRI)) ||
1148 (HII->isSaveCalleeSavedRegsCall(J) &&
1149 doesModifyCalleeSavedReg(I, HRI)))
1152 // Two control flow instructions cannot go in the same packet.
1153 if (isControlFlow(I) && isControlFlow(J))
1156 // \ref-manual (7.3.4) A loop setup packet in loopN or spNloop0 cannot
1157 // contain a speculative indirect jump,
1158 // a new-value compare jump or a dealloc_return.
1159 auto isBadForLoopN = [this] (const MachineInstr &MI) -> bool {
1160 if (MI.isCall() || HII->isDeallocRet(MI) || HII->isNewValueJump(MI))
1162 if (HII->isPredicated(MI) && HII->isPredicatedNew(MI) && HII->isJumpR(MI))
1167 if (HII->isLoopN(I) && isBadForLoopN(J))
1169 if (HII->isLoopN(J) && isBadForLoopN(I))
1172 // dealloc_return cannot appear in the same packet as a conditional or
1173 // unconditional jump.
1174 return HII->isDeallocRet(I) &&
1175 (J.isBranch() || J.isCall() || J.isBarrier());
1178 bool HexagonPacketizerList::hasRegMaskDependence(const MachineInstr &I,
1179 const MachineInstr &J) {
1180 // Adding I to a packet that has J.
1182 // Regmasks are not reflected in the scheduling dependency graph, so
1183 // we need to check them manually. This code assumes that regmasks only
1184 // occur on calls, and the problematic case is when we add an instruction
1185 // defining a register R to a packet that has a call that clobbers R via
1186 // a regmask. Those cannot be packetized together, because the call will
1187 // be executed last. That's also a reson why it is ok to add a call
1188 // clobbering R to a packet that defines R.
1190 // Look for regmasks in J.
1191 for (const MachineOperand &OpJ : J.operands()) {
1192 if (!OpJ.isRegMask())
1194 assert((J.isCall() || HII->isTailCall(J)) && "Regmask on a non-call");
1195 for (const MachineOperand &OpI : I.operands()) {
1197 if (OpJ.clobbersPhysReg(OpI.getReg()))
1199 } else if (OpI.isRegMask()) {
1200 // Both are regmasks. Assume that they intersect.
1208 bool HexagonPacketizerList::hasV4SpecificDependence(const MachineInstr &I,
1209 const MachineInstr &J) {
1210 bool SysI = isSystemInstr(I), SysJ = isSystemInstr(J);
1211 bool StoreI = I.mayStore(), StoreJ = J.mayStore();
1212 if ((SysI && StoreJ) || (SysJ && StoreI))
1215 if (StoreI && StoreJ) {
1216 if (HII->isNewValueInst(J) || HII->isMemOp(J) || HII->isMemOp(I))
1219 // A memop cannot be in the same packet with another memop or a store.
1220 // Two stores can be together, but here I and J cannot both be stores.
1221 bool MopStI = HII->isMemOp(I) || StoreI;
1222 bool MopStJ = HII->isMemOp(J) || StoreJ;
1223 if (MopStI && MopStJ)
1227 return (StoreJ && HII->isDeallocRet(I)) || (StoreI && HII->isDeallocRet(J));
1230 // SUI is the current instruction that is out side of the current packet.
1231 // SUJ is the current instruction inside the current packet against which that
1232 // SUI will be packetized.
1233 bool HexagonPacketizerList::isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) {
1234 assert(SUI->getInstr() && SUJ->getInstr());
1235 MachineInstr &I = *SUI->getInstr();
1236 MachineInstr &J = *SUJ->getInstr();
1238 // Clear IgnoreDepMIs when Packet starts.
1239 if (CurrentPacketMIs.size() == 1)
1240 IgnoreDepMIs.clear();
1242 MachineBasicBlock::iterator II = I.getIterator();
1244 // Solo instructions cannot go in the packet.
1245 assert(!isSoloInstruction(I) && "Unexpected solo instr!");
1247 if (cannotCoexist(I, J))
1250 Dependence = hasDeadDependence(I, J) || hasControlDependence(I, J);
1254 // Regmasks are not accounted for in the scheduling graph, so we need
1255 // to explicitly check for dependencies caused by them. They should only
1256 // appear on calls, so it's not too pessimistic to reject all regmask
1258 Dependence = hasRegMaskDependence(I, J);
1262 // V4 allows dual stores. It does not allow second store, if the first
1263 // store is not in SLOT0. New value store, new value jump, dealloc_return
1264 // and memop always take SLOT0. Arch spec 3.4.4.2.
1265 Dependence = hasV4SpecificDependence(I, J);
1269 // If an instruction feeds new value jump, glue it.
1270 MachineBasicBlock::iterator NextMII = I.getIterator();
1272 if (NextMII != I.getParent()->end() && HII->isNewValueJump(*NextMII)) {
1273 MachineInstr &NextMI = *NextMII;
1275 bool secondRegMatch = false;
1276 const MachineOperand &NOp0 = NextMI.getOperand(0);
1277 const MachineOperand &NOp1 = NextMI.getOperand(1);
1279 if (NOp1.isReg() && I.getOperand(0).getReg() == NOp1.getReg())
1280 secondRegMatch = true;
1282 for (auto T : CurrentPacketMIs) {
1283 SUnit *PacketSU = MIToSUnit.find(T)->second;
1284 MachineInstr &PI = *PacketSU->getInstr();
1285 // NVJ can not be part of the dual jump - Arch Spec: section 7.8.
1291 // 1. Packet does not have a store in it.
1292 // 2. If the first operand of the nvj is newified, and the second
1293 // operand is also a reg, it (second reg) is not defined in
1295 // 3. If the second operand of the nvj is newified, (which means
1296 // first operand is also a reg), first reg is not defined in
1298 if (PI.getOpcode() == Hexagon::S2_allocframe || PI.mayStore() ||
1304 const MachineOperand &OpR = secondRegMatch ? NOp0 : NOp1;
1305 if (OpR.isReg() && PI.modifiesRegister(OpR.getReg(), HRI)) {
1313 GlueToNewValueJump = true;
1316 // There no dependency between a prolog instruction and its successor.
1317 if (!SUJ->isSucc(SUI))
1320 for (unsigned i = 0; i < SUJ->Succs.size(); ++i) {
1321 if (FoundSequentialDependence)
1324 if (SUJ->Succs[i].getSUnit() != SUI)
1327 SDep::Kind DepType = SUJ->Succs[i].getKind();
1328 // For direct calls:
1329 // Ignore register dependences for call instructions for packetization
1330 // purposes except for those due to r31 and predicate registers.
1332 // For indirect calls:
1333 // Same as direct calls + check for true dependences to the register
1334 // used in the indirect call.
1336 // We completely ignore Order dependences for call instructions.
1339 // Ignore register dependences for return instructions like jumpr,
1340 // dealloc return unless we have dependencies on the explicit uses
1341 // of the registers used by jumpr (like r31) or dealloc return
1342 // (like r29 or r30).
1343 unsigned DepReg = 0;
1344 const TargetRegisterClass *RC = nullptr;
1345 if (DepType == SDep::Data) {
1346 DepReg = SUJ->Succs[i].getReg();
1347 RC = HRI->getMinimalPhysRegClass(DepReg);
1350 if (I.isCall() || HII->isJumpR(I) || I.isReturn() || HII->isTailCall(I)) {
1351 if (!isRegDependence(DepType))
1353 if (!isCallDependent(I, DepType, SUJ->Succs[i].getReg()))
1357 if (DepType == SDep::Data) {
1358 if (canPromoteToDotCur(J, SUJ, DepReg, II, RC))
1359 if (promoteToDotCur(J, DepType, II, RC))
1363 // Data dpendence ok if we have load.cur.
1364 if (DepType == SDep::Data && HII->isDotCurInst(J)) {
1365 if (HII->isHVXVec(I))
1369 // For instructions that can be promoted to dot-new, try to promote.
1370 if (DepType == SDep::Data) {
1371 if (canPromoteToDotNew(I, SUJ, DepReg, II, RC)) {
1372 if (promoteToDotNew(I, DepType, II, RC)) {
1373 PromotedToDotNew = true;
1374 if (cannotCoexist(I, J))
1375 FoundSequentialDependence = true;
1379 if (HII->isNewValueJump(I))
1383 // For predicated instructions, if the predicates are complements then
1384 // there can be no dependence.
1385 if (HII->isPredicated(I) && HII->isPredicated(J) &&
1386 arePredicatesComplements(I, J)) {
1387 // Not always safe to do this translation.
1388 // DAG Builder attempts to reduce dependence edges using transitive
1389 // nature of dependencies. Here is an example:
1391 // r0 = tfr_pt ... (1)
1392 // r0 = tfr_pf ... (2)
1393 // r0 = tfr_pt ... (3)
1395 // There will be an output dependence between (1)->(2) and (2)->(3).
1396 // However, there is no dependence edge between (1)->(3). This results
1397 // in all 3 instructions going in the same packet. We ignore dependce
1398 // only once to avoid this situation.
1399 auto Itr = find(IgnoreDepMIs, &J);
1400 if (Itr != IgnoreDepMIs.end()) {
1404 IgnoreDepMIs.push_back(&I);
1408 // Ignore Order dependences between unconditional direct branches
1409 // and non-control-flow instructions.
1410 if (isDirectJump(I) && !J.isBranch() && !J.isCall() &&
1411 DepType == SDep::Order)
1414 // Ignore all dependences for jumps except for true and output
1416 if (I.isConditionalBranch() && DepType != SDep::Data &&
1417 DepType != SDep::Output)
1420 if (DepType == SDep::Output) {
1421 FoundSequentialDependence = true;
1425 // For Order dependences:
1426 // 1. On V4 or later, volatile loads/stores can be packetized together,
1427 // unless other rules prevent is.
1428 // 2. Store followed by a load is not allowed.
1429 // 3. Store followed by a store is only valid on V4 or later.
1430 // 4. Load followed by any memory operation is allowed.
1431 if (DepType == SDep::Order) {
1432 if (!PacketizeVolatiles) {
1433 bool OrdRefs = I.hasOrderedMemoryRef() || J.hasOrderedMemoryRef();
1435 FoundSequentialDependence = true;
1439 // J is first, I is second.
1440 bool LoadJ = J.mayLoad(), StoreJ = J.mayStore();
1441 bool LoadI = I.mayLoad(), StoreI = I.mayStore();
1443 // Two stores are only allowed on V4+. Load following store is never
1446 FoundSequentialDependence = true;
1449 } else if (!LoadJ || (!LoadI && !StoreI)) {
1450 // If J is neither load nor store, assume a dependency.
1451 // If J is a load, but I is neither, also assume a dependency.
1452 FoundSequentialDependence = true;
1455 // Store followed by store: not OK on V2.
1456 // Store followed by load: not OK on all.
1457 // Load followed by store: OK on all.
1458 // Load followed by load: OK on all.
1462 // For V4, special case ALLOCFRAME. Even though there is dependency
1463 // between ALLOCFRAME and subsequent store, allow it to be packetized
1464 // in a same packet. This implies that the store is using the caller's
1465 // SP. Hence, offset needs to be updated accordingly.
1466 if (DepType == SDep::Data && J.getOpcode() == Hexagon::S2_allocframe) {
1467 unsigned Opc = I.getOpcode();
1469 case Hexagon::S2_storerd_io:
1470 case Hexagon::S2_storeri_io:
1471 case Hexagon::S2_storerh_io:
1472 case Hexagon::S2_storerb_io:
1473 if (I.getOperand(0).getReg() == HRI->getStackRegister()) {
1474 // Since this store is to be glued with allocframe in the same
1475 // packet, it will use SP of the previous stack frame, i.e.
1476 // caller's SP. Therefore, we need to recalculate offset
1477 // according to this change.
1478 GlueAllocframeStore = useCallersSP(I);
1479 if (GlueAllocframeStore)
1487 // There are certain anti-dependencies that cannot be ignored.
1489 // J2_call ... %R0<imp-def> ; SUJ
1491 // Those cannot be packetized together, since the call will observe
1492 // the effect of the assignment to R0.
1493 if ((DepType == SDep::Anti || DepType == SDep::Output) && J.isCall()) {
1494 // Check if I defines any volatile register. We should also check
1495 // registers that the call may read, but these happen to be a
1496 // subset of the volatile register set.
1497 for (const MachineOperand &Op : I.operands()) {
1498 if (Op.isReg() && Op.isDef()) {
1499 unsigned R = Op.getReg();
1500 if (!J.readsRegister(R, HRI) && !J.modifiesRegister(R, HRI))
1502 } else if (!Op.isRegMask()) {
1503 // If I has a regmask assume dependency.
1506 FoundSequentialDependence = true;
1511 // Skip over remaining anti-dependences. Two instructions that are
1512 // anti-dependent can share a packet, since in most such cases all
1513 // operands are read before any modifications take place.
1514 // The exceptions are branch and call instructions, since they are
1515 // executed after all other instructions have completed (at least
1517 if (DepType != SDep::Anti) {
1518 FoundSequentialDependence = true;
1523 if (FoundSequentialDependence) {
1531 bool HexagonPacketizerList::isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) {
1532 assert(SUI->getInstr() && SUJ->getInstr());
1533 MachineInstr &I = *SUI->getInstr();
1534 MachineInstr &J = *SUJ->getInstr();
1536 bool Coexist = !cannotCoexist(I, J);
1538 if (Coexist && !Dependence)
1541 // Check if the instruction was promoted to a dot-new. If so, demote it
1542 // back into a dot-old.
1543 if (PromotedToDotNew)
1547 // Check if the instruction (must be a store) was glued with an allocframe
1548 // instruction. If so, restore its offset to its original value, i.e. use
1549 // current SP instead of caller's SP.
1550 if (GlueAllocframeStore) {
1552 GlueAllocframeStore = false;
1557 MachineBasicBlock::iterator
1558 HexagonPacketizerList::addToPacket(MachineInstr &MI) {
1559 MachineBasicBlock::iterator MII = MI.getIterator();
1560 MachineBasicBlock *MBB = MI.getParent();
1562 if (CurrentPacketMIs.size() == 0)
1563 PacketStalls = false;
1564 PacketStalls |= producesStall(MI);
1566 if (MI.isImplicitDef())
1568 assert(ResourceTracker->canReserveResources(MI));
1570 bool ExtMI = HII->isExtended(MI) || HII->isConstExtended(MI);
1573 if (GlueToNewValueJump) {
1574 MachineInstr &NvjMI = *++MII;
1575 // We need to put both instructions in the same packet: MI and NvjMI.
1576 // Either of them can require a constant extender. Try to add both to
1577 // the current packet, and if that fails, end the packet and start a
1579 ResourceTracker->reserveResources(MI);
1581 Good = tryAllocateResourcesForConstExt(true);
1583 bool ExtNvjMI = HII->isExtended(NvjMI) || HII->isConstExtended(NvjMI);
1585 if (ResourceTracker->canReserveResources(NvjMI))
1586 ResourceTracker->reserveResources(NvjMI);
1590 if (Good && ExtNvjMI)
1591 Good = tryAllocateResourcesForConstExt(true);
1595 assert(ResourceTracker->canReserveResources(MI));
1596 ResourceTracker->reserveResources(MI);
1598 assert(canReserveResourcesForConstExt());
1599 tryAllocateResourcesForConstExt(true);
1601 assert(ResourceTracker->canReserveResources(NvjMI));
1602 ResourceTracker->reserveResources(NvjMI);
1604 assert(canReserveResourcesForConstExt());
1605 reserveResourcesForConstExt();
1608 CurrentPacketMIs.push_back(&MI);
1609 CurrentPacketMIs.push_back(&NvjMI);
1613 ResourceTracker->reserveResources(MI);
1614 if (ExtMI && !tryAllocateResourcesForConstExt(true)) {
1616 if (PromotedToDotNew)
1618 if (GlueAllocframeStore) {
1620 GlueAllocframeStore = false;
1622 ResourceTracker->reserveResources(MI);
1623 reserveResourcesForConstExt();
1626 CurrentPacketMIs.push_back(&MI);
1630 void HexagonPacketizerList::endPacket(MachineBasicBlock *MBB,
1631 MachineBasicBlock::iterator MI) {
1632 OldPacketMIs = CurrentPacketMIs;
1633 VLIWPacketizerList::endPacket(MBB, MI);
1636 bool HexagonPacketizerList::shouldAddToPacket(const MachineInstr &MI) {
1637 return !producesStall(MI);
1641 // V60 forward scheduling.
1642 bool HexagonPacketizerList::producesStall(const MachineInstr &I) {
1643 // If the packet already stalls, then ignore the stall from a subsequent
1644 // instruction in the same packet.
1648 // Check whether the previous packet is in a different loop. If this is the
1649 // case, there is little point in trying to avoid a stall because that would
1650 // favor the rare case (loop entry) over the common case (loop iteration).
1652 // TODO: We should really be able to check all the incoming edges if this is
1653 // the first packet in a basic block, so we can avoid stalls from the loop
1655 if (!OldPacketMIs.empty()) {
1656 auto *OldBB = OldPacketMIs.front()->getParent();
1657 auto *ThisBB = I.getParent();
1658 if (MLI->getLoopFor(OldBB) != MLI->getLoopFor(ThisBB))
1662 SUnit *SUI = MIToSUnit[const_cast<MachineInstr *>(&I)];
1664 // Check if the latency is 0 between this instruction and any instruction
1665 // in the current packet. If so, we disregard any potential stalls due to
1666 // the instructions in the previous packet. Most of the instruction pairs
1667 // that can go together in the same packet have 0 latency between them.
1668 // Only exceptions are newValueJumps as they're generated much later and
1669 // the latencies can't be changed at that point. Another is .cur
1670 // instructions if its consumer has a 0 latency successor (such as .new).
1671 // In this case, the latency between .cur and the consumer stays non-zero
1672 // even though we can have both .cur and .new in the same packet. Changing
1673 // the latency to 0 is not an option as it causes software pipeliner to
1674 // not pipeline in some cases.
1678 // I1: v6.cur = vmem(r0++#1)
1679 // I2: v7 = valign(v6,v4,r2)
1680 // I3: vmem(r5++#1) = v7.new
1682 // Here I2 and I3 has 0 cycle latency, but I1 and I2 has 2.
1684 for (auto J : CurrentPacketMIs) {
1685 SUnit *SUJ = MIToSUnit[J];
1686 for (auto &Pred : SUI->Preds)
1687 if (Pred.getSUnit() == SUJ &&
1688 (Pred.getLatency() == 0 || HII->isNewValueJump(I) ||
1689 HII->isToBeScheduledASAP(*J, I)))
1693 // Check if the latency is greater than one between this instruction and any
1694 // instruction in the previous packet.
1695 for (auto J : OldPacketMIs) {
1696 SUnit *SUJ = MIToSUnit[J];
1697 for (auto &Pred : SUI->Preds)
1698 if (Pred.getSUnit() == SUJ && Pred.getLatency() > 1)
1702 // Check if the latency is greater than one between this instruction and any
1703 // instruction in the previous packet.
1704 for (auto J : OldPacketMIs) {
1705 SUnit *SUJ = MIToSUnit[J];
1706 for (auto &Pred : SUI->Preds)
1707 if (Pred.getSUnit() == SUJ && Pred.getLatency() > 1)
1714 //===----------------------------------------------------------------------===//
1715 // Public Constructor Functions
1716 //===----------------------------------------------------------------------===//
1718 FunctionPass *llvm::createHexagonPacketizer() {
1719 return new HexagonPacketizer();