LLVM 24.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 "AMDGPULaneMaskUtils.h"
70#include "GCNSubtarget.h"
75
76using namespace llvm;
77
78#define DEBUG_TYPE "si-fix-sgpr-copies"
79
81 "amdgpu-enable-merge-m0",
82 cl::desc("Merge and hoist M0 initializations"),
83 cl::init(true));
84
85namespace {
86
87class V2SCopyInfo {
88public:
89 // VGPR to SGPR copy being processed
90 MachineInstr *Copy;
91 // All SALU instructions reachable from this copy in SSA graph
93 // Number of SGPR to VGPR copies that are used to put the SALU computation
94 // results back to VALU.
95 unsigned NumSVCopies = 0;
96
97 unsigned Score = 0;
98 // Actual count of v_readfirstlane_b32
99 // which need to be inserted to keep SChain SALU
100 unsigned NumReadfirstlanes = 0;
101 // Current score state. To speedup selection V2SCopyInfos for processing
102 bool NeedToBeConvertedToVALU = false;
103 // Marks entries lowered to VALU for bulk removal from V2SCopies.
104 bool Erased = false;
105 // Unique ID. Used as a key for mapping to keep permanent order.
106 unsigned ID;
107
108 // Count of another VGPR to SGPR copies that contribute to the
109 // current copy SChain
110 unsigned SiblingPenalty = 0;
111 SetVector<unsigned> Siblings;
112 V2SCopyInfo() : Copy(nullptr), ID(0){};
113 V2SCopyInfo(unsigned Id, MachineInstr *C, unsigned Width)
114 : Copy(C), NumReadfirstlanes(Width / 32), ID(Id){};
115#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
116 void dump() const {
117 dbgs() << ID << " : " << *Copy << "\n\tS:" << SChain.size()
118 << "\n\tSV:" << NumSVCopies << "\n\tSP: " << SiblingPenalty
119 << "\nScore: " << Score << "\n";
120 }
121#endif
122};
123
124class SIFixSGPRCopies {
125 MachineDominatorTree *MDT;
126 SmallVector<MachineInstr*, 4> SCCCopies;
127 SmallVector<MachineInstr*, 4> RegSequences;
128 SmallVector<MachineInstr*, 4> PHINodes;
129 SmallVector<MachineInstr*, 4> S2VCopies;
130 unsigned NextVGPRToSGPRCopyID = 0;
131 MapVector<unsigned, V2SCopyInfo> V2SCopies;
132 DenseMap<MachineInstr *, SetVector<unsigned>> SiblingPenalty;
133 DenseSet<MachineInstr *> PHISources;
134
135public:
136 MachineRegisterInfo *MRI;
137 const SIRegisterInfo *TRI;
138 const SIInstrInfo *TII;
139
140 SIFixSGPRCopies(MachineDominatorTree *MDT) : MDT(MDT) {}
141
142 bool run(MachineFunction &MF);
143 void fixSCCCopies(MachineFunction &MF);
144 void prepareRegSequenceAndPHIs(MachineFunction &MF);
145 unsigned getNextVGPRToSGPRCopyId() { return ++NextVGPRToSGPRCopyID; }
146 bool needToBeConvertedToVALU(V2SCopyInfo *I);
147 void analyzeVGPRToSGPRCopy(MachineInstr *MI);
148 void lowerVGPR2SGPRCopies(MachineFunction &MF);
149 // Handles copies which source register is:
150 // 1. Physical register
151 // 2. AGPR
152 // 3. Defined by the instruction the merely moves the immediate
153 bool lowerSpecialCase(MachineInstr &MI, MachineBasicBlock::iterator &I);
154
155 void processPHINode(MachineInstr &MI);
156
157 // Check if MO is an immediate materialized into a VGPR, and if so replace it
158 // with an SGPR immediate. The VGPR immediate is also deleted if it does not
159 // have any other uses.
160 bool tryMoveVGPRConstToSGPR(MachineOperand &MO, Register NewDst,
161 MachineBasicBlock *BlockToInsertTo,
162 MachineBasicBlock::iterator PointToInsertTo,
163 const DebugLoc &DL);
164};
165
166class SIFixSGPRCopiesLegacy : public MachineFunctionPass {
167public:
168 static char ID;
169
170 SIFixSGPRCopiesLegacy() : MachineFunctionPass(ID) {}
171
172 bool runOnMachineFunction(MachineFunction &MF) override {
173 MachineDominatorTree *MDT =
174 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
175 SIFixSGPRCopies Impl(MDT);
176 return Impl.run(MF);
177 }
178
179 StringRef getPassName() const override { return "SI Fix SGPR copies"; }
180
181 void getAnalysisUsage(AnalysisUsage &AU) const override {
182 AU.addRequired<MachineDominatorTreeWrapperPass>();
183 AU.addPreserved<MachineDominatorTreeWrapperPass>();
184 AU.setPreservesCFG();
186 }
187
188 // Waterfall expansion may introduce Phi nodes and -verify-machineinstrs will
189 // fail.
190 MachineFunctionProperties getClearedProperties() const override {
191 return MachineFunctionProperties().setNoPHIs();
192 }
193};
194
195} // end anonymous namespace
196
197INITIALIZE_PASS_BEGIN(SIFixSGPRCopiesLegacy, DEBUG_TYPE, "SI Fix SGPR copies",
198 false, false)
200INITIALIZE_PASS_END(SIFixSGPRCopiesLegacy, DEBUG_TYPE, "SI Fix SGPR copies",
202
203char SIFixSGPRCopiesLegacy::ID = 0;
204
205char &llvm::SIFixSGPRCopiesLegacyID = SIFixSGPRCopiesLegacy::ID;
206
208 return new SIFixSGPRCopiesLegacy();
209}
210
211static std::pair<const TargetRegisterClass *, const TargetRegisterClass *>
213 const SIRegisterInfo &TRI,
214 const MachineRegisterInfo &MRI) {
215 Register DstReg = Copy.getOperand(0).getReg();
216 Register SrcReg = Copy.getOperand(1).getReg();
217
218 const TargetRegisterClass *SrcRC = SrcReg.isVirtual()
219 ? MRI.getRegClass(SrcReg)
220 : TRI.getPhysRegBaseClass(SrcReg);
221
222 // We don't really care about the subregister here.
223 // SrcRC = TRI.getSubRegClass(SrcRC, Copy.getOperand(1).getSubReg());
224
225 const TargetRegisterClass *DstRC = DstReg.isVirtual()
226 ? MRI.getRegClass(DstReg)
227 : TRI.getPhysRegBaseClass(DstReg);
228
229 return std::pair(SrcRC, DstRC);
230}
231
232static bool isVGPRToSGPRCopy(const TargetRegisterClass *SrcRC,
233 const TargetRegisterClass *DstRC,
234 const SIRegisterInfo &TRI) {
235 return SrcRC != &AMDGPU::VReg_1RegClass && TRI.isSGPRClass(DstRC) &&
236 TRI.hasVectorRegisters(SrcRC);
237}
238
239static bool isSGPRToVGPRCopy(const TargetRegisterClass *SrcRC,
240 const TargetRegisterClass *DstRC,
241 const SIRegisterInfo &TRI) {
242 return DstRC != &AMDGPU::VReg_1RegClass && TRI.isSGPRClass(SrcRC) &&
243 TRI.hasVectorRegisters(DstRC);
244}
245
247 const SIRegisterInfo *TRI,
248 const SIInstrInfo *TII) {
249 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
250 auto &Src = MI.getOperand(1);
251 Register DstReg = MI.getOperand(0).getReg();
252 Register SrcReg = Src.getReg();
253 if (!SrcReg.isVirtual() || !DstReg.isVirtual())
254 return false;
255
256 for (const auto &MO : MRI.reg_nodbg_operands(DstReg)) {
257 const auto *UseMI = MO.getParent();
258 if (UseMI == &MI)
259 continue;
260 if (MO.isDef() || UseMI->getParent() != MI.getParent() ||
261 UseMI->getOpcode() <= TargetOpcode::GENERIC_OP_END)
262 return false;
263
264 unsigned OpIdx = MO.getOperandNo();
265 if (OpIdx >= UseMI->getDesc().getNumOperands() ||
266 !TII->isOperandLegal(*UseMI, OpIdx, &Src))
267 return false;
268 }
269 // Change VGPR to SGPR destination.
270 MRI.setRegClass(DstReg, TRI->getEquivalentSGPRClass(MRI.getRegClass(DstReg)));
271 return true;
272}
273
274// Distribute an SGPR->VGPR copy of a REG_SEQUENCE into a VGPR REG_SEQUENCE.
275//
276// SGPRx = ...
277// SGPRy = REG_SEQUENCE SGPRx, sub0 ...
278// VGPRz = COPY SGPRy
279//
280// ==>
281//
282// VGPRx = COPY SGPRx
283// VGPRz = REG_SEQUENCE VGPRx, sub0
284//
285// This exposes immediate folding opportunities when materializing 64-bit
286// immediates.
288 const SIRegisterInfo *TRI,
289 const SIInstrInfo *TII,
290 MachineRegisterInfo &MRI) {
291 assert(MI.isRegSequence());
292
293 Register DstReg = MI.getOperand(0).getReg();
294 if (!TRI->isSGPRClass(MRI.getRegClass(DstReg)))
295 return false;
296
297 if (!MRI.hasOneUse(DstReg))
298 return false;
299
300 MachineInstr &CopyUse = *MRI.use_instr_begin(DstReg);
301 if (!CopyUse.isCopy())
302 return false;
303
304 // It is illegal to have vreg inputs to a physreg defining reg_sequence.
305 if (CopyUse.getOperand(0).getReg().isPhysical())
306 return false;
307
308 const TargetRegisterClass *SrcRC, *DstRC;
309 std::tie(SrcRC, DstRC) = getCopyRegClasses(CopyUse, *TRI, MRI);
310
311 if (!isSGPRToVGPRCopy(SrcRC, DstRC, *TRI))
312 return false;
313
314 if (tryChangeVGPRtoSGPRinCopy(CopyUse, TRI, TII))
315 return true;
316
317 // TODO: Could have multiple extracts?
318 unsigned SubReg = CopyUse.getOperand(1).getSubReg();
319 if (SubReg != AMDGPU::NoSubRegister)
320 return false;
321
322 MRI.setRegClass(DstReg, DstRC);
323
324 // SGPRx = ...
325 // SGPRy = REG_SEQUENCE SGPRx, sub0 ...
326 // VGPRz = COPY SGPRy
327
328 // =>
329 // VGPRx = COPY SGPRx
330 // VGPRz = REG_SEQUENCE VGPRx, sub0
331
332 MI.getOperand(0).setReg(CopyUse.getOperand(0).getReg());
333 bool IsAGPR = TRI->isAGPRClass(DstRC);
334
335 for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
336 const TargetRegisterClass *SrcRC =
337 TRI->getRegClassForOperandReg(MRI, MI.getOperand(I));
338 assert(TRI->isSGPRClass(SrcRC) &&
339 "Expected SGPR REG_SEQUENCE to only have SGPR inputs");
340 const TargetRegisterClass *NewSrcRC = TRI->getEquivalentVGPRClass(SrcRC);
341
342 Register TmpReg = MRI.createVirtualRegister(NewSrcRC);
343
344 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(), TII->get(AMDGPU::COPY),
345 TmpReg)
346 .add(MI.getOperand(I));
347
348 if (IsAGPR) {
349 const TargetRegisterClass *NewSrcRC = TRI->getEquivalentAGPRClass(SrcRC);
350 Register TmpAReg = MRI.createVirtualRegister(NewSrcRC);
351 unsigned Opc = NewSrcRC == &AMDGPU::AGPR_32RegClass ?
352 AMDGPU::V_ACCVGPR_WRITE_B32_e64 : AMDGPU::COPY;
353 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(), TII->get(Opc),
354 TmpAReg)
355 .addReg(TmpReg, RegState::Kill);
356 TmpReg = TmpAReg;
357 }
358
359 MI.getOperand(I).setReg(TmpReg);
360 }
361
362 CopyUse.eraseFromParent();
363 return true;
364}
365
366static bool isSafeToFoldImmIntoCopy(const MachineInstr *Copy,
367 const MachineInstr *MoveImm,
368 const SIInstrInfo *TII,
369 unsigned &SMovOp,
370 int64_t &Imm) {
371 if (Copy->getOpcode() != AMDGPU::COPY)
372 return false;
373
374 if (!MoveImm->isMoveImmediate())
375 return false;
376
377 const MachineOperand *ImmOp =
378 TII->getNamedOperand(*MoveImm, AMDGPU::OpName::src0);
379 if (!ImmOp->isImm())
380 return false;
381
382 // FIXME: Handle copies with sub-regs.
383 if (Copy->getOperand(1).getSubReg())
384 return false;
385
386 switch (MoveImm->getOpcode()) {
387 default:
388 return false;
389 case AMDGPU::V_MOV_B32_e32:
390 case AMDGPU::AV_MOV_B32_IMM_PSEUDO:
391 SMovOp = AMDGPU::S_MOV_B32;
392 break;
393 case AMDGPU::V_MOV_B64_e32:
394 case AMDGPU::V_MOV_B64_PSEUDO:
395 SMovOp = AMDGPU::S_MOV_B64_IMM_PSEUDO;
396 break;
397 }
398 Imm = ImmOp->getImm();
399 return true;
400}
401
402template <class UnaryPredicate>
404 const MachineBasicBlock *CutOff,
405 UnaryPredicate Predicate) {
406 if (MBB == CutOff)
407 return false;
408
410 SmallVector<MachineBasicBlock *, 4> Worklist(MBB->predecessors());
411
412 while (!Worklist.empty()) {
413 MachineBasicBlock *MBB = Worklist.pop_back_val();
414
415 if (!Visited.insert(MBB).second)
416 continue;
417 if (MBB == CutOff)
418 continue;
419 if (Predicate(MBB))
420 return true;
421
422 Worklist.append(MBB->pred_begin(), MBB->pred_end());
423 }
424
425 return false;
426}
427
428// Checks if there is potential path From instruction To instruction.
429// If CutOff is specified and it sits in between of that path we ignore
430// a higher portion of the path and report it is not reachable.
431static bool isReachable(const MachineInstr *From,
432 const MachineInstr *To,
433 const MachineBasicBlock *CutOff,
435 if (MDT.dominates(From, To))
436 return true;
437
438 const MachineBasicBlock *MBBFrom = From->getParent();
439 const MachineBasicBlock *MBBTo = To->getParent();
440
441 // Do predecessor search.
442 // We should almost never get here since we do not usually produce M0 stores
443 // other than -1.
444 return searchPredecessors(MBBTo, CutOff, [MBBFrom]
445 (const MachineBasicBlock *MBB) { return MBB == MBBFrom; });
446}
447
448// Return the first non-prologue instruction in the block.
451 MachineBasicBlock::iterator I = MBB->getFirstNonPHI();
452 while (I != MBB->end() && TII->isBasicBlockPrologue(*I))
453 ++I;
454
455 return I;
456}
457
458// Hoist and merge identical SGPR initializations into a common predecessor.
459// This is intended to combine M0 initializations, but can work with any
460// SGPR. A VGPR cannot be processed since we cannot guarantee vector
461// executioon.
462static bool hoistAndMergeSGPRInits(unsigned Reg,
463 const MachineRegisterInfo &MRI,
464 const TargetRegisterInfo *TRI,
466 const TargetInstrInfo *TII) {
467 // List of inits by immediate value.
468 using InitListMap = std::map<unsigned, std::list<MachineInstr *>>;
469 InitListMap Inits;
470 // List of clobbering instructions.
472 // List of instructions marked for deletion.
474
475 bool Changed = false;
476
477 for (auto &MI : MRI.def_instructions(Reg)) {
478 MachineOperand *Imm = nullptr;
479 for (auto &MO : MI.operands()) {
480 if ((MO.isReg() && ((MO.isDef() && MO.getReg() != Reg) || !MO.isDef())) ||
481 (!MO.isImm() && !MO.isReg()) || (MO.isImm() && Imm)) {
482 Imm = nullptr;
483 break;
484 }
485 if (MO.isImm())
486 Imm = &MO;
487 }
488 if (Imm)
489 Inits[Imm->getImm()].push_front(&MI);
490 else
491 Clobbers.push_back(&MI);
492 }
493
494 for (auto &Init : Inits) {
495 auto &Defs = Init.second;
496
497 for (auto I1 = Defs.begin(), E = Defs.end(); I1 != E; ) {
498 MachineInstr *MI1 = *I1;
499
500 for (auto I2 = std::next(I1); I2 != E; ) {
501 MachineInstr *MI2 = *I2;
502
503 // Check any possible interference
504 auto interferes = [&](MachineBasicBlock::iterator From,
505 MachineBasicBlock::iterator To) -> bool {
506
507 assert(MDT.dominates(&*To, &*From));
508
509 auto interferes = [&MDT, From, To](MachineInstr* &Clobber) -> bool {
510 const MachineBasicBlock *MBBFrom = From->getParent();
511 const MachineBasicBlock *MBBTo = To->getParent();
512 bool MayClobberFrom = isReachable(Clobber, &*From, MBBTo, MDT);
513 bool MayClobberTo = isReachable(Clobber, &*To, MBBTo, MDT);
514 if (!MayClobberFrom && !MayClobberTo)
515 return false;
516 if ((MayClobberFrom && !MayClobberTo) ||
517 (!MayClobberFrom && MayClobberTo))
518 return true;
519 // Both can clobber, this is not an interference only if both are
520 // dominated by Clobber and belong to the same block or if Clobber
521 // properly dominates To, given that To >> From, so it dominates
522 // both and located in a common dominator.
523 return !((MBBFrom == MBBTo &&
524 MDT.dominates(Clobber, &*From) &&
525 MDT.dominates(Clobber, &*To)) ||
526 MDT.properlyDominates(Clobber->getParent(), MBBTo));
527 };
528
529 return (llvm::any_of(Clobbers, interferes)) ||
530 (llvm::any_of(Inits, [&](InitListMap::value_type &C) {
531 return C.first != Init.first &&
532 llvm::any_of(C.second, interferes);
533 }));
534 };
535
536 if (MDT.dominates(MI1, MI2)) {
537 if (!interferes(MI2, MI1)) {
539 << "Erasing from "
540 << printMBBReference(*MI2->getParent()) << " " << *MI2);
541 MergedInstrs.insert(MI2);
542 Changed = true;
543 ++I2;
544 continue;
545 }
546 } else if (MDT.dominates(MI2, MI1)) {
547 if (!interferes(MI1, MI2)) {
549 << "Erasing from "
550 << printMBBReference(*MI1->getParent()) << " " << *MI1);
551 MergedInstrs.insert(MI1);
552 Changed = true;
553 ++I1;
554 break;
555 }
556 } else {
557 auto *MBB = MDT.findNearestCommonDominator(MI1->getParent(),
558 MI2->getParent());
559 if (!MBB) {
560 ++I2;
561 continue;
562 }
563
565 if (!interferes(MI1, I) && !interferes(MI2, I)) {
567 << "Erasing from "
568 << printMBBReference(*MI1->getParent()) << " " << *MI1
569 << "and moving from "
570 << printMBBReference(*MI2->getParent()) << " to "
571 << printMBBReference(*I->getParent()) << " " << *MI2);
572 I->getParent()->splice(I, MI2->getParent(), MI2);
573 MergedInstrs.insert(MI1);
574 Changed = true;
575 ++I1;
576 break;
577 }
578 }
579 ++I2;
580 }
581 ++I1;
582 }
583 }
584
585 // Remove initializations that were merged into another.
586 for (auto &Init : Inits) {
587 auto &Defs = Init.second;
588 auto I = Defs.begin();
589 while (I != Defs.end()) {
590 if (MergedInstrs.count(*I)) {
591 (*I)->eraseFromParent();
592 I = Defs.erase(I);
593 } else
594 ++I;
595 }
596 }
597
598 // Try to schedule SGPR initializations as early as possible in the MBB.
599 for (auto &Init : Inits) {
600 auto &Defs = Init.second;
601 for (auto *MI : Defs) {
602 auto *MBB = MI->getParent();
603 MachineInstr &BoundaryMI = *getFirstNonPrologue(MBB, TII);
605 // Check if B should actually be a boundary. If not set the previous
606 // instruction as the boundary instead.
607 if (!TII->isBasicBlockPrologue(*B))
608 B++;
609
610 auto R = std::next(MI->getReverseIterator());
611 const unsigned Threshold = 50;
612 // Search until B or Threshold for a place to insert the initialization.
613 for (unsigned I = 0; R != B && I < Threshold; ++R, ++I)
614 if (R->readsRegister(Reg, TRI) || R->definesRegister(Reg, TRI) ||
615 TII->isSchedulingBoundary(*R, MBB, *MBB->getParent()))
616 break;
617
618 // Move to directly after R.
619 if (&*--R != MI)
620 MBB->splice(*R, MBB, MI);
621 }
622 }
623
624 if (Changed)
625 MRI.clearKillFlags(Reg);
626
627 return Changed;
628}
629
630bool SIFixSGPRCopies::run(MachineFunction &MF) {
631 // Only need to run this in SelectionDAG path.
632 if (MF.getProperties().hasSelected())
633 return false;
634
635 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
636 MRI = &MF.getRegInfo();
637 TRI = ST.getRegisterInfo();
638 TII = ST.getInstrInfo();
639
640 // Instructions to re-legalize after changing register classes
641 SmallVector<MachineInstr *, 8> Relegalize;
642
643 for (MachineBasicBlock &MBB : MF) {
644 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
645 ++I) {
646 MachineInstr &MI = *I;
647
648 switch (MI.getOpcode()) {
649 default:
650 // scale_src has a register class restricted to low 256 VGPRs, changing
651 // registers to VGPR may not take it into acount.
652 if (TII->isWMMA(MI) &&
653 AMDGPU::hasNamedOperand(MI.getOpcode(), AMDGPU::OpName::scale_src0))
654 Relegalize.push_back(&MI);
655 continue;
656 case AMDGPU::COPY: {
657 const TargetRegisterClass *SrcRC, *DstRC;
658 std::tie(SrcRC, DstRC) = getCopyRegClasses(MI, *TRI, *MRI);
659
660 if (isSGPRToVGPRCopy(SrcRC, DstRC, *TRI)) {
661 // Since VGPR to SGPR copies affect VGPR to SGPR copy
662 // score and, hence the lowering decision, let's try to get rid of
663 // them as early as possible
665 continue;
666
667 // Collect those not changed to try them after VGPR to SGPR copies
668 // lowering as there will be more opportunities.
669 S2VCopies.push_back(&MI);
670 }
671 if (!isVGPRToSGPRCopy(SrcRC, DstRC, *TRI))
672 continue;
673 if (lowerSpecialCase(MI, I))
674 continue;
675
676 analyzeVGPRToSGPRCopy(&MI);
677
678 break;
679 }
680 case AMDGPU::WQM:
681 case AMDGPU::STRICT_WQM:
682 case AMDGPU::SOFT_WQM:
683 case AMDGPU::STRICT_WWM:
684 case AMDGPU::INSERT_SUBREG:
685 case AMDGPU::PHI:
686 case AMDGPU::REG_SEQUENCE: {
687 if (TRI->isSGPRClass(TII->getOpRegClass(MI, 0))) {
688 for (MachineOperand &MO : MI.operands()) {
689 if (!MO.isReg() || !MO.getReg().isVirtual())
690 continue;
691 const TargetRegisterClass *SrcRC = MRI->getRegClass(MO.getReg());
692 if (SrcRC == &AMDGPU::VReg_1RegClass)
693 continue;
694
695 if (TRI->hasVectorRegisters(SrcRC)) {
696 const TargetRegisterClass *DestRC =
697 TRI->getEquivalentSGPRClass(SrcRC);
698 Register NewDst = MRI->createVirtualRegister(DestRC);
699 MachineBasicBlock *BlockToInsertCopy =
700 MI.isPHI() ? MI.getOperand(MO.getOperandNo() + 1).getMBB()
701 : &MBB;
702 MachineBasicBlock::iterator PointToInsertCopy =
703 MI.isPHI() ? BlockToInsertCopy->getFirstInstrTerminator() : I;
704
705 const DebugLoc &DL = MI.getDebugLoc();
706 if (!tryMoveVGPRConstToSGPR(MO, NewDst, BlockToInsertCopy,
707 PointToInsertCopy, DL)) {
708 MachineInstr *NewCopy =
709 BuildMI(*BlockToInsertCopy, PointToInsertCopy, DL,
710 TII->get(AMDGPU::COPY), NewDst)
711 .addReg(MO.getReg());
712 MO.setReg(NewDst);
713 analyzeVGPRToSGPRCopy(NewCopy);
714 PHISources.insert(NewCopy);
715 }
716 }
717 }
718 }
719
720 if (MI.isPHI())
721 PHINodes.push_back(&MI);
722 else if (MI.isRegSequence())
723 RegSequences.push_back(&MI);
724
725 break;
726 }
727 case AMDGPU::V_WRITELANE_B32: {
728 // Some architectures allow more than one constant bus access without
729 // SGPR restriction
730 if (ST.getConstantBusLimit(MI.getOpcode()) != 1)
731 break;
732
733 // Writelane is special in that it can use SGPR and M0 (which would
734 // normally count as using the constant bus twice - but in this case it
735 // is allowed since the lane selector doesn't count as a use of the
736 // constant bus). However, it is still required to abide by the 1 SGPR
737 // rule. Apply a fix here as we might have multiple SGPRs after
738 // legalizing VGPRs to SGPRs
739 int Src0Idx =
740 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
741 int Src1Idx =
742 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src1);
743 MachineOperand &Src0 = MI.getOperand(Src0Idx);
744 MachineOperand &Src1 = MI.getOperand(Src1Idx);
745
746 // Check to see if the instruction violates the 1 SGPR rule
747 if ((Src0.isReg() && TRI->isSGPRReg(*MRI, Src0.getReg()) &&
748 Src0.getReg() != AMDGPU::M0) &&
749 (Src1.isReg() && TRI->isSGPRReg(*MRI, Src1.getReg()) &&
750 Src1.getReg() != AMDGPU::M0)) {
751
752 // Check for trivially easy constant prop into one of the operands
753 // If this is the case then perform the operation now to resolve SGPR
754 // issue. If we don't do that here we will always insert a mov to m0
755 // that can't be resolved in later operand folding pass
756 bool Resolved = false;
757 for (MachineOperand *MO : {&Src0, &Src1}) {
758 if (MO->getReg().isVirtual()) {
759 MachineInstr *DefMI = MRI->getVRegDef(MO->getReg());
760 if (DefMI && TII->isFoldableCopy(*DefMI)) {
761 const MachineOperand &Def = DefMI->getOperand(0);
762 if (Def.isReg() &&
763 MO->getReg() == Def.getReg() &&
764 MO->getSubReg() == Def.getSubReg()) {
765 const MachineOperand &Copied = DefMI->getOperand(1);
766 if (Copied.isImm() &&
767 TII->isInlineConstant(APInt(64, Copied.getImm(), true))) {
768 MO->ChangeToImmediate(Copied.getImm());
769 Resolved = true;
770 break;
771 }
772 }
773 }
774 }
775 }
776
777 if (!Resolved) {
778 // Haven't managed to resolve by replacing an SGPR with an immediate
779 // Move src1 to be in M0
780 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
781 TII->get(AMDGPU::COPY), AMDGPU::M0)
782 .add(Src1);
783 Src1.ChangeToRegister(AMDGPU::M0, false);
784 }
785 }
786 break;
787 }
788 }
789 }
790 }
791
792 lowerVGPR2SGPRCopies(MF);
793 // Postprocessing
794 fixSCCCopies(MF);
795 for (auto *MI : S2VCopies) {
796 // Check if it is still valid
797 if (MI->isCopy()) {
798 const TargetRegisterClass *SrcRC, *DstRC;
799 std::tie(SrcRC, DstRC) = getCopyRegClasses(*MI, *TRI, *MRI);
800 if (isSGPRToVGPRCopy(SrcRC, DstRC, *TRI))
802 }
803 }
804 for (auto *MI : RegSequences) {
805 // Check if it is still valid
806 if (MI->isRegSequence())
808 }
809 for (auto *MI : PHINodes) {
810 processPHINode(*MI);
811 }
812 while (!Relegalize.empty())
813 TII->legalizeOperands(*Relegalize.pop_back_val(), MDT);
814
815 if (MF.getTarget().getOptLevel() > CodeGenOptLevel::None && EnableM0Merge)
816 hoistAndMergeSGPRInits(AMDGPU::M0, *MRI, TRI, *MDT, TII);
817
818 SiblingPenalty.clear();
819 V2SCopies.clear();
820 SCCCopies.clear();
821 RegSequences.clear();
822 PHINodes.clear();
823 S2VCopies.clear();
824 PHISources.clear();
825
826 return true;
827}
828
829void SIFixSGPRCopies::processPHINode(MachineInstr &MI) {
830 bool AllAGPRUses = true;
831 SetVector<const MachineInstr *> worklist;
832 SmallPtrSet<const MachineInstr *, 4> Visited;
833 SetVector<MachineInstr *> PHIOperands;
834 worklist.insert(&MI);
835 Visited.insert(&MI);
836 // HACK to make MIR tests with no uses happy
837 bool HasUses = false;
838 while (!worklist.empty()) {
839 const MachineInstr *Instr = worklist.pop_back_val();
840 Register Reg = Instr->getOperand(0).getReg();
841 for (const auto &Use : MRI->use_operands(Reg)) {
842 HasUses = true;
843 const MachineInstr *UseMI = Use.getParent();
844 AllAGPRUses &= (UseMI->isCopy() &&
845 TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg())) ||
846 TRI->isAGPR(*MRI, Use.getReg());
847 if (UseMI->isCopy() || UseMI->isRegSequence()) {
848 if (Visited.insert(UseMI).second)
849 worklist.insert(UseMI);
850
851 continue;
852 }
853 }
854 }
855
856 Register PHIRes = MI.getOperand(0).getReg();
857 const TargetRegisterClass *RC0 = MRI->getRegClass(PHIRes);
858 if (HasUses && AllAGPRUses && !TRI->isAGPRClass(RC0)) {
859 LLVM_DEBUG(dbgs() << "Moving PHI to AGPR: " << MI);
860 MRI->setRegClass(PHIRes, TRI->getEquivalentAGPRClass(RC0));
861 for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
862 MachineInstr *DefMI = MRI->getVRegDef(MI.getOperand(I).getReg());
863 if (DefMI && DefMI->isPHI())
864 PHIOperands.insert(DefMI);
865 }
866 }
867
868 if (TRI->hasVectorRegisters(MRI->getRegClass(PHIRes)) ||
869 RC0 == &AMDGPU::VReg_1RegClass) {
870 LLVM_DEBUG(dbgs() << "Legalizing PHI: " << MI);
871 TII->legalizeOperands(MI, MDT);
872 }
873
874 // Propagate register class back to PHI operands which are PHI themselves.
875 while (!PHIOperands.empty()) {
876 processPHINode(*PHIOperands.pop_back_val());
877 }
878}
879
880bool SIFixSGPRCopies::tryMoveVGPRConstToSGPR(
881 MachineOperand &MaybeVGPRConstMO, Register DstReg,
882 MachineBasicBlock *BlockToInsertTo,
883 MachineBasicBlock::iterator PointToInsertTo, const DebugLoc &DL) {
884
885 MachineInstr *DefMI = MRI->getVRegDef(MaybeVGPRConstMO.getReg());
886 if (!DefMI || !DefMI->isMoveImmediate())
887 return false;
888
889 MachineOperand *SrcConst = TII->getNamedOperand(*DefMI, AMDGPU::OpName::src0);
890 if (SrcConst->isReg())
891 return false;
892
893 const TargetRegisterClass *SrcRC =
894 MRI->getRegClass(MaybeVGPRConstMO.getReg());
895 unsigned MoveSize = TRI->getRegSizeInBits(*SrcRC);
896 unsigned MoveOp =
897 MoveSize == 64 ? AMDGPU::S_MOV_B64_IMM_PSEUDO : AMDGPU::S_MOV_B32;
898 BuildMI(*BlockToInsertTo, PointToInsertTo, DL, TII->get(MoveOp), DstReg)
899 .add(*SrcConst);
900 if (MRI->hasOneUse(MaybeVGPRConstMO.getReg()))
902 MaybeVGPRConstMO.setReg(DstReg);
903 return true;
904}
905
906bool SIFixSGPRCopies::lowerSpecialCase(MachineInstr &MI,
908 Register DstReg = MI.getOperand(0).getReg();
909 Register SrcReg = MI.getOperand(1).getReg();
910 if (!DstReg.isVirtual()) {
911 // If the destination register is a physical register there isn't
912 // really much we can do to fix this.
913 // Some special instructions use M0 as an input. Some even only use
914 // the first lane. Insert a readfirstlane and hope for the best.
915 const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
916 if (DstReg == AMDGPU::M0 && TRI->hasVectorRegisters(SrcRC)) {
917 Register TmpReg =
918 MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
919
920 const MCInstrDesc &ReadFirstLaneDesc =
921 TII->get(AMDGPU::V_READFIRSTLANE_B32);
922 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), ReadFirstLaneDesc, TmpReg)
923 .add(MI.getOperand(1));
924
925 unsigned SubReg = MI.getOperand(1).getSubReg();
926 MI.getOperand(1).setReg(TmpReg);
927 MI.getOperand(1).setSubReg(AMDGPU::NoSubRegister);
928
929 const TargetRegisterClass *OpRC = TII->getRegClass(ReadFirstLaneDesc, 1);
930 const TargetRegisterClass *ConstrainRC =
931 SubReg == AMDGPU::NoSubRegister
932 ? OpRC
933 : TRI->getMatchingSuperRegClass(SrcRC, OpRC, SubReg);
934
935 if (!MRI->constrainRegClass(SrcReg, ConstrainRC))
936 llvm_unreachable("failed to constrain register");
937 return true;
938 }
939
940 if (tryMoveVGPRConstToSGPR(MI.getOperand(1), DstReg, MI.getParent(), MI,
941 MI.getDebugLoc())) {
942 I = MI.eraseFromParent();
943 return true;
944 }
945
946 if (!SrcReg.isVirtual())
947 return true;
948 }
949 if (!SrcReg.isVirtual() || TRI->isAGPR(*MRI, SrcReg)) {
950 SIInstrWorklist worklist;
951 worklist.insert(&MI);
952 TII->moveToVALU(worklist, MDT);
953 return true;
954 }
955
956 unsigned SMovOp;
957 int64_t Imm;
958 // If we are just copying an immediate, we can replace the copy with
959 // s_mov_b32.
960 if (isSafeToFoldImmIntoCopy(&MI, MRI->getVRegDef(SrcReg), TII, SMovOp, Imm)) {
961 MI.getOperand(1).ChangeToImmediate(Imm);
962 MI.addImplicitDefUseOperands(*MI.getMF());
963 MI.setDesc(TII->get(SMovOp));
964 return true;
965 }
966 return false;
967}
968
969void SIFixSGPRCopies::analyzeVGPRToSGPRCopy(MachineInstr* MI) {
970 if (PHISources.contains(MI))
971 return;
972 Register DstReg = MI->getOperand(0).getReg();
973 const TargetRegisterClass *DstRC = TRI->getRegClassForReg(*MRI, DstReg);
974
975 V2SCopyInfo Info(getNextVGPRToSGPRCopyId(), MI,
976 TRI->getRegSizeInBits(*DstRC));
977 SmallVector<MachineInstr *, 8> AnalysisWorklist;
978 // Needed because the SSA is not a tree but a graph and may have
979 // forks and joins. We should not then go same way twice.
980 DenseSet<MachineInstr *> Visited;
981 AnalysisWorklist.push_back(Info.Copy);
982 while (!AnalysisWorklist.empty()) {
983
984 MachineInstr *Inst = AnalysisWorklist.pop_back_val();
985
986 if (!Visited.insert(Inst).second)
987 continue;
988
989 // Copies and REG_SEQUENCE do not contribute to the final assembly
990 // So, skip them but take care of the SGPR to VGPR copies bookkeeping.
991 if (Inst->isRegSequence() &&
992 TRI->isVGPR(*MRI, Inst->getOperand(0).getReg())) {
993 Info.NumSVCopies++;
994 continue;
995 }
996 if (Inst->isCopy()) {
997 const TargetRegisterClass *SrcRC, *DstRC;
998 std::tie(SrcRC, DstRC) = getCopyRegClasses(*Inst, *TRI, *MRI);
999 if (isSGPRToVGPRCopy(SrcRC, DstRC, *TRI) &&
1000 !tryChangeVGPRtoSGPRinCopy(*Inst, TRI, TII)) {
1001 Info.NumSVCopies++;
1002 continue;
1003 }
1004 }
1005
1006 SiblingPenalty[Inst].insert(Info.ID);
1007
1008 SmallVector<MachineInstr *, 4> Users;
1009 if ((TII->isSALU(*Inst) && Inst->isCompare()) ||
1010 (Inst->isCopy() && Inst->getOperand(0).getReg() == AMDGPU::SCC)) {
1011 auto I = Inst->getIterator();
1012 auto E = Inst->getParent()->end();
1013 while (++I != E &&
1014 !I->findRegisterDefOperand(AMDGPU::SCC, /*TRI=*/nullptr)) {
1015 if (I->readsRegister(AMDGPU::SCC, /*TRI=*/nullptr))
1016 Users.push_back(&*I);
1017 }
1018 } else if (Inst->getNumExplicitDefs() != 0) {
1019 Register Reg = Inst->getOperand(0).getReg();
1020 if (Reg.isVirtual() && TRI->isSGPRReg(*MRI, Reg) &&
1021 !TII->isVALU(*Inst, /*AllowLDSDMA=*/true)) {
1022 for (auto &U : MRI->use_instructions(Reg))
1023 Users.push_back(&U);
1024 }
1025 }
1026 for (auto *U : Users) {
1027 if (TII->isSALU(*U))
1028 Info.SChain.insert(U);
1029 AnalysisWorklist.push_back(U);
1030 }
1031 }
1032 V2SCopies[Info.ID] = std::move(Info);
1033}
1034
1035// The main function that computes the VGPR to SGPR copy score
1036// and determines copy further lowering way: v_readfirstlane_b32 or moveToVALU
1037bool SIFixSGPRCopies::needToBeConvertedToVALU(V2SCopyInfo *Info) {
1038 if (Info->SChain.empty()) {
1039 Info->Score = 0;
1040 return true;
1041 }
1042 Info->Siblings = SiblingPenalty[*llvm::max_element(
1043 Info->SChain, [&](MachineInstr *A, MachineInstr *B) -> bool {
1044 return SiblingPenalty[A].size() < SiblingPenalty[B].size();
1045 })];
1046 Info->Siblings.remove_if([&](unsigned ID) { return ID == Info->ID; });
1047 // The loop below computes the number of another VGPR to SGPR V2SCopies
1048 // which contribute to the current copy SALU chain. We assume that all the
1049 // V2SCopies with the same source virtual register will be squashed to one
1050 // by regalloc. Also we take care of the V2SCopies of the differnt subregs
1051 // of the same register.
1052 SmallSet<std::pair<Register, unsigned>, 4> SrcRegs;
1053 for (auto J : Info->Siblings) {
1054 auto *InfoIt = V2SCopies.find(J);
1055 if (InfoIt != V2SCopies.end()) {
1056 MachineInstr *SiblingCopy = InfoIt->second.Copy;
1057 if (SiblingCopy->isImplicitDef())
1058 // the COPY has already been MoveToVALUed
1059 continue;
1060
1061 SrcRegs.insert(std::pair(SiblingCopy->getOperand(1).getReg(),
1062 SiblingCopy->getOperand(1).getSubReg()));
1063 }
1064 }
1065 Info->SiblingPenalty = SrcRegs.size();
1066
1067 unsigned Penalty =
1068 Info->NumSVCopies + Info->SiblingPenalty + Info->NumReadfirstlanes;
1069 unsigned Profit = Info->SChain.size();
1070 Info->Score = Penalty > Profit ? 0 : Profit - Penalty;
1071 Info->NeedToBeConvertedToVALU = Info->Score < 3;
1072 return Info->NeedToBeConvertedToVALU;
1073}
1074
1075void SIFixSGPRCopies::lowerVGPR2SGPRCopies(MachineFunction &MF) {
1076
1077 SmallVector<unsigned, 8> LoweringWorklist;
1078 for (auto &C : V2SCopies) {
1079 if (needToBeConvertedToVALU(&C.second))
1080 LoweringWorklist.push_back(C.second.ID);
1081 }
1082
1083 // Store all the V2S copy instructions that need to be moved to VALU
1084 // in the Copies worklist.
1085 SIInstrWorklist Copies;
1086
1087 while (!LoweringWorklist.empty()) {
1088 unsigned CurID = LoweringWorklist.pop_back_val();
1089 auto *CurInfoIt = V2SCopies.find(CurID);
1090 if (CurInfoIt != V2SCopies.end() && !CurInfoIt->second.Erased) {
1091 V2SCopyInfo &C = CurInfoIt->second;
1092 LLVM_DEBUG(dbgs() << "Processing ...\n"; C.dump());
1093 for (auto S : C.Siblings) {
1094 auto *SibInfoIt = V2SCopies.find(S);
1095 if (SibInfoIt != V2SCopies.end() && !SibInfoIt->second.Erased) {
1096 V2SCopyInfo &SI = SibInfoIt->second;
1097 LLVM_DEBUG(dbgs() << "Sibling:\n"; SI.dump());
1098 if (!SI.NeedToBeConvertedToVALU) {
1099 SI.SChain.set_subtract(C.SChain);
1100 if (needToBeConvertedToVALU(&SI))
1101 LoweringWorklist.push_back(SI.ID);
1102 }
1103 SI.Siblings.remove_if([&](unsigned ID) { return ID == C.ID; });
1104 }
1105 }
1106 LLVM_DEBUG(dbgs() << "V2S copy " << *C.Copy
1107 << " is being turned to VALU\n");
1108 Copies.insert(C.Copy);
1109 C.Erased = true;
1110 }
1111 }
1112 V2SCopies.remove_if([](const auto &P) { return P.second.Erased; });
1113
1114 TII->moveToVALU(Copies, MDT);
1115 Copies.clear();
1116
1117 // Now do actual lowering
1118 for (auto C : V2SCopies) {
1119 MachineInstr *MI = C.second.Copy;
1120 MachineBasicBlock *MBB = MI->getParent();
1121 // We decide to turn V2S copy to v_readfirstlane_b32
1122 // remove it from the V2SCopies and remove it from all its siblings
1123 LLVM_DEBUG(dbgs() << "V2S copy " << *MI
1124 << " is being turned to v_readfirstlane_b32"
1125 << " Score: " << C.second.Score << "\n");
1126 Register DstReg = MI->getOperand(0).getReg();
1127 MRI->constrainRegClass(DstReg, &AMDGPU::SReg_32_XM0RegClass);
1128
1129 Register SrcReg = MI->getOperand(1).getReg();
1130 unsigned SubReg = MI->getOperand(1).getSubReg();
1131 const TargetRegisterClass *SrcRC =
1132 TRI->getRegClassForOperandReg(*MRI, MI->getOperand(1));
1133 size_t SrcSize = TRI->getRegSizeInBits(*SrcRC);
1134 if (SrcSize == 16) {
1135 assert(MF.getSubtarget<GCNSubtarget>().useRealTrue16Insts() &&
1136 "We do not expect to see 16-bit copies from VGPR to SGPR unless "
1137 "we have 16-bit VGPRs");
1138 assert(MRI->getRegClass(DstReg) == &AMDGPU::SReg_32RegClass ||
1139 MRI->getRegClass(DstReg) == &AMDGPU::SReg_32_XM0RegClass);
1140 // There is no V_READFIRSTLANE_B16, so legalize the dst/src reg to 32 bits
1141 MRI->setRegClass(DstReg, &AMDGPU::SReg_32_XM0RegClass);
1142 Register VReg32 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1143 const DebugLoc &DL = MI->getDebugLoc();
1144 Register Undef = MRI->createVirtualRegister(&AMDGPU::VGPR_16RegClass);
1145 BuildMI(*MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
1146 BuildMI(*MBB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), VReg32)
1147 .addReg(SrcReg, {}, SubReg)
1148 .addImm(AMDGPU::lo16)
1149 .addReg(Undef)
1150 .addImm(AMDGPU::hi16);
1151 BuildMI(*MBB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
1152 .addReg(VReg32);
1153 } else if (SrcSize == 32) {
1154 const MCInstrDesc &ReadFirstLaneDesc =
1155 TII->get(AMDGPU::V_READFIRSTLANE_B32);
1156 const TargetRegisterClass *OpRC = TII->getRegClass(ReadFirstLaneDesc, 1);
1157 BuildMI(*MBB, MI, MI->getDebugLoc(), ReadFirstLaneDesc, DstReg)
1158 .addReg(SrcReg, {}, SubReg);
1159
1160 const TargetRegisterClass *ConstrainRC =
1161 SubReg == AMDGPU::NoSubRegister
1162 ? OpRC
1163 : TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), OpRC,
1164 SubReg);
1165
1166 if (!MRI->constrainRegClass(SrcReg, ConstrainRC))
1167 llvm_unreachable("failed to constrain register");
1168 } else {
1169 auto Result = BuildMI(*MBB, MI, MI->getDebugLoc(),
1170 TII->get(AMDGPU::REG_SEQUENCE), DstReg);
1171 int N = TRI->getRegSizeInBits(*SrcRC) / 32;
1172 for (int i = 0; i < N; i++) {
1173 Register PartialSrc = TII->buildExtractSubReg(
1174 Result, *MRI, MI->getOperand(1), SrcRC,
1175 TRI->getSubRegFromChannel(i), &AMDGPU::VGPR_32RegClass);
1176 Register PartialDst =
1177 MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1178 BuildMI(*MBB, *Result, Result->getDebugLoc(),
1179 TII->get(AMDGPU::V_READFIRSTLANE_B32), PartialDst)
1180 .addReg(PartialSrc);
1181 Result.addReg(PartialDst).addImm(TRI->getSubRegFromChannel(i));
1182 }
1183 }
1184 MI->eraseFromParent();
1185 }
1186}
1187
1188void SIFixSGPRCopies::fixSCCCopies(MachineFunction &MF) {
1189 const AMDGPU::LaneMaskConstants &LMC =
1190 AMDGPU::LaneMaskConstants::get(MF.getSubtarget<GCNSubtarget>());
1191 for (MachineBasicBlock &MBB : MF) {
1192 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1193 ++I) {
1194 MachineInstr &MI = *I;
1195 // May already have been lowered.
1196 if (!MI.isCopy())
1197 continue;
1198 Register SrcReg = MI.getOperand(1).getReg();
1199 Register DstReg = MI.getOperand(0).getReg();
1200 if (SrcReg == AMDGPU::SCC) {
1201 Register SCCCopy =
1202 MRI->createVirtualRegister(TRI->getWaveMaskRegClass());
1203 I = BuildMI(*MI.getParent(), std::next(MachineBasicBlock::iterator(MI)),
1204 MI.getDebugLoc(), TII->get(LMC.CSelectOpc), SCCCopy)
1205 .addImm(-1)
1206 .addImm(0);
1207 I = BuildMI(*MI.getParent(), std::next(I), I->getDebugLoc(),
1208 TII->get(AMDGPU::COPY), DstReg)
1209 .addReg(SCCCopy);
1210 MI.eraseFromParent();
1211 continue;
1212 }
1213 if (DstReg == AMDGPU::SCC) {
1214 Register Tmp = MRI->createVirtualRegister(TRI->getBoolRC());
1215 I = BuildMI(*MI.getParent(), std::next(MachineBasicBlock::iterator(MI)),
1216 MI.getDebugLoc(), TII->get(LMC.AndOpc))
1217 .addReg(Tmp, getDefRegState(true))
1218 .addReg(SrcReg)
1219 .addReg(LMC.ExecReg);
1220 MI.eraseFromParent();
1221 }
1222 }
1223 }
1224}
1225
1226PreservedAnalyses
1230 SIFixSGPRCopies Impl(&MDT);
1231 bool Changed = Impl.run(MF);
1232 if (!Changed)
1233 return PreservedAnalyses::all();
1234
1235 // TODO: We could detect CFG changed.
1237 return PA;
1238}
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")
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:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineInstr unsigned OpIdx
#define P(N)
#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:119
static const LaneMaskConstants & get(const GCNSubtarget &ST)
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:275
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
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 & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
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.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
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,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
use_instr_iterator use_instr_begin(Register RegNo) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool hasOneUse(Register RegNo) const
hasOneUse - Return true if there is exactly one instruction using the specified register.
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(Register Reg) const
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:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A vector that has set insertion semantics.
Definition SetVector.h:57
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
value_type pop_back_val()
Definition SetVector.h:279
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:184
size_type size() const
Definition SmallSet.h:171
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:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
@ Resolved
Queried, materialization begun.
Definition Core.h:569
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.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
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:1746
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr RegState 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:2088
char & SIFixSGPRCopiesLegacyID
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
FunctionPass * createSIFixSGPRCopiesLegacyPass()
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
#define N
void insert(MachineInstr *MI)