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 {
122 MachineDominatorTree *MDT;
123 SmallVector<MachineInstr*, 4> SCCCopies;
124 SmallVector<MachineInstr*, 4> RegSequences;
125 SmallVector<MachineInstr*, 4> PHINodes;
126 SmallVector<MachineInstr*, 4> S2VCopies;
127 unsigned NextVGPRToSGPRCopyID = 0;
128 MapVector<unsigned, V2SCopyInfo> V2SCopies;
129 DenseMap<MachineInstr *, SetVector<unsigned>> SiblingPenalty;
130 DenseSet<MachineInstr *> PHISources;
131
132public:
133 MachineRegisterInfo *MRI;
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 {
170 MachineDominatorTree *MDT =
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 {
179 AU.addRequired<MachineDominatorTreeWrapperPass>();
180 AU.addPreserved<MachineDominatorTreeWrapperPass>();
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
400 SmallVector<MachineBasicBlock *, 4> Worklist(MBB->predecessors());
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.
441 MachineBasicBlock::iterator I = MBB->getFirstNonPHI();
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) ||
605 TII->isSchedulingBoundary(*R, MBB, *MBB->getParent()))
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
625 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
626 MRI = &MF.getRegInfo();
627 TRI = ST.getRegisterInfo();
628 TII = ST.getInstrInfo();
629
630 // Instructions to re-legalize after changing register classes
631 SmallVector<MachineInstr *, 8> Relegalize;
632
633 for (MachineBasicBlock &MBB : MF) {
634 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
635 ++I) {
636 MachineInstr &MI = *I;
637
638 switch (MI.getOpcode()) {
639 default:
640 // scale_src has a register class restricted to low 256 VGPRs, changing
641 // registers to VGPR may not take it into acount.
642 if (TII->isWMMA(MI) &&
643 AMDGPU::hasNamedOperand(MI.getOpcode(), AMDGPU::OpName::scale_src0))
644 Relegalize.push_back(&MI);
645 continue;
646 case AMDGPU::COPY: {
647 const TargetRegisterClass *SrcRC, *DstRC;
648 std::tie(SrcRC, DstRC) = getCopyRegClasses(MI, *TRI, *MRI);
649
650 if (isSGPRToVGPRCopy(SrcRC, DstRC, *TRI)) {
651 // Since VGPR to SGPR copies affect VGPR to SGPR copy
652 // score and, hence the lowering decision, let's try to get rid of
653 // them as early as possible
655 continue;
656
657 // Collect those not changed to try them after VGPR to SGPR copies
658 // lowering as there will be more opportunities.
659 S2VCopies.push_back(&MI);
660 }
661 if (!isVGPRToSGPRCopy(SrcRC, DstRC, *TRI))
662 continue;
663 if (lowerSpecialCase(MI, I))
664 continue;
665
666 analyzeVGPRToSGPRCopy(&MI);
667
668 break;
669 }
670 case AMDGPU::WQM:
671 case AMDGPU::STRICT_WQM:
672 case AMDGPU::SOFT_WQM:
673 case AMDGPU::STRICT_WWM:
674 case AMDGPU::INSERT_SUBREG:
675 case AMDGPU::PHI:
676 case AMDGPU::REG_SEQUENCE: {
677 if (TRI->isSGPRClass(TII->getOpRegClass(MI, 0))) {
678 for (MachineOperand &MO : MI.operands()) {
679 if (!MO.isReg() || !MO.getReg().isVirtual())
680 continue;
681 const TargetRegisterClass *SrcRC = MRI->getRegClass(MO.getReg());
682 if (SrcRC == &AMDGPU::VReg_1RegClass)
683 continue;
684
685 if (TRI->hasVectorRegisters(SrcRC)) {
686 const TargetRegisterClass *DestRC =
687 TRI->getEquivalentSGPRClass(SrcRC);
688 Register NewDst = MRI->createVirtualRegister(DestRC);
689 MachineBasicBlock *BlockToInsertCopy =
690 MI.isPHI() ? MI.getOperand(MO.getOperandNo() + 1).getMBB()
691 : &MBB;
692 MachineBasicBlock::iterator PointToInsertCopy =
693 MI.isPHI() ? BlockToInsertCopy->getFirstInstrTerminator() : I;
694
695 const DebugLoc &DL = MI.getDebugLoc();
696 if (!tryMoveVGPRConstToSGPR(MO, NewDst, BlockToInsertCopy,
697 PointToInsertCopy, DL)) {
698 MachineInstr *NewCopy =
699 BuildMI(*BlockToInsertCopy, PointToInsertCopy, DL,
700 TII->get(AMDGPU::COPY), NewDst)
701 .addReg(MO.getReg());
702 MO.setReg(NewDst);
703 analyzeVGPRToSGPRCopy(NewCopy);
704 PHISources.insert(NewCopy);
705 }
706 }
707 }
708 }
709
710 if (MI.isPHI())
711 PHINodes.push_back(&MI);
712 else if (MI.isRegSequence())
713 RegSequences.push_back(&MI);
714
715 break;
716 }
717 case AMDGPU::V_WRITELANE_B32: {
718 // Some architectures allow more than one constant bus access without
719 // SGPR restriction
720 if (ST.getConstantBusLimit(MI.getOpcode()) != 1)
721 break;
722
723 // Writelane is special in that it can use SGPR and M0 (which would
724 // normally count as using the constant bus twice - but in this case it
725 // is allowed since the lane selector doesn't count as a use of the
726 // constant bus). However, it is still required to abide by the 1 SGPR
727 // rule. Apply a fix here as we might have multiple SGPRs after
728 // legalizing VGPRs to SGPRs
729 int Src0Idx =
730 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
731 int Src1Idx =
732 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src1);
733 MachineOperand &Src0 = MI.getOperand(Src0Idx);
734 MachineOperand &Src1 = MI.getOperand(Src1Idx);
735
736 // Check to see if the instruction violates the 1 SGPR rule
737 if ((Src0.isReg() && TRI->isSGPRReg(*MRI, Src0.getReg()) &&
738 Src0.getReg() != AMDGPU::M0) &&
739 (Src1.isReg() && TRI->isSGPRReg(*MRI, Src1.getReg()) &&
740 Src1.getReg() != AMDGPU::M0)) {
741
742 // Check for trivially easy constant prop into one of the operands
743 // If this is the case then perform the operation now to resolve SGPR
744 // issue. If we don't do that here we will always insert a mov to m0
745 // that can't be resolved in later operand folding pass
746 bool Resolved = false;
747 for (MachineOperand *MO : {&Src0, &Src1}) {
748 if (MO->getReg().isVirtual()) {
749 MachineInstr *DefMI = MRI->getVRegDef(MO->getReg());
750 if (DefMI && TII->isFoldableCopy(*DefMI)) {
751 const MachineOperand &Def = DefMI->getOperand(0);
752 if (Def.isReg() &&
753 MO->getReg() == Def.getReg() &&
754 MO->getSubReg() == Def.getSubReg()) {
755 const MachineOperand &Copied = DefMI->getOperand(1);
756 if (Copied.isImm() &&
757 TII->isInlineConstant(APInt(64, Copied.getImm(), true))) {
758 MO->ChangeToImmediate(Copied.getImm());
759 Resolved = true;
760 break;
761 }
762 }
763 }
764 }
765 }
766
767 if (!Resolved) {
768 // Haven't managed to resolve by replacing an SGPR with an immediate
769 // Move src1 to be in M0
770 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
771 TII->get(AMDGPU::COPY), AMDGPU::M0)
772 .add(Src1);
773 Src1.ChangeToRegister(AMDGPU::M0, false);
774 }
775 }
776 break;
777 }
778 }
779 }
780 }
781
782 lowerVGPR2SGPRCopies(MF);
783 // Postprocessing
784 fixSCCCopies(MF);
785 for (auto *MI : S2VCopies) {
786 // Check if it is still valid
787 if (MI->isCopy()) {
788 const TargetRegisterClass *SrcRC, *DstRC;
789 std::tie(SrcRC, DstRC) = getCopyRegClasses(*MI, *TRI, *MRI);
790 if (isSGPRToVGPRCopy(SrcRC, DstRC, *TRI))
792 }
793 }
794 for (auto *MI : RegSequences) {
795 // Check if it is still valid
796 if (MI->isRegSequence())
798 }
799 for (auto *MI : PHINodes) {
800 processPHINode(*MI);
801 }
802 while (!Relegalize.empty())
803 TII->legalizeOperands(*Relegalize.pop_back_val(), MDT);
804
805 if (MF.getTarget().getOptLevel() > CodeGenOptLevel::None && EnableM0Merge)
806 hoistAndMergeSGPRInits(AMDGPU::M0, *MRI, TRI, *MDT, TII);
807
808 SiblingPenalty.clear();
809 V2SCopies.clear();
810 SCCCopies.clear();
811 RegSequences.clear();
812 PHINodes.clear();
813 S2VCopies.clear();
814 PHISources.clear();
815
816 return true;
817}
818
819void SIFixSGPRCopies::processPHINode(MachineInstr &MI) {
820 bool AllAGPRUses = true;
821 SetVector<const MachineInstr *> worklist;
822 SmallPtrSet<const MachineInstr *, 4> Visited;
823 SetVector<MachineInstr *> PHIOperands;
824 worklist.insert(&MI);
825 Visited.insert(&MI);
826 // HACK to make MIR tests with no uses happy
827 bool HasUses = false;
828 while (!worklist.empty()) {
829 const MachineInstr *Instr = worklist.pop_back_val();
830 Register Reg = Instr->getOperand(0).getReg();
831 for (const auto &Use : MRI->use_operands(Reg)) {
832 HasUses = true;
833 const MachineInstr *UseMI = Use.getParent();
834 AllAGPRUses &= (UseMI->isCopy() &&
835 TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg())) ||
836 TRI->isAGPR(*MRI, Use.getReg());
837 if (UseMI->isCopy() || UseMI->isRegSequence()) {
838 if (Visited.insert(UseMI).second)
839 worklist.insert(UseMI);
840
841 continue;
842 }
843 }
844 }
845
846 Register PHIRes = MI.getOperand(0).getReg();
847 const TargetRegisterClass *RC0 = MRI->getRegClass(PHIRes);
848 if (HasUses && AllAGPRUses && !TRI->isAGPRClass(RC0)) {
849 LLVM_DEBUG(dbgs() << "Moving PHI to AGPR: " << MI);
850 MRI->setRegClass(PHIRes, TRI->getEquivalentAGPRClass(RC0));
851 for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
852 MachineInstr *DefMI = MRI->getVRegDef(MI.getOperand(I).getReg());
853 if (DefMI && DefMI->isPHI())
854 PHIOperands.insert(DefMI);
855 }
856 }
857
858 if (TRI->isVectorRegister(*MRI, PHIRes) ||
859 RC0 == &AMDGPU::VReg_1RegClass) {
860 LLVM_DEBUG(dbgs() << "Legalizing PHI: " << MI);
861 TII->legalizeOperands(MI, MDT);
862 }
863
864 // Propagate register class back to PHI operands which are PHI themselves.
865 while (!PHIOperands.empty()) {
866 processPHINode(*PHIOperands.pop_back_val());
867 }
868}
869
870bool SIFixSGPRCopies::tryMoveVGPRConstToSGPR(
871 MachineOperand &MaybeVGPRConstMO, Register DstReg,
872 MachineBasicBlock *BlockToInsertTo,
873 MachineBasicBlock::iterator PointToInsertTo, const DebugLoc &DL) {
874
875 MachineInstr *DefMI = MRI->getVRegDef(MaybeVGPRConstMO.getReg());
876 if (!DefMI || !DefMI->isMoveImmediate())
877 return false;
878
879 MachineOperand *SrcConst = TII->getNamedOperand(*DefMI, AMDGPU::OpName::src0);
880 if (SrcConst->isReg())
881 return false;
882
883 const TargetRegisterClass *SrcRC =
884 MRI->getRegClass(MaybeVGPRConstMO.getReg());
885 unsigned MoveSize = TRI->getRegSizeInBits(*SrcRC);
886 unsigned MoveOp = MoveSize == 64 ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
887 BuildMI(*BlockToInsertTo, PointToInsertTo, DL, TII->get(MoveOp), DstReg)
888 .add(*SrcConst);
889 if (MRI->hasOneUse(MaybeVGPRConstMO.getReg()))
891 MaybeVGPRConstMO.setReg(DstReg);
892 return true;
893}
894
895bool SIFixSGPRCopies::lowerSpecialCase(MachineInstr &MI,
897 Register DstReg = MI.getOperand(0).getReg();
898 Register SrcReg = MI.getOperand(1).getReg();
899 if (!DstReg.isVirtual()) {
900 // If the destination register is a physical register there isn't
901 // really much we can do to fix this.
902 // Some special instructions use M0 as an input. Some even only use
903 // the first lane. Insert a readfirstlane and hope for the best.
904 if (DstReg == AMDGPU::M0 &&
905 TRI->hasVectorRegisters(MRI->getRegClass(SrcReg))) {
906 Register TmpReg =
907 MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
908 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
909 TII->get(AMDGPU::V_READFIRSTLANE_B32), TmpReg)
910 .add(MI.getOperand(1));
911 MI.getOperand(1).setReg(TmpReg);
912 } else if (tryMoveVGPRConstToSGPR(MI.getOperand(1), DstReg, MI.getParent(),
913 MI, MI.getDebugLoc())) {
914 I = std::next(I);
915 MI.eraseFromParent();
916 }
917 return true;
918 }
919 if (!SrcReg.isVirtual() || TRI->isAGPR(*MRI, SrcReg)) {
920 SIInstrWorklist worklist;
921 worklist.insert(&MI);
922 TII->moveToVALU(worklist, MDT);
923 return true;
924 }
925
926 unsigned SMovOp;
927 int64_t Imm;
928 // If we are just copying an immediate, we can replace the copy with
929 // s_mov_b32.
930 if (isSafeToFoldImmIntoCopy(&MI, MRI->getVRegDef(SrcReg), TII, SMovOp, Imm)) {
931 MI.getOperand(1).ChangeToImmediate(Imm);
932 MI.addImplicitDefUseOperands(*MI.getParent()->getParent());
933 MI.setDesc(TII->get(SMovOp));
934 return true;
935 }
936 return false;
937}
938
939void SIFixSGPRCopies::analyzeVGPRToSGPRCopy(MachineInstr* MI) {
940 if (PHISources.contains(MI))
941 return;
942 Register DstReg = MI->getOperand(0).getReg();
943 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
944
945 V2SCopyInfo Info(getNextVGPRToSGPRCopyId(), MI,
946 TRI->getRegSizeInBits(*DstRC));
947 SmallVector<MachineInstr *, 8> AnalysisWorklist;
948 // Needed because the SSA is not a tree but a graph and may have
949 // forks and joins. We should not then go same way twice.
950 DenseSet<MachineInstr *> Visited;
951 AnalysisWorklist.push_back(Info.Copy);
952 while (!AnalysisWorklist.empty()) {
953
954 MachineInstr *Inst = AnalysisWorklist.pop_back_val();
955
956 if (!Visited.insert(Inst).second)
957 continue;
958
959 // Copies and REG_SEQUENCE do not contribute to the final assembly
960 // So, skip them but take care of the SGPR to VGPR copies bookkeeping.
961 if (Inst->isRegSequence() &&
962 TRI->isVGPR(*MRI, Inst->getOperand(0).getReg())) {
963 Info.NumSVCopies++;
964 continue;
965 }
966 if (Inst->isCopy()) {
967 const TargetRegisterClass *SrcRC, *DstRC;
968 std::tie(SrcRC, DstRC) = getCopyRegClasses(*Inst, *TRI, *MRI);
969 if (isSGPRToVGPRCopy(SrcRC, DstRC, *TRI) &&
971 Info.NumSVCopies++;
972 continue;
973 }
974 }
975
976 SiblingPenalty[Inst].insert(Info.ID);
977
978 SmallVector<MachineInstr *, 4> Users;
979 if ((TII->isSALU(*Inst) && Inst->isCompare()) ||
980 (Inst->isCopy() && Inst->getOperand(0).getReg() == AMDGPU::SCC)) {
981 auto I = Inst->getIterator();
982 auto E = Inst->getParent()->end();
983 while (++I != E &&
984 !I->findRegisterDefOperand(AMDGPU::SCC, /*TRI=*/nullptr)) {
985 if (I->readsRegister(AMDGPU::SCC, /*TRI=*/nullptr))
986 Users.push_back(&*I);
987 }
988 } else if (Inst->getNumExplicitDefs() != 0) {
989 Register Reg = Inst->getOperand(0).getReg();
990 if (Reg.isVirtual() && TRI->isSGPRReg(*MRI, Reg) && !TII->isVALU(*Inst)) {
991 for (auto &U : MRI->use_instructions(Reg))
992 Users.push_back(&U);
993 }
994 }
995 for (auto *U : Users) {
996 if (TII->isSALU(*U))
997 Info.SChain.insert(U);
998 AnalysisWorklist.push_back(U);
999 }
1000 }
1001 V2SCopies[Info.ID] = Info;
1002}
1003
1004// The main function that computes the VGPR to SGPR copy score
1005// and determines copy further lowering way: v_readfirstlane_b32 or moveToVALU
1006bool SIFixSGPRCopies::needToBeConvertedToVALU(V2SCopyInfo *Info) {
1007 if (Info->SChain.empty()) {
1008 Info->Score = 0;
1009 return true;
1010 }
1011 Info->Siblings = SiblingPenalty[*llvm::max_element(
1012 Info->SChain, [&](MachineInstr *A, MachineInstr *B) -> bool {
1013 return SiblingPenalty[A].size() < SiblingPenalty[B].size();
1014 })];
1015 Info->Siblings.remove_if([&](unsigned ID) { return ID == Info->ID; });
1016 // The loop below computes the number of another VGPR to SGPR V2SCopies
1017 // which contribute to the current copy SALU chain. We assume that all the
1018 // V2SCopies with the same source virtual register will be squashed to one
1019 // by regalloc. Also we take care of the V2SCopies of the differnt subregs
1020 // of the same register.
1021 SmallSet<std::pair<Register, unsigned>, 4> SrcRegs;
1022 for (auto J : Info->Siblings) {
1023 auto *InfoIt = V2SCopies.find(J);
1024 if (InfoIt != V2SCopies.end()) {
1025 MachineInstr *SiblingCopy = InfoIt->second.Copy;
1026 if (SiblingCopy->isImplicitDef())
1027 // the COPY has already been MoveToVALUed
1028 continue;
1029
1030 SrcRegs.insert(std::pair(SiblingCopy->getOperand(1).getReg(),
1031 SiblingCopy->getOperand(1).getSubReg()));
1032 }
1033 }
1034 Info->SiblingPenalty = SrcRegs.size();
1035
1036 unsigned Penalty =
1037 Info->NumSVCopies + Info->SiblingPenalty + Info->NumReadfirstlanes;
1038 unsigned Profit = Info->SChain.size();
1039 Info->Score = Penalty > Profit ? 0 : Profit - Penalty;
1040 Info->NeedToBeConvertedToVALU = Info->Score < 3;
1041 return Info->NeedToBeConvertedToVALU;
1042}
1043
1044void SIFixSGPRCopies::lowerVGPR2SGPRCopies(MachineFunction &MF) {
1045
1046 SmallVector<unsigned, 8> LoweringWorklist;
1047 for (auto &C : V2SCopies) {
1048 if (needToBeConvertedToVALU(&C.second))
1049 LoweringWorklist.push_back(C.second.ID);
1050 }
1051
1052 // Store all the V2S copy instructions that need to be moved to VALU
1053 // in the Copies worklist.
1054 SIInstrWorklist Copies;
1055
1056 while (!LoweringWorklist.empty()) {
1057 unsigned CurID = LoweringWorklist.pop_back_val();
1058 auto *CurInfoIt = V2SCopies.find(CurID);
1059 if (CurInfoIt != V2SCopies.end()) {
1060 V2SCopyInfo C = CurInfoIt->second;
1061 LLVM_DEBUG(dbgs() << "Processing ...\n"; C.dump());
1062 for (auto S : C.Siblings) {
1063 auto *SibInfoIt = V2SCopies.find(S);
1064 if (SibInfoIt != V2SCopies.end()) {
1065 V2SCopyInfo &SI = SibInfoIt->second;
1066 LLVM_DEBUG(dbgs() << "Sibling:\n"; SI.dump());
1067 if (!SI.NeedToBeConvertedToVALU) {
1068 SI.SChain.set_subtract(C.SChain);
1069 if (needToBeConvertedToVALU(&SI))
1070 LoweringWorklist.push_back(SI.ID);
1071 }
1072 SI.Siblings.remove_if([&](unsigned ID) { return ID == C.ID; });
1073 }
1074 }
1075 LLVM_DEBUG(dbgs() << "V2S copy " << *C.Copy
1076 << " is being turned to VALU\n");
1077 // TODO: MapVector::erase is inefficient. Do bulk removal with remove_if
1078 // instead.
1079 V2SCopies.erase(C.ID);
1080 Copies.insert(C.Copy);
1081 }
1082 }
1083
1084 TII->moveToVALU(Copies, MDT);
1085 Copies.clear();
1086
1087 // Now do actual lowering
1088 for (auto C : V2SCopies) {
1089 MachineInstr *MI = C.second.Copy;
1090 MachineBasicBlock *MBB = MI->getParent();
1091 // We decide to turn V2S copy to v_readfirstlane_b32
1092 // remove it from the V2SCopies and remove it from all its siblings
1093 LLVM_DEBUG(dbgs() << "V2S copy " << *MI
1094 << " is being turned to v_readfirstlane_b32"
1095 << " Score: " << C.second.Score << "\n");
1096 Register DstReg = MI->getOperand(0).getReg();
1097 MRI->constrainRegClass(DstReg, &AMDGPU::SReg_32_XM0RegClass);
1098
1099 Register SrcReg = MI->getOperand(1).getReg();
1100 unsigned SubReg = MI->getOperand(1).getSubReg();
1101 const TargetRegisterClass *SrcRC =
1102 TRI->getRegClassForOperandReg(*MRI, MI->getOperand(1));
1103 size_t SrcSize = TRI->getRegSizeInBits(*SrcRC);
1104 if (SrcSize == 16) {
1105 assert(MF.getSubtarget<GCNSubtarget>().useRealTrue16Insts() &&
1106 "We do not expect to see 16-bit copies from VGPR to SGPR unless "
1107 "we have 16-bit VGPRs");
1108 assert(MRI->getRegClass(DstReg) == &AMDGPU::SReg_32RegClass ||
1109 MRI->getRegClass(DstReg) == &AMDGPU::SReg_32_XM0RegClass);
1110 // There is no V_READFIRSTLANE_B16, so legalize the dst/src reg to 32 bits
1111 MRI->setRegClass(DstReg, &AMDGPU::SReg_32_XM0RegClass);
1112 Register VReg32 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1113 const DebugLoc &DL = MI->getDebugLoc();
1114 Register Undef = MRI->createVirtualRegister(&AMDGPU::VGPR_16RegClass);
1115 BuildMI(*MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
1116 BuildMI(*MBB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), VReg32)
1117 .addReg(SrcReg, 0, SubReg)
1118 .addImm(AMDGPU::lo16)
1119 .addReg(Undef)
1120 .addImm(AMDGPU::hi16);
1121 BuildMI(*MBB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
1122 .addReg(VReg32);
1123 } else if (SrcSize == 32) {
1124 auto MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
1125 TII->get(AMDGPU::V_READFIRSTLANE_B32), DstReg);
1126 MIB.addReg(SrcReg, 0, SubReg);
1127 } else {
1128 auto Result = BuildMI(*MBB, MI, MI->getDebugLoc(),
1129 TII->get(AMDGPU::REG_SEQUENCE), DstReg);
1130 int N = TRI->getRegSizeInBits(*SrcRC) / 32;
1131 for (int i = 0; i < N; i++) {
1132 Register PartialSrc = TII->buildExtractSubReg(
1133 Result, *MRI, MI->getOperand(1), SrcRC,
1134 TRI->getSubRegFromChannel(i), &AMDGPU::VGPR_32RegClass);
1135 Register PartialDst =
1136 MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1137 BuildMI(*MBB, *Result, Result->getDebugLoc(),
1138 TII->get(AMDGPU::V_READFIRSTLANE_B32), PartialDst)
1139 .addReg(PartialSrc);
1140 Result.addReg(PartialDst).addImm(TRI->getSubRegFromChannel(i));
1141 }
1142 }
1143 MI->eraseFromParent();
1144 }
1145}
1146
1147void SIFixSGPRCopies::fixSCCCopies(MachineFunction &MF) {
1148 bool IsWave32 = MF.getSubtarget<GCNSubtarget>().isWave32();
1149 for (MachineBasicBlock &MBB : MF) {
1150 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1151 ++I) {
1152 MachineInstr &MI = *I;
1153 // May already have been lowered.
1154 if (!MI.isCopy())
1155 continue;
1156 Register SrcReg = MI.getOperand(1).getReg();
1157 Register DstReg = MI.getOperand(0).getReg();
1158 if (SrcReg == AMDGPU::SCC) {
1159 Register SCCCopy =
1160 MRI->createVirtualRegister(TRI->getWaveMaskRegClass());
1161 I = BuildMI(*MI.getParent(), std::next(MachineBasicBlock::iterator(MI)),
1162 MI.getDebugLoc(),
1163 TII->get(IsWave32 ? AMDGPU::S_CSELECT_B32
1164 : AMDGPU::S_CSELECT_B64),
1165 SCCCopy)
1166 .addImm(-1)
1167 .addImm(0);
1168 I = BuildMI(*MI.getParent(), std::next(I), I->getDebugLoc(),
1169 TII->get(AMDGPU::COPY), DstReg)
1170 .addReg(SCCCopy);
1171 MI.eraseFromParent();
1172 continue;
1173 }
1174 if (DstReg == AMDGPU::SCC) {
1175 unsigned Opcode = IsWave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
1176 Register Exec = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
1177 Register Tmp = MRI->createVirtualRegister(TRI->getBoolRC());
1178 I = BuildMI(*MI.getParent(), std::next(MachineBasicBlock::iterator(MI)),
1179 MI.getDebugLoc(), TII->get(Opcode))
1180 .addReg(Tmp, getDefRegState(true))
1181 .addReg(SrcReg)
1182 .addReg(Exec);
1183 MI.eraseFromParent();
1184 }
1185 }
1186 }
1187}
1188
1189PreservedAnalyses
1193 SIFixSGPRCopies Impl(&MDT);
1194 bool Changed = Impl.run(MF);
1195 if (!Changed)
1196 return PreservedAnalyses::all();
1197
1198 // TODO: We could detect CFG changed.
1200 return PA;
1201}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
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 Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
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)
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)
static MachineBasicBlock::iterator getFirstNonPrologue(MachineBasicBlock *MBB, const TargetInstrInfo *TII)
SI Lower i1 Copies
#define LLVM_DEBUG(...)
Definition Debug.h:114
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
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
Implements a dense probed hash-table based set.
Definition DenseSet.h:269
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
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
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.
MachineInstrBundleIterator< MachineInstr > iterator
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.
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.
bool isImplicitDef() const
bool isCopy() const
const MachineBasicBlock * getParent() const
bool isCompare(QueryType Type=IgnoreBundle) const
Return true if this instruction is a comparison.
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.
const MachineOperand & getOperand(unsigned i) const
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 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,...
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
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.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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:181
size_type size() const
Definition SmallSet.h:170
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:194
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:169
self_iterator getIterator()
Definition ilist_node.h:134
Changed
LLVM_READONLY bool hasNamedOperand(uint64_t Opcode, OpName NamedIdx)
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.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ Resolved
Queried, materialization begun.
Definition Core.h:776
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
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.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
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:1714
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:2012
char & SIFixSGPRCopiesLegacyID
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
FunctionPass * createSIFixSGPRCopiesLegacyPass()
#define N
void insert(MachineInstr *MI)