LLVM 23.0.0git
SIInstrInfo.cpp
Go to the documentation of this file.
1//===- SIInstrInfo.cpp - SI Instruction Information ----------------------===//
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/// SI Implementation of TargetInstrInfo.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SIInstrInfo.h"
15#include "AMDGPU.h"
16#include "AMDGPUInstrInfo.h"
17#include "AMDGPULaneMaskUtils.h"
18#include "GCNHazardRecognizer.h"
19#include "GCNSubtarget.h"
22#include "llvm/ADT/STLExtras.h"
34#include "llvm/IR/IntrinsicsAMDGPU.h"
35#include "llvm/MC/MCContext.h"
38
39using namespace llvm;
40
41#define DEBUG_TYPE "si-instr-info"
42
43#define GET_INSTRINFO_CTOR_DTOR
44#include "AMDGPUGenInstrInfo.inc"
45
46namespace llvm::AMDGPU {
47#define GET_D16ImageDimIntrinsics_IMPL
48#define GET_ImageDimIntrinsicTable_IMPL
49#define GET_RsrcIntrinsics_IMPL
50#include "AMDGPUGenSearchableTables.inc"
51} // namespace llvm::AMDGPU
52
53// Must be at least 4 to be able to branch over minimum unconditional branch
54// code. This is only for making it possible to write reasonably small tests for
55// long branches.
57BranchOffsetBits("amdgpu-s-branch-bits", cl::ReallyHidden, cl::init(16),
58 cl::desc("Restrict range of branch instructions (DEBUG)"));
59
61 "amdgpu-fix-16-bit-physreg-copies",
62 cl::desc("Fix copies between 32 and 16 bit registers by extending to 32 bit"),
63 cl::init(true),
65
67 : AMDGPUGenInstrInfo(ST, RI, AMDGPU::ADJCALLSTACKUP,
68 AMDGPU::ADJCALLSTACKDOWN),
69 RI(ST), ST(ST) {
70 SchedModel.init(&ST);
71}
72
73//===----------------------------------------------------------------------===//
74// TargetInstrInfo callbacks
75//===----------------------------------------------------------------------===//
76
77static unsigned getNumOperandsNoGlue(SDNode *Node) {
78 unsigned N = Node->getNumOperands();
79 while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
80 --N;
81 return N;
82}
83
84/// Returns true if both nodes have the same value for the given
85/// operand \p Op, or if both nodes do not have this operand.
87 AMDGPU::OpName OpName) {
88 unsigned Opc0 = N0->getMachineOpcode();
89 unsigned Opc1 = N1->getMachineOpcode();
90
91 int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
92 int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
93
94 if (Op0Idx == -1 && Op1Idx == -1)
95 return true;
96
97
98 if ((Op0Idx == -1 && Op1Idx != -1) ||
99 (Op1Idx == -1 && Op0Idx != -1))
100 return false;
101
102 // getNamedOperandIdx returns the index for the MachineInstr's operands,
103 // which includes the result as the first operand. We are indexing into the
104 // MachineSDNode's operands, so we need to skip the result operand to get
105 // the real index.
106 --Op0Idx;
107 --Op1Idx;
108
109 return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
110}
111
112static bool canRemat(const MachineInstr &MI) {
113
117 return true;
118
119 if (SIInstrInfo::isSMRD(MI)) {
120 return !MI.memoperands_empty() &&
121 llvm::all_of(MI.memoperands(), [](const MachineMemOperand *MMO) {
122 return MMO->isLoad() && MMO->isInvariant();
123 });
124 }
125
126 return false;
127}
128
130 const MachineInstr &MI) const {
131
132 if (canRemat(MI)) {
133 // Normally VALU use of exec would block the rematerialization, but that
134 // is OK in this case to have an implicit exec read as all VALU do.
135 // We really want all of the generic logic for this except for this.
136
137 // Another potential implicit use is mode register. The core logic of
138 // the RA will not attempt rematerialization if mode is set anywhere
139 // in the function, otherwise it is safe since mode is not changed.
140
141 // There is difference to generic method which does not allow
142 // rematerialization if there are virtual register uses. We allow this,
143 // therefore this method includes SOP instructions as well.
144 if (!MI.hasImplicitDef() &&
145 MI.getNumImplicitOperands() == MI.getDesc().implicit_uses().size() &&
146 !MI.mayRaiseFPException())
147 return true;
148 }
149
151}
152
153// Returns true if the result of a VALU instruction depends on exec.
154bool SIInstrInfo::resultDependsOnExec(const MachineInstr &MI) const {
155 assert(isVALU(MI));
156
157 // If it is convergent it depends on EXEC.
158 if (MI.isConvergent())
159 return true;
160
161 // If it defines SGPR it depends on EXEC
162 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
163 for (const MachineOperand &Def : MI.defs()) {
164 if (!Def.isReg())
165 continue;
166
167 Register Reg = Def.getReg();
168 if (Reg && RI.isSGPRReg(MRI, Reg))
169 return true;
170 }
171
172 return false;
173}
174
176 // Any implicit use of exec by VALU is not a real register read.
177 return MO.getReg() == AMDGPU::EXEC && MO.isImplicit() &&
178 isVALU(*MO.getParent()) && !resultDependsOnExec(*MO.getParent());
179}
180
182 MachineBasicBlock *SuccToSinkTo,
183 MachineCycleInfo *CI) const {
184 // Allow sinking if MI edits lane mask (divergent i1 in sgpr).
185 if (MI.getOpcode() == AMDGPU::SI_IF_BREAK)
186 return true;
187
188 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
189 // Check if sinking of MI would create temporal divergent use.
190 for (auto Op : MI.uses()) {
191 if (Op.isReg() && Op.getReg().isVirtual() &&
192 RI.isSGPRClass(MRI.getRegClass(Op.getReg()))) {
193 MachineInstr *SgprDef = MRI.getVRegDef(Op.getReg());
194
195 // SgprDef defined inside cycle
196 MachineCycle *FromCycle = CI->getCycle(SgprDef->getParent());
197 if (FromCycle == nullptr)
198 continue;
199
200 MachineCycle *ToCycle = CI->getCycle(SuccToSinkTo);
201 // Check if there is a FromCycle that contains SgprDef's basic block but
202 // does not contain SuccToSinkTo and also has divergent exit condition.
203 while (FromCycle && !FromCycle->contains(ToCycle)) {
205 FromCycle->getExitingBlocks(ExitingBlocks);
206
207 // FromCycle has divergent exit condition.
208 for (MachineBasicBlock *ExitingBlock : ExitingBlocks) {
209 if (hasDivergentBranch(ExitingBlock))
210 return false;
211 }
212
213 FromCycle = FromCycle->getParentCycle();
214 }
215 }
216 }
217
218 return true;
219}
220
222 int64_t &Offset0,
223 int64_t &Offset1) const {
224 if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
225 return false;
226
227 unsigned Opc0 = Load0->getMachineOpcode();
228 unsigned Opc1 = Load1->getMachineOpcode();
229
230 // Make sure both are actually loads.
231 if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
232 return false;
233
234 // A mayLoad instruction without a def is not a load. Likely a prefetch.
235 if (!get(Opc0).getNumDefs() || !get(Opc1).getNumDefs())
236 return false;
237
238 if (isDS(Opc0) && isDS(Opc1)) {
239
240 // FIXME: Handle this case:
241 if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
242 return false;
243
244 // Check base reg.
245 if (Load0->getOperand(0) != Load1->getOperand(0))
246 return false;
247
248 // Skip read2 / write2 variants for simplicity.
249 // TODO: We should report true if the used offsets are adjacent (excluded
250 // st64 versions).
251 int Offset0Idx = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
252 int Offset1Idx = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
253 if (Offset0Idx == -1 || Offset1Idx == -1)
254 return false;
255
256 // XXX - be careful of dataless loads
257 // getNamedOperandIdx returns the index for MachineInstrs. Since they
258 // include the output in the operand list, but SDNodes don't, we need to
259 // subtract the index by one.
260 Offset0Idx -= get(Opc0).NumDefs;
261 Offset1Idx -= get(Opc1).NumDefs;
262 Offset0 = Load0->getConstantOperandVal(Offset0Idx);
263 Offset1 = Load1->getConstantOperandVal(Offset1Idx);
264 return true;
265 }
266
267 if (isSMRD(Opc0) && isSMRD(Opc1)) {
268 // Skip time and cache invalidation instructions.
269 if (!AMDGPU::hasNamedOperand(Opc0, AMDGPU::OpName::sbase) ||
270 !AMDGPU::hasNamedOperand(Opc1, AMDGPU::OpName::sbase))
271 return false;
272
273 unsigned NumOps = getNumOperandsNoGlue(Load0);
274 if (NumOps != getNumOperandsNoGlue(Load1))
275 return false;
276
277 // Check base reg.
278 if (Load0->getOperand(0) != Load1->getOperand(0))
279 return false;
280
281 // Match register offsets, if both register and immediate offsets present.
282 assert(NumOps == 4 || NumOps == 5);
283 if (NumOps == 5 && Load0->getOperand(1) != Load1->getOperand(1))
284 return false;
285
286 const ConstantSDNode *Load0Offset =
288 const ConstantSDNode *Load1Offset =
290
291 if (!Load0Offset || !Load1Offset)
292 return false;
293
294 Offset0 = Load0Offset->getZExtValue();
295 Offset1 = Load1Offset->getZExtValue();
296 return true;
297 }
298
299 // MUBUF and MTBUF can access the same addresses.
300 if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
301
302 // MUBUF and MTBUF have vaddr at different indices.
303 if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
304 !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
305 !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
306 return false;
307
308 int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
309 int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
310
311 if (OffIdx0 == -1 || OffIdx1 == -1)
312 return false;
313
314 // getNamedOperandIdx returns the index for MachineInstrs. Since they
315 // include the output in the operand list, but SDNodes don't, we need to
316 // subtract the index by one.
317 OffIdx0 -= get(Opc0).NumDefs;
318 OffIdx1 -= get(Opc1).NumDefs;
319
320 SDValue Off0 = Load0->getOperand(OffIdx0);
321 SDValue Off1 = Load1->getOperand(OffIdx1);
322
323 // The offset might be a FrameIndexSDNode.
324 if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
325 return false;
326
327 Offset0 = Off0->getAsZExtVal();
328 Offset1 = Off1->getAsZExtVal();
329 return true;
330 }
331
332 return false;
333}
334
335static bool isStride64(unsigned Opc) {
336 switch (Opc) {
337 case AMDGPU::DS_READ2ST64_B32:
338 case AMDGPU::DS_READ2ST64_B64:
339 case AMDGPU::DS_WRITE2ST64_B32:
340 case AMDGPU::DS_WRITE2ST64_B64:
341 return true;
342 default:
343 return false;
344 }
345}
346
349 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width,
350 const TargetRegisterInfo *TRI) const {
351 if (!LdSt.mayLoadOrStore())
352 return false;
353
354 unsigned Opc = LdSt.getOpcode();
355 OffsetIsScalable = false;
356 const MachineOperand *BaseOp, *OffsetOp;
357 int DataOpIdx;
358
359 if (isDS(LdSt)) {
360 BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::addr);
361 OffsetOp = getNamedOperand(LdSt, AMDGPU::OpName::offset);
362 if (OffsetOp) {
363 // Normal, single offset LDS instruction.
364 if (!BaseOp) {
365 // DS_CONSUME/DS_APPEND use M0 for the base address.
366 // TODO: find the implicit use operand for M0 and use that as BaseOp?
367 return false;
368 }
369 BaseOps.push_back(BaseOp);
370 Offset = OffsetOp->getImm();
371 // Get appropriate operand, and compute width accordingly.
372 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
373 if (DataOpIdx == -1)
374 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
375 if (Opc == AMDGPU::DS_ATOMIC_ASYNC_BARRIER_ARRIVE_B64)
376 Width = LocationSize::precise(64);
377 else
378 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
379 } else {
380 // The 2 offset instructions use offset0 and offset1 instead. We can treat
381 // these as a load with a single offset if the 2 offsets are consecutive.
382 // We will use this for some partially aligned loads.
383 const MachineOperand *Offset0Op =
384 getNamedOperand(LdSt, AMDGPU::OpName::offset0);
385 const MachineOperand *Offset1Op =
386 getNamedOperand(LdSt, AMDGPU::OpName::offset1);
387
388 unsigned Offset0 = Offset0Op->getImm() & 0xff;
389 unsigned Offset1 = Offset1Op->getImm() & 0xff;
390 if (Offset0 + 1 != Offset1)
391 return false;
392
393 // Each of these offsets is in element sized units, so we need to convert
394 // to bytes of the individual reads.
395
396 unsigned EltSize;
397 if (LdSt.mayLoad())
398 EltSize = TRI->getRegSizeInBits(*getOpRegClass(LdSt, 0)) / 16;
399 else {
400 assert(LdSt.mayStore());
401 int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
402 EltSize = TRI->getRegSizeInBits(*getOpRegClass(LdSt, Data0Idx)) / 8;
403 }
404
405 if (isStride64(Opc))
406 EltSize *= 64;
407
408 BaseOps.push_back(BaseOp);
409 Offset = EltSize * Offset0;
410 // Get appropriate operand(s), and compute width accordingly.
411 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
412 if (DataOpIdx == -1) {
413 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
414 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
415 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data1);
416 Width = LocationSize::precise(
417 Width.getValue() + TypeSize::getFixed(getOpSize(LdSt, DataOpIdx)));
418 } else {
419 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
420 }
421 }
422 return true;
423 }
424
425 if (isMUBUF(LdSt) || isMTBUF(LdSt)) {
426 const MachineOperand *RSrc = getNamedOperand(LdSt, AMDGPU::OpName::srsrc);
427 if (!RSrc) // e.g. BUFFER_WBINVL1_VOL
428 return false;
429 BaseOps.push_back(RSrc);
430 BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
431 if (BaseOp && !BaseOp->isFI())
432 BaseOps.push_back(BaseOp);
433 const MachineOperand *OffsetImm =
434 getNamedOperand(LdSt, AMDGPU::OpName::offset);
435 Offset = OffsetImm->getImm();
436 const MachineOperand *SOffset =
437 getNamedOperand(LdSt, AMDGPU::OpName::soffset);
438 if (SOffset) {
439 if (SOffset->isReg())
440 BaseOps.push_back(SOffset);
441 else
442 Offset += SOffset->getImm();
443 }
444 // Get appropriate operand, and compute width accordingly.
445 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
446 if (DataOpIdx == -1)
447 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
448 if (DataOpIdx == -1) // LDS DMA
449 return false;
450 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
451 return true;
452 }
453
454 if (isImage(LdSt)) {
455 auto RsrcOpName =
456 isMIMG(LdSt) ? AMDGPU::OpName::srsrc : AMDGPU::OpName::rsrc;
457 int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opc, RsrcOpName);
458 BaseOps.push_back(&LdSt.getOperand(SRsrcIdx));
459 int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
460 if (VAddr0Idx >= 0) {
461 // GFX10 possible NSA encoding.
462 for (int I = VAddr0Idx; I < SRsrcIdx; ++I)
463 BaseOps.push_back(&LdSt.getOperand(I));
464 } else {
465 BaseOps.push_back(getNamedOperand(LdSt, AMDGPU::OpName::vaddr));
466 }
467 Offset = 0;
468 // Get appropriate operand, and compute width accordingly.
469 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
470 if (DataOpIdx == -1)
471 return false; // no return sampler
472 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
473 return true;
474 }
475
476 if (isSMRD(LdSt)) {
477 BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::sbase);
478 if (!BaseOp) // e.g. S_MEMTIME
479 return false;
480 BaseOps.push_back(BaseOp);
481 OffsetOp = getNamedOperand(LdSt, AMDGPU::OpName::offset);
482 Offset = OffsetOp ? OffsetOp->getImm() : 0;
483 // Get appropriate operand, and compute width accordingly.
484 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::sdst);
485 if (DataOpIdx == -1)
486 return false;
487 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
488 return true;
489 }
490
491 if (isFLAT(LdSt)) {
492 // Instructions have either vaddr or saddr or both or none.
493 BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
494 if (BaseOp)
495 BaseOps.push_back(BaseOp);
496 BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::saddr);
497 if (BaseOp)
498 BaseOps.push_back(BaseOp);
499 Offset = getNamedOperand(LdSt, AMDGPU::OpName::offset)->getImm();
500 // Get appropriate operand, and compute width accordingly.
501 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
502 if (DataOpIdx == -1)
503 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
504 if (DataOpIdx == -1) // LDS DMA
505 return false;
506 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
507 return true;
508 }
509
510 return false;
511}
512
513static bool memOpsHaveSameBasePtr(const MachineInstr &MI1,
515 const MachineInstr &MI2,
517 // Only examine the first "base" operand of each instruction, on the
518 // assumption that it represents the real base address of the memory access.
519 // Other operands are typically offsets or indices from this base address.
520 if (BaseOps1.front()->isIdenticalTo(*BaseOps2.front()))
521 return true;
522
523 if (!MI1.hasOneMemOperand() || !MI2.hasOneMemOperand())
524 return false;
525
526 auto *MO1 = *MI1.memoperands_begin();
527 auto *MO2 = *MI2.memoperands_begin();
528 if (MO1->getAddrSpace() != MO2->getAddrSpace())
529 return false;
530
531 const auto *Base1 = MO1->getValue();
532 const auto *Base2 = MO2->getValue();
533 if (!Base1 || !Base2)
534 return false;
535 Base1 = getUnderlyingObject(Base1);
536 Base2 = getUnderlyingObject(Base2);
537
538 if (isa<UndefValue>(Base1) || isa<UndefValue>(Base2))
539 return false;
540
541 return Base1 == Base2;
542}
543
545 int64_t Offset1, bool OffsetIsScalable1,
547 int64_t Offset2, bool OffsetIsScalable2,
548 unsigned ClusterSize,
549 unsigned NumBytes) const {
550 // If the mem ops (to be clustered) do not have the same base ptr, then they
551 // should not be clustered
552 unsigned MaxMemoryClusterDWords = DefaultMemoryClusterDWordsLimit;
553 if (!BaseOps1.empty() && !BaseOps2.empty()) {
554 const MachineInstr &FirstLdSt = *BaseOps1.front()->getParent();
555 const MachineInstr &SecondLdSt = *BaseOps2.front()->getParent();
556 if (!memOpsHaveSameBasePtr(FirstLdSt, BaseOps1, SecondLdSt, BaseOps2))
557 return false;
558
559 const SIMachineFunctionInfo *MFI =
560 FirstLdSt.getMF()->getInfo<SIMachineFunctionInfo>();
561 MaxMemoryClusterDWords = MFI->getMaxMemoryClusterDWords();
562 } else if (!BaseOps1.empty() || !BaseOps2.empty()) {
563 // If only one base op is empty, they do not have the same base ptr
564 return false;
565 }
566
567 // In order to avoid register pressure, on an average, the number of DWORDS
568 // loaded together by all clustered mem ops should not exceed
569 // MaxMemoryClusterDWords. This is an empirical value based on certain
570 // observations and performance related experiments.
571 // The good thing about this heuristic is - it avoids clustering of too many
572 // sub-word loads, and also avoids clustering of wide loads. Below is the
573 // brief summary of how the heuristic behaves for various `LoadSize` when
574 // MaxMemoryClusterDWords is 8.
575 //
576 // (1) 1 <= LoadSize <= 4: cluster at max 8 mem ops
577 // (2) 5 <= LoadSize <= 8: cluster at max 4 mem ops
578 // (3) 9 <= LoadSize <= 12: cluster at max 2 mem ops
579 // (4) 13 <= LoadSize <= 16: cluster at max 2 mem ops
580 // (5) LoadSize >= 17: do not cluster
581 const unsigned LoadSize = NumBytes / ClusterSize;
582 const unsigned NumDWords = ((LoadSize + 3) / 4) * ClusterSize;
583 return NumDWords <= MaxMemoryClusterDWords;
584}
585
586// FIXME: This behaves strangely. If, for example, you have 32 load + stores,
587// the first 16 loads will be interleaved with the stores, and the next 16 will
588// be clustered as expected. It should really split into 2 16 store batches.
589//
590// Loads are clustered until this returns false, rather than trying to schedule
591// groups of stores. This also means we have to deal with saying different
592// address space loads should be clustered, and ones which might cause bank
593// conflicts.
594//
595// This might be deprecated so it might not be worth that much effort to fix.
597 int64_t Offset0, int64_t Offset1,
598 unsigned NumLoads) const {
599 assert(Offset1 > Offset0 &&
600 "Second offset should be larger than first offset!");
601 // If we have less than 16 loads in a row, and the offsets are within 64
602 // bytes, then schedule together.
603
604 // A cacheline is 64 bytes (for global memory).
605 return (NumLoads <= 16 && (Offset1 - Offset0) < 64);
606}
607
610 const DebugLoc &DL, MCRegister DestReg,
611 MCRegister SrcReg, bool KillSrc,
612 const char *Msg = "illegal VGPR to SGPR copy") {
613 MachineFunction *MF = MBB.getParent();
614
616 C.diagnose(DiagnosticInfoUnsupported(MF->getFunction(), Msg, DL, DS_Error));
617
618 BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_ILLEGAL_COPY), DestReg)
619 .addReg(SrcReg, getKillRegState(KillSrc));
620}
621
622/// Handle copying from SGPR to AGPR, or from AGPR to AGPR on GFX908. It is not
623/// possible to have a direct copy in these cases on GFX908, so an intermediate
624/// VGPR copy is required.
628 const DebugLoc &DL, MCRegister DestReg,
629 MCRegister SrcReg, bool KillSrc,
630 RegScavenger &RS, bool RegsOverlap,
631 Register ImpDefSuperReg = Register(),
632 Register ImpUseSuperReg = Register()) {
633 assert((TII.getSubtarget().hasMAIInsts() &&
634 !TII.getSubtarget().hasGFX90AInsts()) &&
635 "Expected GFX908 subtarget.");
636
637 assert((AMDGPU::SReg_32RegClass.contains(SrcReg) ||
638 AMDGPU::AGPR_32RegClass.contains(SrcReg)) &&
639 "Source register of the copy should be either an SGPR or an AGPR.");
640
641 assert(AMDGPU::AGPR_32RegClass.contains(DestReg) &&
642 "Destination register of the copy should be an AGPR.");
643
644 const SIRegisterInfo &RI = TII.getRegisterInfo();
645
646 // First try to find defining accvgpr_write to avoid temporary registers.
647 // In the case of copies of overlapping AGPRs, we conservatively do not
648 // reuse previous accvgpr_writes. Otherwise, we may incorrectly pick up
649 // an accvgpr_write used for this same copy due to implicit-defs
650 if (!RegsOverlap) {
651 for (auto Def = MI, E = MBB.begin(); Def != E; ) {
652 --Def;
653
654 if (!Def->modifiesRegister(SrcReg, &RI))
655 continue;
656
657 if (Def->getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32_e64 ||
658 Def->getOperand(0).getReg() != SrcReg)
659 break;
660
661 MachineOperand &DefOp = Def->getOperand(1);
662 assert(DefOp.isReg() || DefOp.isImm());
663
664 if (DefOp.isReg()) {
665 bool SafeToPropagate = true;
666 // Check that register source operand is not clobbered before MI.
667 // Immediate operands are always safe to propagate.
668 for (auto I = Def; I != MI && SafeToPropagate; ++I)
669 if (I->modifiesRegister(DefOp.getReg(), &RI))
670 SafeToPropagate = false;
671
672 if (!SafeToPropagate)
673 break;
674
675 for (auto I = Def; I != MI; ++I)
676 I->clearRegisterKills(DefOp.getReg(), &RI);
677 }
678
679 MachineInstrBuilder Builder =
680 BuildMI(MBB, MI, DL, TII.get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
681 .add(DefOp);
682 if (ImpDefSuperReg)
683 Builder.addReg(ImpDefSuperReg, RegState::Define | RegState::Implicit);
684
685 if (ImpUseSuperReg) {
686 Builder.addReg(ImpUseSuperReg,
688 }
689
690 return;
691 }
692 }
693
694 RS.enterBasicBlockEnd(MBB);
695 RS.backward(std::next(MI));
696
697 // Ideally we want to have three registers for a long reg_sequence copy
698 // to hide 2 waitstates between v_mov_b32 and accvgpr_write.
699 unsigned MaxVGPRs = RI.getRegPressureLimit(&AMDGPU::VGPR_32RegClass,
700 *MBB.getParent());
701
702 // Registers in the sequence are allocated contiguously so we can just
703 // use register number to pick one of three round-robin temps.
704 unsigned RegNo = (DestReg - AMDGPU::AGPR0) % 3;
705 Register Tmp =
706 MBB.getParent()->getInfo<SIMachineFunctionInfo>()->getVGPRForAGPRCopy();
707 assert(MBB.getParent()->getRegInfo().isReserved(Tmp) &&
708 "VGPR used for an intermediate copy should have been reserved.");
709
710 // Only loop through if there are any free registers left. We don't want to
711 // spill.
712 while (RegNo--) {
713 Register Tmp2 = RS.scavengeRegisterBackwards(AMDGPU::VGPR_32RegClass, MI,
714 /* RestoreAfter */ false, 0,
715 /* AllowSpill */ false);
716 if (!Tmp2 || RI.getHWRegIndex(Tmp2) >= MaxVGPRs)
717 break;
718 Tmp = Tmp2;
719 RS.setRegUsed(Tmp);
720 }
721
722 // Insert copy to temporary VGPR.
723 unsigned TmpCopyOp = AMDGPU::V_MOV_B32_e32;
724 if (AMDGPU::AGPR_32RegClass.contains(SrcReg)) {
725 TmpCopyOp = AMDGPU::V_ACCVGPR_READ_B32_e64;
726 } else {
727 assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
728 }
729
730 MachineInstrBuilder UseBuilder = BuildMI(MBB, MI, DL, TII.get(TmpCopyOp), Tmp)
731 .addReg(SrcReg, getKillRegState(KillSrc));
732 if (ImpUseSuperReg) {
733 UseBuilder.addReg(ImpUseSuperReg,
735 }
736
737 MachineInstrBuilder DefBuilder
738 = BuildMI(MBB, MI, DL, TII.get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
739 .addReg(Tmp, RegState::Kill);
740
741 if (ImpDefSuperReg)
742 DefBuilder.addReg(ImpDefSuperReg, RegState::Define | RegState::Implicit);
743}
744
747 MCRegister DestReg, MCRegister SrcReg, bool KillSrc,
748 const TargetRegisterClass *RC, bool Forward) {
749 const SIRegisterInfo &RI = TII.getRegisterInfo();
750 ArrayRef<int16_t> BaseIndices = RI.getRegSplitParts(RC, 4);
752 MachineInstr *FirstMI = nullptr, *LastMI = nullptr;
753
754 for (unsigned Idx = 0; Idx < BaseIndices.size(); ++Idx) {
755 int16_t SubIdx = BaseIndices[Idx];
756 Register DestSubReg = RI.getSubReg(DestReg, SubIdx);
757 Register SrcSubReg = RI.getSubReg(SrcReg, SubIdx);
758 assert(DestSubReg && SrcSubReg && "Failed to find subregs!");
759 unsigned Opcode = AMDGPU::S_MOV_B32;
760
761 // Is SGPR aligned? If so try to combine with next.
762 bool AlignedDest = ((DestSubReg - AMDGPU::SGPR0) % 2) == 0;
763 bool AlignedSrc = ((SrcSubReg - AMDGPU::SGPR0) % 2) == 0;
764 if (AlignedDest && AlignedSrc && (Idx + 1 < BaseIndices.size())) {
765 // Can use SGPR64 copy
766 unsigned Channel = RI.getChannelFromSubReg(SubIdx);
767 SubIdx = RI.getSubRegFromChannel(Channel, 2);
768 DestSubReg = RI.getSubReg(DestReg, SubIdx);
769 SrcSubReg = RI.getSubReg(SrcReg, SubIdx);
770 assert(DestSubReg && SrcSubReg && "Failed to find subregs!");
771 Opcode = AMDGPU::S_MOV_B64;
772 Idx++;
773 }
774
775 LastMI = BuildMI(MBB, I, DL, TII.get(Opcode), DestSubReg)
776 .addReg(SrcSubReg)
777 .addReg(SrcReg, RegState::Implicit);
778
779 if (!FirstMI)
780 FirstMI = LastMI;
781
782 if (!Forward)
783 I--;
784 }
785
786 assert(FirstMI && LastMI);
787 if (!Forward)
788 std::swap(FirstMI, LastMI);
789
790 FirstMI->addOperand(
791 MachineOperand::CreateReg(DestReg, true /*IsDef*/, true /*IsImp*/));
792
793 if (KillSrc)
794 LastMI->addRegisterKilled(SrcReg, &RI);
795}
796
799 const DebugLoc &DL, Register DestReg,
800 Register SrcReg, bool KillSrc, bool RenamableDest,
801 bool RenamableSrc) const {
802 const TargetRegisterClass *RC = RI.getPhysRegBaseClass(DestReg);
803 unsigned Size = RI.getRegSizeInBits(*RC);
804 const TargetRegisterClass *SrcRC = RI.getPhysRegBaseClass(SrcReg);
805 unsigned SrcSize = RI.getRegSizeInBits(*SrcRC);
806
807 // The rest of copyPhysReg assumes Src and Dst size are the same size.
808 // TODO-GFX11_16BIT If all true 16 bit instruction patterns are completed can
809 // we remove Fix16BitCopies and this code block?
810 if (Fix16BitCopies) {
811 if (((Size == 16) != (SrcSize == 16))) {
812 // Non-VGPR Src and Dst will later be expanded back to 32 bits.
813 assert(ST.useRealTrue16Insts());
814 Register &RegToFix = (Size == 32) ? DestReg : SrcReg;
815 MCRegister SubReg = RI.getSubReg(RegToFix, AMDGPU::lo16);
816 RegToFix = SubReg;
817
818 if (DestReg == SrcReg) {
819 // Identity copy. Insert empty bundle since ExpandPostRA expects an
820 // instruction here.
821 BuildMI(MBB, MI, DL, get(AMDGPU::BUNDLE));
822 return;
823 }
824 RC = RI.getPhysRegBaseClass(DestReg);
825 Size = RI.getRegSizeInBits(*RC);
826 SrcRC = RI.getPhysRegBaseClass(SrcReg);
827 SrcSize = RI.getRegSizeInBits(*SrcRC);
828 }
829 }
830
831 if (RC == &AMDGPU::VGPR_32RegClass) {
832 assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
833 AMDGPU::SReg_32RegClass.contains(SrcReg) ||
834 AMDGPU::AGPR_32RegClass.contains(SrcReg));
835 unsigned Opc = AMDGPU::AGPR_32RegClass.contains(SrcReg) ?
836 AMDGPU::V_ACCVGPR_READ_B32_e64 : AMDGPU::V_MOV_B32_e32;
837 BuildMI(MBB, MI, DL, get(Opc), DestReg)
838 .addReg(SrcReg, getKillRegState(KillSrc));
839 return;
840 }
841
842 if (RC == &AMDGPU::SReg_32_XM0RegClass ||
843 RC == &AMDGPU::SReg_32RegClass) {
844 if (SrcReg == AMDGPU::SCC) {
845 BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B32), DestReg)
846 .addImm(1)
847 .addImm(0);
848 return;
849 }
850
851 if (!AMDGPU::SReg_32RegClass.contains(SrcReg)) {
852 if (DestReg == AMDGPU::VCC_LO) {
853 // FIXME: Hack until VReg_1 removed.
854 assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
855 BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
856 .addImm(0)
857 .addReg(SrcReg, getKillRegState(KillSrc));
858 return;
859 }
860
861 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
862 return;
863 }
864
865 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
866 .addReg(SrcReg, getKillRegState(KillSrc));
867 return;
868 }
869
870 if (RC == &AMDGPU::SReg_64RegClass) {
871 if (SrcReg == AMDGPU::SCC) {
872 BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B64), DestReg)
873 .addImm(1)
874 .addImm(0);
875 return;
876 }
877
878 if (!AMDGPU::SReg_64_EncodableRegClass.contains(SrcReg)) {
879 if (DestReg == AMDGPU::VCC) {
880 // FIXME: Hack until VReg_1 removed.
881 assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
882 BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
883 .addImm(0)
884 .addReg(SrcReg, getKillRegState(KillSrc));
885 return;
886 }
887
888 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
889 return;
890 }
891
892 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
893 .addReg(SrcReg, getKillRegState(KillSrc));
894 return;
895 }
896
897 if (DestReg == AMDGPU::SCC) {
898 // Copying 64-bit or 32-bit sources to SCC barely makes sense,
899 // but SelectionDAG emits such copies for i1 sources.
900 if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
901 // This copy can only be produced by patterns
902 // with explicit SCC, which are known to be enabled
903 // only for subtargets with S_CMP_LG_U64 present.
904 assert(ST.hasScalarCompareEq64());
905 BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U64))
906 .addReg(SrcReg, getKillRegState(KillSrc))
907 .addImm(0);
908 } else {
909 assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
910 BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32))
911 .addReg(SrcReg, getKillRegState(KillSrc))
912 .addImm(0);
913 }
914
915 return;
916 }
917
918 if (RC == &AMDGPU::AGPR_32RegClass) {
919 if (AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
920 (ST.hasGFX90AInsts() && AMDGPU::SReg_32RegClass.contains(SrcReg))) {
921 BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
922 .addReg(SrcReg, getKillRegState(KillSrc));
923 return;
924 }
925
926 if (AMDGPU::AGPR_32RegClass.contains(SrcReg) && ST.hasGFX90AInsts()) {
927 BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_MOV_B32), DestReg)
928 .addReg(SrcReg, getKillRegState(KillSrc));
929 return;
930 }
931
932 // FIXME: Pass should maintain scavenger to avoid scan through the block on
933 // every AGPR spill.
934 RegScavenger RS;
935 const bool Overlap = RI.regsOverlap(SrcReg, DestReg);
936 indirectCopyToAGPR(*this, MBB, MI, DL, DestReg, SrcReg, KillSrc, RS, Overlap);
937 return;
938 }
939
940 if (Size == 16) {
941 assert(AMDGPU::VGPR_16RegClass.contains(SrcReg) ||
942 AMDGPU::SReg_LO16RegClass.contains(SrcReg) ||
943 AMDGPU::AGPR_LO16RegClass.contains(SrcReg));
944
945 bool IsSGPRDst = AMDGPU::SReg_LO16RegClass.contains(DestReg);
946 bool IsSGPRSrc = AMDGPU::SReg_LO16RegClass.contains(SrcReg);
947 bool IsAGPRDst = AMDGPU::AGPR_LO16RegClass.contains(DestReg);
948 bool IsAGPRSrc = AMDGPU::AGPR_LO16RegClass.contains(SrcReg);
949 bool DstLow = !AMDGPU::isHi16Reg(DestReg, RI);
950 bool SrcLow = !AMDGPU::isHi16Reg(SrcReg, RI);
951 MCRegister NewDestReg = RI.get32BitRegister(DestReg);
952 MCRegister NewSrcReg = RI.get32BitRegister(SrcReg);
953
954 if (IsSGPRDst) {
955 if (!IsSGPRSrc) {
956 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
957 return;
958 }
959
960 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), NewDestReg)
961 .addReg(NewSrcReg, getKillRegState(KillSrc));
962 return;
963 }
964
965 if (IsAGPRDst || IsAGPRSrc) {
966 if (!DstLow || !SrcLow) {
967 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc,
968 "Cannot use hi16 subreg with an AGPR!");
969 }
970
971 copyPhysReg(MBB, MI, DL, NewDestReg, NewSrcReg, KillSrc);
972 return;
973 }
974
975 if (ST.useRealTrue16Insts()) {
976 if (IsSGPRSrc) {
977 assert(SrcLow);
978 SrcReg = NewSrcReg;
979 }
980 // Use the smaller instruction encoding if possible.
981 if (AMDGPU::VGPR_16_Lo128RegClass.contains(DestReg) &&
982 (IsSGPRSrc || AMDGPU::VGPR_16_Lo128RegClass.contains(SrcReg))) {
983 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B16_t16_e32), DestReg)
984 .addReg(SrcReg);
985 } else {
986 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B16_t16_e64), DestReg)
987 .addImm(0) // src0_modifiers
988 .addReg(SrcReg)
989 .addImm(0); // op_sel
990 }
991 return;
992 }
993
994 if (IsSGPRSrc && !ST.hasSDWAScalar()) {
995 if (!DstLow || !SrcLow) {
996 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc,
997 "Cannot use hi16 subreg on VI!");
998 }
999
1000 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), NewDestReg)
1001 .addReg(NewSrcReg, getKillRegState(KillSrc));
1002 return;
1003 }
1004
1005 auto MIB = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_sdwa), NewDestReg)
1006 .addImm(0) // src0_modifiers
1007 .addReg(NewSrcReg)
1008 .addImm(0) // clamp
1015 // First implicit operand is $exec.
1016 MIB->tieOperands(0, MIB->getNumOperands() - 1);
1017 return;
1018 }
1019
1020 if (RC == RI.getVGPR64Class() && (SrcRC == RC || RI.isSGPRClass(SrcRC))) {
1021 if (ST.hasVMovB64Inst()) {
1022 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_e32), DestReg)
1023 .addReg(SrcReg, getKillRegState(KillSrc));
1024 return;
1025 }
1026 if (ST.hasPkMovB32()) {
1027 BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), DestReg)
1029 .addReg(SrcReg)
1031 .addReg(SrcReg)
1032 .addImm(0) // op_sel_lo
1033 .addImm(0) // op_sel_hi
1034 .addImm(0) // neg_lo
1035 .addImm(0) // neg_hi
1036 .addImm(0) // clamp
1037 .addReg(SrcReg, getKillRegState(KillSrc) | RegState::Implicit);
1038 return;
1039 }
1040 }
1041
1042 const bool Forward = RI.getHWRegIndex(DestReg) <= RI.getHWRegIndex(SrcReg);
1043 if (RI.isSGPRClass(RC)) {
1044 if (!RI.isSGPRClass(SrcRC)) {
1045 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
1046 return;
1047 }
1048 const bool CanKillSuperReg = KillSrc && !RI.regsOverlap(SrcReg, DestReg);
1049 expandSGPRCopy(*this, MBB, MI, DL, DestReg, SrcReg, CanKillSuperReg, RC,
1050 Forward);
1051 return;
1052 }
1053
1054 unsigned EltSize = 4;
1055 unsigned Opcode = AMDGPU::V_MOV_B32_e32;
1056 if (RI.isAGPRClass(RC)) {
1057 if (ST.hasGFX90AInsts() && RI.isAGPRClass(SrcRC))
1058 Opcode = AMDGPU::V_ACCVGPR_MOV_B32;
1059 else if (RI.hasVGPRs(SrcRC) ||
1060 (ST.hasGFX90AInsts() && RI.isSGPRClass(SrcRC)))
1061 Opcode = AMDGPU::V_ACCVGPR_WRITE_B32_e64;
1062 else
1063 Opcode = AMDGPU::INSTRUCTION_LIST_END;
1064 } else if (RI.hasVGPRs(RC) && RI.isAGPRClass(SrcRC)) {
1065 Opcode = AMDGPU::V_ACCVGPR_READ_B32_e64;
1066 } else if ((Size % 64 == 0) && RI.hasVGPRs(RC) &&
1067 (RI.isProperlyAlignedRC(*RC) &&
1068 (SrcRC == RC || RI.isSGPRClass(SrcRC)))) {
1069 // TODO: In 96-bit case, could do a 64-bit mov and then a 32-bit mov.
1070 if (ST.hasVMovB64Inst()) {
1071 Opcode = AMDGPU::V_MOV_B64_e32;
1072 EltSize = 8;
1073 } else if (ST.hasPkMovB32()) {
1074 Opcode = AMDGPU::V_PK_MOV_B32;
1075 EltSize = 8;
1076 }
1077 }
1078
1079 // For the cases where we need an intermediate instruction/temporary register
1080 // (destination is an AGPR), we need a scavenger.
1081 //
1082 // FIXME: The pass should maintain this for us so we don't have to re-scan the
1083 // whole block for every handled copy.
1084 std::unique_ptr<RegScavenger> RS;
1085 if (Opcode == AMDGPU::INSTRUCTION_LIST_END)
1086 RS = std::make_unique<RegScavenger>();
1087
1088 ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RC, EltSize);
1089
1090 // If there is an overlap, we can't kill the super-register on the last
1091 // instruction, since it will also kill the components made live by this def.
1092 const bool Overlap = RI.regsOverlap(SrcReg, DestReg);
1093 const bool CanKillSuperReg = KillSrc && !Overlap;
1094
1095 for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
1096 unsigned SubIdx;
1097 if (Forward)
1098 SubIdx = SubIndices[Idx];
1099 else
1100 SubIdx = SubIndices[SubIndices.size() - Idx - 1];
1101 Register DestSubReg = RI.getSubReg(DestReg, SubIdx);
1102 Register SrcSubReg = RI.getSubReg(SrcReg, SubIdx);
1103 assert(DestSubReg && SrcSubReg && "Failed to find subregs!");
1104
1105 bool IsFirstSubreg = Idx == 0;
1106 bool UseKill = CanKillSuperReg && Idx == SubIndices.size() - 1;
1107
1108 if (Opcode == AMDGPU::INSTRUCTION_LIST_END) {
1109 Register ImpDefSuper = IsFirstSubreg ? Register(DestReg) : Register();
1110 Register ImpUseSuper = SrcReg;
1111 indirectCopyToAGPR(*this, MBB, MI, DL, DestSubReg, SrcSubReg, UseKill,
1112 *RS, Overlap, ImpDefSuper, ImpUseSuper);
1113 } else if (Opcode == AMDGPU::V_PK_MOV_B32) {
1115 BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), DestSubReg)
1117 .addReg(SrcSubReg)
1119 .addReg(SrcSubReg)
1120 .addImm(0) // op_sel_lo
1121 .addImm(0) // op_sel_hi
1122 .addImm(0) // neg_lo
1123 .addImm(0) // neg_hi
1124 .addImm(0) // clamp
1125 .addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
1126 if (IsFirstSubreg)
1128 } else {
1129 MachineInstrBuilder Builder =
1130 BuildMI(MBB, MI, DL, get(Opcode), DestSubReg).addReg(SrcSubReg);
1131 if (IsFirstSubreg)
1132 Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
1133
1134 Builder.addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
1135 }
1136 }
1137}
1138
1139int SIInstrInfo::commuteOpcode(unsigned Opcode) const {
1140 int32_t NewOpc;
1141
1142 // Try to map original to commuted opcode
1143 NewOpc = AMDGPU::getCommuteRev(Opcode);
1144 if (NewOpc != -1)
1145 // Check if the commuted (REV) opcode exists on the target.
1146 return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
1147
1148 // Try to map commuted to original opcode
1149 NewOpc = AMDGPU::getCommuteOrig(Opcode);
1150 if (NewOpc != -1)
1151 // Check if the original (non-REV) opcode exists on the target.
1152 return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
1153
1154 return Opcode;
1155}
1156
1157const TargetRegisterClass *
1159 return &AMDGPU::VGPR_32RegClass;
1160}
1161
1164 const DebugLoc &DL, Register DstReg,
1166 Register TrueReg,
1167 Register FalseReg) const {
1168 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1169 const TargetRegisterClass *BoolXExecRC = RI.getWaveMaskRegClass();
1171 assert(MRI.getRegClass(DstReg) == &AMDGPU::VGPR_32RegClass &&
1172 "Not a VGPR32 reg");
1173
1174 if (Cond.size() == 1) {
1175 Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1176 BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
1177 .add(Cond[0]);
1178 BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1179 .addImm(0)
1180 .addReg(FalseReg)
1181 .addImm(0)
1182 .addReg(TrueReg)
1183 .addReg(SReg);
1184 } else if (Cond.size() == 2) {
1185 assert(Cond[0].isImm() && "Cond[0] is not an immediate");
1186 switch (Cond[0].getImm()) {
1187 case SIInstrInfo::SCC_TRUE: {
1188 Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1189 BuildMI(MBB, I, DL, get(LMC.CSelectOpc), SReg).addImm(1).addImm(0);
1190 BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1191 .addImm(0)
1192 .addReg(FalseReg)
1193 .addImm(0)
1194 .addReg(TrueReg)
1195 .addReg(SReg);
1196 break;
1197 }
1198 case SIInstrInfo::SCC_FALSE: {
1199 Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1200 BuildMI(MBB, I, DL, get(LMC.CSelectOpc), SReg).addImm(0).addImm(1);
1201 BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1202 .addImm(0)
1203 .addReg(FalseReg)
1204 .addImm(0)
1205 .addReg(TrueReg)
1206 .addReg(SReg);
1207 break;
1208 }
1209 case SIInstrInfo::VCCNZ: {
1210 MachineOperand RegOp = Cond[1];
1211 RegOp.setImplicit(false);
1212 Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1213 BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
1214 .add(RegOp);
1215 BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1216 .addImm(0)
1217 .addReg(FalseReg)
1218 .addImm(0)
1219 .addReg(TrueReg)
1220 .addReg(SReg);
1221 break;
1222 }
1223 case SIInstrInfo::VCCZ: {
1224 MachineOperand RegOp = Cond[1];
1225 RegOp.setImplicit(false);
1226 Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1227 BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
1228 .add(RegOp);
1229 BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1230 .addImm(0)
1231 .addReg(TrueReg)
1232 .addImm(0)
1233 .addReg(FalseReg)
1234 .addReg(SReg);
1235 break;
1236 }
1237 case SIInstrInfo::EXECNZ: {
1238 Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1239 Register SReg2 = MRI.createVirtualRegister(RI.getBoolRC());
1240 BuildMI(MBB, I, DL, get(LMC.OrSaveExecOpc), SReg2).addImm(0);
1241 BuildMI(MBB, I, DL, get(LMC.CSelectOpc), SReg).addImm(1).addImm(0);
1242 BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1243 .addImm(0)
1244 .addReg(FalseReg)
1245 .addImm(0)
1246 .addReg(TrueReg)
1247 .addReg(SReg);
1248 break;
1249 }
1250 case SIInstrInfo::EXECZ: {
1251 Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1252 Register SReg2 = MRI.createVirtualRegister(RI.getBoolRC());
1253 BuildMI(MBB, I, DL, get(LMC.OrSaveExecOpc), SReg2).addImm(0);
1254 BuildMI(MBB, I, DL, get(LMC.CSelectOpc), SReg).addImm(0).addImm(1);
1255 BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1256 .addImm(0)
1257 .addReg(FalseReg)
1258 .addImm(0)
1259 .addReg(TrueReg)
1260 .addReg(SReg);
1261 llvm_unreachable("Unhandled branch predicate EXECZ");
1262 break;
1263 }
1264 default:
1265 llvm_unreachable("invalid branch predicate");
1266 }
1267 } else {
1268 llvm_unreachable("Can only handle Cond size 1 or 2");
1269 }
1270}
1271
1274 const DebugLoc &DL,
1275 Register SrcReg, int Value) const {
1276 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1277 Register Reg = MRI.createVirtualRegister(RI.getBoolRC());
1278 BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_EQ_I32_e64), Reg)
1279 .addImm(Value)
1280 .addReg(SrcReg);
1281
1282 return Reg;
1283}
1284
1287 const DebugLoc &DL,
1288 Register SrcReg, int Value) const {
1289 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1290 Register Reg = MRI.createVirtualRegister(RI.getBoolRC());
1291 BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_NE_I32_e64), Reg)
1292 .addImm(Value)
1293 .addReg(SrcReg);
1294
1295 return Reg;
1296}
1297
1299 const Register Reg,
1300 int64_t &ImmVal) const {
1301 switch (MI.getOpcode()) {
1302 case AMDGPU::V_MOV_B32_e32:
1303 case AMDGPU::S_MOV_B32:
1304 case AMDGPU::S_MOVK_I32:
1305 case AMDGPU::S_MOV_B64:
1306 case AMDGPU::V_MOV_B64_e32:
1307 case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
1308 case AMDGPU::AV_MOV_B32_IMM_PSEUDO:
1309 case AMDGPU::AV_MOV_B64_IMM_PSEUDO:
1310 case AMDGPU::S_MOV_B64_IMM_PSEUDO:
1311 case AMDGPU::V_MOV_B64_PSEUDO:
1312 case AMDGPU::V_MOV_B16_t16_e32: {
1313 const MachineOperand &Src0 = MI.getOperand(1);
1314 if (Src0.isImm()) {
1315 ImmVal = Src0.getImm();
1316 return MI.getOperand(0).getReg() == Reg;
1317 }
1318
1319 return false;
1320 }
1321 case AMDGPU::V_MOV_B16_t16_e64: {
1322 const MachineOperand &Src0 = MI.getOperand(2);
1323 if (Src0.isImm() && !MI.getOperand(1).getImm()) {
1324 ImmVal = Src0.getImm();
1325 return MI.getOperand(0).getReg() == Reg;
1326 }
1327
1328 return false;
1329 }
1330 case AMDGPU::S_BREV_B32:
1331 case AMDGPU::V_BFREV_B32_e32:
1332 case AMDGPU::V_BFREV_B32_e64: {
1333 const MachineOperand &Src0 = MI.getOperand(1);
1334 if (Src0.isImm()) {
1335 ImmVal = static_cast<int64_t>(reverseBits<int32_t>(Src0.getImm()));
1336 return MI.getOperand(0).getReg() == Reg;
1337 }
1338
1339 return false;
1340 }
1341 case AMDGPU::S_NOT_B32:
1342 case AMDGPU::V_NOT_B32_e32:
1343 case AMDGPU::V_NOT_B32_e64: {
1344 const MachineOperand &Src0 = MI.getOperand(1);
1345 if (Src0.isImm()) {
1346 ImmVal = static_cast<int64_t>(~static_cast<int32_t>(Src0.getImm()));
1347 return MI.getOperand(0).getReg() == Reg;
1348 }
1349
1350 return false;
1351 }
1352 default:
1353 return false;
1354 }
1355}
1356
1357std::optional<int64_t>
1359 if (Op.isImm())
1360 return Op.getImm();
1361
1362 if (!Op.isReg() || !Op.getReg().isVirtual())
1363 return std::nullopt;
1364 MachineRegisterInfo &MRI = Op.getParent()->getMF()->getRegInfo();
1365 const MachineInstr *Def = MRI.getVRegDef(Op.getReg());
1366 if (Def && Def->isMoveImmediate()) {
1367 const MachineOperand &ImmSrc = Def->getOperand(1);
1368 if (ImmSrc.isImm())
1369 return extractSubregFromImm(ImmSrc.getImm(), Op.getSubReg());
1370 }
1371
1372 return std::nullopt;
1373}
1374
1376
1377 if (RI.isAGPRClass(DstRC))
1378 return AMDGPU::COPY;
1379 if (RI.getRegSizeInBits(*DstRC) == 16) {
1380 // Assume hi bits are unneeded. Only _e64 true16 instructions are legal
1381 // before RA.
1382 return RI.isSGPRClass(DstRC) ? AMDGPU::COPY : AMDGPU::V_MOV_B16_t16_e64;
1383 }
1384 if (RI.getRegSizeInBits(*DstRC) == 32)
1385 return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1386 if (RI.getRegSizeInBits(*DstRC) == 64 && RI.isSGPRClass(DstRC))
1387 return AMDGPU::S_MOV_B64;
1388 if (RI.getRegSizeInBits(*DstRC) == 64 && !RI.isSGPRClass(DstRC))
1389 return AMDGPU::V_MOV_B64_PSEUDO;
1390 return AMDGPU::COPY;
1391}
1392
1393const MCInstrDesc &
1395 bool IsIndirectSrc) const {
1396 if (IsIndirectSrc) {
1397 if (VecSize <= 32) // 4 bytes
1398 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V1);
1399 if (VecSize <= 64) // 8 bytes
1400 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V2);
1401 if (VecSize <= 96) // 12 bytes
1402 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V3);
1403 if (VecSize <= 128) // 16 bytes
1404 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V4);
1405 if (VecSize <= 160) // 20 bytes
1406 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V5);
1407 if (VecSize <= 192) // 24 bytes
1408 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V6);
1409 if (VecSize <= 224) // 28 bytes
1410 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V7);
1411 if (VecSize <= 256) // 32 bytes
1412 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V8);
1413 if (VecSize <= 288) // 36 bytes
1414 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V9);
1415 if (VecSize <= 320) // 40 bytes
1416 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V10);
1417 if (VecSize <= 352) // 44 bytes
1418 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V11);
1419 if (VecSize <= 384) // 48 bytes
1420 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V12);
1421 if (VecSize <= 512) // 64 bytes
1422 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V16);
1423 if (VecSize <= 1024) // 128 bytes
1424 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V32);
1425
1426 llvm_unreachable("unsupported size for IndirectRegReadGPRIDX pseudos");
1427 }
1428
1429 if (VecSize <= 32) // 4 bytes
1430 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V1);
1431 if (VecSize <= 64) // 8 bytes
1432 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V2);
1433 if (VecSize <= 96) // 12 bytes
1434 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V3);
1435 if (VecSize <= 128) // 16 bytes
1436 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V4);
1437 if (VecSize <= 160) // 20 bytes
1438 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V5);
1439 if (VecSize <= 192) // 24 bytes
1440 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V6);
1441 if (VecSize <= 224) // 28 bytes
1442 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V7);
1443 if (VecSize <= 256) // 32 bytes
1444 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V8);
1445 if (VecSize <= 288) // 36 bytes
1446 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V9);
1447 if (VecSize <= 320) // 40 bytes
1448 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V10);
1449 if (VecSize <= 352) // 44 bytes
1450 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V11);
1451 if (VecSize <= 384) // 48 bytes
1452 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V12);
1453 if (VecSize <= 512) // 64 bytes
1454 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V16);
1455 if (VecSize <= 1024) // 128 bytes
1456 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V32);
1457
1458 llvm_unreachable("unsupported size for IndirectRegWriteGPRIDX pseudos");
1459}
1460
1461static unsigned getIndirectVGPRWriteMovRelPseudoOpc(unsigned VecSize) {
1462 if (VecSize <= 32) // 4 bytes
1463 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V1;
1464 if (VecSize <= 64) // 8 bytes
1465 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V2;
1466 if (VecSize <= 96) // 12 bytes
1467 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V3;
1468 if (VecSize <= 128) // 16 bytes
1469 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V4;
1470 if (VecSize <= 160) // 20 bytes
1471 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V5;
1472 if (VecSize <= 192) // 24 bytes
1473 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V6;
1474 if (VecSize <= 224) // 28 bytes
1475 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V7;
1476 if (VecSize <= 256) // 32 bytes
1477 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V8;
1478 if (VecSize <= 288) // 36 bytes
1479 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V9;
1480 if (VecSize <= 320) // 40 bytes
1481 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V10;
1482 if (VecSize <= 352) // 44 bytes
1483 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V11;
1484 if (VecSize <= 384) // 48 bytes
1485 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V12;
1486 if (VecSize <= 512) // 64 bytes
1487 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V16;
1488 if (VecSize <= 1024) // 128 bytes
1489 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V32;
1490
1491 llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1492}
1493
1494static unsigned getIndirectSGPRWriteMovRelPseudo32(unsigned VecSize) {
1495 if (VecSize <= 32) // 4 bytes
1496 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V1;
1497 if (VecSize <= 64) // 8 bytes
1498 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V2;
1499 if (VecSize <= 96) // 12 bytes
1500 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V3;
1501 if (VecSize <= 128) // 16 bytes
1502 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V4;
1503 if (VecSize <= 160) // 20 bytes
1504 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V5;
1505 if (VecSize <= 192) // 24 bytes
1506 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V6;
1507 if (VecSize <= 224) // 28 bytes
1508 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V7;
1509 if (VecSize <= 256) // 32 bytes
1510 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V8;
1511 if (VecSize <= 288) // 36 bytes
1512 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V9;
1513 if (VecSize <= 320) // 40 bytes
1514 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V10;
1515 if (VecSize <= 352) // 44 bytes
1516 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V11;
1517 if (VecSize <= 384) // 48 bytes
1518 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V12;
1519 if (VecSize <= 512) // 64 bytes
1520 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V16;
1521 if (VecSize <= 1024) // 128 bytes
1522 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V32;
1523
1524 llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1525}
1526
1527static unsigned getIndirectSGPRWriteMovRelPseudo64(unsigned VecSize) {
1528 if (VecSize <= 64) // 8 bytes
1529 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V1;
1530 if (VecSize <= 128) // 16 bytes
1531 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V2;
1532 if (VecSize <= 256) // 32 bytes
1533 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V4;
1534 if (VecSize <= 512) // 64 bytes
1535 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V8;
1536 if (VecSize <= 1024) // 128 bytes
1537 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V16;
1538
1539 llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1540}
1541
1542const MCInstrDesc &
1543SIInstrInfo::getIndirectRegWriteMovRelPseudo(unsigned VecSize, unsigned EltSize,
1544 bool IsSGPR) const {
1545 if (IsSGPR) {
1546 switch (EltSize) {
1547 case 32:
1548 return get(getIndirectSGPRWriteMovRelPseudo32(VecSize));
1549 case 64:
1550 return get(getIndirectSGPRWriteMovRelPseudo64(VecSize));
1551 default:
1552 llvm_unreachable("invalid reg indexing elt size");
1553 }
1554 }
1555
1556 assert(EltSize == 32 && "invalid reg indexing elt size");
1558}
1559
1560static unsigned getSGPRSpillSaveOpcode(unsigned Size, bool NeedsCFI) {
1561 switch (Size) {
1562 case 4:
1563 return NeedsCFI ? AMDGPU::SI_SPILL_S32_CFI_SAVE : AMDGPU::SI_SPILL_S32_SAVE;
1564 case 8:
1565 return NeedsCFI ? AMDGPU::SI_SPILL_S64_CFI_SAVE : AMDGPU::SI_SPILL_S64_SAVE;
1566 case 12:
1567 return NeedsCFI ? AMDGPU::SI_SPILL_S96_CFI_SAVE : AMDGPU::SI_SPILL_S96_SAVE;
1568 case 16:
1569 return NeedsCFI ? AMDGPU::SI_SPILL_S128_CFI_SAVE
1570 : AMDGPU::SI_SPILL_S128_SAVE;
1571 case 20:
1572 return NeedsCFI ? AMDGPU::SI_SPILL_S160_CFI_SAVE
1573 : AMDGPU::SI_SPILL_S160_SAVE;
1574 case 24:
1575 return NeedsCFI ? AMDGPU::SI_SPILL_S192_CFI_SAVE
1576 : AMDGPU::SI_SPILL_S192_SAVE;
1577 case 28:
1578 return NeedsCFI ? AMDGPU::SI_SPILL_S224_CFI_SAVE
1579 : AMDGPU::SI_SPILL_S224_SAVE;
1580 case 32:
1581 return AMDGPU::SI_SPILL_S256_SAVE;
1582 case 36:
1583 return AMDGPU::SI_SPILL_S288_SAVE;
1584 case 40:
1585 return AMDGPU::SI_SPILL_S320_SAVE;
1586 case 44:
1587 return AMDGPU::SI_SPILL_S352_SAVE;
1588 case 48:
1589 return AMDGPU::SI_SPILL_S384_SAVE;
1590 case 64:
1591 return NeedsCFI ? AMDGPU::SI_SPILL_S512_CFI_SAVE
1592 : AMDGPU::SI_SPILL_S512_SAVE;
1593 case 128:
1594 return NeedsCFI ? AMDGPU::SI_SPILL_S1024_CFI_SAVE
1595 : AMDGPU::SI_SPILL_S1024_SAVE;
1596 default:
1597 llvm_unreachable("unknown register size");
1598 }
1599}
1600
1601static unsigned getVGPRSpillSaveOpcode(unsigned Size, bool NeedsCFI) {
1602 switch (Size) {
1603 case 2:
1604 return AMDGPU::SI_SPILL_V16_SAVE;
1605 case 4:
1606 return NeedsCFI ? AMDGPU::SI_SPILL_V32_CFI_SAVE : AMDGPU::SI_SPILL_V32_SAVE;
1607 case 8:
1608 return NeedsCFI ? AMDGPU::SI_SPILL_V64_CFI_SAVE : AMDGPU::SI_SPILL_V64_SAVE;
1609 case 12:
1610 return NeedsCFI ? AMDGPU::SI_SPILL_V96_CFI_SAVE : AMDGPU::SI_SPILL_V96_SAVE;
1611 case 16:
1612 return NeedsCFI ? AMDGPU::SI_SPILL_V128_CFI_SAVE
1613 : AMDGPU::SI_SPILL_V128_SAVE;
1614 case 20:
1615 return NeedsCFI ? AMDGPU::SI_SPILL_V160_CFI_SAVE
1616 : AMDGPU::SI_SPILL_V160_SAVE;
1617 case 24:
1618 return NeedsCFI ? AMDGPU::SI_SPILL_V192_CFI_SAVE
1619 : AMDGPU::SI_SPILL_V192_SAVE;
1620 case 28:
1621 return NeedsCFI ? AMDGPU::SI_SPILL_V224_CFI_SAVE
1622 : AMDGPU::SI_SPILL_V224_SAVE;
1623 case 32:
1624 return NeedsCFI ? AMDGPU::SI_SPILL_V256_CFI_SAVE
1625 : AMDGPU::SI_SPILL_V256_SAVE;
1626 case 36:
1627 return NeedsCFI ? AMDGPU::SI_SPILL_V288_CFI_SAVE
1628 : AMDGPU::SI_SPILL_V288_SAVE;
1629 case 40:
1630 return NeedsCFI ? AMDGPU::SI_SPILL_V320_CFI_SAVE
1631 : AMDGPU::SI_SPILL_V320_SAVE;
1632 case 44:
1633 return NeedsCFI ? AMDGPU::SI_SPILL_V352_CFI_SAVE
1634 : AMDGPU::SI_SPILL_V352_SAVE;
1635 case 48:
1636 return NeedsCFI ? AMDGPU::SI_SPILL_V384_CFI_SAVE
1637 : AMDGPU::SI_SPILL_V384_SAVE;
1638 case 64:
1639 return NeedsCFI ? AMDGPU::SI_SPILL_V512_CFI_SAVE
1640 : AMDGPU::SI_SPILL_V512_SAVE;
1641 case 128:
1642 return NeedsCFI ? AMDGPU::SI_SPILL_V1024_CFI_SAVE
1643 : AMDGPU::SI_SPILL_V1024_SAVE;
1644 default:
1645 llvm_unreachable("unknown register size");
1646 }
1647}
1648
1649static unsigned getAVSpillSaveOpcode(unsigned Size, bool NeedsCFI) {
1650 switch (Size) {
1651 case 4:
1652 return NeedsCFI ? AMDGPU::SI_SPILL_AV32_CFI_SAVE
1653 : AMDGPU::SI_SPILL_AV32_SAVE;
1654 case 8:
1655 return NeedsCFI ? AMDGPU::SI_SPILL_AV64_CFI_SAVE
1656 : AMDGPU::SI_SPILL_AV64_SAVE;
1657 case 12:
1658 return NeedsCFI ? AMDGPU::SI_SPILL_AV96_CFI_SAVE
1659 : AMDGPU::SI_SPILL_AV96_SAVE;
1660 case 16:
1661 return NeedsCFI ? AMDGPU::SI_SPILL_AV128_CFI_SAVE
1662 : AMDGPU::SI_SPILL_AV128_SAVE;
1663 case 20:
1664 return NeedsCFI ? AMDGPU::SI_SPILL_AV160_CFI_SAVE
1665 : AMDGPU::SI_SPILL_AV160_SAVE;
1666 case 24:
1667 return NeedsCFI ? AMDGPU::SI_SPILL_AV192_CFI_SAVE
1668 : AMDGPU::SI_SPILL_AV192_SAVE;
1669 case 28:
1670 return NeedsCFI ? AMDGPU::SI_SPILL_AV224_CFI_SAVE
1671 : AMDGPU::SI_SPILL_AV224_SAVE;
1672 case 32:
1673 return NeedsCFI ? AMDGPU::SI_SPILL_AV256_CFI_SAVE
1674 : AMDGPU::SI_SPILL_AV256_SAVE;
1675 case 36:
1676 return AMDGPU::SI_SPILL_AV288_SAVE;
1677 case 40:
1678 return AMDGPU::SI_SPILL_AV320_SAVE;
1679 case 44:
1680 return AMDGPU::SI_SPILL_AV352_SAVE;
1681 case 48:
1682 return AMDGPU::SI_SPILL_AV384_SAVE;
1683 case 64:
1684 return NeedsCFI ? AMDGPU::SI_SPILL_AV512_CFI_SAVE
1685 : AMDGPU::SI_SPILL_AV512_SAVE;
1686 case 128:
1687 return NeedsCFI ? AMDGPU::SI_SPILL_AV1024_CFI_SAVE
1688 : AMDGPU::SI_SPILL_AV1024_SAVE;
1689 default:
1690 llvm_unreachable("unknown register size");
1691 }
1692}
1693
1694static unsigned getWWMRegSpillSaveOpcode(unsigned Size,
1695 bool IsVectorSuperClass) {
1696 // Currently, there is only 32-bit WWM register spills needed.
1697 if (Size != 4)
1698 llvm_unreachable("unknown wwm register spill size");
1699
1700 if (IsVectorSuperClass)
1701 return AMDGPU::SI_SPILL_WWM_AV32_SAVE;
1702
1703 return AMDGPU::SI_SPILL_WWM_V32_SAVE;
1704}
1705
1707 Register Reg, const TargetRegisterClass *RC, unsigned Size,
1708 const SIMachineFunctionInfo &MFI, bool NeedsCFI) const {
1709 bool IsVectorSuperClass = RI.isVectorSuperClass(RC);
1710
1711 // Choose the right opcode if spilling a WWM register.
1713 return getWWMRegSpillSaveOpcode(Size, IsVectorSuperClass);
1714
1715 // TODO: Check if AGPRs are available
1716 if (ST.hasMAIInsts())
1717 return getAVSpillSaveOpcode(Size, NeedsCFI);
1718
1719 return getVGPRSpillSaveOpcode(Size, NeedsCFI);
1720}
1721
1722void SIInstrInfo::storeRegToStackSlotImpl(
1724 bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
1725 MachineInstr::MIFlag Flags, bool NeedsCFI) const {
1726 MachineFunction *MF = MBB.getParent();
1728 MachineFrameInfo &FrameInfo = MF->getFrameInfo();
1729 const DebugLoc &DL = MBB.findDebugLoc(MI);
1730
1731 MachinePointerInfo PtrInfo
1732 = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
1734 PtrInfo, MachineMemOperand::MOStore, FrameInfo.getObjectSize(FrameIndex),
1735 FrameInfo.getObjectAlign(FrameIndex));
1736 unsigned SpillSize = RI.getSpillSize(*RC);
1737
1738 MachineRegisterInfo &MRI = MF->getRegInfo();
1739 if (RI.isSGPRClass(RC)) {
1740 if (FrameInfo.getStackID(FrameIndex) == TargetStackID::SGPRSpill)
1741 MFI->setHasSpilledSGPRs();
1742 assert(SrcReg != AMDGPU::M0 && "m0 should not be spilled");
1743 assert(SrcReg != AMDGPU::EXEC_LO && SrcReg != AMDGPU::EXEC_HI &&
1744 SrcReg != AMDGPU::EXEC && "exec should not be spilled");
1745
1746 // We are only allowed to create one new instruction when spilling
1747 // registers, so we need to use pseudo instruction for spilling SGPRs.
1748 const MCInstrDesc &OpDesc =
1749 get(getSGPRSpillSaveOpcode(SpillSize, NeedsCFI));
1750
1751 // The SGPR spill/restore instructions only work on number sgprs, so we need
1752 // to make sure we are using the correct register class.
1753 if (SrcReg.isVirtual() && SpillSize == 4) {
1754 MRI.constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
1755 }
1756
1757 BuildMI(MBB, MI, DL, OpDesc)
1758 .addReg(SrcReg, getKillRegState(isKill)) // data
1759 .addFrameIndex(FrameIndex) // addr
1760 .addMemOperand(MMO)
1762
1763 return;
1764 }
1765
1766 unsigned Opcode = getVectorRegSpillSaveOpcode(VReg ? VReg : SrcReg, RC,
1767 SpillSize, *MFI, NeedsCFI);
1768 MFI->setHasSpilledVGPRs();
1769
1770 BuildMI(MBB, MI, DL, get(Opcode))
1771 .addReg(SrcReg, getKillRegState(isKill)) // data
1772 .addFrameIndex(FrameIndex) // addr
1773 .addReg(MFI->getStackPtrOffsetReg()) // scratch_offset
1774 .addImm(0) // offset
1775 .addMemOperand(MMO);
1776}
1777
1780 bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
1781 MachineInstr::MIFlag Flags) const {
1782 storeRegToStackSlotImpl(MBB, MI, SrcReg, isKill, FrameIndex, RC, VReg, Flags,
1783 false);
1784}
1785
1788 Register SrcReg, bool isKill,
1789 int FrameIndex,
1790 const TargetRegisterClass *RC) const {
1791 storeRegToStackSlotImpl(MBB, MI, SrcReg, isKill, FrameIndex, RC, Register(),
1792 MachineInstr::NoFlags, true);
1793}
1794
1795static unsigned getSGPRSpillRestoreOpcode(unsigned Size) {
1796 switch (Size) {
1797 case 4:
1798 return AMDGPU::SI_SPILL_S32_RESTORE;
1799 case 8:
1800 return AMDGPU::SI_SPILL_S64_RESTORE;
1801 case 12:
1802 return AMDGPU::SI_SPILL_S96_RESTORE;
1803 case 16:
1804 return AMDGPU::SI_SPILL_S128_RESTORE;
1805 case 20:
1806 return AMDGPU::SI_SPILL_S160_RESTORE;
1807 case 24:
1808 return AMDGPU::SI_SPILL_S192_RESTORE;
1809 case 28:
1810 return AMDGPU::SI_SPILL_S224_RESTORE;
1811 case 32:
1812 return AMDGPU::SI_SPILL_S256_RESTORE;
1813 case 36:
1814 return AMDGPU::SI_SPILL_S288_RESTORE;
1815 case 40:
1816 return AMDGPU::SI_SPILL_S320_RESTORE;
1817 case 44:
1818 return AMDGPU::SI_SPILL_S352_RESTORE;
1819 case 48:
1820 return AMDGPU::SI_SPILL_S384_RESTORE;
1821 case 64:
1822 return AMDGPU::SI_SPILL_S512_RESTORE;
1823 case 128:
1824 return AMDGPU::SI_SPILL_S1024_RESTORE;
1825 default:
1826 llvm_unreachable("unknown register size");
1827 }
1828}
1829
1830static unsigned getVGPRSpillRestoreOpcode(unsigned Size) {
1831 switch (Size) {
1832 case 2:
1833 return AMDGPU::SI_SPILL_V16_RESTORE;
1834 case 4:
1835 return AMDGPU::SI_SPILL_V32_RESTORE;
1836 case 8:
1837 return AMDGPU::SI_SPILL_V64_RESTORE;
1838 case 12:
1839 return AMDGPU::SI_SPILL_V96_RESTORE;
1840 case 16:
1841 return AMDGPU::SI_SPILL_V128_RESTORE;
1842 case 20:
1843 return AMDGPU::SI_SPILL_V160_RESTORE;
1844 case 24:
1845 return AMDGPU::SI_SPILL_V192_RESTORE;
1846 case 28:
1847 return AMDGPU::SI_SPILL_V224_RESTORE;
1848 case 32:
1849 return AMDGPU::SI_SPILL_V256_RESTORE;
1850 case 36:
1851 return AMDGPU::SI_SPILL_V288_RESTORE;
1852 case 40:
1853 return AMDGPU::SI_SPILL_V320_RESTORE;
1854 case 44:
1855 return AMDGPU::SI_SPILL_V352_RESTORE;
1856 case 48:
1857 return AMDGPU::SI_SPILL_V384_RESTORE;
1858 case 64:
1859 return AMDGPU::SI_SPILL_V512_RESTORE;
1860 case 128:
1861 return AMDGPU::SI_SPILL_V1024_RESTORE;
1862 default:
1863 llvm_unreachable("unknown register size");
1864 }
1865}
1866
1867static unsigned getAVSpillRestoreOpcode(unsigned Size) {
1868 switch (Size) {
1869 case 4:
1870 return AMDGPU::SI_SPILL_AV32_RESTORE;
1871 case 8:
1872 return AMDGPU::SI_SPILL_AV64_RESTORE;
1873 case 12:
1874 return AMDGPU::SI_SPILL_AV96_RESTORE;
1875 case 16:
1876 return AMDGPU::SI_SPILL_AV128_RESTORE;
1877 case 20:
1878 return AMDGPU::SI_SPILL_AV160_RESTORE;
1879 case 24:
1880 return AMDGPU::SI_SPILL_AV192_RESTORE;
1881 case 28:
1882 return AMDGPU::SI_SPILL_AV224_RESTORE;
1883 case 32:
1884 return AMDGPU::SI_SPILL_AV256_RESTORE;
1885 case 36:
1886 return AMDGPU::SI_SPILL_AV288_RESTORE;
1887 case 40:
1888 return AMDGPU::SI_SPILL_AV320_RESTORE;
1889 case 44:
1890 return AMDGPU::SI_SPILL_AV352_RESTORE;
1891 case 48:
1892 return AMDGPU::SI_SPILL_AV384_RESTORE;
1893 case 64:
1894 return AMDGPU::SI_SPILL_AV512_RESTORE;
1895 case 128:
1896 return AMDGPU::SI_SPILL_AV1024_RESTORE;
1897 default:
1898 llvm_unreachable("unknown register size");
1899 }
1900}
1901
1902static unsigned getWWMRegSpillRestoreOpcode(unsigned Size,
1903 bool IsVectorSuperClass) {
1904 // Currently, there is only 32-bit WWM register spills needed.
1905 if (Size != 4)
1906 llvm_unreachable("unknown wwm register spill size");
1907
1908 if (IsVectorSuperClass) // TODO: Always use this if there are AGPRs
1909 return AMDGPU::SI_SPILL_WWM_AV32_RESTORE;
1910
1911 return AMDGPU::SI_SPILL_WWM_V32_RESTORE;
1912}
1913
1915 Register Reg, const TargetRegisterClass *RC, unsigned Size,
1916 const SIMachineFunctionInfo &MFI) const {
1917 bool IsVectorSuperClass = RI.isVectorSuperClass(RC);
1918
1919 // Choose the right opcode if restoring a WWM register.
1921 return getWWMRegSpillRestoreOpcode(Size, IsVectorSuperClass);
1922
1923 // TODO: Check if AGPRs are available
1924 if (ST.hasMAIInsts())
1926
1927 assert(!RI.isAGPRClass(RC));
1929}
1930
1933 Register DestReg, int FrameIndex,
1934 const TargetRegisterClass *RC,
1935 Register VReg, unsigned SubReg,
1936 MachineInstr::MIFlag Flags) const {
1937 MachineFunction *MF = MBB.getParent();
1939 MachineFrameInfo &FrameInfo = MF->getFrameInfo();
1940 const DebugLoc &DL = MBB.findDebugLoc(MI);
1941 unsigned SpillSize = RI.getSpillSize(*RC);
1942
1943 MachinePointerInfo PtrInfo
1944 = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
1945
1947 PtrInfo, MachineMemOperand::MOLoad, FrameInfo.getObjectSize(FrameIndex),
1948 FrameInfo.getObjectAlign(FrameIndex));
1949
1950 if (RI.isSGPRClass(RC)) {
1951 if (FrameInfo.getStackID(FrameIndex) == TargetStackID::SGPRSpill)
1952 MFI->setHasSpilledSGPRs();
1953 assert(DestReg != AMDGPU::M0 && "m0 should not be reloaded into");
1954 assert(DestReg != AMDGPU::EXEC_LO && DestReg != AMDGPU::EXEC_HI &&
1955 DestReg != AMDGPU::EXEC && "exec should not be spilled");
1956
1957 // FIXME: Maybe this should not include a memoperand because it will be
1958 // lowered to non-memory instructions.
1959 const MCInstrDesc &OpDesc = get(getSGPRSpillRestoreOpcode(SpillSize));
1960 if (DestReg.isVirtual() && SpillSize == 4) {
1961 MachineRegisterInfo &MRI = MF->getRegInfo();
1962 MRI.constrainRegClass(DestReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
1963 }
1964
1965 BuildMI(MBB, MI, DL, OpDesc, DestReg)
1966 .addFrameIndex(FrameIndex) // addr
1967 .addMemOperand(MMO)
1969
1970 return;
1971 }
1972
1973 unsigned Opcode = getVectorRegSpillRestoreOpcode(VReg ? VReg : DestReg, RC,
1974 SpillSize, *MFI);
1975 BuildMI(MBB, MI, DL, get(Opcode), DestReg)
1976 .addFrameIndex(FrameIndex) // vaddr
1977 .addReg(MFI->getStackPtrOffsetReg()) // scratch_offset
1978 .addImm(0) // offset
1979 .addMemOperand(MMO);
1980}
1981
1986
1989 unsigned Quantity) const {
1990 DebugLoc DL = MBB.findDebugLoc(MI);
1991 unsigned MaxSNopCount = 1u << ST.getSNopBits();
1992 while (Quantity > 0) {
1993 unsigned Arg = std::min(Quantity, MaxSNopCount);
1994 Quantity -= Arg;
1995 BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP)).addImm(Arg - 1);
1996 }
1997}
1998
2000 auto *MF = MBB.getParent();
2002
2003 assert(Info->isEntryFunction());
2004
2005 if (MBB.succ_empty()) {
2006 bool HasNoTerminator = MBB.getFirstTerminator() == MBB.end();
2007 if (HasNoTerminator) {
2008 if (Info->returnsVoid()) {
2009 BuildMI(MBB, MBB.end(), DebugLoc(), get(AMDGPU::S_ENDPGM)).addImm(0);
2010 } else {
2011 BuildMI(MBB, MBB.end(), DebugLoc(), get(AMDGPU::SI_RETURN_TO_EPILOG));
2012 }
2013 }
2014 }
2015}
2016
2020 const DebugLoc &DL) const {
2021 MachineFunction *MF = MBB.getParent();
2022 constexpr unsigned DoorbellIDMask = 0x3ff;
2023 constexpr unsigned ECQueueWaveAbort = 0x400;
2024
2025 MachineBasicBlock *TrapBB = &MBB;
2026 MachineBasicBlock *HaltLoopBB = MF->CreateMachineBasicBlock();
2027
2028 if (!MBB.succ_empty() || std::next(MI.getIterator()) != MBB.end()) {
2029 MBB.splitAt(MI, /*UpdateLiveIns=*/false);
2030 TrapBB = MF->CreateMachineBasicBlock();
2031 BuildMI(MBB, MI, DL, get(AMDGPU::S_CBRANCH_EXECNZ)).addMBB(TrapBB);
2032 MF->push_back(TrapBB);
2033 MBB.addSuccessor(TrapBB);
2034 }
2035 // Start with a `s_trap 2`, if we're in PRIV=1 and we need the workaround this
2036 // will be a nop.
2037 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_TRAP))
2038 .addImm(static_cast<unsigned>(GCNSubtarget::TrapID::LLVMAMDHSATrap));
2039 Register DoorbellReg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
2040 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_SENDMSG_RTN_B32),
2041 DoorbellReg)
2043 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_MOV_B32), AMDGPU::TTMP2)
2044 .addUse(AMDGPU::M0);
2045 Register DoorbellRegMasked =
2046 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
2047 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_AND_B32), DoorbellRegMasked)
2048 .addUse(DoorbellReg)
2049 .addImm(DoorbellIDMask);
2050 Register SetWaveAbortBit =
2051 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
2052 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_OR_B32), SetWaveAbortBit)
2053 .addUse(DoorbellRegMasked)
2054 .addImm(ECQueueWaveAbort);
2055 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2056 .addUse(SetWaveAbortBit);
2057 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_SENDMSG))
2059 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2060 .addUse(AMDGPU::TTMP2);
2061 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_BRANCH)).addMBB(HaltLoopBB);
2062 TrapBB->addSuccessor(HaltLoopBB);
2063
2064 BuildMI(*HaltLoopBB, HaltLoopBB->end(), DL, get(AMDGPU::S_SETHALT)).addImm(5);
2065 BuildMI(*HaltLoopBB, HaltLoopBB->end(), DL, get(AMDGPU::S_BRANCH))
2066 .addMBB(HaltLoopBB);
2067 MF->push_back(HaltLoopBB);
2068 HaltLoopBB->addSuccessor(HaltLoopBB);
2069
2070 return MBB.getNextNode();
2071}
2072
2074 switch (MI.getOpcode()) {
2075 default:
2076 if (MI.isMetaInstruction())
2077 return 0;
2078 return 1; // FIXME: Do wait states equal cycles?
2079
2080 case AMDGPU::S_NOP:
2081 return MI.getOperand(0).getImm() + 1;
2082 // SI_RETURN_TO_EPILOG is a fallthrough to code outside of the function. The
2083 // hazard, even if one exist, won't really be visible. Should we handle it?
2084 }
2085}
2086
2088 MachineBasicBlock &MBB = *MI.getParent();
2089 DebugLoc DL = MBB.findDebugLoc(MI);
2091 switch (MI.getOpcode()) {
2092 default: return TargetInstrInfo::expandPostRAPseudo(MI);
2093 case AMDGPU::S_MOV_B64_term:
2094 // This is only a terminator to get the correct spill code placement during
2095 // register allocation.
2096 MI.setDesc(get(AMDGPU::S_MOV_B64));
2097 break;
2098
2099 case AMDGPU::S_MOV_B32_term:
2100 // This is only a terminator to get the correct spill code placement during
2101 // register allocation.
2102 MI.setDesc(get(AMDGPU::S_MOV_B32));
2103 break;
2104
2105 case AMDGPU::S_XOR_B64_term:
2106 // This is only a terminator to get the correct spill code placement during
2107 // register allocation.
2108 MI.setDesc(get(AMDGPU::S_XOR_B64));
2109 break;
2110
2111 case AMDGPU::S_XOR_B32_term:
2112 // This is only a terminator to get the correct spill code placement during
2113 // register allocation.
2114 MI.setDesc(get(AMDGPU::S_XOR_B32));
2115 break;
2116 case AMDGPU::S_OR_B64_term:
2117 // This is only a terminator to get the correct spill code placement during
2118 // register allocation.
2119 MI.setDesc(get(AMDGPU::S_OR_B64));
2120 break;
2121 case AMDGPU::S_OR_B32_term:
2122 // This is only a terminator to get the correct spill code placement during
2123 // register allocation.
2124 MI.setDesc(get(AMDGPU::S_OR_B32));
2125 break;
2126
2127 case AMDGPU::S_ANDN2_B64_term:
2128 // This is only a terminator to get the correct spill code placement during
2129 // register allocation.
2130 MI.setDesc(get(AMDGPU::S_ANDN2_B64));
2131 break;
2132
2133 case AMDGPU::S_ANDN2_B32_term:
2134 // This is only a terminator to get the correct spill code placement during
2135 // register allocation.
2136 MI.setDesc(get(AMDGPU::S_ANDN2_B32));
2137 break;
2138
2139 case AMDGPU::S_AND_B64_term:
2140 // This is only a terminator to get the correct spill code placement during
2141 // register allocation.
2142 MI.setDesc(get(AMDGPU::S_AND_B64));
2143 break;
2144
2145 case AMDGPU::S_AND_B32_term:
2146 // This is only a terminator to get the correct spill code placement during
2147 // register allocation.
2148 MI.setDesc(get(AMDGPU::S_AND_B32));
2149 break;
2150
2151 case AMDGPU::S_AND_SAVEEXEC_B64_term:
2152 // This is only a terminator to get the correct spill code placement during
2153 // register allocation.
2154 MI.setDesc(get(AMDGPU::S_AND_SAVEEXEC_B64));
2155 break;
2156
2157 case AMDGPU::S_AND_SAVEEXEC_B32_term:
2158 // This is only a terminator to get the correct spill code placement during
2159 // register allocation.
2160 MI.setDesc(get(AMDGPU::S_AND_SAVEEXEC_B32));
2161 break;
2162
2163 case AMDGPU::SI_SPILL_S32_TO_VGPR:
2164 MI.setDesc(get(AMDGPU::V_WRITELANE_B32));
2165 break;
2166
2167 case AMDGPU::SI_RESTORE_S32_FROM_VGPR:
2168 MI.setDesc(get(AMDGPU::V_READLANE_B32));
2169 break;
2170 case AMDGPU::AV_MOV_B32_IMM_PSEUDO: {
2171 Register Dst = MI.getOperand(0).getReg();
2172 bool IsAGPR = SIRegisterInfo::isAGPRClass(RI.getPhysRegBaseClass(Dst));
2173 MI.setDesc(
2174 get(IsAGPR ? AMDGPU::V_ACCVGPR_WRITE_B32_e64 : AMDGPU::V_MOV_B32_e32));
2175 break;
2176 }
2177 case AMDGPU::AV_MOV_B64_IMM_PSEUDO: {
2178 Register Dst = MI.getOperand(0).getReg();
2179 if (SIRegisterInfo::isAGPRClass(RI.getPhysRegBaseClass(Dst))) {
2180 int64_t Imm = MI.getOperand(1).getImm();
2181
2182 Register DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
2183 Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
2184 BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DstLo)
2185 .addImm(SignExtend64<32>(Imm));
2186 BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DstHi)
2187 .addImm(SignExtend64<32>(Imm >> 32));
2188 MI.eraseFromParent();
2189 break;
2190 }
2191
2192 [[fallthrough]];
2193 }
2194 case AMDGPU::V_MOV_B64_PSEUDO: {
2195 Register Dst = MI.getOperand(0).getReg();
2196 Register DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
2197 Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
2198
2199 const MCInstrDesc &Mov64Desc = get(AMDGPU::V_MOV_B64_e32);
2200 const TargetRegisterClass *Mov64RC = getRegClass(Mov64Desc, /*OpNum=*/0);
2201
2202 const MachineOperand &SrcOp = MI.getOperand(1);
2203 // FIXME: Will this work for 64-bit floating point immediates?
2204 assert(!SrcOp.isFPImm());
2205 if (ST.hasVMovB64Inst() && Mov64RC->contains(Dst)) {
2206 MI.setDesc(Mov64Desc);
2207 if (SrcOp.isReg() || isInlineConstant(MI, 1) ||
2208 isUInt<32>(SrcOp.getImm()) || ST.has64BitLiterals())
2209 break;
2210 }
2211 if (SrcOp.isImm()) {
2212 APInt Imm(64, SrcOp.getImm());
2213 APInt Lo(32, Imm.getLoBits(32).getZExtValue());
2214 APInt Hi(32, Imm.getHiBits(32).getZExtValue());
2215 const MCInstrDesc &PkMovDesc = get(AMDGPU::V_PK_MOV_B32);
2216 const TargetRegisterClass *PkMovRC = getRegClass(PkMovDesc, /*OpNum=*/0);
2217
2218 if (ST.hasPkMovB32() && Lo == Hi && isInlineConstant(Lo) &&
2219 PkMovRC->contains(Dst)) {
2220 BuildMI(MBB, MI, DL, PkMovDesc, Dst)
2222 .addImm(Lo.getSExtValue())
2224 .addImm(Lo.getSExtValue())
2225 .addImm(0) // op_sel_lo
2226 .addImm(0) // op_sel_hi
2227 .addImm(0) // neg_lo
2228 .addImm(0) // neg_hi
2229 .addImm(0); // clamp
2230 } else {
2231 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
2232 .addImm(Lo.getSExtValue());
2233 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
2234 .addImm(Hi.getSExtValue());
2235 }
2236 } else {
2237 assert(SrcOp.isReg());
2238 if (ST.hasPkMovB32() &&
2239 !RI.isAGPR(MBB.getParent()->getRegInfo(), SrcOp.getReg())) {
2240 BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), Dst)
2241 .addImm(SISrcMods::OP_SEL_1) // src0_mod
2242 .addReg(SrcOp.getReg())
2244 .addReg(SrcOp.getReg())
2245 .addImm(0) // op_sel_lo
2246 .addImm(0) // op_sel_hi
2247 .addImm(0) // neg_lo
2248 .addImm(0) // neg_hi
2249 .addImm(0); // clamp
2250 } else {
2251 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
2252 .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0));
2253 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
2254 .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1));
2255 }
2256 }
2257 MI.eraseFromParent();
2258 break;
2259 }
2260 case AMDGPU::V_MOV_B64_DPP_PSEUDO: {
2262 break;
2263 }
2264 case AMDGPU::S_MOV_B64_IMM_PSEUDO: {
2265 const MachineOperand &SrcOp = MI.getOperand(1);
2266 assert(!SrcOp.isFPImm());
2267
2268 if (ST.has64BitLiterals()) {
2269 MI.setDesc(get(AMDGPU::S_MOV_B64));
2270 break;
2271 }
2272
2273 APInt Imm(64, SrcOp.getImm());
2274 if (Imm.isIntN(32) || isInlineConstant(Imm)) {
2275 MI.setDesc(get(AMDGPU::S_MOV_B64));
2276 break;
2277 }
2278
2279 Register Dst = MI.getOperand(0).getReg();
2280 Register DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
2281 Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
2282
2283 APInt Lo(32, Imm.getLoBits(32).getZExtValue());
2284 APInt Hi(32, Imm.getHiBits(32).getZExtValue());
2285 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DstLo)
2286 .addImm(Lo.getSExtValue());
2287 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DstHi)
2288 .addImm(Hi.getSExtValue());
2289 MI.eraseFromParent();
2290 break;
2291 }
2292 case AMDGPU::V_SET_INACTIVE_B32: {
2293 // Lower V_SET_INACTIVE_B32 to V_CNDMASK_B32.
2294 Register DstReg = MI.getOperand(0).getReg();
2295 BuildMI(MBB, MI, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
2296 .add(MI.getOperand(3))
2297 .add(MI.getOperand(4))
2298 .add(MI.getOperand(1))
2299 .add(MI.getOperand(2))
2300 .add(MI.getOperand(5));
2301 MI.eraseFromParent();
2302 break;
2303 }
2304 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V1:
2305 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V2:
2306 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V3:
2307 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V4:
2308 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V5:
2309 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V6:
2310 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V7:
2311 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V8:
2312 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V9:
2313 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V10:
2314 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V11:
2315 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V12:
2316 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V16:
2317 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V32:
2318 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V1:
2319 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V2:
2320 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V3:
2321 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V4:
2322 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V5:
2323 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V6:
2324 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V7:
2325 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V8:
2326 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V9:
2327 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V10:
2328 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V11:
2329 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V12:
2330 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V16:
2331 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V32:
2332 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V1:
2333 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V2:
2334 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V4:
2335 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V8:
2336 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V16: {
2337 const TargetRegisterClass *EltRC = getOpRegClass(MI, 2);
2338
2339 unsigned Opc;
2340 if (RI.hasVGPRs(EltRC)) {
2341 Opc = AMDGPU::V_MOVRELD_B32_e32;
2342 } else {
2343 Opc = RI.getRegSizeInBits(*EltRC) == 64 ? AMDGPU::S_MOVRELD_B64
2344 : AMDGPU::S_MOVRELD_B32;
2345 }
2346
2347 const MCInstrDesc &OpDesc = get(Opc);
2348 Register VecReg = MI.getOperand(0).getReg();
2349 bool IsUndef = MI.getOperand(1).isUndef();
2350 unsigned SubReg = MI.getOperand(3).getImm();
2351 assert(VecReg == MI.getOperand(1).getReg());
2352
2354 BuildMI(MBB, MI, DL, OpDesc)
2355 .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
2356 .add(MI.getOperand(2))
2358 .addReg(VecReg, RegState::Implicit | getUndefRegState(IsUndef));
2359
2360 const int ImpDefIdx =
2361 OpDesc.getNumOperands() + OpDesc.implicit_uses().size();
2362 const int ImpUseIdx = ImpDefIdx + 1;
2363 MIB->tieOperands(ImpDefIdx, ImpUseIdx);
2364 MI.eraseFromParent();
2365 break;
2366 }
2367 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V1:
2368 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V2:
2369 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V3:
2370 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V4:
2371 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V5:
2372 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V6:
2373 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V7:
2374 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V8:
2375 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V9:
2376 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V10:
2377 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V11:
2378 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V12:
2379 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V16:
2380 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V32: {
2381 assert(ST.useVGPRIndexMode());
2382 Register VecReg = MI.getOperand(0).getReg();
2383 bool IsUndef = MI.getOperand(1).isUndef();
2384 MachineOperand &Idx = MI.getOperand(3);
2385 Register SubReg = MI.getOperand(4).getImm();
2386
2387 MachineInstr *SetOn = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_ON))
2388 .add(Idx)
2390 SetOn->getOperand(3).setIsUndef();
2391
2392 const MCInstrDesc &OpDesc = get(AMDGPU::V_MOV_B32_indirect_write);
2394 BuildMI(MBB, MI, DL, OpDesc)
2395 .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
2396 .add(MI.getOperand(2))
2398 .addReg(VecReg, RegState::Implicit | getUndefRegState(IsUndef));
2399
2400 const int ImpDefIdx =
2401 OpDesc.getNumOperands() + OpDesc.implicit_uses().size();
2402 const int ImpUseIdx = ImpDefIdx + 1;
2403 MIB->tieOperands(ImpDefIdx, ImpUseIdx);
2404
2405 MachineInstr *SetOff = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_OFF));
2406
2407 finalizeBundle(MBB, SetOn->getIterator(), std::next(SetOff->getIterator()));
2408
2409 MI.eraseFromParent();
2410 break;
2411 }
2412 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V1:
2413 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V2:
2414 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V3:
2415 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V4:
2416 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V5:
2417 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V6:
2418 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V7:
2419 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V8:
2420 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V9:
2421 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V10:
2422 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V11:
2423 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V12:
2424 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V16:
2425 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V32: {
2426 assert(ST.useVGPRIndexMode());
2427 Register Dst = MI.getOperand(0).getReg();
2428 Register VecReg = MI.getOperand(1).getReg();
2429 bool IsUndef = MI.getOperand(1).isUndef();
2430 Register SubReg = MI.getOperand(3).getImm();
2431
2432 MachineInstr *SetOn = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_ON))
2433 .add(MI.getOperand(2))
2435 SetOn->getOperand(3).setIsUndef();
2436
2437 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_indirect_read))
2438 .addDef(Dst)
2439 .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
2440 .addReg(VecReg, RegState::Implicit | getUndefRegState(IsUndef));
2441
2442 MachineInstr *SetOff = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_OFF));
2443
2444 finalizeBundle(MBB, SetOn->getIterator(), std::next(SetOff->getIterator()));
2445
2446 MI.eraseFromParent();
2447 break;
2448 }
2449 case AMDGPU::SI_PC_ADD_REL_OFFSET: {
2450 MachineFunction &MF = *MBB.getParent();
2451 Register Reg = MI.getOperand(0).getReg();
2452 Register RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
2453 Register RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
2454 MachineOperand OpLo = MI.getOperand(1);
2455 MachineOperand OpHi = MI.getOperand(2);
2456
2457 // Create a bundle so these instructions won't be re-ordered by the
2458 // post-RA scheduler.
2459 MIBundleBuilder Bundler(MBB, MI);
2460 Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
2461
2462 // What we want here is an offset from the value returned by s_getpc (which
2463 // is the address of the s_add_u32 instruction) to the global variable, but
2464 // since the encoding of $symbol starts 4 bytes after the start of the
2465 // s_add_u32 instruction, we end up with an offset that is 4 bytes too
2466 // small. This requires us to add 4 to the global variable offset in order
2467 // to compute the correct address. Similarly for the s_addc_u32 instruction,
2468 // the encoding of $symbol starts 12 bytes after the start of the s_add_u32
2469 // instruction.
2470
2471 int64_t Adjust = 0;
2472 if (ST.hasGetPCZeroExtension()) {
2473 // Fix up hardware that does not sign-extend the 48-bit PC value by
2474 // inserting: s_sext_i32_i16 reghi, reghi
2475 Bundler.append(
2476 BuildMI(MF, DL, get(AMDGPU::S_SEXT_I32_I16), RegHi).addReg(RegHi));
2477 Adjust += 4;
2478 }
2479
2480 if (OpLo.isGlobal())
2481 OpLo.setOffset(OpLo.getOffset() + Adjust + 4);
2482 Bundler.append(
2483 BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo).addReg(RegLo).add(OpLo));
2484
2485 if (OpHi.isGlobal())
2486 OpHi.setOffset(OpHi.getOffset() + Adjust + 12);
2487 Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
2488 .addReg(RegHi)
2489 .add(OpHi));
2490
2491 finalizeBundle(MBB, Bundler.begin());
2492
2493 MI.eraseFromParent();
2494 break;
2495 }
2496 case AMDGPU::SI_PC_ADD_REL_OFFSET64: {
2497 MachineFunction &MF = *MBB.getParent();
2498 Register Reg = MI.getOperand(0).getReg();
2499 MachineOperand Op = MI.getOperand(1);
2500
2501 // Create a bundle so these instructions won't be re-ordered by the
2502 // post-RA scheduler.
2503 MIBundleBuilder Bundler(MBB, MI);
2504 Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
2505 if (Op.isGlobal())
2506 Op.setOffset(Op.getOffset() + 4);
2507 Bundler.append(
2508 BuildMI(MF, DL, get(AMDGPU::S_ADD_U64), Reg).addReg(Reg).add(Op));
2509
2510 finalizeBundle(MBB, Bundler.begin());
2511
2512 MI.eraseFromParent();
2513 break;
2514 }
2515 case AMDGPU::ENTER_STRICT_WWM: {
2516 // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
2517 // Whole Wave Mode is entered.
2518 MI.setDesc(get(LMC.OrSaveExecOpc));
2519 break;
2520 }
2521 case AMDGPU::ENTER_STRICT_WQM: {
2522 // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
2523 // STRICT_WQM is entered.
2524 BuildMI(MBB, MI, DL, get(LMC.MovOpc), MI.getOperand(0).getReg())
2525 .addReg(LMC.ExecReg);
2526 BuildMI(MBB, MI, DL, get(LMC.WQMOpc), LMC.ExecReg).addReg(LMC.ExecReg);
2527
2528 MI.eraseFromParent();
2529 break;
2530 }
2531 case AMDGPU::EXIT_STRICT_WWM:
2532 case AMDGPU::EXIT_STRICT_WQM: {
2533 // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
2534 // WWM/STICT_WQM is exited.
2535 MI.setDesc(get(LMC.MovOpc));
2536 break;
2537 }
2538 case AMDGPU::SI_RETURN: {
2539 const MachineFunction *MF = MBB.getParent();
2540 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
2541 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2542 // Hiding the return address use with SI_RETURN may lead to extra kills in
2543 // the function and missing live-ins. We are fine in practice because callee
2544 // saved register handling ensures the register value is restored before
2545 // RET, but we need the undef flag here to appease the MachineVerifier
2546 // liveness checks.
2548 BuildMI(MBB, MI, DL, get(AMDGPU::S_SETPC_B64_return))
2549 .addReg(TRI->getReturnAddressReg(*MF), RegState::Undef);
2550
2551 MIB.copyImplicitOps(MI);
2552 MI.eraseFromParent();
2553 break;
2554 }
2555
2556 case AMDGPU::S_MUL_U64_U32_PSEUDO:
2557 case AMDGPU::S_MUL_I64_I32_PSEUDO:
2558 MI.setDesc(get(AMDGPU::S_MUL_U64));
2559 break;
2560
2561 case AMDGPU::S_GETPC_B64_pseudo:
2562 MI.setDesc(get(AMDGPU::S_GETPC_B64));
2563 if (ST.hasGetPCZeroExtension()) {
2564 Register Dst = MI.getOperand(0).getReg();
2565 Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
2566 // Fix up hardware that does not sign-extend the 48-bit PC value by
2567 // inserting: s_sext_i32_i16 dsthi, dsthi
2568 BuildMI(MBB, std::next(MI.getIterator()), DL, get(AMDGPU::S_SEXT_I32_I16),
2569 DstHi)
2570 .addReg(DstHi);
2571 }
2572 break;
2573
2574 case AMDGPU::V_MAX_BF16_PSEUDO_e64: {
2575 assert(ST.hasBF16PackedInsts());
2576 MI.setDesc(get(AMDGPU::V_PK_MAX_NUM_BF16));
2577 MI.addOperand(MachineOperand::CreateImm(0)); // op_sel
2578 MI.addOperand(MachineOperand::CreateImm(0)); // neg_lo
2579 MI.addOperand(MachineOperand::CreateImm(0)); // neg_hi
2580 auto Op0 = getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
2581 Op0->setImm(Op0->getImm() | SISrcMods::OP_SEL_1);
2582 auto Op1 = getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
2583 Op1->setImm(Op1->getImm() | SISrcMods::OP_SEL_1);
2584 break;
2585 }
2586
2587 case AMDGPU::GET_STACK_BASE:
2588 // The stack starts at offset 0 unless we need to reserve some space at the
2589 // bottom.
2590 if (ST.getFrameLowering()->mayReserveScratchForCWSR(*MBB.getParent())) {
2591 // When CWSR is used in dynamic VGPR mode, the trap handler needs to save
2592 // some of the VGPRs. The size of the required scratch space has already
2593 // been computed by prolog epilog insertion.
2594 const SIMachineFunctionInfo *MFI =
2595 MBB.getParent()->getInfo<SIMachineFunctionInfo>();
2596 unsigned VGPRSize = MFI->getScratchReservedForDynamicVGPRs();
2597 Register DestReg = MI.getOperand(0).getReg();
2598 BuildMI(MBB, MI, DL, get(AMDGPU::S_GETREG_B32), DestReg)
2601 // The MicroEngine ID is 0 for the graphics queue, and 1 or 2 for compute
2602 // (3 is unused, so we ignore it). Unfortunately, S_GETREG doesn't set
2603 // SCC, so we need to check for 0 manually.
2604 BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32)).addImm(0).addReg(DestReg);
2605 // Change the implicif-def of SCC to an explicit use (but first remove
2606 // the dead flag if present).
2607 MI.getOperand(MI.getNumExplicitOperands()).setIsDead(false);
2608 MI.getOperand(MI.getNumExplicitOperands()).setIsUse();
2609 MI.setDesc(get(AMDGPU::S_CMOVK_I32));
2610 MI.addOperand(MachineOperand::CreateImm(VGPRSize));
2611 } else {
2612 MI.setDesc(get(AMDGPU::S_MOV_B32));
2613 MI.addOperand(MachineOperand::CreateImm(0));
2614 MI.removeOperand(
2615 MI.getNumExplicitOperands()); // Drop implicit def of SCC.
2616 }
2617 break;
2618 }
2619
2620 return true;
2621}
2622
2625 unsigned SubIdx, const MachineInstr &Orig,
2626 LaneBitmask UsedLanes) const {
2627
2628 // Try shrinking the instruction to remat only the part needed for current
2629 // context.
2630 // TODO: Handle more cases.
2631 unsigned Opcode = Orig.getOpcode();
2632 switch (Opcode) {
2633 case AMDGPU::S_MOV_B64:
2634 case AMDGPU::S_MOV_B64_IMM_PSEUDO: {
2635 if (SubIdx != 0)
2636 break;
2637
2638 if (!Orig.getOperand(1).isImm())
2639 break;
2640
2641 // Shrink S_MOV_B64 to S_MOV_B32 when UsedLanes indicates only a single
2642 // 32-bit lane of the 64-bit value is live at the rematerialization point.
2643 if (UsedLanes.all())
2644 break;
2645
2646 // Determine which half of the 64-bit immediate corresponds to the use.
2647 unsigned OrigSubReg = Orig.getOperand(0).getSubReg();
2648 unsigned LoSubReg = RI.composeSubRegIndices(OrigSubReg, AMDGPU::sub0);
2649 unsigned HiSubReg = RI.composeSubRegIndices(OrigSubReg, AMDGPU::sub1);
2650
2651 bool NeedLo = (UsedLanes & RI.getSubRegIndexLaneMask(LoSubReg)).any();
2652 bool NeedHi = (UsedLanes & RI.getSubRegIndexLaneMask(HiSubReg)).any();
2653
2654 if (NeedLo && NeedHi)
2655 break;
2656
2657 int64_t Imm64 = Orig.getOperand(1).getImm();
2658 int32_t Imm32 = NeedLo ? Lo_32(Imm64) : Hi_32(Imm64);
2659
2660 unsigned UseSubReg = NeedLo ? LoSubReg : HiSubReg;
2661
2662 // Emit S_MOV_B32 defining just the needed 32-bit subreg of DestReg.
2663 BuildMI(MBB, I, Orig.getDebugLoc(), get(AMDGPU::S_MOV_B32))
2664 .addReg(DestReg, RegState::Define | RegState::Undef, UseSubReg)
2665 .addImm(Imm32);
2666 return;
2667 }
2668
2669 case AMDGPU::S_LOAD_DWORDX16_IMM:
2670 case AMDGPU::S_LOAD_DWORDX8_IMM: {
2671 if (SubIdx != 0)
2672 break;
2673
2674 if (I == MBB.end())
2675 break;
2676
2677 if (I->isBundled())
2678 break;
2679
2680 // Look for a single use of the register that is also a subreg.
2681 Register RegToFind = Orig.getOperand(0).getReg();
2682 MachineOperand *UseMO = nullptr;
2683 for (auto &CandMO : I->operands()) {
2684 if (!CandMO.isReg() || CandMO.getReg() != RegToFind || CandMO.isDef())
2685 continue;
2686 if (UseMO) {
2687 UseMO = nullptr;
2688 break;
2689 }
2690 UseMO = &CandMO;
2691 }
2692 if (!UseMO || UseMO->getSubReg() == AMDGPU::NoSubRegister)
2693 break;
2694
2695 unsigned Offset = RI.getSubRegIdxOffset(UseMO->getSubReg());
2696 unsigned SubregSize = RI.getSubRegIdxSize(UseMO->getSubReg());
2697
2698 MachineFunction *MF = MBB.getParent();
2699 MachineRegisterInfo &MRI = MF->getRegInfo();
2700 assert(MRI.use_nodbg_empty(DestReg) && "DestReg should have no users yet.");
2701
2702 unsigned NewOpcode = -1;
2703 if (SubregSize == 256)
2704 NewOpcode = AMDGPU::S_LOAD_DWORDX8_IMM;
2705 else if (SubregSize == 128)
2706 NewOpcode = AMDGPU::S_LOAD_DWORDX4_IMM;
2707 else
2708 break;
2709
2710 const MCInstrDesc &TID = get(NewOpcode);
2711 const TargetRegisterClass *NewRC =
2712 RI.getAllocatableClass(getRegClass(TID, 0));
2713 MRI.setRegClass(DestReg, NewRC);
2714
2715 UseMO->setReg(DestReg);
2716 UseMO->setSubReg(AMDGPU::NoSubRegister);
2717
2718 // Use a smaller load with the desired size, possibly with updated offset.
2719 MachineInstr *MI = MF->CloneMachineInstr(&Orig);
2720 MI->setDesc(TID);
2721 MI->getOperand(0).setReg(DestReg);
2722 MI->getOperand(0).setSubReg(AMDGPU::NoSubRegister);
2723 if (Offset) {
2724 MachineOperand *OffsetMO = getNamedOperand(*MI, AMDGPU::OpName::offset);
2725 int64_t FinalOffset = OffsetMO->getImm() + Offset / 8;
2726 OffsetMO->setImm(FinalOffset);
2727 }
2729 for (const MachineMemOperand *MemOp : Orig.memoperands())
2730 NewMMOs.push_back(MF->getMachineMemOperand(MemOp, MemOp->getPointerInfo(),
2731 SubregSize / 8));
2732 MI->setMemRefs(*MF, NewMMOs);
2733
2734 MBB.insert(I, MI);
2735 return;
2736 }
2737
2738 default:
2739 break;
2740 }
2741
2742 TargetInstrInfo::reMaterialize(MBB, I, DestReg, SubIdx, Orig, UsedLanes);
2743}
2744
2745std::pair<MachineInstr*, MachineInstr*>
2747 assert (MI.getOpcode() == AMDGPU::V_MOV_B64_DPP_PSEUDO);
2748
2749 if (ST.hasVMovB64Inst() && ST.hasFeature(AMDGPU::FeatureDPALU_DPP) &&
2751 ST, getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl)->getImm())) {
2752 MI.setDesc(get(AMDGPU::V_MOV_B64_dpp));
2753 return std::pair(&MI, nullptr);
2754 }
2755
2756 MachineBasicBlock &MBB = *MI.getParent();
2757 DebugLoc DL = MBB.findDebugLoc(MI);
2758 MachineFunction *MF = MBB.getParent();
2759 MachineRegisterInfo &MRI = MF->getRegInfo();
2760 Register Dst = MI.getOperand(0).getReg();
2761 unsigned Part = 0;
2762 MachineInstr *Split[2];
2763
2764 for (auto Sub : { AMDGPU::sub0, AMDGPU::sub1 }) {
2765 auto MovDPP = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_dpp));
2766 if (Dst.isPhysical()) {
2767 MovDPP.addDef(RI.getSubReg(Dst, Sub));
2768 } else {
2769 assert(MRI.isSSA());
2770 auto Tmp = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2771 MovDPP.addDef(Tmp);
2772 }
2773
2774 for (unsigned I = 1; I <= 2; ++I) { // old and src operands.
2775 const MachineOperand &SrcOp = MI.getOperand(I);
2776 assert(!SrcOp.isFPImm());
2777 if (SrcOp.isImm()) {
2778 APInt Imm(64, SrcOp.getImm());
2779 Imm.ashrInPlace(Part * 32);
2780 MovDPP.addImm(Imm.getLoBits(32).getZExtValue());
2781 } else {
2782 assert(SrcOp.isReg());
2783 Register Src = SrcOp.getReg();
2784 if (Src.isPhysical())
2785 MovDPP.addReg(RI.getSubReg(Src, Sub));
2786 else
2787 MovDPP.addReg(Src, getUndefRegState(SrcOp.isUndef()), Sub);
2788 }
2789 }
2790
2791 for (const MachineOperand &MO : llvm::drop_begin(MI.explicit_operands(), 3))
2792 MovDPP.addImm(MO.getImm());
2793
2794 Split[Part] = MovDPP;
2795 ++Part;
2796 }
2797
2798 if (Dst.isVirtual())
2799 BuildMI(MBB, MI, DL, get(AMDGPU::REG_SEQUENCE), Dst)
2800 .addReg(Split[0]->getOperand(0).getReg())
2801 .addImm(AMDGPU::sub0)
2802 .addReg(Split[1]->getOperand(0).getReg())
2803 .addImm(AMDGPU::sub1);
2804
2805 MI.eraseFromParent();
2806 return std::pair(Split[0], Split[1]);
2807}
2808
2809std::optional<DestSourcePair>
2811 if (MI.getOpcode() == AMDGPU::WWM_COPY)
2812 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
2813
2814 return std::nullopt;
2815}
2816
2818 AMDGPU::OpName Src0OpName,
2819 MachineOperand &Src1,
2820 AMDGPU::OpName Src1OpName) const {
2821 MachineOperand *Src0Mods = getNamedOperand(MI, Src0OpName);
2822 if (!Src0Mods)
2823 return false;
2824
2825 MachineOperand *Src1Mods = getNamedOperand(MI, Src1OpName);
2826 assert(Src1Mods &&
2827 "All commutable instructions have both src0 and src1 modifiers");
2828
2829 int Src0ModsVal = Src0Mods->getImm();
2830 int Src1ModsVal = Src1Mods->getImm();
2831
2832 Src1Mods->setImm(Src0ModsVal);
2833 Src0Mods->setImm(Src1ModsVal);
2834 return true;
2835}
2836
2838 MachineOperand &RegOp,
2839 MachineOperand &NonRegOp) {
2840 Register Reg = RegOp.getReg();
2841 unsigned SubReg = RegOp.getSubReg();
2842 bool IsKill = RegOp.isKill();
2843 bool IsDead = RegOp.isDead();
2844 bool IsUndef = RegOp.isUndef();
2845 bool IsDebug = RegOp.isDebug();
2846
2847 if (NonRegOp.isImm())
2848 RegOp.ChangeToImmediate(NonRegOp.getImm());
2849 else if (NonRegOp.isFI())
2850 RegOp.ChangeToFrameIndex(NonRegOp.getIndex());
2851 else if (NonRegOp.isGlobal()) {
2852 RegOp.ChangeToGA(NonRegOp.getGlobal(), NonRegOp.getOffset(),
2853 NonRegOp.getTargetFlags());
2854 } else
2855 return nullptr;
2856
2857 // Make sure we don't reinterpret a subreg index in the target flags.
2858 RegOp.setTargetFlags(NonRegOp.getTargetFlags());
2859
2860 NonRegOp.ChangeToRegister(Reg, false, false, IsKill, IsDead, IsUndef, IsDebug);
2861 NonRegOp.setSubReg(SubReg);
2862
2863 return &MI;
2864}
2865
2867 MachineOperand &NonRegOp1,
2868 MachineOperand &NonRegOp2) {
2869 unsigned TargetFlags = NonRegOp1.getTargetFlags();
2870 int64_t NonRegVal = NonRegOp1.getImm();
2871
2872 NonRegOp1.setImm(NonRegOp2.getImm());
2873 NonRegOp2.setImm(NonRegVal);
2874 NonRegOp1.setTargetFlags(NonRegOp2.getTargetFlags());
2875 NonRegOp2.setTargetFlags(TargetFlags);
2876 return &MI;
2877}
2878
2879bool SIInstrInfo::isLegalToSwap(const MachineInstr &MI, unsigned OpIdx0,
2880 unsigned OpIdx1) const {
2881 const MCInstrDesc &InstDesc = MI.getDesc();
2882 const MCOperandInfo &OpInfo0 = InstDesc.operands()[OpIdx0];
2883 const MCOperandInfo &OpInfo1 = InstDesc.operands()[OpIdx1];
2884
2885 unsigned Opc = MI.getOpcode();
2886 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2887
2888 const MachineOperand &MO0 = MI.getOperand(OpIdx0);
2889 const MachineOperand &MO1 = MI.getOperand(OpIdx1);
2890
2891 // Swap doesn't breach constant bus or literal limits
2892 // It may move literal to position other than src0, this is not allowed
2893 // pre-gfx10 However, most test cases need literals in Src0 for VOP
2894 // FIXME: After gfx9, literal can be in place other than Src0
2895 if (isVALU(MI)) {
2896 if ((int)OpIdx0 == Src0Idx && !MO0.isReg() &&
2897 !isInlineConstant(MO0, OpInfo1))
2898 return false;
2899 if ((int)OpIdx1 == Src0Idx && !MO1.isReg() &&
2900 !isInlineConstant(MO1, OpInfo0))
2901 return false;
2902 }
2903
2904 if ((int)OpIdx1 != Src0Idx && MO0.isReg()) {
2905 if (OpInfo1.RegClass == -1)
2906 return OpInfo1.OperandType == MCOI::OPERAND_UNKNOWN;
2907 return isLegalRegOperand(MI, OpIdx1, MO0) &&
2908 (!MO1.isReg() || isLegalRegOperand(MI, OpIdx0, MO1));
2909 }
2910 if ((int)OpIdx0 != Src0Idx && MO1.isReg()) {
2911 if (OpInfo0.RegClass == -1)
2912 return OpInfo0.OperandType == MCOI::OPERAND_UNKNOWN;
2913 return (!MO0.isReg() || isLegalRegOperand(MI, OpIdx1, MO0)) &&
2914 isLegalRegOperand(MI, OpIdx0, MO1);
2915 }
2916
2917 // No need to check 64-bit literals since swapping does not bring new
2918 // 64-bit literals into current instruction to fold to 32-bit
2919
2920 return isImmOperandLegal(MI, OpIdx1, MO0);
2921}
2922
2924 unsigned Src0Idx,
2925 unsigned Src1Idx) const {
2926 assert(!NewMI && "this should never be used");
2927
2928 unsigned Opc = MI.getOpcode();
2929 int CommutedOpcode = commuteOpcode(Opc);
2930 if (CommutedOpcode == -1)
2931 return nullptr;
2932
2933 if (Src0Idx > Src1Idx)
2934 std::swap(Src0Idx, Src1Idx);
2935
2936 assert(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) ==
2937 static_cast<int>(Src0Idx) &&
2938 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) ==
2939 static_cast<int>(Src1Idx) &&
2940 "inconsistency with findCommutedOpIndices");
2941
2942 if (!isLegalToSwap(MI, Src0Idx, Src1Idx))
2943 return nullptr;
2944
2945 MachineInstr *CommutedMI = nullptr;
2946 MachineOperand &Src0 = MI.getOperand(Src0Idx);
2947 MachineOperand &Src1 = MI.getOperand(Src1Idx);
2948 if (Src0.isReg() && Src1.isReg()) {
2949 // Be sure to copy the source modifiers to the right place.
2950 CommutedMI =
2951 TargetInstrInfo::commuteInstructionImpl(MI, NewMI, Src0Idx, Src1Idx);
2952 } else if (Src0.isReg() && !Src1.isReg()) {
2953 CommutedMI = swapRegAndNonRegOperand(MI, Src0, Src1);
2954 } else if (!Src0.isReg() && Src1.isReg()) {
2955 CommutedMI = swapRegAndNonRegOperand(MI, Src1, Src0);
2956 } else if (Src0.isImm() && Src1.isImm()) {
2957 CommutedMI = swapImmOperands(MI, Src0, Src1);
2958 } else {
2959 // FIXME: Found two non registers to commute. This does happen.
2960 return nullptr;
2961 }
2962
2963 if (CommutedMI) {
2964 swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_modifiers,
2965 Src1, AMDGPU::OpName::src1_modifiers);
2966
2967 swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_sel, Src1,
2968 AMDGPU::OpName::src1_sel);
2969
2970 CommutedMI->setDesc(get(CommutedOpcode));
2971 }
2972
2973 return CommutedMI;
2974}
2975
2976// This needs to be implemented because the source modifiers may be inserted
2977// between the true commutable operands, and the base
2978// TargetInstrInfo::commuteInstruction uses it.
2980 unsigned &SrcOpIdx0,
2981 unsigned &SrcOpIdx1) const {
2982 return findCommutedOpIndices(MI.getDesc(), SrcOpIdx0, SrcOpIdx1);
2983}
2984
2986 unsigned &SrcOpIdx0,
2987 unsigned &SrcOpIdx1) const {
2988 if (!Desc.isCommutable())
2989 return false;
2990
2991 unsigned Opc = Desc.getOpcode();
2992 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2993 if (Src0Idx == -1)
2994 return false;
2995
2996 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
2997 if (Src1Idx == -1)
2998 return false;
2999
3000 return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
3001}
3002
3004 int64_t BrOffset) const {
3005 // BranchRelaxation should never have to check s_setpc_b64 or s_add_pc_i64
3006 // because its dest block is unanalyzable.
3007 assert(isSOPP(BranchOp) || isSOPK(BranchOp));
3008
3009 // Convert to dwords.
3010 BrOffset /= 4;
3011
3012 // The branch instructions do PC += signext(SIMM16 * 4) + 4, so the offset is
3013 // from the next instruction.
3014 BrOffset -= 1;
3015
3016 return isIntN(BranchOffsetBits, BrOffset);
3017}
3018
3021 return MI.getOperand(0).getMBB();
3022}
3023
3025 for (const MachineInstr &MI : MBB->terminators()) {
3026 if (MI.getOpcode() == AMDGPU::SI_IF || MI.getOpcode() == AMDGPU::SI_ELSE ||
3027 MI.getOpcode() == AMDGPU::SI_LOOP)
3028 return true;
3029 }
3030 return false;
3031}
3032
3034 MachineBasicBlock &DestBB,
3035 MachineBasicBlock &RestoreBB,
3036 const DebugLoc &DL, int64_t BrOffset,
3037 RegScavenger *RS) const {
3038 assert(MBB.empty() &&
3039 "new block should be inserted for expanding unconditional branch");
3040 assert(MBB.pred_size() == 1);
3041 assert(RestoreBB.empty() &&
3042 "restore block should be inserted for restoring clobbered registers");
3043
3044 MachineFunction *MF = MBB.getParent();
3045 MachineRegisterInfo &MRI = MF->getRegInfo();
3047 auto I = MBB.end();
3048 auto &MCCtx = MF->getContext();
3049
3050 if (ST.useAddPC64Inst()) {
3051 MCSymbol *Offset =
3052 MCCtx.createTempSymbol("offset", /*AlwaysAddSuffix=*/true);
3053 auto AddPC = BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_PC_I64))
3055 MCSymbol *PostAddPCLabel =
3056 MCCtx.createTempSymbol("post_addpc", /*AlwaysAddSuffix=*/true);
3057 AddPC->setPostInstrSymbol(*MF, PostAddPCLabel);
3058 auto *OffsetExpr = MCBinaryExpr::createSub(
3059 MCSymbolRefExpr::create(DestBB.getSymbol(), MCCtx),
3060 MCSymbolRefExpr::create(PostAddPCLabel, MCCtx), MCCtx);
3061 Offset->setVariableValue(OffsetExpr);
3062 return;
3063 }
3064
3065 assert(RS && "RegScavenger required for long branching");
3066
3067 // FIXME: Virtual register workaround for RegScavenger not working with empty
3068 // blocks.
3069 Register PCReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3070
3071 // Note: as this is used after hazard recognizer we need to apply some hazard
3072 // workarounds directly.
3073 const bool FlushSGPRWrites = (ST.isWave64() && ST.hasVALUMaskWriteHazard()) ||
3074 ST.hasVALUReadSGPRHazard();
3075 auto ApplyHazardWorkarounds = [this, &MBB, &I, &DL, FlushSGPRWrites]() {
3076 if (FlushSGPRWrites)
3077 BuildMI(MBB, I, DL, get(AMDGPU::S_WAITCNT_DEPCTR))
3079 };
3080
3081 // We need to compute the offset relative to the instruction immediately after
3082 // s_getpc_b64. Insert pc arithmetic code before last terminator.
3083 MachineInstr *GetPC = BuildMI(MBB, I, DL, get(AMDGPU::S_GETPC_B64), PCReg);
3084 ApplyHazardWorkarounds();
3085
3086 MCSymbol *PostGetPCLabel =
3087 MCCtx.createTempSymbol("post_getpc", /*AlwaysAddSuffix=*/true);
3088 GetPC->setPostInstrSymbol(*MF, PostGetPCLabel);
3089
3090 MCSymbol *OffsetLo =
3091 MCCtx.createTempSymbol("offset_lo", /*AlwaysAddSuffix=*/true);
3092 MCSymbol *OffsetHi =
3093 MCCtx.createTempSymbol("offset_hi", /*AlwaysAddSuffix=*/true);
3094 BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_U32))
3095 .addReg(PCReg, RegState::Define, AMDGPU::sub0)
3096 .addReg(PCReg, {}, AMDGPU::sub0)
3097 .addSym(OffsetLo, MO_FAR_BRANCH_OFFSET);
3098 BuildMI(MBB, I, DL, get(AMDGPU::S_ADDC_U32))
3099 .addReg(PCReg, RegState::Define, AMDGPU::sub1)
3100 .addReg(PCReg, {}, AMDGPU::sub1)
3101 .addSym(OffsetHi, MO_FAR_BRANCH_OFFSET);
3102 ApplyHazardWorkarounds();
3103
3104 // Insert the indirect branch after the other terminator.
3105 BuildMI(&MBB, DL, get(AMDGPU::S_SETPC_B64))
3106 .addReg(PCReg);
3107
3108 // If a spill is needed for the pc register pair, we need to insert a spill
3109 // restore block right before the destination block, and insert a short branch
3110 // into the old destination block's fallthrough predecessor.
3111 // e.g.:
3112 //
3113 // s_cbranch_scc0 skip_long_branch:
3114 //
3115 // long_branch_bb:
3116 // spill s[8:9]
3117 // s_getpc_b64 s[8:9]
3118 // s_add_u32 s8, s8, restore_bb
3119 // s_addc_u32 s9, s9, 0
3120 // s_setpc_b64 s[8:9]
3121 //
3122 // skip_long_branch:
3123 // foo;
3124 //
3125 // .....
3126 //
3127 // dest_bb_fallthrough_predecessor:
3128 // bar;
3129 // s_branch dest_bb
3130 //
3131 // restore_bb:
3132 // restore s[8:9]
3133 // fallthrough dest_bb
3134 ///
3135 // dest_bb:
3136 // buzz;
3137
3138 Register LongBranchReservedReg = MFI->getLongBranchReservedReg();
3139 Register Scav;
3140
3141 // If we've previously reserved a register for long branches
3142 // avoid running the scavenger and just use those registers
3143 if (LongBranchReservedReg) {
3144 RS->enterBasicBlock(MBB);
3145 Scav = LongBranchReservedReg;
3146 } else {
3147 RS->enterBasicBlockEnd(MBB);
3148 Scav = RS->scavengeRegisterBackwards(
3149 AMDGPU::SReg_64RegClass, MachineBasicBlock::iterator(GetPC),
3150 /* RestoreAfter */ false, 0, /* AllowSpill */ false);
3151 }
3152 if (Scav) {
3153 RS->setRegUsed(Scav);
3154 MRI.replaceRegWith(PCReg, Scav);
3155 MRI.clearVirtRegs();
3156 } else {
3157 // As SGPR needs VGPR to be spilled, we reuse the slot of temporary VGPR for
3158 // SGPR spill.
3159 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3160 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3161 TRI->spillEmergencySGPR(GetPC, RestoreBB, AMDGPU::SGPR0_SGPR1, RS);
3162 MRI.replaceRegWith(PCReg, AMDGPU::SGPR0_SGPR1);
3163 MRI.clearVirtRegs();
3164 }
3165
3166 MCSymbol *DestLabel = Scav ? DestBB.getSymbol() : RestoreBB.getSymbol();
3167 // Now, the distance could be defined.
3169 MCSymbolRefExpr::create(DestLabel, MCCtx),
3170 MCSymbolRefExpr::create(PostGetPCLabel, MCCtx), MCCtx);
3171 // Add offset assignments.
3172 auto *Mask = MCConstantExpr::create(0xFFFFFFFFULL, MCCtx);
3173 OffsetLo->setVariableValue(MCBinaryExpr::createAnd(Offset, Mask, MCCtx));
3174 auto *ShAmt = MCConstantExpr::create(32, MCCtx);
3175 OffsetHi->setVariableValue(MCBinaryExpr::createAShr(Offset, ShAmt, MCCtx));
3176}
3177
3178unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
3179 switch (Cond) {
3180 case SIInstrInfo::SCC_TRUE:
3181 return AMDGPU::S_CBRANCH_SCC1;
3182 case SIInstrInfo::SCC_FALSE:
3183 return AMDGPU::S_CBRANCH_SCC0;
3184 case SIInstrInfo::VCCNZ:
3185 return AMDGPU::S_CBRANCH_VCCNZ;
3186 case SIInstrInfo::VCCZ:
3187 return AMDGPU::S_CBRANCH_VCCZ;
3188 case SIInstrInfo::EXECNZ:
3189 return AMDGPU::S_CBRANCH_EXECNZ;
3190 case SIInstrInfo::EXECZ:
3191 return AMDGPU::S_CBRANCH_EXECZ;
3192 default:
3193 llvm_unreachable("invalid branch predicate");
3194 }
3195}
3196
3197SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
3198 switch (Opcode) {
3199 case AMDGPU::S_CBRANCH_SCC0:
3200 return SCC_FALSE;
3201 case AMDGPU::S_CBRANCH_SCC1:
3202 return SCC_TRUE;
3203 case AMDGPU::S_CBRANCH_VCCNZ:
3204 return VCCNZ;
3205 case AMDGPU::S_CBRANCH_VCCZ:
3206 return VCCZ;
3207 case AMDGPU::S_CBRANCH_EXECNZ:
3208 return EXECNZ;
3209 case AMDGPU::S_CBRANCH_EXECZ:
3210 return EXECZ;
3211 default:
3212 return INVALID_BR;
3213 }
3214}
3215
3219 MachineBasicBlock *&FBB,
3221 bool AllowModify) const {
3222 if (I->getOpcode() == AMDGPU::S_BRANCH) {
3223 // Unconditional Branch
3224 TBB = I->getOperand(0).getMBB();
3225 return false;
3226 }
3227
3228 BranchPredicate Pred = getBranchPredicate(I->getOpcode());
3229 if (Pred == INVALID_BR)
3230 return true;
3231
3232 MachineBasicBlock *CondBB = I->getOperand(0).getMBB();
3233 Cond.push_back(MachineOperand::CreateImm(Pred));
3234 Cond.push_back(I->getOperand(1)); // Save the branch register.
3235
3236 ++I;
3237
3238 if (I == MBB.end()) {
3239 // Conditional branch followed by fall-through.
3240 TBB = CondBB;
3241 return false;
3242 }
3243
3244 if (I->getOpcode() == AMDGPU::S_BRANCH) {
3245 TBB = CondBB;
3246 FBB = I->getOperand(0).getMBB();
3247 return false;
3248 }
3249
3250 return true;
3251}
3252
3254 MachineBasicBlock *&FBB,
3256 bool AllowModify) const {
3257 MachineBasicBlock::iterator I = MBB.getFirstTerminator();
3258 auto E = MBB.end();
3259 if (I == E)
3260 return false;
3261
3262 // Skip over the instructions that are artificially terminators for special
3263 // exec management.
3264 while (I != E && !I->isBranch() && !I->isReturn()) {
3265 switch (I->getOpcode()) {
3266 case AMDGPU::S_MOV_B64_term:
3267 case AMDGPU::S_XOR_B64_term:
3268 case AMDGPU::S_OR_B64_term:
3269 case AMDGPU::S_ANDN2_B64_term:
3270 case AMDGPU::S_AND_B64_term:
3271 case AMDGPU::S_AND_SAVEEXEC_B64_term:
3272 case AMDGPU::S_MOV_B32_term:
3273 case AMDGPU::S_XOR_B32_term:
3274 case AMDGPU::S_OR_B32_term:
3275 case AMDGPU::S_ANDN2_B32_term:
3276 case AMDGPU::S_AND_B32_term:
3277 case AMDGPU::S_AND_SAVEEXEC_B32_term:
3278 break;
3279 case AMDGPU::SI_IF:
3280 case AMDGPU::SI_ELSE:
3281 case AMDGPU::SI_KILL_I1_TERMINATOR:
3282 case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
3283 // FIXME: It's messy that these need to be considered here at all.
3284 return true;
3285 default:
3286 llvm_unreachable("unexpected non-branch terminator inst");
3287 }
3288
3289 ++I;
3290 }
3291
3292 if (I == E)
3293 return false;
3294
3295 return analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify);
3296}
3297
3299 int *BytesRemoved) const {
3300 unsigned Count = 0;
3301 unsigned RemovedSize = 0;
3302 for (MachineInstr &MI : llvm::make_early_inc_range(MBB.terminators())) {
3303 // Skip over artificial terminators when removing instructions.
3304 if (MI.isBranch() || MI.isReturn()) {
3305 RemovedSize += getInstSizeInBytes(MI);
3306 MI.eraseFromParent();
3307 ++Count;
3308 }
3309 }
3310
3311 if (BytesRemoved)
3312 *BytesRemoved = RemovedSize;
3313
3314 return Count;
3315}
3316
3317// Copy the flags onto the implicit condition register operand.
3319 const MachineOperand &OrigCond) {
3320 CondReg.setIsUndef(OrigCond.isUndef());
3321 CondReg.setIsKill(OrigCond.isKill());
3322}
3323
3326 MachineBasicBlock *FBB,
3328 const DebugLoc &DL,
3329 int *BytesAdded) const {
3330 if (!FBB && Cond.empty()) {
3331 BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
3332 .addMBB(TBB);
3333 if (BytesAdded)
3334 *BytesAdded = ST.hasOffset3fBug() ? 8 : 4;
3335 return 1;
3336 }
3337
3338 assert(TBB && Cond[0].isImm());
3339
3340 unsigned Opcode
3341 = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
3342
3343 if (!FBB) {
3344 MachineInstr *CondBr =
3345 BuildMI(&MBB, DL, get(Opcode))
3346 .addMBB(TBB);
3347
3348 // Copy the flags onto the implicit condition register operand.
3349 preserveCondRegFlags(CondBr->getOperand(1), Cond[1]);
3350 fixImplicitOperands(*CondBr);
3351
3352 if (BytesAdded)
3353 *BytesAdded = ST.hasOffset3fBug() ? 8 : 4;
3354 return 1;
3355 }
3356
3357 assert(TBB && FBB);
3358
3359 MachineInstr *CondBr =
3360 BuildMI(&MBB, DL, get(Opcode))
3361 .addMBB(TBB);
3362 fixImplicitOperands(*CondBr);
3363 BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
3364 .addMBB(FBB);
3365
3366 MachineOperand &CondReg = CondBr->getOperand(1);
3367 CondReg.setIsUndef(Cond[1].isUndef());
3368 CondReg.setIsKill(Cond[1].isKill());
3369
3370 if (BytesAdded)
3371 *BytesAdded = ST.hasOffset3fBug() ? 16 : 8;
3372
3373 return 2;
3374}
3375
3378 if (Cond.size() != 2) {
3379 return true;
3380 }
3381
3382 if (Cond[0].isImm()) {
3383 Cond[0].setImm(-Cond[0].getImm());
3384 return false;
3385 }
3386
3387 return true;
3388}
3389
3392 Register DstReg, Register TrueReg,
3393 Register FalseReg, int &CondCycles,
3394 int &TrueCycles, int &FalseCycles) const {
3395 switch (Cond[0].getImm()) {
3396 case VCCNZ:
3397 case VCCZ: {
3398 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3399 const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
3400 if (MRI.getRegClass(FalseReg) != RC)
3401 return false;
3402
3403 int NumInsts = AMDGPU::getRegBitWidth(*RC) / 32;
3404 CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
3405
3406 // Limit to equal cost for branch vs. N v_cndmask_b32s.
3407 return RI.hasVGPRs(RC) && NumInsts <= 6;
3408 }
3409 case SCC_TRUE:
3410 case SCC_FALSE: {
3411 // FIXME: We could insert for VGPRs if we could replace the original compare
3412 // with a vector one.
3413 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3414 const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
3415 if (MRI.getRegClass(FalseReg) != RC)
3416 return false;
3417
3418 int NumInsts = AMDGPU::getRegBitWidth(*RC) / 32;
3419
3420 // Multiples of 8 can do s_cselect_b64
3421 if (NumInsts % 2 == 0)
3422 NumInsts /= 2;
3423
3424 CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
3425 return RI.isSGPRClass(RC);
3426 }
3427 default:
3428 return false;
3429 }
3430}
3431
3435 Register TrueReg, Register FalseReg) const {
3436 BranchPredicate Pred = static_cast<BranchPredicate>(Cond[0].getImm());
3437 if (Pred == VCCZ || Pred == SCC_FALSE) {
3438 Pred = static_cast<BranchPredicate>(-Pred);
3439 std::swap(TrueReg, FalseReg);
3440 }
3441
3442 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3443 const TargetRegisterClass *DstRC = MRI.getRegClass(DstReg);
3444 unsigned DstSize = RI.getRegSizeInBits(*DstRC);
3445
3446 if (DstSize == 32) {
3448 if (Pred == SCC_TRUE) {
3449 Select = BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B32), DstReg)
3450 .addReg(TrueReg)
3451 .addReg(FalseReg);
3452 } else {
3453 // Instruction's operands are backwards from what is expected.
3454 Select = BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e32), DstReg)
3455 .addReg(FalseReg)
3456 .addReg(TrueReg);
3457 }
3458
3459 preserveCondRegFlags(Select->getOperand(3), Cond[1]);
3460 return;
3461 }
3462
3463 if (DstSize == 64 && Pred == SCC_TRUE) {
3465 BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), DstReg)
3466 .addReg(TrueReg)
3467 .addReg(FalseReg);
3468
3469 preserveCondRegFlags(Select->getOperand(3), Cond[1]);
3470 return;
3471 }
3472
3473 static const int16_t Sub0_15[] = {
3474 AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
3475 AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
3476 AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
3477 AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15,
3478 };
3479
3480 static const int16_t Sub0_15_64[] = {
3481 AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
3482 AMDGPU::sub4_sub5, AMDGPU::sub6_sub7,
3483 AMDGPU::sub8_sub9, AMDGPU::sub10_sub11,
3484 AMDGPU::sub12_sub13, AMDGPU::sub14_sub15,
3485 };
3486
3487 unsigned SelOp = AMDGPU::V_CNDMASK_B32_e32;
3488 const TargetRegisterClass *EltRC = &AMDGPU::VGPR_32RegClass;
3489 const int16_t *SubIndices = Sub0_15;
3490 int NElts = DstSize / 32;
3491
3492 // 64-bit select is only available for SALU.
3493 // TODO: Split 96-bit into 64-bit and 32-bit, not 3x 32-bit.
3494 if (Pred == SCC_TRUE) {
3495 if (NElts % 2) {
3496 SelOp = AMDGPU::S_CSELECT_B32;
3497 EltRC = &AMDGPU::SGPR_32RegClass;
3498 } else {
3499 SelOp = AMDGPU::S_CSELECT_B64;
3500 EltRC = &AMDGPU::SGPR_64RegClass;
3501 SubIndices = Sub0_15_64;
3502 NElts /= 2;
3503 }
3504 }
3505
3507 MBB, I, DL, get(AMDGPU::REG_SEQUENCE), DstReg);
3508
3509 I = MIB->getIterator();
3510
3512 for (int Idx = 0; Idx != NElts; ++Idx) {
3513 Register DstElt = MRI.createVirtualRegister(EltRC);
3514 Regs.push_back(DstElt);
3515
3516 unsigned SubIdx = SubIndices[Idx];
3517
3519 if (SelOp == AMDGPU::V_CNDMASK_B32_e32) {
3520 Select = BuildMI(MBB, I, DL, get(SelOp), DstElt)
3521 .addReg(FalseReg, {}, SubIdx)
3522 .addReg(TrueReg, {}, SubIdx);
3523 } else {
3524 Select = BuildMI(MBB, I, DL, get(SelOp), DstElt)
3525 .addReg(TrueReg, {}, SubIdx)
3526 .addReg(FalseReg, {}, SubIdx);
3527 }
3528
3529 preserveCondRegFlags(Select->getOperand(3), Cond[1]);
3531
3532 MIB.addReg(DstElt)
3533 .addImm(SubIdx);
3534 }
3535}
3536
3538
3539 if (MI.isBranch() || MI.isCall() || MI.isReturn() || MI.isIndirectBranch())
3540 return true;
3541
3542 switch (MI.getOpcode()) {
3543 case AMDGPU::S_ENDPGM:
3544 case AMDGPU::S_ENDPGM_SAVED:
3545 case AMDGPU::S_TRAP:
3546 case AMDGPU::S_GETREG_B32:
3547 case AMDGPU::S_SETREG_B32:
3548 case AMDGPU::S_SETREG_B32_mode:
3549 case AMDGPU::S_SETREG_IMM32_B32:
3550 case AMDGPU::S_SETREG_IMM32_B32_mode:
3551 case AMDGPU::S_SENDMSG:
3552 case AMDGPU::S_SENDMSGHALT:
3553 case AMDGPU::S_SENDMSG_RTN_B32:
3554 case AMDGPU::S_SENDMSG_RTN_B64:
3555 case AMDGPU::S_BARRIER_WAIT:
3556 case AMDGPU::S_BARRIER_SIGNAL_M0:
3557 case AMDGPU::S_BARRIER_SIGNAL_IMM:
3558 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_M0:
3559 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM:
3560 return true;
3561 default:
3562 return false;
3563 }
3564}
3565
3567 switch (MI.getOpcode()) {
3568 case AMDGPU::V_MOV_B16_t16_e32:
3569 case AMDGPU::V_MOV_B16_t16_e64:
3570 case AMDGPU::V_MOV_B32_e32:
3571 case AMDGPU::V_MOV_B32_e64:
3572 case AMDGPU::V_MOV_B64_PSEUDO:
3573 case AMDGPU::V_MOV_B64_e32:
3574 case AMDGPU::V_MOV_B64_e64:
3575 case AMDGPU::S_MOV_B32:
3576 case AMDGPU::S_MOV_B64:
3577 case AMDGPU::S_MOV_B64_IMM_PSEUDO:
3578 case AMDGPU::COPY:
3579 case AMDGPU::WWM_COPY:
3580 case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
3581 case AMDGPU::V_ACCVGPR_READ_B32_e64:
3582 case AMDGPU::V_ACCVGPR_MOV_B32:
3583 case AMDGPU::AV_MOV_B32_IMM_PSEUDO:
3584 case AMDGPU::AV_MOV_B64_IMM_PSEUDO:
3585 return true;
3586 default:
3587 return false;
3588 }
3589}
3590
3592 switch (MI.getOpcode()) {
3593 case AMDGPU::V_MOV_B16_t16_e32:
3594 case AMDGPU::V_MOV_B16_t16_e64:
3595 return 2;
3596 case AMDGPU::V_MOV_B32_e32:
3597 case AMDGPU::V_MOV_B32_e64:
3598 case AMDGPU::V_MOV_B64_PSEUDO:
3599 case AMDGPU::V_MOV_B64_e32:
3600 case AMDGPU::V_MOV_B64_e64:
3601 case AMDGPU::S_MOV_B32:
3602 case AMDGPU::S_MOV_B64:
3603 case AMDGPU::S_MOV_B64_IMM_PSEUDO:
3604 case AMDGPU::COPY:
3605 case AMDGPU::WWM_COPY:
3606 case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
3607 case AMDGPU::V_ACCVGPR_READ_B32_e64:
3608 case AMDGPU::V_ACCVGPR_MOV_B32:
3609 case AMDGPU::AV_MOV_B32_IMM_PSEUDO:
3610 case AMDGPU::AV_MOV_B64_IMM_PSEUDO:
3611 return 1;
3612 default:
3613 llvm_unreachable("MI is not a foldable copy");
3614 }
3615}
3616
3617static constexpr AMDGPU::OpName ModifierOpNames[] = {
3618 AMDGPU::OpName::src0_modifiers, AMDGPU::OpName::src1_modifiers,
3619 AMDGPU::OpName::src2_modifiers, AMDGPU::OpName::clamp,
3620 AMDGPU::OpName::omod, AMDGPU::OpName::op_sel};
3621
3623 unsigned Opc = MI.getOpcode();
3624 for (AMDGPU::OpName Name : reverse(ModifierOpNames)) {
3625 int Idx = AMDGPU::getNamedOperandIdx(Opc, Name);
3626 if (Idx >= 0)
3627 MI.removeOperand(Idx);
3628 }
3629}
3630
3632 const MCInstrDesc &NewDesc) const {
3633 MI.setDesc(NewDesc);
3634
3635 // Remove any leftover implicit operands from mutating the instruction. e.g.
3636 // if we replace an s_and_b32 with a copy, we don't need the implicit scc def
3637 // anymore.
3638 const MCInstrDesc &Desc = MI.getDesc();
3639 unsigned NumOps = Desc.getNumOperands() + Desc.implicit_uses().size() +
3640 Desc.implicit_defs().size();
3641
3642 for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
3643 MI.removeOperand(I);
3644}
3645
3646std::optional<int64_t> SIInstrInfo::extractSubregFromImm(int64_t Imm,
3647 unsigned SubRegIndex) {
3648 switch (SubRegIndex) {
3649 case AMDGPU::NoSubRegister:
3650 return Imm;
3651 case AMDGPU::sub0:
3652 return SignExtend64<32>(Imm);
3653 case AMDGPU::sub1:
3654 return SignExtend64<32>(Imm >> 32);
3655 case AMDGPU::lo16:
3656 return SignExtend64<16>(Imm);
3657 case AMDGPU::hi16:
3658 return SignExtend64<16>(Imm >> 16);
3659 case AMDGPU::sub1_lo16:
3660 return SignExtend64<16>(Imm >> 32);
3661 case AMDGPU::sub1_hi16:
3662 return SignExtend64<16>(Imm >> 48);
3663 default:
3664 return std::nullopt;
3665 }
3666
3667 llvm_unreachable("covered subregister switch");
3668}
3669
3670static unsigned getNewFMAAKInst(const GCNSubtarget &ST, unsigned Opc) {
3671 switch (Opc) {
3672 case AMDGPU::V_MAC_F16_e32:
3673 case AMDGPU::V_MAC_F16_e64:
3674 case AMDGPU::V_MAD_F16_e64:
3675 return AMDGPU::V_MADAK_F16;
3676 case AMDGPU::V_MAC_F32_e32:
3677 case AMDGPU::V_MAC_F32_e64:
3678 case AMDGPU::V_MAD_F32_e64:
3679 return AMDGPU::V_MADAK_F32;
3680 case AMDGPU::V_FMAC_F32_e32:
3681 case AMDGPU::V_FMAC_F32_e64:
3682 case AMDGPU::V_FMA_F32_e64:
3683 return AMDGPU::V_FMAAK_F32;
3684 case AMDGPU::V_FMAC_F16_e32:
3685 case AMDGPU::V_FMAC_F16_e64:
3686 case AMDGPU::V_FMAC_F16_t16_e64:
3687 case AMDGPU::V_FMAC_F16_fake16_e64:
3688 case AMDGPU::V_FMAC_F16_t16_e32:
3689 case AMDGPU::V_FMAC_F16_fake16_e32:
3690 case AMDGPU::V_FMA_F16_e64:
3691 return ST.hasTrue16BitInsts() ? ST.useRealTrue16Insts()
3692 ? AMDGPU::V_FMAAK_F16_t16
3693 : AMDGPU::V_FMAAK_F16_fake16
3694 : AMDGPU::V_FMAAK_F16;
3695 case AMDGPU::V_FMAC_F64_e32:
3696 case AMDGPU::V_FMAC_F64_e64:
3697 case AMDGPU::V_FMA_F64_e64:
3698 return AMDGPU::V_FMAAK_F64;
3699 default:
3700 llvm_unreachable("invalid instruction");
3701 }
3702}
3703
3704static unsigned getNewFMAMKInst(const GCNSubtarget &ST, unsigned Opc) {
3705 switch (Opc) {
3706 case AMDGPU::V_MAC_F16_e32:
3707 case AMDGPU::V_MAC_F16_e64:
3708 case AMDGPU::V_MAD_F16_e64:
3709 return AMDGPU::V_MADMK_F16;
3710 case AMDGPU::V_MAC_F32_e32:
3711 case AMDGPU::V_MAC_F32_e64:
3712 case AMDGPU::V_MAD_F32_e64:
3713 return AMDGPU::V_MADMK_F32;
3714 case AMDGPU::V_FMAC_F32_e32:
3715 case AMDGPU::V_FMAC_F32_e64:
3716 case AMDGPU::V_FMA_F32_e64:
3717 return AMDGPU::V_FMAMK_F32;
3718 case AMDGPU::V_FMAC_F16_e32:
3719 case AMDGPU::V_FMAC_F16_e64:
3720 case AMDGPU::V_FMAC_F16_t16_e64:
3721 case AMDGPU::V_FMAC_F16_fake16_e64:
3722 case AMDGPU::V_FMAC_F16_t16_e32:
3723 case AMDGPU::V_FMAC_F16_fake16_e32:
3724 case AMDGPU::V_FMA_F16_e64:
3725 return ST.hasTrue16BitInsts() ? ST.useRealTrue16Insts()
3726 ? AMDGPU::V_FMAMK_F16_t16
3727 : AMDGPU::V_FMAMK_F16_fake16
3728 : AMDGPU::V_FMAMK_F16;
3729 case AMDGPU::V_FMAC_F64_e32:
3730 case AMDGPU::V_FMAC_F64_e64:
3731 case AMDGPU::V_FMA_F64_e64:
3732 return AMDGPU::V_FMAMK_F64;
3733 default:
3734 llvm_unreachable("invalid instruction");
3735 }
3736}
3737
3739 Register Reg, MachineRegisterInfo *MRI) const {
3740 int64_t Imm;
3741 if (!getConstValDefinedInReg(DefMI, Reg, Imm))
3742 return false;
3743
3744 const bool HasMultipleUses = !MRI->hasOneNonDBGUse(Reg);
3745
3746 assert(!DefMI.getOperand(0).getSubReg() && "Expected SSA form");
3747
3748 unsigned Opc = UseMI.getOpcode();
3749 if (Opc == AMDGPU::COPY) {
3750 assert(!UseMI.getOperand(0).getSubReg() && "Expected SSA form");
3751
3752 Register DstReg = UseMI.getOperand(0).getReg();
3753 Register UseSubReg = UseMI.getOperand(1).getSubReg();
3754
3755 const TargetRegisterClass *DstRC = RI.getRegClassForReg(*MRI, DstReg);
3756
3757 if (HasMultipleUses) {
3758 // TODO: This should fold in more cases with multiple use, but we need to
3759 // more carefully consider what those uses are.
3760 unsigned ImmDefSize = RI.getRegSizeInBits(*MRI->getRegClass(Reg));
3761
3762 // Avoid breaking up a 64-bit inline immediate into a subregister extract.
3763 if (UseSubReg != AMDGPU::NoSubRegister && ImmDefSize == 64)
3764 return false;
3765
3766 // Most of the time folding a 32-bit inline constant is free (though this
3767 // might not be true if we can't later fold it into a real user).
3768 //
3769 // FIXME: This isInlineConstant check is imprecise if
3770 // getConstValDefinedInReg handled the tricky non-mov cases.
3771 if (ImmDefSize == 32 &&
3773 return false;
3774 }
3775
3776 bool Is16Bit = UseSubReg != AMDGPU::NoSubRegister &&
3777 RI.getSubRegIdxSize(UseSubReg) == 16;
3778
3779 if (Is16Bit) {
3780 if (RI.hasVGPRs(DstRC))
3781 return false; // Do not clobber vgpr_hi16
3782
3783 if (DstReg.isVirtual() && UseSubReg != AMDGPU::lo16)
3784 return false;
3785 }
3786
3787 MachineFunction *MF = UseMI.getMF();
3788
3789 unsigned NewOpc = AMDGPU::INSTRUCTION_LIST_END;
3790 MCRegister MovDstPhysReg =
3791 DstReg.isPhysical() ? DstReg.asMCReg() : MCRegister();
3792
3793 std::optional<int64_t> SubRegImm = extractSubregFromImm(Imm, UseSubReg);
3794
3795 // TODO: Try to fold with AMDGPU::V_MOV_B16_t16_e64
3796 for (unsigned MovOp :
3797 {AMDGPU::S_MOV_B32, AMDGPU::V_MOV_B32_e32, AMDGPU::S_MOV_B64,
3798 AMDGPU::V_MOV_B64_PSEUDO, AMDGPU::V_ACCVGPR_WRITE_B32_e64}) {
3799 const MCInstrDesc &MovDesc = get(MovOp);
3800
3801 const TargetRegisterClass *MovDstRC = getRegClass(MovDesc, 0);
3802 if (Is16Bit) {
3803 // We just need to find a correctly sized register class, so the
3804 // subregister index compatibility doesn't matter since we're statically
3805 // extracting the immediate value.
3806 MovDstRC = RI.getMatchingSuperRegClass(MovDstRC, DstRC, AMDGPU::lo16);
3807 if (!MovDstRC)
3808 continue;
3809
3810 if (MovDstPhysReg) {
3811 // FIXME: We probably should not do this. If there is a live value in
3812 // the high half of the register, it will be corrupted.
3813 MovDstPhysReg =
3814 RI.getMatchingSuperReg(MovDstPhysReg, AMDGPU::lo16, MovDstRC);
3815 if (!MovDstPhysReg)
3816 continue;
3817 }
3818 }
3819
3820 // Result class isn't the right size, try the next instruction.
3821 if (MovDstPhysReg) {
3822 if (!MovDstRC->contains(MovDstPhysReg))
3823 return false;
3824 } else if (!MRI->constrainRegClass(DstReg, MovDstRC)) {
3825 // TODO: This will be overly conservative in the case of 16-bit virtual
3826 // SGPRs. We could hack up the virtual register uses to use a compatible
3827 // 32-bit class.
3828 continue;
3829 }
3830
3831 const MCOperandInfo &OpInfo = MovDesc.operands()[1];
3832
3833 // Ensure the interpreted immediate value is a valid operand in the new
3834 // mov.
3835 //
3836 // FIXME: isImmOperandLegal should have form that doesn't require existing
3837 // MachineInstr or MachineOperand
3838 if (!RI.opCanUseLiteralConstant(OpInfo.OperandType) &&
3839 !isInlineConstant(*SubRegImm, OpInfo.OperandType))
3840 break;
3841
3842 NewOpc = MovOp;
3843 break;
3844 }
3845
3846 if (NewOpc == AMDGPU::INSTRUCTION_LIST_END)
3847 return false;
3848
3849 if (Is16Bit) {
3850 UseMI.getOperand(0).setSubReg(AMDGPU::NoSubRegister);
3851 if (MovDstPhysReg)
3852 UseMI.getOperand(0).setReg(MovDstPhysReg);
3853 assert(UseMI.getOperand(1).getReg().isVirtual());
3854 }
3855
3856 const MCInstrDesc &NewMCID = get(NewOpc);
3857 UseMI.setDesc(NewMCID);
3858 UseMI.getOperand(1).ChangeToImmediate(*SubRegImm);
3859 UseMI.addImplicitDefUseOperands(*MF);
3860 return true;
3861 }
3862
3863 if (HasMultipleUses)
3864 return false;
3865
3866 if (Opc == AMDGPU::V_MAD_F32_e64 || Opc == AMDGPU::V_MAC_F32_e64 ||
3867 Opc == AMDGPU::V_MAD_F16_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
3868 Opc == AMDGPU::V_FMA_F32_e64 || Opc == AMDGPU::V_FMAC_F32_e64 ||
3869 Opc == AMDGPU::V_FMA_F16_e64 || Opc == AMDGPU::V_FMAC_F16_e64 ||
3870 Opc == AMDGPU::V_FMAC_F16_t16_e64 ||
3871 Opc == AMDGPU::V_FMAC_F16_fake16_e64 || Opc == AMDGPU::V_FMA_F64_e64 ||
3872 Opc == AMDGPU::V_FMAC_F64_e64) {
3873 // Don't fold if we are using source or output modifiers. The new VOP2
3874 // instructions don't have them.
3876 return false;
3877
3878 // If this is a free constant, there's no reason to do this.
3879 // TODO: We could fold this here instead of letting SIFoldOperands do it
3880 // later.
3881 int Src0Idx = getNamedOperandIdx(UseMI.getOpcode(), AMDGPU::OpName::src0);
3882
3883 // Any src operand can be used for the legality check.
3884 if (isInlineConstant(UseMI, Src0Idx, Imm))
3885 return false;
3886
3887 MachineOperand *Src0 = &UseMI.getOperand(Src0Idx);
3888
3889 MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
3890 MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
3891
3892 auto CopyRegOperandToNarrowerRC =
3893 [MRI, this](MachineInstr &MI, unsigned OpNo,
3894 const TargetRegisterClass *NewRC) -> void {
3895 if (!MI.getOperand(OpNo).isReg())
3896 return;
3897 Register Reg = MI.getOperand(OpNo).getReg();
3898 const TargetRegisterClass *RC = RI.getRegClassForReg(*MRI, Reg);
3899 if (RI.getCommonSubClass(RC, NewRC) != NewRC)
3900 return;
3901 Register Tmp = MRI->createVirtualRegister(NewRC);
3902 BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
3903 get(AMDGPU::COPY), Tmp)
3904 .addReg(Reg);
3905 MI.getOperand(OpNo).setReg(Tmp);
3906 MI.getOperand(OpNo).setIsKill();
3907 };
3908
3909 // Multiplied part is the constant: Use v_madmk_{f16, f32}.
3910 if ((Src0->isReg() && Src0->getReg() == Reg) ||
3911 (Src1->isReg() && Src1->getReg() == Reg)) {
3912 MachineOperand *RegSrc =
3913 Src1->isReg() && Src1->getReg() == Reg ? Src0 : Src1;
3914 if (!RegSrc->isReg())
3915 return false;
3916 if (RI.isSGPRClass(MRI->getRegClass(RegSrc->getReg())) &&
3917 ST.getConstantBusLimit(Opc) < 2)
3918 return false;
3919
3920 if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
3921 return false;
3922
3923 // If src2 is also a literal constant then we have to choose which one to
3924 // fold. In general it is better to choose madak so that the other literal
3925 // can be materialized in an sgpr instead of a vgpr:
3926 // s_mov_b32 s0, literal
3927 // v_madak_f32 v0, s0, v0, literal
3928 // Instead of:
3929 // v_mov_b32 v1, literal
3930 // v_madmk_f32 v0, v0, literal, v1
3931 MachineInstr *Def = MRI->getUniqueVRegDef(Src2->getReg());
3932 if (Def && Def->isMoveImmediate() &&
3933 !isInlineConstant(Def->getOperand(1)))
3934 return false;
3935
3936 unsigned NewOpc = getNewFMAMKInst(ST, Opc);
3937 if (pseudoToMCOpcode(NewOpc) == -1)
3938 return false;
3939
3940 const std::optional<int64_t> SubRegImm = extractSubregFromImm(
3941 Imm, RegSrc == Src1 ? Src0->getSubReg() : Src1->getSubReg());
3942
3943 // FIXME: This would be a lot easier if we could return a new instruction
3944 // instead of having to modify in place.
3945
3946 Register SrcReg = RegSrc->getReg();
3947 unsigned SrcSubReg = RegSrc->getSubReg();
3948 Src0->setReg(SrcReg);
3949 Src0->setSubReg(SrcSubReg);
3950 Src0->setIsKill(RegSrc->isKill());
3951
3952 if (Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
3953 Opc == AMDGPU::V_FMAC_F32_e64 || Opc == AMDGPU::V_FMAC_F16_t16_e64 ||
3954 Opc == AMDGPU::V_FMAC_F16_fake16_e64 ||
3955 Opc == AMDGPU::V_FMAC_F16_e64 || Opc == AMDGPU::V_FMAC_F64_e64)
3956 UseMI.untieRegOperand(
3957 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
3958
3959 Src1->ChangeToImmediate(*SubRegImm);
3960
3962 UseMI.setDesc(get(NewOpc));
3963
3964 if (NewOpc == AMDGPU::V_FMAMK_F16_t16 ||
3965 NewOpc == AMDGPU::V_FMAMK_F16_fake16) {
3966 const TargetRegisterClass *NewRC = getRegClass(get(NewOpc), 0);
3967 Register Tmp = MRI->createVirtualRegister(NewRC);
3968 BuildMI(*UseMI.getParent(), std::next(UseMI.getIterator()),
3969 UseMI.getDebugLoc(), get(AMDGPU::COPY),
3970 UseMI.getOperand(0).getReg())
3971 .addReg(Tmp, RegState::Kill);
3972 UseMI.getOperand(0).setReg(Tmp);
3973 CopyRegOperandToNarrowerRC(UseMI, 1, NewRC);
3974 CopyRegOperandToNarrowerRC(UseMI, 3, NewRC);
3975 }
3976
3977 bool DeleteDef = MRI->use_nodbg_empty(Reg);
3978 if (DeleteDef)
3979 DefMI.eraseFromParent();
3980
3981 return true;
3982 }
3983
3984 // Added part is the constant: Use v_madak_{f16, f32}.
3985 if (Src2->isReg() && Src2->getReg() == Reg) {
3986 if (ST.getConstantBusLimit(Opc) < 2) {
3987 // Not allowed to use constant bus for another operand.
3988 // We can however allow an inline immediate as src0.
3989 bool Src0Inlined = false;
3990 if (Src0->isReg()) {
3991 // Try to inline constant if possible.
3992 // If the Def moves immediate and the use is single
3993 // We are saving VGPR here.
3994 MachineInstr *Def = MRI->getUniqueVRegDef(Src0->getReg());
3995 if (Def && Def->isMoveImmediate() &&
3996 isInlineConstant(Def->getOperand(1)) &&
3997 MRI->hasOneNonDBGUse(Src0->getReg())) {
3998 Src0->ChangeToImmediate(Def->getOperand(1).getImm());
3999 Src0Inlined = true;
4000 } else if (ST.getConstantBusLimit(Opc) <= 1 &&
4001 RI.isSGPRReg(*MRI, Src0->getReg())) {
4002 return false;
4003 }
4004 // VGPR is okay as Src0 - fallthrough
4005 }
4006
4007 if (Src1->isReg() && !Src0Inlined) {
4008 // We have one slot for inlinable constant so far - try to fill it
4009 MachineInstr *Def = MRI->getUniqueVRegDef(Src1->getReg());
4010 if (Def && Def->isMoveImmediate() &&
4011 isInlineConstant(Def->getOperand(1)) &&
4012 MRI->hasOneNonDBGUse(Src1->getReg()) && commuteInstruction(UseMI))
4013 Src0->ChangeToImmediate(Def->getOperand(1).getImm());
4014 else if (RI.isSGPRReg(*MRI, Src1->getReg()))
4015 return false;
4016 // VGPR is okay as Src1 - fallthrough
4017 }
4018 }
4019
4020 unsigned NewOpc = getNewFMAAKInst(ST, Opc);
4021 if (pseudoToMCOpcode(NewOpc) == -1)
4022 return false;
4023
4024 // FIXME: This would be a lot easier if we could return a new instruction
4025 // instead of having to modify in place.
4026
4027 if (Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
4028 Opc == AMDGPU::V_FMAC_F32_e64 || Opc == AMDGPU::V_FMAC_F16_t16_e64 ||
4029 Opc == AMDGPU::V_FMAC_F16_fake16_e64 ||
4030 Opc == AMDGPU::V_FMAC_F16_e64 || Opc == AMDGPU::V_FMAC_F64_e64)
4031 UseMI.untieRegOperand(
4032 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
4033
4034 const std::optional<int64_t> SubRegImm =
4035 extractSubregFromImm(Imm, Src2->getSubReg());
4036
4037 // ChangingToImmediate adds Src2 back to the instruction.
4038 Src2->ChangeToImmediate(*SubRegImm);
4039
4040 // These come before src2.
4042 UseMI.setDesc(get(NewOpc));
4043
4044 if (NewOpc == AMDGPU::V_FMAAK_F16_t16 ||
4045 NewOpc == AMDGPU::V_FMAAK_F16_fake16) {
4046 const TargetRegisterClass *NewRC = getRegClass(get(NewOpc), 0);
4047 Register Tmp = MRI->createVirtualRegister(NewRC);
4048 BuildMI(*UseMI.getParent(), std::next(UseMI.getIterator()),
4049 UseMI.getDebugLoc(), get(AMDGPU::COPY),
4050 UseMI.getOperand(0).getReg())
4051 .addReg(Tmp, RegState::Kill);
4052 UseMI.getOperand(0).setReg(Tmp);
4053 CopyRegOperandToNarrowerRC(UseMI, 1, NewRC);
4054 CopyRegOperandToNarrowerRC(UseMI, 2, NewRC);
4055 }
4056
4057 // It might happen that UseMI was commuted
4058 // and we now have SGPR as SRC1. If so 2 inlined
4059 // constant and SGPR are illegal.
4061
4062 bool DeleteDef = MRI->use_nodbg_empty(Reg);
4063 if (DeleteDef)
4064 DefMI.eraseFromParent();
4065
4066 return true;
4067 }
4068 }
4069
4070 return false;
4071}
4072
4073static bool
4076 if (BaseOps1.size() != BaseOps2.size())
4077 return false;
4078 for (size_t I = 0, E = BaseOps1.size(); I < E; ++I) {
4079 if (!BaseOps1[I]->isIdenticalTo(*BaseOps2[I]))
4080 return false;
4081 }
4082 return true;
4083}
4084
4085static bool offsetsDoNotOverlap(LocationSize WidthA, int OffsetA,
4086 LocationSize WidthB, int OffsetB) {
4087 int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
4088 int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
4089 LocationSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
4090 return LowWidth.hasValue() &&
4091 LowOffset + (int)LowWidth.getValue() <= HighOffset;
4092}
4093
4094bool SIInstrInfo::checkInstOffsetsDoNotOverlap(const MachineInstr &MIa,
4095 const MachineInstr &MIb) const {
4096 SmallVector<const MachineOperand *, 4> BaseOps0, BaseOps1;
4097 int64_t Offset0, Offset1;
4098 LocationSize Dummy0 = LocationSize::precise(0);
4099 LocationSize Dummy1 = LocationSize::precise(0);
4100 bool Offset0IsScalable, Offset1IsScalable;
4101 if (!getMemOperandsWithOffsetWidth(MIa, BaseOps0, Offset0, Offset0IsScalable,
4102 Dummy0, &RI) ||
4103 !getMemOperandsWithOffsetWidth(MIb, BaseOps1, Offset1, Offset1IsScalable,
4104 Dummy1, &RI))
4105 return false;
4106
4107 if (!memOpsHaveSameBaseOperands(BaseOps0, BaseOps1))
4108 return false;
4109
4110 if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
4111 // FIXME: Handle ds_read2 / ds_write2.
4112 return false;
4113 }
4114 LocationSize Width0 = MIa.memoperands().front()->getSize();
4115 LocationSize Width1 = MIb.memoperands().front()->getSize();
4116 return offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1);
4117}
4118
4120 const MachineInstr &MIb) const {
4121 assert(MIa.mayLoadOrStore() &&
4122 "MIa must load from or modify a memory location");
4123 assert(MIb.mayLoadOrStore() &&
4124 "MIb must load from or modify a memory location");
4125
4127 return false;
4128
4129 // XXX - Can we relax this between address spaces?
4130 if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
4131 return false;
4132
4133 if (isLDSDMA(MIa) || isLDSDMA(MIb))
4134 return false;
4135
4136 if (MIa.isBundle() || MIb.isBundle())
4137 return false;
4138
4139 // TODO: Should we check the address space from the MachineMemOperand? That
4140 // would allow us to distinguish objects we know don't alias based on the
4141 // underlying address space, even if it was lowered to a different one,
4142 // e.g. private accesses lowered to use MUBUF instructions on a scratch
4143 // buffer.
4144 if (isDS(MIa)) {
4145 if (isDS(MIb))
4146 return checkInstOffsetsDoNotOverlap(MIa, MIb);
4147
4148 return !isFLAT(MIb) || isSegmentSpecificFLAT(MIb);
4149 }
4150
4151 if (isMUBUF(MIa) || isMTBUF(MIa)) {
4152 if (isMUBUF(MIb) || isMTBUF(MIb))
4153 return checkInstOffsetsDoNotOverlap(MIa, MIb);
4154
4155 if (isFLAT(MIb))
4156 return isFLATScratch(MIb);
4157
4158 return !isSMRD(MIb);
4159 }
4160
4161 if (isSMRD(MIa)) {
4162 if (isSMRD(MIb))
4163 return checkInstOffsetsDoNotOverlap(MIa, MIb);
4164
4165 if (isFLAT(MIb))
4166 return isFLATScratch(MIb);
4167
4168 return !isMUBUF(MIb) && !isMTBUF(MIb);
4169 }
4170
4171 if (isFLAT(MIa)) {
4172 if (isFLAT(MIb)) {
4173 if ((isFLATScratch(MIa) && isFLATGlobal(MIb)) ||
4174 (isFLATGlobal(MIa) && isFLATScratch(MIb)))
4175 return true;
4176
4177 return checkInstOffsetsDoNotOverlap(MIa, MIb);
4178 }
4179
4180 return false;
4181 }
4182
4183 return false;
4184}
4185
4187 int64_t &Imm, MachineInstr **DefMI = nullptr) {
4188 if (Reg.isPhysical())
4189 return false;
4190 auto *Def = MRI.getUniqueVRegDef(Reg);
4191 if (Def && SIInstrInfo::isFoldableCopy(*Def) && Def->getOperand(1).isImm()) {
4192 Imm = Def->getOperand(1).getImm();
4193 if (DefMI)
4194 *DefMI = Def;
4195 return true;
4196 }
4197 return false;
4198}
4199
4200static bool getFoldableImm(const MachineOperand *MO, int64_t &Imm,
4201 MachineInstr **DefMI = nullptr) {
4202 if (!MO->isReg())
4203 return false;
4204 const MachineFunction *MF = MO->getParent()->getMF();
4205 const MachineRegisterInfo &MRI = MF->getRegInfo();
4206 return getFoldableImm(MO->getReg(), MRI, Imm, DefMI);
4207}
4208
4210 MachineInstr &NewMI) {
4211 if (LV) {
4212 unsigned NumOps = MI.getNumOperands();
4213 for (unsigned I = 1; I < NumOps; ++I) {
4214 MachineOperand &Op = MI.getOperand(I);
4215 if (Op.isReg() && Op.isKill())
4216 LV->replaceKillInstruction(Op.getReg(), MI, NewMI);
4217 }
4218 }
4219}
4220
4221static unsigned getNewFMAInst(const GCNSubtarget &ST, unsigned Opc) {
4222 switch (Opc) {
4223 case AMDGPU::V_MAC_F16_e32:
4224 case AMDGPU::V_MAC_F16_e64:
4225 return AMDGPU::V_MAD_F16_e64;
4226 case AMDGPU::V_MAC_F32_e32:
4227 case AMDGPU::V_MAC_F32_e64:
4228 return AMDGPU::V_MAD_F32_e64;
4229 case AMDGPU::V_MAC_LEGACY_F32_e32:
4230 case AMDGPU::V_MAC_LEGACY_F32_e64:
4231 return AMDGPU::V_MAD_LEGACY_F32_e64;
4232 case AMDGPU::V_FMAC_LEGACY_F32_e32:
4233 case AMDGPU::V_FMAC_LEGACY_F32_e64:
4234 return AMDGPU::V_FMA_LEGACY_F32_e64;
4235 case AMDGPU::V_FMAC_F16_e32:
4236 case AMDGPU::V_FMAC_F16_e64:
4237 case AMDGPU::V_FMAC_F16_t16_e64:
4238 case AMDGPU::V_FMAC_F16_fake16_e64:
4239 return ST.hasTrue16BitInsts() ? ST.useRealTrue16Insts()
4240 ? AMDGPU::V_FMA_F16_gfx9_t16_e64
4241 : AMDGPU::V_FMA_F16_gfx9_fake16_e64
4242 : AMDGPU::V_FMA_F16_gfx9_e64;
4243 case AMDGPU::V_FMAC_F32_e32:
4244 case AMDGPU::V_FMAC_F32_e64:
4245 return AMDGPU::V_FMA_F32_e64;
4246 case AMDGPU::V_FMAC_F64_e32:
4247 case AMDGPU::V_FMAC_F64_e64:
4248 return AMDGPU::V_FMA_F64_e64;
4249 default:
4250 llvm_unreachable("invalid instruction");
4251 }
4252}
4253
4254/// Helper struct for the implementation of 3-address conversion to communicate
4255/// updates made to instruction operands.
4257 /// Other instruction whose def is no longer used by the converted
4258 /// instruction.
4260};
4261
4263 LiveVariables *LV,
4264 LiveIntervals *LIS) const {
4265 MachineBasicBlock &MBB = *MI.getParent();
4266 MachineInstr *CandidateMI = &MI;
4267
4268 if (MI.isBundle()) {
4269 // This is a temporary placeholder for bundle handling that enables us to
4270 // exercise the relevant code paths in the two-address instruction pass.
4271 if (MI.getBundleSize() != 1)
4272 return nullptr;
4273 CandidateMI = MI.getNextNode();
4274 }
4275
4277 MachineInstr *NewMI = convertToThreeAddressImpl(*CandidateMI, U);
4278 if (!NewMI)
4279 return nullptr;
4280
4281 if (MI.isBundle()) {
4282 CandidateMI->eraseFromBundle();
4283
4284 for (MachineOperand &MO : MI.all_defs()) {
4285 if (MO.isTied())
4286 MI.untieRegOperand(MO.getOperandNo());
4287 }
4288 } else {
4289 updateLiveVariables(LV, MI, *NewMI);
4290 if (LIS) {
4291 LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
4292 // SlotIndex of defs needs to be updated when converting to early-clobber
4293 MachineOperand &Def = NewMI->getOperand(0);
4294 if (Def.isEarlyClobber() && Def.isReg() &&
4295 LIS->hasInterval(Def.getReg())) {
4296 SlotIndex OldIndex = LIS->getInstructionIndex(*NewMI).getRegSlot(false);
4297 SlotIndex NewIndex = LIS->getInstructionIndex(*NewMI).getRegSlot(true);
4298 auto &LI = LIS->getInterval(Def.getReg());
4299 auto UpdateDefIndex = [&](LiveRange &LR) {
4300 auto *S = LR.find(OldIndex);
4301 if (S != LR.end() && S->start == OldIndex) {
4302 assert(S->valno && S->valno->def == OldIndex);
4303 S->start = NewIndex;
4304 S->valno->def = NewIndex;
4305 }
4306 };
4307 UpdateDefIndex(LI);
4308 for (auto &SR : LI.subranges())
4309 UpdateDefIndex(SR);
4310 }
4311 }
4312 }
4313
4314 if (U.RemoveMIUse) {
4315 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4316 // The only user is the instruction which will be killed.
4317 Register DefReg = U.RemoveMIUse->getOperand(0).getReg();
4318
4319 if (MRI.hasOneNonDBGUse(DefReg)) {
4320 // We cannot just remove the DefMI here, calling pass will crash.
4321 U.RemoveMIUse->setDesc(get(AMDGPU::IMPLICIT_DEF));
4322 U.RemoveMIUse->getOperand(0).setIsDead(true);
4323 for (unsigned I = U.RemoveMIUse->getNumOperands() - 1; I != 0; --I)
4324 U.RemoveMIUse->removeOperand(I);
4325 if (LV)
4326 LV->getVarInfo(DefReg).AliveBlocks.clear();
4327 }
4328
4329 if (MI.isBundle()) {
4330 VirtRegInfo VRI = AnalyzeVirtRegInBundle(MI, DefReg);
4331 if (!VRI.Reads && !VRI.Writes) {
4332 for (MachineOperand &MO : MI.all_uses()) {
4333 if (MO.isReg() && MO.getReg() == DefReg) {
4334 assert(MO.getSubReg() == 0 &&
4335 "tied sub-registers in bundles currently not supported");
4336 MI.removeOperand(MO.getOperandNo());
4337 break;
4338 }
4339 }
4340
4341 if (LIS)
4342 LIS->shrinkToUses(&LIS->getInterval(DefReg));
4343 }
4344 } else if (LIS) {
4345 LiveInterval &DefLI = LIS->getInterval(DefReg);
4346
4347 // We cannot delete the original instruction here, so hack out the use
4348 // in the original instruction with a dummy register so we can use
4349 // shrinkToUses to deal with any multi-use edge cases. Other targets do
4350 // not have the complexity of deleting a use to consider here.
4351 Register DummyReg = MRI.cloneVirtualRegister(DefReg);
4352 for (MachineOperand &MIOp : MI.uses()) {
4353 if (MIOp.isReg() && MIOp.getReg() == DefReg) {
4354 MIOp.setIsUndef(true);
4355 MIOp.setReg(DummyReg);
4356 }
4357 }
4358
4359 if (MI.isBundle()) {
4360 VirtRegInfo VRI = AnalyzeVirtRegInBundle(MI, DefReg);
4361 if (!VRI.Reads && !VRI.Writes) {
4362 for (MachineOperand &MIOp : MI.uses()) {
4363 if (MIOp.isReg() && MIOp.getReg() == DefReg) {
4364 MIOp.setIsUndef(true);
4365 MIOp.setReg(DummyReg);
4366 }
4367 }
4368 }
4369
4370 MI.addOperand(MachineOperand::CreateReg(DummyReg, false, false, false,
4371 false, /*isUndef=*/true));
4372 }
4373
4374 LIS->shrinkToUses(&DefLI);
4375 }
4376 }
4377
4378 return MI.isBundle() ? &MI : NewMI;
4379}
4380
4382SIInstrInfo::convertToThreeAddressImpl(MachineInstr &MI,
4383 ThreeAddressUpdates &U) const {
4384 MachineBasicBlock &MBB = *MI.getParent();
4385 unsigned Opc = MI.getOpcode();
4386
4387 // Handle MFMA.
4388 int NewMFMAOpc = AMDGPU::getMFMAEarlyClobberOp(Opc);
4389 if (NewMFMAOpc != -1) {
4391 BuildMI(MBB, MI, MI.getDebugLoc(), get(NewMFMAOpc));
4392 for (unsigned I = 0, E = MI.getNumExplicitOperands(); I != E; ++I)
4393 MIB.add(MI.getOperand(I));
4394 return MIB;
4395 }
4396
4397 if (SIInstrInfo::isWMMA(MI)) {
4398 unsigned NewOpc = AMDGPU::mapWMMA2AddrTo3AddrOpcode(MI.getOpcode());
4399 MachineInstrBuilder MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
4400 .setMIFlags(MI.getFlags());
4401 for (unsigned I = 0, E = MI.getNumExplicitOperands(); I != E; ++I)
4402 MIB->addOperand(MI.getOperand(I));
4403 return MIB;
4404 }
4405
4406 assert(Opc != AMDGPU::V_FMAC_F16_t16_e32 &&
4407 Opc != AMDGPU::V_FMAC_F16_fake16_e32 &&
4408 "V_FMAC_F16_t16/fake16_e32 is not supported and not expected to be "
4409 "present pre-RA");
4410
4411 // Handle MAC/FMAC.
4412 bool IsF64 = Opc == AMDGPU::V_FMAC_F64_e32 || Opc == AMDGPU::V_FMAC_F64_e64;
4413 bool IsLegacy = Opc == AMDGPU::V_MAC_LEGACY_F32_e32 ||
4414 Opc == AMDGPU::V_MAC_LEGACY_F32_e64 ||
4415 Opc == AMDGPU::V_FMAC_LEGACY_F32_e32 ||
4416 Opc == AMDGPU::V_FMAC_LEGACY_F32_e64;
4417 bool Src0Literal = false;
4418
4419 switch (Opc) {
4420 default:
4421 return nullptr;
4422 case AMDGPU::V_MAC_F16_e64:
4423 case AMDGPU::V_FMAC_F16_e64:
4424 case AMDGPU::V_FMAC_F16_t16_e64:
4425 case AMDGPU::V_FMAC_F16_fake16_e64:
4426 case AMDGPU::V_MAC_F32_e64:
4427 case AMDGPU::V_MAC_LEGACY_F32_e64:
4428 case AMDGPU::V_FMAC_F32_e64:
4429 case AMDGPU::V_FMAC_LEGACY_F32_e64:
4430 case AMDGPU::V_FMAC_F64_e64:
4431 break;
4432 case AMDGPU::V_MAC_F16_e32:
4433 case AMDGPU::V_FMAC_F16_e32:
4434 case AMDGPU::V_MAC_F32_e32:
4435 case AMDGPU::V_MAC_LEGACY_F32_e32:
4436 case AMDGPU::V_FMAC_F32_e32:
4437 case AMDGPU::V_FMAC_LEGACY_F32_e32:
4438 case AMDGPU::V_FMAC_F64_e32: {
4439 int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
4440 AMDGPU::OpName::src0);
4441 const MachineOperand *Src0 = &MI.getOperand(Src0Idx);
4442 if (!Src0->isReg() && !Src0->isImm())
4443 return nullptr;
4444
4445 if (Src0->isImm() && !isInlineConstant(MI, Src0Idx, *Src0))
4446 Src0Literal = true;
4447
4448 break;
4449 }
4450 }
4451
4452 MachineInstrBuilder MIB;
4453 const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4454 const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
4455 const MachineOperand *Src0Mods =
4456 getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
4457 const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
4458 const MachineOperand *Src1Mods =
4459 getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
4460 const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
4461 const MachineOperand *Src2Mods =
4462 getNamedOperand(MI, AMDGPU::OpName::src2_modifiers);
4463 const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
4464 const MachineOperand *Omod = getNamedOperand(MI, AMDGPU::OpName::omod);
4465 const MachineOperand *OpSel = getNamedOperand(MI, AMDGPU::OpName::op_sel);
4466
4467 if (!Src0Mods && !Src1Mods && !Src2Mods && !Clamp && !Omod && !IsLegacy &&
4468 (!IsF64 || ST.hasFmaakFmamkF64Insts()) &&
4469 // If we have an SGPR input, we will violate the constant bus restriction.
4470 (ST.getConstantBusLimit(Opc) > 1 || !Src0->isReg() ||
4471 !RI.isSGPRReg(MBB.getParent()->getRegInfo(), Src0->getReg()))) {
4472 MachineInstr *DefMI;
4473
4474 int64_t Imm;
4475 if (!Src0Literal && getFoldableImm(Src2, Imm, &DefMI)) {
4476 unsigned NewOpc = getNewFMAAKInst(ST, Opc);
4477 if (pseudoToMCOpcode(NewOpc) != -1) {
4478 MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
4479 .add(*Dst)
4480 .add(*Src0)
4481 .add(*Src1)
4482 .addImm(Imm)
4483 .setMIFlags(MI.getFlags());
4484 U.RemoveMIUse = DefMI;
4485 return MIB;
4486 }
4487 }
4488 unsigned NewOpc = getNewFMAMKInst(ST, Opc);
4489 if (!Src0Literal && getFoldableImm(Src1, Imm, &DefMI)) {
4490 if (pseudoToMCOpcode(NewOpc) != -1) {
4491 MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
4492 .add(*Dst)
4493 .add(*Src0)
4494 .addImm(Imm)
4495 .add(*Src2)
4496 .setMIFlags(MI.getFlags());
4497 U.RemoveMIUse = DefMI;
4498 return MIB;
4499 }
4500 }
4501 if (Src0Literal || getFoldableImm(Src0, Imm, &DefMI)) {
4502 if (Src0Literal) {
4503 Imm = Src0->getImm();
4504 DefMI = nullptr;
4505 }
4506 if (pseudoToMCOpcode(NewOpc) != -1 &&
4508 MI, AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::src0),
4509 Src1)) {
4510 MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
4511 .add(*Dst)
4512 .add(*Src1)
4513 .addImm(Imm)
4514 .add(*Src2)
4515 .setMIFlags(MI.getFlags());
4516 U.RemoveMIUse = DefMI;
4517 return MIB;
4518 }
4519 }
4520 }
4521
4522 // VOP2 mac/fmac with a literal operand cannot be converted to VOP3 mad/fma
4523 // if VOP3 does not allow a literal operand.
4524 if (Src0Literal && !ST.hasVOP3Literal())
4525 return nullptr;
4526
4527 unsigned NewOpc = getNewFMAInst(ST, Opc);
4528
4529 if (pseudoToMCOpcode(NewOpc) == -1)
4530 return nullptr;
4531
4532 MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
4533 .add(*Dst)
4534 .addImm(Src0Mods ? Src0Mods->getImm() : 0)
4535 .add(*Src0)
4536 .addImm(Src1Mods ? Src1Mods->getImm() : 0)
4537 .add(*Src1)
4538 .addImm(Src2Mods ? Src2Mods->getImm() : 0)
4539 .add(*Src2)
4540 .addImm(Clamp ? Clamp->getImm() : 0)
4541 .addImm(Omod ? Omod->getImm() : 0)
4542 .setMIFlags(MI.getFlags());
4543 if (AMDGPU::hasNamedOperand(NewOpc, AMDGPU::OpName::op_sel))
4544 MIB.addImm(OpSel ? OpSel->getImm() : 0);
4545 return MIB;
4546}
4547
4548// It's not generally safe to move VALU instructions across these since it will
4549// start using the register as a base index rather than directly.
4550// XXX - Why isn't hasSideEffects sufficient for these?
4552 switch (MI.getOpcode()) {
4553 case AMDGPU::S_SET_GPR_IDX_ON:
4554 case AMDGPU::S_SET_GPR_IDX_MODE:
4555 case AMDGPU::S_SET_GPR_IDX_OFF:
4556 return true;
4557 default:
4558 return false;
4559 }
4560}
4561
4563 const MachineBasicBlock *MBB,
4564 const MachineFunction &MF) const {
4565 // Skipping the check for SP writes in the base implementation. The reason it
4566 // was added was apparently due to compile time concerns.
4567 //
4568 // TODO: Do we really want this barrier? It triggers unnecessary hazard nops
4569 // but is probably avoidable.
4570
4571 // Copied from base implementation.
4572 // Terminators and labels can't be scheduled around.
4573 if (MI.isTerminator() || MI.isPosition())
4574 return true;
4575
4576 // INLINEASM_BR can jump to another block
4577 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
4578 return true;
4579
4580 if (MI.getOpcode() == AMDGPU::SCHED_BARRIER && MI.getOperand(0).getImm() == 0)
4581 return true;
4582
4583 // Target-independent instructions do not have an implicit-use of EXEC, even
4584 // when they operate on VGPRs. Treating EXEC modifications as scheduling
4585 // boundaries prevents incorrect movements of such instructions.
4586 return MI.modifiesRegister(AMDGPU::EXEC, &RI) ||
4587 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
4588 MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
4589 MI.getOpcode() == AMDGPU::S_SETPRIO ||
4590 MI.getOpcode() == AMDGPU::S_SETPRIO_INC_WG ||
4592}
4593
4595 return Opcode == AMDGPU::DS_ORDERED_COUNT ||
4596 Opcode == AMDGPU::DS_ADD_GS_REG_RTN ||
4597 Opcode == AMDGPU::DS_SUB_GS_REG_RTN || isGWS(Opcode);
4598}
4599
4601 // Instructions that access scratch use FLAT encoding or BUF encodings.
4602 if ((!isFLAT(MI) || isFLATGlobal(MI)) && !isBUF(MI))
4603 return false;
4604
4605 // SCRATCH instructions always access scratch.
4606 if (isFLATScratch(MI))
4607 return true;
4608
4609 // If FLAT_SCRATCH registers are not initialized, we can never access scratch
4610 // via the aperture.
4611 if (MI.getMF()->getFunction().hasFnAttribute("amdgpu-no-flat-scratch-init"))
4612 return false;
4613
4614 // If there are no memory operands then conservatively assume the flat
4615 // operation may access scratch.
4616 if (MI.memoperands_empty())
4617 return true;
4618
4619 // See if any memory operand specifies an address space that involves scratch.
4620 return any_of(MI.memoperands(), [](const MachineMemOperand *Memop) {
4621 unsigned AS = Memop->getAddrSpace();
4622 if (AS == AMDGPUAS::FLAT_ADDRESS) {
4623 const MDNode *MD = Memop->getAAInfo().NoAliasAddrSpace;
4624 return !MD || !AMDGPU::hasValueInRangeLikeMetadata(
4625 *MD, AMDGPUAS::PRIVATE_ADDRESS);
4626 }
4627 return AS == AMDGPUAS::PRIVATE_ADDRESS;
4628 });
4629}
4630
4632 assert(isFLAT(MI));
4633
4634 // All flat instructions use the VMEM counter except prefetch.
4635 if (!usesVM_CNT(MI))
4636 return false;
4637
4638 // If there are no memory operands then conservatively assume the flat
4639 // operation may access VMEM.
4640 if (MI.memoperands_empty())
4641 return true;
4642
4643 // See if any memory operand specifies an address space that involves VMEM.
4644 // Flat operations only supported FLAT, LOCAL (LDS), or address spaces
4645 // involving VMEM such as GLOBAL, CONSTANT, PRIVATE (SCRATCH), etc. The REGION
4646 // (GDS) address space is not supported by flat operations. Therefore, simply
4647 // return true unless only the LDS address space is found.
4648 for (const MachineMemOperand *Memop : MI.memoperands()) {
4649 unsigned AS = Memop->getAddrSpace();
4651 if (AS != AMDGPUAS::LOCAL_ADDRESS)
4652 return true;
4653 }
4654
4655 return false;
4656}
4657
4659 assert(isFLAT(MI));
4660
4661 // Flat instruction such as SCRATCH and GLOBAL do not use the lgkm counter.
4662 if (!usesLGKM_CNT(MI))
4663 return false;
4664
4665 // If in tgsplit mode then there can be no use of LDS.
4666 if (ST.isTgSplitEnabled())
4667 return false;
4668
4669 // If there are no memory operands then conservatively assume the flat
4670 // operation may access LDS.
4671 if (MI.memoperands_empty())
4672 return true;
4673
4674 // See if any memory operand specifies an address space that involves LDS.
4675 for (const MachineMemOperand *Memop : MI.memoperands()) {
4676 unsigned AS = Memop->getAddrSpace();
4678 return true;
4679 }
4680
4681 return false;
4682}
4683
4685 // Skip the full operand and register alias search modifiesRegister
4686 // does. There's only a handful of instructions that touch this, it's only an
4687 // implicit def, and doesn't alias any other registers.
4688 return is_contained(MI.getDesc().implicit_defs(), AMDGPU::MODE);
4689}
4690
4692 unsigned Opcode = MI.getOpcode();
4693
4694 if (MI.mayStore() && isSMRD(MI))
4695 return true; // scalar store or atomic
4696
4697 // This will terminate the function when other lanes may need to continue.
4698 if (MI.isReturn())
4699 return true;
4700
4701 // These instructions cause shader I/O that may cause hardware lockups
4702 // when executed with an empty EXEC mask.
4703 //
4704 // Note: exp with VM = DONE = 0 is automatically skipped by hardware when
4705 // EXEC = 0, but checking for that case here seems not worth it
4706 // given the typical code patterns.
4707 if (Opcode == AMDGPU::S_SENDMSG || Opcode == AMDGPU::S_SENDMSGHALT ||
4708 isEXP(Opcode) || Opcode == AMDGPU::DS_ORDERED_COUNT ||
4709 Opcode == AMDGPU::S_TRAP || Opcode == AMDGPU::S_WAIT_EVENT ||
4710 Opcode == AMDGPU::S_SETHALT)
4711 return true;
4712
4713 if (MI.isCall() || MI.isInlineAsm())
4714 return true; // conservative assumption
4715
4716 // Assume that barrier interactions are only intended with active lanes.
4717 if (isBarrier(Opcode))
4718 return true;
4719
4720 // A mode change is a scalar operation that influences vector instructions.
4722 return true;
4723
4724 // These are like SALU instructions in terms of effects, so it's questionable
4725 // whether we should return true for those.
4726 //
4727 // However, executing them with EXEC = 0 causes them to operate on undefined
4728 // data, which we avoid by returning true here.
4729 if (Opcode == AMDGPU::V_READFIRSTLANE_B32 ||
4730 Opcode == AMDGPU::V_READLANE_B32 || Opcode == AMDGPU::V_WRITELANE_B32 ||
4731 Opcode == AMDGPU::SI_RESTORE_S32_FROM_VGPR ||
4732 Opcode == AMDGPU::SI_SPILL_S32_TO_VGPR)
4733 return true;
4734
4735 return false;
4736}
4737
4739 const MachineInstr &MI) const {
4740 if (MI.isMetaInstruction())
4741 return false;
4742
4743 // This won't read exec if this is an SGPR->SGPR copy.
4744 if (MI.isCopyLike()) {
4745 if (!RI.isSGPRReg(MRI, MI.getOperand(0).getReg()))
4746 return true;
4747
4748 // Make sure this isn't copying exec as a normal operand
4749 return MI.readsRegister(AMDGPU::EXEC, &RI);
4750 }
4751
4752 // Make a conservative assumption about the callee.
4753 if (MI.isCall())
4754 return true;
4755
4756 // Be conservative with any unhandled generic opcodes.
4757 if (!isTargetSpecificOpcode(MI.getOpcode()))
4758 return true;
4759
4760 return !isSALU(MI) || MI.readsRegister(AMDGPU::EXEC, &RI);
4761}
4762
4763bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
4764 switch (Imm.getBitWidth()) {
4765 case 1: // This likely will be a condition code mask.
4766 return true;
4767
4768 case 32:
4769 return AMDGPU::isInlinableLiteral32(Imm.getSExtValue(),
4770 ST.hasInv2PiInlineImm());
4771 case 64:
4772 return AMDGPU::isInlinableLiteral64(Imm.getSExtValue(),
4773 ST.hasInv2PiInlineImm());
4774 case 16:
4775 return ST.has16BitInsts() &&
4776 AMDGPU::isInlinableLiteralI16(Imm.getSExtValue(),
4777 ST.hasInv2PiInlineImm());
4778 default:
4779 llvm_unreachable("invalid bitwidth");
4780 }
4781}
4782
4784 APInt IntImm = Imm.bitcastToAPInt();
4785 int64_t IntImmVal = IntImm.getSExtValue();
4786 bool HasInv2Pi = ST.hasInv2PiInlineImm();
4787 switch (APFloat::SemanticsToEnum(Imm.getSemantics())) {
4788 default:
4789 llvm_unreachable("invalid fltSemantics");
4792 return isInlineConstant(IntImm);
4794 return ST.has16BitInsts() &&
4795 AMDGPU::isInlinableLiteralBF16(IntImmVal, HasInv2Pi);
4797 return ST.has16BitInsts() &&
4798 AMDGPU::isInlinableLiteralFP16(IntImmVal, HasInv2Pi);
4799 }
4800}
4801
4802bool SIInstrInfo::isInlineConstant(int64_t Imm, uint8_t OperandType) const {
4803 // MachineOperand provides no way to tell the true operand size, since it only
4804 // records a 64-bit value. We need to know the size to determine if a 32-bit
4805 // floating point immediate bit pattern is legal for an integer immediate. It
4806 // would be for any 32-bit integer operand, but would not be for a 64-bit one.
4807 switch (OperandType) {
4817 int32_t Trunc = static_cast<int32_t>(Imm);
4818 return AMDGPU::isInlinableLiteral32(Trunc, ST.hasInv2PiInlineImm());
4819 }
4826 return AMDGPU::isInlinableLiteral64(Imm, ST.hasInv2PiInlineImm());
4829 // We would expect inline immediates to not be concerned with an integer/fp
4830 // distinction. However, in the case of 16-bit integer operations, the
4831 // "floating point" values appear to not work. It seems read the low 16-bits
4832 // of 32-bit immediates, which happens to always work for the integer
4833 // values.
4834 //
4835 // See llvm bugzilla 46302.
4836 //
4837 // TODO: Theoretically we could use op-sel to use the high bits of the
4838 // 32-bit FP values.
4847 return AMDGPU::isPKFMACF16InlineConstant(Imm, ST.isGFX11Plus());
4852 return false;
4855 if (isInt<16>(Imm) || isUInt<16>(Imm)) {
4856 // A few special case instructions have 16-bit operands on subtargets
4857 // where 16-bit instructions are not legal.
4858 // TODO: Do the 32-bit immediates work? We shouldn't really need to handle
4859 // constants in these cases
4860 int16_t Trunc = static_cast<int16_t>(Imm);
4861 return ST.has16BitInsts() &&
4862 AMDGPU::isInlinableLiteralFP16(Trunc, ST.hasInv2PiInlineImm());
4863 }
4864
4865 return false;
4866 }
4869 if (isInt<16>(Imm) || isUInt<16>(Imm)) {
4870 int16_t Trunc = static_cast<int16_t>(Imm);
4871 return ST.has16BitInsts() &&
4872 AMDGPU::isInlinableLiteralBF16(Trunc, ST.hasInv2PiInlineImm());
4873 }
4874 return false;
4875 }
4879 return false;
4881 return isLegalAV64PseudoImm(Imm);
4884 // Always embedded in the instruction for free.
4885 return true;
4895 // Just ignore anything else.
4896 return true;
4897 default:
4898 llvm_unreachable("invalid operand type");
4899 }
4900}
4901
4902static bool compareMachineOp(const MachineOperand &Op0,
4903 const MachineOperand &Op1) {
4904 if (Op0.getType() != Op1.getType())
4905 return false;
4906
4907 switch (Op0.getType()) {
4909 return Op0.getReg() == Op1.getReg();
4911 return Op0.getImm() == Op1.getImm();
4912 default:
4913 llvm_unreachable("Didn't expect to be comparing these operand types");
4914 }
4915}
4916
4918 const MCOperandInfo &OpInfo) const {
4919 if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
4920 return true;
4921
4922 if (!RI.opCanUseLiteralConstant(OpInfo.OperandType))
4923 return false;
4924
4925 if (!isVOP3(InstDesc) || !AMDGPU::isSISrcOperand(OpInfo))
4926 return true;
4927
4928 return ST.hasVOP3Literal();
4929}
4930
4931bool SIInstrInfo::isImmOperandLegal(const MCInstrDesc &InstDesc, unsigned OpNo,
4932 int64_t ImmVal) const {
4933 const MCOperandInfo &OpInfo = InstDesc.operands()[OpNo];
4934 if (isInlineConstant(ImmVal, OpInfo.OperandType)) {
4935 if (isMAI(InstDesc) && ST.hasMFMAInlineLiteralBug() &&
4936 OpNo == (unsigned)AMDGPU::getNamedOperandIdx(InstDesc.getOpcode(),
4937 AMDGPU::OpName::src2))
4938 return false;
4939 return RI.opCanUseInlineConstant(OpInfo.OperandType);
4940 }
4941
4942 return isLiteralOperandLegal(InstDesc, OpInfo);
4943}
4944
4945bool SIInstrInfo::isImmOperandLegal(const MCInstrDesc &InstDesc, unsigned OpNo,
4946 const MachineOperand &MO) const {
4947 if (MO.isImm())
4948 return isImmOperandLegal(InstDesc, OpNo, MO.getImm());
4949
4950 assert((MO.isTargetIndex() || MO.isFI() || MO.isGlobal()) &&
4951 "unexpected imm-like operand kind");
4952 const MCOperandInfo &OpInfo = InstDesc.operands()[OpNo];
4953 return isLiteralOperandLegal(InstDesc, OpInfo);
4954}
4955
4957 // 2 32-bit inline constants packed into one.
4958 return AMDGPU::isInlinableLiteral32(Lo_32(Imm), ST.hasInv2PiInlineImm()) &&
4959 AMDGPU::isInlinableLiteral32(Hi_32(Imm), ST.hasInv2PiInlineImm());
4960}
4961
4962bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
4963 // GFX90A does not have V_MUL_LEGACY_F32_e32.
4964 if (Opcode == AMDGPU::V_MUL_LEGACY_F32_e64 && ST.hasGFX90AInsts())
4965 return false;
4966
4967 int Op32 = AMDGPU::getVOPe32(Opcode);
4968 if (Op32 == -1)
4969 return false;
4970
4971 return pseudoToMCOpcode(Op32) != -1;
4972}
4973
4974bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
4975 // The src0_modifier operand is present on all instructions
4976 // that have modifiers.
4977
4978 return AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::src0_modifiers);
4979}
4980
4982 AMDGPU::OpName OpName) const {
4983 const MachineOperand *Mods = getNamedOperand(MI, OpName);
4984 return Mods && Mods->getImm();
4985}
4986
4988 return any_of(ModifierOpNames,
4989 [&](AMDGPU::OpName Name) { return hasModifiersSet(MI, Name); });
4990}
4991
4993 const MachineRegisterInfo &MRI) const {
4994 const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
4995 // Can't shrink instruction with three operands.
4996 if (Src2) {
4997 switch (MI.getOpcode()) {
4998 default: return false;
4999
5000 case AMDGPU::V_ADDC_U32_e64:
5001 case AMDGPU::V_SUBB_U32_e64:
5002 case AMDGPU::V_SUBBREV_U32_e64: {
5003 const MachineOperand *Src1
5004 = getNamedOperand(MI, AMDGPU::OpName::src1);
5005 if (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()))
5006 return false;
5007 // Additional verification is needed for sdst/src2.
5008 return true;
5009 }
5010 case AMDGPU::V_MAC_F16_e64:
5011 case AMDGPU::V_MAC_F32_e64:
5012 case AMDGPU::V_MAC_LEGACY_F32_e64:
5013 case AMDGPU::V_FMAC_F16_e64:
5014 case AMDGPU::V_FMAC_F16_t16_e64:
5015 case AMDGPU::V_FMAC_F16_fake16_e64:
5016 case AMDGPU::V_FMAC_F32_e64:
5017 case AMDGPU::V_FMAC_F64_e64:
5018 case AMDGPU::V_FMAC_LEGACY_F32_e64:
5019 if (!Src2->isReg() || !RI.isVGPR(MRI, Src2->getReg()) ||
5020 hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
5021 return false;
5022 break;
5023
5024 case AMDGPU::V_CNDMASK_B32_e64:
5025 break;
5026 }
5027 }
5028
5029 const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
5030 if (Src1 && (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()) ||
5031 hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers)))
5032 return false;
5033
5034 // We don't need to check src0, all input types are legal, so just make sure
5035 // src0 isn't using any modifiers.
5036 if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
5037 return false;
5038
5039 // Can it be shrunk to a valid 32 bit opcode?
5040 if (!hasVALU32BitEncoding(MI.getOpcode()))
5041 return false;
5042
5043 // Check output modifiers
5044 return !hasModifiersSet(MI, AMDGPU::OpName::omod) &&
5045 !hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
5046 !hasModifiersSet(MI, AMDGPU::OpName::byte_sel) &&
5047 // TODO: Can we avoid checking bound_ctrl/fi here?
5048 // They are only used by permlane*_swap special case.
5049 !hasModifiersSet(MI, AMDGPU::OpName::bound_ctrl) &&
5050 !hasModifiersSet(MI, AMDGPU::OpName::fi);
5051}
5052
5053// Set VCC operand with all flags from \p Orig, except for setting it as
5054// implicit.
5056 const MachineOperand &Orig) {
5057
5058 for (MachineOperand &Use : MI.implicit_operands()) {
5059 if (Use.isUse() &&
5060 (Use.getReg() == AMDGPU::VCC || Use.getReg() == AMDGPU::VCC_LO)) {
5061 Use.setIsUndef(Orig.isUndef());
5062 Use.setIsKill(Orig.isKill());
5063 return;
5064 }
5065 }
5066}
5067
5069 unsigned Op32) const {
5070 MachineBasicBlock *MBB = MI.getParent();
5071
5072 const MCInstrDesc &Op32Desc = get(Op32);
5073 MachineInstrBuilder Inst32 =
5074 BuildMI(*MBB, MI, MI.getDebugLoc(), Op32Desc)
5075 .setMIFlags(MI.getFlags());
5076
5077 // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
5078 // For VOPC instructions, this is replaced by an implicit def of vcc.
5079
5080 // We assume the defs of the shrunk opcode are in the same order, and the
5081 // shrunk opcode loses the last def (SGPR def, in the VOP3->VOPC case).
5082 for (int I = 0, E = Op32Desc.getNumDefs(); I != E; ++I)
5083 Inst32.add(MI.getOperand(I));
5084
5085 const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
5086
5087 int Idx = MI.getNumExplicitDefs();
5088 for (const MachineOperand &Use : MI.explicit_uses()) {
5089 int OpTy = MI.getDesc().operands()[Idx++].OperandType;
5091 continue;
5092
5093 if (&Use == Src2) {
5094 if (AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2) == -1) {
5095 // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
5096 // replaced with an implicit read of vcc or vcc_lo. The implicit read
5097 // of vcc was already added during the initial BuildMI, but we
5098 // 1) may need to change vcc to vcc_lo to preserve the original register
5099 // 2) have to preserve the original flags.
5100 copyFlagsToImplicitVCC(*Inst32, *Src2);
5101 continue;
5102 }
5103 }
5104
5105 Inst32.add(Use);
5106 }
5107
5108 // FIXME: Losing implicit operands
5109 fixImplicitOperands(*Inst32);
5110 return Inst32;
5111}
5112
5114 // Null is free
5115 Register Reg = RegOp.getReg();
5116 if (Reg == AMDGPU::SGPR_NULL || Reg == AMDGPU::SGPR_NULL64)
5117 return false;
5118
5119 // SGPRs use the constant bus
5120
5121 // FIXME: implicit registers that are not part of the MCInstrDesc's implicit
5122 // physical register operands should also count, except for exec.
5123 if (RegOp.isImplicit())
5124 return Reg == AMDGPU::VCC || Reg == AMDGPU::VCC_LO || Reg == AMDGPU::M0;
5125
5126 // SGPRs use the constant bus
5127 return AMDGPU::SReg_32RegClass.contains(Reg) ||
5128 AMDGPU::SReg_64RegClass.contains(Reg);
5129}
5130
5132 const MachineRegisterInfo &MRI) const {
5133 Register Reg = RegOp.getReg();
5134 return Reg.isVirtual() ? RI.isSGPRClass(MRI.getRegClass(Reg))
5135 : physRegUsesConstantBus(RegOp);
5136}
5137
5139 const MachineOperand &MO,
5140 const MCOperandInfo &OpInfo) const {
5141 // Literal constants use the constant bus.
5142 if (!MO.isReg())
5143 return !isInlineConstant(MO, OpInfo);
5144
5145 Register Reg = MO.getReg();
5146 return Reg.isVirtual() ? RI.isSGPRClass(MRI.getRegClass(Reg))
5148}
5149
5151 for (const MachineOperand &MO : MI.implicit_operands()) {
5152 // We only care about reads.
5153 if (MO.isDef())
5154 continue;
5155
5156 switch (MO.getReg()) {
5157 case AMDGPU::VCC:
5158 case AMDGPU::VCC_LO:
5159 case AMDGPU::VCC_HI:
5160 case AMDGPU::M0:
5161 case AMDGPU::FLAT_SCR:
5162 return MO.getReg();
5163
5164 default:
5165 break;
5166 }
5167 }
5168
5169 return Register();
5170}
5171
5172static bool shouldReadExec(const MachineInstr &MI) {
5173 if (SIInstrInfo::isVALU(MI)) {
5174 switch (MI.getOpcode()) {
5175 case AMDGPU::V_READLANE_B32:
5176 case AMDGPU::SI_RESTORE_S32_FROM_VGPR:
5177 case AMDGPU::V_WRITELANE_B32:
5178 case AMDGPU::SI_SPILL_S32_TO_VGPR:
5179 return false;
5180 }
5181
5182 return true;
5183 }
5184
5185 if (MI.isPreISelOpcode() ||
5186 SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
5189 return false;
5190
5191 return true;
5192}
5193
5194static bool isRegOrFI(const MachineOperand &MO) {
5195 return MO.isReg() || MO.isFI();
5196}
5197
5198static bool isSubRegOf(const SIRegisterInfo &TRI,
5199 const MachineOperand &SuperVec,
5200 const MachineOperand &SubReg) {
5201 if (SubReg.getReg().isPhysical())
5202 return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
5203
5204 return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
5205 SubReg.getReg() == SuperVec.getReg();
5206}
5207
5208// Verify the illegal copy from vector register to SGPR for generic opcode COPY
5209bool SIInstrInfo::verifyCopy(const MachineInstr &MI,
5210 const MachineRegisterInfo &MRI,
5211 StringRef &ErrInfo) const {
5212 Register DstReg = MI.getOperand(0).getReg();
5213 Register SrcReg = MI.getOperand(1).getReg();
5214 // This is a check for copy from vector register to SGPR
5215 if (RI.isVectorRegister(MRI, SrcReg) && RI.isSGPRReg(MRI, DstReg)) {
5216 ErrInfo = "illegal copy from vector register to SGPR";
5217 return false;
5218 }
5219 return true;
5220}
5221
5223 StringRef &ErrInfo) const {
5224 uint32_t Opcode = MI.getOpcode();
5225 const MachineFunction *MF = MI.getMF();
5226 const MachineRegisterInfo &MRI = MF->getRegInfo();
5227
5228 // FIXME: At this point the COPY verify is done only for non-ssa forms.
5229 // Find a better property to recognize the point where instruction selection
5230 // is just done.
5231 // We can only enforce this check after SIFixSGPRCopies pass so that the
5232 // illegal copies are legalized and thereafter we don't expect a pass
5233 // inserting similar copies.
5234 if (!MRI.isSSA() && MI.isCopy())
5235 return verifyCopy(MI, MRI, ErrInfo);
5236
5237 if (SIInstrInfo::isGenericOpcode(Opcode))
5238 return true;
5239
5240 int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
5241 int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
5242 int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
5243 int Src3Idx = -1;
5244 if (Src0Idx == -1) {
5245 // VOPD V_DUAL_* instructions use different operand names.
5246 Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0X);
5247 Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vsrc1X);
5248 Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0Y);
5249 Src3Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vsrc1Y);
5250 }
5251
5252 // Make sure the number of operands is correct.
5253 const MCInstrDesc &Desc = get(Opcode);
5254 if (!Desc.isVariadic() &&
5255 Desc.getNumOperands() != MI.getNumExplicitOperands()) {
5256 ErrInfo = "Instruction has wrong number of operands.";
5257 return false;
5258 }
5259
5260 if (MI.isInlineAsm()) {
5261 // Verify register classes for inlineasm constraints.
5262 for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
5263 I != E; ++I) {
5264 const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
5265 if (!RC)
5266 continue;
5267
5268 const MachineOperand &Op = MI.getOperand(I);
5269 if (!Op.isReg())
5270 continue;
5271
5272 Register Reg = Op.getReg();
5273 if (!Reg.isVirtual() && !RC->contains(Reg)) {
5274 ErrInfo = "inlineasm operand has incorrect register class.";
5275 return false;
5276 }
5277 }
5278
5279 return true;
5280 }
5281
5282 if (isImage(MI) && MI.memoperands_empty() && MI.mayLoadOrStore()) {
5283 ErrInfo = "missing memory operand from image instruction.";
5284 return false;
5285 }
5286
5287 // Make sure the register classes are correct.
5288 for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
5289 const MachineOperand &MO = MI.getOperand(i);
5290 if (MO.isFPImm()) {
5291 ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
5292 "all fp values to integers.";
5293 return false;
5294 }
5295
5296 const MCOperandInfo &OpInfo = Desc.operands()[i];
5297 int16_t RegClass = getOpRegClassID(OpInfo);
5298
5299 switch (OpInfo.OperandType) {
5301 if (MI.getOperand(i).isImm() || MI.getOperand(i).isGlobal()) {
5302 ErrInfo = "Illegal immediate value for operand.";
5303 return false;
5304 }
5305 break;
5316 break;
5318 break;
5319 break;
5333 if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
5334 ErrInfo = "Illegal immediate value for operand.";
5335 return false;
5336 }
5337 break;
5338 }
5343 if (ST.has64BitLiterals() && Desc.getSize() != 4 && MO.isImm() &&
5344 !isInlineConstant(MI, i) &&
5346 OpInfo.OperandType ==
5348 ErrInfo = "illegal 64-bit immediate value for operand.";
5349 return false;
5350 }
5351 break;
5354 if (!MI.getOperand(i).isImm() || !isInlineConstant(MI, i)) {
5355 ErrInfo = "Expected inline constant for operand.";
5356 return false;
5357 }
5358 break;
5361 break;
5366 // Check if this operand is an immediate.
5367 // FrameIndex operands will be replaced by immediates, so they are
5368 // allowed.
5369 if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
5370 ErrInfo = "Expected immediate, but got non-immediate";
5371 return false;
5372 }
5373 break;
5377 break;
5378 default:
5379 if (OpInfo.isGenericType())
5380 continue;
5381 break;
5382 }
5383
5384 if (!MO.isReg())
5385 continue;
5386 Register Reg = MO.getReg();
5387 if (!Reg)
5388 continue;
5389
5390 // FIXME: Ideally we would have separate instruction definitions with the
5391 // aligned register constraint.
5392 // FIXME: We do not verify inline asm operands, but custom inline asm
5393 // verification is broken anyway
5394 if (ST.needsAlignedVGPRs() && Opcode != AMDGPU::AV_MOV_B64_IMM_PSEUDO &&
5395 Opcode != AMDGPU::V_MOV_B64_PSEUDO && !isSpill(MI)) {
5396 const TargetRegisterClass *RC = RI.getRegClassForReg(MRI, Reg);
5397 if (RI.hasVectorRegisters(RC) && MO.getSubReg()) {
5398 if (const TargetRegisterClass *SubRC =
5399 RI.getSubRegisterClass(RC, MO.getSubReg())) {
5400 RC = RI.getCompatibleSubRegClass(RC, SubRC, MO.getSubReg());
5401 if (RC)
5402 RC = SubRC;
5403 }
5404 }
5405
5406 // Check that this is the aligned version of the class.
5407 if (!RC || !RI.isProperlyAlignedRC(*RC)) {
5408 ErrInfo = "Subtarget requires even aligned vector registers";
5409 return false;
5410 }
5411 }
5412
5413 if (RegClass != -1) {
5414 if (Reg.isVirtual())
5415 continue;
5416
5417 const TargetRegisterClass *RC = RI.getRegClass(RegClass);
5418 if (!RC->contains(Reg)) {
5419 ErrInfo = "Operand has incorrect register class.";
5420 return false;
5421 }
5422 }
5423 }
5424
5425 // Verify SDWA
5426 if (isSDWA(MI)) {
5427 if (!ST.hasSDWA()) {
5428 ErrInfo = "SDWA is not supported on this target";
5429 return false;
5430 }
5431
5432 for (auto Op : {AMDGPU::OpName::src0_sel, AMDGPU::OpName::src1_sel,
5433 AMDGPU::OpName::dst_sel}) {
5434 const MachineOperand *MO = getNamedOperand(MI, Op);
5435 if (!MO)
5436 continue;
5437 int64_t Imm = MO->getImm();
5438 if (Imm < 0 || Imm > AMDGPU::SDWA::SdwaSel::DWORD) {
5439 ErrInfo = "Invalid SDWA selection";
5440 return false;
5441 }
5442 }
5443
5444 int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
5445
5446 for (int OpIdx : {DstIdx, Src0Idx, Src1Idx, Src2Idx}) {
5447 if (OpIdx == -1)
5448 continue;
5449 const MachineOperand &MO = MI.getOperand(OpIdx);
5450
5451 if (!ST.hasSDWAScalar()) {
5452 // Only VGPRS on VI
5453 if (!MO.isReg() || !RI.hasVGPRs(RI.getRegClassForReg(MRI, MO.getReg()))) {
5454 ErrInfo = "Only VGPRs allowed as operands in SDWA instructions on VI";
5455 return false;
5456 }
5457 } else {
5458 // No immediates on GFX9
5459 if (!MO.isReg()) {
5460 ErrInfo =
5461 "Only reg allowed as operands in SDWA instructions on GFX9+";
5462 return false;
5463 }
5464 }
5465 }
5466
5467 if (!ST.hasSDWAOmod()) {
5468 // No omod allowed on VI
5469 const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
5470 if (OMod != nullptr &&
5471 (!OMod->isImm() || OMod->getImm() != 0)) {
5472 ErrInfo = "OMod not allowed in SDWA instructions on VI";
5473 return false;
5474 }
5475 }
5476
5477 if (Opcode == AMDGPU::V_CVT_F32_FP8_sdwa ||
5478 Opcode == AMDGPU::V_CVT_F32_BF8_sdwa ||
5479 Opcode == AMDGPU::V_CVT_PK_F32_FP8_sdwa ||
5480 Opcode == AMDGPU::V_CVT_PK_F32_BF8_sdwa) {
5481 const MachineOperand *Src0ModsMO =
5482 getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
5483 unsigned Mods = Src0ModsMO->getImm();
5484 if (Mods & SISrcMods::ABS || Mods & SISrcMods::NEG ||
5485 Mods & SISrcMods::SEXT) {
5486 ErrInfo = "sext, abs and neg are not allowed on this instruction";
5487 return false;
5488 }
5489 }
5490
5491 uint32_t BasicOpcode = AMDGPU::getBasicFromSDWAOp(Opcode);
5492 if (isVOPC(BasicOpcode)) {
5493 if (!ST.hasSDWASdst() && DstIdx != -1) {
5494 // Only vcc allowed as dst on VI for VOPC
5495 const MachineOperand &Dst = MI.getOperand(DstIdx);
5496 if (!Dst.isReg() || Dst.getReg() != AMDGPU::VCC) {
5497 ErrInfo = "Only VCC allowed as dst in SDWA instructions on VI";
5498 return false;
5499 }
5500 } else if (!ST.hasSDWAOutModsVOPC()) {
5501 // No clamp allowed on GFX9 for VOPC
5502 const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
5503 if (Clamp && (!Clamp->isImm() || Clamp->getImm() != 0)) {
5504 ErrInfo = "Clamp not allowed in VOPC SDWA instructions on VI";
5505 return false;
5506 }
5507
5508 // No omod allowed on GFX9 for VOPC
5509 const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
5510 if (OMod && (!OMod->isImm() || OMod->getImm() != 0)) {
5511 ErrInfo = "OMod not allowed in VOPC SDWA instructions on VI";
5512 return false;
5513 }
5514 }
5515 }
5516
5517 const MachineOperand *DstUnused = getNamedOperand(MI, AMDGPU::OpName::dst_unused);
5518 if (DstUnused && DstUnused->isImm() &&
5519 DstUnused->getImm() == AMDGPU::SDWA::UNUSED_PRESERVE) {
5520 const MachineOperand &Dst = MI.getOperand(DstIdx);
5521 if (!Dst.isReg() || !Dst.isTied()) {
5522 ErrInfo = "Dst register should have tied register";
5523 return false;
5524 }
5525
5526 const MachineOperand &TiedMO =
5527 MI.getOperand(MI.findTiedOperandIdx(DstIdx));
5528 if (!TiedMO.isReg() || !TiedMO.isImplicit() || !TiedMO.isUse()) {
5529 ErrInfo =
5530 "Dst register should be tied to implicit use of preserved register";
5531 return false;
5532 }
5533 if (TiedMO.getReg().isPhysical() && Dst.getReg() != TiedMO.getReg()) {
5534 ErrInfo = "Dst register should use same physical register as preserved";
5535 return false;
5536 }
5537 }
5538 }
5539
5540 if (isDPP(MI) && !ST.hasDPPSrc1SGPR() && Src1Idx != -1) {
5541 const MachineOperand &Src1MO = MI.getOperand(Src1Idx);
5542 if (Src1MO.isReg() && RI.isSGPRReg(MRI, Src1MO.getReg())) {
5543 ErrInfo = "DPP src1 cannot be SGPR on this subtarget";
5544 return false;
5545 }
5546 }
5547
5548 // Verify MIMG / VIMAGE / VSAMPLE
5549 if (isImage(Opcode) && !MI.mayStore()) {
5550 // Ensure that the return type used is large enough for all the options
5551 // being used TFE/LWE require an extra result register.
5552 const MachineOperand *DMask = getNamedOperand(MI, AMDGPU::OpName::dmask);
5553 if (DMask) {
5554 uint64_t DMaskImm = DMask->getImm();
5555 uint32_t RegCount = isGather4(Opcode) ? 4 : llvm::popcount(DMaskImm);
5556 const MachineOperand *TFE = getNamedOperand(MI, AMDGPU::OpName::tfe);
5557 const MachineOperand *LWE = getNamedOperand(MI, AMDGPU::OpName::lwe);
5558 const MachineOperand *D16 = getNamedOperand(MI, AMDGPU::OpName::d16);
5559
5560 // Adjust for packed 16 bit values
5561 if (D16 && D16->getImm() && !ST.hasUnpackedD16VMem())
5562 RegCount = divideCeil(RegCount, 2);
5563
5564 // Adjust if using LWE or TFE
5565 if ((LWE && LWE->getImm()) || (TFE && TFE->getImm()))
5566 RegCount += 1;
5567
5568 const uint32_t DstIdx =
5569 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
5570 const MachineOperand &Dst = MI.getOperand(DstIdx);
5571 if (Dst.isReg()) {
5572 const TargetRegisterClass *DstRC = getOpRegClass(MI, DstIdx);
5573 uint32_t DstSize = RI.getRegSizeInBits(*DstRC) / 32;
5574 if (RegCount > DstSize) {
5575 ErrInfo = "Image instruction returns too many registers for dst "
5576 "register class";
5577 return false;
5578 }
5579 }
5580 }
5581 }
5582
5583 // Verify VOP*. Ignore multiple sgpr operands on writelane.
5584 if (isVALU(MI) && Desc.getOpcode() != AMDGPU::V_WRITELANE_B32) {
5585 unsigned ConstantBusCount = 0;
5586 bool UsesLiteral = false;
5587 const MachineOperand *LiteralVal = nullptr;
5588
5589 int ImmIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm);
5590 if (ImmIdx != -1) {
5591 ++ConstantBusCount;
5592 UsesLiteral = true;
5593 LiteralVal = &MI.getOperand(ImmIdx);
5594 }
5595
5596 SmallVector<Register, 2> SGPRsUsed;
5597 Register SGPRUsed;
5598
5599 // Only look at the true operands. Only a real operand can use the constant
5600 // bus, and we don't want to check pseudo-operands like the source modifier
5601 // flags.
5602 for (int OpIdx : {Src0Idx, Src1Idx, Src2Idx, Src3Idx}) {
5603 if (OpIdx == -1)
5604 continue;
5605 const MachineOperand &MO = MI.getOperand(OpIdx);
5606 if (usesConstantBus(MRI, MO, MI.getDesc().operands()[OpIdx])) {
5607 if (MO.isReg()) {
5608 SGPRUsed = MO.getReg();
5609 if (!llvm::is_contained(SGPRsUsed, SGPRUsed)) {
5610 ++ConstantBusCount;
5611 SGPRsUsed.push_back(SGPRUsed);
5612 }
5613 } else if (!MO.isFI()) { // Treat FI like a register.
5614 if (!UsesLiteral) {
5615 ++ConstantBusCount;
5616 UsesLiteral = true;
5617 LiteralVal = &MO;
5618 } else if (!MO.isIdenticalTo(*LiteralVal)) {
5619 assert(isVOP2(MI) || isVOP3(MI));
5620 ErrInfo = "VOP2/VOP3 instruction uses more than one literal";
5621 return false;
5622 }
5623 }
5624 }
5625 }
5626
5627 SGPRUsed = findImplicitSGPRRead(MI);
5628 if (SGPRUsed) {
5629 // Implicit uses may safely overlap true operands
5630 if (llvm::all_of(SGPRsUsed, [this, SGPRUsed](unsigned SGPR) {
5631 return !RI.regsOverlap(SGPRUsed, SGPR);
5632 })) {
5633 ++ConstantBusCount;
5634 SGPRsUsed.push_back(SGPRUsed);
5635 }
5636 }
5637
5638 // v_writelane_b32 is an exception from constant bus restriction:
5639 // vsrc0 can be sgpr, const or m0 and lane select sgpr, m0 or inline-const
5640 if (ConstantBusCount > ST.getConstantBusLimit(Opcode) &&
5641 Opcode != AMDGPU::V_WRITELANE_B32) {
5642 ErrInfo = "VOP* instruction violates constant bus restriction";
5643 return false;
5644 }
5645
5646 if (isVOP3(MI) && UsesLiteral && !ST.hasVOP3Literal()) {
5647 ErrInfo = "VOP3 instruction uses literal";
5648 return false;
5649 }
5650 }
5651
5652 // Special case for writelane - this can break the multiple constant bus rule,
5653 // but still can't use more than one SGPR register
5654 if (Desc.getOpcode() == AMDGPU::V_WRITELANE_B32) {
5655 unsigned SGPRCount = 0;
5656 Register SGPRUsed;
5657
5658 for (int OpIdx : {Src0Idx, Src1Idx}) {
5659 if (OpIdx == -1)
5660 break;
5661
5662 const MachineOperand &MO = MI.getOperand(OpIdx);
5663
5664 if (usesConstantBus(MRI, MO, MI.getDesc().operands()[OpIdx])) {
5665 if (MO.isReg() && MO.getReg() != AMDGPU::M0) {
5666 if (MO.getReg() != SGPRUsed)
5667 ++SGPRCount;
5668 SGPRUsed = MO.getReg();
5669 }
5670 }
5671 if (SGPRCount > ST.getConstantBusLimit(Opcode)) {
5672 ErrInfo = "WRITELANE instruction violates constant bus restriction";
5673 return false;
5674 }
5675 }
5676 }
5677
5678 // Verify misc. restrictions on specific instructions.
5679 if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32_e64 ||
5680 Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64_e64) {
5681 const MachineOperand &Src0 = MI.getOperand(Src0Idx);
5682 const MachineOperand &Src1 = MI.getOperand(Src1Idx);
5683 const MachineOperand &Src2 = MI.getOperand(Src2Idx);
5684 if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
5685 if (!compareMachineOp(Src0, Src1) &&
5686 !compareMachineOp(Src0, Src2)) {
5687 ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
5688 return false;
5689 }
5690 }
5691 if ((getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm() &
5692 SISrcMods::ABS) ||
5693 (getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm() &
5694 SISrcMods::ABS) ||
5695 (getNamedOperand(MI, AMDGPU::OpName::src2_modifiers)->getImm() &
5696 SISrcMods::ABS)) {
5697 ErrInfo = "ABS not allowed in VOP3B instructions";
5698 return false;
5699 }
5700 }
5701
5702 if (isSOP2(MI) || isSOPC(MI)) {
5703 const MachineOperand &Src0 = MI.getOperand(Src0Idx);
5704 const MachineOperand &Src1 = MI.getOperand(Src1Idx);
5705
5706 if (!isRegOrFI(Src0) && !isRegOrFI(Src1) &&
5707 !isInlineConstant(Src0, Desc.operands()[Src0Idx]) &&
5708 !isInlineConstant(Src1, Desc.operands()[Src1Idx]) &&
5709 !Src0.isIdenticalTo(Src1)) {
5710 ErrInfo = "SOP2/SOPC instruction requires too many immediate constants";
5711 return false;
5712 }
5713 }
5714
5715 if (isSOPK(MI)) {
5716 const auto *Op = getNamedOperand(MI, AMDGPU::OpName::simm16);
5717 if (Desc.isBranch()) {
5718 if (!Op->isMBB()) {
5719 ErrInfo = "invalid branch target for SOPK instruction";
5720 return false;
5721 }
5722 } else {
5723 uint64_t Imm = Op->getImm();
5724 if (sopkIsZext(Opcode)) {
5725 if (!isUInt<16>(Imm)) {
5726 ErrInfo = "invalid immediate for SOPK instruction";
5727 return false;
5728 }
5729 } else {
5730 if (!isInt<16>(Imm)) {
5731 ErrInfo = "invalid immediate for SOPK instruction";
5732 return false;
5733 }
5734 }
5735 }
5736 }
5737
5738 if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
5739 Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
5740 Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
5741 Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
5742 const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
5743 Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
5744
5745 const unsigned StaticNumOps =
5746 Desc.getNumOperands() + Desc.implicit_uses().size();
5747 const unsigned NumImplicitOps = IsDst ? 2 : 1;
5748
5749 // Require additional implicit operands. This allows a fixup done by the
5750 // post RA scheduler where the main implicit operand is killed and
5751 // implicit-defs are added for sub-registers that remain live after this
5752 // instruction.
5753 if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
5754 ErrInfo = "missing implicit register operands";
5755 return false;
5756 }
5757
5758 const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
5759 if (IsDst) {
5760 if (!Dst->isUse()) {
5761 ErrInfo = "v_movreld_b32 vdst should be a use operand";
5762 return false;
5763 }
5764
5765 unsigned UseOpIdx;
5766 if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
5767 UseOpIdx != StaticNumOps + 1) {
5768 ErrInfo = "movrel implicit operands should be tied";
5769 return false;
5770 }
5771 }
5772
5773 const MachineOperand &Src0 = MI.getOperand(Src0Idx);
5774 const MachineOperand &ImpUse
5775 = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
5776 if (!ImpUse.isReg() || !ImpUse.isUse() ||
5777 !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
5778 ErrInfo = "src0 should be subreg of implicit vector use";
5779 return false;
5780 }
5781 }
5782
5783 // Make sure we aren't losing exec uses in the td files. This mostly requires
5784 // being careful when using let Uses to try to add other use registers.
5785 if (shouldReadExec(MI)) {
5786 if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
5787 ErrInfo = "VALU instruction does not implicitly read exec mask";
5788 return false;
5789 }
5790 }
5791
5792 if (isSMRD(MI)) {
5793 if (MI.mayStore() &&
5794 ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS) {
5795 // The register offset form of scalar stores may only use m0 as the
5796 // soffset register.
5797 const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soffset);
5798 if (Soff && Soff->getReg() != AMDGPU::M0) {
5799 ErrInfo = "scalar stores must use m0 as offset register";
5800 return false;
5801 }
5802 }
5803 }
5804
5805 if (isFLAT(MI) && !ST.hasFlatInstOffsets()) {
5806 const MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
5807 if (Offset->getImm() != 0) {
5808 ErrInfo = "subtarget does not support offsets in flat instructions";
5809 return false;
5810 }
5811 }
5812
5813 if (isDS(MI) && !ST.hasGDS()) {
5814 const MachineOperand *GDSOp = getNamedOperand(MI, AMDGPU::OpName::gds);
5815 if (GDSOp && GDSOp->getImm() != 0) {
5816 ErrInfo = "GDS is not supported on this subtarget";
5817 return false;
5818 }
5819 }
5820
5821 if (isImage(MI)) {
5822 const MachineOperand *DimOp = getNamedOperand(MI, AMDGPU::OpName::dim);
5823 if (DimOp) {
5824 int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opcode,
5825 AMDGPU::OpName::vaddr0);
5826 AMDGPU::OpName RSrcOpName =
5827 isMIMG(MI) ? AMDGPU::OpName::srsrc : AMDGPU::OpName::rsrc;
5828 int RsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, RSrcOpName);
5829 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opcode);
5830 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5831 AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
5832 const AMDGPU::MIMGDimInfo *Dim =
5834
5835 if (!Dim) {
5836 ErrInfo = "dim is out of range";
5837 return false;
5838 }
5839
5840 bool IsA16 = false;
5841 if (ST.hasR128A16()) {
5842 const MachineOperand *R128A16 = getNamedOperand(MI, AMDGPU::OpName::r128);
5843 IsA16 = R128A16->getImm() != 0;
5844 } else if (ST.hasA16()) {
5845 const MachineOperand *A16 = getNamedOperand(MI, AMDGPU::OpName::a16);
5846 IsA16 = A16->getImm() != 0;
5847 }
5848
5849 bool IsNSA = RsrcIdx - VAddr0Idx > 1;
5850
5851 unsigned AddrWords =
5852 AMDGPU::getAddrSizeMIMGOp(BaseOpcode, Dim, IsA16, ST.hasG16());
5853
5854 unsigned VAddrWords;
5855 if (IsNSA) {
5856 VAddrWords = RsrcIdx - VAddr0Idx;
5857 if (ST.hasPartialNSAEncoding() &&
5858 AddrWords > ST.getNSAMaxSize(isVSAMPLE(MI))) {
5859 unsigned LastVAddrIdx = RsrcIdx - 1;
5860 VAddrWords += getOpSize(MI, LastVAddrIdx) / 4 - 1;
5861 }
5862 } else {
5863 VAddrWords = getOpSize(MI, VAddr0Idx) / 4;
5864 if (AddrWords > 12)
5865 AddrWords = 16;
5866 }
5867
5868 if (VAddrWords != AddrWords) {
5869 LLVM_DEBUG(dbgs() << "bad vaddr size, expected " << AddrWords
5870 << " but got " << VAddrWords << "\n");
5871 ErrInfo = "bad vaddr size";
5872 return false;
5873 }
5874 }
5875 }
5876
5877 const MachineOperand *DppCt = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
5878 if (DppCt) {
5879 using namespace AMDGPU::DPP;
5880
5881 unsigned DC = DppCt->getImm();
5882 if (DC == DppCtrl::DPP_UNUSED1 || DC == DppCtrl::DPP_UNUSED2 ||
5883 DC == DppCtrl::DPP_UNUSED3 || DC > DppCtrl::DPP_LAST ||
5884 (DC >= DppCtrl::DPP_UNUSED4_FIRST && DC <= DppCtrl::DPP_UNUSED4_LAST) ||
5885 (DC >= DppCtrl::DPP_UNUSED5_FIRST && DC <= DppCtrl::DPP_UNUSED5_LAST) ||
5886 (DC >= DppCtrl::DPP_UNUSED6_FIRST && DC <= DppCtrl::DPP_UNUSED6_LAST) ||
5887 (DC >= DppCtrl::DPP_UNUSED7_FIRST && DC <= DppCtrl::DPP_UNUSED7_LAST) ||
5888 (DC >= DppCtrl::DPP_UNUSED8_FIRST && DC <= DppCtrl::DPP_UNUSED8_LAST)) {
5889 ErrInfo = "Invalid dpp_ctrl value";
5890 return false;
5891 }
5892 if (DC >= DppCtrl::WAVE_SHL1 && DC <= DppCtrl::WAVE_ROR1 &&
5893 !ST.hasDPPWavefrontShifts()) {
5894 ErrInfo = "Invalid dpp_ctrl value: "
5895 "wavefront shifts are not supported on GFX10+";
5896 return false;
5897 }
5898 if (DC >= DppCtrl::BCAST15 && DC <= DppCtrl::BCAST31 &&
5899 !ST.hasDPPBroadcasts()) {
5900 ErrInfo = "Invalid dpp_ctrl value: "
5901 "broadcasts are not supported on GFX10+";
5902 return false;
5903 }
5904 if (DC >= DppCtrl::ROW_SHARE_FIRST && DC <= DppCtrl::ROW_XMASK_LAST &&
5905 ST.getGeneration() < AMDGPUSubtarget::GFX10) {
5906 if (DC >= DppCtrl::ROW_NEWBCAST_FIRST &&
5907 DC <= DppCtrl::ROW_NEWBCAST_LAST &&
5908 !ST.hasGFX90AInsts()) {
5909 ErrInfo = "Invalid dpp_ctrl value: "
5910 "row_newbroadcast/row_share is not supported before "
5911 "GFX90A/GFX10";
5912 return false;
5913 }
5914 if (DC > DppCtrl::ROW_NEWBCAST_LAST || !ST.hasGFX90AInsts()) {
5915 ErrInfo = "Invalid dpp_ctrl value: "
5916 "row_share and row_xmask are not supported before GFX10";
5917 return false;
5918 }
5919 }
5920
5921 if (Opcode != AMDGPU::V_MOV_B64_DPP_PSEUDO &&
5923 AMDGPU::isDPALU_DPP(Desc, *this, ST)) {
5924 ErrInfo = "Invalid dpp_ctrl value: "
5925 "DP ALU dpp only support row_newbcast";
5926 return false;
5927 }
5928 }
5929
5930 if ((MI.mayStore() || MI.mayLoad()) && !isVGPRSpill(MI)) {
5931 const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
5932 AMDGPU::OpName DataName =
5933 isDS(Opcode) ? AMDGPU::OpName::data0 : AMDGPU::OpName::vdata;
5934 const MachineOperand *Data = getNamedOperand(MI, DataName);
5935 const MachineOperand *Data2 = getNamedOperand(MI, AMDGPU::OpName::data1);
5936 if (Data && !Data->isReg())
5937 Data = nullptr;
5938
5939 if (ST.hasGFX90AInsts()) {
5940 if (Dst && Data && !Dst->isTied() && !Data->isTied() &&
5941 (RI.isAGPR(MRI, Dst->getReg()) != RI.isAGPR(MRI, Data->getReg()))) {
5942 ErrInfo = "Invalid register class: "
5943 "vdata and vdst should be both VGPR or AGPR";
5944 return false;
5945 }
5946 if (Data && Data2 &&
5947 (RI.isAGPR(MRI, Data->getReg()) != RI.isAGPR(MRI, Data2->getReg()))) {
5948 ErrInfo = "Invalid register class: "
5949 "both data operands should be VGPR or AGPR";
5950 return false;
5951 }
5952 } else {
5953 if ((Dst && RI.isAGPR(MRI, Dst->getReg())) ||
5954 (Data && RI.isAGPR(MRI, Data->getReg())) ||
5955 (Data2 && RI.isAGPR(MRI, Data2->getReg()))) {
5956 ErrInfo = "Invalid register class: "
5957 "agpr loads and stores not supported on this GPU";
5958 return false;
5959 }
5960 }
5961 }
5962
5963 if (ST.needsAlignedVGPRs()) {
5964 const auto isAlignedReg = [&MI, &MRI, this](AMDGPU::OpName OpName) -> bool {
5966 if (!Op)
5967 return true;
5968 Register Reg = Op->getReg();
5969 if (Reg.isPhysical())
5970 return !(RI.getHWRegIndex(Reg) & 1);
5971 const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
5972 return RI.getRegSizeInBits(RC) > 32 && RI.isProperlyAlignedRC(RC) &&
5973 !(RI.getChannelFromSubReg(Op->getSubReg()) & 1);
5974 };
5975
5976 if (Opcode == AMDGPU::DS_GWS_INIT || Opcode == AMDGPU::DS_GWS_SEMA_BR ||
5977 Opcode == AMDGPU::DS_GWS_BARRIER) {
5978
5979 if (!isAlignedReg(AMDGPU::OpName::data0)) {
5980 ErrInfo = "Subtarget requires even aligned vector registers "
5981 "for DS_GWS instructions";
5982 return false;
5983 }
5984 }
5985
5986 if (isMIMG(MI)) {
5987 if (!isAlignedReg(AMDGPU::OpName::vaddr)) {
5988 ErrInfo = "Subtarget requires even aligned vector registers "
5989 "for vaddr operand of image instructions";
5990 return false;
5991 }
5992 }
5993 }
5994
5995 if (Opcode == AMDGPU::V_ACCVGPR_WRITE_B32_e64 && !ST.hasGFX90AInsts()) {
5996 const MachineOperand *Src = getNamedOperand(MI, AMDGPU::OpName::src0);
5997 if (Src->isReg() && RI.isSGPRReg(MRI, Src->getReg())) {
5998 ErrInfo = "Invalid register class: "
5999 "v_accvgpr_write with an SGPR is not supported on this GPU";
6000 return false;
6001 }
6002 }
6003
6004 if (Desc.getOpcode() == AMDGPU::G_AMDGPU_WAVE_ADDRESS) {
6005 const MachineOperand &SrcOp = MI.getOperand(1);
6006 if (!SrcOp.isReg() || SrcOp.getReg().isVirtual()) {
6007 ErrInfo = "pseudo expects only physical SGPRs";
6008 return false;
6009 }
6010 }
6011
6012 if (const MachineOperand *CPol = getNamedOperand(MI, AMDGPU::OpName::cpol)) {
6013 if (CPol->getImm() & AMDGPU::CPol::SCAL) {
6014 if (!ST.hasScaleOffset()) {
6015 ErrInfo = "Subtarget does not support offset scaling";
6016 return false;
6017 }
6018 if (!AMDGPU::supportsScaleOffset(*this, MI.getOpcode())) {
6019 ErrInfo = "Instruction does not support offset scaling";
6020 return false;
6021 }
6022 }
6023 }
6024
6025 // See SIInstrInfo::isLegalGFX12PlusPackedMathFP32or64BitOperand for more
6026 // information.
6028 for (unsigned I = 0; I < 3; ++I) {
6030 return false;
6031 }
6032 }
6033
6034 if (ST.hasFlatScratchHiInB64InstHazard() && isSALU(MI) &&
6035 MI.readsRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE_HI, nullptr)) {
6036 const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::sdst);
6037 if ((Dst && RI.getRegClassForReg(MRI, Dst->getReg()) ==
6038 &AMDGPU::SReg_64RegClass) ||
6039 Opcode == AMDGPU::S_BITCMP0_B64 || Opcode == AMDGPU::S_BITCMP1_B64) {
6040 ErrInfo = "Instruction cannot read flat_scratch_base_hi";
6041 return false;
6042 }
6043 }
6044
6045 return true;
6046}
6047
6049 if (MI.getOpcode() == AMDGPU::S_MOV_B32) {
6050 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
6051 return MI.getOperand(1).isReg() || RI.isAGPR(MRI, MI.getOperand(0).getReg())
6052 ? AMDGPU::COPY
6053 : AMDGPU::V_MOV_B32_e32;
6054 }
6055 return getVALUOp(MI.getOpcode());
6056}
6057
6058// It is more readable to list mapped opcodes on the same line.
6059// clang-format off
6060
6061unsigned SIInstrInfo::getVALUOp(unsigned Opc) const {
6062 switch (Opc) {
6063 default: return AMDGPU::INSTRUCTION_LIST_END;
6064 case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
6065 case AMDGPU::COPY: return AMDGPU::COPY;
6066 case AMDGPU::PHI: return AMDGPU::PHI;
6067 case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
6068 case AMDGPU::WQM: return AMDGPU::WQM;
6069 case AMDGPU::SOFT_WQM: return AMDGPU::SOFT_WQM;
6070 case AMDGPU::STRICT_WWM: return AMDGPU::STRICT_WWM;
6071 case AMDGPU::STRICT_WQM: return AMDGPU::STRICT_WQM;
6072 case AMDGPU::S_ADD_I32:
6073 return ST.hasAddNoCarryInsts() ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_CO_U32_e32;
6074 case AMDGPU::S_ADDC_U32:
6075 return AMDGPU::V_ADDC_U32_e32;
6076 case AMDGPU::S_SUB_I32:
6077 return ST.hasAddNoCarryInsts() ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_SUB_CO_U32_e32;
6078 // FIXME: These are not consistently handled, and selected when the carry is
6079 // used.
6080 case AMDGPU::S_ADD_U32:
6081 return AMDGPU::V_ADD_CO_U32_e32;
6082 case AMDGPU::S_SUB_U32:
6083 return AMDGPU::V_SUB_CO_U32_e32;
6084 case AMDGPU::S_ADD_U64_PSEUDO:
6085 return AMDGPU::V_ADD_U64_PSEUDO;
6086 case AMDGPU::S_SUB_U64_PSEUDO:
6087 return AMDGPU::V_SUB_U64_PSEUDO;
6088 case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
6089 case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_U32_e64;
6090 case AMDGPU::S_MUL_HI_U32: return AMDGPU::V_MUL_HI_U32_e64;
6091 case AMDGPU::S_MUL_HI_I32: return AMDGPU::V_MUL_HI_I32_e64;
6092 case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
6093 case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
6094 case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
6095 case AMDGPU::S_XNOR_B32:
6096 return ST.hasDLInsts() ? AMDGPU::V_XNOR_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
6097 case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
6098 case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
6099 case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
6100 case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
6101 case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
6102 case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64_e64;
6103 case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
6104 case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64_e64;
6105 case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
6106 case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64_e64;
6107 case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32_e64;
6108 case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32_e64;
6109 case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32_e64;
6110 case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32_e64;
6111 case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
6112 case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
6113 case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
6114 case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
6115 case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e64;
6116 case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e64;
6117 case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e64;
6118 case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e64;
6119 case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e64;
6120 case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e64;
6121 case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e64;
6122 case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e64;
6123 case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e64;
6124 case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e64;
6125 case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e64;
6126 case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e64;
6127 case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e64;
6128 case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e64;
6129 case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
6130 case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
6131 case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
6132 case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
6133 case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
6134 case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
6135 case AMDGPU::S_CVT_F32_I32: return AMDGPU::V_CVT_F32_I32_e64;
6136 case AMDGPU::S_CVT_F32_U32: return AMDGPU::V_CVT_F32_U32_e64;
6137 case AMDGPU::S_CVT_I32_F32: return AMDGPU::V_CVT_I32_F32_e64;
6138 case AMDGPU::S_CVT_U32_F32: return AMDGPU::V_CVT_U32_F32_e64;
6139 case AMDGPU::S_CVT_F32_F16:
6140 case AMDGPU::S_CVT_HI_F32_F16:
6141 return ST.useRealTrue16Insts() ? AMDGPU::V_CVT_F32_F16_t16_e64
6142 : AMDGPU::V_CVT_F32_F16_fake16_e64;
6143 case AMDGPU::S_CVT_F16_F32:
6144 return ST.useRealTrue16Insts() ? AMDGPU::V_CVT_F16_F32_t16_e64
6145 : AMDGPU::V_CVT_F16_F32_fake16_e64;
6146 case AMDGPU::S_CEIL_F32: return AMDGPU::V_CEIL_F32_e64;
6147 case AMDGPU::S_FLOOR_F32: return AMDGPU::V_FLOOR_F32_e64;
6148 case AMDGPU::S_TRUNC_F32: return AMDGPU::V_TRUNC_F32_e64;
6149 case AMDGPU::S_RNDNE_F32: return AMDGPU::V_RNDNE_F32_e64;
6150 case AMDGPU::S_CEIL_F16:
6151 return ST.useRealTrue16Insts() ? AMDGPU::V_CEIL_F16_t16_e64
6152 : AMDGPU::V_CEIL_F16_fake16_e64;
6153 case AMDGPU::S_FLOOR_F16:
6154 return ST.useRealTrue16Insts() ? AMDGPU::V_FLOOR_F16_t16_e64
6155 : AMDGPU::V_FLOOR_F16_fake16_e64;
6156 case AMDGPU::S_TRUNC_F16:
6157 return ST.useRealTrue16Insts() ? AMDGPU::V_TRUNC_F16_t16_e64
6158 : AMDGPU::V_TRUNC_F16_fake16_e64;
6159 case AMDGPU::S_RNDNE_F16:
6160 return ST.useRealTrue16Insts() ? AMDGPU::V_RNDNE_F16_t16_e64
6161 : AMDGPU::V_RNDNE_F16_fake16_e64;
6162 case AMDGPU::S_ADD_F32: return AMDGPU::V_ADD_F32_e64;
6163 case AMDGPU::S_SUB_F32: return AMDGPU::V_SUB_F32_e64;
6164 case AMDGPU::S_MIN_F32: return AMDGPU::V_MIN_F32_e64;
6165 case AMDGPU::S_MAX_F32: return AMDGPU::V_MAX_F32_e64;
6166 case AMDGPU::S_MINIMUM_F32: return AMDGPU::V_MINIMUM_F32_e64;
6167 case AMDGPU::S_MAXIMUM_F32: return AMDGPU::V_MAXIMUM_F32_e64;
6168 case AMDGPU::S_MUL_F32: return AMDGPU::V_MUL_F32_e64;
6169 case AMDGPU::S_ADD_F16:
6170 return ST.useRealTrue16Insts() ? AMDGPU::V_ADD_F16_t16_e64
6171 : AMDGPU::V_ADD_F16_fake16_e64;
6172 case AMDGPU::S_SUB_F16:
6173 return ST.useRealTrue16Insts() ? AMDGPU::V_SUB_F16_t16_e64
6174 : AMDGPU::V_SUB_F16_fake16_e64;
6175 case AMDGPU::S_MIN_F16:
6176 return ST.useRealTrue16Insts() ? AMDGPU::V_MIN_F16_t16_e64
6177 : AMDGPU::V_MIN_F16_fake16_e64;
6178 case AMDGPU::S_MAX_F16:
6179 return ST.useRealTrue16Insts() ? AMDGPU::V_MAX_F16_t16_e64
6180 : AMDGPU::V_MAX_F16_fake16_e64;
6181 case AMDGPU::S_MINIMUM_F16:
6182 return ST.useRealTrue16Insts() ? AMDGPU::V_MINIMUM_F16_t16_e64
6183 : AMDGPU::V_MINIMUM_F16_fake16_e64;
6184 case AMDGPU::S_MAXIMUM_F16:
6185 return ST.useRealTrue16Insts() ? AMDGPU::V_MAXIMUM_F16_t16_e64
6186 : AMDGPU::V_MAXIMUM_F16_fake16_e64;
6187 case AMDGPU::S_MUL_F16:
6188 return ST.useRealTrue16Insts() ? AMDGPU::V_MUL_F16_t16_e64
6189 : AMDGPU::V_MUL_F16_fake16_e64;
6190 case AMDGPU::S_CVT_PK_RTZ_F16_F32: return AMDGPU::V_CVT_PKRTZ_F16_F32_e64;
6191 case AMDGPU::S_FMAC_F32: return AMDGPU::V_FMAC_F32_e64;
6192 case AMDGPU::S_FMAC_F16:
6193 return ST.useRealTrue16Insts() ? AMDGPU::V_FMAC_F16_t16_e64
6194 : AMDGPU::V_FMAC_F16_fake16_e64;
6195 case AMDGPU::S_FMAMK_F32: return AMDGPU::V_FMAMK_F32;
6196 case AMDGPU::S_FMAAK_F32: return AMDGPU::V_FMAAK_F32;
6197 case AMDGPU::S_CMP_LT_F32: return AMDGPU::V_CMP_LT_F32_e64;
6198 case AMDGPU::S_CMP_EQ_F32: return AMDGPU::V_CMP_EQ_F32_e64;
6199 case AMDGPU::S_CMP_LE_F32: return AMDGPU::V_CMP_LE_F32_e64;
6200 case AMDGPU::S_CMP_GT_F32: return AMDGPU::V_CMP_GT_F32_e64;
6201 case AMDGPU::S_CMP_LG_F32: return AMDGPU::V_CMP_LG_F32_e64;
6202 case AMDGPU::S_CMP_GE_F32: return AMDGPU::V_CMP_GE_F32_e64;
6203 case AMDGPU::S_CMP_O_F32: return AMDGPU::V_CMP_O_F32_e64;
6204 case AMDGPU::S_CMP_U_F32: return AMDGPU::V_CMP_U_F32_e64;
6205 case AMDGPU::S_CMP_NGE_F32: return AMDGPU::V_CMP_NGE_F32_e64;
6206 case AMDGPU::S_CMP_NLG_F32: return AMDGPU::V_CMP_NLG_F32_e64;
6207 case AMDGPU::S_CMP_NGT_F32: return AMDGPU::V_CMP_NGT_F32_e64;
6208 case AMDGPU::S_CMP_NLE_F32: return AMDGPU::V_CMP_NLE_F32_e64;
6209 case AMDGPU::S_CMP_NEQ_F32: return AMDGPU::V_CMP_NEQ_F32_e64;
6210 case AMDGPU::S_CMP_NLT_F32: return AMDGPU::V_CMP_NLT_F32_e64;
6211 case AMDGPU::S_CMP_LT_F16:
6212 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_LT_F16_t16_e64
6213 : AMDGPU::V_CMP_LT_F16_fake16_e64;
6214 case AMDGPU::S_CMP_EQ_F16:
6215 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_EQ_F16_t16_e64
6216 : AMDGPU::V_CMP_EQ_F16_fake16_e64;
6217 case AMDGPU::S_CMP_LE_F16:
6218 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_LE_F16_t16_e64
6219 : AMDGPU::V_CMP_LE_F16_fake16_e64;
6220 case AMDGPU::S_CMP_GT_F16:
6221 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_GT_F16_t16_e64
6222 : AMDGPU::V_CMP_GT_F16_fake16_e64;
6223 case AMDGPU::S_CMP_LG_F16:
6224 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_LG_F16_t16_e64
6225 : AMDGPU::V_CMP_LG_F16_fake16_e64;
6226 case AMDGPU::S_CMP_GE_F16:
6227 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_GE_F16_t16_e64
6228 : AMDGPU::V_CMP_GE_F16_fake16_e64;
6229 case AMDGPU::S_CMP_O_F16:
6230 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_O_F16_t16_e64
6231 : AMDGPU::V_CMP_O_F16_fake16_e64;
6232 case AMDGPU::S_CMP_U_F16:
6233 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_U_F16_t16_e64
6234 : AMDGPU::V_CMP_U_F16_fake16_e64;
6235 case AMDGPU::S_CMP_NGE_F16:
6236 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NGE_F16_t16_e64
6237 : AMDGPU::V_CMP_NGE_F16_fake16_e64;
6238 case AMDGPU::S_CMP_NLG_F16:
6239 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NLG_F16_t16_e64
6240 : AMDGPU::V_CMP_NLG_F16_fake16_e64;
6241 case AMDGPU::S_CMP_NGT_F16:
6242 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NGT_F16_t16_e64
6243 : AMDGPU::V_CMP_NGT_F16_fake16_e64;
6244 case AMDGPU::S_CMP_NLE_F16:
6245 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NLE_F16_t16_e64
6246 : AMDGPU::V_CMP_NLE_F16_fake16_e64;
6247 case AMDGPU::S_CMP_NEQ_F16:
6248 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NEQ_F16_t16_e64
6249 : AMDGPU::V_CMP_NEQ_F16_fake16_e64;
6250 case AMDGPU::S_CMP_NLT_F16:
6251 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NLT_F16_t16_e64
6252 : AMDGPU::V_CMP_NLT_F16_fake16_e64;
6253 case AMDGPU::V_S_EXP_F32_e64: return AMDGPU::V_EXP_F32_e64;
6254 case AMDGPU::V_S_EXP_F16_e64:
6255 return ST.useRealTrue16Insts() ? AMDGPU::V_EXP_F16_t16_e64
6256 : AMDGPU::V_EXP_F16_fake16_e64;
6257 case AMDGPU::V_S_LOG_F32_e64: return AMDGPU::V_LOG_F32_e64;
6258 case AMDGPU::V_S_LOG_F16_e64:
6259 return ST.useRealTrue16Insts() ? AMDGPU::V_LOG_F16_t16_e64
6260 : AMDGPU::V_LOG_F16_fake16_e64;
6261 case AMDGPU::V_S_RCP_F32_e64: return AMDGPU::V_RCP_F32_e64;
6262 case AMDGPU::V_S_RCP_F16_e64:
6263 return ST.useRealTrue16Insts() ? AMDGPU::V_RCP_F16_t16_e64
6264 : AMDGPU::V_RCP_F16_fake16_e64;
6265 case AMDGPU::V_S_RSQ_F32_e64: return AMDGPU::V_RSQ_F32_e64;
6266 case AMDGPU::V_S_RSQ_F16_e64:
6267 return ST.useRealTrue16Insts() ? AMDGPU::V_RSQ_F16_t16_e64
6268 : AMDGPU::V_RSQ_F16_fake16_e64;
6269 case AMDGPU::V_S_SQRT_F32_e64: return AMDGPU::V_SQRT_F32_e64;
6270 case AMDGPU::V_S_SQRT_F16_e64:
6271 return ST.useRealTrue16Insts() ? AMDGPU::V_SQRT_F16_t16_e64
6272 : AMDGPU::V_SQRT_F16_fake16_e64;
6273 }
6275 "Unexpected scalar opcode without corresponding vector one!");
6276}
6277
6278// clang-format on
6279
6283 const DebugLoc &DL, Register Reg,
6284 bool IsSCCLive,
6285 SlotIndexes *Indexes) const {
6286 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6287 const SIInstrInfo *TII = ST.getInstrInfo();
6289 if (IsSCCLive) {
6290 // Insert two move instructions, one to save the original value of EXEC and
6291 // the other to turn on all bits in EXEC. This is required as we can't use
6292 // the single instruction S_OR_SAVEEXEC that clobbers SCC.
6293 auto StoreExecMI = BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), Reg)
6295 auto FlipExecMI =
6296 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg).addImm(-1);
6297 if (Indexes) {
6298 Indexes->insertMachineInstrInMaps(*StoreExecMI);
6299 Indexes->insertMachineInstrInMaps(*FlipExecMI);
6300 }
6301 } else {
6302 auto SaveExec =
6303 BuildMI(MBB, MBBI, DL, TII->get(LMC.OrSaveExecOpc), Reg).addImm(-1);
6304 SaveExec->getOperand(3).setIsDead(); // Mark SCC as dead.
6305 if (Indexes)
6306 Indexes->insertMachineInstrInMaps(*SaveExec);
6307 }
6308}
6309
6312 const DebugLoc &DL, Register Reg,
6313 SlotIndexes *Indexes) const {
6315 auto ExecRestoreMI = BuildMI(MBB, MBBI, DL, get(LMC.MovOpc), LMC.ExecReg)
6316 .addReg(Reg, RegState::Kill);
6317 if (Indexes)
6318 Indexes->insertMachineInstrInMaps(*ExecRestoreMI);
6319}
6320
6324 "Not a whole wave func");
6325 MachineBasicBlock &MBB = *MF.begin();
6326 for (MachineInstr &MI : MBB)
6327 if (MI.getOpcode() == AMDGPU::SI_WHOLE_WAVE_FUNC_SETUP ||
6328 MI.getOpcode() == AMDGPU::G_AMDGPU_WHOLE_WAVE_FUNC_SETUP)
6329 return &MI;
6330
6331 llvm_unreachable("Couldn't find SI_SETUP_WHOLE_WAVE_FUNC instruction");
6332}
6333
6335 unsigned OpNo) const {
6336 const MCInstrDesc &Desc = get(MI.getOpcode());
6337 if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
6338 Desc.operands()[OpNo].RegClass == -1) {
6339 Register Reg = MI.getOperand(OpNo).getReg();
6340
6341 if (Reg.isVirtual()) {
6342 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
6343 return MRI.getRegClass(Reg);
6344 }
6345 return RI.getPhysRegBaseClass(Reg);
6346 }
6347
6348 int16_t RegClass = getOpRegClassID(Desc.operands()[OpNo]);
6349 return RegClass < 0 ? nullptr : RI.getRegClass(RegClass);
6350}
6351
6354 MachineBasicBlock *MBB = MI.getParent();
6355 MachineOperand &MO = MI.getOperand(OpIdx);
6356 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
6357 unsigned RCID = getOpRegClassID(get(MI.getOpcode()).operands()[OpIdx]);
6358 const TargetRegisterClass *RC = RI.getRegClass(RCID);
6359 unsigned Size = RI.getRegSizeInBits(*RC);
6360 unsigned Opcode = (Size == 64) ? AMDGPU::V_MOV_B64_PSEUDO
6361 : Size == 16 ? AMDGPU::V_MOV_B16_t16_e64
6362 : AMDGPU::V_MOV_B32_e32;
6363 if (MO.isReg())
6364 Opcode = AMDGPU::COPY;
6365 else if (RI.isSGPRClass(RC))
6366 Opcode = (Size == 64) ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
6367
6368 const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
6369 Register Reg = MRI.createVirtualRegister(VRC);
6370 DebugLoc DL = MBB->findDebugLoc(I);
6371 BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).add(MO);
6372 MO.ChangeToRegister(Reg, false);
6373}
6374
6377 const MachineOperand &SuperReg, const TargetRegisterClass *SuperRC,
6378 unsigned SubIdx, const TargetRegisterClass *SubRC) const {
6379 if (!SuperReg.getReg().isVirtual())
6380 return RI.getSubReg(SuperReg.getReg(), SubIdx);
6381
6382 MachineBasicBlock *MBB = MI->getParent();
6383 const DebugLoc &DL = MI->getDebugLoc();
6384 Register SubReg = MRI.createVirtualRegister(SubRC);
6385
6386 unsigned NewSubIdx = RI.composeSubRegIndices(SuperReg.getSubReg(), SubIdx);
6387 BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
6388 .addReg(SuperReg.getReg(), {}, NewSubIdx);
6389 return SubReg;
6390}
6391
6394 const MachineOperand &Op, const TargetRegisterClass *SuperRC,
6395 unsigned SubIdx, const TargetRegisterClass *SubRC) const {
6396 if (Op.isImm()) {
6397 if (SubIdx == AMDGPU::sub0)
6398 return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
6399 if (SubIdx == AMDGPU::sub1)
6400 return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
6401
6402 llvm_unreachable("Unhandled register index for immediate");
6403 }
6404
6405 unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
6406 SubIdx, SubRC);
6407 return MachineOperand::CreateReg(SubReg, false);
6408}
6409
6410// Change the order of operands from (0, 1, 2) to (0, 2, 1)
6411void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
6412 assert(Inst.getNumExplicitOperands() == 3);
6413 MachineOperand Op1 = Inst.getOperand(1);
6414 Inst.removeOperand(1);
6415 Inst.addOperand(Op1);
6416}
6417
6419 const MCOperandInfo &OpInfo,
6420 const MachineOperand &MO) const {
6421 if (!MO.isReg())
6422 return false;
6423
6424 Register Reg = MO.getReg();
6425
6426 const TargetRegisterClass *DRC = RI.getRegClass(getOpRegClassID(OpInfo));
6427 if (Reg.isPhysical())
6428 return DRC->contains(Reg);
6429
6430 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
6431
6432 if (MO.getSubReg()) {
6433 const MachineFunction *MF = MO.getParent()->getMF();
6434 const TargetRegisterClass *SuperRC = RI.getLargestLegalSuperClass(RC, *MF);
6435 if (!SuperRC)
6436 return false;
6437 return RI.getMatchingSuperRegClass(SuperRC, DRC, MO.getSubReg()) != nullptr;
6438 }
6439
6440 return RI.getCommonSubClass(DRC, RC) != nullptr;
6441}
6442
6444 const MachineOperand &MO) const {
6445 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
6446 const MCOperandInfo OpInfo = MI.getDesc().operands()[OpIdx];
6447 unsigned Opc = MI.getOpcode();
6448
6449 // See SIInstrInfo::isLegalGFX12PlusPackedMathFP32or64BitOperand for more
6450 // information.
6451 if (AMDGPU::isPackedFP32or64BitInst(MI.getOpcode()) &&
6452 AMDGPU::isGFX12Plus(ST) && MO.isReg() && RI.isSGPRReg(MRI, MO.getReg())) {
6453 constexpr AMDGPU::OpName OpNames[] = {
6454 AMDGPU::OpName::src0, AMDGPU::OpName::src1, AMDGPU::OpName::src2};
6455
6456 for (auto [I, OpName] : enumerate(OpNames)) {
6457 int SrcIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpNames[I]);
6458 if (static_cast<unsigned>(SrcIdx) == OpIdx &&
6460 return false;
6461 }
6462 }
6463
6464 if (!isLegalRegOperand(MRI, OpInfo, MO))
6465 return false;
6466
6467 // check Accumulate GPR operand
6468 bool IsAGPR = RI.isAGPR(MRI, MO.getReg());
6469 if (IsAGPR && !ST.hasMAIInsts())
6470 return false;
6471 if (IsAGPR && (!ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
6472 (MI.mayLoad() || MI.mayStore() || isDS(Opc) || isMIMG(Opc)))
6473 return false;
6474 // Atomics should have both vdst and vdata either vgpr or agpr.
6475 const int VDstIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
6476 const int DataIdx = AMDGPU::getNamedOperandIdx(
6477 Opc, isDS(Opc) ? AMDGPU::OpName::data0 : AMDGPU::OpName::vdata);
6478 if ((int)OpIdx == VDstIdx && DataIdx != -1 &&
6479 MI.getOperand(DataIdx).isReg() &&
6480 RI.isAGPR(MRI, MI.getOperand(DataIdx).getReg()) != IsAGPR)
6481 return false;
6482 if ((int)OpIdx == DataIdx) {
6483 if (VDstIdx != -1 &&
6484 RI.isAGPR(MRI, MI.getOperand(VDstIdx).getReg()) != IsAGPR)
6485 return false;
6486 // DS instructions with 2 src operands also must have tied RC.
6487 const int Data1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data1);
6488 if (Data1Idx != -1 && MI.getOperand(Data1Idx).isReg() &&
6489 RI.isAGPR(MRI, MI.getOperand(Data1Idx).getReg()) != IsAGPR)
6490 return false;
6491 }
6492
6493 // Check V_ACCVGPR_WRITE_B32_e64
6494 if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64 && !ST.hasGFX90AInsts() &&
6495 (int)OpIdx == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) &&
6496 RI.isSGPRReg(MRI, MO.getReg()))
6497 return false;
6498
6499 if (ST.hasFlatScratchHiInB64InstHazard() &&
6500 MO.getReg() == AMDGPU::SRC_FLAT_SCRATCH_BASE_HI && isSALU(MI)) {
6501 if (const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::sdst)) {
6502 if (AMDGPU::getRegBitWidth(*RI.getRegClassForReg(MRI, Dst->getReg())) ==
6503 64)
6504 return false;
6505 }
6506 if (Opc == AMDGPU::S_BITCMP0_B64 || Opc == AMDGPU::S_BITCMP1_B64)
6507 return false;
6508 }
6509 if (!ST.hasDPPSrc1SGPR() && isDPP(MI) && RI.isSGPRReg(MRI, MO.getReg()) &&
6510 (int)OpIdx == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1))
6511 return false;
6512
6513 return true;
6514}
6515
6517 const MCOperandInfo &OpInfo,
6518 const MachineOperand &MO) const {
6519 if (MO.isReg())
6520 return isLegalRegOperand(MRI, OpInfo, MO);
6521
6522 // Handle non-register types that are treated like immediates.
6523 assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
6524 return true;
6525}
6526
6528 const MachineRegisterInfo &MRI, const MachineInstr &MI, unsigned SrcN,
6529 const MachineOperand *MO) const {
6530 constexpr unsigned NumOps = 3;
6531 constexpr AMDGPU::OpName OpNames[NumOps * 2] = {
6532 AMDGPU::OpName::src0, AMDGPU::OpName::src1,
6533 AMDGPU::OpName::src2, AMDGPU::OpName::src0_modifiers,
6534 AMDGPU::OpName::src1_modifiers, AMDGPU::OpName::src2_modifiers};
6535
6536 assert(SrcN < NumOps);
6537
6538 if (!MO) {
6539 int SrcIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpNames[SrcN]);
6540 if (SrcIdx == -1)
6541 return true;
6542 MO = &MI.getOperand(SrcIdx);
6543 }
6544
6545 if (!MO->isReg() || !RI.isSGPRReg(MRI, MO->getReg()))
6546 return true;
6547
6548 int ModsIdx =
6549 AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpNames[NumOps + SrcN]);
6550 if (ModsIdx == -1)
6551 return false;
6552
6553 unsigned Mods = MI.getOperand(ModsIdx).getImm();
6554 bool OpSel = Mods & SISrcMods::OP_SEL_0;
6555 bool OpSelHi = Mods & SISrcMods::OP_SEL_1;
6556
6557 return !OpSel && !OpSelHi;
6558}
6559
6561 const MachineOperand *MO) const {
6562 const MachineFunction &MF = *MI.getMF();
6563 const MachineRegisterInfo &MRI = MF.getRegInfo();
6564 const MCInstrDesc &InstDesc = MI.getDesc();
6565 const MCOperandInfo &OpInfo = InstDesc.operands()[OpIdx];
6566 int64_t RegClass = getOpRegClassID(OpInfo);
6567 const TargetRegisterClass *DefinedRC =
6568 RegClass != -1 ? RI.getRegClass(RegClass) : nullptr;
6569 if (!MO)
6570 MO = &MI.getOperand(OpIdx);
6571
6572 const bool IsInlineConst = !MO->isReg() && isInlineConstant(*MO, OpInfo);
6573
6574 if (isVALU(MI) && !IsInlineConst && usesConstantBus(MRI, *MO, OpInfo)) {
6575 const MachineOperand *UsedLiteral = nullptr;
6576
6577 int ConstantBusLimit = ST.getConstantBusLimit(MI.getOpcode());
6578 int LiteralLimit = !isVOP3(MI) || ST.hasVOP3Literal() ? 1 : 0;
6579
6580 // TODO: Be more permissive with frame indexes.
6581 if (!MO->isReg() && !isInlineConstant(*MO, OpInfo)) {
6582 if (!LiteralLimit--)
6583 return false;
6584
6585 UsedLiteral = MO;
6586 }
6587
6589 if (MO->isReg())
6590 SGPRsUsed.insert(RegSubRegPair(MO->getReg(), MO->getSubReg()));
6591
6592 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
6593 if (i == OpIdx)
6594 continue;
6595 const MachineOperand &Op = MI.getOperand(i);
6596 if (Op.isReg()) {
6597 if (Op.isUse()) {
6598 RegSubRegPair SGPR(Op.getReg(), Op.getSubReg());
6599 if (regUsesConstantBus(Op, MRI) && SGPRsUsed.insert(SGPR).second) {
6600 if (--ConstantBusLimit <= 0)
6601 return false;
6602 }
6603 }
6604 } else if (AMDGPU::isSISrcOperand(InstDesc.operands()[i]) &&
6605 !isInlineConstant(Op, InstDesc.operands()[i])) {
6606 // The same literal may be used multiple times.
6607 if (!UsedLiteral)
6608 UsedLiteral = &Op;
6609 else if (UsedLiteral->isIdenticalTo(Op))
6610 continue;
6611
6612 if (!LiteralLimit--)
6613 return false;
6614 if (--ConstantBusLimit <= 0)
6615 return false;
6616 }
6617 }
6618 } else if (!IsInlineConst && !MO->isReg() && isSALU(MI)) {
6619 // There can be at most one literal operand, but it can be repeated.
6620 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
6621 if (i == OpIdx)
6622 continue;
6623 const MachineOperand &Op = MI.getOperand(i);
6624 if (!Op.isReg() && !Op.isFI() && !Op.isRegMask() &&
6625 !isInlineConstant(Op, InstDesc.operands()[i]) &&
6626 !Op.isIdenticalTo(*MO))
6627 return false;
6628
6629 // Do not fold a non-inlineable and non-register operand into an
6630 // instruction that already has a frame index. The frame index handling
6631 // code could not handle well when a frame index co-exists with another
6632 // non-register operand, unless that operand is an inlineable immediate.
6633 if (Op.isFI())
6634 return false;
6635 }
6636 } else if (IsInlineConst && ST.hasNoF16PseudoScalarTransInlineConstants() &&
6637 isF16PseudoScalarTrans(MI.getOpcode())) {
6638 return false;
6639 }
6640
6641 if (MO->isReg()) {
6642 if (!DefinedRC)
6643 return OpInfo.OperandType == MCOI::OPERAND_UNKNOWN;
6644 return isLegalRegOperand(MI, OpIdx, *MO);
6645 }
6646
6647 if (MO->isImm()) {
6648 uint64_t Imm = MO->getImm();
6649 bool Is64BitFPOp = OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_FP64 ||
6650 OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_V2FP64;
6651 bool Is64BitOp = Is64BitFPOp ||
6652 OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_INT64 ||
6653 OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_V2INT32 ||
6654 OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_V2FP32;
6655 if (Is64BitOp &&
6656 !AMDGPU::isInlinableLiteral64(Imm, ST.hasInv2PiInlineImm())) {
6657 if (!AMDGPU::isValid32BitLiteral(Imm, Is64BitFPOp) &&
6658 (!ST.has64BitLiterals() || InstDesc.getSize() != 4))
6659 return false;
6660
6661 // FIXME: We can use sign extended 64-bit literals, but only for signed
6662 // operands. At the moment we do not know if an operand is signed.
6663 // Such operand will be encoded as its low 32 bits and then either
6664 // correctly sign extended or incorrectly zero extended by HW.
6665 // If 64-bit literals are supported and the literal will be encoded
6666 // as full 64 bit we still can use it.
6667 if (!Is64BitFPOp && (int32_t)Imm < 0 &&
6668 (!ST.has64BitLiterals() || AMDGPU::isValid32BitLiteral(Imm, false)))
6669 return false;
6670 }
6671 }
6672
6673 // Handle non-register types that are treated like immediates.
6674 assert(MO->isImm() || MO->isTargetIndex() || MO->isFI() || MO->isGlobal());
6675
6676 if (!DefinedRC) {
6677 // This operand expects an immediate.
6678 return true;
6679 }
6680
6681 return isImmOperandLegal(MI, OpIdx, *MO);
6682}
6683
6685 bool IsGFX950Only = ST.hasGFX950Insts();
6686 bool IsGFX940Only = ST.hasGFX940Insts();
6687
6688 if (!IsGFX950Only && !IsGFX940Only)
6689 return false;
6690
6691 if (!isVALU(MI))
6692 return false;
6693
6694 // V_COS, V_EXP, V_RCP, etc.
6695 if (isTRANS(MI))
6696 return true;
6697
6698 // DOT2, DOT2C, DOT4, etc.
6699 if (isDOT(MI))
6700 return true;
6701
6702 // MFMA, SMFMA
6703 if (isMFMA(MI))
6704 return true;
6705
6706 unsigned Opcode = MI.getOpcode();
6707 switch (Opcode) {
6708 case AMDGPU::V_CVT_PK_BF8_F32_e64:
6709 case AMDGPU::V_CVT_PK_FP8_F32_e64:
6710 case AMDGPU::V_MQSAD_PK_U16_U8_e64:
6711 case AMDGPU::V_MQSAD_U32_U8_e64:
6712 case AMDGPU::V_PK_ADD_F16:
6713 case AMDGPU::V_PK_ADD_F32:
6714 case AMDGPU::V_PK_ADD_I16:
6715 case AMDGPU::V_PK_ADD_U16:
6716 case AMDGPU::V_PK_ASHRREV_I16:
6717 case AMDGPU::V_PK_FMA_F16:
6718 case AMDGPU::V_PK_FMA_F32:
6719 case AMDGPU::V_PK_FMAC_F16_e32:
6720 case AMDGPU::V_PK_FMAC_F16_e64:
6721 case AMDGPU::V_PK_LSHLREV_B16:
6722 case AMDGPU::V_PK_LSHRREV_B16:
6723 case AMDGPU::V_PK_MAD_I16:
6724 case AMDGPU::V_PK_MAD_U16:
6725 case AMDGPU::V_PK_MAX_F16:
6726 case AMDGPU::V_PK_MAX_I16:
6727 case AMDGPU::V_PK_MAX_U16:
6728 case AMDGPU::V_PK_MIN_F16:
6729 case AMDGPU::V_PK_MIN_I16:
6730 case AMDGPU::V_PK_MIN_U16:
6731 case AMDGPU::V_PK_MOV_B32:
6732 case AMDGPU::V_PK_MUL_F16:
6733 case AMDGPU::V_PK_MUL_F32:
6734 case AMDGPU::V_PK_MUL_LO_U16:
6735 case AMDGPU::V_PK_SUB_I16:
6736 case AMDGPU::V_PK_SUB_U16:
6737 case AMDGPU::V_QSAD_PK_U16_U8_e64:
6738 return true;
6739 default:
6740 return false;
6741 }
6742}
6743
6745 MachineInstr &MI) const {
6746 unsigned Opc = MI.getOpcode();
6747 const MCInstrDesc &InstrDesc = get(Opc);
6748
6749 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
6750 MachineOperand &Src0 = MI.getOperand(Src0Idx);
6751
6752 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
6753 MachineOperand &Src1 = MI.getOperand(Src1Idx);
6754
6755 // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
6756 // we need to only have one constant bus use before GFX10.
6757 bool HasImplicitSGPR = findImplicitSGPRRead(MI);
6758 if (HasImplicitSGPR && ST.getConstantBusLimit(Opc) <= 1 && Src0.isReg() &&
6759 RI.isSGPRReg(MRI, Src0.getReg()))
6760 legalizeOpWithMove(MI, Src0Idx);
6761
6762 // Special case: V_WRITELANE_B32 accepts only immediate or SGPR operands for
6763 // both the value to write (src0) and lane select (src1). Fix up non-SGPR
6764 // src0/src1 with V_READFIRSTLANE.
6765 if (Opc == AMDGPU::V_WRITELANE_B32) {
6766 const DebugLoc &DL = MI.getDebugLoc();
6767 if (Src0.isReg() && RI.isVGPR(MRI, Src0.getReg())) {
6768 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6769 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
6770 .add(Src0);
6771 Src0.ChangeToRegister(Reg, false);
6772 }
6773 if (Src1.isReg() && RI.isVGPR(MRI, Src1.getReg())) {
6774 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6775 const DebugLoc &DL = MI.getDebugLoc();
6776 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
6777 .add(Src1);
6778 Src1.ChangeToRegister(Reg, false);
6779 }
6780 return;
6781 }
6782
6783 // Special case: V_FMAC_F32 and V_FMAC_F16 have src2.
6784 if (Opc == AMDGPU::V_FMAC_F32_e32 || Opc == AMDGPU::V_FMAC_F16_e32) {
6785 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
6786 if (!RI.isVGPR(MRI, MI.getOperand(Src2Idx).getReg()))
6787 legalizeOpWithMove(MI, Src2Idx);
6788 }
6789
6790 // VOP2 src0 instructions support all operand types, so we don't need to check
6791 // their legality. If src1 is already legal, we don't need to do anything.
6792 if (isLegalRegOperand(MRI, InstrDesc.operands()[Src1Idx], Src1))
6793 return;
6794
6795 // Special case: V_READLANE_B32 accepts only immediate or SGPR operands for
6796 // lane select. Fix up using V_READFIRSTLANE, since we assume that the lane
6797 // select is uniform.
6798 if (Opc == AMDGPU::V_READLANE_B32 && Src1.isReg() &&
6799 RI.isVGPR(MRI, Src1.getReg())) {
6800 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6801 const DebugLoc &DL = MI.getDebugLoc();
6802 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
6803 .add(Src1);
6804 Src1.ChangeToRegister(Reg, false);
6805 return;
6806 }
6807
6808 // We do not use commuteInstruction here because it is too aggressive and will
6809 // commute if it is possible. We only want to commute here if it improves
6810 // legality. This can be called a fairly large number of times so don't waste
6811 // compile time pointlessly swapping and checking legality again.
6812 if (HasImplicitSGPR || !MI.isCommutable()) {
6813 legalizeOpWithMove(MI, Src1Idx);
6814 return;
6815 }
6816
6817 // If src0 can be used as src1, commuting will make the operands legal.
6818 // Otherwise we have to give up and insert a move.
6819 //
6820 // TODO: Other immediate-like operand kinds could be commuted if there was a
6821 // MachineOperand::ChangeTo* for them.
6822 if ((!Src1.isImm() && !Src1.isReg()) ||
6823 !isLegalRegOperand(MRI, InstrDesc.operands()[Src1Idx], Src0)) {
6824 legalizeOpWithMove(MI, Src1Idx);
6825 return;
6826 }
6827
6828 int CommutedOpc = commuteOpcode(MI);
6829 if (CommutedOpc == -1) {
6830 legalizeOpWithMove(MI, Src1Idx);
6831 return;
6832 }
6833
6834 MI.setDesc(get(CommutedOpc));
6835
6836 Register Src0Reg = Src0.getReg();
6837 unsigned Src0SubReg = Src0.getSubReg();
6838 bool Src0Kill = Src0.isKill();
6839
6840 if (Src1.isImm())
6841 Src0.ChangeToImmediate(Src1.getImm());
6842 else if (Src1.isReg()) {
6843 Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
6844 Src0.setSubReg(Src1.getSubReg());
6845 } else
6846 llvm_unreachable("Should only have register or immediate operands");
6847
6848 Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
6849 Src1.setSubReg(Src0SubReg);
6851}
6852
6853// Legalize VOP3 operands. All operand types are supported for any operand
6854// but only one literal constant and only starting from GFX10.
6856 MachineInstr &MI) const {
6857 unsigned Opc = MI.getOpcode();
6858
6859 int VOP3Idx[3] = {
6860 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
6861 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
6862 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
6863 };
6864
6865 if (Opc == AMDGPU::V_PERMLANE16_B32_e64 ||
6866 Opc == AMDGPU::V_PERMLANEX16_B32_e64 ||
6867 Opc == AMDGPU::V_PERMLANE_BCAST_B32_e64 ||
6868 Opc == AMDGPU::V_PERMLANE_UP_B32_e64 ||
6869 Opc == AMDGPU::V_PERMLANE_DOWN_B32_e64 ||
6870 Opc == AMDGPU::V_PERMLANE_XOR_B32_e64 ||
6871 Opc == AMDGPU::V_PERMLANE_IDX_GEN_B32_e64) {
6872 // src1 and src2 must be scalar
6873 MachineOperand &Src1 = MI.getOperand(VOP3Idx[1]);
6874 const DebugLoc &DL = MI.getDebugLoc();
6875 if (Src1.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src1.getReg()))) {
6876 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6877 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
6878 .add(Src1);
6879 Src1.ChangeToRegister(Reg, false);
6880 }
6881 if (VOP3Idx[2] != -1) {
6882 MachineOperand &Src2 = MI.getOperand(VOP3Idx[2]);
6883 if (Src2.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src2.getReg()))) {
6884 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6885 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
6886 .add(Src2);
6887 Src2.ChangeToRegister(Reg, false);
6888 }
6889 }
6890 }
6891
6892 // Find the one SGPR operand we are allowed to use.
6893 int ConstantBusLimit = ST.getConstantBusLimit(Opc);
6894 int LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
6895 SmallDenseSet<unsigned> SGPRsUsed;
6896 Register SGPRReg = findUsedSGPR(MI, VOP3Idx);
6897 if (SGPRReg) {
6898 SGPRsUsed.insert(SGPRReg);
6899 --ConstantBusLimit;
6900 }
6901
6902 for (int Idx : VOP3Idx) {
6903 if (Idx == -1)
6904 break;
6905 MachineOperand &MO = MI.getOperand(Idx);
6906
6907 if (!MO.isReg()) {
6908 if (isInlineConstant(MO, get(Opc).operands()[Idx]))
6909 continue;
6910
6911 if (LiteralLimit > 0 && ConstantBusLimit > 0) {
6912 --LiteralLimit;
6913 --ConstantBusLimit;
6914 continue;
6915 }
6916
6917 --LiteralLimit;
6918 --ConstantBusLimit;
6919 legalizeOpWithMove(MI, Idx);
6920 continue;
6921 }
6922
6923 if (!RI.isSGPRClass(RI.getRegClassForReg(MRI, MO.getReg())))
6924 continue; // VGPRs are legal
6925
6926 // We can use one SGPR in each VOP3 instruction prior to GFX10
6927 // and two starting from GFX10.
6928 if (SGPRsUsed.count(MO.getReg()))
6929 continue;
6930 if (ConstantBusLimit > 0) {
6931 SGPRsUsed.insert(MO.getReg());
6932 --ConstantBusLimit;
6933 continue;
6934 }
6935
6936 // If we make it this far, then the operand is not legal and we must
6937 // legalize it.
6938 legalizeOpWithMove(MI, Idx);
6939 }
6940
6941 // Special case: V_FMAC_F32 and V_FMAC_F16 have src2 tied to vdst.
6942 if ((Opc == AMDGPU::V_FMAC_F32_e64 || Opc == AMDGPU::V_FMAC_F16_e64) &&
6943 !RI.isVGPR(MRI, MI.getOperand(VOP3Idx[2]).getReg()))
6944 legalizeOpWithMove(MI, VOP3Idx[2]);
6945
6946 // Fix the register class of packed FP32 instructions on gfx12+. See
6947 // SIInstrInfo::isLegalGFX12PlusPackedMathFP32or64BitOperand for more
6948 // information.
6950 for (unsigned I = 0; I < 3; ++I) {
6952 legalizeOpWithMove(MI, VOP3Idx[I]);
6953 }
6954 }
6955}
6956
6959 const TargetRegisterClass *DstRC /*=nullptr*/) const {
6960 const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
6961 const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
6962 if (DstRC)
6963 SRC = RI.getCommonSubClass(SRC, DstRC);
6964
6965 Register DstReg = MRI.createVirtualRegister(SRC);
6966 unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
6967
6968 if (RI.hasAGPRs(VRC)) {
6969 VRC = RI.getEquivalentVGPRClass(VRC);
6970 Register NewSrcReg = MRI.createVirtualRegister(VRC);
6971 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
6972 get(TargetOpcode::COPY), NewSrcReg)
6973 .addReg(SrcReg);
6974 SrcReg = NewSrcReg;
6975 }
6976
6977 if (SubRegs == 1) {
6978 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
6979 get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
6980 .addReg(SrcReg);
6981 return DstReg;
6982 }
6983
6985 for (unsigned i = 0; i < SubRegs; ++i) {
6986 Register SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
6987 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
6988 get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
6989 .addReg(SrcReg, {}, RI.getSubRegFromChannel(i));
6990 SRegs.push_back(SGPR);
6991 }
6992
6994 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
6995 get(AMDGPU::REG_SEQUENCE), DstReg);
6996 for (unsigned i = 0; i < SubRegs; ++i) {
6997 MIB.addReg(SRegs[i]);
6998 MIB.addImm(RI.getSubRegFromChannel(i));
6999 }
7000 return DstReg;
7001}
7002
7004 MachineInstr &MI) const {
7005
7006 // If the pointer is store in VGPRs, then we need to move them to
7007 // SGPRs using v_readfirstlane. This is safe because we only select
7008 // loads with uniform pointers to SMRD instruction so we know the
7009 // pointer value is uniform.
7010 MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
7011 if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
7012 Register SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
7013 SBase->setReg(SGPR);
7014 }
7015 MachineOperand *SOff = getNamedOperand(MI, AMDGPU::OpName::soffset);
7016 if (SOff && !RI.isSGPRReg(MRI, SOff->getReg())) {
7017 Register SGPR = readlaneVGPRToSGPR(SOff->getReg(), MI, MRI);
7018 SOff->setReg(SGPR);
7019 }
7020}
7021
7023 unsigned Opc = Inst.getOpcode();
7024 int OldSAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
7025 if (OldSAddrIdx < 0)
7026 return false;
7027
7028 assert(isSegmentSpecificFLAT(Inst) || (isFLAT(Inst) && ST.hasFlatGVSMode()));
7029
7030 int NewOpc = AMDGPU::getGlobalVaddrOp(Opc);
7031 if (NewOpc < 0)
7033 if (NewOpc < 0)
7034 return false;
7035
7036 MachineRegisterInfo &MRI = Inst.getMF()->getRegInfo();
7037 MachineOperand &SAddr = Inst.getOperand(OldSAddrIdx);
7038 if (RI.isSGPRReg(MRI, SAddr.getReg()))
7039 return false;
7040
7041 int NewVAddrIdx = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vaddr);
7042 if (NewVAddrIdx < 0)
7043 return false;
7044
7045 int OldVAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
7046
7047 // Check vaddr, it shall be zero or absent.
7048 MachineInstr *VAddrDef = nullptr;
7049 if (OldVAddrIdx >= 0) {
7050 MachineOperand &VAddr = Inst.getOperand(OldVAddrIdx);
7051 VAddrDef = MRI.getUniqueVRegDef(VAddr.getReg());
7052 if (!VAddrDef || !VAddrDef->isMoveImmediate() ||
7053 !VAddrDef->getOperand(1).isImm() ||
7054 VAddrDef->getOperand(1).getImm() != 0)
7055 return false;
7056 }
7057
7058 const MCInstrDesc &NewDesc = get(NewOpc);
7059 Inst.setDesc(NewDesc);
7060
7061 // Callers expect iterator to be valid after this call, so modify the
7062 // instruction in place.
7063 if (OldVAddrIdx == NewVAddrIdx) {
7064 MachineOperand &NewVAddr = Inst.getOperand(NewVAddrIdx);
7065 // Clear use list from the old vaddr holding a zero register.
7066 MRI.removeRegOperandFromUseList(&NewVAddr);
7067 MRI.moveOperands(&NewVAddr, &SAddr, 1);
7068 Inst.removeOperand(OldSAddrIdx);
7069 // Update the use list with the pointer we have just moved from vaddr to
7070 // saddr position. Otherwise new vaddr will be missing from the use list.
7071 MRI.removeRegOperandFromUseList(&NewVAddr);
7072 MRI.addRegOperandToUseList(&NewVAddr);
7073 } else {
7074 assert(OldSAddrIdx == NewVAddrIdx);
7075
7076 if (OldVAddrIdx >= 0) {
7077 int NewVDstIn = AMDGPU::getNamedOperandIdx(NewOpc,
7078 AMDGPU::OpName::vdst_in);
7079
7080 // removeOperand doesn't try to fixup tied operand indexes at it goes, so
7081 // it asserts. Untie the operands for now and retie them afterwards.
7082 if (NewVDstIn != -1) {
7083 int OldVDstIn = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in);
7084 Inst.untieRegOperand(OldVDstIn);
7085 }
7086
7087 Inst.removeOperand(OldVAddrIdx);
7088
7089 if (NewVDstIn != -1) {
7090 int NewVDst = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vdst);
7091 Inst.tieOperands(NewVDst, NewVDstIn);
7092 }
7093 }
7094 }
7095
7096 if (VAddrDef && MRI.use_nodbg_empty(VAddrDef->getOperand(0).getReg()))
7097 VAddrDef->eraseFromParent();
7098
7099 return true;
7100}
7101
7102// FIXME: Remove this when SelectionDAG is obsoleted.
7104 MachineInstr &MI) const {
7105 if (!isSegmentSpecificFLAT(MI) && !ST.hasFlatGVSMode())
7106 return;
7107
7108 // Fixup SGPR operands in VGPRs. We only select these when the DAG divergence
7109 // thinks they are uniform, so a readfirstlane should be valid.
7110 MachineOperand *SAddr = getNamedOperand(MI, AMDGPU::OpName::saddr);
7111 if (!SAddr || RI.isSGPRClass(MRI.getRegClass(SAddr->getReg())))
7112 return;
7113
7115 return;
7116
7117 const TargetRegisterClass *DeclaredRC =
7118 getRegClass(MI.getDesc(), SAddr->getOperandNo());
7119
7120 Register ToSGPR = readlaneVGPRToSGPR(SAddr->getReg(), MI, MRI, DeclaredRC);
7121 SAddr->setReg(ToSGPR);
7122}
7123
7126 const TargetRegisterClass *DstRC,
7129 const DebugLoc &DL) const {
7130 Register OpReg = Op.getReg();
7131 unsigned OpSubReg = Op.getSubReg();
7132
7133 const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
7134 RI.getRegClassForReg(MRI, OpReg), OpSubReg);
7135
7136 // Check if operand is already the correct register class.
7137 if (DstRC == OpRC)
7138 return;
7139
7140 Register DstReg = MRI.createVirtualRegister(DstRC);
7141 auto Copy =
7142 BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).addReg(OpReg);
7143 Op.setReg(DstReg);
7144
7145 MachineInstr *Def = MRI.getVRegDef(OpReg);
7146 if (!Def)
7147 return;
7148
7149 // Try to eliminate the copy if it is copying an immediate value.
7150 if (Def->isMoveImmediate() && DstRC != &AMDGPU::VReg_1RegClass)
7151 foldImmediate(*Copy, *Def, OpReg, &MRI);
7152
7153 bool ImpDef = Def->isImplicitDef();
7154 while (!ImpDef && Def && Def->isCopy()) {
7155 if (Def->getOperand(1).getReg().isPhysical())
7156 break;
7157 Def = MRI.getUniqueVRegDef(Def->getOperand(1).getReg());
7158 ImpDef = Def && Def->isImplicitDef();
7159 }
7160 if (!RI.isSGPRClass(DstRC) && !Copy->readsRegister(AMDGPU::EXEC, &RI) &&
7161 !ImpDef)
7162 Copy.addReg(AMDGPU::EXEC, RegState::Implicit);
7163}
7164
7165// Emit the actual waterfall loop, executing the wrapped instruction for each
7166// unique value of \p ScalarOps across all lanes. In the best case we execute 1
7167// iteration, in the worst case we execute 64 (once per lane).
7170 MachineBasicBlock &BodyBB, const DebugLoc &DL,
7171 ArrayRef<MachineOperand *> ScalarOps, ArrayRef<Register> PhySGPRs = {}) {
7172 MachineFunction &MF = *LoopBB.getParent();
7174 const SIRegisterInfo *TRI = ST.getRegisterInfo();
7176 const auto *BoolXExecRC = TRI->getWaveMaskRegClass();
7177
7179 Register CondReg;
7180 for (auto [Idx, ScalarOp] : enumerate(ScalarOps)) {
7181 unsigned RegSize = TRI->getRegSizeInBits(ScalarOp->getReg(), MRI);
7182 unsigned NumSubRegs = RegSize / 32;
7183 Register VScalarOp = ScalarOp->getReg();
7184
7185 const TargetRegisterClass *RFLSrcRC =
7186 TII.getRegClass(TII.get(AMDGPU::V_READFIRSTLANE_B32), 1);
7187
7188 if (NumSubRegs == 1) {
7189 const TargetRegisterClass *VScalarOpRC = MRI.getRegClass(VScalarOp);
7190 if (const TargetRegisterClass *Common =
7191 TRI->getCommonSubClass(VScalarOpRC, RFLSrcRC);
7192 Common != VScalarOpRC) {
7193 Register VRReg = MRI.createVirtualRegister(Common);
7194 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::COPY), VRReg).addReg(VScalarOp);
7195 VScalarOp = VRReg;
7196 }
7197 Register CurReg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7198
7199 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurReg)
7200 .addReg(VScalarOp);
7201
7202 Register NewCondReg = MRI.createVirtualRegister(BoolXExecRC);
7203
7204 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U32_e64), NewCondReg)
7205 .addReg(CurReg)
7206 .addReg(VScalarOp);
7207
7208 // Combine the comparison results with AND.
7209 if (!CondReg) // First.
7210 CondReg = NewCondReg;
7211 else { // If not the first, we create an AND.
7212 Register AndReg = MRI.createVirtualRegister(BoolXExecRC);
7213 BuildMI(LoopBB, I, DL, TII.get(LMC.AndOpc), AndReg)
7214 .addReg(CondReg)
7215 .addReg(NewCondReg);
7216 CondReg = AndReg;
7217 }
7218
7219 // Update ScalarOp operand to use the SGPR ScalarOp.
7220 if (PhySGPRs.empty() || !PhySGPRs[Idx].isValid())
7221 ScalarOp->setReg(CurReg);
7222 else {
7223 // Insert into the same block of use
7224 BuildMI(*ScalarOp->getParent()->getParent(), ScalarOp->getParent(), DL,
7225 TII.get(AMDGPU::COPY), PhySGPRs[Idx])
7226 .addReg(CurReg);
7227 ScalarOp->setReg(PhySGPRs[Idx]);
7228 }
7229 ScalarOp->setIsKill();
7230 } else {
7231 SmallVector<Register, 8> ReadlanePieces;
7232 RegState VScalarOpUndef = getUndefRegState(ScalarOp->isUndef());
7233 assert(NumSubRegs % 2 == 0 && NumSubRegs <= 32 &&
7234 "Unhandled register size");
7235
7236 for (unsigned Idx = 0; Idx < NumSubRegs; Idx += 2) {
7237 Register CurRegLo =
7238 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7239 Register CurRegHi =
7240 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7241
7242 // Read the next variant <- also loop target.
7243 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegLo)
7244 .addReg(VScalarOp, VScalarOpUndef, TRI->getSubRegFromChannel(Idx));
7245
7246 // Read the next variant <- also loop target.
7247 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegHi)
7248 .addReg(VScalarOp, VScalarOpUndef,
7249 TRI->getSubRegFromChannel(Idx + 1));
7250
7251 ReadlanePieces.push_back(CurRegLo);
7252 ReadlanePieces.push_back(CurRegHi);
7253
7254 // Comparison is to be done as 64-bit.
7255 Register CurReg = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
7256 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), CurReg)
7257 .addReg(CurRegLo)
7258 .addImm(AMDGPU::sub0)
7259 .addReg(CurRegHi)
7260 .addImm(AMDGPU::sub1);
7261
7262 Register NewCondReg = MRI.createVirtualRegister(BoolXExecRC);
7263 auto Cmp = BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64),
7264 NewCondReg)
7265 .addReg(CurReg);
7266 if (NumSubRegs <= 2)
7267 Cmp.addReg(VScalarOp);
7268 else
7269 Cmp.addReg(VScalarOp, VScalarOpUndef,
7270 TRI->getSubRegFromChannel(Idx, 2));
7271
7272 // Combine the comparison results with AND.
7273 if (!CondReg) // First.
7274 CondReg = NewCondReg;
7275 else { // If not the first, we create an AND.
7276 Register AndReg = MRI.createVirtualRegister(BoolXExecRC);
7277 BuildMI(LoopBB, I, DL, TII.get(LMC.AndOpc), AndReg)
7278 .addReg(CondReg)
7279 .addReg(NewCondReg);
7280 CondReg = AndReg;
7281 }
7282 } // End for loop.
7283
7284 const auto *SScalarOpRC =
7285 TRI->getEquivalentSGPRClass(MRI.getRegClass(VScalarOp));
7286 Register SScalarOp = MRI.createVirtualRegister(SScalarOpRC);
7287
7288 // Build scalar ScalarOp.
7289 auto Merge =
7290 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SScalarOp);
7291 unsigned Channel = 0;
7292 for (Register Piece : ReadlanePieces) {
7293 Merge.addReg(Piece).addImm(TRI->getSubRegFromChannel(Channel++));
7294 }
7295
7296 // Update ScalarOp operand to use the SGPR ScalarOp.
7297 if (PhySGPRs.empty() || !PhySGPRs[Idx].isValid())
7298 ScalarOp->setReg(SScalarOp);
7299 else {
7300 BuildMI(*ScalarOp->getParent()->getParent(), ScalarOp->getParent(), DL,
7301 TII.get(AMDGPU::COPY), PhySGPRs[Idx])
7302 .addReg(SScalarOp);
7303 ScalarOp->setReg(PhySGPRs[Idx]);
7304 }
7305 ScalarOp->setIsKill();
7306 }
7307 }
7308
7309 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
7310 MRI.setSimpleHint(SaveExec, CondReg);
7311
7312 // Update EXEC to matching lanes, saving original to SaveExec.
7313 BuildMI(LoopBB, I, DL, TII.get(LMC.AndSaveExecOpc), SaveExec)
7314 .addReg(CondReg, RegState::Kill);
7315
7316 // The original instruction is here; we insert the terminators after it.
7317 I = BodyBB.end();
7318
7319 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
7320 BuildMI(BodyBB, I, DL, TII.get(LMC.XorTermOpc), LMC.ExecReg)
7321 .addReg(LMC.ExecReg)
7322 .addReg(SaveExec);
7323
7324 BuildMI(BodyBB, I, DL, TII.get(AMDGPU::SI_WATERFALL_LOOP)).addMBB(&LoopBB);
7325}
7326
7327// Build a waterfall loop around \p MI, replacing the VGPR \p ScalarOp register
7328// with SGPRs by iterating over all unique values across all lanes.
7329// Returns the loop basic block that now contains \p MI.
7330static MachineBasicBlock *
7334 MachineBasicBlock::iterator Begin = nullptr,
7335 MachineBasicBlock::iterator End = nullptr,
7336 ArrayRef<Register> PhySGPRs = {}) {
7337 assert((PhySGPRs.empty() || PhySGPRs.size() == ScalarOps.size()) &&
7338 "Physical SGPRs must be empty or match the number of scalar operands");
7339 MachineBasicBlock &MBB = *MI.getParent();
7340 MachineFunction &MF = *MBB.getParent();
7342 const SIRegisterInfo *TRI = ST.getRegisterInfo();
7343 MachineRegisterInfo &MRI = MF.getRegInfo();
7344 if (!Begin.isValid())
7345 Begin = &MI;
7346 if (!End.isValid()) {
7347 End = &MI;
7348 ++End;
7349 }
7350 const DebugLoc &DL = MI.getDebugLoc();
7352 const auto *BoolXExecRC = TRI->getWaveMaskRegClass();
7353
7354 // Save SCC. Waterfall Loop may overwrite SCC.
7355 Register SaveSCCReg;
7356
7357 // FIXME: We should maintain SCC liveness while doing the FixSGPRCopies walk
7358 // rather than unlimited scan everywhere
7359 bool SCCNotDead =
7360 MBB.computeRegisterLiveness(TRI, AMDGPU::SCC, MI,
7361 std::numeric_limits<unsigned>::max()) !=
7363 if (SCCNotDead) {
7364 SaveSCCReg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7365 BuildMI(MBB, Begin, DL, TII.get(AMDGPU::S_CSELECT_B32), SaveSCCReg)
7366 .addImm(1)
7367 .addImm(0);
7368 }
7369
7370 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
7371
7372 // Save the EXEC mask
7373 BuildMI(MBB, Begin, DL, TII.get(LMC.MovOpc), SaveExec).addReg(LMC.ExecReg);
7374
7375 // Killed uses in the instruction we are waterfalling around will be
7376 // incorrect due to the added control-flow.
7378 ++AfterMI;
7379 for (auto I = Begin; I != AfterMI; I++) {
7380 for (auto &MO : I->all_uses())
7381 MRI.clearKillFlags(MO.getReg());
7382 }
7383
7384 // To insert the loop we need to split the block. Move everything after this
7385 // point to a new block, and insert a new empty block between the two.
7388 MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
7390 ++MBBI;
7391
7392 MF.insert(MBBI, LoopBB);
7393 MF.insert(MBBI, BodyBB);
7394 MF.insert(MBBI, RemainderBB);
7395
7396 LoopBB->addSuccessor(BodyBB);
7397 BodyBB->addSuccessor(LoopBB);
7398 BodyBB->addSuccessor(RemainderBB);
7399
7400 // Move Begin to MI to the BodyBB, and the remainder of the block to
7401 // RemainderBB.
7402 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
7403 RemainderBB->splice(RemainderBB->begin(), &MBB, End, MBB.end());
7404 BodyBB->splice(BodyBB->begin(), &MBB, Begin, MBB.end());
7405
7406 MBB.addSuccessor(LoopBB);
7407
7408 // Update dominators. We know that MBB immediately dominates LoopBB, that
7409 // LoopBB immediately dominates BodyBB, and BodyBB immediately dominates
7410 // RemainderBB. RemainderBB immediately dominates all of the successors
7411 // transferred to it from MBB that MBB used to properly dominate.
7412 if (MDT) {
7413 MDT->addNewBlock(LoopBB, &MBB);
7414 MDT->addNewBlock(BodyBB, LoopBB);
7415 MDT->addNewBlock(RemainderBB, BodyBB);
7416 for (auto &Succ : RemainderBB->successors()) {
7417 if (MDT->properlyDominates(&MBB, Succ)) {
7418 MDT->changeImmediateDominator(Succ, RemainderBB);
7419 }
7420 }
7421 }
7422
7423 emitLoadScalarOpsFromVGPRLoop(TII, MRI, *LoopBB, *BodyBB, DL, ScalarOps,
7424 PhySGPRs);
7425
7426 MachineBasicBlock::iterator First = RemainderBB->begin();
7427 // Restore SCC
7428 if (SCCNotDead) {
7429 BuildMI(*RemainderBB, First, DL, TII.get(AMDGPU::S_CMP_LG_U32))
7430 .addReg(SaveSCCReg, RegState::Kill)
7431 .addImm(0);
7432 }
7433
7434 // Restore the EXEC mask
7435 BuildMI(*RemainderBB, First, DL, TII.get(LMC.MovOpc), LMC.ExecReg)
7436 .addReg(SaveExec);
7437 return BodyBB;
7438}
7439
7440// Extract pointer from Rsrc and return a zero-value Rsrc replacement.
7441static std::tuple<unsigned, unsigned>
7443 MachineBasicBlock &MBB = *MI.getParent();
7444 MachineFunction &MF = *MBB.getParent();
7445 MachineRegisterInfo &MRI = MF.getRegInfo();
7446
7447 // Extract the ptr from the resource descriptor.
7448 unsigned RsrcPtr =
7449 TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
7450 AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
7451
7452 // Create an empty resource descriptor
7453 Register Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
7454 Register SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
7455 Register SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
7456 Register NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
7457 uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
7458
7459 // Zero64 = 0
7460 BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
7461 .addImm(0);
7462
7463 // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
7464 BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
7465 .addImm(Lo_32(RsrcDataFormat));
7466
7467 // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
7468 BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
7469 .addImm(Hi_32(RsrcDataFormat));
7470
7471 // NewSRsrc = {Zero64, SRsrcFormat}
7472 BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
7473 .addReg(Zero64)
7474 .addImm(AMDGPU::sub0_sub1)
7475 .addReg(SRsrcFormatLo)
7476 .addImm(AMDGPU::sub2)
7477 .addReg(SRsrcFormatHi)
7478 .addImm(AMDGPU::sub3);
7479
7480 return std::tuple(RsrcPtr, NewSRsrc);
7481}
7482
7485 MachineDominatorTree *MDT) const {
7486 MachineFunction &MF = *MI.getMF();
7487 MachineRegisterInfo &MRI = MF.getRegInfo();
7488 MachineBasicBlock *CreatedBB = nullptr;
7489
7490 // Legalize VOP2
7491 if (isVOP2(MI) || isVOPC(MI)) {
7493 return CreatedBB;
7494 }
7495
7496 // Legalize VOP3
7497 if (isVOP3(MI)) {
7499 return CreatedBB;
7500 }
7501
7502 // Legalize SMRD
7503 if (isSMRD(MI)) {
7505 return CreatedBB;
7506 }
7507
7508 // Legalize FLAT
7509 if (isFLAT(MI)) {
7511 return CreatedBB;
7512 }
7513
7514 // Legalize PHI
7515 // The register class of the operands must be the same type as the register
7516 // class of the output.
7517 if (MI.getOpcode() == AMDGPU::PHI) {
7518 const TargetRegisterClass *VRC = getOpRegClass(MI, 0);
7519 assert(!RI.isSGPRClass(VRC));
7520
7521 // Update all the operands so they have the same type.
7522 for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
7523 MachineOperand &Op = MI.getOperand(I);
7524 if (!Op.isReg() || !Op.getReg().isVirtual())
7525 continue;
7526
7527 // MI is a PHI instruction.
7528 MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
7530
7531 // Avoid creating no-op copies with the same src and dst reg class. These
7532 // confuse some of the machine passes.
7533 legalizeGenericOperand(*InsertBB, Insert, VRC, Op, MRI, MI.getDebugLoc());
7534 }
7535 }
7536
7537 // REG_SEQUENCE doesn't really require operand legalization, but if one has a
7538 // VGPR dest type and SGPR sources, insert copies so all operands are
7539 // VGPRs. This seems to help operand folding / the register coalescer.
7540 if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
7541 MachineBasicBlock *MBB = MI.getParent();
7542 const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
7543 if (RI.hasVGPRs(DstRC)) {
7544 // Update all the operands so they are VGPR register classes. These may
7545 // not be the same register class because REG_SEQUENCE supports mixing
7546 // subregister index types e.g. sub0_sub1 + sub2 + sub3
7547 for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
7548 MachineOperand &Op = MI.getOperand(I);
7549 if (!Op.isReg() || !Op.getReg().isVirtual())
7550 continue;
7551
7552 const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
7553 const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
7554 if (VRC == OpRC)
7555 continue;
7556
7557 legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
7558 Op.setIsKill();
7559 }
7560 }
7561
7562 return CreatedBB;
7563 }
7564
7565 // Legalize INSERT_SUBREG
7566 // src0 must have the same register class as dst
7567 if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
7568 Register Dst = MI.getOperand(0).getReg();
7569 Register Src0 = MI.getOperand(1).getReg();
7570 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
7571 const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
7572 if (DstRC != Src0RC) {
7573 MachineBasicBlock *MBB = MI.getParent();
7574 MachineOperand &Op = MI.getOperand(1);
7575 legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
7576 }
7577 return CreatedBB;
7578 }
7579
7580 // Legalize SI_INIT_M0
7581 if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
7582 MachineOperand &Src = MI.getOperand(0);
7583 if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
7584 Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
7585 return CreatedBB;
7586 }
7587
7588 // Legalize S_BITREPLICATE, S_QUADMASK and S_WQM
7589 if (MI.getOpcode() == AMDGPU::S_BITREPLICATE_B64_B32 ||
7590 MI.getOpcode() == AMDGPU::S_QUADMASK_B32 ||
7591 MI.getOpcode() == AMDGPU::S_QUADMASK_B64 ||
7592 MI.getOpcode() == AMDGPU::S_WQM_B32 ||
7593 MI.getOpcode() == AMDGPU::S_WQM_B64 ||
7594 MI.getOpcode() == AMDGPU::S_INVERSE_BALLOT_U32 ||
7595 MI.getOpcode() == AMDGPU::S_INVERSE_BALLOT_U64) {
7596 MachineOperand &Src = MI.getOperand(1);
7597 if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
7598 Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
7599 return CreatedBB;
7600 }
7601
7602 // Legalize MIMG/VIMAGE/VSAMPLE and MUBUF/MTBUF for shaders.
7603 //
7604 // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
7605 // scratch memory access. In both cases, the legalization never involves
7606 // conversion to the addr64 form.
7608 (isMUBUF(MI) || isMTBUF(MI)))) {
7609 AMDGPU::OpName RSrcOpName = (isVIMAGE(MI) || isVSAMPLE(MI))
7610 ? AMDGPU::OpName::rsrc
7611 : AMDGPU::OpName::srsrc;
7612 MachineOperand *SRsrc = getNamedOperand(MI, RSrcOpName);
7613 if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg())))
7614 CreatedBB = generateWaterFallLoop(*this, MI, {SRsrc}, MDT);
7615
7616 AMDGPU::OpName SampOpName =
7617 isMIMG(MI) ? AMDGPU::OpName::ssamp : AMDGPU::OpName::samp;
7618 MachineOperand *SSamp = getNamedOperand(MI, SampOpName);
7619 if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg())))
7620 CreatedBB = generateWaterFallLoop(*this, MI, {SSamp}, MDT);
7621
7622 return CreatedBB;
7623 }
7624
7625 // Legalize SI_CALL
7626 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
7627 MachineOperand *Dest = &MI.getOperand(0);
7628 if (!RI.isSGPRClass(MRI.getRegClass(Dest->getReg()))) {
7629 createWaterFallForSiCall(&MI, MDT, {Dest});
7630 }
7631 }
7632
7633 // Legalize s_sleep_var.
7634 if (MI.getOpcode() == AMDGPU::S_SLEEP_VAR) {
7635 const DebugLoc &DL = MI.getDebugLoc();
7636 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7637 int Src0Idx =
7638 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
7639 MachineOperand &Src0 = MI.getOperand(Src0Idx);
7640 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
7641 .add(Src0);
7642 Src0.ChangeToRegister(Reg, false);
7643 return nullptr;
7644 }
7645
7646 // Legalize TENSOR_LOAD_TO_LDS_d2/_d4, TENSOR_STORE_FROM_LDS_d2/_d4. All their
7647 // operands are scalar.
7648 if (MI.getOpcode() == AMDGPU::TENSOR_LOAD_TO_LDS_d2 ||
7649 MI.getOpcode() == AMDGPU::TENSOR_LOAD_TO_LDS_d4 ||
7650 MI.getOpcode() == AMDGPU::TENSOR_STORE_FROM_LDS_d2 ||
7651 MI.getOpcode() == AMDGPU::TENSOR_STORE_FROM_LDS_d4) {
7652 for (MachineOperand &Src : MI.explicit_operands()) {
7653 if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
7654 Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
7655 }
7656 return CreatedBB;
7657 }
7658
7659 // Legalize MUBUF instructions.
7660 bool isSoffsetLegal = true;
7661 int SoffsetIdx =
7662 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::soffset);
7663 if (SoffsetIdx != -1) {
7664 MachineOperand *Soffset = &MI.getOperand(SoffsetIdx);
7665 if (Soffset->isReg() && Soffset->getReg().isVirtual() &&
7666 !RI.isSGPRClass(MRI.getRegClass(Soffset->getReg()))) {
7667 isSoffsetLegal = false;
7668 }
7669 }
7670
7671 bool isRsrcLegal = true;
7672 int RsrcIdx =
7673 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
7674 if (RsrcIdx != -1) {
7675 MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
7676 if (Rsrc->isReg() && !RI.isSGPRReg(MRI, Rsrc->getReg()))
7677 isRsrcLegal = false;
7678 }
7679
7680 // The operands are legal.
7681 if (isRsrcLegal && isSoffsetLegal)
7682 return CreatedBB;
7683
7684 if (!isRsrcLegal) {
7685 // Legalize a VGPR Rsrc
7686 //
7687 // If the instruction is _ADDR64, we can avoid a waterfall by extracting
7688 // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
7689 // a zero-value SRsrc.
7690 //
7691 // If the instruction is _OFFSET (both idxen and offen disabled), and we
7692 // support ADDR64 instructions, we can convert to ADDR64 and do the same as
7693 // above.
7694 //
7695 // Otherwise we are on non-ADDR64 hardware, and/or we have
7696 // idxen/offen/bothen and we fall back to a waterfall loop.
7697
7698 MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
7699 MachineBasicBlock &MBB = *MI.getParent();
7700
7701 MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
7702 if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
7703 // This is already an ADDR64 instruction so we need to add the pointer
7704 // extracted from the resource descriptor to the current value of VAddr.
7705 Register NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7706 Register NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7707 Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
7708
7709 const auto *BoolXExecRC = RI.getWaveMaskRegClass();
7710 Register CondReg0 = MRI.createVirtualRegister(BoolXExecRC);
7711 Register CondReg1 = MRI.createVirtualRegister(BoolXExecRC);
7712
7713 unsigned RsrcPtr, NewSRsrc;
7714 std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
7715
7716 // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
7717 const DebugLoc &DL = MI.getDebugLoc();
7718 BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_CO_U32_e64), NewVAddrLo)
7719 .addDef(CondReg0)
7720 .addReg(RsrcPtr, {}, AMDGPU::sub0)
7721 .addReg(VAddr->getReg(), {}, AMDGPU::sub0)
7722 .addImm(0);
7723
7724 // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
7725 BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e64), NewVAddrHi)
7726 .addDef(CondReg1, RegState::Dead)
7727 .addReg(RsrcPtr, {}, AMDGPU::sub1)
7728 .addReg(VAddr->getReg(), {}, AMDGPU::sub1)
7729 .addReg(CondReg0, RegState::Kill)
7730 .addImm(0);
7731
7732 // NewVaddr = {NewVaddrHi, NewVaddrLo}
7733 BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
7734 .addReg(NewVAddrLo)
7735 .addImm(AMDGPU::sub0)
7736 .addReg(NewVAddrHi)
7737 .addImm(AMDGPU::sub1);
7738
7739 VAddr->setReg(NewVAddr);
7740 Rsrc->setReg(NewSRsrc);
7741 } else if (!VAddr && ST.hasAddr64()) {
7742 // This instructions is the _OFFSET variant, so we need to convert it to
7743 // ADDR64.
7744 assert(ST.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
7745 "FIXME: Need to emit flat atomics here");
7746
7747 unsigned RsrcPtr, NewSRsrc;
7748 std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
7749
7750 Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
7751 MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
7752 MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
7753 MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
7754 unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
7755
7756 // Atomics with return have an additional tied operand and are
7757 // missing some of the special bits.
7758 MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
7759 MachineInstr *Addr64;
7760
7761 if (!VDataIn) {
7762 // Regular buffer load / store.
7764 BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
7765 .add(*VData)
7766 .addReg(NewVAddr)
7767 .addReg(NewSRsrc)
7768 .add(*SOffset)
7769 .add(*Offset);
7770
7771 if (const MachineOperand *CPol =
7772 getNamedOperand(MI, AMDGPU::OpName::cpol)) {
7773 MIB.addImm(CPol->getImm());
7774 }
7775
7776 if (const MachineOperand *TFE =
7777 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
7778 MIB.addImm(TFE->getImm());
7779 }
7780
7781 MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::swz));
7782
7783 MIB.cloneMemRefs(MI);
7784 Addr64 = MIB;
7785 } else {
7786 // Atomics with return.
7787 Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
7788 .add(*VData)
7789 .add(*VDataIn)
7790 .addReg(NewVAddr)
7791 .addReg(NewSRsrc)
7792 .add(*SOffset)
7793 .add(*Offset)
7794 .addImm(getNamedImmOperand(MI, AMDGPU::OpName::cpol))
7795 .cloneMemRefs(MI);
7796 }
7797
7798 MI.removeFromParent();
7799
7800 // NewVaddr = {NewVaddrHi, NewVaddrLo}
7801 BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
7802 NewVAddr)
7803 .addReg(RsrcPtr, {}, AMDGPU::sub0)
7804 .addImm(AMDGPU::sub0)
7805 .addReg(RsrcPtr, {}, AMDGPU::sub1)
7806 .addImm(AMDGPU::sub1);
7807 } else {
7808 // Legalize a VGPR Rsrc and soffset together.
7809 if (!isSoffsetLegal) {
7810 MachineOperand *Soffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
7811 CreatedBB = generateWaterFallLoop(*this, MI, {Rsrc, Soffset}, MDT);
7812 return CreatedBB;
7813 }
7814 CreatedBB = generateWaterFallLoop(*this, MI, {Rsrc}, MDT);
7815 return CreatedBB;
7816 }
7817 }
7818
7819 // Legalize a VGPR soffset.
7820 if (!isSoffsetLegal) {
7821 MachineOperand *Soffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
7822 CreatedBB = generateWaterFallLoop(*this, MI, {Soffset}, MDT);
7823 return CreatedBB;
7824 }
7825 return CreatedBB;
7826}
7827
7829 InstrList.insert(MI);
7830 // Add MBUF instructiosn to deferred list.
7831 int RsrcIdx =
7832 AMDGPU::getNamedOperandIdx(MI->getOpcode(), AMDGPU::OpName::srsrc);
7833 if (RsrcIdx != -1) {
7834 DeferredList.insert(MI);
7835 }
7836}
7837
7839 return DeferredList.contains(MI);
7840}
7841
7842// Legalize size mismatches between 16bit and 32bit registers in v2s copy
7843// lowering (change sgpr to vgpr).
7844// This is mainly caused by 16bit SALU and 16bit VALU using reg with different
7845// size. Need to legalize the size of the operands during the vgpr lowering
7846// chain. This can be removed after we have sgpr16 in place
7848 MachineRegisterInfo &MRI) const {
7849 if (!ST.useRealTrue16Insts())
7850 return;
7851
7852 unsigned Opcode = MI.getOpcode();
7853 MachineBasicBlock *MBB = MI.getParent();
7854 // Legalize operands and check for size mismatch
7855 if (!OpIdx || OpIdx >= MI.getNumExplicitOperands() ||
7856 OpIdx >= get(Opcode).getNumOperands() ||
7857 get(Opcode).operands()[OpIdx].RegClass == -1)
7858 return;
7859
7860 MachineOperand &Op = MI.getOperand(OpIdx);
7861 if (!Op.isReg() || !Op.getReg().isVirtual())
7862 return;
7863
7864 const TargetRegisterClass *CurrRC = MRI.getRegClass(Op.getReg());
7865 if (!RI.isVGPRClass(CurrRC))
7866 return;
7867
7868 int16_t RCID = getOpRegClassID(get(Opcode).operands()[OpIdx]);
7869 const TargetRegisterClass *ExpectedRC = RI.getRegClass(RCID);
7870 if (RI.getMatchingSuperRegClass(CurrRC, ExpectedRC, AMDGPU::lo16)) {
7871 Op.setSubReg(AMDGPU::lo16);
7872 } else if (RI.getMatchingSuperRegClass(ExpectedRC, CurrRC, AMDGPU::lo16)) {
7873 const DebugLoc &DL = MI.getDebugLoc();
7874 Register NewDstReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7875 Register Undef = MRI.createVirtualRegister(&AMDGPU::VGPR_16RegClass);
7876 BuildMI(*MBB, MI, DL, get(AMDGPU::IMPLICIT_DEF), Undef);
7877 BuildMI(*MBB, MI, DL, get(AMDGPU::REG_SEQUENCE), NewDstReg)
7878 .addReg(Op.getReg())
7879 .addImm(AMDGPU::lo16)
7880 .addReg(Undef)
7881 .addImm(AMDGPU::hi16);
7882 Op.setReg(NewDstReg);
7883 }
7884}
7886 MachineRegisterInfo &MRI) const {
7887 for (unsigned OpIdx = 1; OpIdx < MI.getNumExplicitOperands(); OpIdx++)
7889}
7890
7894 ArrayRef<Register> PhySGPRs) const {
7895 assert(MI->getOpcode() == AMDGPU::SI_CALL_ISEL &&
7896 "This only handle waterfall for SI_CALL_ISEL");
7897 // Move everything between ADJCALLSTACKUP and ADJCALLSTACKDOWN and
7898 // following copies, we also need to move copies from and to physical
7899 // registers into the loop block.
7900 // Also move the copies to physical registers into the loop block
7901 MachineBasicBlock &MBB = *MI->getParent();
7903 while (Start->getOpcode() != AMDGPU::ADJCALLSTACKUP)
7904 --Start;
7906 while (End->getOpcode() != AMDGPU::ADJCALLSTACKDOWN)
7907 ++End;
7908
7909 // Also include following copies of the return value
7910 ++End;
7911 while (End != MBB.end() && End->isCopy() &&
7912 MI->definesRegister(End->getOperand(1).getReg(), &RI))
7913 ++End;
7914
7915 generateWaterFallLoop(*this, *MI, ScalarOps, MDT, Start, End, PhySGPRs);
7916}
7917
7919 MachineDominatorTree *MDT) const {
7921 DenseMap<MachineInstr *, bool> V2SPhyCopiesToErase;
7922 while (!Worklist.empty()) {
7923 MachineInstr &Inst = *Worklist.top();
7924 Worklist.erase_top();
7925 // Skip MachineInstr in the deferred list.
7926 if (Worklist.isDeferred(&Inst))
7927 continue;
7928 moveToVALUImpl(Worklist, MDT, Inst, WaterFalls, V2SPhyCopiesToErase);
7929 }
7930
7931 // Deferred list of instructions will be processed once
7932 // all the MachineInstr in the worklist are done.
7933 for (MachineInstr *Inst : Worklist.getDeferredList()) {
7934 moveToVALUImpl(Worklist, MDT, *Inst, WaterFalls, V2SPhyCopiesToErase);
7935 assert(Worklist.empty() &&
7936 "Deferred MachineInstr are not supposed to re-populate worklist");
7937 }
7938
7939 for (std::pair<MachineInstr *, V2PhysSCopyInfo> &Entry : WaterFalls) {
7940 if (Entry.first->getOpcode() == AMDGPU::SI_CALL_ISEL)
7941 createWaterFallForSiCall(Entry.first, MDT, Entry.second.MOs,
7942 Entry.second.SGPRs);
7943 }
7944
7945 for (std::pair<MachineInstr *, bool> Entry : V2SPhyCopiesToErase)
7946 if (Entry.second)
7947 Entry.first->eraseFromParent();
7948}
7950 MachineRegisterInfo &MRI, Register DstReg, MachineInstr &Inst) const {
7951 // If it's a copy of a VGPR to a physical SGPR, insert a V_READFIRSTLANE and
7952 // hope for the best.
7953 const TargetRegisterClass *DstRC = RI.getRegClassForReg(MRI, DstReg);
7954 ArrayRef<int16_t> SubRegIndices = RI.getRegSplitParts(DstRC, 4);
7955 if (SubRegIndices.size() <= 1) {
7956 Register NewDst = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7957 BuildMI(*Inst.getParent(), &Inst, Inst.getDebugLoc(),
7958 get(AMDGPU::V_READFIRSTLANE_B32), NewDst)
7959 .add(Inst.getOperand(1));
7960 BuildMI(*Inst.getParent(), &Inst, Inst.getDebugLoc(), get(AMDGPU::COPY),
7961 DstReg)
7962 .addReg(NewDst);
7963 } else {
7965 for (int16_t Indice : SubRegIndices) {
7966 Register NewDst = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7967 BuildMI(*Inst.getParent(), &Inst, Inst.getDebugLoc(),
7968 get(AMDGPU::V_READFIRSTLANE_B32), NewDst)
7969 .addReg(Inst.getOperand(1).getReg(), {}, Indice);
7970
7971 DstRegs.push_back(NewDst);
7972 }
7974 BuildMI(*Inst.getParent(), &Inst, Inst.getDebugLoc(),
7975 get(AMDGPU::REG_SEQUENCE), DstReg);
7976 for (unsigned i = 0; i < SubRegIndices.size(); ++i) {
7977 MIB.addReg(DstRegs[i]);
7978 MIB.addImm(RI.getSubRegFromChannel(i));
7979 }
7980 }
7981}
7982
7984 SIInstrWorklist &Worklist, Register DstReg, MachineInstr &Inst,
7987 DenseMap<MachineInstr *, bool> &V2SPhyCopiesToErase) const {
7988 if (DstReg == AMDGPU::M0) {
7989 createReadFirstLaneFromCopyToPhysReg(MRI, DstReg, Inst);
7990 V2SPhyCopiesToErase.try_emplace(&Inst, true);
7991 return;
7992 }
7993 Register SrcReg = Inst.getOperand(1).getReg();
7996 // Only search current block since phyreg's def & use cannot cross
7997 // blocks when MF.NoPhi = false.
7998 while (++I != E) {
7999 // For SI_CALL_ISEL users, replace the phys SGPR with the VGPR source
8000 // and record the operand for later waterfall loop generation.
8001 if (I->getOpcode() == AMDGPU::SI_CALL_ISEL) {
8002 MachineInstr *UseMI = &*I;
8003 for (unsigned i = 0; i < UseMI->getNumOperands(); ++i) {
8004 if (UseMI->getOperand(i).isReg() &&
8005 UseMI->getOperand(i).getReg() == DstReg) {
8006 MachineOperand *MO = &UseMI->getOperand(i);
8007 MO->setReg(SrcReg);
8008 V2PhysSCopyInfo &V2SCopyInfo = WaterFalls[UseMI];
8009 V2SCopyInfo.MOs.push_back(MO);
8010 V2SCopyInfo.SGPRs.push_back(DstReg);
8011 V2SPhyCopiesToErase.try_emplace(&Inst, true);
8012 }
8013 }
8014 } else if (I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG &&
8015 I->getOperand(0).isReg() &&
8016 I->getOperand(0).getReg() == DstReg) {
8017 createReadFirstLaneFromCopyToPhysReg(MRI, DstReg, Inst);
8018 V2SPhyCopiesToErase.try_emplace(&Inst, true);
8019 } else if (I->readsRegister(DstReg, &RI)) {
8020 // COPY cannot be erased if other type of inst uses it.
8021 V2SPhyCopiesToErase[&Inst] = false;
8022 }
8023 if (I->findRegisterDefOperand(DstReg, &RI))
8024 break;
8025 }
8026}
8027
8029 SIInstrWorklist &Worklist, MachineDominatorTree *MDT, MachineInstr &Inst,
8031 DenseMap<MachineInstr *, bool> &V2SPhyCopiesToErase) const {
8032
8034 if (!MBB)
8035 return;
8036 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8037 unsigned Opcode = Inst.getOpcode();
8038 unsigned NewOpcode = getVALUOp(Inst);
8039 const DebugLoc &DL = Inst.getDebugLoc();
8040
8041 // Handle some special cases
8042 switch (Opcode) {
8043 default:
8044 break;
8045 case AMDGPU::S_ADD_I32:
8046 case AMDGPU::S_SUB_I32: {
8047 // FIXME: The u32 versions currently selected use the carry.
8048 bool Changed;
8049 MachineBasicBlock *CreatedBBTmp = nullptr;
8050 std::tie(Changed, CreatedBBTmp) = moveScalarAddSub(Worklist, Inst, MDT);
8051 if (Changed)
8052 return;
8053
8054 // Default handling
8055 break;
8056 }
8057
8058 case AMDGPU::S_MUL_U64:
8059 if (ST.hasVMulU64Inst()) {
8060 NewOpcode = AMDGPU::V_MUL_U64_e64;
8061 break;
8062 }
8063 // Split s_mul_u64 in 32-bit vector multiplications.
8064 splitScalarSMulU64(Worklist, Inst, MDT);
8065 Inst.eraseFromParent();
8066 return;
8067
8068 case AMDGPU::S_MUL_U64_U32_PSEUDO:
8069 case AMDGPU::S_MUL_I64_I32_PSEUDO:
8070 // This is a special case of s_mul_u64 where all the operands are either
8071 // zero extended or sign extended.
8072 splitScalarSMulPseudo(Worklist, Inst, MDT);
8073 Inst.eraseFromParent();
8074 return;
8075
8076 case AMDGPU::S_AND_B64:
8077 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32, MDT);
8078 Inst.eraseFromParent();
8079 return;
8080
8081 case AMDGPU::S_OR_B64:
8082 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32, MDT);
8083 Inst.eraseFromParent();
8084 return;
8085
8086 case AMDGPU::S_XOR_B64:
8087 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32, MDT);
8088 Inst.eraseFromParent();
8089 return;
8090
8091 case AMDGPU::S_NAND_B64:
8092 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NAND_B32, MDT);
8093 Inst.eraseFromParent();
8094 return;
8095
8096 case AMDGPU::S_NOR_B64:
8097 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NOR_B32, MDT);
8098 Inst.eraseFromParent();
8099 return;
8100
8101 case AMDGPU::S_XNOR_B64:
8102 if (ST.hasDLInsts())
8103 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
8104 else
8105 splitScalar64BitXnor(Worklist, Inst, MDT);
8106 Inst.eraseFromParent();
8107 return;
8108
8109 case AMDGPU::S_ANDN2_B64:
8110 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ANDN2_B32, MDT);
8111 Inst.eraseFromParent();
8112 return;
8113
8114 case AMDGPU::S_ORN2_B64:
8115 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ORN2_B32, MDT);
8116 Inst.eraseFromParent();
8117 return;
8118
8119 case AMDGPU::S_BREV_B64:
8120 splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_BREV_B32, true);
8121 Inst.eraseFromParent();
8122 return;
8123
8124 case AMDGPU::S_NOT_B64:
8125 splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
8126 Inst.eraseFromParent();
8127 return;
8128
8129 case AMDGPU::S_BCNT1_I32_B64:
8130 splitScalar64BitBCNT(Worklist, Inst);
8131 Inst.eraseFromParent();
8132 return;
8133
8134 case AMDGPU::S_BFE_I64:
8135 splitScalar64BitBFE(Worklist, Inst);
8136 Inst.eraseFromParent();
8137 return;
8138
8139 case AMDGPU::S_FLBIT_I32_B64:
8140 splitScalar64BitCountOp(Worklist, Inst, AMDGPU::V_FFBH_U32_e32);
8141 Inst.eraseFromParent();
8142 return;
8143 case AMDGPU::S_FF1_I32_B64:
8144 splitScalar64BitCountOp(Worklist, Inst, AMDGPU::V_FFBL_B32_e32);
8145 Inst.eraseFromParent();
8146 return;
8147
8148 case AMDGPU::S_LSHL_B32:
8149 if (ST.hasOnlyRevVALUShifts()) {
8150 NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
8151 swapOperands(Inst);
8152 }
8153 break;
8154 case AMDGPU::S_ASHR_I32:
8155 if (ST.hasOnlyRevVALUShifts()) {
8156 NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
8157 swapOperands(Inst);
8158 }
8159 break;
8160 case AMDGPU::S_LSHR_B32:
8161 if (ST.hasOnlyRevVALUShifts()) {
8162 NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
8163 swapOperands(Inst);
8164 }
8165 break;
8166 case AMDGPU::S_LSHL_B64:
8167 if (ST.hasOnlyRevVALUShifts()) {
8168 NewOpcode = ST.getGeneration() >= AMDGPUSubtarget::GFX12
8169 ? AMDGPU::V_LSHLREV_B64_pseudo_e64
8170 : AMDGPU::V_LSHLREV_B64_e64;
8171 swapOperands(Inst);
8172 }
8173 break;
8174 case AMDGPU::S_ASHR_I64:
8175 if (ST.hasOnlyRevVALUShifts()) {
8176 NewOpcode = AMDGPU::V_ASHRREV_I64_e64;
8177 swapOperands(Inst);
8178 }
8179 break;
8180 case AMDGPU::S_LSHR_B64:
8181 if (ST.hasOnlyRevVALUShifts()) {
8182 NewOpcode = AMDGPU::V_LSHRREV_B64_e64;
8183 swapOperands(Inst);
8184 }
8185 break;
8186
8187 case AMDGPU::S_ABS_I32:
8188 lowerScalarAbs(Worklist, Inst);
8189 Inst.eraseFromParent();
8190 return;
8191
8192 case AMDGPU::S_ABSDIFF_I32:
8193 lowerScalarAbsDiff(Worklist, Inst);
8194 Inst.eraseFromParent();
8195 return;
8196
8197 case AMDGPU::S_CBRANCH_SCC0:
8198 case AMDGPU::S_CBRANCH_SCC1: {
8199 // Clear unused bits of vcc
8200 Register CondReg = Inst.getOperand(1).getReg();
8201 bool IsSCC = CondReg == AMDGPU::SCC;
8203 BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(LMC.AndOpc), LMC.VccReg)
8204 .addReg(LMC.ExecReg)
8205 .addReg(IsSCC ? LMC.VccReg : CondReg);
8206 Inst.removeOperand(1);
8207 } break;
8208
8209 case AMDGPU::S_BFE_U64:
8210 case AMDGPU::S_BFM_B64:
8211 llvm_unreachable("Moving this op to VALU not implemented");
8212
8213 case AMDGPU::S_PACK_LL_B32_B16:
8214 case AMDGPU::S_PACK_LH_B32_B16:
8215 case AMDGPU::S_PACK_HL_B32_B16:
8216 case AMDGPU::S_PACK_HH_B32_B16:
8217 movePackToVALU(Worklist, MRI, Inst);
8218 Inst.eraseFromParent();
8219 return;
8220
8221 case AMDGPU::S_XNOR_B32:
8222 lowerScalarXnor(Worklist, Inst);
8223 Inst.eraseFromParent();
8224 return;
8225
8226 case AMDGPU::S_NAND_B32:
8227 splitScalarNotBinop(Worklist, Inst, AMDGPU::S_AND_B32);
8228 Inst.eraseFromParent();
8229 return;
8230
8231 case AMDGPU::S_NOR_B32:
8232 splitScalarNotBinop(Worklist, Inst, AMDGPU::S_OR_B32);
8233 Inst.eraseFromParent();
8234 return;
8235
8236 case AMDGPU::S_ANDN2_B32:
8237 splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_AND_B32);
8238 Inst.eraseFromParent();
8239 return;
8240
8241 case AMDGPU::S_ORN2_B32:
8242 splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_OR_B32);
8243 Inst.eraseFromParent();
8244 return;
8245
8246 // TODO: remove as soon as everything is ready
8247 // to replace VGPR to SGPR copy with V_READFIRSTLANEs.
8248 // S_ADD/SUB_CO_PSEUDO as well as S_UADDO/USUBO_PSEUDO
8249 // can only be selected from the uniform SDNode.
8250 case AMDGPU::S_ADD_CO_PSEUDO:
8251 case AMDGPU::S_SUB_CO_PSEUDO: {
8252 unsigned Opc = (Inst.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
8253 ? AMDGPU::V_ADDC_U32_e64
8254 : AMDGPU::V_SUBB_U32_e64;
8255 const auto *CarryRC = RI.getWaveMaskRegClass();
8256
8257 Register CarryInReg = Inst.getOperand(4).getReg();
8258 if (!MRI.constrainRegClass(CarryInReg, CarryRC)) {
8259 Register NewCarryReg = MRI.createVirtualRegister(CarryRC);
8260 BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::COPY), NewCarryReg)
8261 .addReg(CarryInReg);
8262 }
8263
8264 Register CarryOutReg = Inst.getOperand(1).getReg();
8265
8266 Register DestReg = MRI.createVirtualRegister(RI.getEquivalentVGPRClass(
8267 MRI.getRegClass(Inst.getOperand(0).getReg())));
8268 MachineInstr *CarryOp =
8269 BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(Opc), DestReg)
8270 .addReg(CarryOutReg, RegState::Define)
8271 .add(Inst.getOperand(2))
8272 .add(Inst.getOperand(3))
8273 .addReg(CarryInReg)
8274 .addImm(0);
8275 legalizeOperands(*CarryOp);
8276 MRI.replaceRegWith(Inst.getOperand(0).getReg(), DestReg);
8277 addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
8278 Inst.eraseFromParent();
8279 }
8280 return;
8281 case AMDGPU::S_UADDO_PSEUDO:
8282 case AMDGPU::S_USUBO_PSEUDO: {
8283 MachineOperand &Dest0 = Inst.getOperand(0);
8284 MachineOperand &Dest1 = Inst.getOperand(1);
8285 MachineOperand &Src0 = Inst.getOperand(2);
8286 MachineOperand &Src1 = Inst.getOperand(3);
8287
8288 unsigned Opc = (Inst.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
8289 ? AMDGPU::V_ADD_CO_U32_e64
8290 : AMDGPU::V_SUB_CO_U32_e64;
8291 const TargetRegisterClass *NewRC =
8292 RI.getEquivalentVGPRClass(MRI.getRegClass(Dest0.getReg()));
8293 Register DestReg = MRI.createVirtualRegister(NewRC);
8294 MachineInstr *NewInstr = BuildMI(*MBB, &Inst, DL, get(Opc), DestReg)
8295 .addReg(Dest1.getReg(), RegState::Define)
8296 .add(Src0)
8297 .add(Src1)
8298 .addImm(0); // clamp bit
8299
8300 legalizeOperands(*NewInstr, MDT);
8301 MRI.replaceRegWith(Dest0.getReg(), DestReg);
8302 addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
8303 Inst.eraseFromParent();
8304 }
8305 return;
8306 case AMDGPU::S_LSHL1_ADD_U32:
8307 case AMDGPU::S_LSHL2_ADD_U32:
8308 case AMDGPU::S_LSHL3_ADD_U32:
8309 case AMDGPU::S_LSHL4_ADD_U32: {
8310 MachineOperand &Dest = Inst.getOperand(0);
8311 MachineOperand &Src0 = Inst.getOperand(1);
8312 MachineOperand &Src1 = Inst.getOperand(2);
8313 unsigned ShiftAmt = (Opcode == AMDGPU::S_LSHL1_ADD_U32 ? 1
8314 : Opcode == AMDGPU::S_LSHL2_ADD_U32 ? 2
8315 : Opcode == AMDGPU::S_LSHL3_ADD_U32 ? 3
8316 : 4);
8317
8318 const TargetRegisterClass *NewRC =
8319 RI.getEquivalentVGPRClass(MRI.getRegClass(Dest.getReg()));
8320 Register DestReg = MRI.createVirtualRegister(NewRC);
8321 MachineInstr *NewInstr =
8322 BuildMI(*MBB, &Inst, DL, get(AMDGPU::V_LSHL_ADD_U32_e64), DestReg)
8323 .add(Src0)
8324 .addImm(ShiftAmt)
8325 .add(Src1);
8326
8327 legalizeOperands(*NewInstr, MDT);
8328 MRI.replaceRegWith(Dest.getReg(), DestReg);
8329 addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
8330 Inst.eraseFromParent();
8331 }
8332 return;
8333 case AMDGPU::S_CSELECT_B32:
8334 case AMDGPU::S_CSELECT_B64:
8335 lowerSelect(Worklist, Inst, MDT);
8336 Inst.eraseFromParent();
8337 return;
8338 case AMDGPU::S_CMP_EQ_I32:
8339 case AMDGPU::S_CMP_LG_I32:
8340 case AMDGPU::S_CMP_GT_I32:
8341 case AMDGPU::S_CMP_GE_I32:
8342 case AMDGPU::S_CMP_LT_I32:
8343 case AMDGPU::S_CMP_LE_I32:
8344 case AMDGPU::S_CMP_EQ_U32:
8345 case AMDGPU::S_CMP_LG_U32:
8346 case AMDGPU::S_CMP_GT_U32:
8347 case AMDGPU::S_CMP_GE_U32:
8348 case AMDGPU::S_CMP_LT_U32:
8349 case AMDGPU::S_CMP_LE_U32:
8350 case AMDGPU::S_CMP_EQ_U64:
8351 case AMDGPU::S_CMP_LG_U64:
8352 case AMDGPU::S_CMP_LT_F32:
8353 case AMDGPU::S_CMP_EQ_F32:
8354 case AMDGPU::S_CMP_LE_F32:
8355 case AMDGPU::S_CMP_GT_F32:
8356 case AMDGPU::S_CMP_LG_F32:
8357 case AMDGPU::S_CMP_GE_F32:
8358 case AMDGPU::S_CMP_O_F32:
8359 case AMDGPU::S_CMP_U_F32:
8360 case AMDGPU::S_CMP_NGE_F32:
8361 case AMDGPU::S_CMP_NLG_F32:
8362 case AMDGPU::S_CMP_NGT_F32:
8363 case AMDGPU::S_CMP_NLE_F32:
8364 case AMDGPU::S_CMP_NEQ_F32:
8365 case AMDGPU::S_CMP_NLT_F32: {
8366 Register CondReg = MRI.createVirtualRegister(RI.getWaveMaskRegClass());
8367 auto NewInstr =
8368 BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(NewOpcode), CondReg)
8369 .setMIFlags(Inst.getFlags());
8370 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::src0_modifiers) >=
8371 0) {
8372 NewInstr
8373 .addImm(0) // src0_modifiers
8374 .add(Inst.getOperand(0)) // src0
8375 .addImm(0) // src1_modifiers
8376 .add(Inst.getOperand(1)) // src1
8377 .addImm(0); // clamp
8378 } else {
8379 NewInstr.add(Inst.getOperand(0)).add(Inst.getOperand(1));
8380 }
8381 legalizeOperands(*NewInstr, MDT);
8382 int SCCIdx = Inst.findRegisterDefOperandIdx(AMDGPU::SCC, /*TRI=*/nullptr);
8383 const MachineOperand &SCCOp = Inst.getOperand(SCCIdx);
8384 addSCCDefUsersToVALUWorklist(SCCOp, Inst, Worklist, CondReg);
8385 Inst.eraseFromParent();
8386 return;
8387 }
8388 case AMDGPU::S_CMP_LT_F16:
8389 case AMDGPU::S_CMP_EQ_F16:
8390 case AMDGPU::S_CMP_LE_F16:
8391 case AMDGPU::S_CMP_GT_F16:
8392 case AMDGPU::S_CMP_LG_F16:
8393 case AMDGPU::S_CMP_GE_F16:
8394 case AMDGPU::S_CMP_O_F16:
8395 case AMDGPU::S_CMP_U_F16:
8396 case AMDGPU::S_CMP_NGE_F16:
8397 case AMDGPU::S_CMP_NLG_F16:
8398 case AMDGPU::S_CMP_NGT_F16:
8399 case AMDGPU::S_CMP_NLE_F16:
8400 case AMDGPU::S_CMP_NEQ_F16:
8401 case AMDGPU::S_CMP_NLT_F16: {
8402 Register CondReg = MRI.createVirtualRegister(RI.getWaveMaskRegClass());
8403 auto NewInstr =
8404 BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(NewOpcode), CondReg)
8405 .setMIFlags(Inst.getFlags());
8406 if (AMDGPU::hasNamedOperand(NewOpcode, AMDGPU::OpName::src0_modifiers)) {
8407 NewInstr
8408 .addImm(0) // src0_modifiers
8409 .add(Inst.getOperand(0)) // src0
8410 .addImm(0) // src1_modifiers
8411 .add(Inst.getOperand(1)) // src1
8412 .addImm(0); // clamp
8413 if (AMDGPU::hasNamedOperand(NewOpcode, AMDGPU::OpName::op_sel))
8414 NewInstr.addImm(0); // op_sel0
8415 } else {
8416 NewInstr
8417 .add(Inst.getOperand(0))
8418 .add(Inst.getOperand(1));
8419 }
8420 legalizeOperandsVALUt16(*NewInstr, MRI);
8421 legalizeOperands(*NewInstr, MDT);
8422 int SCCIdx = Inst.findRegisterDefOperandIdx(AMDGPU::SCC, /*TRI=*/nullptr);
8423 const MachineOperand &SCCOp = Inst.getOperand(SCCIdx);
8424 addSCCDefUsersToVALUWorklist(SCCOp, Inst, Worklist, CondReg);
8425 Inst.eraseFromParent();
8426 return;
8427 }
8428 case AMDGPU::S_CVT_HI_F32_F16: {
8429 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8430 Register NewDst = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8431 if (ST.useRealTrue16Insts()) {
8432 BuildMI(*MBB, Inst, DL, get(AMDGPU::COPY), TmpReg)
8433 .add(Inst.getOperand(1));
8434 BuildMI(*MBB, Inst, DL, get(NewOpcode), NewDst)
8435 .addImm(0) // src0_modifiers
8436 .addReg(TmpReg, {}, AMDGPU::hi16)
8437 .addImm(0) // clamp
8438 .addImm(0) // omod
8439 .addImm(0); // op_sel0
8440 } else {
8441 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
8442 .addImm(16)
8443 .add(Inst.getOperand(1));
8444 BuildMI(*MBB, Inst, DL, get(NewOpcode), NewDst)
8445 .addImm(0) // src0_modifiers
8446 .addReg(TmpReg)
8447 .addImm(0) // clamp
8448 .addImm(0); // omod
8449 }
8450
8451 MRI.replaceRegWith(Inst.getOperand(0).getReg(), NewDst);
8452 addUsersToMoveToVALUWorklist(NewDst, MRI, Worklist);
8453 Inst.eraseFromParent();
8454 return;
8455 }
8456 case AMDGPU::S_MINIMUM_F32:
8457 case AMDGPU::S_MAXIMUM_F32: {
8458 Register NewDst = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8459 MachineInstr *NewInstr = BuildMI(*MBB, Inst, DL, get(NewOpcode), NewDst)
8460 .addImm(0) // src0_modifiers
8461 .add(Inst.getOperand(1))
8462 .addImm(0) // src1_modifiers
8463 .add(Inst.getOperand(2))
8464 .addImm(0) // clamp
8465 .addImm(0); // omod
8466 MRI.replaceRegWith(Inst.getOperand(0).getReg(), NewDst);
8467
8468 legalizeOperands(*NewInstr, MDT);
8469 addUsersToMoveToVALUWorklist(NewDst, MRI, Worklist);
8470 Inst.eraseFromParent();
8471 return;
8472 }
8473 case AMDGPU::S_MINIMUM_F16:
8474 case AMDGPU::S_MAXIMUM_F16: {
8475 Register NewDst = MRI.createVirtualRegister(ST.useRealTrue16Insts()
8476 ? &AMDGPU::VGPR_16RegClass
8477 : &AMDGPU::VGPR_32RegClass);
8478 MachineInstr *NewInstr = BuildMI(*MBB, Inst, DL, get(NewOpcode), NewDst)
8479 .addImm(0) // src0_modifiers
8480 .add(Inst.getOperand(1))
8481 .addImm(0) // src1_modifiers
8482 .add(Inst.getOperand(2))
8483 .addImm(0) // clamp
8484 .addImm(0) // omod
8485 .addImm(0); // opsel0
8486 MRI.replaceRegWith(Inst.getOperand(0).getReg(), NewDst);
8487 legalizeOperandsVALUt16(*NewInstr, MRI);
8488 legalizeOperands(*NewInstr, MDT);
8489 addUsersToMoveToVALUWorklist(NewDst, MRI, Worklist);
8490 Inst.eraseFromParent();
8491 return;
8492 }
8493 case AMDGPU::V_S_EXP_F16_e64:
8494 case AMDGPU::V_S_LOG_F16_e64:
8495 case AMDGPU::V_S_RCP_F16_e64:
8496 case AMDGPU::V_S_RSQ_F16_e64:
8497 case AMDGPU::V_S_SQRT_F16_e64: {
8498 Register NewDst = MRI.createVirtualRegister(ST.useRealTrue16Insts()
8499 ? &AMDGPU::VGPR_16RegClass
8500 : &AMDGPU::VGPR_32RegClass);
8501 auto NewInstr = BuildMI(*MBB, Inst, DL, get(NewOpcode), NewDst)
8502 .add(Inst.getOperand(1)) // src0_modifiers
8503 .add(Inst.getOperand(2))
8504 .add(Inst.getOperand(3)) // clamp
8505 .add(Inst.getOperand(4)) // omod
8506 .setMIFlags(Inst.getFlags());
8507 if (AMDGPU::hasNamedOperand(NewOpcode, AMDGPU::OpName::op_sel))
8508 NewInstr.addImm(0); // opsel0
8509 MRI.replaceRegWith(Inst.getOperand(0).getReg(), NewDst);
8510 legalizeOperandsVALUt16(*NewInstr, MRI);
8511 legalizeOperands(*NewInstr, MDT);
8512 addUsersToMoveToVALUWorklist(NewDst, MRI, Worklist);
8513 Inst.eraseFromParent();
8514 return;
8515 }
8516 }
8517
8518 if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
8519 // We cannot move this instruction to the VALU, so we should try to
8520 // legalize its operands instead.
8521 legalizeOperands(Inst, MDT);
8522 return;
8523 }
8524 // Handle converting generic instructions like COPY-to-SGPR into
8525 // COPY-to-VGPR.
8526 if (NewOpcode == Opcode) {
8527 Register DstReg = Inst.getOperand(0).getReg();
8528 const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
8529
8530 if (Inst.isCopy() && DstReg.isPhysical() &&
8531 Inst.getOperand(1).getReg().isVirtual()) {
8532 handleCopyToPhysHelper(Worklist, DstReg, Inst, MRI, WaterFalls,
8533 V2SPhyCopiesToErase);
8534 return;
8535 }
8536
8537 if (Inst.isCopy() && Inst.getOperand(1).getReg().isVirtual()) {
8538 Register NewDstReg = Inst.getOperand(1).getReg();
8539 const TargetRegisterClass *SrcRC = RI.getRegClassForReg(MRI, NewDstReg);
8540 if (const TargetRegisterClass *CommonRC =
8541 RI.getCommonSubClass(NewDstRC, SrcRC)) {
8542 // Instead of creating a copy where src and dst are the same register
8543 // class, we just replace all uses of dst with src. These kinds of
8544 // copies interfere with the heuristics MachineSink uses to decide
8545 // whether or not to split a critical edge. Since the pass assumes
8546 // that copies will end up as machine instructions and not be
8547 // eliminated.
8548 addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
8549 MRI.replaceRegWith(DstReg, NewDstReg);
8550 MRI.clearKillFlags(NewDstReg);
8551 Inst.getOperand(0).setReg(DstReg);
8552
8553 if (!MRI.constrainRegClass(NewDstReg, CommonRC))
8554 llvm_unreachable("failed to constrain register");
8555
8556 Inst.eraseFromParent();
8557
8558 for (MachineOperand &UseMO :
8559 make_early_inc_range(MRI.use_operands(NewDstReg))) {
8560 MachineInstr &UseMI = *UseMO.getParent();
8561
8562 // Legalize t16 operands since replaceReg is called after
8563 // addUsersToVALU.
8565
8566 unsigned OpIdx = UseMI.getOperandNo(&UseMO);
8567 if (const TargetRegisterClass *OpRC =
8568 getRegClass(UseMI.getDesc(), OpIdx))
8569 MRI.constrainRegClass(NewDstReg, OpRC);
8570 }
8571
8572 return;
8573 }
8574 }
8575
8576 // If this is a v2s copy between 16bit and 32bit reg,
8577 // replace vgpr copy to reg_sequence/extract_subreg
8578 // This can be remove after we have sgpr16 in place
8579 if (ST.useRealTrue16Insts() && Inst.isCopy() &&
8580 Inst.getOperand(1).getReg().isVirtual() &&
8581 RI.isVGPR(MRI, Inst.getOperand(1).getReg())) {
8582 const TargetRegisterClass *SrcRegRC = getOpRegClass(Inst, 1);
8583 if (RI.getMatchingSuperRegClass(NewDstRC, SrcRegRC, AMDGPU::lo16)) {
8584 Register NewDstReg = MRI.createVirtualRegister(NewDstRC);
8585 Register Undef = MRI.createVirtualRegister(&AMDGPU::VGPR_16RegClass);
8586 BuildMI(*Inst.getParent(), &Inst, Inst.getDebugLoc(),
8587 get(AMDGPU::IMPLICIT_DEF), Undef);
8588 BuildMI(*Inst.getParent(), &Inst, Inst.getDebugLoc(),
8589 get(AMDGPU::REG_SEQUENCE), NewDstReg)
8590 .addReg(Inst.getOperand(1).getReg())
8591 .addImm(AMDGPU::lo16)
8592 .addReg(Undef)
8593 .addImm(AMDGPU::hi16);
8594 Inst.eraseFromParent();
8595 MRI.replaceRegWith(DstReg, NewDstReg);
8596 addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
8597 return;
8598 } else if (RI.getMatchingSuperRegClass(SrcRegRC, NewDstRC,
8599 AMDGPU::lo16)) {
8600 Inst.getOperand(1).setSubReg(AMDGPU::lo16);
8601 Register NewDstReg = MRI.createVirtualRegister(NewDstRC);
8602 MRI.replaceRegWith(DstReg, NewDstReg);
8603 addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
8604 return;
8605 }
8606 }
8607
8608 Register NewDstReg = MRI.createVirtualRegister(NewDstRC);
8609 MRI.replaceRegWith(DstReg, NewDstReg);
8610 legalizeOperands(Inst, MDT);
8611 addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
8612 return;
8613 }
8614
8615 // Use the new VALU Opcode.
8616 auto NewInstr = BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(NewOpcode))
8617 .setMIFlags(Inst.getFlags());
8618 if (isVOP3(NewOpcode) && !isVOP3(Opcode)) {
8619 // Intersperse VOP3 modifiers among the SALU operands.
8620 NewInstr->addOperand(Inst.getOperand(0));
8621 if (AMDGPU::getNamedOperandIdx(NewOpcode,
8622 AMDGPU::OpName::src0_modifiers) >= 0)
8623 NewInstr.addImm(0);
8624 if (AMDGPU::hasNamedOperand(NewOpcode, AMDGPU::OpName::src0)) {
8625 const MachineOperand &Src = Inst.getOperand(1);
8626 NewInstr->addOperand(Src);
8627 }
8628
8629 if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
8630 // We are converting these to a BFE, so we need to add the missing
8631 // operands for the size and offset.
8632 unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
8633 NewInstr.addImm(0);
8634 NewInstr.addImm(Size);
8635 } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
8636 // The VALU version adds the second operand to the result, so insert an
8637 // extra 0 operand.
8638 NewInstr.addImm(0);
8639 } else if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
8640 const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
8641 // If we need to move this to VGPRs, we need to unpack the second
8642 // operand back into the 2 separate ones for bit offset and width.
8643 assert(OffsetWidthOp.isImm() &&
8644 "Scalar BFE is only implemented for constant width and offset");
8645 uint32_t Imm = OffsetWidthOp.getImm();
8646
8647 uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
8648 uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
8649 NewInstr.addImm(Offset);
8650 NewInstr.addImm(BitWidth);
8651 } else {
8652 if (AMDGPU::getNamedOperandIdx(NewOpcode,
8653 AMDGPU::OpName::src1_modifiers) >= 0)
8654 NewInstr.addImm(0);
8655 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::src1) >= 0)
8656 NewInstr->addOperand(Inst.getOperand(2));
8657 if (AMDGPU::getNamedOperandIdx(NewOpcode,
8658 AMDGPU::OpName::src2_modifiers) >= 0)
8659 NewInstr.addImm(0);
8660 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::src2) >= 0)
8661 NewInstr->addOperand(Inst.getOperand(3));
8662 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::clamp) >= 0)
8663 NewInstr.addImm(0);
8664 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::omod) >= 0)
8665 NewInstr.addImm(0);
8666 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::op_sel) >= 0)
8667 NewInstr.addImm(0);
8668 }
8669 } else {
8670 // Just copy the SALU operands.
8671 for (const MachineOperand &Op : Inst.explicit_operands())
8672 NewInstr->addOperand(Op);
8673 }
8674
8675 // Remove any references to SCC. Vector instructions can't read from it, and
8676 // We're just about to add the implicit use / defs of VCC, and we don't want
8677 // both.
8678 for (MachineOperand &Op : Inst.implicit_operands()) {
8679 if (Op.getReg() == AMDGPU::SCC) {
8680 // Only propagate through live-def of SCC.
8681 if (Op.isDef() && !Op.isDead())
8682 addSCCDefUsersToVALUWorklist(Op, Inst, Worklist);
8683 if (Op.isUse())
8684 addSCCDefsToVALUWorklist(NewInstr, Worklist);
8685 }
8686 }
8687 Inst.eraseFromParent();
8688 Register NewDstReg;
8689 if (NewInstr->getOperand(0).isReg() && NewInstr->getOperand(0).isDef()) {
8690 Register DstReg = NewInstr->getOperand(0).getReg();
8691 assert(DstReg.isVirtual());
8692 // Update the destination register class.
8693 const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(*NewInstr);
8694 assert(NewDstRC);
8695 NewDstReg = MRI.createVirtualRegister(NewDstRC);
8696 MRI.replaceRegWith(DstReg, NewDstReg);
8697 }
8698 fixImplicitOperands(*NewInstr);
8699
8700 legalizeOperandsVALUt16(*NewInstr, MRI);
8701
8702 // Legalize the operands
8703 legalizeOperands(*NewInstr, MDT);
8704 if (NewDstReg)
8705 addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
8706}
8707
8708// Add/sub require special handling to deal with carry outs.
8709std::pair<bool, MachineBasicBlock *>
8710SIInstrInfo::moveScalarAddSub(SIInstrWorklist &Worklist, MachineInstr &Inst,
8711 MachineDominatorTree *MDT) const {
8712 if (ST.hasAddNoCarryInsts()) {
8713 // Assume there is no user of scc since we don't select this in that case.
8714 // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
8715 // is used.
8716
8717 MachineBasicBlock &MBB = *Inst.getParent();
8718 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8719
8720 Register OldDstReg = Inst.getOperand(0).getReg();
8721 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8722
8723 unsigned Opc = Inst.getOpcode();
8724 assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
8725
8726 unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
8727 AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
8728
8729 assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
8730 Inst.removeOperand(3);
8731
8732 Inst.setDesc(get(NewOpc));
8733 Inst.addOperand(MachineOperand::CreateImm(0)); // clamp bit
8734 Inst.addImplicitDefUseOperands(*MBB.getParent());
8735 MRI.replaceRegWith(OldDstReg, ResultReg);
8736 MachineBasicBlock *NewBB = legalizeOperands(Inst, MDT);
8737
8738 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
8739 return std::pair(true, NewBB);
8740 }
8741
8742 return std::pair(false, nullptr);
8743}
8744
8745void SIInstrInfo::lowerSelect(SIInstrWorklist &Worklist, MachineInstr &Inst,
8746 MachineDominatorTree *MDT) const {
8747
8748 MachineBasicBlock &MBB = *Inst.getParent();
8749 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8750 MachineBasicBlock::iterator MII = Inst;
8751 const DebugLoc &DL = Inst.getDebugLoc();
8752
8753 MachineOperand &Dest = Inst.getOperand(0);
8754 MachineOperand &Src0 = Inst.getOperand(1);
8755 MachineOperand &Src1 = Inst.getOperand(2);
8756 MachineOperand &Cond = Inst.getOperand(3);
8757
8758 Register CondReg = Cond.getReg();
8759 bool IsSCC = (CondReg == AMDGPU::SCC);
8760
8761 // If this is a trivial select where the condition is effectively not SCC
8762 // (CondReg is a source of copy to SCC), then the select is semantically
8763 // equivalent to copying CondReg. Hence, there is no need to create
8764 // V_CNDMASK, we can just use that and bail out.
8765 if (!IsSCC && Src0.isImm() && (Src0.getImm() == -1) && Src1.isImm() &&
8766 (Src1.getImm() == 0)) {
8767 MRI.replaceRegWith(Dest.getReg(), CondReg);
8768 return;
8769 }
8770
8771 Register NewCondReg = CondReg;
8772 if (IsSCC) {
8773 const TargetRegisterClass *TC = RI.getWaveMaskRegClass();
8774 NewCondReg = MRI.createVirtualRegister(TC);
8775
8776 // Now look for the closest SCC def if it is a copy
8777 // replacing the CondReg with the COPY source register
8778 bool CopyFound = false;
8779 for (MachineInstr &CandI :
8781 Inst.getParent()->rend())) {
8782 if (CandI.findRegisterDefOperandIdx(AMDGPU::SCC, &RI, false, false) !=
8783 -1) {
8784 if (CandI.isCopy() && CandI.getOperand(0).getReg() == AMDGPU::SCC) {
8785 BuildMI(MBB, MII, DL, get(AMDGPU::COPY), NewCondReg)
8786 .addReg(CandI.getOperand(1).getReg());
8787 CopyFound = true;
8788 }
8789 break;
8790 }
8791 }
8792 if (!CopyFound) {
8793 // SCC def is not a copy
8794 // Insert a trivial select instead of creating a copy, because a copy from
8795 // SCC would semantically mean just copying a single bit, but we may need
8796 // the result to be a vector condition mask that needs preserving.
8797 unsigned Opcode =
8798 ST.isWave64() ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
8799 auto NewSelect =
8800 BuildMI(MBB, MII, DL, get(Opcode), NewCondReg).addImm(-1).addImm(0);
8801 NewSelect->getOperand(3).setIsUndef(Cond.isUndef());
8802 }
8803 }
8804
8805 Register NewDestReg = MRI.createVirtualRegister(
8806 RI.getEquivalentVGPRClass(MRI.getRegClass(Dest.getReg())));
8807 MachineInstr *NewInst;
8808 if (Inst.getOpcode() == AMDGPU::S_CSELECT_B32) {
8809 NewInst = BuildMI(MBB, MII, DL, get(AMDGPU::V_CNDMASK_B32_e64), NewDestReg)
8810 .addImm(0)
8811 .add(Src1) // False
8812 .addImm(0)
8813 .add(Src0) // True
8814 .addReg(NewCondReg);
8815 } else {
8816 NewInst =
8817 BuildMI(MBB, MII, DL, get(AMDGPU::V_CNDMASK_B64_PSEUDO), NewDestReg)
8818 .add(Src1) // False
8819 .add(Src0) // True
8820 .addReg(NewCondReg);
8821 }
8822 MRI.replaceRegWith(Dest.getReg(), NewDestReg);
8823 legalizeOperands(*NewInst, MDT);
8824 addUsersToMoveToVALUWorklist(NewDestReg, MRI, Worklist);
8825}
8826
8827void SIInstrInfo::lowerScalarAbs(SIInstrWorklist &Worklist,
8828 MachineInstr &Inst) const {
8829 MachineBasicBlock &MBB = *Inst.getParent();
8830 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8831 MachineBasicBlock::iterator MII = Inst;
8832 const DebugLoc &DL = Inst.getDebugLoc();
8833
8834 MachineOperand &Dest = Inst.getOperand(0);
8835 MachineOperand &Src = Inst.getOperand(1);
8836 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8837 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8838
8839 unsigned SubOp = ST.hasAddNoCarryInsts() ? AMDGPU::V_SUB_U32_e32
8840 : AMDGPU::V_SUB_CO_U32_e32;
8841
8842 BuildMI(MBB, MII, DL, get(SubOp), TmpReg)
8843 .addImm(0)
8844 .addReg(Src.getReg());
8845
8846 BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
8847 .addReg(Src.getReg())
8848 .addReg(TmpReg);
8849
8850 MRI.replaceRegWith(Dest.getReg(), ResultReg);
8851 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
8852}
8853
8854void SIInstrInfo::lowerScalarAbsDiff(SIInstrWorklist &Worklist,
8855 MachineInstr &Inst) const {
8856 MachineBasicBlock &MBB = *Inst.getParent();
8857 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8858 MachineBasicBlock::iterator MII = Inst;
8859 const DebugLoc &DL = Inst.getDebugLoc();
8860
8861 MachineOperand &Dest = Inst.getOperand(0);
8862 MachineOperand &Src1 = Inst.getOperand(1);
8863 MachineOperand &Src2 = Inst.getOperand(2);
8864 Register SubResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8865 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8866 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8867
8868 unsigned SubOp = ST.hasAddNoCarryInsts() ? AMDGPU::V_SUB_U32_e32
8869 : AMDGPU::V_SUB_CO_U32_e32;
8870
8871 BuildMI(MBB, MII, DL, get(SubOp), SubResultReg)
8872 .addReg(Src1.getReg())
8873 .addReg(Src2.getReg());
8874
8875 BuildMI(MBB, MII, DL, get(SubOp), TmpReg).addImm(0).addReg(SubResultReg);
8876
8877 BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
8878 .addReg(SubResultReg)
8879 .addReg(TmpReg);
8880
8881 MRI.replaceRegWith(Dest.getReg(), ResultReg);
8882 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
8883}
8884
8885void SIInstrInfo::lowerScalarXnor(SIInstrWorklist &Worklist,
8886 MachineInstr &Inst) const {
8887 MachineBasicBlock &MBB = *Inst.getParent();
8888 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8889 MachineBasicBlock::iterator MII = Inst;
8890 const DebugLoc &DL = Inst.getDebugLoc();
8891
8892 MachineOperand &Dest = Inst.getOperand(0);
8893 MachineOperand &Src0 = Inst.getOperand(1);
8894 MachineOperand &Src1 = Inst.getOperand(2);
8895
8896 if (ST.hasDLInsts()) {
8897 Register NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8898 legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
8899 legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
8900
8901 BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
8902 .add(Src0)
8903 .add(Src1);
8904
8905 MRI.replaceRegWith(Dest.getReg(), NewDest);
8906 addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
8907 } else {
8908 // Using the identity !(x ^ y) == (!x ^ y) == (x ^ !y), we can
8909 // invert either source and then perform the XOR. If either source is a
8910 // scalar register, then we can leave the inversion on the scalar unit to
8911 // achieve a better distribution of scalar and vector instructions.
8912 bool Src0IsSGPR = Src0.isReg() &&
8913 RI.isSGPRClass(MRI.getRegClass(Src0.getReg()));
8914 bool Src1IsSGPR = Src1.isReg() &&
8915 RI.isSGPRClass(MRI.getRegClass(Src1.getReg()));
8916 MachineInstr *Xor;
8917 Register Temp = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
8918 Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
8919
8920 // Build a pair of scalar instructions and add them to the work list.
8921 // The next iteration over the work list will lower these to the vector
8922 // unit as necessary.
8923 if (Src0IsSGPR) {
8924 BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src0);
8925 Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
8926 .addReg(Temp)
8927 .add(Src1);
8928 } else if (Src1IsSGPR) {
8929 BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src1);
8930 Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
8931 .add(Src0)
8932 .addReg(Temp);
8933 } else {
8934 Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), Temp)
8935 .add(Src0)
8936 .add(Src1);
8937 MachineInstr *Not =
8938 BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest).addReg(Temp);
8939 Worklist.insert(Not);
8940 }
8941
8942 MRI.replaceRegWith(Dest.getReg(), NewDest);
8943
8944 Worklist.insert(Xor);
8945
8946 addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
8947 }
8948}
8949
8950void SIInstrInfo::splitScalarNotBinop(SIInstrWorklist &Worklist,
8951 MachineInstr &Inst,
8952 unsigned Opcode) const {
8953 MachineBasicBlock &MBB = *Inst.getParent();
8954 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8955 MachineBasicBlock::iterator MII = Inst;
8956 const DebugLoc &DL = Inst.getDebugLoc();
8957
8958 MachineOperand &Dest = Inst.getOperand(0);
8959 MachineOperand &Src0 = Inst.getOperand(1);
8960 MachineOperand &Src1 = Inst.getOperand(2);
8961
8962 Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
8963 Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
8964
8965 MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), Interm)
8966 .add(Src0)
8967 .add(Src1);
8968
8969 MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
8970 .addReg(Interm);
8971
8972 Worklist.insert(&Op);
8973 Worklist.insert(&Not);
8974
8975 MRI.replaceRegWith(Dest.getReg(), NewDest);
8976 addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
8977}
8978
8979void SIInstrInfo::splitScalarBinOpN2(SIInstrWorklist &Worklist,
8980 MachineInstr &Inst,
8981 unsigned Opcode) const {
8982 MachineBasicBlock &MBB = *Inst.getParent();
8983 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8984 MachineBasicBlock::iterator MII = Inst;
8985 const DebugLoc &DL = Inst.getDebugLoc();
8986
8987 MachineOperand &Dest = Inst.getOperand(0);
8988 MachineOperand &Src0 = Inst.getOperand(1);
8989 MachineOperand &Src1 = Inst.getOperand(2);
8990
8991 Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
8992 Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
8993
8994 MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Interm)
8995 .add(Src1);
8996
8997 MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), NewDest)
8998 .add(Src0)
8999 .addReg(Interm);
9000
9001 Worklist.insert(&Not);
9002 Worklist.insert(&Op);
9003
9004 MRI.replaceRegWith(Dest.getReg(), NewDest);
9005 addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
9006}
9007
9008void SIInstrInfo::splitScalar64BitUnaryOp(SIInstrWorklist &Worklist,
9009 MachineInstr &Inst, unsigned Opcode,
9010 bool Swap) const {
9011 MachineBasicBlock &MBB = *Inst.getParent();
9012 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9013
9014 MachineOperand &Dest = Inst.getOperand(0);
9015 MachineOperand &Src0 = Inst.getOperand(1);
9016 const DebugLoc &DL = Inst.getDebugLoc();
9017
9018 MachineBasicBlock::iterator MII = Inst;
9019
9020 const MCInstrDesc &InstDesc = get(Opcode);
9021 const TargetRegisterClass *Src0RC = Src0.isReg() ?
9022 MRI.getRegClass(Src0.getReg()) :
9023 &AMDGPU::SGPR_32RegClass;
9024
9025 const TargetRegisterClass *Src0SubRC =
9026 RI.getSubRegisterClass(Src0RC, AMDGPU::sub0);
9027
9028 MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
9029 AMDGPU::sub0, Src0SubRC);
9030
9031 const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
9032 const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
9033 const TargetRegisterClass *NewDestSubRC =
9034 RI.getSubRegisterClass(NewDestRC, AMDGPU::sub0);
9035
9036 Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
9037 MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
9038
9039 MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
9040 AMDGPU::sub1, Src0SubRC);
9041
9042 Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
9043 MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
9044
9045 if (Swap)
9046 std::swap(DestSub0, DestSub1);
9047
9048 Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
9049 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
9050 .addReg(DestSub0)
9051 .addImm(AMDGPU::sub0)
9052 .addReg(DestSub1)
9053 .addImm(AMDGPU::sub1);
9054
9055 MRI.replaceRegWith(Dest.getReg(), FullDestReg);
9056
9057 Worklist.insert(&LoHalf);
9058 Worklist.insert(&HiHalf);
9059
9060 // We don't need to legalizeOperands here because for a single operand, src0
9061 // will support any kind of input.
9062
9063 // Move all users of this moved value.
9064 addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
9065}
9066
9067// There is not a vector equivalent of s_mul_u64. For this reason, we need to
9068// split the s_mul_u64 in 32-bit vector multiplications.
9069void SIInstrInfo::splitScalarSMulU64(SIInstrWorklist &Worklist,
9070 MachineInstr &Inst,
9071 MachineDominatorTree *MDT) const {
9072 MachineBasicBlock &MBB = *Inst.getParent();
9073 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9074
9075 Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
9076 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9077 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9078
9079 MachineOperand &Dest = Inst.getOperand(0);
9080 MachineOperand &Src0 = Inst.getOperand(1);
9081 MachineOperand &Src1 = Inst.getOperand(2);
9082 const DebugLoc &DL = Inst.getDebugLoc();
9083 MachineBasicBlock::iterator MII = Inst;
9084
9085 const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
9086 const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
9087 const TargetRegisterClass *Src0SubRC =
9088 RI.getSubRegisterClass(Src0RC, AMDGPU::sub0);
9089 if (RI.isSGPRClass(Src0SubRC))
9090 Src0SubRC = RI.getEquivalentVGPRClass(Src0SubRC);
9091 const TargetRegisterClass *Src1SubRC =
9092 RI.getSubRegisterClass(Src1RC, AMDGPU::sub0);
9093 if (RI.isSGPRClass(Src1SubRC))
9094 Src1SubRC = RI.getEquivalentVGPRClass(Src1SubRC);
9095
9096 // First, we extract the low 32-bit and high 32-bit values from each of the
9097 // operands.
9098 MachineOperand Op0L =
9099 buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
9100 MachineOperand Op1L =
9101 buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
9102 MachineOperand Op0H =
9103 buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
9104 MachineOperand Op1H =
9105 buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
9106
9107 // The multilication is done as follows:
9108 //
9109 // Op1H Op1L
9110 // * Op0H Op0L
9111 // --------------------
9112 // Op1H*Op0L Op1L*Op0L
9113 // + Op1H*Op0H Op1L*Op0H
9114 // -----------------------------------------
9115 // (Op1H*Op0L + Op1L*Op0H + carry) Op1L*Op0L
9116 //
9117 // We drop Op1H*Op0H because the result of the multiplication is a 64-bit
9118 // value and that would overflow.
9119 // The low 32-bit value is Op1L*Op0L.
9120 // The high 32-bit value is Op1H*Op0L + Op1L*Op0H + carry (from Op1L*Op0L).
9121
9122 Register Op1L_Op0H_Reg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9123 MachineInstr *Op1L_Op0H =
9124 BuildMI(MBB, MII, DL, get(AMDGPU::V_MUL_LO_U32_e64), Op1L_Op0H_Reg)
9125 .add(Op1L)
9126 .add(Op0H);
9127
9128 Register Op1H_Op0L_Reg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9129 MachineInstr *Op1H_Op0L =
9130 BuildMI(MBB, MII, DL, get(AMDGPU::V_MUL_LO_U32_e64), Op1H_Op0L_Reg)
9131 .add(Op1H)
9132 .add(Op0L);
9133
9134 Register CarryReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9135 MachineInstr *Carry =
9136 BuildMI(MBB, MII, DL, get(AMDGPU::V_MUL_HI_U32_e64), CarryReg)
9137 .add(Op1L)
9138 .add(Op0L);
9139
9140 MachineInstr *LoHalf =
9141 BuildMI(MBB, MII, DL, get(AMDGPU::V_MUL_LO_U32_e64), DestSub0)
9142 .add(Op1L)
9143 .add(Op0L);
9144
9145 Register AddReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9146 MachineInstr *Add = BuildMI(MBB, MII, DL, get(AMDGPU::V_ADD_U32_e32), AddReg)
9147 .addReg(Op1L_Op0H_Reg)
9148 .addReg(Op1H_Op0L_Reg);
9149
9150 MachineInstr *HiHalf =
9151 BuildMI(MBB, MII, DL, get(AMDGPU::V_ADD_U32_e32), DestSub1)
9152 .addReg(AddReg)
9153 .addReg(CarryReg);
9154
9155 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
9156 .addReg(DestSub0)
9157 .addImm(AMDGPU::sub0)
9158 .addReg(DestSub1)
9159 .addImm(AMDGPU::sub1);
9160
9161 MRI.replaceRegWith(Dest.getReg(), FullDestReg);
9162
9163 // Try to legalize the operands in case we need to swap the order to keep it
9164 // valid.
9165 legalizeOperands(*Op1L_Op0H, MDT);
9166 legalizeOperands(*Op1H_Op0L, MDT);
9167 legalizeOperands(*Carry, MDT);
9168 legalizeOperands(*LoHalf, MDT);
9169 legalizeOperands(*Add, MDT);
9170 legalizeOperands(*HiHalf, MDT);
9171
9172 // Move all users of this moved value.
9173 addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
9174}
9175
9176// Lower S_MUL_U64_U32_PSEUDO/S_MUL_I64_I32_PSEUDO in two 32-bit vector
9177// multiplications.
9178void SIInstrInfo::splitScalarSMulPseudo(SIInstrWorklist &Worklist,
9179 MachineInstr &Inst,
9180 MachineDominatorTree *MDT) const {
9181 MachineBasicBlock &MBB = *Inst.getParent();
9182 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9183
9184 Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
9185 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9186 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9187
9188 MachineOperand &Dest = Inst.getOperand(0);
9189 MachineOperand &Src0 = Inst.getOperand(1);
9190 MachineOperand &Src1 = Inst.getOperand(2);
9191 const DebugLoc &DL = Inst.getDebugLoc();
9192 MachineBasicBlock::iterator MII = Inst;
9193
9194 const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
9195 const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
9196 const TargetRegisterClass *Src0SubRC =
9197 RI.getSubRegisterClass(Src0RC, AMDGPU::sub0);
9198 if (RI.isSGPRClass(Src0SubRC))
9199 Src0SubRC = RI.getEquivalentVGPRClass(Src0SubRC);
9200 const TargetRegisterClass *Src1SubRC =
9201 RI.getSubRegisterClass(Src1RC, AMDGPU::sub0);
9202 if (RI.isSGPRClass(Src1SubRC))
9203 Src1SubRC = RI.getEquivalentVGPRClass(Src1SubRC);
9204
9205 // First, we extract the low 32-bit and high 32-bit values from each of the
9206 // operands.
9207 MachineOperand Op0L =
9208 buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
9209 MachineOperand Op1L =
9210 buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
9211
9212 unsigned Opc = Inst.getOpcode();
9213 unsigned NewOpc = Opc == AMDGPU::S_MUL_U64_U32_PSEUDO
9214 ? AMDGPU::V_MUL_HI_U32_e64
9215 : AMDGPU::V_MUL_HI_I32_e64;
9216 MachineInstr *HiHalf =
9217 BuildMI(MBB, MII, DL, get(NewOpc), DestSub1).add(Op1L).add(Op0L);
9218
9219 MachineInstr *LoHalf =
9220 BuildMI(MBB, MII, DL, get(AMDGPU::V_MUL_LO_U32_e64), DestSub0)
9221 .add(Op1L)
9222 .add(Op0L);
9223
9224 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
9225 .addReg(DestSub0)
9226 .addImm(AMDGPU::sub0)
9227 .addReg(DestSub1)
9228 .addImm(AMDGPU::sub1);
9229
9230 MRI.replaceRegWith(Dest.getReg(), FullDestReg);
9231
9232 // Try to legalize the operands in case we need to swap the order to keep it
9233 // valid.
9234 legalizeOperands(*HiHalf, MDT);
9235 legalizeOperands(*LoHalf, MDT);
9236
9237 // Move all users of this moved value.
9238 addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
9239}
9240
9241void SIInstrInfo::splitScalar64BitBinaryOp(SIInstrWorklist &Worklist,
9242 MachineInstr &Inst, unsigned Opcode,
9243 MachineDominatorTree *MDT) const {
9244 MachineBasicBlock &MBB = *Inst.getParent();
9245 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9246
9247 MachineOperand &Dest = Inst.getOperand(0);
9248 MachineOperand &Src0 = Inst.getOperand(1);
9249 MachineOperand &Src1 = Inst.getOperand(2);
9250 const DebugLoc &DL = Inst.getDebugLoc();
9251
9252 MachineBasicBlock::iterator MII = Inst;
9253
9254 const MCInstrDesc &InstDesc = get(Opcode);
9255 const TargetRegisterClass *Src0RC = Src0.isReg() ?
9256 MRI.getRegClass(Src0.getReg()) :
9257 &AMDGPU::SGPR_32RegClass;
9258
9259 const TargetRegisterClass *Src0SubRC =
9260 RI.getSubRegisterClass(Src0RC, AMDGPU::sub0);
9261 const TargetRegisterClass *Src1RC = Src1.isReg() ?
9262 MRI.getRegClass(Src1.getReg()) :
9263 &AMDGPU::SGPR_32RegClass;
9264
9265 const TargetRegisterClass *Src1SubRC =
9266 RI.getSubRegisterClass(Src1RC, AMDGPU::sub0);
9267
9268 MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
9269 AMDGPU::sub0, Src0SubRC);
9270 MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
9271 AMDGPU::sub0, Src1SubRC);
9272 MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
9273 AMDGPU::sub1, Src0SubRC);
9274 MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
9275 AMDGPU::sub1, Src1SubRC);
9276
9277 const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
9278 const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
9279 const TargetRegisterClass *NewDestSubRC =
9280 RI.getSubRegisterClass(NewDestRC, AMDGPU::sub0);
9281
9282 Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
9283 MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
9284 .add(SrcReg0Sub0)
9285 .add(SrcReg1Sub0);
9286
9287 Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
9288 MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
9289 .add(SrcReg0Sub1)
9290 .add(SrcReg1Sub1);
9291
9292 Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
9293 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
9294 .addReg(DestSub0)
9295 .addImm(AMDGPU::sub0)
9296 .addReg(DestSub1)
9297 .addImm(AMDGPU::sub1);
9298
9299 MRI.replaceRegWith(Dest.getReg(), FullDestReg);
9300
9301 Worklist.insert(&LoHalf);
9302 Worklist.insert(&HiHalf);
9303
9304 // Move all users of this moved value.
9305 addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
9306}
9307
9308void SIInstrInfo::splitScalar64BitXnor(SIInstrWorklist &Worklist,
9309 MachineInstr &Inst,
9310 MachineDominatorTree *MDT) const {
9311 MachineBasicBlock &MBB = *Inst.getParent();
9312 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9313
9314 MachineOperand &Dest = Inst.getOperand(0);
9315 MachineOperand &Src0 = Inst.getOperand(1);
9316 MachineOperand &Src1 = Inst.getOperand(2);
9317 const DebugLoc &DL = Inst.getDebugLoc();
9318
9319 MachineBasicBlock::iterator MII = Inst;
9320
9321 const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
9322
9323 Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
9324
9325 MachineOperand* Op0;
9326 MachineOperand* Op1;
9327
9328 if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg())) {
9329 Op0 = &Src0;
9330 Op1 = &Src1;
9331 } else {
9332 Op0 = &Src1;
9333 Op1 = &Src0;
9334 }
9335
9336 BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B64), Interm)
9337 .add(*Op0);
9338
9339 Register NewDest = MRI.createVirtualRegister(DestRC);
9340
9341 MachineInstr &Xor = *BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B64), NewDest)
9342 .addReg(Interm)
9343 .add(*Op1);
9344
9345 MRI.replaceRegWith(Dest.getReg(), NewDest);
9346
9347 Worklist.insert(&Xor);
9348}
9349
9350void SIInstrInfo::splitScalar64BitBCNT(SIInstrWorklist &Worklist,
9351 MachineInstr &Inst) const {
9352 MachineBasicBlock &MBB = *Inst.getParent();
9353 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9354
9355 MachineBasicBlock::iterator MII = Inst;
9356 const DebugLoc &DL = Inst.getDebugLoc();
9357
9358 MachineOperand &Dest = Inst.getOperand(0);
9359 MachineOperand &Src = Inst.getOperand(1);
9360
9361 const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
9362 const TargetRegisterClass *SrcRC = Src.isReg() ?
9363 MRI.getRegClass(Src.getReg()) :
9364 &AMDGPU::SGPR_32RegClass;
9365
9366 Register MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9367 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9368
9369 const TargetRegisterClass *SrcSubRC =
9370 RI.getSubRegisterClass(SrcRC, AMDGPU::sub0);
9371
9372 MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
9373 AMDGPU::sub0, SrcSubRC);
9374 MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
9375 AMDGPU::sub1, SrcSubRC);
9376
9377 BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
9378
9379 BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
9380
9381 MRI.replaceRegWith(Dest.getReg(), ResultReg);
9382
9383 // We don't need to legalize operands here. src0 for either instruction can be
9384 // an SGPR, and the second input is unused or determined here.
9385 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
9386}
9387
9388void SIInstrInfo::splitScalar64BitBFE(SIInstrWorklist &Worklist,
9389 MachineInstr &Inst) const {
9390 MachineBasicBlock &MBB = *Inst.getParent();
9391 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9392 MachineBasicBlock::iterator MII = Inst;
9393 const DebugLoc &DL = Inst.getDebugLoc();
9394
9395 MachineOperand &Dest = Inst.getOperand(0);
9396 uint32_t Imm = Inst.getOperand(2).getImm();
9397 uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
9398 uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
9399
9400 (void) Offset;
9401
9402 // Only sext_inreg cases handled.
9403 assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
9404 Offset == 0 && "Not implemented");
9405
9406 if (BitWidth < 32) {
9407 Register MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9408 Register MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9409 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
9410
9411 BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32_e64), MidRegLo)
9412 .addReg(Inst.getOperand(1).getReg(), {}, AMDGPU::sub0)
9413 .addImm(0)
9414 .addImm(BitWidth);
9415
9416 BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
9417 .addImm(31)
9418 .addReg(MidRegLo);
9419
9420 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
9421 .addReg(MidRegLo)
9422 .addImm(AMDGPU::sub0)
9423 .addReg(MidRegHi)
9424 .addImm(AMDGPU::sub1);
9425
9426 MRI.replaceRegWith(Dest.getReg(), ResultReg);
9427 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
9428 return;
9429 }
9430
9431 MachineOperand &Src = Inst.getOperand(1);
9432 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9433 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
9434
9435 BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
9436 .addImm(31)
9437 .addReg(Src.getReg(), {}, AMDGPU::sub0);
9438
9439 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
9440 .addReg(Src.getReg(), {}, AMDGPU::sub0)
9441 .addImm(AMDGPU::sub0)
9442 .addReg(TmpReg)
9443 .addImm(AMDGPU::sub1);
9444
9445 MRI.replaceRegWith(Dest.getReg(), ResultReg);
9446 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
9447}
9448
9449void SIInstrInfo::splitScalar64BitCountOp(SIInstrWorklist &Worklist,
9450 MachineInstr &Inst, unsigned Opcode,
9451 MachineDominatorTree *MDT) const {
9452 // (S_FLBIT_I32_B64 hi:lo) ->
9453 // -> (umin (V_FFBH_U32_e32 hi), (uaddsat (V_FFBH_U32_e32 lo), 32))
9454 // (S_FF1_I32_B64 hi:lo) ->
9455 // ->(umin (uaddsat (V_FFBL_B32_e32 hi), 32) (V_FFBL_B32_e32 lo))
9456
9457 MachineBasicBlock &MBB = *Inst.getParent();
9458 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9459 MachineBasicBlock::iterator MII = Inst;
9460 const DebugLoc &DL = Inst.getDebugLoc();
9461
9462 MachineOperand &Dest = Inst.getOperand(0);
9463 MachineOperand &Src = Inst.getOperand(1);
9464
9465 const MCInstrDesc &InstDesc = get(Opcode);
9466
9467 bool IsCtlz = Opcode == AMDGPU::V_FFBH_U32_e32;
9468 unsigned OpcodeAdd = ST.hasAddNoCarryInsts() ? AMDGPU::V_ADD_U32_e64
9469 : AMDGPU::V_ADD_CO_U32_e32;
9470
9471 const TargetRegisterClass *SrcRC =
9472 Src.isReg() ? MRI.getRegClass(Src.getReg()) : &AMDGPU::SGPR_32RegClass;
9473 const TargetRegisterClass *SrcSubRC =
9474 RI.getSubRegisterClass(SrcRC, AMDGPU::sub0);
9475
9476 MachineOperand SrcRegSub0 =
9477 buildExtractSubRegOrImm(MII, MRI, Src, SrcRC, AMDGPU::sub0, SrcSubRC);
9478 MachineOperand SrcRegSub1 =
9479 buildExtractSubRegOrImm(MII, MRI, Src, SrcRC, AMDGPU::sub1, SrcSubRC);
9480
9481 Register MidReg1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9482 Register MidReg2 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9483 Register MidReg3 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9484 Register MidReg4 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9485
9486 BuildMI(MBB, MII, DL, InstDesc, MidReg1).add(SrcRegSub0);
9487
9488 BuildMI(MBB, MII, DL, InstDesc, MidReg2).add(SrcRegSub1);
9489
9490 BuildMI(MBB, MII, DL, get(OpcodeAdd), MidReg3)
9491 .addReg(IsCtlz ? MidReg1 : MidReg2)
9492 .addImm(32)
9493 .addImm(1); // enable clamp
9494
9495 BuildMI(MBB, MII, DL, get(AMDGPU::V_MIN_U32_e64), MidReg4)
9496 .addReg(MidReg3)
9497 .addReg(IsCtlz ? MidReg2 : MidReg1);
9498
9499 MRI.replaceRegWith(Dest.getReg(), MidReg4);
9500
9501 addUsersToMoveToVALUWorklist(MidReg4, MRI, Worklist);
9502}
9503
9504void SIInstrInfo::addUsersToMoveToVALUWorklist(
9505 Register DstReg, MachineRegisterInfo &MRI,
9506 SIInstrWorklist &Worklist) const {
9507 for (MachineOperand &MO : make_early_inc_range(MRI.use_operands(DstReg))) {
9508 MachineInstr &UseMI = *MO.getParent();
9509
9510 unsigned OpNo = 0;
9511
9512 switch (UseMI.getOpcode()) {
9513 case AMDGPU::COPY:
9514 case AMDGPU::WQM:
9515 case AMDGPU::SOFT_WQM:
9516 case AMDGPU::STRICT_WWM:
9517 case AMDGPU::STRICT_WQM:
9518 case AMDGPU::REG_SEQUENCE:
9519 case AMDGPU::PHI:
9520 case AMDGPU::INSERT_SUBREG:
9521 break;
9522 default:
9523 OpNo = MO.getOperandNo();
9524 break;
9525 }
9526
9527 const TargetRegisterClass *OpRC = getOpRegClass(UseMI, OpNo);
9528 MRI.constrainRegClass(DstReg, OpRC);
9529
9530 if (!RI.hasVectorRegisters(OpRC))
9531 Worklist.insert(&UseMI);
9532 else
9533 // Legalization could change user list.
9534 legalizeOperandsVALUt16(UseMI, OpNo, MRI);
9535 }
9536}
9537
9538void SIInstrInfo::movePackToVALU(SIInstrWorklist &Worklist,
9540 MachineInstr &Inst) const {
9541 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9542 MachineBasicBlock *MBB = Inst.getParent();
9543 MachineOperand &Src0 = Inst.getOperand(1);
9544 MachineOperand &Src1 = Inst.getOperand(2);
9545 const DebugLoc &DL = Inst.getDebugLoc();
9546
9547 if (ST.useRealTrue16Insts()) {
9548 Register SrcReg0, SrcReg1;
9549 if (!Src0.isReg() || !RI.isVGPR(MRI, Src0.getReg())) {
9550 SrcReg0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9551 BuildMI(*MBB, Inst, DL,
9552 get(Src0.isImm() ? AMDGPU::V_MOV_B32_e32 : AMDGPU::COPY), SrcReg0)
9553 .add(Src0);
9554 } else {
9555 SrcReg0 = Src0.getReg();
9556 }
9557
9558 if (!Src1.isReg() || !RI.isVGPR(MRI, Src1.getReg())) {
9559 SrcReg1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9560 BuildMI(*MBB, Inst, DL,
9561 get(Src1.isImm() ? AMDGPU::V_MOV_B32_e32 : AMDGPU::COPY), SrcReg1)
9562 .add(Src1);
9563 } else {
9564 SrcReg1 = Src1.getReg();
9565 }
9566
9567 bool isSrc0Reg16 = MRI.constrainRegClass(SrcReg0, &AMDGPU::VGPR_16RegClass);
9568 bool isSrc1Reg16 = MRI.constrainRegClass(SrcReg1, &AMDGPU::VGPR_16RegClass);
9569
9570 auto NewMI = BuildMI(*MBB, Inst, DL, get(AMDGPU::REG_SEQUENCE), ResultReg);
9571 switch (Inst.getOpcode()) {
9572 case AMDGPU::S_PACK_LL_B32_B16:
9573 NewMI
9574 .addReg(SrcReg0, {},
9575 isSrc0Reg16 ? AMDGPU::NoSubRegister : AMDGPU::lo16)
9576 .addImm(AMDGPU::lo16)
9577 .addReg(SrcReg1, {},
9578 isSrc1Reg16 ? AMDGPU::NoSubRegister : AMDGPU::lo16)
9579 .addImm(AMDGPU::hi16);
9580 break;
9581 case AMDGPU::S_PACK_LH_B32_B16:
9582 NewMI
9583 .addReg(SrcReg0, {},
9584 isSrc0Reg16 ? AMDGPU::NoSubRegister : AMDGPU::lo16)
9585 .addImm(AMDGPU::lo16)
9586 .addReg(SrcReg1, {}, AMDGPU::hi16)
9587 .addImm(AMDGPU::hi16);
9588 break;
9589 case AMDGPU::S_PACK_HL_B32_B16:
9590 NewMI.addReg(SrcReg0, {}, AMDGPU::hi16)
9591 .addImm(AMDGPU::lo16)
9592 .addReg(SrcReg1, {},
9593 isSrc1Reg16 ? AMDGPU::NoSubRegister : AMDGPU::lo16)
9594 .addImm(AMDGPU::hi16);
9595 break;
9596 case AMDGPU::S_PACK_HH_B32_B16:
9597 NewMI.addReg(SrcReg0, {}, AMDGPU::hi16)
9598 .addImm(AMDGPU::lo16)
9599 .addReg(SrcReg1, {}, AMDGPU::hi16)
9600 .addImm(AMDGPU::hi16);
9601 break;
9602 default:
9603 llvm_unreachable("unhandled s_pack_* instruction");
9604 }
9605
9606 MachineOperand &Dest = Inst.getOperand(0);
9607 MRI.replaceRegWith(Dest.getReg(), ResultReg);
9608 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
9609 return;
9610 }
9611
9612 switch (Inst.getOpcode()) {
9613 case AMDGPU::S_PACK_LL_B32_B16: {
9614 Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9615 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9616
9617 // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
9618 // 0.
9619 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
9620 .addImm(0xffff);
9621
9622 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
9623 .addReg(ImmReg, RegState::Kill)
9624 .add(Src0);
9625
9626 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
9627 .add(Src1)
9628 .addImm(16)
9629 .addReg(TmpReg, RegState::Kill);
9630 break;
9631 }
9632 case AMDGPU::S_PACK_LH_B32_B16: {
9633 Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9634 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
9635 .addImm(0xffff);
9636 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32_e64), ResultReg)
9637 .addReg(ImmReg, RegState::Kill)
9638 .add(Src0)
9639 .add(Src1);
9640 break;
9641 }
9642 case AMDGPU::S_PACK_HL_B32_B16: {
9643 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9644 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
9645 .addImm(16)
9646 .add(Src0);
9647 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
9648 .add(Src1)
9649 .addImm(16)
9650 .addReg(TmpReg, RegState::Kill);
9651 break;
9652 }
9653 case AMDGPU::S_PACK_HH_B32_B16: {
9654 Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9655 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9656 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
9657 .addImm(16)
9658 .add(Src0);
9659 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
9660 .addImm(0xffff0000);
9661 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32_e64), ResultReg)
9662 .add(Src1)
9663 .addReg(ImmReg, RegState::Kill)
9664 .addReg(TmpReg, RegState::Kill);
9665 break;
9666 }
9667 default:
9668 llvm_unreachable("unhandled s_pack_* instruction");
9669 }
9670
9671 MachineOperand &Dest = Inst.getOperand(0);
9672 MRI.replaceRegWith(Dest.getReg(), ResultReg);
9673 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
9674}
9675
9676void SIInstrInfo::addSCCDefUsersToVALUWorklist(const MachineOperand &Op,
9677 MachineInstr &SCCDefInst,
9678 SIInstrWorklist &Worklist,
9679 Register NewCond) const {
9680
9681 // Ensure that def inst defines SCC, which is still live.
9682 assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isDef() &&
9683 !Op.isDead() && Op.getParent() == &SCCDefInst);
9684 SmallVector<MachineInstr *, 4> CopyToDelete;
9685 // This assumes that all the users of SCC are in the same block
9686 // as the SCC def.
9687 for (MachineInstr &MI : // Skip the def inst itself.
9688 make_range(std::next(MachineBasicBlock::iterator(SCCDefInst)),
9689 SCCDefInst.getParent()->end())) {
9690 // Check if SCC is used first.
9691 int SCCIdx = MI.findRegisterUseOperandIdx(AMDGPU::SCC, &RI, false);
9692 if (SCCIdx != -1) {
9693 if (MI.isCopy()) {
9694 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
9695 Register DestReg = MI.getOperand(0).getReg();
9696
9697 MRI.replaceRegWith(DestReg, NewCond);
9698 CopyToDelete.push_back(&MI);
9699 } else {
9700
9701 if (NewCond.isValid())
9702 MI.getOperand(SCCIdx).setReg(NewCond);
9703
9704 Worklist.insert(&MI);
9705 }
9706 }
9707 // Exit if we find another SCC def.
9708 if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, &RI, false, false) != -1)
9709 break;
9710 }
9711 for (auto &Copy : CopyToDelete)
9712 Copy->eraseFromParent();
9713}
9714
9715// Instructions that use SCC may be converted to VALU instructions. When that
9716// happens, the SCC register is changed to VCC_LO. The instruction that defines
9717// SCC must be changed to an instruction that defines VCC. This function makes
9718// sure that the instruction that defines SCC is added to the moveToVALU
9719// worklist.
9720void SIInstrInfo::addSCCDefsToVALUWorklist(MachineInstr *SCCUseInst,
9721 SIInstrWorklist &Worklist) const {
9722 // Look for a preceding instruction that either defines VCC or SCC. If VCC
9723 // then there is nothing to do because the defining instruction has been
9724 // converted to a VALU already. If SCC then that instruction needs to be
9725 // converted to a VALU.
9726 for (MachineInstr &MI :
9727 make_range(std::next(MachineBasicBlock::reverse_iterator(SCCUseInst)),
9728 SCCUseInst->getParent()->rend())) {
9729 if (MI.modifiesRegister(AMDGPU::VCC, &RI))
9730 break;
9731 if (MI.definesRegister(AMDGPU::SCC, &RI)) {
9732 Worklist.insert(&MI);
9733 break;
9734 }
9735 }
9736}
9737
9738const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
9739 const MachineInstr &Inst) const {
9740 const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
9741
9742 switch (Inst.getOpcode()) {
9743 // For target instructions, getOpRegClass just returns the virtual register
9744 // class associated with the operand, so we need to find an equivalent VGPR
9745 // register class in order to move the instruction to the VALU.
9746 case AMDGPU::COPY:
9747 case AMDGPU::PHI:
9748 case AMDGPU::REG_SEQUENCE:
9749 case AMDGPU::INSERT_SUBREG:
9750 case AMDGPU::WQM:
9751 case AMDGPU::SOFT_WQM:
9752 case AMDGPU::STRICT_WWM:
9753 case AMDGPU::STRICT_WQM: {
9754 const TargetRegisterClass *SrcRC = getOpRegClass(Inst, 1);
9755 if (RI.isAGPRClass(SrcRC)) {
9756 if (RI.isAGPRClass(NewDstRC))
9757 return nullptr;
9758
9759 switch (Inst.getOpcode()) {
9760 case AMDGPU::PHI:
9761 case AMDGPU::REG_SEQUENCE:
9762 case AMDGPU::INSERT_SUBREG:
9763 NewDstRC = RI.getEquivalentAGPRClass(NewDstRC);
9764 break;
9765 default:
9766 NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
9767 }
9768
9769 if (!NewDstRC)
9770 return nullptr;
9771 } else {
9772 if (RI.isVGPRClass(NewDstRC) || NewDstRC == &AMDGPU::VReg_1RegClass)
9773 return nullptr;
9774
9775 NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
9776 if (!NewDstRC)
9777 return nullptr;
9778 }
9779
9780 return NewDstRC;
9781 }
9782 default:
9783 return NewDstRC;
9784 }
9785}
9786
9787// Find the one SGPR operand we are allowed to use.
9788Register SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
9789 int OpIndices[3]) const {
9790 const MCInstrDesc &Desc = MI.getDesc();
9791
9792 // Find the one SGPR operand we are allowed to use.
9793 //
9794 // First we need to consider the instruction's operand requirements before
9795 // legalizing. Some operands are required to be SGPRs, such as implicit uses
9796 // of VCC, but we are still bound by the constant bus requirement to only use
9797 // one.
9798 //
9799 // If the operand's class is an SGPR, we can never move it.
9800
9801 Register SGPRReg = findImplicitSGPRRead(MI);
9802 if (SGPRReg)
9803 return SGPRReg;
9804
9805 Register UsedSGPRs[3] = {Register()};
9806 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
9807
9808 for (unsigned i = 0; i < 3; ++i) {
9809 int Idx = OpIndices[i];
9810 if (Idx == -1)
9811 break;
9812
9813 const MachineOperand &MO = MI.getOperand(Idx);
9814 if (!MO.isReg())
9815 continue;
9816
9817 // Is this operand statically required to be an SGPR based on the operand
9818 // constraints?
9819 const TargetRegisterClass *OpRC =
9820 RI.getRegClass(getOpRegClassID(Desc.operands()[Idx]));
9821 bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
9822 if (IsRequiredSGPR)
9823 return MO.getReg();
9824
9825 // If this could be a VGPR or an SGPR, Check the dynamic register class.
9826 Register Reg = MO.getReg();
9827 const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
9828 if (RI.isSGPRClass(RegRC))
9829 UsedSGPRs[i] = Reg;
9830 }
9831
9832 // We don't have a required SGPR operand, so we have a bit more freedom in
9833 // selecting operands to move.
9834
9835 // Try to select the most used SGPR. If an SGPR is equal to one of the
9836 // others, we choose that.
9837 //
9838 // e.g.
9839 // V_FMA_F32 v0, s0, s0, s0 -> No moves
9840 // V_FMA_F32 v0, s0, s1, s0 -> Move s1
9841
9842 // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
9843 // prefer those.
9844
9845 if (UsedSGPRs[0]) {
9846 if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
9847 SGPRReg = UsedSGPRs[0];
9848 }
9849
9850 if (!SGPRReg && UsedSGPRs[1]) {
9851 if (UsedSGPRs[1] == UsedSGPRs[2])
9852 SGPRReg = UsedSGPRs[1];
9853 }
9854
9855 return SGPRReg;
9856}
9857
9859 AMDGPU::OpName OperandName) const {
9860 if (OperandName == AMDGPU::OpName::NUM_OPERAND_NAMES)
9861 return nullptr;
9862
9863 int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
9864 if (Idx == -1)
9865 return nullptr;
9866
9867 return &MI.getOperand(Idx);
9868}
9869
9871 if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
9872 int64_t Format = ST.getGeneration() >= AMDGPUSubtarget::GFX11
9875 return (Format << 44) |
9876 (1ULL << 56) | // RESOURCE_LEVEL = 1
9877 (3ULL << 60); // OOB_SELECT = 3
9878 }
9879
9880 uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
9881 if (ST.isAmdHsaOS()) {
9882 // Set ATC = 1. GFX9 doesn't have this bit.
9883 if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
9884 RsrcDataFormat |= (1ULL << 56);
9885
9886 // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
9887 // BTW, it disables TC L2 and therefore decreases performance.
9888 if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
9889 RsrcDataFormat |= (2ULL << 59);
9890 }
9891
9892 return RsrcDataFormat;
9893}
9894
9898 0xffffffff; // Size;
9899
9900 // GFX9 doesn't have ELEMENT_SIZE.
9901 if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
9902 uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize(true)) - 1;
9903 Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
9904 }
9905
9906 // IndexStride = 64 / 32.
9907 uint64_t IndexStride = ST.isWave64() ? 3 : 2;
9908 Rsrc23 |= IndexStride << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
9909
9910 // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
9911 // Clear them unless we want a huge stride.
9912 if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
9913 ST.getGeneration() <= AMDGPUSubtarget::GFX9)
9914 Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
9915
9916 return Rsrc23;
9917}
9918
9920 unsigned Opc = MI.getOpcode();
9921
9922 return isSMRD(Opc);
9923}
9924
9926 return get(Opc).mayLoad() &&
9927 (isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc) || isFLAT(Opc));
9928}
9929
9931 TypeSize &MemBytes) const {
9932 const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
9933 if (!Addr || !Addr->isFI())
9934 return Register();
9935
9936 assert(!MI.memoperands_empty() &&
9937 (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
9938
9939 FrameIndex = Addr->getIndex();
9940
9941 int VDataIdx =
9942 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
9943 MemBytes = TypeSize::getFixed(getOpSize(MI.getOpcode(), VDataIdx));
9944 return MI.getOperand(VDataIdx).getReg();
9945}
9946
9948 TypeSize &MemBytes) const {
9949 const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
9950 assert(Addr && Addr->isFI());
9951 FrameIndex = Addr->getIndex();
9952
9953 int DataIdx =
9954 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::data);
9955 MemBytes = TypeSize::getFixed(getOpSize(MI.getOpcode(), DataIdx));
9956 return MI.getOperand(DataIdx).getReg();
9957}
9958
9960 int &FrameIndex,
9961 TypeSize &MemBytes) const {
9962 if (!MI.mayLoad())
9963 return Register();
9964
9965 if (isMUBUF(MI) || isVGPRSpill(MI))
9966 return isStackAccess(MI, FrameIndex, MemBytes);
9967
9968 if (isSGPRSpill(MI))
9969 return isSGPRStackAccess(MI, FrameIndex, MemBytes);
9970
9971 return Register();
9972}
9973
9975 int &FrameIndex,
9976 TypeSize &MemBytes) const {
9977 if (!MI.mayStore())
9978 return Register();
9979
9980 if (isMUBUF(MI) || isVGPRSpill(MI))
9981 return isStackAccess(MI, FrameIndex, MemBytes);
9982
9983 if (isSGPRSpill(MI))
9984 return isSGPRStackAccess(MI, FrameIndex, MemBytes);
9985
9986 return Register();
9987}
9988
9990 unsigned Opc = MI.getOpcode();
9992 unsigned DescSize = Desc.getSize();
9993
9994 // If we have a definitive size, we can use it. Otherwise we need to inspect
9995 // the operands to know the size.
9996 if (isFixedSize(MI)) {
9997 unsigned Size = DescSize;
9998
9999 // If we hit the buggy offset, an extra nop will be inserted in MC so
10000 // estimate the worst case.
10001 if (MI.isBranch() && ST.hasOffset3fBug())
10002 Size += 4;
10003
10004 return Size;
10005 }
10006
10007 // Instructions may have a 32-bit literal encoded after them. Check
10008 // operands that could ever be literals.
10009 if (isVALU(MI) || isSALU(MI)) {
10010 if (isDPP(MI))
10011 return DescSize;
10012 bool HasLiteral = false;
10013 unsigned LiteralSize = 4;
10014 for (int I = 0, E = MI.getNumExplicitOperands(); I != E; ++I) {
10015 const MachineOperand &Op = MI.getOperand(I);
10016 const MCOperandInfo &OpInfo = Desc.operands()[I];
10017 if (!Op.isReg() && !isInlineConstant(Op, OpInfo)) {
10018 HasLiteral = true;
10019 if (ST.has64BitLiterals()) {
10020 switch (OpInfo.OperandType) {
10021 default:
10022 break;
10025 if (!AMDGPU::isValid32BitLiteral(Op.getImm(), true))
10026 LiteralSize = 8;
10027 break;
10029 // A 32-bit literal is only valid when the value fits in BOTH signed
10030 // and unsigned 32-bit ranges [0, 2^31-1], matching the MC code
10031 // emitter's getLit64Encoding logic. This is because of the lack of
10032 // abilility to tell signedness of the literal, therefore we need to
10033 // be conservative and assume values outside this range require a
10034 // 64-bit literal encoding (8 bytes).
10035 if (!Op.isImm() || !isInt<32>(Op.getImm()) ||
10036 !isUInt<32>(Op.getImm()))
10037 LiteralSize = 8;
10038 break;
10039 }
10040 }
10041 break;
10042 }
10043 }
10044 return HasLiteral ? DescSize + LiteralSize : DescSize;
10045 }
10046
10047 // Check whether we have extra NSA words.
10048 if (isMIMG(MI)) {
10049 int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
10050 if (VAddr0Idx < 0)
10051 return 8;
10052
10053 int RSrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
10054 return 8 + 4 * ((RSrcIdx - VAddr0Idx + 2) / 4);
10055 }
10056
10057 switch (Opc) {
10058 case TargetOpcode::BUNDLE:
10059 return getInstBundleSize(MI);
10060 case TargetOpcode::INLINEASM:
10061 case TargetOpcode::INLINEASM_BR: {
10062 const MachineFunction *MF = MI.getMF();
10063 const char *AsmStr = MI.getOperand(0).getSymbolName();
10064 return getInlineAsmLength(AsmStr, MF->getTarget().getMCAsmInfo(), &ST);
10065 }
10066 default:
10067 if (MI.isMetaInstruction())
10068 return 0;
10069
10070 // If D16 Pseudo inst, get correct MC code size
10071 const auto *D16Info = AMDGPU::getT16D16Helper(Opc);
10072 if (D16Info) {
10073 // Assume d16_lo/hi inst are always in same size
10074 unsigned LoInstOpcode = D16Info->LoOp;
10075 const MCInstrDesc &Desc = getMCOpcodeFromPseudo(LoInstOpcode);
10076 DescSize = Desc.getSize();
10077 }
10078
10079 // If FMA Pseudo inst, get correct MC code size
10080 if (Opc == AMDGPU::V_FMA_MIX_F16_t16 || Opc == AMDGPU::V_FMA_MIX_BF16_t16) {
10081 // All potential lowerings are the same size; arbitrarily pick one.
10082 const MCInstrDesc &Desc = getMCOpcodeFromPseudo(AMDGPU::V_FMA_MIXLO_F16);
10083 DescSize = Desc.getSize();
10084 }
10085
10086 return DescSize;
10087 }
10088}
10089
10092 if (MI.isBranch() && ST.hasOffset3fBug())
10093 return InstSizeVerifyMode::NoVerify;
10094 return InstSizeVerifyMode::ExactSize;
10095}
10096
10098 if (!isFLAT(MI))
10099 return false;
10100
10101 if (MI.memoperands_empty())
10102 return true;
10103
10104 for (const MachineMemOperand *MMO : MI.memoperands()) {
10106 return true;
10107 }
10108 return false;
10109}
10110
10113 static const std::pair<int, const char *> TargetIndices[] = {
10114 {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
10115 {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
10116 {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
10117 {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
10118 {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
10119 return ArrayRef(TargetIndices);
10120}
10121
10122/// This is used by the post-RA scheduler (SchedulePostRAList.cpp). The
10123/// post-RA version of misched uses CreateTargetMIHazardRecognizer.
10126 const ScheduleDAG *DAG) const {
10127 return new GCNHazardRecognizer(DAG->MF);
10128}
10129
10130/// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
10131/// pass.
10134 MachineLoopInfo *MLI) const {
10135 return new GCNHazardRecognizer(MF, MLI);
10136}
10137
10138// Called during:
10139// - pre-RA scheduling and post-RA scheduling
10142 const ScheduleDAGMI *DAG) const {
10143 // Borrowed from Arm Target
10144 // We would like to restrict this hazard recognizer to only
10145 // post-RA scheduling; we can tell that we're post-RA because we don't
10146 // track VRegLiveness.
10147 if (!DAG->hasVRegLiveness())
10148 return new GCNHazardRecognizer(DAG->MF);
10150}
10151
10152std::pair<unsigned, unsigned>
10154 return std::pair(TF & MO_MASK, TF & ~MO_MASK);
10155}
10156
10159 static const std::pair<unsigned, const char *> TargetFlags[] = {
10160 {MO_GOTPCREL, "amdgpu-gotprel"},
10161 {MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo"},
10162 {MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi"},
10163 {MO_GOTPCREL64, "amdgpu-gotprel64"},
10164 {MO_REL32_LO, "amdgpu-rel32-lo"},
10165 {MO_REL32_HI, "amdgpu-rel32-hi"},
10166 {MO_REL64, "amdgpu-rel64"},
10167 {MO_ABS32_LO, "amdgpu-abs32-lo"},
10168 {MO_ABS32_HI, "amdgpu-abs32-hi"},
10169 {MO_ABS64, "amdgpu-abs64"},
10170 };
10171
10172 return ArrayRef(TargetFlags);
10173}
10174
10177 static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
10178 {
10179 {MONoClobber, "amdgpu-noclobber"},
10180 {MOLastUse, "amdgpu-last-use"},
10181 {MOCooperative, "amdgpu-cooperative"},
10182 {MOThreadPrivate, "amdgpu-thread-private"},
10183 };
10184
10185 return ArrayRef(TargetFlags);
10186}
10187
10189 const MachineFunction &MF) const {
10191 assert(SrcReg.isVirtual());
10192 if (MFI->checkFlag(SrcReg, AMDGPU::VirtRegFlag::WWM_REG))
10193 return AMDGPU::WWM_COPY;
10194
10195 return AMDGPU::COPY;
10196}
10197
10199 uint32_t Opcode = MI.getOpcode();
10200 // Check if it is SGPR spill or wwm-register spill Opcode.
10201 if (isSGPRSpill(Opcode) || isWWMRegSpillOpcode(Opcode))
10202 return true;
10203
10204 const MachineFunction *MF = MI.getMF();
10205 const MachineRegisterInfo &MRI = MF->getRegInfo();
10207
10208 // See if this is Liverange split instruction inserted for SGPR or
10209 // wwm-register. The implicit def inserted for wwm-registers should also be
10210 // included as they can appear at the bb begin.
10211 bool IsLRSplitInst = MI.getFlag(MachineInstr::LRSplit);
10212 if (!IsLRSplitInst && Opcode != AMDGPU::IMPLICIT_DEF)
10213 return false;
10214
10215 Register Reg = MI.getOperand(0).getReg();
10216 if (RI.isSGPRClass(RI.getRegClassForReg(MRI, Reg)))
10217 return IsLRSplitInst;
10218
10219 return MFI->isWWMReg(Reg);
10220}
10221
10223 Register Reg) const {
10224 // We need to handle instructions which may be inserted during register
10225 // allocation to handle the prolog. The initial prolog instruction may have
10226 // been separated from the start of the block by spills and copies inserted
10227 // needed by the prolog. However, the insertions for scalar registers can
10228 // always be placed at the BB top as they are independent of the exec mask
10229 // value.
10230 bool IsNullOrVectorRegister = true;
10231 if (Reg) {
10232 const MachineFunction *MF = MI.getMF();
10233 const MachineRegisterInfo &MRI = MF->getRegInfo();
10234 IsNullOrVectorRegister = !RI.isSGPRClass(RI.getRegClassForReg(MRI, Reg));
10235 }
10236
10237 return IsNullOrVectorRegister &&
10238 (canAddToBBProlog(MI) ||
10239 (!MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
10240 MI.modifiesRegister(AMDGPU::EXEC, &RI)));
10241}
10242
10246 const DebugLoc &DL,
10247 Register DestReg) const {
10248 if (ST.hasAddNoCarryInsts())
10249 return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
10250
10251 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
10252 Register UnusedCarry = MRI.createVirtualRegister(RI.getBoolRC());
10253 MRI.setRegAllocationHint(UnusedCarry, 0, RI.getVCC());
10254
10255 return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
10256 .addReg(UnusedCarry, RegState::Define | RegState::Dead);
10257}
10258
10261 const DebugLoc &DL,
10262 Register DestReg,
10263 RegScavenger &RS) const {
10264 if (ST.hasAddNoCarryInsts())
10265 return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e32), DestReg);
10266
10267 // If available, prefer to use vcc.
10268 Register UnusedCarry = !RS.isRegUsed(AMDGPU::VCC)
10269 ? Register(RI.getVCC())
10270 : RS.scavengeRegisterBackwards(
10271 *RI.getBoolRC(), I, /* RestoreAfter */ false,
10272 0, /* AllowSpill */ false);
10273
10274 // TODO: Users need to deal with this.
10275 if (!UnusedCarry.isValid())
10276 return MachineInstrBuilder();
10277
10278 return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
10279 .addReg(UnusedCarry, RegState::Define | RegState::Dead);
10280}
10281
10282bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
10283 switch (Opcode) {
10284 case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
10285 case AMDGPU::SI_KILL_I1_TERMINATOR:
10286 return true;
10287 default:
10288 return false;
10289 }
10290}
10291
10293 switch (Opcode) {
10294 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
10295 return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
10296 case AMDGPU::SI_KILL_I1_PSEUDO:
10297 return get(AMDGPU::SI_KILL_I1_TERMINATOR);
10298 default:
10299 llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
10300 }
10301}
10302
10303bool SIInstrInfo::isLegalMUBUFImmOffset(unsigned Imm) const {
10304 return Imm <= getMaxMUBUFImmOffset(ST);
10305}
10306
10308 // GFX12 field is non-negative 24-bit signed byte offset.
10309 const unsigned OffsetBits =
10310 ST.getGeneration() >= AMDGPUSubtarget::GFX12 ? 23 : 12;
10311 return (1 << OffsetBits) - 1;
10312}
10313
10315 if (!ST.isWave32())
10316 return;
10317
10318 if (MI.isInlineAsm())
10319 return;
10320
10321 if (MI.getNumOperands() < MI.getNumExplicitOperands())
10322 return;
10323
10324 for (auto &Op : MI.implicit_operands()) {
10325 if (Op.isReg() && Op.getReg() == AMDGPU::VCC)
10326 Op.setReg(AMDGPU::VCC_LO);
10327 }
10328}
10329
10331 if (!isSMRD(MI))
10332 return false;
10333
10334 // Check that it is using a buffer resource.
10335 int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
10336 if (Idx == -1) // e.g. s_memtime
10337 return false;
10338
10339 const int16_t RCID = getOpRegClassID(MI.getDesc().operands()[Idx]);
10340 return RI.getRegClass(RCID)->hasSubClassEq(&AMDGPU::SGPR_128RegClass);
10341}
10342
10343// Given Imm, split it into the values to put into the SOffset and ImmOffset
10344// fields in an MUBUF instruction. Return false if it is not possible (due to a
10345// hardware bug needing a workaround).
10346//
10347// The required alignment ensures that individual address components remain
10348// aligned if they are aligned to begin with. It also ensures that additional
10349// offsets within the given alignment can be added to the resulting ImmOffset.
10351 uint32_t &ImmOffset, Align Alignment) const {
10352 const uint32_t MaxOffset = SIInstrInfo::getMaxMUBUFImmOffset(ST);
10353 const uint32_t MaxImm = alignDown(MaxOffset, Alignment.value());
10354 uint32_t Overflow = 0;
10355
10356 if (Imm > MaxImm) {
10357 if (Imm <= MaxImm + 64) {
10358 // Use an SOffset inline constant for 4..64
10359 Overflow = Imm - MaxImm;
10360 Imm = MaxImm;
10361 } else {
10362 // Try to keep the same value in SOffset for adjacent loads, so that
10363 // the corresponding register contents can be re-used.
10364 //
10365 // Load values with all low-bits (except for alignment bits) set into
10366 // SOffset, so that a larger range of values can be covered using
10367 // s_movk_i32.
10368 //
10369 // Atomic operations fail to work correctly when individual address
10370 // components are unaligned, even if their sum is aligned.
10371 uint32_t High = (Imm + Alignment.value()) & ~MaxOffset;
10372 uint32_t Low = (Imm + Alignment.value()) & MaxOffset;
10373 Imm = Low;
10374 Overflow = High - Alignment.value();
10375 }
10376 }
10377
10378 if (Overflow > 0) {
10379 // There is a hardware bug in SI and CI which prevents address clamping in
10380 // MUBUF instructions from working correctly with SOffsets. The immediate
10381 // offset is unaffected.
10382 if (ST.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS)
10383 return false;
10384
10385 // It is not possible to set immediate in SOffset field on some targets.
10386 if (ST.hasRestrictedSOffset())
10387 return false;
10388 }
10389
10390 ImmOffset = Imm;
10391 SOffset = Overflow;
10392 return true;
10393}
10394
10395// Depending on the used address space and instructions, some immediate offsets
10396// are allowed and some are not.
10397// Pre-GFX12, flat instruction offsets can only be non-negative, global and
10398// scratch instruction offsets can also be negative. On GFX12, offsets can be
10399// negative for all variants.
10400//
10401// There are several bugs related to these offsets:
10402// On gfx10.1, flat instructions that go into the global address space cannot
10403// use an offset.
10404//
10405// For scratch instructions, the address can be either an SGPR or a VGPR.
10406// The following offsets can be used, depending on the architecture (x means
10407// cannot be used):
10408// +----------------------------+------+------+
10409// | Address-Mode | SGPR | VGPR |
10410// +----------------------------+------+------+
10411// | gfx9 | | |
10412// | negative, 4-aligned offset | x | ok |
10413// | negative, unaligned offset | x | ok |
10414// +----------------------------+------+------+
10415// | gfx10 | | |
10416// | negative, 4-aligned offset | ok | ok |
10417// | negative, unaligned offset | ok | x |
10418// +----------------------------+------+------+
10419// | gfx10.3 | | |
10420// | negative, 4-aligned offset | ok | ok |
10421// | negative, unaligned offset | ok | ok |
10422// +----------------------------+------+------+
10423//
10424// This function ignores the addressing mode, so if an offset cannot be used in
10425// one addressing mode, it is considered illegal.
10426bool SIInstrInfo::isLegalFLATOffset(int64_t Offset, unsigned AddrSpace,
10427 AMDGPU::FlatAddrSpace FlatVariant) const {
10428 // TODO: Should 0 be special cased?
10429 if (!ST.hasFlatInstOffsets())
10430 return false;
10431
10433 if (ST.hasFlatSegmentOffsetBug() && FlatVariant == FlatAddrSpace::FLAT &&
10434 (AddrSpace == AMDGPUAS::FLAT_ADDRESS ||
10435 AddrSpace == AMDGPUAS::GLOBAL_ADDRESS))
10436 return false;
10437
10438 if (ST.hasNegativeUnalignedScratchOffsetBug() &&
10439 FlatVariant == FlatAddrSpace::FlatScratch && Offset < 0 &&
10440 (Offset % 4) != 0) {
10441 return false;
10442 }
10443
10444 bool AllowNegative = allowNegativeFlatOffset(FlatVariant);
10445 unsigned N = AMDGPU::getNumFlatOffsetBits(ST);
10446 return isIntN(N, Offset) && (AllowNegative || Offset >= 0);
10447}
10448
10449// See comment on SIInstrInfo::isLegalFLATOffset for what is legal and what not.
10450std::pair<int64_t, int64_t>
10451SIInstrInfo::splitFlatOffset(int64_t COffsetVal, unsigned AddrSpace,
10452 AMDGPU::FlatAddrSpace FlatVariant) const {
10453 int64_t RemainderOffset = COffsetVal;
10454 int64_t ImmField = 0;
10455
10456 bool AllowNegative = allowNegativeFlatOffset(FlatVariant);
10457 const unsigned NumBits = AMDGPU::getNumFlatOffsetBits(ST) - 1;
10458
10459 if (AllowNegative) {
10460 // Use signed division by a power of two to truncate towards 0.
10461 int64_t D = 1LL << NumBits;
10462 RemainderOffset = (COffsetVal / D) * D;
10463 ImmField = COffsetVal - RemainderOffset;
10464
10465 if (ST.hasNegativeUnalignedScratchOffsetBug() &&
10466 FlatVariant == AMDGPU::FlatAddrSpace::FlatScratch && ImmField < 0 &&
10467 (ImmField % 4) != 0) {
10468 // Make ImmField a multiple of 4
10469 RemainderOffset += ImmField % 4;
10470 ImmField -= ImmField % 4;
10471 }
10472 } else if (COffsetVal >= 0) {
10473 ImmField = COffsetVal & maskTrailingOnes<uint64_t>(NumBits);
10474 RemainderOffset = COffsetVal - ImmField;
10475 }
10476
10477 assert(isLegalFLATOffset(ImmField, AddrSpace, FlatVariant));
10478 assert(RemainderOffset + ImmField == COffsetVal);
10479 return {ImmField, RemainderOffset};
10480}
10481
10483 AMDGPU::FlatAddrSpace FlatVariant) const {
10484 if (ST.hasNegativeScratchOffsetBug() &&
10486 return false;
10487
10488 return FlatVariant != AMDGPU::FlatAddrSpace::FLAT || AMDGPU::isGFX12Plus(ST);
10489}
10490
10491static unsigned subtargetEncodingFamily(const GCNSubtarget &ST) {
10492 switch (ST.getGeneration()) {
10493 default:
10494 break;
10497 return SIEncodingFamily::SI;
10500 return SIEncodingFamily::VI;
10504 return ST.hasGFX11_7Insts() ? SIEncodingFamily::GFX1170
10507 return ST.hasGFX1250Insts() ? SIEncodingFamily::GFX1250
10511 }
10512 llvm_unreachable("Unknown subtarget generation!");
10513}
10514
10515bool SIInstrInfo::isAsmOnlyOpcode(int MCOp) const {
10516 switch(MCOp) {
10517 // These opcodes use indirect register addressing so
10518 // they need special handling by codegen (currently missing).
10519 // Therefore it is too risky to allow these opcodes
10520 // to be selected by dpp combiner or sdwa peepholer.
10521 case AMDGPU::V_MOVRELS_B32_dpp_gfx10:
10522 case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
10523 case AMDGPU::V_MOVRELD_B32_dpp_gfx10:
10524 case AMDGPU::V_MOVRELD_B32_sdwa_gfx10:
10525 case AMDGPU::V_MOVRELSD_B32_dpp_gfx10:
10526 case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
10527 case AMDGPU::V_MOVRELSD_2_B32_dpp_gfx10:
10528 case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
10529 return true;
10530 default:
10531 return false;
10532 }
10533}
10534
10535#define GENERATE_RENAMED_GFX9_CASES(OPCODE) \
10536 case OPCODE##_dpp: \
10537 case OPCODE##_e32: \
10538 case OPCODE##_e64: \
10539 case OPCODE##_e64_dpp: \
10540 case OPCODE##_sdwa:
10541
10542static bool isRenamedInGFX9(int Opcode) {
10543 switch (Opcode) {
10544 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_ADDC_U32)
10545 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_ADD_CO_U32)
10546 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_ADD_U32)
10547 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUBBREV_U32)
10548 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUBB_U32)
10549 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUBREV_CO_U32)
10550 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUBREV_U32)
10551 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUB_CO_U32)
10552 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUB_U32)
10553 //
10554 case AMDGPU::V_DIV_FIXUP_F16_gfx9_e64:
10555 case AMDGPU::V_DIV_FIXUP_F16_gfx9_fake16_e64:
10556 case AMDGPU::V_FMA_F16_gfx9_e64:
10557 case AMDGPU::V_FMA_F16_gfx9_fake16_e64:
10558 case AMDGPU::V_INTERP_P2_F16:
10559 case AMDGPU::V_MAD_F16_e64:
10560 case AMDGPU::V_MAD_U16_e64:
10561 case AMDGPU::V_MAD_I16_e64:
10562 return true;
10563 default:
10564 return false;
10565 }
10566}
10567
10568int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
10569 assert(Opcode == (int)SIInstrInfo::getNonSoftWaitcntOpcode(Opcode) &&
10570 "SIInsertWaitcnts should have promoted soft waitcnt instructions!");
10571
10572 unsigned Gen = subtargetEncodingFamily(ST);
10573
10574 if (ST.getGeneration() == AMDGPUSubtarget::GFX9 && isRenamedInGFX9(Opcode))
10576
10577 // Adjust the encoding family to GFX80 for D16 buffer instructions when the
10578 // subtarget has UnpackedD16VMem feature.
10579 // TODO: remove this when we discard GFX80 encoding.
10580 if (ST.hasUnpackedD16VMem() && (get(Opcode).TSFlags & SIInstrFlags::D16Buf))
10582
10583 if (get(Opcode).TSFlags & SIInstrFlags::SDWA) {
10584 switch (ST.getGeneration()) {
10585 default:
10587 break;
10590 break;
10593 break;
10594 }
10595 }
10596
10597 if (isMAI(Opcode)) {
10598 int MFMAOp = AMDGPU::getMFMAEarlyClobberOp(Opcode);
10599 if (MFMAOp != -1)
10600 Opcode = MFMAOp;
10601 }
10602
10603 int32_t MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
10604
10605 if (MCOp == AMDGPU::INSTRUCTION_LIST_END && ST.hasGFX11_7Insts())
10607
10608 if (MCOp == AMDGPU::INSTRUCTION_LIST_END && ST.hasGFX1250Insts())
10610
10611 // -1 means that Opcode is already a native instruction.
10612 if (MCOp == -1)
10613 return Opcode;
10614
10615 if (ST.hasGFX90AInsts()) {
10616 uint32_t NMCOp = AMDGPU::INSTRUCTION_LIST_END;
10617 if (ST.hasGFX940Insts())
10619 if (NMCOp == AMDGPU::INSTRUCTION_LIST_END)
10621 if (NMCOp == AMDGPU::INSTRUCTION_LIST_END)
10623 if (NMCOp != AMDGPU::INSTRUCTION_LIST_END)
10624 MCOp = NMCOp;
10625 }
10626
10627 // INSTRUCTION_LIST_END means that Opcode is a pseudo instruction that has no
10628 // encoding in the given subtarget generation.
10629 if (MCOp == AMDGPU::INSTRUCTION_LIST_END)
10630 return -1;
10631
10632 if (isAsmOnlyOpcode(MCOp))
10633 return -1;
10634
10635 return MCOp;
10636}
10637
10638static
10640 assert(RegOpnd.isReg());
10641 return RegOpnd.isUndef() ? TargetInstrInfo::RegSubRegPair() :
10642 getRegSubRegPair(RegOpnd);
10643}
10644
10647 assert(MI.isRegSequence());
10648 for (unsigned I = 0, E = (MI.getNumOperands() - 1)/ 2; I < E; ++I)
10649 if (MI.getOperand(1 + 2 * I + 1).getImm() == SubReg) {
10650 auto &RegOp = MI.getOperand(1 + 2 * I);
10651 return getRegOrUndef(RegOp);
10652 }
10654}
10655
10656// Try to find the definition of reg:subreg in subreg-manipulation pseudos
10657// Following a subreg of reg:subreg isn't supported
10660 if (!RSR.SubReg)
10661 return false;
10662 switch (MI.getOpcode()) {
10663 default: break;
10664 case AMDGPU::REG_SEQUENCE:
10665 RSR = getRegSequenceSubReg(MI, RSR.SubReg);
10666 return true;
10667 // EXTRACT_SUBREG ins't supported as this would follow a subreg of subreg
10668 case AMDGPU::INSERT_SUBREG:
10669 if (RSR.SubReg == (unsigned)MI.getOperand(3).getImm())
10670 // inserted the subreg we're looking for
10671 RSR = getRegOrUndef(MI.getOperand(2));
10672 else { // the subreg in the rest of the reg
10673 auto R1 = getRegOrUndef(MI.getOperand(1));
10674 if (R1.SubReg) // subreg of subreg isn't supported
10675 return false;
10676 RSR.Reg = R1.Reg;
10677 }
10678 return true;
10679 }
10680 return false;
10681}
10682
10684 const MachineRegisterInfo &MRI) {
10685 assert(MRI.isSSA());
10686 if (!P.Reg.isVirtual())
10687 return nullptr;
10688
10689 auto RSR = P;
10690 auto *DefInst = MRI.getVRegDef(RSR.Reg);
10691 while (auto *MI = DefInst) {
10692 DefInst = nullptr;
10693 switch (MI->getOpcode()) {
10694 case AMDGPU::COPY:
10695 case AMDGPU::V_MOV_B32_e32: {
10696 auto &Op1 = MI->getOperand(1);
10697 if (Op1.isReg() && Op1.getReg().isVirtual()) {
10698 if (Op1.isUndef())
10699 return nullptr;
10700 RSR = getRegSubRegPair(Op1);
10701 DefInst = MRI.getVRegDef(RSR.Reg);
10702 }
10703 break;
10704 }
10705 default:
10706 if (followSubRegDef(*MI, RSR)) {
10707 if (!RSR.Reg)
10708 return nullptr;
10709 DefInst = MRI.getVRegDef(RSR.Reg);
10710 }
10711 }
10712 if (!DefInst)
10713 return MI;
10714 }
10715 return nullptr;
10716}
10717
10719 Register VReg,
10720 const MachineInstr &DefMI,
10721 const MachineInstr &UseMI) {
10722 assert(MRI.isSSA() && "Must be run on SSA");
10723
10724 auto *TRI = MRI.getTargetRegisterInfo();
10725 auto *DefBB = DefMI.getParent();
10726
10727 // Don't bother searching between blocks, although it is possible this block
10728 // doesn't modify exec.
10729 if (UseMI.getParent() != DefBB)
10730 return true;
10731
10732 const int MaxInstScan = 20;
10733 int NumInst = 0;
10734
10735 // Stop scan at the use.
10736 auto E = UseMI.getIterator();
10737 for (auto I = std::next(DefMI.getIterator()); I != E; ++I) {
10738 if (I->isDebugInstr())
10739 continue;
10740
10741 if (++NumInst > MaxInstScan)
10742 return true;
10743
10744 if (I->modifiesRegister(AMDGPU::EXEC, TRI))
10745 return true;
10746 }
10747
10748 return false;
10749}
10750
10752 Register VReg,
10753 const MachineInstr &DefMI) {
10754 assert(MRI.isSSA() && "Must be run on SSA");
10755
10756 auto *TRI = MRI.getTargetRegisterInfo();
10757 auto *DefBB = DefMI.getParent();
10758
10759 const int MaxUseScan = 10;
10760 int NumUse = 0;
10761
10762 for (auto &Use : MRI.use_nodbg_operands(VReg)) {
10763 auto &UseInst = *Use.getParent();
10764 // Don't bother searching between blocks, although it is possible this block
10765 // doesn't modify exec.
10766 if (UseInst.getParent() != DefBB || UseInst.isPHI())
10767 return true;
10768
10769 if (++NumUse > MaxUseScan)
10770 return true;
10771 }
10772
10773 if (NumUse == 0)
10774 return false;
10775
10776 const int MaxInstScan = 20;
10777 int NumInst = 0;
10778
10779 // Stop scan when we have seen all the uses.
10780 for (auto I = std::next(DefMI.getIterator()); ; ++I) {
10781 assert(I != DefBB->end());
10782
10783 if (I->isDebugInstr())
10784 continue;
10785
10786 if (++NumInst > MaxInstScan)
10787 return true;
10788
10789 for (const MachineOperand &Op : I->operands()) {
10790 // We don't check reg masks here as they're used only on calls:
10791 // 1. EXEC is only considered const within one BB
10792 // 2. Call should be a terminator instruction if present in a BB
10793
10794 if (!Op.isReg())
10795 continue;
10796
10797 Register Reg = Op.getReg();
10798 if (Op.isUse()) {
10799 if (Reg == VReg && --NumUse == 0)
10800 return false;
10801 } else if (TRI->regsOverlap(Reg, AMDGPU::EXEC))
10802 return true;
10803 }
10804 }
10805}
10806
10809 const DebugLoc &DL, Register Src, Register Dst) const {
10810 auto Cur = MBB.begin();
10811 if (Cur != MBB.end())
10812 do {
10813 if (!Cur->isPHI() && Cur->readsRegister(Dst, /*TRI=*/nullptr))
10814 return BuildMI(MBB, Cur, DL, get(TargetOpcode::COPY), Dst).addReg(Src);
10815 ++Cur;
10816 } while (Cur != MBB.end() && Cur != LastPHIIt);
10817
10818 return TargetInstrInfo::createPHIDestinationCopy(MBB, LastPHIIt, DL, Src,
10819 Dst);
10820}
10821
10824 const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const {
10825 if (InsPt != MBB.end() &&
10826 (InsPt->getOpcode() == AMDGPU::SI_IF ||
10827 InsPt->getOpcode() == AMDGPU::SI_ELSE ||
10828 InsPt->getOpcode() == AMDGPU::SI_IF_BREAK) &&
10829 InsPt->definesRegister(Src, /*TRI=*/nullptr)) {
10830 InsPt++;
10831 return BuildMI(MBB, InsPt, DL,
10832 get(AMDGPU::LaneMaskConstants::get(ST).MovTermOpc), Dst)
10833 .addReg(Src, {}, SrcSubReg)
10834 .addReg(AMDGPU::EXEC, RegState::Implicit);
10835 }
10836 return TargetInstrInfo::createPHISourceCopy(MBB, InsPt, DL, Src, SrcSubReg,
10837 Dst);
10838}
10839
10840bool llvm::SIInstrInfo::isWave32() const { return ST.isWave32(); }
10841
10843 const MachineInstr &SecondMI) const {
10844 for (const auto &Use : SecondMI.all_uses()) {
10845 if (Use.isReg() && FirstMI.modifiesRegister(Use.getReg(), &RI))
10846 return true;
10847 }
10848 return false;
10849}
10850
10851/// If OpX is multicycle, anti-dependencies are not allowed.
10852/// isDPMACCInstruction was not designed for VOPD, but it is fit for the
10853/// purpose.
10855 const MachineInstr &OpX) const {
10857}
10858
10861 ArrayRef<unsigned> Ops, int FrameIndex,
10862 MachineInstr *&CopyMI, LiveIntervals *LIS,
10863 VirtRegMap *VRM) const {
10864 // This is a bit of a hack (copied from AArch64). Consider this instruction:
10865 //
10866 // %0:sreg_32 = COPY $m0
10867 //
10868 // We explicitly chose SReg_32 for the virtual register so such a copy might
10869 // be eliminated by RegisterCoalescer. However, that may not be possible, and
10870 // %0 may even spill. We can't spill $m0 normally (it would require copying to
10871 // a numbered SGPR anyway), and since it is in the SReg_32 register class,
10872 // TargetInstrInfo::foldMemoryOperand() is going to try.
10873 // A similar issue also exists with spilling and reloading $exec registers.
10874 //
10875 // To prevent that, constrain the %0 register class here.
10876 if (isFullCopyInstr(MI)) {
10877 Register DstReg = MI.getOperand(0).getReg();
10878 Register SrcReg = MI.getOperand(1).getReg();
10879 if ((DstReg.isVirtual() || SrcReg.isVirtual()) &&
10880 (DstReg.isVirtual() != SrcReg.isVirtual())) {
10881 MachineRegisterInfo &MRI = MF.getRegInfo();
10882 Register VirtReg = DstReg.isVirtual() ? DstReg : SrcReg;
10883 const TargetRegisterClass *RC = MRI.getRegClass(VirtReg);
10884 if (RC->hasSuperClassEq(&AMDGPU::SReg_32RegClass)) {
10885 MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
10886 return nullptr;
10887 }
10888 if (RC->hasSuperClassEq(&AMDGPU::SReg_64RegClass)) {
10889 MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_64_XEXECRegClass);
10890 return nullptr;
10891 }
10892 }
10893 }
10894
10895 return nullptr;
10896}
10897
10899 const MachineInstr &MI,
10900 unsigned *PredCost) const {
10901 if (MI.isBundle()) {
10903 MachineBasicBlock::const_instr_iterator E(MI.getParent()->instr_end());
10904 unsigned Lat = 0, Count = 0;
10905 for (++I; I != E && I->isBundledWithPred(); ++I) {
10906 ++Count;
10907 Lat = std::max(Lat, SchedModel.computeInstrLatency(&*I));
10908 }
10909 return Lat + Count - 1;
10910 }
10911
10912 return SchedModel.computeInstrLatency(&MI);
10913}
10914
10915const MachineOperand &
10917 if (const MachineOperand *CallAddrOp =
10918 getNamedOperand(MI, AMDGPU::OpName::src0))
10919 return *CallAddrOp;
10921}
10922
10925 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
10926 unsigned Opcode = MI.getOpcode();
10927
10928 auto HandleAddrSpaceCast = [this, &MRI](const MachineInstr &MI) {
10929 Register Dst = MI.getOperand(0).getReg();
10930 Register Src = isa<GIntrinsic>(MI) ? MI.getOperand(2).getReg()
10931 : MI.getOperand(1).getReg();
10932 LLT DstTy = MRI.getType(Dst);
10933 LLT SrcTy = MRI.getType(Src);
10934 unsigned DstAS = DstTy.getAddressSpace();
10935 unsigned SrcAS = SrcTy.getAddressSpace();
10936 return SrcAS == AMDGPUAS::PRIVATE_ADDRESS &&
10937 DstAS == AMDGPUAS::FLAT_ADDRESS &&
10938 ST.hasGloballyAddressableScratch()
10941 };
10942
10943 // If the target supports globally addressable scratch, the mapping from
10944 // scratch memory to the flat aperture changes therefore an address space cast
10945 // is no longer uniform.
10946 if (Opcode == TargetOpcode::G_ADDRSPACE_CAST)
10947 return HandleAddrSpaceCast(MI);
10948
10949 if (auto *GI = dyn_cast<GIntrinsic>(&MI)) {
10950 auto IID = GI->getIntrinsicID();
10955
10956 switch (IID) {
10957 case Intrinsic::amdgcn_addrspacecast_nonnull:
10958 return HandleAddrSpaceCast(MI);
10959 case Intrinsic::amdgcn_if:
10960 case Intrinsic::amdgcn_else:
10961 // FIXME: Uniform if second result
10962 break;
10963 }
10964
10966 }
10967
10968 // Loads from the private and flat address spaces are divergent, because
10969 // threads can execute the load instruction with the same inputs and get
10970 // different results.
10971 //
10972 // All other loads are not divergent, because if threads issue loads with the
10973 // same arguments, they will always get the same result.
10974 if (Opcode == AMDGPU::G_LOAD || Opcode == AMDGPU::G_ZEXTLOAD ||
10975 Opcode == AMDGPU::G_SEXTLOAD) {
10976 if (MI.memoperands_empty())
10977 return ValueUniformity::NeverUniform; // conservative assumption
10978
10979 if (llvm::any_of(MI.memoperands(), [](const MachineMemOperand *mmo) {
10980 return mmo->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
10981 mmo->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS;
10982 })) {
10983 // At least one MMO in a non-global address space.
10985 }
10987 }
10988
10989 if (SIInstrInfo::isGenericAtomicRMWOpcode(Opcode) ||
10990 Opcode == AMDGPU::G_ATOMIC_CMPXCHG ||
10991 Opcode == AMDGPU::G_ATOMIC_CMPXCHG_WITH_SUCCESS ||
10992 AMDGPU::isGenericAtomic(Opcode)) {
10994 }
10995
10996 // Result is computed from uniform SP and uniform wave-wide max size.
10997 if (Opcode == TargetOpcode::G_DYN_STACKALLOC)
10999
11000 if (Opcode == AMDGPU::G_AMDGPU_WHOLE_WAVE_FUNC_SETUP)
11002
11004}
11005
11007 if (!Formatter)
11008 Formatter = std::make_unique<AMDGPUMIRFormatter>(ST);
11009 return Formatter.get();
11010}
11011
11013
11014 if (isNeverUniform(MI))
11016
11017 unsigned opcode = MI.getOpcode();
11018 if (opcode == AMDGPU::V_READLANE_B32 ||
11019 opcode == AMDGPU::V_READFIRSTLANE_B32 ||
11020 opcode == AMDGPU::SI_RESTORE_S32_FROM_VGPR)
11022
11023 // If any of defs is divergent, report as NeverUniform. isUniformReg will
11024 // calculate in more detail for each def from its reg class, if available.
11025 if (MI.isInlineAsm()) {
11026 for (const MachineOperand &MO : MI.operands()) {
11027 if (!MO.isReg() || !MO.isDef())
11028 continue;
11029 const TargetRegisterClass *RC =
11030 MI.getRegClassConstraint(MO.getOperandNo(), this, &RI);
11031 if (!RC || !RI.isSGPRClass(RC))
11033 }
11034 }
11035
11036 if (isCopyInstr(MI)) {
11037 const MachineOperand &srcOp = MI.getOperand(1);
11038 if (srcOp.isReg() && srcOp.getReg().isPhysical()) {
11039 const TargetRegisterClass *regClass =
11040 RI.getPhysRegBaseClass(srcOp.getReg());
11041 return RI.isSGPRClass(regClass) ? ValueUniformity::AlwaysUniform
11043 }
11045 }
11046
11047 // GMIR handling
11048 if (MI.isPreISelOpcode())
11050
11051 // Atomics are divergent because they are executed sequentially: when an
11052 // atomic operation refers to the same address in each thread, then each
11053 // thread after the first sees the value written by the previous thread as
11054 // original value.
11055
11056 if (isAtomic(MI))
11058
11059 // Loads from the private and flat address spaces are divergent, because
11060 // threads can execute the load instruction with the same inputs and get
11061 // different results.
11062 if (isFLAT(MI) && MI.mayLoad()) {
11063 if (MI.memoperands_empty())
11064 return ValueUniformity::NeverUniform; // conservative assumption
11065
11066 if (llvm::any_of(MI.memoperands(), [](const MachineMemOperand *mmo) {
11067 return mmo->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
11068 mmo->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS;
11069 })) {
11070 // At least one MMO in a non-global address space.
11072 }
11073
11075 }
11076
11077 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11078 const AMDGPURegisterBankInfo *RBI = ST.getRegBankInfo();
11079
11080 // FIXME: It's conceptually broken to report this for an instruction, and not
11081 // a specific def operand. For inline asm in particular, there could be mixed
11082 // uniform and divergent results.
11083 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
11084 const MachineOperand &SrcOp = MI.getOperand(I);
11085 if (!SrcOp.isReg())
11086 continue;
11087
11088 Register Reg = SrcOp.getReg();
11089 if (!Reg || !SrcOp.readsReg())
11090 continue;
11091
11092 // If RegBank is null, this is unassigned or an unallocatable special
11093 // register, which are all scalars.
11094 const RegisterBank *RegBank = RBI->getRegBank(Reg, MRI, RI);
11095 if (RegBank && RegBank->getID() != AMDGPU::SGPRRegBankID)
11097 }
11098
11099 // TODO: Uniformity check condtions above can be rearranged for more
11100 // redability
11101
11102 // TODO: amdgcn.{ballot, [if]cmp} should be AlwaysUniform, but they are
11103 // currently turned into no-op COPYs by SelectionDAG ISel and are
11104 // therefore no longer recognizable.
11105
11107}
11108
11110 switch (MF.getFunction().getCallingConv()) {
11112 return 1;
11114 return 2;
11116 return 3;
11120 const Function &F = MF.getFunction();
11121 F.getContext().diagnose(DiagnosticInfoUnsupported(
11122 F, "ds_ordered_count unsupported for this calling conv"));
11123 [[fallthrough]];
11124 }
11127 case CallingConv::C:
11128 case CallingConv::Fast:
11129 default:
11130 // Assume other calling conventions are various compute callable functions
11131 return 0;
11132 }
11133}
11134
11136 Register &SrcReg2, int64_t &CmpMask,
11137 int64_t &CmpValue) const {
11138 if (!MI.getOperand(0).isReg() || MI.getOperand(0).getSubReg())
11139 return false;
11140
11141 switch (MI.getOpcode()) {
11142 default:
11143 break;
11144 case AMDGPU::S_CMP_EQ_U32:
11145 case AMDGPU::S_CMP_EQ_I32:
11146 case AMDGPU::S_CMP_LG_U32:
11147 case AMDGPU::S_CMP_LG_I32:
11148 case AMDGPU::S_CMP_LT_U32:
11149 case AMDGPU::S_CMP_LT_I32:
11150 case AMDGPU::S_CMP_GT_U32:
11151 case AMDGPU::S_CMP_GT_I32:
11152 case AMDGPU::S_CMP_LE_U32:
11153 case AMDGPU::S_CMP_LE_I32:
11154 case AMDGPU::S_CMP_GE_U32:
11155 case AMDGPU::S_CMP_GE_I32:
11156 case AMDGPU::S_CMP_EQ_U64:
11157 case AMDGPU::S_CMP_LG_U64:
11158 SrcReg = MI.getOperand(0).getReg();
11159 if (MI.getOperand(1).isReg()) {
11160 if (MI.getOperand(1).getSubReg())
11161 return false;
11162 SrcReg2 = MI.getOperand(1).getReg();
11163 CmpValue = 0;
11164 } else if (MI.getOperand(1).isImm()) {
11165 SrcReg2 = Register();
11166 CmpValue = MI.getOperand(1).getImm();
11167 } else {
11168 return false;
11169 }
11170 CmpMask = ~0;
11171 return true;
11172 case AMDGPU::S_CMPK_EQ_U32:
11173 case AMDGPU::S_CMPK_EQ_I32:
11174 case AMDGPU::S_CMPK_LG_U32:
11175 case AMDGPU::S_CMPK_LG_I32:
11176 case AMDGPU::S_CMPK_LT_U32:
11177 case AMDGPU::S_CMPK_LT_I32:
11178 case AMDGPU::S_CMPK_GT_U32:
11179 case AMDGPU::S_CMPK_GT_I32:
11180 case AMDGPU::S_CMPK_LE_U32:
11181 case AMDGPU::S_CMPK_LE_I32:
11182 case AMDGPU::S_CMPK_GE_U32:
11183 case AMDGPU::S_CMPK_GE_I32:
11184 SrcReg = MI.getOperand(0).getReg();
11185 SrcReg2 = Register();
11186 CmpValue = MI.getOperand(1).getImm();
11187 CmpMask = ~0;
11188 return true;
11189 }
11190
11191 return false;
11192}
11193
11195 for (MachineBasicBlock *S : MBB->successors()) {
11196 if (S->isLiveIn(AMDGPU::SCC))
11197 return false;
11198 }
11199 return true;
11200}
11201
11202// Invert all uses of SCC following SCCDef because SCCDef may be deleted and
11203// (incoming SCC) = !(SCC defined by SCCDef).
11204// Return true if all uses can be re-written, false otherwise.
11205bool SIInstrInfo::invertSCCUse(MachineInstr *SCCDef) const {
11206 MachineBasicBlock *MBB = SCCDef->getParent();
11207 SmallVector<MachineInstr *> InvertInstr;
11208 bool SCCIsDead = false;
11209
11210 // Scan instructions for SCC uses that need to be inverted until SCC is dead.
11211 constexpr unsigned ScanLimit = 12;
11212 unsigned Count = 0;
11213 for (MachineInstr &MI :
11214 make_range(std::next(MachineBasicBlock::iterator(SCCDef)), MBB->end())) {
11215 if (++Count > ScanLimit)
11216 return false;
11217 if (MI.readsRegister(AMDGPU::SCC, &RI)) {
11218 if (MI.getOpcode() == AMDGPU::S_CSELECT_B32 ||
11219 MI.getOpcode() == AMDGPU::S_CSELECT_B64 ||
11220 MI.getOpcode() == AMDGPU::S_CBRANCH_SCC0 ||
11221 MI.getOpcode() == AMDGPU::S_CBRANCH_SCC1)
11222 InvertInstr.push_back(&MI);
11223 else
11224 return false;
11225 }
11226 if (MI.definesRegister(AMDGPU::SCC, &RI)) {
11227 SCCIsDead = true;
11228 break;
11229 }
11230 }
11231 if (!SCCIsDead && isSCCDeadOnExit(MBB))
11232 SCCIsDead = true;
11233
11234 // SCC may have more uses. Can't invert all of them.
11235 if (!SCCIsDead)
11236 return false;
11237
11238 // Invert uses
11239 for (MachineInstr *MI : InvertInstr) {
11240 if (MI->getOpcode() == AMDGPU::S_CSELECT_B32 ||
11241 MI->getOpcode() == AMDGPU::S_CSELECT_B64) {
11242 swapOperands(*MI);
11243 } else if (MI->getOpcode() == AMDGPU::S_CBRANCH_SCC0 ||
11244 MI->getOpcode() == AMDGPU::S_CBRANCH_SCC1) {
11245 MI->setDesc(get(MI->getOpcode() == AMDGPU::S_CBRANCH_SCC0
11246 ? AMDGPU::S_CBRANCH_SCC1
11247 : AMDGPU::S_CBRANCH_SCC0));
11248 } else {
11249 llvm_unreachable("SCC used but no inversion handling");
11250 }
11251 }
11252 return true;
11253}
11254
11255// SCC is already valid after SCCValid.
11256// SCCRedefine will redefine SCC to the same value already available after
11257// SCCValid. If there are no intervening SCC conflicts delete SCCRedefine and
11258// update kill/dead flags if necessary.
11259bool SIInstrInfo::optimizeSCC(MachineInstr *SCCValid, MachineInstr *SCCRedefine,
11260 bool NeedInversion) const {
11261 MachineInstr *KillsSCC = nullptr;
11262 if (SCCValid->getParent() != SCCRedefine->getParent())
11263 return false;
11264 for (MachineInstr &MI : make_range(std::next(SCCValid->getIterator()),
11265 SCCRedefine->getIterator())) {
11266 if (MI.modifiesRegister(AMDGPU::SCC, &RI))
11267 return false;
11268 if (MI.killsRegister(AMDGPU::SCC, &RI))
11269 KillsSCC = &MI;
11270 }
11271 if (NeedInversion && !invertSCCUse(SCCRedefine))
11272 return false;
11273 if (MachineOperand *SccDef =
11274 SCCValid->findRegisterDefOperand(AMDGPU::SCC, /*TRI=*/nullptr))
11275 SccDef->setIsDead(false);
11276 if (KillsSCC)
11277 KillsSCC->clearRegisterKills(AMDGPU::SCC, /*TRI=*/nullptr);
11278 SCCRedefine->eraseFromParent();
11279 return true;
11280}
11281
11282static bool foldableSelect(const MachineInstr &Def) {
11283 if (Def.getOpcode() != AMDGPU::S_CSELECT_B32 &&
11284 Def.getOpcode() != AMDGPU::S_CSELECT_B64)
11285 return false;
11286 bool Op1IsNonZeroImm =
11287 Def.getOperand(1).isImm() && Def.getOperand(1).getImm() != 0;
11288 bool Op2IsZeroImm =
11289 Def.getOperand(2).isImm() && Def.getOperand(2).getImm() == 0;
11290 if (!Op1IsNonZeroImm || !Op2IsZeroImm)
11291 return false;
11292 return true;
11293}
11294
11295static bool setsSCCIfResultIsZero(const MachineInstr &Def, bool &NeedInversion,
11296 unsigned &NewDefOpc) {
11297 // S_ADD_U32 X, 1 sets SCC on carryout which can only happen if result==0.
11298 // S_ADD_I32 X, 1 can be converted to S_ADD_U32 X, 1 if SCC is dead.
11299 if (Def.getOpcode() != AMDGPU::S_ADD_I32 &&
11300 Def.getOpcode() != AMDGPU::S_ADD_U32)
11301 return false;
11302 const MachineOperand &AddSrc1 = Def.getOperand(1);
11303 const MachineOperand &AddSrc2 = Def.getOperand(2);
11304 int64_t addend;
11305
11306 if ((!AddSrc1.isImm() || AddSrc1.getImm() != 1) &&
11307 (!AddSrc2.isImm() || AddSrc2.getImm() != 1) &&
11308 (!getFoldableImm(&AddSrc1, addend) || addend != 1) &&
11309 (!getFoldableImm(&AddSrc2, addend) || addend != 1))
11310 return false;
11311
11312 if (Def.getOpcode() == AMDGPU::S_ADD_I32) {
11313 const MachineOperand *SccDef =
11314 Def.findRegisterDefOperand(AMDGPU::SCC, /*TRI=*/nullptr);
11315 if (!SccDef->isDead())
11316 return false;
11317 NewDefOpc = AMDGPU::S_ADD_U32;
11318 }
11319 NeedInversion = !NeedInversion;
11320 return true;
11321}
11322
11324 Register SrcReg2, int64_t CmpMask,
11325 int64_t CmpValue,
11326 const MachineRegisterInfo *MRI) const {
11327 if (!SrcReg || SrcReg.isPhysical())
11328 return false;
11329
11330 if (SrcReg2 && !getFoldableImm(SrcReg2, *MRI, CmpValue))
11331 return false;
11332
11333 const auto optimizeCmpSelect = [&CmpInstr, SrcReg, CmpValue, MRI,
11334 this](bool NeedInversion) -> bool {
11335 if (CmpValue != 0)
11336 return false;
11337
11338 MachineInstr *Def = MRI->getVRegDef(SrcReg);
11339 if (!Def)
11340 return false;
11341
11342 // For S_OP that set SCC = DST!=0, do the transformation
11343 //
11344 // s_cmp_[lg|eq]_* (S_OP ...), 0 => (S_OP ...)
11345 //
11346 // For (S_OP ...) that set SCC = DST==0, invert NeedInversion and
11347 // do the transformation:
11348 //
11349 // s_cmp_[lg|eq]_* (S_OP ...), 0 => (S_OP ...)
11350 //
11351 // If foldableSelect, s_cmp_lg_* is redundant because the SCC input value
11352 // for S_CSELECT* already has the same value that will be calculated by
11353 // s_cmp_lg_*
11354 //
11355 // s_cmp_[lg|eq]_* (S_CSELECT* (non-zero imm), 0), 0 => (S_CSELECT*
11356 // (non-zero imm), 0)
11357
11358 unsigned NewDefOpc = Def->getOpcode();
11359 if (!setsSCCIfResultIsNonZero(*Def) &&
11360 !setsSCCIfResultIsZero(*Def, NeedInversion, NewDefOpc) &&
11361 !foldableSelect(*Def))
11362 return false;
11363
11364 if (!optimizeSCC(Def, &CmpInstr, NeedInversion))
11365 return false;
11366
11367 if (NewDefOpc != Def->getOpcode())
11368 Def->setDesc(get(NewDefOpc));
11369
11370 // If s_or_b32 result, sY, is unused (i.e. it is effectively a 64-bit
11371 // s_cmp_lg of a register pair) and the inputs are the hi and lo-halves of a
11372 // 64-bit foldableSelect then delete s_or_b32 in the sequence:
11373 // sX = s_cselect_b64 (non-zero imm), 0
11374 // sLo = copy sX.sub0
11375 // sHi = copy sX.sub1
11376 // sY = s_or_b32 sLo, sHi
11377 if (Def->getOpcode() == AMDGPU::S_OR_B32 &&
11378 MRI->use_nodbg_empty(Def->getOperand(0).getReg())) {
11379 const MachineOperand &OrOpnd1 = Def->getOperand(1);
11380 const MachineOperand &OrOpnd2 = Def->getOperand(2);
11381 if (OrOpnd1.isReg() && OrOpnd2.isReg()) {
11382 MachineInstr *Def1 = MRI->getVRegDef(OrOpnd1.getReg());
11383 MachineInstr *Def2 = MRI->getVRegDef(OrOpnd2.getReg());
11384 if (Def1 && Def1->getOpcode() == AMDGPU::COPY && Def2 &&
11385 Def2->getOpcode() == AMDGPU::COPY && Def1->getOperand(1).isReg() &&
11386 Def2->getOperand(1).isReg() &&
11387 Def1->getOperand(1).getSubReg() == AMDGPU::sub0 &&
11388 Def2->getOperand(1).getSubReg() == AMDGPU::sub1 &&
11389 Def1->getOperand(1).getReg() == Def2->getOperand(1).getReg()) {
11390 MachineInstr *Select = MRI->getVRegDef(Def1->getOperand(1).getReg());
11391 if (Select && foldableSelect(*Select))
11392 optimizeSCC(Select, Def, /*NeedInversion=*/false);
11393 }
11394 }
11395 }
11396 return true;
11397 };
11398
11399 const auto optimizeCmpAnd = [&CmpInstr, SrcReg, CmpValue, MRI,
11400 this](int64_t ExpectedValue, unsigned SrcSize,
11401 bool IsReversible, bool IsSigned) -> bool {
11402 // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
11403 // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
11404 // s_cmp_ge_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
11405 // s_cmp_ge_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
11406 // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 1 << n => s_and_b64 $src, 1 << n
11407 // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
11408 // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
11409 // s_cmp_gt_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
11410 // s_cmp_gt_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
11411 // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 0 => s_and_b64 $src, 1 << n
11412 //
11413 // Signed ge/gt are not used for the sign bit.
11414 //
11415 // If result of the AND is unused except in the compare:
11416 // s_and_b(32|64) $src, 1 << n => s_bitcmp1_b(32|64) $src, n
11417 //
11418 // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
11419 // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
11420 // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 0 => s_bitcmp0_b64 $src, n
11421 // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
11422 // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
11423 // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 1 << n => s_bitcmp0_b64 $src, n
11424
11425 MachineInstr *Def = MRI->getVRegDef(SrcReg);
11426 if (!Def)
11427 return false;
11428
11429 if (Def->getOpcode() != AMDGPU::S_AND_B32 &&
11430 Def->getOpcode() != AMDGPU::S_AND_B64)
11431 return false;
11432
11433 int64_t Mask;
11434 const auto isMask = [&Mask, SrcSize](const MachineOperand *MO) -> bool {
11435 if (MO->isImm())
11436 Mask = MO->getImm();
11437 else if (!getFoldableImm(MO, Mask))
11438 return false;
11439 Mask &= maxUIntN(SrcSize);
11440 return isPowerOf2_64(Mask);
11441 };
11442
11443 MachineOperand *SrcOp = &Def->getOperand(1);
11444 if (isMask(SrcOp))
11445 SrcOp = &Def->getOperand(2);
11446 else if (isMask(&Def->getOperand(2)))
11447 SrcOp = &Def->getOperand(1);
11448 else
11449 return false;
11450
11451 // A valid Mask is required to have a single bit set, hence a non-zero and
11452 // power-of-two value. This verifies that we will not do 64-bit shift below.
11453 assert(llvm::has_single_bit<uint64_t>(Mask) && "Invalid mask.");
11454 unsigned BitNo = llvm::countr_zero((uint64_t)Mask);
11455 if (IsSigned && BitNo == SrcSize - 1)
11456 return false;
11457
11458 ExpectedValue <<= BitNo;
11459
11460 bool IsReversedCC = false;
11461 if (CmpValue != ExpectedValue) {
11462 if (!IsReversible)
11463 return false;
11464 IsReversedCC = CmpValue == (ExpectedValue ^ Mask);
11465 if (!IsReversedCC)
11466 return false;
11467 }
11468
11469 Register DefReg = Def->getOperand(0).getReg();
11470 if (IsReversedCC && !MRI->hasOneNonDBGUse(DefReg))
11471 return false;
11472
11473 if (!optimizeSCC(Def, &CmpInstr, /*NeedInversion=*/false))
11474 return false;
11475
11476 if (!MRI->use_nodbg_empty(DefReg)) {
11477 assert(!IsReversedCC);
11478 return true;
11479 }
11480
11481 // Replace AND with unused result with a S_BITCMP.
11482 MachineBasicBlock *MBB = Def->getParent();
11483
11484 unsigned NewOpc = (SrcSize == 32) ? IsReversedCC ? AMDGPU::S_BITCMP0_B32
11485 : AMDGPU::S_BITCMP1_B32
11486 : IsReversedCC ? AMDGPU::S_BITCMP0_B64
11487 : AMDGPU::S_BITCMP1_B64;
11488
11489 BuildMI(*MBB, Def, Def->getDebugLoc(), get(NewOpc))
11490 .add(*SrcOp)
11491 .addImm(BitNo);
11492 Def->eraseFromParent();
11493
11494 return true;
11495 };
11496
11497 switch (CmpInstr.getOpcode()) {
11498 default:
11499 break;
11500 case AMDGPU::S_CMP_EQ_U32:
11501 case AMDGPU::S_CMP_EQ_I32:
11502 case AMDGPU::S_CMPK_EQ_U32:
11503 case AMDGPU::S_CMPK_EQ_I32:
11504 return optimizeCmpAnd(1, 32, true, false) ||
11505 optimizeCmpSelect(/*NeedInversion=*/true);
11506 case AMDGPU::S_CMP_GE_U32:
11507 case AMDGPU::S_CMPK_GE_U32:
11508 return optimizeCmpAnd(1, 32, false, false);
11509 case AMDGPU::S_CMP_GE_I32:
11510 case AMDGPU::S_CMPK_GE_I32:
11511 return optimizeCmpAnd(1, 32, false, true);
11512 case AMDGPU::S_CMP_EQ_U64:
11513 return optimizeCmpAnd(1, 64, true, false);
11514 case AMDGPU::S_CMP_LG_U32:
11515 case AMDGPU::S_CMP_LG_I32:
11516 case AMDGPU::S_CMPK_LG_U32:
11517 case AMDGPU::S_CMPK_LG_I32:
11518 return optimizeCmpAnd(0, 32, true, false) ||
11519 optimizeCmpSelect(/*NeedInversion=*/false);
11520 case AMDGPU::S_CMP_GT_U32:
11521 case AMDGPU::S_CMPK_GT_U32:
11522 return optimizeCmpAnd(0, 32, false, false);
11523 case AMDGPU::S_CMP_GT_I32:
11524 case AMDGPU::S_CMPK_GT_I32:
11525 return optimizeCmpAnd(0, 32, false, true);
11526 case AMDGPU::S_CMP_LG_U64:
11527 return optimizeCmpAnd(0, 64, true, false) ||
11528 optimizeCmpSelect(/*NeedInversion=*/false);
11529 }
11530
11531 return false;
11532}
11533
11535 AMDGPU::OpName OpName) const {
11536 if (!ST.needsAlignedVGPRs())
11537 return;
11538
11539 int OpNo = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpName);
11540 if (OpNo < 0)
11541 return;
11542 MachineOperand &Op = MI.getOperand(OpNo);
11543 if (getOpSize(MI, OpNo) > 4)
11544 return;
11545
11546 // Add implicit aligned super-reg to force alignment on the data operand.
11547 const DebugLoc &DL = MI.getDebugLoc();
11548 MachineBasicBlock *BB = MI.getParent();
11550 Register DataReg = Op.getReg();
11551 bool IsAGPR = RI.isAGPR(MRI, DataReg);
11553 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
11554 BuildMI(*BB, MI, DL, get(AMDGPU::IMPLICIT_DEF), Undef);
11555 Register NewVR =
11556 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
11557 : &AMDGPU::VReg_64_Align2RegClass);
11558 BuildMI(*BB, MI, DL, get(AMDGPU::REG_SEQUENCE), NewVR)
11559 .addReg(DataReg, {}, Op.getSubReg())
11560 .addImm(AMDGPU::sub0)
11561 .addReg(Undef)
11562 .addImm(AMDGPU::sub1);
11563 Op.setReg(NewVR);
11564 Op.setSubReg(AMDGPU::sub0);
11565 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
11566}
11567
11569 if (isIGLP(*MI))
11570 return false;
11571
11573}
11574
11576 if (!isWMMA(MI) && !isSWMMAC(MI))
11577 return false;
11578
11579 if (ST.hasGFX1250Insts())
11580 return AMDGPU::getWMMAIsXDL(MI.getOpcode());
11581
11582 return true;
11583}
11584
11586 unsigned Opcode = MI.getOpcode();
11587
11588 if (AMDGPU::isGFX12Plus(ST))
11589 return isDOT(MI) || isXDLWMMA(MI);
11590
11591 if (!isMAI(MI) || isDGEMM(Opcode) ||
11592 Opcode == AMDGPU::V_ACCVGPR_WRITE_B32_e64 ||
11593 Opcode == AMDGPU::V_ACCVGPR_READ_B32_e64)
11594 return false;
11595
11596 if (!ST.hasGFX940Insts())
11597 return true;
11598
11599 return AMDGPU::getMAIIsGFX940XDL(Opcode);
11600}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
static const TargetRegisterClass * getRegClass(const MachineInstr &MI, Register Reg)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Contains the definition of a TargetInstrInfo class that is common to all AMD GPUs.
AMDGPU Register Bank Select
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isUndef(const MachineInstr &MI)
TargetInstrInfo::RegSubRegPair RegSubRegPair
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
MachineInstr unsigned OpIdx
uint64_t High
uint64_t IntrinsicInst * II
#define P(N)
R600 Clause Merge
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
This file declares the machine register scavenger class.
static cl::opt< bool > Fix16BitCopies("amdgpu-fix-16-bit-physreg-copies", cl::desc("Fix copies between 32 and 16 bit registers by extending to 32 bit"), cl::init(true), cl::ReallyHidden)
static void emitLoadScalarOpsFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI, MachineBasicBlock &LoopBB, MachineBasicBlock &BodyBB, const DebugLoc &DL, ArrayRef< MachineOperand * > ScalarOps, ArrayRef< Register > PhySGPRs={})
static void expandSGPRCopy(const SIInstrInfo &TII, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, const TargetRegisterClass *RC, bool Forward)
static unsigned getNewFMAInst(const GCNSubtarget &ST, unsigned Opc)
static void indirectCopyToAGPR(const SIInstrInfo &TII, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, RegScavenger &RS, bool RegsOverlap, Register ImpDefSuperReg=Register(), Register ImpUseSuperReg=Register())
Handle copying from SGPR to AGPR, or from AGPR to AGPR on GFX908.
static unsigned getIndirectSGPRWriteMovRelPseudo32(unsigned VecSize)
static bool compareMachineOp(const MachineOperand &Op0, const MachineOperand &Op1)
static bool isStride64(unsigned Opc)
static MachineBasicBlock * generateWaterFallLoop(const SIInstrInfo &TII, MachineInstr &MI, ArrayRef< MachineOperand * > ScalarOps, MachineDominatorTree *MDT, MachineBasicBlock::iterator Begin=nullptr, MachineBasicBlock::iterator End=nullptr, ArrayRef< Register > PhySGPRs={})
#define GENERATE_RENAMED_GFX9_CASES(OPCODE)
static std::tuple< unsigned, unsigned > extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc)
static bool followSubRegDef(MachineInstr &MI, TargetInstrInfo::RegSubRegPair &RSR)
static unsigned getIndirectSGPRWriteMovRelPseudo64(unsigned VecSize)
static MachineInstr * swapImmOperands(MachineInstr &MI, MachineOperand &NonRegOp1, MachineOperand &NonRegOp2)
static void copyFlagsToImplicitVCC(MachineInstr &MI, const MachineOperand &Orig)
static bool offsetsDoNotOverlap(LocationSize WidthA, int OffsetA, LocationSize WidthB, int OffsetB)
static unsigned getWWMRegSpillSaveOpcode(unsigned Size, bool IsVectorSuperClass)
static bool memOpsHaveSameBaseOperands(ArrayRef< const MachineOperand * > BaseOps1, ArrayRef< const MachineOperand * > BaseOps2)
static unsigned getWWMRegSpillRestoreOpcode(unsigned Size, bool IsVectorSuperClass)
static unsigned getSGPRSpillSaveOpcode(unsigned Size, bool NeedsCFI)
static bool setsSCCIfResultIsZero(const MachineInstr &Def, bool &NeedInversion, unsigned &NewDefOpc)
static bool isSCCDeadOnExit(MachineBasicBlock *MBB)
static bool getFoldableImm(Register Reg, const MachineRegisterInfo &MRI, int64_t &Imm, MachineInstr **DefMI=nullptr)
static unsigned getIndirectVGPRWriteMovRelPseudoOpc(unsigned VecSize)
static unsigned subtargetEncodingFamily(const GCNSubtarget &ST)
static void preserveCondRegFlags(MachineOperand &CondReg, const MachineOperand &OrigCond)
static Register findImplicitSGPRRead(const MachineInstr &MI)
static unsigned getNewFMAAKInst(const GCNSubtarget &ST, unsigned Opc)
static cl::opt< unsigned > BranchOffsetBits("amdgpu-s-branch-bits", cl::ReallyHidden, cl::init(16), cl::desc("Restrict range of branch instructions (DEBUG)"))
static void updateLiveVariables(LiveVariables *LV, MachineInstr &MI, MachineInstr &NewMI)
static unsigned getAVSpillSaveOpcode(unsigned Size, bool NeedsCFI)
static bool memOpsHaveSameBasePtr(const MachineInstr &MI1, ArrayRef< const MachineOperand * > BaseOps1, const MachineInstr &MI2, ArrayRef< const MachineOperand * > BaseOps2)
static unsigned getSGPRSpillRestoreOpcode(unsigned Size)
static bool isRegOrFI(const MachineOperand &MO)
static unsigned getVGPRSpillSaveOpcode(unsigned Size, bool NeedsCFI)
static constexpr AMDGPU::OpName ModifierOpNames[]
static void reportIllegalCopy(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, const char *Msg="illegal VGPR to SGPR copy")
static MachineInstr * swapRegAndNonRegOperand(MachineInstr &MI, MachineOperand &RegOp, MachineOperand &NonRegOp)
static bool shouldReadExec(const MachineInstr &MI)
static unsigned getNewFMAMKInst(const GCNSubtarget &ST, unsigned Opc)
static bool isRenamedInGFX9(int Opcode)
static TargetInstrInfo::RegSubRegPair getRegOrUndef(const MachineOperand &RegOpnd)
static bool changesVGPRIndexingMode(const MachineInstr &MI)
static bool isSubRegOf(const SIRegisterInfo &TRI, const MachineOperand &SuperVec, const MachineOperand &SubReg)
static bool foldableSelect(const MachineInstr &Def)
static bool nodesHaveSameOperandValue(SDNode *N0, SDNode *N1, AMDGPU::OpName OpName)
Returns true if both nodes have the same value for the given operand Op, or if both nodes do not have...
static unsigned getNumOperandsNoGlue(SDNode *Node)
static bool canRemat(const MachineInstr &MI)
static unsigned getAVSpillRestoreOpcode(unsigned Size)
static unsigned getVGPRSpillRestoreOpcode(unsigned Size)
Interface definition for SIInstrInfo.
bool IsDead
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const LaneMaskConstants & get(const GCNSubtarget &ST)
static LLVM_ABI Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
Definition APFloat.cpp:158
Class for arbitrary precision integers.
Definition APInt.h:78
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1585
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
uint64_t getZExtValue() const
A debug info location.
Definition DebugLoc.h:124
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:301
Diagnostic information for unsupported feature in backend.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:354
CycleT * getCycle(const BlockT *Block) const
Find the innermost cycle containing a given block.
void getExitingBlocks(SmallVectorImpl< BlockT * > &TmpStorage) const
Return all blocks of this cycle that have successor outside of this cycle.
bool contains(const BlockT *Block) const
Return whether Block is contained in the cycle.
const GenericCycle * getParentCycle() const
Itinerary data supplied by a subtarget to be used by a target.
constexpr unsigned getAddressSpace() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LiveInterval - This class represents the liveness of a register, or stack slot.
bool hasInterval(Register Reg) const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
LiveInterval & getInterval(Register Reg)
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
This class represents the liveness of a register, stack slot, etc.
LLVM_ABI void replaceKillInstruction(Register Reg, MachineInstr &OldMI, MachineInstr &NewMI)
replaceKillInstruction - Update register kill info by replacing a kill instruction with a new one.
LLVM_ABI VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
bool hasValue() const
static LocationSize precise(uint64_t Value)
TypeSize getValue() const
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:348
static const MCBinaryExpr * createAShr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:418
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:428
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
ArrayRef< MCOperandInfo > operands() const
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
unsigned getSize() const
Return the number of bytes in the encoding of this instruction, or zero if the encoding size cannot b...
ArrayRef< MCPhysReg > implicit_uses() const
Return a list of registers that are potentially read by any instance of this machine instruction.
unsigned getOpcode() const
Return the opcode number for this descriptor.
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition MCInstrDesc.h:86
uint8_t OperandType
Information about the type of the operand.
Definition MCInstrDesc.h:98
int16_t RegClass
This specifies the register class enumeration of the operand if the operand is a register.
Definition MCInstrDesc.h:92
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:214
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
LLVM_ABI void setVariableValue(const MCExpr *Value)
Definition MCSymbol.cpp:50
Helper class for constructing bundles of MachineInstrs.
MachineBasicBlock::instr_iterator begin() const
Return an iterator to the first bundled instruction.
MIBundleBuilder & append(MachineInstr *MI)
Insert MI into MBB by appending it to the instructions in the bundle.
MIRFormater - Interface to format MIR operand based on target.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI, MCRegister Reg, const_iterator Before, unsigned Neighborhood=10) const
Return whether (physical) register Reg has been defined and not killed as of just before Before.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
Instructions::const_iterator const_instr_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
@ LQR_Dead
Register is known to be fully dead.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, Align base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void push_back(MachineBasicBlock *MBB)
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
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
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & copyImplicitOps(const MachineInstr &OtherMI) const
Copy all the implicit operands from OtherMI onto this one.
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
bool isCopy() const
const MachineBasicBlock * getParent() const
LLVM_ABI void addImplicitDefUseOperands(MachineFunction &MF)
Add all implicit def and use operands to this instruction.
bool isBundle() const
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
LLVM_ABI unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
mop_range implicit_operands()
bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
void untieRegOperand(unsigned OpIdx)
Break any tie involving OpIdx.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI void eraseFromBundle()
Unlink 'this' from its basic block and delete it.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
mop_range explicit_operands()
LLVM_ABI void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
LLVM_ABI bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
bool isMoveImmediate(QueryType Type=IgnoreBundle) const
Return true if this instruction is a move immediate (including conditional moves) instruction.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
LLVM_ABI void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol)
Set a symbol that will be emitted just after the instruction itself.
LLVM_ABI void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo)
Clear all kill flags affecting Reg.
const MachineOperand & getOperand(unsigned i) const
uint32_t getFlags() const
Return the MI flags bitvector.
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand * findRegisterDefOperand(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false)
Wrapper for findRegisterDefOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
A description of a memory reference used in the backend.
unsigned getAddrSpace() const
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
const GlobalValue * getGlobal() const
void setImplicit(bool Val=true)
LLVM_ABI void ChangeToFrameIndex(int Idx, unsigned TargetFlags=0)
Replace this operand with a frame index.
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_ABI void ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags=0)
ChangeToImmediate - Replace this operand with a new immediate operand of the specified value.
LLVM_ABI void ChangeToGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
ChangeToGA - Replace this operand with a new global address operand.
void setIsKill(bool Val=true)
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.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setOffset(int64_t Offset)
unsigned getTargetFlags() const
static MachineOperand CreateImm(int64_t Val)
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
bool isTargetIndex() const
isTargetIndex - Tests if this is a MO_TargetIndex operand.
void setTargetFlags(unsigned F)
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
@ MO_Immediate
Immediate operand.
@ MO_Register
Register operand.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
int64_t getOffset() const
Return the offset from the symbol in this operand.
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
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...
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
LLVM_ABI void moveOperands(MachineOperand *Dst, MachineOperand *Src, unsigned NumOps)
Move NumOps operands from Src to Dst, updating use-def lists as needed.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
bool reservedRegsFrozen() const
reservedRegsFrozen - Returns true after freezeReservedRegs() was called to ensure the set of reserved...
LLVM_ABI void clearVirtRegs()
clearVirtRegs - Remove all virtual registers (after physreg assignment).
void setRegAllocationHint(Register VReg, unsigned Type, Register PrefReg)
setRegAllocationHint - Specify a register allocation hint for the specified virtual register.
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
void setSimpleHint(Register VReg, Register PrefReg)
Specify the preferred (target independent) register allocation hint for the specified virtual registe...
const TargetRegisterInfo * getTargetRegisterInfo() const
LLVM_ABI Register cloneVirtualRegister(Register VReg, StringRef Name="")
Create and return a new virtual register in the function with the same attributes as the given regist...
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
iterator_range< use_iterator > use_operands(Register Reg) const
LLVM_ABI void removeRegOperandFromUseList(MachineOperand *MO)
Remove MO from its use-def list.
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI void addRegOperandToUseList(MachineOperand *MO)
Add MO to the linked list of operands for its register.
LLVM_ABI MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
const RegisterBank & getRegBank(unsigned ID)
Get the register bank identified by ID.
This class implements the register bank concept.
unsigned getID() const
Get the identifier of this register bank.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isValid() const
Definition Register.h:112
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
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
const SDValue & getOperand(unsigned Num) const
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isLegalMUBUFImmOffset(unsigned Imm) const
bool isInlineConstant(const APInt &Imm) const
void legalizeOperandsVOP3(MachineRegisterInfo &MRI, MachineInstr &MI) const
Fix operands in MI to satisfy constant bus requirements.
bool canAddToBBProlog(const MachineInstr &MI) const
static bool isDS(const MachineInstr &MI)
MachineBasicBlock * legalizeOperands(MachineInstr &MI, MachineDominatorTree *MDT=nullptr) const
Legalize all operands in this instruction.
bool areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1, int64_t &Offset0, int64_t &Offset1) const override
unsigned getLiveRangeSplitOpcode(Register Reg, const MachineFunction &MF) const override
bool getMemOperandsWithOffsetWidth(const MachineInstr &LdSt, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width, const TargetRegisterInfo *TRI) const final
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
static bool isNeverUniform(const MachineInstr &MI)
bool isXDLWMMA(const MachineInstr &MI) const
bool isBasicBlockPrologue(const MachineInstr &MI, Register Reg=Register()) const override
bool isSpill(uint32_t Opcode) const
uint64_t getDefaultRsrcDataFormat() const
static bool isSOPP(const MachineInstr &MI)
bool mayAccessScratch(const MachineInstr &MI) const
bool isIGLP(unsigned Opcode) const
static bool isFLATScratch(const MachineInstr &MI)
bool isLegalFLATOffset(int64_t Offset, unsigned AddrSpace, AMDGPU::FlatAddrSpace FlatVariant) const
Returns if Offset is legal for the subtarget as the offset to a FLAT encoded instruction with the giv...
const MCInstrDesc & getIndirectRegWriteMovRelPseudo(unsigned VecSize, unsigned EltSize, bool IsSGPR) const
MachineInstrBuilder getAddNoCarry(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DestReg) const
Return a partially built integer add instruction without carry.
bool mayAccessFlatAddressSpace(const MachineInstr &MI) const
bool shouldScheduleLoadsNear(SDNode *Load0, SDNode *Load1, int64_t Offset0, int64_t Offset1, unsigned NumLoads) const override
bool splitMUBUFOffset(uint32_t Imm, uint32_t &SOffset, uint32_t &ImmOffset, Align Alignment=Align(4)) const
ArrayRef< std::pair< unsigned, const char * > > getSerializableDirectMachineOperandTargetFlags() const override
void moveToVALU(SIInstrWorklist &Worklist, MachineDominatorTree *MDT) const
Replace the instructions opcode with the equivalent VALU opcode.
static bool isSMRD(const MachineInstr &MI)
void restoreExec(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, Register Reg, SlotIndexes *Indexes=nullptr) const
void storeRegToStackSlotCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC) const
bool usesConstantBus(const MachineRegisterInfo &MRI, const MachineOperand &MO, const MCOperandInfo &OpInfo) const
Returns true if this operand uses the constant bus.
static unsigned getMaxMUBUFImmOffset(const GCNSubtarget &ST)
static unsigned getFoldableCopySrcIdx(const MachineInstr &MI)
unsigned getOpSize(uint32_t Opcode, unsigned OpNo) const
Return the size in bytes of the operand OpNo on the given.
void legalizeOperandsFLAT(MachineRegisterInfo &MRI, MachineInstr &MI) const
bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask, int64_t CmpValue, const MachineRegisterInfo *MRI) const override
static std::optional< int64_t > extractSubregFromImm(int64_t ImmVal, unsigned SubRegIndex)
Return the extracted immediate value in a subregister use from a constant materialized in a super reg...
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
static bool isMTBUF(const MachineInstr &MI)
const MCInstrDesc & getIndirectGPRIDXPseudo(unsigned VecSize, bool IsIndirectSrc) const
void insertReturn(MachineBasicBlock &MBB) const
static bool isDGEMM(unsigned Opcode)
static bool isEXP(const MachineInstr &MI)
static bool isSALU(const MachineInstr &MI)
static bool setsSCCIfResultIsNonZero(const MachineInstr &MI)
const MIRFormatter * getMIRFormatter() const override
static bool isXcntDrain(const MachineInstr &MI)
True if MI implicitly drains XCNT.
void legalizeGenericOperand(MachineBasicBlock &InsertMBB, MachineBasicBlock::iterator I, const TargetRegisterClass *DstRC, MachineOperand &Op, MachineRegisterInfo &MRI, const DebugLoc &DL) const
MachineInstr * buildShrunkInst(MachineInstr &MI, unsigned NewOpcode) const
static bool isVOP2(const MachineInstr &MI)
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
static bool isSDWA(const MachineInstr &MI)
const MCInstrDesc & getKillTerminatorFromPseudo(unsigned Opcode) const
void insertNoops(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned Quantity) const override
static bool isGather4(const MachineInstr &MI)
MachineInstr * getWholeWaveFunctionSetup(MachineFunction &MF) const
bool isLegalVSrcOperand(const MachineRegisterInfo &MRI, const MCOperandInfo &OpInfo, const MachineOperand &MO) const
Check if MO would be a valid operand for the given operand definition OpInfo.
static bool isDOT(const MachineInstr &MI)
InstSizeVerifyMode getInstSizeVerifyMode(const MachineInstr &MI) const override
MachineInstr * createPHISourceCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const override
bool hasModifiers(unsigned Opcode) const
Return true if this instruction has any modifiers.
bool shouldClusterMemOps(ArrayRef< const MachineOperand * > BaseOps1, int64_t Offset1, bool OffsetIsScalable1, ArrayRef< const MachineOperand * > BaseOps2, int64_t Offset2, bool OffsetIsScalable2, unsigned ClusterSize, unsigned NumBytes) const override
static bool isSWMMAC(const MachineInstr &MI)
ScheduleHazardRecognizer * CreateTargetMIHazardRecognizer(const InstrItineraryData *II, const ScheduleDAGMI *DAG) const override
bool isWave32() const
bool isHighLatencyDef(int Opc) const override
void legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const
Legalize the OpIndex operand of this instruction by inserting a MOV.
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
static bool isVOPC(const MachineInstr &MI)
void removeModOperands(MachineInstr &MI) const
unsigned getVectorRegSpillRestoreOpcode(Register Reg, const TargetRegisterClass *RC, unsigned Size, const SIMachineFunctionInfo &MFI) const
bool isXDL(const MachineInstr &MI) const
Register isStackAccess(const MachineInstr &MI, int &FrameIndex, TypeSize &MemBytes) const
static bool isVIMAGE(const MachineInstr &MI)
void enforceOperandRCAlignment(MachineInstr &MI, AMDGPU::OpName OpName) const
static bool isSOP2(const MachineInstr &MI)
static bool isGWS(const MachineInstr &MI)
bool hasRAWDependency(const MachineInstr &FirstMI, const MachineInstr &SecondMI) const
bool isLegalAV64PseudoImm(uint64_t Imm) const
Check if this immediate value can be used for AV_MOV_B64_IMM_PSEUDO.
bool isNeverCoissue(MachineInstr &MI) const
static bool isBUF(const MachineInstr &MI)
void handleCopyToPhysHelper(SIInstrWorklist &Worklist, Register DstReg, MachineInstr &Inst, MachineRegisterInfo &MRI, DenseMap< MachineInstr *, V2PhysSCopyInfo > &WaterFalls, DenseMap< MachineInstr *, bool > &V2SPhyCopiesToErase) const
bool hasModifiersSet(const MachineInstr &MI, AMDGPU::OpName OpName) const
const TargetRegisterClass * getPreferredSelectRegClass(unsigned Size) const
bool isLegalToSwap(const MachineInstr &MI, unsigned fromIdx, unsigned toIdx) const
static bool isFLATGlobal(const MachineInstr &MI)
MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS=nullptr, VirtRegMap *VRM=nullptr) const override
bool isGlobalMemoryObject(const MachineInstr *MI) const override
static bool isVSAMPLE(const MachineInstr &MI)
bool isBufferSMRD(const MachineInstr &MI) const
static bool isKillTerminator(unsigned Opcode)
bool isVOPDAntidependencyAllowed(const MachineInstr &MI) const
If OpX is multicycle, anti-dependencies are not allowed.
bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx0, unsigned &SrcOpIdx1) const override
void insertScratchExecCopy(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, Register Reg, bool IsSCCLive, SlotIndexes *Indexes=nullptr) const
bool hasVALU32BitEncoding(unsigned Opcode) const
Return true if this 64-bit VALU instruction has a 32-bit encoding.
unsigned getMovOpcode(const TargetRegisterClass *DstRC) const
Register isSGPRStackAccess(const MachineInstr &MI, int &FrameIndex, TypeSize &MemBytes) const
unsigned buildExtractSubReg(MachineBasicBlock::iterator MI, MachineRegisterInfo &MRI, const MachineOperand &SuperReg, const TargetRegisterClass *SuperRC, unsigned SubIdx, const TargetRegisterClass *SubRC) const
void legalizeOperandsVOP2(MachineRegisterInfo &MRI, MachineInstr &MI) const
Legalize operands in MI by either commuting it or inserting a copy of src1.
bool foldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, Register Reg, MachineRegisterInfo *MRI) const final
static bool isTRANS(const MachineInstr &MI)
static bool isImage(const MachineInstr &MI)
static bool isSOPK(const MachineInstr &MI)
const TargetRegisterClass * getOpRegClass(const MachineInstr &MI, unsigned OpNo) const
Return the correct register class for OpNo.
MachineBasicBlock * insertSimulatedTrap(MachineRegisterInfo &MRI, MachineBasicBlock &MBB, MachineInstr &MI, const DebugLoc &DL) const
Build instructions that simulate the behavior of a s_trap 2 instructions for hardware (namely,...
static unsigned getNonSoftWaitcntOpcode(unsigned Opcode)
static unsigned getDSShaderTypeValue(const MachineFunction &MF)
static bool isFoldableCopy(const MachineInstr &MI)
bool mayAccessLDSThroughFlat(const MachineInstr &MI) const
bool isIgnorableUse(const MachineOperand &MO) const override
static bool isMUBUF(const MachineInstr &MI)
bool expandPostRAPseudo(MachineInstr &MI) const override
bool analyzeCompare(const MachineInstr &MI, Register &SrcReg, Register &SrcReg2, int64_t &CmpMask, int64_t &CmpValue) const override
void createWaterFallForSiCall(MachineInstr *MI, MachineDominatorTree *MDT, ArrayRef< MachineOperand * > ScalarOps, ArrayRef< Register > PhySGPRs={}) const
Wrapper function for generating waterfall for instruction MI This function take into consideration of...
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
static bool isSegmentSpecificFLAT(const MachineInstr &MI)
bool isReMaterializableImpl(const MachineInstr &MI) const override
static bool isVOP3(const MCInstrDesc &Desc)
Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const override
bool physRegUsesConstantBus(const MachineOperand &Reg) const
static bool isF16PseudoScalarTrans(unsigned Opcode)
void insertSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DstReg, ArrayRef< MachineOperand > Cond, Register TrueReg, Register FalseReg) const override
bool mayAccessVMEMThroughFlat(const MachineInstr &MI) const
static bool isDPP(const MachineInstr &MI)
bool analyzeBranchImpl(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const
static bool isMFMA(const MachineInstr &MI)
bool isLowLatencyInstruction(const MachineInstr &MI) const
std::optional< DestSourcePair > isCopyInstrImpl(const MachineInstr &MI) const override
If the specific machine instruction is a instruction that moves/copies value from one register to ano...
void mutateAndCleanupImplicit(MachineInstr &MI, const MCInstrDesc &NewDesc) const
ValueUniformity getGenericValueUniformity(const MachineInstr &MI) const
static bool isMAI(const MCInstrDesc &Desc)
void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, unsigned SubIdx, const MachineInstr &Orig, LaneBitmask UsedLanes=LaneBitmask::getAll()) const override
static bool usesLGKM_CNT(const MachineInstr &MI)
void legalizeOperandsVALUt16(MachineInstr &Inst, MachineRegisterInfo &MRI) const
Fix operands in Inst to fix 16bit SALU to VALU lowering.
bool isImmOperandLegal(const MCInstrDesc &InstDesc, unsigned OpNo, const MachineOperand &MO) const
bool canShrink(const MachineInstr &MI, const MachineRegisterInfo &MRI) const
const MachineOperand & getCalleeOperand(const MachineInstr &MI) const override
bool isAsmOnlyOpcode(int MCOp) const
Check if this instruction should only be used by assembler.
bool isAlwaysGDS(uint32_t Opcode) const
static bool isVGPRSpill(const MachineInstr &MI)
ScheduleHazardRecognizer * CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, const ScheduleDAG *DAG) const override
This is used by the post-RA scheduler (SchedulePostRAList.cpp).
bool verifyInstruction(const MachineInstr &MI, StringRef &ErrInfo) const override
unsigned getInstrLatency(const InstrItineraryData *ItinData, const MachineInstr &MI, unsigned *PredCost=nullptr) const override
bool isLegalGFX12PlusPackedMathFP32or64BitOperand(const MachineRegisterInfo &MRI, const MachineInstr &MI, unsigned SrcN, const MachineOperand *MO=nullptr) const
Check if MO would be a legal operand for gfx12+ packed math FP32 or 64 instructions.
unsigned getVectorRegSpillSaveOpcode(Register Reg, const TargetRegisterClass *RC, unsigned Size, const SIMachineFunctionInfo &MFI, bool NeedsCFI) const
int64_t getNamedImmOperand(const MachineInstr &MI, AMDGPU::OpName OperandName) const
Get required immediate operand.
ArrayRef< std::pair< int, const char * > > getSerializableTargetIndices() const override
bool regUsesConstantBus(const MachineOperand &Reg, const MachineRegisterInfo &MRI) const
static bool isMIMG(const MachineInstr &MI)
MachineOperand buildExtractSubRegOrImm(MachineBasicBlock::iterator MI, MachineRegisterInfo &MRI, const MachineOperand &SuperReg, const TargetRegisterClass *SuperRC, unsigned SubIdx, const TargetRegisterClass *SubRC) const
bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const override
bool isLegalRegOperand(const MachineRegisterInfo &MRI, const MCOperandInfo &OpInfo, const MachineOperand &MO) const
Check if MO (a register operand) is a legal register for the given operand description or operand ind...
static unsigned getNumWaitStates(const MachineInstr &MI)
Return the number of wait states that result from executing this instruction.
unsigned getVALUOp(const MachineInstr &MI) const
static bool modifiesModeRegister(const MachineInstr &MI)
Return true if the instruction modifies the mode register.q.
Register readlaneVGPRToSGPR(Register SrcReg, MachineInstr &UseMI, MachineRegisterInfo &MRI, const TargetRegisterClass *DstRC=nullptr) const
Copy a value from a VGPR (SrcReg) to SGPR.
bool hasDivergentBranch(const MachineBasicBlock *MBB) const
Return whether the block terminate with divergent branch.
std::pair< int64_t, int64_t > splitFlatOffset(int64_t COffsetVal, unsigned AddrSpace, AMDGPU::FlatAddrSpace FlatVariant) const
Split COffsetVal into {immediate offset field, remainder offset} values.
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
void fixImplicitOperands(MachineInstr &MI) const
bool moveFlatAddrToVGPR(MachineInstr &Inst) const
Change SADDR form of a FLAT Inst to its VADDR form if saddr operand was moved to VGPR.
void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const override
void createReadFirstLaneFromCopyToPhysReg(MachineRegisterInfo &MRI, Register DstReg, MachineInstr &Inst) const
bool swapSourceModifiers(MachineInstr &MI, MachineOperand &Src0, AMDGPU::OpName Src0OpName, MachineOperand &Src1, AMDGPU::OpName Src1OpName) const
Register insertNE(MachineBasicBlock *MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register SrcReg, int Value) const
MachineBasicBlock * getBranchDestBlock(const MachineInstr &MI) const override
bool hasUnwantedEffectsWhenEXECEmpty(const MachineInstr &MI) const
This function is used to determine if an instruction can be safely executed under EXEC = 0 without ha...
bool getConstValDefinedInReg(const MachineInstr &MI, const Register Reg, int64_t &ImmVal) const override
static bool isAtomic(const MachineInstr &MI)
bool canInsertSelect(const MachineBasicBlock &MBB, ArrayRef< MachineOperand > Cond, Register DstReg, Register TrueReg, Register FalseReg, int &CondCycles, int &TrueCycles, int &FalseCycles) const override
bool isLiteralOperandLegal(const MCInstrDesc &InstDesc, const MCOperandInfo &OpInfo) const
static bool isWWMRegSpillOpcode(uint32_t Opcode)
static bool sopkIsZext(unsigned Opcode)
static bool isSGPRSpill(const MachineInstr &MI)
static bool isWMMA(const MachineInstr &MI)
ArrayRef< std::pair< MachineMemOperand::Flags, const char * > > getSerializableMachineMemOperandTargetFlags() const override
MachineInstr * convertToThreeAddress(MachineInstr &MI, LiveVariables *LV, LiveIntervals *LIS) const override
bool mayReadEXEC(const MachineRegisterInfo &MRI, const MachineInstr &MI) const
Returns true if the instruction could potentially depend on the value of exec.
void legalizeOperandsSMRD(MachineRegisterInfo &MRI, MachineInstr &MI) const
bool isBranchOffsetInRange(unsigned BranchOpc, int64_t BrOffset) const override
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
void insertVectorSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DstReg, ArrayRef< MachineOperand > Cond, Register TrueReg, Register FalseReg) const
void insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
std::pair< MachineInstr *, MachineInstr * > expandMovDPP64(MachineInstr &MI) const
Register insertEQ(MachineBasicBlock *MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register SrcReg, int Value) const
static bool isSOPC(const MachineInstr &MI)
static bool isFLAT(const MachineInstr &MI)
static bool isVALU(const MachineInstr &MI)
bool isBarrier(unsigned Opcode) const
MachineInstr * commuteInstructionImpl(MachineInstr &MI, bool NewMI, unsigned OpIdx0, unsigned OpIdx1) const override
int pseudoToMCOpcode(int Opcode) const
Return a target-specific opcode if Opcode is a pseudo instruction.
const MCInstrDesc & getMCOpcodeFromPseudo(unsigned Opcode) const
Return the descriptor of the target-specific machine instruction that corresponds to the specified ps...
static bool usesVM_CNT(const MachineInstr &MI)
MachineInstr * createPHIDestinationCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, Register Dst) const override
static bool isFixedSize(const MachineInstr &MI)
bool isSafeToSink(MachineInstr &MI, MachineBasicBlock *SuccToSinkTo, MachineCycleInfo *CI) const override
LLVM_READONLY int commuteOpcode(unsigned Opc) const
ValueUniformity getValueUniformity(const MachineInstr &MI) const final
uint64_t getScratchRsrcWords23() const
LLVM_READONLY MachineOperand * getNamedOperand(MachineInstr &MI, AMDGPU::OpName OperandName) const
Returns the operand named Op.
std::pair< unsigned, unsigned > decomposeMachineOperandsTargetFlags(unsigned TF) const override
bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) const override
bool isOperandLegal(const MachineInstr &MI, unsigned OpIdx, const MachineOperand *MO=nullptr) const
Check if MO is a legal operand if it was the OpIdx Operand for MI.
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
bool allowNegativeFlatOffset(AMDGPU::FlatAddrSpace FlatVariant) const
Returns true if negative offsets are allowed for the given FlatVariant.
std::optional< int64_t > getImmOrMaterializedImm(MachineOperand &Op) const
void moveToVALUImpl(SIInstrWorklist &Worklist, MachineDominatorTree *MDT, MachineInstr &Inst, DenseMap< MachineInstr *, V2PhysSCopyInfo > &WaterFalls, DenseMap< MachineInstr *, bool > &V2SPhyCopiesToErase) const
static bool isLDSDMA(const MachineInstr &MI)
static bool isVOP1(const MachineInstr &MI)
SIInstrInfo(const GCNSubtarget &ST)
void insertIndirectBranch(MachineBasicBlock &MBB, MachineBasicBlock &NewDestBB, MachineBasicBlock &RestoreBB, const DebugLoc &DL, int64_t BrOffset, RegScavenger *RS) const override
bool hasAnyModifiersSet(const MachineInstr &MI) const
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
void setHasSpilledVGPRs(bool Spill=true)
bool isWWMReg(Register Reg) const
bool checkFlag(Register Reg, uint8_t Flag) const
void setHasSpilledSGPRs(bool Spill=true)
unsigned getScratchReservedForDynamicVGPRs() const
static unsigned getSubRegFromChannel(unsigned Channel, unsigned NumRegs=1)
ArrayRef< int16_t > getRegSplitParts(const TargetRegisterClass *RC, unsigned EltSize) const
unsigned getHWRegIndex(MCRegister Reg) const
bool isSGPRReg(const MachineRegisterInfo &MRI, Register Reg) const
unsigned getRegPressureLimit(const TargetRegisterClass *RC, MachineFunction &MF) const override
unsigned getChannelFromSubReg(unsigned SubReg) const
static bool isSGPRClass(const TargetRegisterClass *RC)
static bool isAGPRClass(const TargetRegisterClass *RC)
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
virtual bool hasVRegLiveness() const
Return true if this DAG supports VReg liveness and RegPressure.
MachineFunction & MF
Machine function.
HazardRecognizer - This determines whether or not an instruction can be issued this cycle,...
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SlotIndexes pass.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:301
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
int64_t getImm() const
Register getReg() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
virtual ScheduleHazardRecognizer * CreateTargetMIHazardRecognizer(const InstrItineraryData *, const ScheduleDAGMI *DAG) const
Allocate and return a hazard recognizer to use for this target when scheduling the machine instructio...
virtual MachineInstr * createPHIDestinationCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
virtual bool isReMaterializableImpl(const MachineInstr &MI) const
For instructions with opcodes for which the M_REMATERIALIZABLE flag is set, this hook lets the target...
virtual const MachineOperand & getCalleeOperand(const MachineInstr &MI) const
Returns the callee operand from the given MI.
virtual void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, unsigned SubIdx, const MachineInstr &Orig, LaneBitmask UsedLanes=LaneBitmask::getAll()) const
Re-issue the specified 'original' instruction at the specific location targeting a new destination re...
virtual MachineInstr * createPHISourceCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
virtual MachineInstr * commuteInstructionImpl(MachineInstr &MI, bool NewMI, unsigned OpIdx1, unsigned OpIdx2) const
This method commutes the operands of the given machine instruction MI.
virtual bool isGlobalMemoryObject(const MachineInstr *MI) const
Returns true if MI is an instruction we are unable to reason about (like a call or something with unm...
virtual bool expandPostRAPseudo(MachineInstr &MI) const
This function is called for all pseudo instructions that remain after register allocation.
const MCAsmInfo & getMCAsmInfo() const
Return target specific asm information.
bool contains(Register Reg) const
Return true if the specified register is included in this register class.
bool hasSuperClassEq(const TargetRegisterClass *RC) const
Returns true if RC is a super-class of or equal to this class.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:190
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
unsigned encodeFieldSaSdst(unsigned Encoded, unsigned SaSdst)
bool isInlinableLiteralBF16(int16_t Literal, bool HasInv2Pi)
const uint64_t RSRC_DATA_FORMAT
bool isPKFMACF16InlineConstant(uint32_t Literal, bool IsGFX11Plus)
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
bool isInlinableLiteralFP16(int16_t Literal, bool HasInv2Pi)
bool getWMMAIsXDL(unsigned Opc)
unsigned mapWMMA2AddrTo3AddrOpcode(unsigned Opc)
bool isInlinableLiteralV2I16(uint32_t Literal)
bool isDPMACCInstruction(unsigned Opc)
bool isHi16Reg(MCRegister Reg, const MCRegisterInfo &MRI)
bool isInlinableLiteralV2BF16(uint32_t Literal)
LLVM_READONLY int32_t getCommuteRev(uint32_t Opcode)
LLVM_READONLY int32_t getCommuteOrig(uint32_t Opcode)
unsigned getNumFlatOffsetBits(const MCSubtargetInfo &ST)
For pre-GFX12 FLAT instructions the offset must be positive; MSB is ignored and forced to zero.
bool isGFX12Plus(const MCSubtargetInfo &STI)
bool isInlinableLiteralV2F16(uint32_t Literal)
bool isValid32BitLiteral(uint64_t Val, bool IsFP64)
LLVM_READONLY int32_t getGlobalVaddrOp(uint32_t Opcode)
LLVM_READNONE bool isLegalDPALU_DPPControl(const MCSubtargetInfo &ST, unsigned DC)
LLVM_READONLY int32_t getMFMAEarlyClobberOp(uint32_t Opcode)
bool getMAIIsGFX940XDL(unsigned Opc)
const uint64_t RSRC_ELEMENT_SIZE_SHIFT
bool isIntrinsicAlwaysUniform(unsigned IntrID)
LLVM_READONLY bool hasNamedOperand(uint64_t Opcode, OpName NamedIdx)
LLVM_READONLY int32_t getIfAddr64Inst(uint32_t Opcode)
Check if Opcode is an Addr64 opcode.
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfoByEncoding(uint8_t DimEnc)
bool isInlinableLiteral32(int32_t Literal, bool HasInv2Pi)
const uint64_t RSRC_TID_ENABLE
LLVM_READONLY int32_t getVOPe32(uint32_t Opcode)
bool isIntrinsicSourceOfDivergence(unsigned IntrID)
constexpr bool isSISrcOperand(const MCOperandInfo &OpInfo)
Is this an AMDGPU specific source operand?
bool isGenericAtomic(unsigned Opc)
LLVM_READNONE bool isInlinableIntLiteral(int64_t Literal)
Is this literal inlinable, and not one of the values intended for floating point values.
unsigned getAddrSizeMIMGOp(const MIMGBaseOpcodeInfo *BaseOpcode, const MIMGDimInfo *Dim, bool IsA16, bool IsG16Supported)
LLVM_READONLY int32_t getAddr64Inst(uint32_t Opcode)
int32_t getMCOpcode(uint32_t Opcode, unsigned Gen)
bool isPackedFP32or64BitInst(unsigned Opc)
@ OPERAND_REG_IMM_V2FP64
Definition SIDefines.h:219
@ OPERAND_KIMM32
Operand with 32-bit immediate that uses the constant bus.
Definition SIDefines.h:237
@ OPERAND_REG_IMM_INT64
Definition SIDefines.h:206
@ OPERAND_REG_IMM_V2FP16
Definition SIDefines.h:213
@ OPERAND_REG_INLINE_C_FP64
Definition SIDefines.h:228
@ OPERAND_REG_INLINE_C_BF16
Definition SIDefines.h:225
@ OPERAND_REG_INLINE_C_V2BF16
Definition SIDefines.h:230
@ OPERAND_REG_IMM_V2INT16
Definition SIDefines.h:215
@ OPERAND_REG_IMM_BF16
Definition SIDefines.h:210
@ OPERAND_REG_IMM_INT32
Operands with register, 32-bit, or 64-bit immediate.
Definition SIDefines.h:205
@ OPERAND_REG_IMM_V2BF16
Definition SIDefines.h:212
@ OPERAND_REG_IMM_FP16
Definition SIDefines.h:211
@ OPERAND_REG_IMM_V2FP16_SPLAT
Definition SIDefines.h:214
@ OPERAND_REG_INLINE_C_INT64
Definition SIDefines.h:224
@ OPERAND_REG_INLINE_C_INT16
Operands with register or inline constant.
Definition SIDefines.h:222
@ OPERAND_REG_IMM_NOINLINE_V2FP16
Definition SIDefines.h:216
@ OPERAND_REG_IMM_FP64
Definition SIDefines.h:209
@ OPERAND_REG_INLINE_C_V2FP16
Definition SIDefines.h:231
@ OPERAND_REG_INLINE_AC_INT32
Operands with an AccVGPR register or inline constant.
Definition SIDefines.h:242
@ OPERAND_REG_INLINE_AC_FP32
Definition SIDefines.h:243
@ OPERAND_REG_IMM_V2INT32
Definition SIDefines.h:217
@ OPERAND_SDWA_VOPC_DST
Definition SIDefines.h:254
@ OPERAND_REG_IMM_FP32
Definition SIDefines.h:208
@ OPERAND_REG_INLINE_C_FP32
Definition SIDefines.h:227
@ OPERAND_REG_INLINE_C_INT32
Definition SIDefines.h:223
@ OPERAND_REG_INLINE_C_V2INT16
Definition SIDefines.h:229
@ OPERAND_INLINE_C_AV64_PSEUDO
Definition SIDefines.h:248
@ OPERAND_REG_IMM_V2FP32
Definition SIDefines.h:218
@ OPERAND_REG_INLINE_AC_FP64
Definition SIDefines.h:244
@ OPERAND_REG_INLINE_C_FP16
Definition SIDefines.h:226
@ OPERAND_REG_IMM_INT16
Definition SIDefines.h:207
@ OPERAND_INLINE_SPLIT_BARRIER_INT32
Definition SIDefines.h:234
LLVM_READONLY int32_t getBasicFromSDWAOp(uint32_t Opcode)
bool isDPALU_DPP(const MCInstrDesc &OpDesc, const MCInstrInfo &MII, const MCSubtargetInfo &ST)
@ TI_SCRATCH_RSRC_DWORD1
Definition AMDGPU.h:614
@ TI_SCRATCH_RSRC_DWORD3
Definition AMDGPU.h:616
@ TI_SCRATCH_RSRC_DWORD0
Definition AMDGPU.h:613
@ TI_SCRATCH_RSRC_DWORD2
Definition AMDGPU.h:615
@ TI_CONSTDATA_START
Definition AMDGPU.h:612
unsigned getRegBitWidth(const TargetRegisterClass &RC)
Get the size in bits of a register from the register class RC.
bool supportsScaleOffset(const MCInstrInfo &MII, unsigned Opcode)
const uint64_t RSRC_INDEX_STRIDE_SHIFT
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
LLVM_READONLY int32_t getFlatScratchInstSVfromSS(uint32_t Opcode)
bool isInlinableLiteralI16(int32_t Literal, bool HasInv2Pi)
LLVM_READNONE constexpr bool isGraphics(CallingConv::ID CC)
bool isInlinableLiteral64(int64_t Literal, bool HasInv2Pi)
Is this literal inlinable.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ OPERAND_GENERIC_4
Definition MCInstrDesc.h:71
@ OPERAND_GENERIC_2
Definition MCInstrDesc.h:69
@ OPERAND_GENERIC_1
Definition MCInstrDesc.h:68
@ OPERAND_GENERIC_3
Definition MCInstrDesc.h:70
@ OPERAND_IMMEDIATE
Definition MCInstrDesc.h:61
@ OPERAND_GENERIC_0
Definition MCInstrDesc.h:67
@ OPERAND_GENERIC_5
Definition MCInstrDesc.h:72
Not(const Pred &P) -> Not< Pred >
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:558
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
TargetInstrInfo::RegSubRegPair getRegSubRegPair(const MachineOperand &O)
Create RegSubRegPair from a register MachineOperand.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1738
constexpr uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition MathExtras.h:207
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
bool execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI, Register VReg, const MachineInstr &DefMI, const MachineInstr &UseMI)
Return false if EXEC is not changed between the def of VReg at DefMI and the use at UseMI.
RegState
Flags to represent properties of register accesses.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
@ Define
Register definition.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2553
constexpr RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
Op::Description Desc
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
TargetInstrInfo::RegSubRegPair getRegSequenceSubReg(MachineInstr &MI, unsigned SubReg)
Return the SubReg component from REG_SEQUENCE.
static const MachineMemOperand::Flags MONoClobber
Mark the MMO of a uniform load if there are no potentially clobbering stores on any path from the sta...
Definition SIInstrInfo.h:44
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
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:1745
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:331
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
MachineInstr * getVRegSubRegDef(const TargetInstrInfo::RegSubRegPair &P, const MachineRegisterInfo &MRI)
Return the defining instruction for a given reg:subreg pair skipping copy like instructions and subre...
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:150
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:155
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI VirtRegInfo AnalyzeVirtRegInBundle(MachineInstr &MI, Register Reg, SmallVectorImpl< std::pair< MachineInstr *, unsigned > > *Ops=nullptr)
AnalyzeVirtRegInBundle - Analyze how the current instruction or bundle uses a virtual register.
static const MachineMemOperand::Flags MOCooperative
Mark the MMO of cooperative load/store atomics.
Definition SIInstrInfo.h:52
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:394
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
@ Xor
Bitwise or logical XOR of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
bool isTargetSpecificOpcode(unsigned Opcode)
Check whether the given Opcode is a target-specific opcode.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned DefaultMemoryClusterDWordsLimit
Definition SIInstrInfo.h:40
constexpr unsigned BitWidth
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:248
static const MachineMemOperand::Flags MOLastUse
Mark the MMO of a load as the last use.
Definition SIInstrInfo.h:48
constexpr T reverseBits(T Val)
Reverse the bits in Val.
Definition MathExtras.h:118
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:77
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
constexpr RegState getUndefRegState(bool B)
ValueUniformity
Enum describing how values behave with respect to uniformity and divergence, to answer the question: ...
Definition Uniformity.h:18
@ AlwaysUniform
The result value is always uniform.
Definition Uniformity.h:23
@ NeverUniform
The result value can never be assumed to be uniform.
Definition Uniformity.h:26
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
MachineCycleInfo::CycleT MachineCycle
static const MachineMemOperand::Flags MOThreadPrivate
Mark the MMO of accesses to memory locations that are never written to by other threads.
Definition SIInstrInfo.h:63
bool execMayBeModifiedBeforeAnyUse(const MachineRegisterInfo &MRI, Register VReg, const MachineInstr &DefMI)
Return false if EXEC is not changed between the def of VReg at DefMI and all its uses.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:862
#define N
Helper struct for the implementation of 3-address conversion to communicate updates made to instructi...
MachineInstr * RemoveMIUse
Other instruction whose def is no longer used by the converted instruction.
static constexpr uint64_t encode(Fields... Values)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
constexpr bool all() const
Definition LaneBitmask.h:54
SparseBitVector AliveBlocks
AliveBlocks - Set of blocks in which this value is alive completely through.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
Utility to store machine instructions worklist.
Definition SIInstrInfo.h:67
MachineInstr * top() const
Definition SIInstrInfo.h:72
bool isDeferred(MachineInstr *MI)
SetVector< MachineInstr * > & getDeferredList()
Definition SIInstrInfo.h:91
void insert(MachineInstr *MI)
A pair composed of a register and a sub-register index.
VirtRegInfo - Information about a virtual register used by a set of operands.
bool Reads
Reads - One of the operands read the virtual register.
bool Writes
Writes - One of the operands writes the virtual register.