LLVM 22.0.0git
SIFixSGPRCopies.cpp
Go to the documentation of this file.
1//===- SIFixSGPRCopies.cpp - Remove potential VGPR => SGPR copies ---------===//
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/// \file
10/// Copies from VGPR to SGPR registers are illegal and the register coalescer
11/// will sometimes generate these illegal copies in situations like this:
12///
13/// Register Class <vsrc> is the union of <vgpr> and <sgpr>
14///
15/// BB0:
16/// %0 <sgpr> = SCALAR_INST
17/// %1 <vsrc> = COPY %0 <sgpr>
18/// ...
19/// BRANCH %cond BB1, BB2
20/// BB1:
21/// %2 <vgpr> = VECTOR_INST
22/// %3 <vsrc> = COPY %2 <vgpr>
23/// BB2:
24/// %4 <vsrc> = PHI %1 <vsrc>, <%bb.0>, %3 <vrsc>, <%bb.1>
25/// %5 <vgpr> = VECTOR_INST %4 <vsrc>
26///
27///
28/// The coalescer will begin at BB0 and eliminate its copy, then the resulting
29/// code will look like this:
30///
31/// BB0:
32/// %0 <sgpr> = SCALAR_INST
33/// ...
34/// BRANCH %cond BB1, BB2
35/// BB1:
36/// %2 <vgpr> = VECTOR_INST
37/// %3 <vsrc> = COPY %2 <vgpr>
38/// BB2:
39/// %4 <sgpr> = PHI %0 <sgpr>, <%bb.0>, %3 <vsrc>, <%bb.1>
40/// %5 <vgpr> = VECTOR_INST %4 <sgpr>
41///
42/// Now that the result of the PHI instruction is an SGPR, the register
43/// allocator is now forced to constrain the register class of %3 to
44/// <sgpr> so we end up with final code like this:
45///
46/// BB0:
47/// %0 <sgpr> = SCALAR_INST
48/// ...
49/// BRANCH %cond BB1, BB2
50/// BB1:
51/// %2 <vgpr> = VECTOR_INST
52/// %3 <sgpr> = COPY %2 <vgpr>
53/// BB2:
54/// %4 <sgpr> = PHI %0 <sgpr>, <%bb.0>, %3 <sgpr>, <%bb.1>
55/// %5 <vgpr> = VECTOR_INST %4 <sgpr>
56///
57/// Now this code contains an illegal copy from a VGPR to an SGPR.
58///
59/// In order to avoid this problem, this pass searches for PHI instructions
60/// which define a <vsrc> register and constrains its definition class to
61/// <vgpr> if the user of the PHI's definition register is a vector instruction.
62/// If the PHI's definition class is constrained to <vgpr> then the coalescer
63/// will be unable to perform the COPY removal from the above example which
64/// ultimately led to the creation of an illegal COPY.
65//===----------------------------------------------------------------------===//
66
67#include "SIFixSGPRCopies.h"
68#include "AMDGPU.h"
69#include "GCNSubtarget.h"
74
75using namespace llvm;
76
77#define DEBUG_TYPE "si-fix-sgpr-copies"
78
80 "amdgpu-enable-merge-m0",
81 cl::desc("Merge and hoist M0 initializations"),
82 cl::init(true));
83
84namespace {
85
86class V2SCopyInfo {
87public:
88 // VGPR to SGPR copy being processed
89 MachineInstr *Copy;
90 // All SALU instructions reachable from this copy in SSA graph
92 // Number of SGPR to VGPR copies that are used to put the SALU computation
93 // results back to VALU.
94 unsigned NumSVCopies = 0;
95
96 unsigned Score = 0;
97 // Actual count of v_readfirstlane_b32
98 // which need to be inserted to keep SChain SALU
99 unsigned NumReadfirstlanes = 0;
100 // Current score state. To speedup selection V2SCopyInfos for processing
101 bool NeedToBeConvertedToVALU = false;
102 // Unique ID. Used as a key for mapping to keep permanent order.
103 unsigned ID;
104
105 // Count of another VGPR to SGPR copies that contribute to the
106 // current copy SChain
107 unsigned SiblingPenalty = 0;
108 SetVector<unsigned> Siblings;
109 V2SCopyInfo() : Copy(nullptr), ID(0){};
110 V2SCopyInfo(unsigned Id, MachineInstr *C, unsigned Width)
111 : Copy(C), NumReadfirstlanes(Width / 32), ID(Id){};
112#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
113 void dump() {
114 dbgs() << ID << " : " << *Copy << "\n\tS:" << SChain.size()
115 << "\n\tSV:" << NumSVCopies << "\n\tSP: " << SiblingPenalty
116 << "\nScore: " << Score << "\n";
117 }
118#endif
119};
120
121class SIFixSGPRCopies {
127 unsigned NextVGPRToSGPRCopyID = 0;
130 DenseSet<MachineInstr *> PHISources;
131
132public:
134 const SIRegisterInfo *TRI;
135 const SIInstrInfo *TII;
136
137 SIFixSGPRCopies(MachineDominatorTree *MDT) : MDT(MDT) {}
138
139 bool run(MachineFunction &MF);
140 void fixSCCCopies(MachineFunction &MF);
141 void prepareRegSequenceAndPHIs(MachineFunction &MF);
142 unsigned getNextVGPRToSGPRCopyId() { return ++NextVGPRToSGPRCopyID; }
143 bool needToBeConvertedToVALU(V2SCopyInfo *I);
144 void analyzeVGPRToSGPRCopy(MachineInstr *MI);
145 void lowerVGPR2SGPRCopies(MachineFunction &MF);
146 // Handles copies which source register is:
147 // 1. Physical register
148 // 2. AGPR
149 // 3. Defined by the instruction the merely moves the immediate
150 bool lowerSpecialCase(MachineInstr &MI, MachineBasicBlock::iterator &I);
151
152 void processPHINode(MachineInstr &MI);
153
154 // Check if MO is an immediate materialized into a VGPR, and if so replace it
155 // with an SGPR immediate. The VGPR immediate is also deleted if it does not
156 // have any other uses.
157 bool tryMoveVGPRConstToSGPR(MachineOperand &MO, Register NewDst,
158 MachineBasicBlock *BlockToInsertTo,
159 MachineBasicBlock::iterator PointToInsertTo,
160 const DebugLoc &DL);
161};
162
163class SIFixSGPRCopiesLegacy : public MachineFunctionPass {
164public:
165 static char ID;
166
167 SIFixSGPRCopiesLegacy() : MachineFunctionPass(ID) {}
168
169 bool runOnMachineFunction(MachineFunction &MF) override {
171 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
172 SIFixSGPRCopies Impl(MDT);
173 return Impl.run(MF);
174 }
175
176 StringRef getPassName() const override { return "SI Fix SGPR copies"; }
177
178 void getAnalysisUsage(AnalysisUsage &AU) const override {
181 AU.setPreservesCFG();
183 }
184};
185
186} // end anonymous namespace
187
188INITIALIZE_PASS_BEGIN(SIFixSGPRCopiesLegacy, DEBUG_TYPE, "SI Fix SGPR copies",
189 false, false)
191INITIALIZE_PASS_END(SIFixSGPRCopiesLegacy, DEBUG_TYPE, "SI Fix SGPR copies",
193
194char SIFixSGPRCopiesLegacy::ID = 0;
195
196char &llvm::SIFixSGPRCopiesLegacyID = SIFixSGPRCopiesLegacy::ID;
197
199 return new SIFixSGPRCopiesLegacy();
200}
201
202static std::pair<const TargetRegisterClass *, const TargetRegisterClass *>
204 const SIRegisterInfo &TRI,
205 const MachineRegisterInfo &MRI) {
206 Register DstReg = Copy.getOperand(0).getReg();
207 Register SrcReg = Copy.getOperand(1).getReg();
208
209 const TargetRegisterClass *SrcRC = SrcReg.isVirtual()
210 ? MRI.getRegClass(SrcReg)
211 : TRI.getPhysRegBaseClass(SrcReg);
212
213 // We don't really care about the subregister here.
214 // SrcRC = TRI.getSubRegClass(SrcRC, Copy.getOperand(1).getSubReg());
215
216 const TargetRegisterClass *DstRC = DstReg.isVirtual()
217 ? MRI.getRegClass(DstReg)
218 : TRI.getPhysRegBaseClass(DstReg);
219
220 return std::pair(SrcRC, DstRC);
221}
222
223static bool isVGPRToSGPRCopy(const TargetRegisterClass *SrcRC,
224 const TargetRegisterClass *DstRC,
225 const SIRegisterInfo &TRI) {
226 return SrcRC != &AMDGPU::VReg_1RegClass && TRI.isSGPRClass(DstRC) &&
227 TRI.hasVectorRegisters(SrcRC);
228}
229
230static bool isSGPRToVGPRCopy(const TargetRegisterClass *SrcRC,
231 const TargetRegisterClass *DstRC,
232 const SIRegisterInfo &TRI) {
233 return DstRC != &AMDGPU::VReg_1RegClass && TRI.isSGPRClass(SrcRC) &&
234 TRI.hasVectorRegisters(DstRC);
235}
236
238 const SIRegisterInfo *TRI,
239 const SIInstrInfo *TII) {
240 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
241 auto &Src = MI.getOperand(1);
242 Register DstReg = MI.getOperand(0).getReg();
243 Register SrcReg = Src.getReg();
244 if (!SrcReg.isVirtual() || !DstReg.isVirtual())
245 return false;
246
247 for (const auto &MO : MRI.reg_nodbg_operands(DstReg)) {
248 const auto *UseMI = MO.getParent();
249 if (UseMI == &MI)
250 continue;
251 if (MO.isDef() || UseMI->getParent() != MI.getParent() ||
252 UseMI->getOpcode() <= TargetOpcode::GENERIC_OP_END)
253 return false;
254
255 unsigned OpIdx = MO.getOperandNo();
256 if (OpIdx >= UseMI->getDesc().getNumOperands() ||
257 !TII->isOperandLegal(*UseMI, OpIdx, &Src))
258 return false;
259 }
260 // Change VGPR to SGPR destination.
261 MRI.setRegClass(DstReg, TRI->getEquivalentSGPRClass(MRI.getRegClass(DstReg)));
262 return true;
263}
264
265// Distribute an SGPR->VGPR copy of a REG_SEQUENCE into a VGPR REG_SEQUENCE.
266//
267// SGPRx = ...
268// SGPRy = REG_SEQUENCE SGPRx, sub0 ...
269// VGPRz = COPY SGPRy
270//
271// ==>
272//
273// VGPRx = COPY SGPRx
274// VGPRz = REG_SEQUENCE VGPRx, sub0
275//
276// This exposes immediate folding opportunities when materializing 64-bit
277// immediates.
279 const SIRegisterInfo *TRI,
280 const SIInstrInfo *TII,
282 assert(MI.isRegSequence());
283
284 Register DstReg = MI.getOperand(0).getReg();
285 if (!TRI->isSGPRClass(MRI.getRegClass(DstReg)))
286 return false;
287
288 if (!MRI.hasOneUse(DstReg))
289 return false;
290
291 MachineInstr &CopyUse = *MRI.use_instr_begin(DstReg);
292 if (!CopyUse.isCopy())
293 return false;
294
295 // It is illegal to have vreg inputs to a physreg defining reg_sequence.
296 if (CopyUse.getOperand(0).getReg().isPhysical())
297 return false;
298
299 const TargetRegisterClass *SrcRC, *DstRC;
300 std::tie(SrcRC, DstRC) = getCopyRegClasses(CopyUse, *TRI, MRI);
301
302 if (!isSGPRToVGPRCopy(SrcRC, DstRC, *TRI))
303 return false;
304
305 if (tryChangeVGPRtoSGPRinCopy(CopyUse, TRI, TII))
306 return true;
307
308 // TODO: Could have multiple extracts?
309 unsigned SubReg = CopyUse.getOperand(1).getSubReg();
310 if (SubReg != AMDGPU::NoSubRegister)
311 return false;
312
313 MRI.setRegClass(DstReg, DstRC);
314
315 // SGPRx = ...
316 // SGPRy = REG_SEQUENCE SGPRx, sub0 ...
317 // VGPRz = COPY SGPRy
318
319 // =>
320 // VGPRx = COPY SGPRx
321 // VGPRz = REG_SEQUENCE VGPRx, sub0
322
323 MI.getOperand(0).setReg(CopyUse.getOperand(0).getReg());
324 bool IsAGPR = TRI->isAGPRClass(DstRC);
325
326 for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
327 const TargetRegisterClass *SrcRC =
328 TRI->getRegClassForOperandReg(MRI, MI.getOperand(I));
329 assert(TRI->isSGPRClass(SrcRC) &&
330 "Expected SGPR REG_SEQUENCE to only have SGPR inputs");
331 const TargetRegisterClass *NewSrcRC = TRI->getEquivalentVGPRClass(SrcRC);
332
333 Register TmpReg = MRI.createVirtualRegister(NewSrcRC);
334
335 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(), TII->get(AMDGPU::COPY),
336 TmpReg)
337 .add(MI.getOperand(I));
338
339 if (IsAGPR) {
340 const TargetRegisterClass *NewSrcRC = TRI->getEquivalentAGPRClass(SrcRC);
341 Register TmpAReg = MRI.createVirtualRegister(NewSrcRC);
342 unsigned Opc = NewSrcRC == &AMDGPU::AGPR_32RegClass ?
343 AMDGPU::V_ACCVGPR_WRITE_B32_e64 : AMDGPU::COPY;
344 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(), TII->get(Opc),
345 TmpAReg)
346 .addReg(TmpReg, RegState::Kill);
347 TmpReg = TmpAReg;
348 }
349
350 MI.getOperand(I).setReg(TmpReg);
351 }
352
353 CopyUse.eraseFromParent();
354 return true;
355}
356
357static bool isSafeToFoldImmIntoCopy(const MachineInstr *Copy,
358 const MachineInstr *MoveImm,
359 const SIInstrInfo *TII,
360 unsigned &SMovOp,
361 int64_t &Imm) {
362 if (Copy->getOpcode() != AMDGPU::COPY)
363 return false;
364
365 if (!MoveImm->isMoveImmediate())
366 return false;
367
368 const MachineOperand *ImmOp =
369 TII->getNamedOperand(*MoveImm, AMDGPU::OpName::src0);
370 if (!ImmOp->isImm())
371 return false;
372
373 // FIXME: Handle copies with sub-regs.
374 if (Copy->getOperand(1).getSubReg())
375 return false;
376
377 switch (MoveImm->getOpcode()) {
378 default:
379 return false;
380 case AMDGPU::V_MOV_B32_e32:
381 case AMDGPU::AV_MOV_B32_IMM_PSEUDO:
382 SMovOp = AMDGPU::S_MOV_B32;
383 break;
384 case AMDGPU::V_MOV_B64_PSEUDO:
385 SMovOp = AMDGPU::S_MOV_B64_IMM_PSEUDO;
386 break;
387 }
388 Imm = ImmOp->getImm();
389 return true;
390}
391
392template <class UnaryPredicate>
394 const MachineBasicBlock *CutOff,
395 UnaryPredicate Predicate) {
396 if (MBB == CutOff)
397 return false;
398
401
402 while (!Worklist.empty()) {
403 MachineBasicBlock *MBB = Worklist.pop_back_val();
404
405 if (!Visited.insert(MBB).second)
406 continue;
407 if (MBB == CutOff)
408 continue;
409 if (Predicate(MBB))
410 return true;
411
412 Worklist.append(MBB->pred_begin(), MBB->pred_end());
413 }
414
415 return false;
416}
417
418// Checks if there is potential path From instruction To instruction.
419// If CutOff is specified and it sits in between of that path we ignore
420// a higher portion of the path and report it is not reachable.
421static bool isReachable(const MachineInstr *From,
422 const MachineInstr *To,
423 const MachineBasicBlock *CutOff,
425 if (MDT.dominates(From, To))
426 return true;
427
428 const MachineBasicBlock *MBBFrom = From->getParent();
429 const MachineBasicBlock *MBBTo = To->getParent();
430
431 // Do predecessor search.
432 // We should almost never get here since we do not usually produce M0 stores
433 // other than -1.
434 return searchPredecessors(MBBTo, CutOff, [MBBFrom]
435 (const MachineBasicBlock *MBB) { return MBB == MBBFrom; });
436}
437
438// Return the first non-prologue instruction in the block.
442 while (I != MBB->end() && TII->isBasicBlockPrologue(*I))
443 ++I;
444
445 return I;
446}
447
448// Hoist and merge identical SGPR initializations into a common predecessor.
449// This is intended to combine M0 initializations, but can work with any
450// SGPR. A VGPR cannot be processed since we cannot guarantee vector
451// executioon.
452static bool hoistAndMergeSGPRInits(unsigned Reg,
454 const TargetRegisterInfo *TRI,
456 const TargetInstrInfo *TII) {
457 // List of inits by immediate value.
458 using InitListMap = std::map<unsigned, std::list<MachineInstr *>>;
459 InitListMap Inits;
460 // List of clobbering instructions.
462 // List of instructions marked for deletion.
464
465 bool Changed = false;
466
467 for (auto &MI : MRI.def_instructions(Reg)) {
468 MachineOperand *Imm = nullptr;
469 for (auto &MO : MI.operands()) {
470 if ((MO.isReg() && ((MO.isDef() && MO.getReg() != Reg) || !MO.isDef())) ||
471 (!MO.isImm() && !MO.isReg()) || (MO.isImm() && Imm)) {
472 Imm = nullptr;
473 break;
474 }
475 if (MO.isImm())
476 Imm = &MO;
477 }
478 if (Imm)
479 Inits[Imm->getImm()].push_front(&MI);
480 else
481 Clobbers.push_back(&MI);
482 }
483
484 for (auto &Init : Inits) {
485 auto &Defs = Init.second;
486
487 for (auto I1 = Defs.begin(), E = Defs.end(); I1 != E; ) {
488 MachineInstr *MI1 = *I1;
489
490 for (auto I2 = std::next(I1); I2 != E; ) {
491 MachineInstr *MI2 = *I2;
492
493 // Check any possible interference
494 auto interferes = [&](MachineBasicBlock::iterator From,
495 MachineBasicBlock::iterator To) -> bool {
496
497 assert(MDT.dominates(&*To, &*From));
498
499 auto interferes = [&MDT, From, To](MachineInstr* &Clobber) -> bool {
500 const MachineBasicBlock *MBBFrom = From->getParent();
501 const MachineBasicBlock *MBBTo = To->getParent();
502 bool MayClobberFrom = isReachable(Clobber, &*From, MBBTo, MDT);
503 bool MayClobberTo = isReachable(Clobber, &*To, MBBTo, MDT);
504 if (!MayClobberFrom && !MayClobberTo)
505 return false;
506 if ((MayClobberFrom && !MayClobberTo) ||
507 (!MayClobberFrom && MayClobberTo))
508 return true;
509 // Both can clobber, this is not an interference only if both are
510 // dominated by Clobber and belong to the same block or if Clobber
511 // properly dominates To, given that To >> From, so it dominates
512 // both and located in a common dominator.
513 return !((MBBFrom == MBBTo &&
514 MDT.dominates(Clobber, &*From) &&
515 MDT.dominates(Clobber, &*To)) ||
516 MDT.properlyDominates(Clobber->getParent(), MBBTo));
517 };
518
519 return (llvm::any_of(Clobbers, interferes)) ||
520 (llvm::any_of(Inits, [&](InitListMap::value_type &C) {
521 return C.first != Init.first &&
522 llvm::any_of(C.second, interferes);
523 }));
524 };
525
526 if (MDT.dominates(MI1, MI2)) {
527 if (!interferes(MI2, MI1)) {
529 << "Erasing from "
530 << printMBBReference(*MI2->getParent()) << " " << *MI2);
531 MergedInstrs.insert(MI2);
532 Changed = true;
533 ++I2;
534 continue;
535 }
536 } else if (MDT.dominates(MI2, MI1)) {
537 if (!interferes(MI1, MI2)) {
539 << "Erasing from "
540 << printMBBReference(*MI1->getParent()) << " " << *MI1);
541 MergedInstrs.insert(MI1);
542 Changed = true;
543 ++I1;
544 break;
545 }
546 } else {
547 auto *MBB = MDT.findNearestCommonDominator(MI1->getParent(),
548 MI2->getParent());
549 if (!MBB) {
550 ++I2;
551 continue;
552 }
553
555 if (!interferes(MI1, I) && !interferes(MI2, I)) {
557 << "Erasing from "
558 << printMBBReference(*MI1->getParent()) << " " << *MI1
559 << "and moving from "
560 << printMBBReference(*MI2->getParent()) << " to "
561 << printMBBReference(*I->getParent()) << " " << *MI2);
562 I->getParent()->splice(I, MI2->getParent(), MI2);
563 MergedInstrs.insert(MI1);
564 Changed = true;
565 ++I1;
566 break;
567 }
568 }
569 ++I2;
570 }
571 ++I1;
572 }
573 }
574
575 // Remove initializations that were merged into another.
576 for (auto &Init : Inits) {
577 auto &Defs = Init.second;
578 auto I = Defs.begin();
579 while (I != Defs.end()) {
580 if (MergedInstrs.count(*I)) {
581 (*I)->eraseFromParent();
582 I = Defs.erase(I);
583 } else
584 ++I;
585 }
586 }
587
588 // Try to schedule SGPR initializations as early as possible in the MBB.
589 for (auto &Init : Inits) {
590 auto &Defs = Init.second;
591 for (auto *MI : Defs) {
592 auto *MBB = MI->getParent();
593 MachineInstr &BoundaryMI = *getFirstNonPrologue(MBB, TII);
595 // Check if B should actually be a boundary. If not set the previous
596 // instruction as the boundary instead.
597 if (!TII->isBasicBlockPrologue(*B))
598 B++;
599
600 auto R = std::next(MI->getReverseIterator());
601 const unsigned Threshold = 50;
602 // Search until B or Threshold for a place to insert the initialization.
603 for (unsigned I = 0; R != B && I < Threshold; ++R, ++I)
604 if (R->readsRegister(Reg, TRI) || R->definesRegister(Reg, TRI) ||
606 break;
607
608 // Move to directly after R.
609 if (&*--R != MI)
610 MBB->splice(*R, MBB, MI);
611 }
612 }
613
614 if (Changed)
615 MRI.clearKillFlags(Reg);
616
617 return Changed;
618}
619
620bool SIFixSGPRCopies::run(MachineFunction &MF) {
621 // Only need to run this in SelectionDAG path.
622 if (MF.getProperties().hasSelected())
623 return false;
624
626 MRI = &MF.getRegInfo();
627 TRI = ST.getRegisterInfo();
628 TII = ST.getInstrInfo();
629
630 for (MachineBasicBlock &MBB : MF) {
631 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
632 ++I) {
633 MachineInstr &MI = *I;
634
635 switch (MI.getOpcode()) {
636 default:
637 continue;
638 case AMDGPU::COPY: {
639 const TargetRegisterClass *SrcRC, *DstRC;
640 std::tie(SrcRC, DstRC) = getCopyRegClasses(MI, *TRI, *MRI);
641
642 if (isSGPRToVGPRCopy(SrcRC, DstRC, *TRI)) {
643 // Since VGPR to SGPR copies affect VGPR to SGPR copy
644 // score and, hence the lowering decision, let's try to get rid of
645 // them as early as possible
647 continue;
648
649 // Collect those not changed to try them after VGPR to SGPR copies
650 // lowering as there will be more opportunities.
651 S2VCopies.push_back(&MI);
652 }
653 if (!isVGPRToSGPRCopy(SrcRC, DstRC, *TRI))
654 continue;
655 if (lowerSpecialCase(MI, I))
656 continue;
657
658 analyzeVGPRToSGPRCopy(&MI);
659
660 break;
661 }
662 case AMDGPU::WQM:
663 case AMDGPU::STRICT_WQM:
664 case AMDGPU::SOFT_WQM:
665 case AMDGPU::STRICT_WWM:
666 case AMDGPU::INSERT_SUBREG:
667 case AMDGPU::PHI:
668 case AMDGPU::REG_SEQUENCE: {
669 if (TRI->isSGPRClass(TII->getOpRegClass(MI, 0))) {
670 for (MachineOperand &MO : MI.operands()) {
671 if (!MO.isReg() || !MO.getReg().isVirtual())
672 continue;
673 const TargetRegisterClass *SrcRC = MRI->getRegClass(MO.getReg());
674 if (SrcRC == &AMDGPU::VReg_1RegClass)
675 continue;
676
677 if (TRI->hasVectorRegisters(SrcRC)) {
678 const TargetRegisterClass *DestRC =
679 TRI->getEquivalentSGPRClass(SrcRC);
680 Register NewDst = MRI->createVirtualRegister(DestRC);
681 MachineBasicBlock *BlockToInsertCopy =
682 MI.isPHI() ? MI.getOperand(MO.getOperandNo() + 1).getMBB()
683 : &MBB;
684 MachineBasicBlock::iterator PointToInsertCopy =
685 MI.isPHI() ? BlockToInsertCopy->getFirstInstrTerminator() : I;
686
687 const DebugLoc &DL = MI.getDebugLoc();
688 if (!tryMoveVGPRConstToSGPR(MO, NewDst, BlockToInsertCopy,
689 PointToInsertCopy, DL)) {
690 MachineInstr *NewCopy =
691 BuildMI(*BlockToInsertCopy, PointToInsertCopy, DL,
692 TII->get(AMDGPU::COPY), NewDst)
693 .addReg(MO.getReg());
694 MO.setReg(NewDst);
695 analyzeVGPRToSGPRCopy(NewCopy);
696 PHISources.insert(NewCopy);
697 }
698 }
699 }
700 }
701
702 if (MI.isPHI())
703 PHINodes.push_back(&MI);
704 else if (MI.isRegSequence())
705 RegSequences.push_back(&MI);
706
707 break;
708 }
709 case AMDGPU::V_WRITELANE_B32: {
710 // Some architectures allow more than one constant bus access without
711 // SGPR restriction
712 if (ST.getConstantBusLimit(MI.getOpcode()) != 1)
713 break;
714
715 // Writelane is special in that it can use SGPR and M0 (which would
716 // normally count as using the constant bus twice - but in this case it
717 // is allowed since the lane selector doesn't count as a use of the
718 // constant bus). However, it is still required to abide by the 1 SGPR
719 // rule. Apply a fix here as we might have multiple SGPRs after
720 // legalizing VGPRs to SGPRs
721 int Src0Idx =
722 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
723 int Src1Idx =
724 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src1);
725 MachineOperand &Src0 = MI.getOperand(Src0Idx);
726 MachineOperand &Src1 = MI.getOperand(Src1Idx);
727
728 // Check to see if the instruction violates the 1 SGPR rule
729 if ((Src0.isReg() && TRI->isSGPRReg(*MRI, Src0.getReg()) &&
730 Src0.getReg() != AMDGPU::M0) &&
731 (Src1.isReg() && TRI->isSGPRReg(*MRI, Src1.getReg()) &&
732 Src1.getReg() != AMDGPU::M0)) {
733
734 // Check for trivially easy constant prop into one of the operands
735 // If this is the case then perform the operation now to resolve SGPR
736 // issue. If we don't do that here we will always insert a mov to m0
737 // that can't be resolved in later operand folding pass
738 bool Resolved = false;
739 for (MachineOperand *MO : {&Src0, &Src1}) {
740 if (MO->getReg().isVirtual()) {
741 MachineInstr *DefMI = MRI->getVRegDef(MO->getReg());
742 if (DefMI && TII->isFoldableCopy(*DefMI)) {
743 const MachineOperand &Def = DefMI->getOperand(0);
744 if (Def.isReg() &&
745 MO->getReg() == Def.getReg() &&
746 MO->getSubReg() == Def.getSubReg()) {
747 const MachineOperand &Copied = DefMI->getOperand(1);
748 if (Copied.isImm() &&
749 TII->isInlineConstant(APInt(64, Copied.getImm(), true))) {
750 MO->ChangeToImmediate(Copied.getImm());
751 Resolved = true;
752 break;
753 }
754 }
755 }
756 }
757 }
758
759 if (!Resolved) {
760 // Haven't managed to resolve by replacing an SGPR with an immediate
761 // Move src1 to be in M0
762 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
763 TII->get(AMDGPU::COPY), AMDGPU::M0)
764 .add(Src1);
765 Src1.ChangeToRegister(AMDGPU::M0, false);
766 }
767 }
768 break;
769 }
770 }
771 }
772 }
773
774 lowerVGPR2SGPRCopies(MF);
775 // Postprocessing
776 fixSCCCopies(MF);
777 for (auto *MI : S2VCopies) {
778 // Check if it is still valid
779 if (MI->isCopy()) {
780 const TargetRegisterClass *SrcRC, *DstRC;
781 std::tie(SrcRC, DstRC) = getCopyRegClasses(*MI, *TRI, *MRI);
782 if (isSGPRToVGPRCopy(SrcRC, DstRC, *TRI))
784 }
785 }
786 for (auto *MI : RegSequences) {
787 // Check if it is still valid
788 if (MI->isRegSequence())
790 }
791 for (auto *MI : PHINodes) {
792 processPHINode(*MI);
793 }
794 if (MF.getTarget().getOptLevel() > CodeGenOptLevel::None && EnableM0Merge)
795 hoistAndMergeSGPRInits(AMDGPU::M0, *MRI, TRI, *MDT, TII);
796
797 SiblingPenalty.clear();
798 V2SCopies.clear();
799 SCCCopies.clear();
800 RegSequences.clear();
801 PHINodes.clear();
802 S2VCopies.clear();
803 PHISources.clear();
804
805 return true;
806}
807
808void SIFixSGPRCopies::processPHINode(MachineInstr &MI) {
809 bool AllAGPRUses = true;
812 SetVector<MachineInstr *> PHIOperands;
813 worklist.insert(&MI);
814 Visited.insert(&MI);
815 // HACK to make MIR tests with no uses happy
816 bool HasUses = false;
817 while (!worklist.empty()) {
818 const MachineInstr *Instr = worklist.pop_back_val();
819 Register Reg = Instr->getOperand(0).getReg();
820 for (const auto &Use : MRI->use_operands(Reg)) {
821 HasUses = true;
822 const MachineInstr *UseMI = Use.getParent();
823 AllAGPRUses &= (UseMI->isCopy() &&
824 TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg())) ||
825 TRI->isAGPR(*MRI, Use.getReg());
826 if (UseMI->isCopy() || UseMI->isRegSequence()) {
827 if (Visited.insert(UseMI).second)
828 worklist.insert(UseMI);
829
830 continue;
831 }
832 }
833 }
834
835 Register PHIRes = MI.getOperand(0).getReg();
836 const TargetRegisterClass *RC0 = MRI->getRegClass(PHIRes);
837 if (HasUses && AllAGPRUses && !TRI->isAGPRClass(RC0)) {
838 LLVM_DEBUG(dbgs() << "Moving PHI to AGPR: " << MI);
839 MRI->setRegClass(PHIRes, TRI->getEquivalentAGPRClass(RC0));
840 for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
841 MachineInstr *DefMI = MRI->getVRegDef(MI.getOperand(I).getReg());
842 if (DefMI && DefMI->isPHI())
843 PHIOperands.insert(DefMI);
844 }
845 }
846
847 if (TRI->isVectorRegister(*MRI, PHIRes) ||
848 RC0 == &AMDGPU::VReg_1RegClass) {
849 LLVM_DEBUG(dbgs() << "Legalizing PHI: " << MI);
850 TII->legalizeOperands(MI, MDT);
851 }
852
853 // Propagate register class back to PHI operands which are PHI themselves.
854 while (!PHIOperands.empty()) {
855 processPHINode(*PHIOperands.pop_back_val());
856 }
857}
858
859bool SIFixSGPRCopies::tryMoveVGPRConstToSGPR(
860 MachineOperand &MaybeVGPRConstMO, Register DstReg,
861 MachineBasicBlock *BlockToInsertTo,
862 MachineBasicBlock::iterator PointToInsertTo, const DebugLoc &DL) {
863
864 MachineInstr *DefMI = MRI->getVRegDef(MaybeVGPRConstMO.getReg());
865 if (!DefMI || !DefMI->isMoveImmediate())
866 return false;
867
868 MachineOperand *SrcConst = TII->getNamedOperand(*DefMI, AMDGPU::OpName::src0);
869 if (SrcConst->isReg())
870 return false;
871
872 const TargetRegisterClass *SrcRC =
873 MRI->getRegClass(MaybeVGPRConstMO.getReg());
874 unsigned MoveSize = TRI->getRegSizeInBits(*SrcRC);
875 unsigned MoveOp = MoveSize == 64 ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
876 BuildMI(*BlockToInsertTo, PointToInsertTo, DL, TII->get(MoveOp), DstReg)
877 .add(*SrcConst);
878 if (MRI->hasOneUse(MaybeVGPRConstMO.getReg()))
880 MaybeVGPRConstMO.setReg(DstReg);
881 return true;
882}
883
884bool SIFixSGPRCopies::lowerSpecialCase(MachineInstr &MI,
886 Register DstReg = MI.getOperand(0).getReg();
887 Register SrcReg = MI.getOperand(1).getReg();
888 if (!DstReg.isVirtual()) {
889 // If the destination register is a physical register there isn't
890 // really much we can do to fix this.
891 // Some special instructions use M0 as an input. Some even only use
892 // the first lane. Insert a readfirstlane and hope for the best.
893 if (DstReg == AMDGPU::M0 &&
894 TRI->hasVectorRegisters(MRI->getRegClass(SrcReg))) {
895 Register TmpReg =
896 MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
897 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
898 TII->get(AMDGPU::V_READFIRSTLANE_B32), TmpReg)
899 .add(MI.getOperand(1));
900 MI.getOperand(1).setReg(TmpReg);
901 } else if (tryMoveVGPRConstToSGPR(MI.getOperand(1), DstReg, MI.getParent(),
902 MI, MI.getDebugLoc())) {
903 I = std::next(I);
904 MI.eraseFromParent();
905 }
906 return true;
907 }
908 if (!SrcReg.isVirtual() || TRI->isAGPR(*MRI, SrcReg)) {
909 SIInstrWorklist worklist;
910 worklist.insert(&MI);
911 TII->moveToVALU(worklist, MDT);
912 return true;
913 }
914
915 unsigned SMovOp;
916 int64_t Imm;
917 // If we are just copying an immediate, we can replace the copy with
918 // s_mov_b32.
919 if (isSafeToFoldImmIntoCopy(&MI, MRI->getVRegDef(SrcReg), TII, SMovOp, Imm)) {
920 MI.getOperand(1).ChangeToImmediate(Imm);
921 MI.addImplicitDefUseOperands(*MI.getParent()->getParent());
922 MI.setDesc(TII->get(SMovOp));
923 return true;
924 }
925 return false;
926}
927
928void SIFixSGPRCopies::analyzeVGPRToSGPRCopy(MachineInstr* MI) {
929 if (PHISources.contains(MI))
930 return;
931 Register DstReg = MI->getOperand(0).getReg();
932 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
933
934 V2SCopyInfo Info(getNextVGPRToSGPRCopyId(), MI,
935 TRI->getRegSizeInBits(*DstRC));
936 SmallVector<MachineInstr *, 8> AnalysisWorklist;
937 // Needed because the SSA is not a tree but a graph and may have
938 // forks and joins. We should not then go same way twice.
940 AnalysisWorklist.push_back(Info.Copy);
941 while (!AnalysisWorklist.empty()) {
942
943 MachineInstr *Inst = AnalysisWorklist.pop_back_val();
944
945 if (!Visited.insert(Inst).second)
946 continue;
947
948 // Copies and REG_SEQUENCE do not contribute to the final assembly
949 // So, skip them but take care of the SGPR to VGPR copies bookkeeping.
950 if (Inst->isRegSequence() &&
951 TRI->isVGPR(*MRI, Inst->getOperand(0).getReg())) {
952 Info.NumSVCopies++;
953 continue;
954 }
955 if (Inst->isCopy()) {
956 const TargetRegisterClass *SrcRC, *DstRC;
957 std::tie(SrcRC, DstRC) = getCopyRegClasses(*Inst, *TRI, *MRI);
958 if (isSGPRToVGPRCopy(SrcRC, DstRC, *TRI) &&
960 Info.NumSVCopies++;
961 continue;
962 }
963 }
964
965 SiblingPenalty[Inst].insert(Info.ID);
966
968 if ((TII->isSALU(*Inst) && Inst->isCompare()) ||
969 (Inst->isCopy() && Inst->getOperand(0).getReg() == AMDGPU::SCC)) {
970 auto I = Inst->getIterator();
971 auto E = Inst->getParent()->end();
972 while (++I != E &&
973 !I->findRegisterDefOperand(AMDGPU::SCC, /*TRI=*/nullptr)) {
974 if (I->readsRegister(AMDGPU::SCC, /*TRI=*/nullptr))
975 Users.push_back(&*I);
976 }
977 } else if (Inst->getNumExplicitDefs() != 0) {
978 Register Reg = Inst->getOperand(0).getReg();
979 if (Reg.isVirtual() && TRI->isSGPRReg(*MRI, Reg) && !TII->isVALU(*Inst)) {
980 for (auto &U : MRI->use_instructions(Reg))
981 Users.push_back(&U);
982 }
983 }
984 for (auto *U : Users) {
985 if (TII->isSALU(*U))
986 Info.SChain.insert(U);
987 AnalysisWorklist.push_back(U);
988 }
989 }
990 V2SCopies[Info.ID] = Info;
991}
992
993// The main function that computes the VGPR to SGPR copy score
994// and determines copy further lowering way: v_readfirstlane_b32 or moveToVALU
995bool SIFixSGPRCopies::needToBeConvertedToVALU(V2SCopyInfo *Info) {
996 if (Info->SChain.empty()) {
997 Info->Score = 0;
998 return true;
999 }
1000 Info->Siblings = SiblingPenalty[*llvm::max_element(
1001 Info->SChain, [&](MachineInstr *A, MachineInstr *B) -> bool {
1002 return SiblingPenalty[A].size() < SiblingPenalty[B].size();
1003 })];
1004 Info->Siblings.remove_if([&](unsigned ID) { return ID == Info->ID; });
1005 // The loop below computes the number of another VGPR to SGPR V2SCopies
1006 // which contribute to the current copy SALU chain. We assume that all the
1007 // V2SCopies with the same source virtual register will be squashed to one
1008 // by regalloc. Also we take care of the V2SCopies of the differnt subregs
1009 // of the same register.
1011 for (auto J : Info->Siblings) {
1012 auto *InfoIt = V2SCopies.find(J);
1013 if (InfoIt != V2SCopies.end()) {
1014 MachineInstr *SiblingCopy = InfoIt->second.Copy;
1015 if (SiblingCopy->isImplicitDef())
1016 // the COPY has already been MoveToVALUed
1017 continue;
1018
1019 SrcRegs.insert(std::pair(SiblingCopy->getOperand(1).getReg(),
1020 SiblingCopy->getOperand(1).getSubReg()));
1021 }
1022 }
1023 Info->SiblingPenalty = SrcRegs.size();
1024
1025 unsigned Penalty =
1026 Info->NumSVCopies + Info->SiblingPenalty + Info->NumReadfirstlanes;
1027 unsigned Profit = Info->SChain.size();
1028 Info->Score = Penalty > Profit ? 0 : Profit - Penalty;
1029 Info->NeedToBeConvertedToVALU = Info->Score < 3;
1030 return Info->NeedToBeConvertedToVALU;
1031}
1032
1033void SIFixSGPRCopies::lowerVGPR2SGPRCopies(MachineFunction &MF) {
1034
1035 SmallVector<unsigned, 8> LoweringWorklist;
1036 for (auto &C : V2SCopies) {
1037 if (needToBeConvertedToVALU(&C.second))
1038 LoweringWorklist.push_back(C.second.ID);
1039 }
1040
1041 // Store all the V2S copy instructions that need to be moved to VALU
1042 // in the Copies worklist.
1044
1045 while (!LoweringWorklist.empty()) {
1046 unsigned CurID = LoweringWorklist.pop_back_val();
1047 auto *CurInfoIt = V2SCopies.find(CurID);
1048 if (CurInfoIt != V2SCopies.end()) {
1049 V2SCopyInfo C = CurInfoIt->second;
1050 LLVM_DEBUG(dbgs() << "Processing ...\n"; C.dump());
1051 for (auto S : C.Siblings) {
1052 auto *SibInfoIt = V2SCopies.find(S);
1053 if (SibInfoIt != V2SCopies.end()) {
1054 V2SCopyInfo &SI = SibInfoIt->second;
1055 LLVM_DEBUG(dbgs() << "Sibling:\n"; SI.dump());
1056 if (!SI.NeedToBeConvertedToVALU) {
1057 SI.SChain.set_subtract(C.SChain);
1058 if (needToBeConvertedToVALU(&SI))
1059 LoweringWorklist.push_back(SI.ID);
1060 }
1061 SI.Siblings.remove_if([&](unsigned ID) { return ID == C.ID; });
1062 }
1063 }
1064 LLVM_DEBUG(dbgs() << "V2S copy " << *C.Copy
1065 << " is being turned to VALU\n");
1066 // TODO: MapVector::erase is inefficient. Do bulk removal with remove_if
1067 // instead.
1068 V2SCopies.erase(C.ID);
1069 Copies.insert(C.Copy);
1070 }
1071 }
1072
1073 TII->moveToVALU(Copies, MDT);
1074 Copies.clear();
1075
1076 // Now do actual lowering
1077 for (auto C : V2SCopies) {
1078 MachineInstr *MI = C.second.Copy;
1079 MachineBasicBlock *MBB = MI->getParent();
1080 // We decide to turn V2S copy to v_readfirstlane_b32
1081 // remove it from the V2SCopies and remove it from all its siblings
1082 LLVM_DEBUG(dbgs() << "V2S copy " << *MI
1083 << " is being turned to v_readfirstlane_b32"
1084 << " Score: " << C.second.Score << "\n");
1085 Register DstReg = MI->getOperand(0).getReg();
1086 MRI->constrainRegClass(DstReg, &AMDGPU::SReg_32_XM0RegClass);
1087
1088 Register SrcReg = MI->getOperand(1).getReg();
1089 unsigned SubReg = MI->getOperand(1).getSubReg();
1090 const TargetRegisterClass *SrcRC =
1091 TRI->getRegClassForOperandReg(*MRI, MI->getOperand(1));
1092 size_t SrcSize = TRI->getRegSizeInBits(*SrcRC);
1093 if (SrcSize == 16) {
1095 "We do not expect to see 16-bit copies from VGPR to SGPR unless "
1096 "we have 16-bit VGPRs");
1097 assert(MRI->getRegClass(DstReg) == &AMDGPU::SReg_32RegClass ||
1098 MRI->getRegClass(DstReg) == &AMDGPU::SReg_32_XM0RegClass);
1099 // There is no V_READFIRSTLANE_B16, so legalize the dst/src reg to 32 bits
1100 MRI->setRegClass(DstReg, &AMDGPU::SReg_32_XM0RegClass);
1101 Register VReg32 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1102 const DebugLoc &DL = MI->getDebugLoc();
1103 Register Undef = MRI->createVirtualRegister(&AMDGPU::VGPR_16RegClass);
1104 BuildMI(*MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
1105 BuildMI(*MBB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), VReg32)
1106 .addReg(SrcReg, 0, SubReg)
1107 .addImm(AMDGPU::lo16)
1108 .addReg(Undef)
1109 .addImm(AMDGPU::hi16);
1110 BuildMI(*MBB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
1111 .addReg(VReg32);
1112 } else if (SrcSize == 32) {
1113 auto MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
1114 TII->get(AMDGPU::V_READFIRSTLANE_B32), DstReg);
1115 MIB.addReg(SrcReg, 0, SubReg);
1116 } else {
1117 auto Result = BuildMI(*MBB, MI, MI->getDebugLoc(),
1118 TII->get(AMDGPU::REG_SEQUENCE), DstReg);
1119 int N = TRI->getRegSizeInBits(*SrcRC) / 32;
1120 for (int i = 0; i < N; i++) {
1121 Register PartialSrc = TII->buildExtractSubReg(
1122 Result, *MRI, MI->getOperand(1), SrcRC,
1123 TRI->getSubRegFromChannel(i), &AMDGPU::VGPR_32RegClass);
1124 Register PartialDst =
1125 MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1126 BuildMI(*MBB, *Result, Result->getDebugLoc(),
1127 TII->get(AMDGPU::V_READFIRSTLANE_B32), PartialDst)
1128 .addReg(PartialSrc);
1129 Result.addReg(PartialDst).addImm(TRI->getSubRegFromChannel(i));
1130 }
1131 }
1132 MI->eraseFromParent();
1133 }
1134}
1135
1136void SIFixSGPRCopies::fixSCCCopies(MachineFunction &MF) {
1137 bool IsWave32 = MF.getSubtarget<GCNSubtarget>().isWave32();
1138 for (MachineBasicBlock &MBB : MF) {
1139 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1140 ++I) {
1141 MachineInstr &MI = *I;
1142 // May already have been lowered.
1143 if (!MI.isCopy())
1144 continue;
1145 Register SrcReg = MI.getOperand(1).getReg();
1146 Register DstReg = MI.getOperand(0).getReg();
1147 if (SrcReg == AMDGPU::SCC) {
1148 Register SCCCopy =
1149 MRI->createVirtualRegister(TRI->getWaveMaskRegClass());
1150 I = BuildMI(*MI.getParent(), std::next(MachineBasicBlock::iterator(MI)),
1151 MI.getDebugLoc(),
1152 TII->get(IsWave32 ? AMDGPU::S_CSELECT_B32
1153 : AMDGPU::S_CSELECT_B64),
1154 SCCCopy)
1155 .addImm(-1)
1156 .addImm(0);
1157 I = BuildMI(*MI.getParent(), std::next(I), I->getDebugLoc(),
1158 TII->get(AMDGPU::COPY), DstReg)
1159 .addReg(SCCCopy);
1160 MI.eraseFromParent();
1161 continue;
1162 }
1163 if (DstReg == AMDGPU::SCC) {
1164 unsigned Opcode = IsWave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
1165 Register Exec = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
1166 Register Tmp = MRI->createVirtualRegister(TRI->getBoolRC());
1167 I = BuildMI(*MI.getParent(), std::next(MachineBasicBlock::iterator(MI)),
1168 MI.getDebugLoc(), TII->get(Opcode))
1169 .addReg(Tmp, getDefRegState(true))
1170 .addReg(SrcReg)
1171 .addReg(Exec);
1172 MI.eraseFromParent();
1173 }
1174 }
1175 }
1176}
1177
1182 SIFixSGPRCopies Impl(&MDT);
1183 bool Changed = Impl.run(MF);
1184 if (!Changed)
1185 return PreservedAnalyses::all();
1186
1187 // TODO: We could detect CFG changed.
1189 return PA;
1190}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
Falkor HW Prefetch Fix
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
iv Induction Variable Users
Definition: IVUsers.cpp:48
#define I(x, y, z)
Definition: MD5.cpp:58
Register const TargetRegisterInfo * TRI
MachineInstr unsigned OpIdx
#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
static std::pair< const TargetRegisterClass *, const TargetRegisterClass * > getCopyRegClasses(const MachineInstr &Copy, const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI)
SI Fix SGPR copies
static cl::opt< bool > EnableM0Merge("amdgpu-enable-merge-m0", cl::desc("Merge and hoist M0 initializations"), cl::init(true))
static bool hoistAndMergeSGPRInits(unsigned Reg, const MachineRegisterInfo &MRI, const TargetRegisterInfo *TRI, MachineDominatorTree &MDT, const TargetInstrInfo *TII)
static bool foldVGPRCopyIntoRegSequence(MachineInstr &MI, const SIRegisterInfo *TRI, const SIInstrInfo *TII, MachineRegisterInfo &MRI)
bool searchPredecessors(const MachineBasicBlock *MBB, const MachineBasicBlock *CutOff, UnaryPredicate Predicate)
static bool isReachable(const MachineInstr *From, const MachineInstr *To, const MachineBasicBlock *CutOff, MachineDominatorTree &MDT)
static bool isVGPRToSGPRCopy(const TargetRegisterClass *SrcRC, const TargetRegisterClass *DstRC, const SIRegisterInfo &TRI)
static bool tryChangeVGPRtoSGPRinCopy(MachineInstr &MI, const SIRegisterInfo *TRI, const SIInstrInfo *TII)
static bool isSGPRToVGPRCopy(const TargetRegisterClass *SrcRC, const TargetRegisterClass *DstRC, const SIRegisterInfo &TRI)
static bool isSafeToFoldImmIntoCopy(const MachineInstr *Copy, const MachineInstr *MoveImm, const SIInstrInfo *TII, unsigned &SMovOp, int64_t &Imm)
#define DEBUG_TYPE
static MachineBasicBlock::iterator getFirstNonPrologue(MachineBasicBlock *MBB, const TargetInstrInfo *TII)
SI Lower i1 Copies
#define LLVM_DEBUG(...)
Definition: Debug.h:119
bool useRealTrue16Insts() const
Return true if real (non-fake) variants of True16 instructions using 16-bit registers should be code-...
Class for arbitrary precision integers.
Definition: APInt.h:78
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:412
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:270
A debug info location.
Definition: DebugLoc.h:124
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:314
bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const override
Test if the given instruction should be considered a scheduling boundary.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:238
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
iterator_range< pred_iterator > predecessors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
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.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Definition: MachineInstr.h:72
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:587
bool isImplicitDef() const
bool isCopy() const
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:359
unsigned getOperandNo(const_mop_iterator I) const
Returns the number of the operand iterator I points to.
Definition: MachineInstr.h:773
bool isCompare(QueryType Type=IgnoreBundle) const
Return true if this instruction is a comparison.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:584
bool isRegSequence() const
LLVM_ABI unsigned getNumExplicitDefs() const
Returns the number of non-implicit definitions.
bool isMoveImmediate(QueryType Type=IgnoreBundle) const
Return true if this instruction is a move immediate (including conditional moves) instruction.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool isPHI() const
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:595
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_ABI void ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags=0)
ChangeToImmediate - Replace this operand with a new immediate operand of the specified value.
LLVM_ABI void ChangeToRegister(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isDebug=false)
ChangeToRegister - Replace this operand with a new register operand of the specified value.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:85
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:74
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:78
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A vector that has set insertion semantics.
Definition: SetVector.h:59
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:104
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:99
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:168
value_type pop_back_val()
Definition: SetVector.h:296
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:470
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:401
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:182
size_type size() const
Definition: SmallSet.h:171
bool empty() const
Definition: SmallVector.h:82
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:684
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:194
self_iterator getIterator()
Definition: ilist_node.h:134
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ Resolved
Queried, materialization begun.
NodeAddr< InstrNode * > Instr
Definition: RDFGraph.h:389
NodeAddr< DefNode * > Def
Definition: RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
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:1751
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
unsigned getDefRegState(bool B)
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:2049
char & SIFixSGPRCopiesLegacyID
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
FunctionPass * createSIFixSGPRCopiesLegacyPass()
#define N
Utility to store machine instructions worklist.
Definition: SIInstrInfo.h:52
void insert(MachineInstr *MI)