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