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