LLVM 22.0.0git
SPIRVInstructionSelector.cpp
Go to the documentation of this file.
1//===- SPIRVInstructionSelector.cpp ------------------------------*- C++ -*-==//
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// This file implements the targeting of the InstructionSelector class for
10// SPIRV.
11// TODO: This should be generated by TableGen.
12//
13//===----------------------------------------------------------------------===//
14
17#include "SPIRV.h"
18#include "SPIRVGlobalRegistry.h"
19#include "SPIRVInstrInfo.h"
20#include "SPIRVRegisterInfo.h"
21#include "SPIRVTargetMachine.h"
22#include "SPIRVUtils.h"
23#include "llvm/ADT/APFloat.h"
32#include "llvm/IR/IntrinsicsSPIRV.h"
33#include "llvm/Support/Debug.h"
35
36#define DEBUG_TYPE "spirv-isel"
37
38using namespace llvm;
39namespace CL = SPIRV::OpenCLExtInst;
40namespace GL = SPIRV::GLSLExtInst;
41
43 std::vector<std::pair<SPIRV::InstructionSet::InstructionSet, uint32_t>>;
44
45namespace {
46
47llvm::SPIRV::SelectionControl::SelectionControl
48getSelectionOperandForImm(int Imm) {
49 if (Imm == 2)
50 return SPIRV::SelectionControl::Flatten;
51 if (Imm == 1)
52 return SPIRV::SelectionControl::DontFlatten;
53 if (Imm == 0)
54 return SPIRV::SelectionControl::None;
55 llvm_unreachable("Invalid immediate");
56}
57
58#define GET_GLOBALISEL_PREDICATE_BITSET
59#include "SPIRVGenGlobalISel.inc"
60#undef GET_GLOBALISEL_PREDICATE_BITSET
61
62class SPIRVInstructionSelector : public InstructionSelector {
63 const SPIRVSubtarget &STI;
64 const SPIRVInstrInfo &TII;
66 const RegisterBankInfo &RBI;
69 MachineFunction *HasVRegsReset = nullptr;
70
71 /// We need to keep track of the number we give to anonymous global values to
72 /// generate the same name every time when this is needed.
73 mutable DenseMap<const GlobalValue *, unsigned> UnnamedGlobalIDs;
75
76public:
77 SPIRVInstructionSelector(const SPIRVTargetMachine &TM,
78 const SPIRVSubtarget &ST,
79 const RegisterBankInfo &RBI);
80 void setupMF(MachineFunction &MF, GISelValueTracking *VT,
81 CodeGenCoverage *CoverageInfo, ProfileSummaryInfo *PSI,
82 BlockFrequencyInfo *BFI) override;
83 // Common selection code. Instruction-specific selection occurs in spvSelect.
84 bool select(MachineInstr &I) override;
85 static const char *getName() { return DEBUG_TYPE; }
86
87#define GET_GLOBALISEL_PREDICATES_DECL
88#include "SPIRVGenGlobalISel.inc"
89#undef GET_GLOBALISEL_PREDICATES_DECL
90
91#define GET_GLOBALISEL_TEMPORARIES_DECL
92#include "SPIRVGenGlobalISel.inc"
93#undef GET_GLOBALISEL_TEMPORARIES_DECL
94
95private:
96 void resetVRegsType(MachineFunction &MF);
97
98 // tblgen-erated 'select' implementation, used as the initial selector for
99 // the patterns that don't require complex C++.
100 bool selectImpl(MachineInstr &I, CodeGenCoverage &CoverageInfo) const;
101
102 // All instruction-specific selection that didn't happen in "select()".
103 // Is basically a large Switch/Case delegating to all other select method.
104 bool spvSelect(Register ResVReg, const SPIRVType *ResType,
105 MachineInstr &I) const;
106
107 bool selectFirstBitHigh(Register ResVReg, const SPIRVType *ResType,
108 MachineInstr &I, bool IsSigned) const;
109
110 bool selectFirstBitLow(Register ResVReg, const SPIRVType *ResType,
111 MachineInstr &I) const;
112
113 bool selectFirstBitSet16(Register ResVReg, const SPIRVType *ResType,
114 MachineInstr &I, unsigned ExtendOpcode,
115 unsigned BitSetOpcode) const;
116
117 bool selectFirstBitSet32(Register ResVReg, const SPIRVType *ResType,
118 MachineInstr &I, Register SrcReg,
119 unsigned BitSetOpcode) const;
120
121 bool selectFirstBitSet64(Register ResVReg, const SPIRVType *ResType,
122 MachineInstr &I, Register SrcReg,
123 unsigned BitSetOpcode, bool SwapPrimarySide) const;
124
125 bool selectFirstBitSet64Overflow(Register ResVReg, const SPIRVType *ResType,
126 MachineInstr &I, Register SrcReg,
127 unsigned BitSetOpcode,
128 bool SwapPrimarySide) const;
129
130 bool selectGlobalValue(Register ResVReg, MachineInstr &I,
131 const MachineInstr *Init = nullptr) const;
132
133 bool selectOpWithSrcs(Register ResVReg, const SPIRVType *ResType,
134 MachineInstr &I, std::vector<Register> SrcRegs,
135 unsigned Opcode) const;
136
137 bool selectUnOp(Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
138 unsigned Opcode) const;
139
140 bool selectBitcast(Register ResVReg, const SPIRVType *ResType,
141 MachineInstr &I) const;
142
143 bool selectLoad(Register ResVReg, const SPIRVType *ResType,
144 MachineInstr &I) const;
145 bool selectStore(MachineInstr &I) const;
146
147 bool selectStackSave(Register ResVReg, const SPIRVType *ResType,
148 MachineInstr &I) const;
149 bool selectStackRestore(MachineInstr &I) const;
150
151 bool selectMemOperation(Register ResVReg, MachineInstr &I) const;
152
153 bool selectAtomicRMW(Register ResVReg, const SPIRVType *ResType,
154 MachineInstr &I, unsigned NewOpcode,
155 unsigned NegateOpcode = 0) const;
156
157 bool selectAtomicCmpXchg(Register ResVReg, const SPIRVType *ResType,
158 MachineInstr &I) const;
159
160 bool selectFence(MachineInstr &I) const;
161
162 bool selectAddrSpaceCast(Register ResVReg, const SPIRVType *ResType,
163 MachineInstr &I) const;
164
165 bool selectAnyOrAll(Register ResVReg, const SPIRVType *ResType,
166 MachineInstr &I, unsigned OpType) const;
167
168 bool selectAll(Register ResVReg, const SPIRVType *ResType,
169 MachineInstr &I) const;
170
171 bool selectAny(Register ResVReg, const SPIRVType *ResType,
172 MachineInstr &I) const;
173
174 bool selectBitreverse(Register ResVReg, const SPIRVType *ResType,
175 MachineInstr &I) const;
176
177 bool selectBuildVector(Register ResVReg, const SPIRVType *ResType,
178 MachineInstr &I) const;
179 bool selectSplatVector(Register ResVReg, const SPIRVType *ResType,
180 MachineInstr &I) const;
181
182 bool selectCmp(Register ResVReg, const SPIRVType *ResType,
183 unsigned comparisonOpcode, MachineInstr &I) const;
184 bool selectDiscard(Register ResVReg, const SPIRVType *ResType,
185 MachineInstr &I) const;
186
187 bool selectICmp(Register ResVReg, const SPIRVType *ResType,
188 MachineInstr &I) const;
189 bool selectFCmp(Register ResVReg, const SPIRVType *ResType,
190 MachineInstr &I) const;
191
192 bool selectSign(Register ResVReg, const SPIRVType *ResType,
193 MachineInstr &I) const;
194
195 bool selectFloatDot(Register ResVReg, const SPIRVType *ResType,
196 MachineInstr &I) const;
197
198 bool selectOverflowArith(Register ResVReg, const SPIRVType *ResType,
199 MachineInstr &I, unsigned Opcode) const;
200
201 bool selectIntegerDot(Register ResVReg, const SPIRVType *ResType,
202 MachineInstr &I, bool Signed) const;
203
204 bool selectIntegerDotExpansion(Register ResVReg, const SPIRVType *ResType,
205 MachineInstr &I) const;
206
207 template <bool Signed>
208 bool selectDot4AddPacked(Register ResVReg, const SPIRVType *ResType,
209 MachineInstr &I) const;
210 template <bool Signed>
211 bool selectDot4AddPackedExpansion(Register ResVReg, const SPIRVType *ResType,
212 MachineInstr &I) const;
213
214 bool selectWaveReduceMax(Register ResVReg, const SPIRVType *ResType,
215 MachineInstr &I, bool IsUnsigned) const;
216
217 bool selectWaveReduceSum(Register ResVReg, const SPIRVType *ResType,
218 MachineInstr &I) const;
219
220 bool selectConst(Register ResVReg, const SPIRVType *ResType,
221 MachineInstr &I) const;
222
223 bool selectSelect(Register ResVReg, const SPIRVType *ResType,
224 MachineInstr &I) const;
225 bool selectSelectDefaultArgs(Register ResVReg, const SPIRVType *ResType,
226 MachineInstr &I, bool IsSigned) const;
227 bool selectIToF(Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
228 bool IsSigned, unsigned Opcode) const;
229 bool selectExt(Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
230 bool IsSigned) const;
231
232 bool selectTrunc(Register ResVReg, const SPIRVType *ResType,
233 MachineInstr &I) const;
234
235 bool selectSUCmp(Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
236 bool IsSigned) const;
237
238 bool selectIntToBool(Register IntReg, Register ResVReg, MachineInstr &I,
239 const SPIRVType *intTy, const SPIRVType *boolTy) const;
240
241 bool selectOpUndef(Register ResVReg, const SPIRVType *ResType,
242 MachineInstr &I) const;
243 bool selectFreeze(Register ResVReg, const SPIRVType *ResType,
244 MachineInstr &I) const;
245 bool selectIntrinsic(Register ResVReg, const SPIRVType *ResType,
246 MachineInstr &I) const;
247 bool selectExtractVal(Register ResVReg, const SPIRVType *ResType,
248 MachineInstr &I) const;
249 bool selectInsertVal(Register ResVReg, const SPIRVType *ResType,
250 MachineInstr &I) const;
251 bool selectExtractElt(Register ResVReg, const SPIRVType *ResType,
252 MachineInstr &I) const;
253 bool selectInsertElt(Register ResVReg, const SPIRVType *ResType,
254 MachineInstr &I) const;
255 bool selectGEP(Register ResVReg, const SPIRVType *ResType,
256 MachineInstr &I) const;
257
258 bool selectFrameIndex(Register ResVReg, const SPIRVType *ResType,
259 MachineInstr &I) const;
260 bool selectAllocaArray(Register ResVReg, const SPIRVType *ResType,
261 MachineInstr &I) const;
262
263 bool selectBranch(MachineInstr &I) const;
264 bool selectBranchCond(MachineInstr &I) const;
265
266 bool selectPhi(Register ResVReg, const SPIRVType *ResType,
267 MachineInstr &I) const;
268
269 bool selectExtInst(Register ResVReg, const SPIRVType *RestType,
270 MachineInstr &I, GL::GLSLExtInst GLInst) const;
271 bool selectExtInst(Register ResVReg, const SPIRVType *ResType,
272 MachineInstr &I, CL::OpenCLExtInst CLInst) const;
273 bool selectExtInst(Register ResVReg, const SPIRVType *ResType,
274 MachineInstr &I, CL::OpenCLExtInst CLInst,
275 GL::GLSLExtInst GLInst) const;
276 bool selectExtInst(Register ResVReg, const SPIRVType *ResType,
277 MachineInstr &I, const ExtInstList &ExtInsts) const;
278
279 bool selectLog10(Register ResVReg, const SPIRVType *ResType,
280 MachineInstr &I) const;
281
282 bool selectSaturate(Register ResVReg, const SPIRVType *ResType,
283 MachineInstr &I) const;
284
285 bool selectWaveOpInst(Register ResVReg, const SPIRVType *ResType,
286 MachineInstr &I, unsigned Opcode) const;
287
288 bool selectWaveActiveCountBits(Register ResVReg, const SPIRVType *ResType,
289 MachineInstr &I) const;
290
292
293 bool selectHandleFromBinding(Register &ResVReg, const SPIRVType *ResType,
294 MachineInstr &I) const;
295
296 bool selectReadImageIntrinsic(Register &ResVReg, const SPIRVType *ResType,
297 MachineInstr &I) const;
298 bool selectImageWriteIntrinsic(MachineInstr &I) const;
299 bool selectResourceGetPointer(Register &ResVReg, const SPIRVType *ResType,
300 MachineInstr &I) const;
301 bool selectModf(Register ResVReg, const SPIRVType *ResType,
302 MachineInstr &I) const;
303
304 // Utilities
305 std::pair<Register, bool>
306 buildI32Constant(uint32_t Val, MachineInstr &I,
307 const SPIRVType *ResType = nullptr) const;
308
309 Register buildZerosVal(const SPIRVType *ResType, MachineInstr &I) const;
310 Register buildZerosValF(const SPIRVType *ResType, MachineInstr &I) const;
311 Register buildOnesVal(bool AllOnes, const SPIRVType *ResType,
312 MachineInstr &I) const;
313 Register buildOnesValF(const SPIRVType *ResType, MachineInstr &I) const;
314
315 bool wrapIntoSpecConstantOp(MachineInstr &I,
316 SmallVector<Register> &CompositeArgs) const;
317
318 Register getUcharPtrTypeReg(MachineInstr &I,
319 SPIRV::StorageClass::StorageClass SC) const;
320 MachineInstrBuilder buildSpecConstantOp(MachineInstr &I, Register Dest,
321 Register Src, Register DestType,
322 uint32_t Opcode) const;
323 MachineInstrBuilder buildConstGenericPtr(MachineInstr &I, Register SrcPtr,
324 SPIRVType *SrcPtrTy) const;
325 Register buildPointerToResource(const SPIRVType *ResType,
326 SPIRV::StorageClass::StorageClass SC,
328 uint32_t ArraySize, Register IndexReg,
329 bool IsNonUniform, StringRef Name,
330 MachineIRBuilder MIRBuilder) const;
331 SPIRVType *widenTypeToVec4(const SPIRVType *Type, MachineInstr &I) const;
332 bool extractSubvector(Register &ResVReg, const SPIRVType *ResType,
333 Register &ReadReg, MachineInstr &InsertionPoint) const;
334 bool generateImageRead(Register &ResVReg, const SPIRVType *ResType,
335 Register ImageReg, Register IdxReg, DebugLoc Loc,
336 MachineInstr &Pos) const;
337 bool BuildCOPY(Register DestReg, Register SrcReg, MachineInstr &I) const;
338 bool loadVec3BuiltinInputID(SPIRV::BuiltIn::BuiltIn BuiltInValue,
339 Register ResVReg, const SPIRVType *ResType,
340 MachineInstr &I) const;
341 bool loadBuiltinInputID(SPIRV::BuiltIn::BuiltIn BuiltInValue,
342 Register ResVReg, const SPIRVType *ResType,
343 MachineInstr &I) const;
344 bool loadHandleBeforePosition(Register &HandleReg, const SPIRVType *ResType,
345 GIntrinsic &HandleDef, MachineInstr &Pos) const;
346};
347
348bool sampledTypeIsSignedInteger(const llvm::Type *HandleType) {
349 const TargetExtType *TET = cast<TargetExtType>(HandleType);
350 if (TET->getTargetExtName() == "spirv.Image") {
351 return false;
352 }
353 assert(TET->getTargetExtName() == "spirv.SignedImage");
354 return TET->getTypeParameter(0)->isIntegerTy();
355}
356} // end anonymous namespace
357
358#define GET_GLOBALISEL_IMPL
359#include "SPIRVGenGlobalISel.inc"
360#undef GET_GLOBALISEL_IMPL
361
362SPIRVInstructionSelector::SPIRVInstructionSelector(const SPIRVTargetMachine &TM,
363 const SPIRVSubtarget &ST,
364 const RegisterBankInfo &RBI)
365 : InstructionSelector(), STI(ST), TII(*ST.getInstrInfo()),
366 TRI(*ST.getRegisterInfo()), RBI(RBI), GR(*ST.getSPIRVGlobalRegistry()),
367 MRI(nullptr),
369#include "SPIRVGenGlobalISel.inc"
372#include "SPIRVGenGlobalISel.inc"
374{
375}
376
377void SPIRVInstructionSelector::setupMF(MachineFunction &MF,
379 CodeGenCoverage *CoverageInfo,
381 BlockFrequencyInfo *BFI) {
382 MRI = &MF.getRegInfo();
383 GR.setCurrentFunc(MF);
384 InstructionSelector::setupMF(MF, VT, CoverageInfo, PSI, BFI);
385}
386
387// Ensure that register classes correspond to pattern matching rules.
388void SPIRVInstructionSelector::resetVRegsType(MachineFunction &MF) {
389 if (HasVRegsReset == &MF)
390 return;
391 HasVRegsReset = &MF;
392
394 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
396 LLT RegType = MRI.getType(Reg);
397 if (RegType.isScalar())
398 MRI.setType(Reg, LLT::scalar(64));
399 else if (RegType.isPointer())
400 MRI.setType(Reg, LLT::pointer(0, 64));
401 else if (RegType.isVector())
402 MRI.setType(Reg, LLT::fixed_vector(2, LLT::scalar(64)));
403 }
404 for (const auto &MBB : MF) {
405 for (const auto &MI : MBB) {
406 if (isPreISelGenericOpcode(MI.getOpcode()))
407 GR.erase(&MI);
408 if (MI.getOpcode() != SPIRV::ASSIGN_TYPE)
409 continue;
410
411 Register DstReg = MI.getOperand(0).getReg();
412 LLT DstType = MRI.getType(DstReg);
413 Register SrcReg = MI.getOperand(1).getReg();
414 LLT SrcType = MRI.getType(SrcReg);
415 if (DstType != SrcType)
416 MRI.setType(DstReg, MRI.getType(SrcReg));
417
418 const TargetRegisterClass *DstRC = MRI.getRegClassOrNull(DstReg);
419 const TargetRegisterClass *SrcRC = MRI.getRegClassOrNull(SrcReg);
420 if (DstRC != SrcRC && SrcRC)
421 MRI.setRegClass(DstReg, SrcRC);
422 }
423 }
424}
425
426// Return true if the type represents a constant register
429 OpDef = passCopy(OpDef, MRI);
430
431 if (Visited.contains(OpDef))
432 return true;
433 Visited.insert(OpDef);
434
435 unsigned Opcode = OpDef->getOpcode();
436 switch (Opcode) {
437 case TargetOpcode::G_CONSTANT:
438 case TargetOpcode::G_FCONSTANT:
439 return true;
440 case TargetOpcode::G_INTRINSIC:
441 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
442 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS:
443 return cast<GIntrinsic>(*OpDef).getIntrinsicID() ==
444 Intrinsic::spv_const_composite;
445 case TargetOpcode::G_BUILD_VECTOR:
446 case TargetOpcode::G_SPLAT_VECTOR: {
447 for (unsigned i = OpDef->getNumExplicitDefs(); i < OpDef->getNumOperands();
448 i++) {
449 MachineInstr *OpNestedDef =
450 OpDef->getOperand(i).isReg()
451 ? MRI->getVRegDef(OpDef->getOperand(i).getReg())
452 : nullptr;
453 if (OpNestedDef && !isConstReg(MRI, OpNestedDef, Visited))
454 return false;
455 }
456 return true;
457 case SPIRV::OpConstantTrue:
458 case SPIRV::OpConstantFalse:
459 case SPIRV::OpConstantI:
460 case SPIRV::OpConstantF:
461 case SPIRV::OpConstantComposite:
462 case SPIRV::OpConstantCompositeContinuedINTEL:
463 case SPIRV::OpConstantSampler:
464 case SPIRV::OpConstantNull:
465 case SPIRV::OpUndef:
466 case SPIRV::OpConstantFunctionPointerINTEL:
467 return true;
468 }
469 }
470 return false;
471}
472
473// Return true if the virtual register represents a constant
476 if (MachineInstr *OpDef = MRI->getVRegDef(OpReg))
477 return isConstReg(MRI, OpDef, Visited);
478 return false;
479}
480
482 for (const auto &MO : MI.all_defs()) {
483 Register Reg = MO.getReg();
484 if (Reg.isPhysical() || !MRI.use_nodbg_empty(Reg))
485 return false;
486 }
487 if (MI.getOpcode() == TargetOpcode::LOCAL_ESCAPE || MI.isFakeUse() ||
488 MI.isLifetimeMarker())
489 return false;
490 if (MI.isPHI())
491 return true;
492 if (MI.mayStore() || MI.isCall() ||
493 (MI.mayLoad() && MI.hasOrderedMemoryRef()) || MI.isPosition() ||
494 MI.isDebugInstr() || MI.isTerminator() || MI.isJumpTableDebugInfo())
495 return false;
496 return true;
497}
498
499bool SPIRVInstructionSelector::select(MachineInstr &I) {
500 resetVRegsType(*I.getParent()->getParent());
501
502 assert(I.getParent() && "Instruction should be in a basic block!");
503 assert(I.getParent()->getParent() && "Instruction should be in a function!");
504
505 Register Opcode = I.getOpcode();
506 // If it's not a GMIR instruction, we've selected it already.
507 if (!isPreISelGenericOpcode(Opcode)) {
508 if (Opcode == SPIRV::ASSIGN_TYPE) { // These pseudos aren't needed any more.
509 Register DstReg = I.getOperand(0).getReg();
510 Register SrcReg = I.getOperand(1).getReg();
511 auto *Def = MRI->getVRegDef(SrcReg);
512 if (isTypeFoldingSupported(Def->getOpcode()) &&
513 Def->getOpcode() != TargetOpcode::G_CONSTANT &&
514 Def->getOpcode() != TargetOpcode::G_FCONSTANT) {
515 bool Res = false;
516 if (Def->getOpcode() == TargetOpcode::G_SELECT) {
517 Register SelectDstReg = Def->getOperand(0).getReg();
518 Res = selectSelect(SelectDstReg, GR.getSPIRVTypeForVReg(SelectDstReg),
519 *Def);
520 GR.invalidateMachineInstr(Def);
521 Def->removeFromParent();
522 MRI->replaceRegWith(DstReg, SelectDstReg);
523 GR.invalidateMachineInstr(&I);
524 I.removeFromParent();
525 } else
526 Res = selectImpl(I, *CoverageInfo);
527 LLVM_DEBUG({
528 if (!Res && Def->getOpcode() != TargetOpcode::G_CONSTANT) {
529 dbgs() << "Unexpected pattern in ASSIGN_TYPE.\nInstruction: ";
530 I.print(dbgs());
531 }
532 });
533 assert(Res || Def->getOpcode() == TargetOpcode::G_CONSTANT);
534 if (Res) {
535 if (!isTriviallyDead(*Def, *MRI) && isDead(*Def, *MRI))
536 DeadMIs.insert(Def);
537 return Res;
538 }
539 }
540 MRI->setRegClass(SrcReg, MRI->getRegClass(DstReg));
541 MRI->replaceRegWith(SrcReg, DstReg);
542 GR.invalidateMachineInstr(&I);
543 I.removeFromParent();
544 return true;
545 } else if (I.getNumDefs() == 1) {
546 // Make all vregs 64 bits (for SPIR-V IDs).
547 MRI->setType(I.getOperand(0).getReg(), LLT::scalar(64));
548 }
550 }
551
552 if (DeadMIs.contains(&I)) {
553 // if the instruction has been already made dead by folding it away
554 // erase it
555 LLVM_DEBUG(dbgs() << "Instruction is folded and dead.\n");
557 GR.invalidateMachineInstr(&I);
558 I.eraseFromParent();
559 return true;
560 }
561
562 if (I.getNumOperands() != I.getNumExplicitOperands()) {
563 LLVM_DEBUG(errs() << "Generic instr has unexpected implicit operands\n");
564 return false;
565 }
566
567 // Common code for getting return reg+type, and removing selected instr
568 // from parent occurs here. Instr-specific selection happens in spvSelect().
569 bool HasDefs = I.getNumDefs() > 0;
570 Register ResVReg = HasDefs ? I.getOperand(0).getReg() : Register(0);
571 SPIRVType *ResType = HasDefs ? GR.getSPIRVTypeForVReg(ResVReg) : nullptr;
572 assert(!HasDefs || ResType || I.getOpcode() == TargetOpcode::G_GLOBAL_VALUE ||
573 I.getOpcode() == TargetOpcode::G_IMPLICIT_DEF);
574 if (spvSelect(ResVReg, ResType, I)) {
575 if (HasDefs) // Make all vregs 64 bits (for SPIR-V IDs).
576 for (unsigned i = 0; i < I.getNumDefs(); ++i)
577 MRI->setType(I.getOperand(i).getReg(), LLT::scalar(64));
578 GR.invalidateMachineInstr(&I);
579 I.removeFromParent();
580 return true;
581 }
582 return false;
583}
584
585static bool mayApplyGenericSelection(unsigned Opcode) {
586 switch (Opcode) {
587 case TargetOpcode::G_CONSTANT:
588 case TargetOpcode::G_FCONSTANT:
589 return false;
590 case TargetOpcode::G_SADDO:
591 case TargetOpcode::G_SSUBO:
592 return true;
593 }
594 return isTypeFoldingSupported(Opcode);
595}
596
597bool SPIRVInstructionSelector::BuildCOPY(Register DestReg, Register SrcReg,
598 MachineInstr &I) const {
599 const TargetRegisterClass *DstRC = MRI->getRegClassOrNull(DestReg);
600 const TargetRegisterClass *SrcRC = MRI->getRegClassOrNull(SrcReg);
601 if (DstRC != SrcRC && SrcRC)
602 MRI->setRegClass(DestReg, SrcRC);
603 return BuildMI(*I.getParent(), I, I.getDebugLoc(),
604 TII.get(TargetOpcode::COPY))
605 .addDef(DestReg)
606 .addUse(SrcReg)
607 .constrainAllUses(TII, TRI, RBI);
608}
609
610bool SPIRVInstructionSelector::spvSelect(Register ResVReg,
611 const SPIRVType *ResType,
612 MachineInstr &I) const {
613 const unsigned Opcode = I.getOpcode();
614 if (mayApplyGenericSelection(Opcode))
615 return selectImpl(I, *CoverageInfo);
616 switch (Opcode) {
617 case TargetOpcode::G_CONSTANT:
618 case TargetOpcode::G_FCONSTANT:
619 return selectConst(ResVReg, ResType, I);
620 case TargetOpcode::G_GLOBAL_VALUE:
621 return selectGlobalValue(ResVReg, I);
622 case TargetOpcode::G_IMPLICIT_DEF:
623 return selectOpUndef(ResVReg, ResType, I);
624 case TargetOpcode::G_FREEZE:
625 return selectFreeze(ResVReg, ResType, I);
626
627 case TargetOpcode::G_INTRINSIC:
628 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
629 case TargetOpcode::G_INTRINSIC_CONVERGENT:
630 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS:
631 return selectIntrinsic(ResVReg, ResType, I);
632 case TargetOpcode::G_BITREVERSE:
633 return selectBitreverse(ResVReg, ResType, I);
634
635 case TargetOpcode::G_BUILD_VECTOR:
636 return selectBuildVector(ResVReg, ResType, I);
637 case TargetOpcode::G_SPLAT_VECTOR:
638 return selectSplatVector(ResVReg, ResType, I);
639
640 case TargetOpcode::G_SHUFFLE_VECTOR: {
641 MachineBasicBlock &BB = *I.getParent();
642 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpVectorShuffle))
643 .addDef(ResVReg)
644 .addUse(GR.getSPIRVTypeID(ResType))
645 .addUse(I.getOperand(1).getReg())
646 .addUse(I.getOperand(2).getReg());
647 for (auto V : I.getOperand(3).getShuffleMask())
648 MIB.addImm(V);
649 return MIB.constrainAllUses(TII, TRI, RBI);
650 }
651 case TargetOpcode::G_MEMMOVE:
652 case TargetOpcode::G_MEMCPY:
653 case TargetOpcode::G_MEMSET:
654 return selectMemOperation(ResVReg, I);
655
656 case TargetOpcode::G_ICMP:
657 return selectICmp(ResVReg, ResType, I);
658 case TargetOpcode::G_FCMP:
659 return selectFCmp(ResVReg, ResType, I);
660
661 case TargetOpcode::G_FRAME_INDEX:
662 return selectFrameIndex(ResVReg, ResType, I);
663
664 case TargetOpcode::G_LOAD:
665 return selectLoad(ResVReg, ResType, I);
666 case TargetOpcode::G_STORE:
667 return selectStore(I);
668
669 case TargetOpcode::G_BR:
670 return selectBranch(I);
671 case TargetOpcode::G_BRCOND:
672 return selectBranchCond(I);
673
674 case TargetOpcode::G_PHI:
675 return selectPhi(ResVReg, ResType, I);
676
677 case TargetOpcode::G_FPTOSI:
678 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertFToS);
679 case TargetOpcode::G_FPTOUI:
680 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertFToU);
681
682 case TargetOpcode::G_FPTOSI_SAT:
683 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertFToS);
684 case TargetOpcode::G_FPTOUI_SAT:
685 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertFToU);
686
687 case TargetOpcode::G_SITOFP:
688 return selectIToF(ResVReg, ResType, I, true, SPIRV::OpConvertSToF);
689 case TargetOpcode::G_UITOFP:
690 return selectIToF(ResVReg, ResType, I, false, SPIRV::OpConvertUToF);
691
692 case TargetOpcode::G_CTPOP:
693 return selectUnOp(ResVReg, ResType, I, SPIRV::OpBitCount);
694 case TargetOpcode::G_SMIN:
695 return selectExtInst(ResVReg, ResType, I, CL::s_min, GL::SMin);
696 case TargetOpcode::G_UMIN:
697 return selectExtInst(ResVReg, ResType, I, CL::u_min, GL::UMin);
698
699 case TargetOpcode::G_SMAX:
700 return selectExtInst(ResVReg, ResType, I, CL::s_max, GL::SMax);
701 case TargetOpcode::G_UMAX:
702 return selectExtInst(ResVReg, ResType, I, CL::u_max, GL::UMax);
703
704 case TargetOpcode::G_SCMP:
705 return selectSUCmp(ResVReg, ResType, I, true);
706 case TargetOpcode::G_UCMP:
707 return selectSUCmp(ResVReg, ResType, I, false);
708
709 case TargetOpcode::G_STRICT_FMA:
710 case TargetOpcode::G_FMA:
711 return selectExtInst(ResVReg, ResType, I, CL::fma, GL::Fma);
712
713 case TargetOpcode::G_STRICT_FLDEXP:
714 return selectExtInst(ResVReg, ResType, I, CL::ldexp);
715
716 case TargetOpcode::G_FPOW:
717 return selectExtInst(ResVReg, ResType, I, CL::pow, GL::Pow);
718 case TargetOpcode::G_FPOWI:
719 return selectExtInst(ResVReg, ResType, I, CL::pown);
720
721 case TargetOpcode::G_FEXP:
722 return selectExtInst(ResVReg, ResType, I, CL::exp, GL::Exp);
723 case TargetOpcode::G_FEXP2:
724 return selectExtInst(ResVReg, ResType, I, CL::exp2, GL::Exp2);
725
726 case TargetOpcode::G_FLOG:
727 return selectExtInst(ResVReg, ResType, I, CL::log, GL::Log);
728 case TargetOpcode::G_FLOG2:
729 return selectExtInst(ResVReg, ResType, I, CL::log2, GL::Log2);
730 case TargetOpcode::G_FLOG10:
731 return selectLog10(ResVReg, ResType, I);
732
733 case TargetOpcode::G_FABS:
734 return selectExtInst(ResVReg, ResType, I, CL::fabs, GL::FAbs);
735 case TargetOpcode::G_ABS:
736 return selectExtInst(ResVReg, ResType, I, CL::s_abs, GL::SAbs);
737
738 case TargetOpcode::G_FMINNUM:
739 case TargetOpcode::G_FMINIMUM:
740 return selectExtInst(ResVReg, ResType, I, CL::fmin, GL::NMin);
741 case TargetOpcode::G_FMAXNUM:
742 case TargetOpcode::G_FMAXIMUM:
743 return selectExtInst(ResVReg, ResType, I, CL::fmax, GL::NMax);
744
745 case TargetOpcode::G_FCOPYSIGN:
746 return selectExtInst(ResVReg, ResType, I, CL::copysign);
747
748 case TargetOpcode::G_FCEIL:
749 return selectExtInst(ResVReg, ResType, I, CL::ceil, GL::Ceil);
750 case TargetOpcode::G_FFLOOR:
751 return selectExtInst(ResVReg, ResType, I, CL::floor, GL::Floor);
752
753 case TargetOpcode::G_FCOS:
754 return selectExtInst(ResVReg, ResType, I, CL::cos, GL::Cos);
755 case TargetOpcode::G_FSIN:
756 return selectExtInst(ResVReg, ResType, I, CL::sin, GL::Sin);
757 case TargetOpcode::G_FTAN:
758 return selectExtInst(ResVReg, ResType, I, CL::tan, GL::Tan);
759 case TargetOpcode::G_FACOS:
760 return selectExtInst(ResVReg, ResType, I, CL::acos, GL::Acos);
761 case TargetOpcode::G_FASIN:
762 return selectExtInst(ResVReg, ResType, I, CL::asin, GL::Asin);
763 case TargetOpcode::G_FATAN:
764 return selectExtInst(ResVReg, ResType, I, CL::atan, GL::Atan);
765 case TargetOpcode::G_FATAN2:
766 return selectExtInst(ResVReg, ResType, I, CL::atan2, GL::Atan2);
767 case TargetOpcode::G_FCOSH:
768 return selectExtInst(ResVReg, ResType, I, CL::cosh, GL::Cosh);
769 case TargetOpcode::G_FSINH:
770 return selectExtInst(ResVReg, ResType, I, CL::sinh, GL::Sinh);
771 case TargetOpcode::G_FTANH:
772 return selectExtInst(ResVReg, ResType, I, CL::tanh, GL::Tanh);
773
774 case TargetOpcode::G_STRICT_FSQRT:
775 case TargetOpcode::G_FSQRT:
776 return selectExtInst(ResVReg, ResType, I, CL::sqrt, GL::Sqrt);
777
778 case TargetOpcode::G_CTTZ:
779 case TargetOpcode::G_CTTZ_ZERO_UNDEF:
780 return selectExtInst(ResVReg, ResType, I, CL::ctz);
781 case TargetOpcode::G_CTLZ:
782 case TargetOpcode::G_CTLZ_ZERO_UNDEF:
783 return selectExtInst(ResVReg, ResType, I, CL::clz);
784
785 case TargetOpcode::G_INTRINSIC_ROUND:
786 return selectExtInst(ResVReg, ResType, I, CL::round, GL::Round);
787 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
788 return selectExtInst(ResVReg, ResType, I, CL::rint, GL::RoundEven);
789 case TargetOpcode::G_INTRINSIC_TRUNC:
790 return selectExtInst(ResVReg, ResType, I, CL::trunc, GL::Trunc);
791 case TargetOpcode::G_FRINT:
792 case TargetOpcode::G_FNEARBYINT:
793 return selectExtInst(ResVReg, ResType, I, CL::rint, GL::RoundEven);
794
795 case TargetOpcode::G_SMULH:
796 return selectExtInst(ResVReg, ResType, I, CL::s_mul_hi);
797 case TargetOpcode::G_UMULH:
798 return selectExtInst(ResVReg, ResType, I, CL::u_mul_hi);
799
800 case TargetOpcode::G_SADDSAT:
801 return selectExtInst(ResVReg, ResType, I, CL::s_add_sat);
802 case TargetOpcode::G_UADDSAT:
803 return selectExtInst(ResVReg, ResType, I, CL::u_add_sat);
804 case TargetOpcode::G_SSUBSAT:
805 return selectExtInst(ResVReg, ResType, I, CL::s_sub_sat);
806 case TargetOpcode::G_USUBSAT:
807 return selectExtInst(ResVReg, ResType, I, CL::u_sub_sat);
808
809 case TargetOpcode::G_UADDO:
810 return selectOverflowArith(ResVReg, ResType, I,
811 ResType->getOpcode() == SPIRV::OpTypeVector
812 ? SPIRV::OpIAddCarryV
813 : SPIRV::OpIAddCarryS);
814 case TargetOpcode::G_USUBO:
815 return selectOverflowArith(ResVReg, ResType, I,
816 ResType->getOpcode() == SPIRV::OpTypeVector
817 ? SPIRV::OpISubBorrowV
818 : SPIRV::OpISubBorrowS);
819 case TargetOpcode::G_UMULO:
820 return selectOverflowArith(ResVReg, ResType, I, SPIRV::OpUMulExtended);
821 case TargetOpcode::G_SMULO:
822 return selectOverflowArith(ResVReg, ResType, I, SPIRV::OpSMulExtended);
823
824 case TargetOpcode::G_SEXT:
825 return selectExt(ResVReg, ResType, I, true);
826 case TargetOpcode::G_ANYEXT:
827 case TargetOpcode::G_ZEXT:
828 return selectExt(ResVReg, ResType, I, false);
829 case TargetOpcode::G_TRUNC:
830 return selectTrunc(ResVReg, ResType, I);
831 case TargetOpcode::G_FPTRUNC:
832 case TargetOpcode::G_FPEXT:
833 return selectUnOp(ResVReg, ResType, I, SPIRV::OpFConvert);
834
835 case TargetOpcode::G_PTRTOINT:
836 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertPtrToU);
837 case TargetOpcode::G_INTTOPTR:
838 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertUToPtr);
839 case TargetOpcode::G_BITCAST:
840 return selectBitcast(ResVReg, ResType, I);
841 case TargetOpcode::G_ADDRSPACE_CAST:
842 return selectAddrSpaceCast(ResVReg, ResType, I);
843 case TargetOpcode::G_PTR_ADD: {
844 // Currently, we get G_PTR_ADD only applied to global variables.
845 assert(I.getOperand(1).isReg() && I.getOperand(2).isReg());
846 Register GV = I.getOperand(1).getReg();
847 MachineRegisterInfo::def_instr_iterator II = MRI->def_instr_begin(GV);
848 (void)II;
849 assert(((*II).getOpcode() == TargetOpcode::G_GLOBAL_VALUE ||
850 (*II).getOpcode() == TargetOpcode::COPY ||
851 (*II).getOpcode() == SPIRV::OpVariable) &&
852 getImm(I.getOperand(2), MRI));
853 // It may be the initialization of a global variable.
854 bool IsGVInit = false;
856 UseIt = MRI->use_instr_begin(I.getOperand(0).getReg()),
857 UseEnd = MRI->use_instr_end();
858 UseIt != UseEnd; UseIt = std::next(UseIt)) {
859 if ((*UseIt).getOpcode() == TargetOpcode::G_GLOBAL_VALUE ||
860 (*UseIt).getOpcode() == SPIRV::OpVariable) {
861 IsGVInit = true;
862 break;
863 }
864 }
865 MachineBasicBlock &BB = *I.getParent();
866 if (!IsGVInit) {
867 SPIRVType *GVType = GR.getSPIRVTypeForVReg(GV);
868 SPIRVType *GVPointeeType = GR.getPointeeType(GVType);
869 SPIRVType *ResPointeeType = GR.getPointeeType(ResType);
870 if (GVPointeeType && ResPointeeType && GVPointeeType != ResPointeeType) {
871 // Build a new virtual register that is associated with the required
872 // data type.
873 Register NewVReg = MRI->createGenericVirtualRegister(MRI->getType(GV));
874 MRI->setRegClass(NewVReg, MRI->getRegClass(GV));
875 // Having a correctly typed base we are ready to build the actually
876 // required GEP. It may not be a constant though, because all Operands
877 // of OpSpecConstantOp is to originate from other const instructions,
878 // and only the AccessChain named opcodes accept a global OpVariable
879 // instruction. We can't use an AccessChain opcode because of the type
880 // mismatch between result and base types.
881 if (!GR.isBitcastCompatible(ResType, GVType))
883 "incompatible result and operand types in a bitcast");
884 Register ResTypeReg = GR.getSPIRVTypeID(ResType);
886 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpBitcast))
887 .addDef(NewVReg)
888 .addUse(ResTypeReg)
889 .addUse(GV);
890 return MIB.constrainAllUses(TII, TRI, RBI) &&
891 BuildMI(BB, I, I.getDebugLoc(),
892 TII.get(STI.isLogicalSPIRV()
893 ? SPIRV::OpInBoundsAccessChain
894 : SPIRV::OpInBoundsPtrAccessChain))
895 .addDef(ResVReg)
896 .addUse(ResTypeReg)
897 .addUse(NewVReg)
898 .addUse(I.getOperand(2).getReg())
899 .constrainAllUses(TII, TRI, RBI);
900 } else {
901 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpSpecConstantOp))
902 .addDef(ResVReg)
903 .addUse(GR.getSPIRVTypeID(ResType))
904 .addImm(
905 static_cast<uint32_t>(SPIRV::Opcode::InBoundsPtrAccessChain))
906 .addUse(GV)
907 .addUse(I.getOperand(2).getReg())
908 .constrainAllUses(TII, TRI, RBI);
909 }
910 }
911 // It's possible to translate G_PTR_ADD to OpSpecConstantOp: either to
912 // initialize a global variable with a constant expression (e.g., the test
913 // case opencl/basic/progvar_prog_scope_init.ll), or for another use case
914 Register Idx = buildZerosVal(GR.getOrCreateSPIRVIntegerType(32, I, TII), I);
915 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpSpecConstantOp))
916 .addDef(ResVReg)
917 .addUse(GR.getSPIRVTypeID(ResType))
918 .addImm(static_cast<uint32_t>(
919 SPIRV::Opcode::InBoundsPtrAccessChain))
920 .addUse(GV)
921 .addUse(Idx)
922 .addUse(I.getOperand(2).getReg());
923 return MIB.constrainAllUses(TII, TRI, RBI);
924 }
925
926 case TargetOpcode::G_ATOMICRMW_OR:
927 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicOr);
928 case TargetOpcode::G_ATOMICRMW_ADD:
929 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicIAdd);
930 case TargetOpcode::G_ATOMICRMW_AND:
931 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicAnd);
932 case TargetOpcode::G_ATOMICRMW_MAX:
933 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicSMax);
934 case TargetOpcode::G_ATOMICRMW_MIN:
935 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicSMin);
936 case TargetOpcode::G_ATOMICRMW_SUB:
937 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicISub);
938 case TargetOpcode::G_ATOMICRMW_XOR:
939 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicXor);
940 case TargetOpcode::G_ATOMICRMW_UMAX:
941 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicUMax);
942 case TargetOpcode::G_ATOMICRMW_UMIN:
943 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicUMin);
944 case TargetOpcode::G_ATOMICRMW_XCHG:
945 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicExchange);
946 case TargetOpcode::G_ATOMIC_CMPXCHG:
947 return selectAtomicCmpXchg(ResVReg, ResType, I);
948
949 case TargetOpcode::G_ATOMICRMW_FADD:
950 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicFAddEXT);
951 case TargetOpcode::G_ATOMICRMW_FSUB:
952 // Translate G_ATOMICRMW_FSUB to OpAtomicFAddEXT with negative value operand
953 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicFAddEXT,
954 SPIRV::OpFNegate);
955 case TargetOpcode::G_ATOMICRMW_FMIN:
956 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicFMinEXT);
957 case TargetOpcode::G_ATOMICRMW_FMAX:
958 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicFMaxEXT);
959
960 case TargetOpcode::G_FENCE:
961 return selectFence(I);
962
963 case TargetOpcode::G_STACKSAVE:
964 return selectStackSave(ResVReg, ResType, I);
965 case TargetOpcode::G_STACKRESTORE:
966 return selectStackRestore(I);
967
968 case TargetOpcode::G_UNMERGE_VALUES:
969 return selectUnmergeValues(I);
970
971 // Discard gen opcodes for intrinsics which we do not expect to actually
972 // represent code after lowering or intrinsics which are not implemented but
973 // should not crash when found in a customer's LLVM IR input.
974 case TargetOpcode::G_TRAP:
975 case TargetOpcode::G_DEBUGTRAP:
976 case TargetOpcode::G_UBSANTRAP:
977 case TargetOpcode::DBG_LABEL:
978 return true;
979
980 default:
981 return false;
982 }
983}
984
985bool SPIRVInstructionSelector::selectExtInst(Register ResVReg,
986 const SPIRVType *ResType,
988 GL::GLSLExtInst GLInst) const {
989 if (!STI.canUseExtInstSet(
990 SPIRV::InstructionSet::InstructionSet::GLSL_std_450)) {
991 std::string DiagMsg;
992 raw_string_ostream OS(DiagMsg);
993 I.print(OS, true, false, false, false);
994 DiagMsg += " is only supported with the GLSL extended instruction set.\n";
995 report_fatal_error(DiagMsg.c_str(), false);
996 }
997 return selectExtInst(ResVReg, ResType, I,
998 {{SPIRV::InstructionSet::GLSL_std_450, GLInst}});
999}
1000
1001bool SPIRVInstructionSelector::selectExtInst(Register ResVReg,
1002 const SPIRVType *ResType,
1003 MachineInstr &I,
1004 CL::OpenCLExtInst CLInst) const {
1005 return selectExtInst(ResVReg, ResType, I,
1006 {{SPIRV::InstructionSet::OpenCL_std, CLInst}});
1007}
1008
1009bool SPIRVInstructionSelector::selectExtInst(Register ResVReg,
1010 const SPIRVType *ResType,
1011 MachineInstr &I,
1012 CL::OpenCLExtInst CLInst,
1013 GL::GLSLExtInst GLInst) const {
1014 ExtInstList ExtInsts = {{SPIRV::InstructionSet::OpenCL_std, CLInst},
1015 {SPIRV::InstructionSet::GLSL_std_450, GLInst}};
1016 return selectExtInst(ResVReg, ResType, I, ExtInsts);
1017}
1018
1019bool SPIRVInstructionSelector::selectExtInst(Register ResVReg,
1020 const SPIRVType *ResType,
1021 MachineInstr &I,
1022 const ExtInstList &Insts) const {
1023
1024 for (const auto &Ex : Insts) {
1025 SPIRV::InstructionSet::InstructionSet Set = Ex.first;
1026 uint32_t Opcode = Ex.second;
1027 if (STI.canUseExtInstSet(Set)) {
1028 MachineBasicBlock &BB = *I.getParent();
1029 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
1030 .addDef(ResVReg)
1031 .addUse(GR.getSPIRVTypeID(ResType))
1032 .addImm(static_cast<uint32_t>(Set))
1033 .addImm(Opcode);
1034 const unsigned NumOps = I.getNumOperands();
1035 unsigned Index = 1;
1036 if (Index < NumOps &&
1037 I.getOperand(Index).getType() ==
1038 MachineOperand::MachineOperandType::MO_IntrinsicID)
1039 Index = 2;
1040 for (; Index < NumOps; ++Index)
1041 MIB.add(I.getOperand(Index));
1042 return MIB.constrainAllUses(TII, TRI, RBI);
1043 }
1044 }
1045 return false;
1046}
1047
1048bool SPIRVInstructionSelector::selectOpWithSrcs(Register ResVReg,
1049 const SPIRVType *ResType,
1050 MachineInstr &I,
1051 std::vector<Register> Srcs,
1052 unsigned Opcode) const {
1053 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcode))
1054 .addDef(ResVReg)
1055 .addUse(GR.getSPIRVTypeID(ResType));
1056 for (Register SReg : Srcs) {
1057 MIB.addUse(SReg);
1058 }
1059 return MIB.constrainAllUses(TII, TRI, RBI);
1060}
1061
1062bool SPIRVInstructionSelector::selectUnOp(Register ResVReg,
1063 const SPIRVType *ResType,
1064 MachineInstr &I,
1065 unsigned Opcode) const {
1066 if (STI.isPhysicalSPIRV() && I.getOperand(1).isReg()) {
1067 Register SrcReg = I.getOperand(1).getReg();
1068 bool IsGV = false;
1070 MRI->def_instr_begin(SrcReg);
1071 DefIt != MRI->def_instr_end(); DefIt = std::next(DefIt)) {
1072 if ((*DefIt).getOpcode() == TargetOpcode::G_GLOBAL_VALUE ||
1073 (*DefIt).getOpcode() == SPIRV::OpVariable) {
1074 IsGV = true;
1075 break;
1076 }
1077 }
1078 if (IsGV) {
1079 uint32_t SpecOpcode = 0;
1080 switch (Opcode) {
1081 case SPIRV::OpConvertPtrToU:
1082 SpecOpcode = static_cast<uint32_t>(SPIRV::Opcode::ConvertPtrToU);
1083 break;
1084 case SPIRV::OpConvertUToPtr:
1085 SpecOpcode = static_cast<uint32_t>(SPIRV::Opcode::ConvertUToPtr);
1086 break;
1087 }
1088 if (SpecOpcode)
1089 return BuildMI(*I.getParent(), I, I.getDebugLoc(),
1090 TII.get(SPIRV::OpSpecConstantOp))
1091 .addDef(ResVReg)
1092 .addUse(GR.getSPIRVTypeID(ResType))
1093 .addImm(SpecOpcode)
1094 .addUse(SrcReg)
1095 .constrainAllUses(TII, TRI, RBI);
1096 }
1097 }
1098 return selectOpWithSrcs(ResVReg, ResType, I, {I.getOperand(1).getReg()},
1099 Opcode);
1100}
1101
1102bool SPIRVInstructionSelector::selectBitcast(Register ResVReg,
1103 const SPIRVType *ResType,
1104 MachineInstr &I) const {
1105 Register OpReg = I.getOperand(1).getReg();
1106 SPIRVType *OpType = OpReg.isValid() ? GR.getSPIRVTypeForVReg(OpReg) : nullptr;
1107 if (!GR.isBitcastCompatible(ResType, OpType))
1108 report_fatal_error("incompatible result and operand types in a bitcast");
1109 return selectUnOp(ResVReg, ResType, I, SPIRV::OpBitcast);
1110}
1111
1114 MachineIRBuilder &MIRBuilder,
1115 SPIRVGlobalRegistry &GR) {
1116 uint32_t SpvMemOp = static_cast<uint32_t>(SPIRV::MemoryOperand::None);
1117 if (MemOp->isVolatile())
1118 SpvMemOp |= static_cast<uint32_t>(SPIRV::MemoryOperand::Volatile);
1119 if (MemOp->isNonTemporal())
1120 SpvMemOp |= static_cast<uint32_t>(SPIRV::MemoryOperand::Nontemporal);
1121 if (MemOp->getAlign().value())
1122 SpvMemOp |= static_cast<uint32_t>(SPIRV::MemoryOperand::Aligned);
1123
1124 [[maybe_unused]] MachineInstr *AliasList = nullptr;
1125 [[maybe_unused]] MachineInstr *NoAliasList = nullptr;
1126 const SPIRVSubtarget *ST =
1127 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
1128 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing)) {
1129 if (auto *MD = MemOp->getAAInfo().Scope) {
1130 AliasList = GR.getOrAddMemAliasingINTELInst(MIRBuilder, MD);
1131 if (AliasList)
1132 SpvMemOp |=
1133 static_cast<uint32_t>(SPIRV::MemoryOperand::AliasScopeINTELMask);
1134 }
1135 if (auto *MD = MemOp->getAAInfo().NoAlias) {
1136 NoAliasList = GR.getOrAddMemAliasingINTELInst(MIRBuilder, MD);
1137 if (NoAliasList)
1138 SpvMemOp |=
1139 static_cast<uint32_t>(SPIRV::MemoryOperand::NoAliasINTELMask);
1140 }
1141 }
1142
1143 if (SpvMemOp != static_cast<uint32_t>(SPIRV::MemoryOperand::None)) {
1144 MIB.addImm(SpvMemOp);
1145 if (SpvMemOp & static_cast<uint32_t>(SPIRV::MemoryOperand::Aligned))
1146 MIB.addImm(MemOp->getAlign().value());
1147 if (AliasList)
1148 MIB.addUse(AliasList->getOperand(0).getReg());
1149 if (NoAliasList)
1150 MIB.addUse(NoAliasList->getOperand(0).getReg());
1151 }
1152}
1153
1155 uint32_t SpvMemOp = static_cast<uint32_t>(SPIRV::MemoryOperand::None);
1156 if (Flags & MachineMemOperand::Flags::MOVolatile)
1157 SpvMemOp |= static_cast<uint32_t>(SPIRV::MemoryOperand::Volatile);
1158 if (Flags & MachineMemOperand::Flags::MONonTemporal)
1159 SpvMemOp |= static_cast<uint32_t>(SPIRV::MemoryOperand::Nontemporal);
1160
1161 if (SpvMemOp != static_cast<uint32_t>(SPIRV::MemoryOperand::None))
1162 MIB.addImm(SpvMemOp);
1163}
1164
1165bool SPIRVInstructionSelector::selectLoad(Register ResVReg,
1166 const SPIRVType *ResType,
1167 MachineInstr &I) const {
1168 unsigned OpOffset = isa<GIntrinsic>(I) ? 1 : 0;
1169 Register Ptr = I.getOperand(1 + OpOffset).getReg();
1170
1171 auto *PtrDef = getVRegDef(*MRI, Ptr);
1172 auto *IntPtrDef = dyn_cast<GIntrinsic>(PtrDef);
1173 if (IntPtrDef &&
1174 IntPtrDef->getIntrinsicID() == Intrinsic::spv_resource_getpointer) {
1175 Register HandleReg = IntPtrDef->getOperand(2).getReg();
1176 SPIRVType *HandleType = GR.getSPIRVTypeForVReg(HandleReg);
1177 if (HandleType->getOpcode() == SPIRV::OpTypeImage) {
1178 Register NewHandleReg =
1179 MRI->createVirtualRegister(MRI->getRegClass(HandleReg));
1180 auto *HandleDef = cast<GIntrinsic>(getVRegDef(*MRI, HandleReg));
1181 if (!loadHandleBeforePosition(NewHandleReg, HandleType, *HandleDef, I)) {
1182 return false;
1183 }
1184
1185 Register IdxReg = IntPtrDef->getOperand(3).getReg();
1186 return generateImageRead(ResVReg, ResType, NewHandleReg, IdxReg,
1187 I.getDebugLoc(), I);
1188 }
1189 }
1190
1191 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpLoad))
1192 .addDef(ResVReg)
1193 .addUse(GR.getSPIRVTypeID(ResType))
1194 .addUse(Ptr);
1195 if (!I.getNumMemOperands()) {
1196 assert(I.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS ||
1197 I.getOpcode() ==
1198 TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS);
1199 addMemoryOperands(I.getOperand(2 + OpOffset).getImm(), MIB);
1200 } else {
1201 MachineIRBuilder MIRBuilder(I);
1202 addMemoryOperands(*I.memoperands_begin(), MIB, MIRBuilder, GR);
1203 }
1204 return MIB.constrainAllUses(TII, TRI, RBI);
1205}
1206
1207bool SPIRVInstructionSelector::selectStore(MachineInstr &I) const {
1208 unsigned OpOffset = isa<GIntrinsic>(I) ? 1 : 0;
1209 Register StoreVal = I.getOperand(0 + OpOffset).getReg();
1210 Register Ptr = I.getOperand(1 + OpOffset).getReg();
1211
1212 auto *PtrDef = getVRegDef(*MRI, Ptr);
1213 auto *IntPtrDef = dyn_cast<GIntrinsic>(PtrDef);
1214 if (IntPtrDef &&
1215 IntPtrDef->getIntrinsicID() == Intrinsic::spv_resource_getpointer) {
1216 Register HandleReg = IntPtrDef->getOperand(2).getReg();
1217 Register NewHandleReg =
1218 MRI->createVirtualRegister(MRI->getRegClass(HandleReg));
1219 auto *HandleDef = cast<GIntrinsic>(getVRegDef(*MRI, HandleReg));
1220 SPIRVType *HandleType = GR.getSPIRVTypeForVReg(HandleReg);
1221 if (!loadHandleBeforePosition(NewHandleReg, HandleType, *HandleDef, I)) {
1222 return false;
1223 }
1224
1225 Register IdxReg = IntPtrDef->getOperand(3).getReg();
1226 if (HandleType->getOpcode() == SPIRV::OpTypeImage) {
1227 auto BMI = BuildMI(*I.getParent(), I, I.getDebugLoc(),
1228 TII.get(SPIRV::OpImageWrite))
1229 .addUse(NewHandleReg)
1230 .addUse(IdxReg)
1231 .addUse(StoreVal);
1232
1233 const llvm::Type *LLVMHandleType = GR.getTypeForSPIRVType(HandleType);
1234 if (sampledTypeIsSignedInteger(LLVMHandleType))
1235 BMI.addImm(0x1000); // SignExtend
1236
1237 return BMI.constrainAllUses(TII, TRI, RBI);
1238 }
1239 }
1240
1241 MachineBasicBlock &BB = *I.getParent();
1242 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpStore))
1243 .addUse(Ptr)
1244 .addUse(StoreVal);
1245 if (!I.getNumMemOperands()) {
1246 assert(I.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS ||
1247 I.getOpcode() ==
1248 TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS);
1249 addMemoryOperands(I.getOperand(2 + OpOffset).getImm(), MIB);
1250 } else {
1251 MachineIRBuilder MIRBuilder(I);
1252 addMemoryOperands(*I.memoperands_begin(), MIB, MIRBuilder, GR);
1253 }
1254 return MIB.constrainAllUses(TII, TRI, RBI);
1255}
1256
1257bool SPIRVInstructionSelector::selectStackSave(Register ResVReg,
1258 const SPIRVType *ResType,
1259 MachineInstr &I) const {
1260 if (!STI.canUseExtension(SPIRV::Extension::SPV_INTEL_variable_length_array))
1262 "llvm.stacksave intrinsic: this instruction requires the following "
1263 "SPIR-V extension: SPV_INTEL_variable_length_array",
1264 false);
1265 MachineBasicBlock &BB = *I.getParent();
1266 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpSaveMemoryINTEL))
1267 .addDef(ResVReg)
1268 .addUse(GR.getSPIRVTypeID(ResType))
1269 .constrainAllUses(TII, TRI, RBI);
1270}
1271
1272bool SPIRVInstructionSelector::selectStackRestore(MachineInstr &I) const {
1273 if (!STI.canUseExtension(SPIRV::Extension::SPV_INTEL_variable_length_array))
1275 "llvm.stackrestore intrinsic: this instruction requires the following "
1276 "SPIR-V extension: SPV_INTEL_variable_length_array",
1277 false);
1278 if (!I.getOperand(0).isReg())
1279 return false;
1280 MachineBasicBlock &BB = *I.getParent();
1281 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpRestoreMemoryINTEL))
1282 .addUse(I.getOperand(0).getReg())
1283 .constrainAllUses(TII, TRI, RBI);
1284}
1285
1286bool SPIRVInstructionSelector::selectMemOperation(Register ResVReg,
1287 MachineInstr &I) const {
1288 MachineBasicBlock &BB = *I.getParent();
1289 Register SrcReg = I.getOperand(1).getReg();
1290 bool Result = true;
1291 if (I.getOpcode() == TargetOpcode::G_MEMSET) {
1292 MachineIRBuilder MIRBuilder(I);
1293 assert(I.getOperand(1).isReg() && I.getOperand(2).isReg());
1294 unsigned Val = getIConstVal(I.getOperand(1).getReg(), MRI);
1295 unsigned Num = getIConstVal(I.getOperand(2).getReg(), MRI);
1296 Type *ValTy = Type::getInt8Ty(I.getMF()->getFunction().getContext());
1297 Type *ArrTy = ArrayType::get(ValTy, Num);
1298 SPIRVType *VarTy = GR.getOrCreateSPIRVPointerType(
1299 ArrTy, MIRBuilder, SPIRV::StorageClass::UniformConstant);
1300
1301 SPIRVType *SpvArrTy = GR.getOrCreateSPIRVType(
1302 ArrTy, MIRBuilder, SPIRV::AccessQualifier::None, false);
1303 Register Const = GR.getOrCreateConstIntArray(Val, Num, I, SpvArrTy, TII);
1304 // TODO: check if we have such GV, add init, use buildGlobalVariable.
1305 Function &CurFunction = GR.CurMF->getFunction();
1306 Type *LLVMArrTy =
1307 ArrayType::get(IntegerType::get(CurFunction.getContext(), 8), Num);
1308 // Module takes ownership of the global var.
1309 GlobalVariable *GV = new GlobalVariable(*CurFunction.getParent(), LLVMArrTy,
1311 Constant::getNullValue(LLVMArrTy));
1312 Register VarReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
1313 auto MIBVar =
1314 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpVariable))
1315 .addDef(VarReg)
1316 .addUse(GR.getSPIRVTypeID(VarTy))
1317 .addImm(SPIRV::StorageClass::UniformConstant)
1318 .addUse(Const);
1319 Result &= MIBVar.constrainAllUses(TII, TRI, RBI);
1320
1321 GR.add(GV, MIBVar);
1322 GR.addGlobalObject(GV, GR.CurMF, VarReg);
1323
1324 buildOpDecorate(VarReg, I, TII, SPIRV::Decoration::Constant, {});
1325 SPIRVType *SourceTy = GR.getOrCreateSPIRVPointerType(
1326 ValTy, I, SPIRV::StorageClass::UniformConstant);
1327 SrcReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
1328 selectOpWithSrcs(SrcReg, SourceTy, I, {VarReg}, SPIRV::OpBitcast);
1329 }
1330 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCopyMemorySized))
1331 .addUse(I.getOperand(0).getReg())
1332 .addUse(SrcReg)
1333 .addUse(I.getOperand(2).getReg());
1334 if (I.getNumMemOperands()) {
1335 MachineIRBuilder MIRBuilder(I);
1336 addMemoryOperands(*I.memoperands_begin(), MIB, MIRBuilder, GR);
1337 }
1338 Result &= MIB.constrainAllUses(TII, TRI, RBI);
1339 if (ResVReg.isValid() && ResVReg != MIB->getOperand(0).getReg())
1340 Result &= BuildCOPY(ResVReg, MIB->getOperand(0).getReg(), I);
1341 return Result;
1342}
1343
1344bool SPIRVInstructionSelector::selectAtomicRMW(Register ResVReg,
1345 const SPIRVType *ResType,
1346 MachineInstr &I,
1347 unsigned NewOpcode,
1348 unsigned NegateOpcode) const {
1349 bool Result = true;
1350 assert(I.hasOneMemOperand());
1351 const MachineMemOperand *MemOp = *I.memoperands_begin();
1352 uint32_t Scope = static_cast<uint32_t>(getMemScope(
1353 GR.CurMF->getFunction().getContext(), MemOp->getSyncScopeID()));
1354 auto ScopeConstant = buildI32Constant(Scope, I);
1355 Register ScopeReg = ScopeConstant.first;
1356 Result &= ScopeConstant.second;
1357
1358 Register Ptr = I.getOperand(1).getReg();
1359 // TODO: Changed as it's implemented in the translator. See test/atomicrmw.ll
1360 // auto ScSem =
1361 // getMemSemanticsForStorageClass(GR.getPointerStorageClass(Ptr));
1362 AtomicOrdering AO = MemOp->getSuccessOrdering();
1363 uint32_t MemSem = static_cast<uint32_t>(getMemSemantics(AO));
1364 auto MemSemConstant = buildI32Constant(MemSem /*| ScSem*/, I);
1365 Register MemSemReg = MemSemConstant.first;
1366 Result &= MemSemConstant.second;
1367
1368 Register ValueReg = I.getOperand(2).getReg();
1369 if (NegateOpcode != 0) {
1370 // Translation with negative value operand is requested
1371 Register TmpReg = createVirtualRegister(ResType, &GR, MRI, MRI->getMF());
1372 Result &= selectOpWithSrcs(TmpReg, ResType, I, {ValueReg}, NegateOpcode);
1373 ValueReg = TmpReg;
1374 }
1375
1376 return Result &&
1377 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(NewOpcode))
1378 .addDef(ResVReg)
1379 .addUse(GR.getSPIRVTypeID(ResType))
1380 .addUse(Ptr)
1381 .addUse(ScopeReg)
1382 .addUse(MemSemReg)
1383 .addUse(ValueReg)
1384 .constrainAllUses(TII, TRI, RBI);
1385}
1386
1387bool SPIRVInstructionSelector::selectUnmergeValues(MachineInstr &I) const {
1388 unsigned ArgI = I.getNumOperands() - 1;
1389 Register SrcReg =
1390 I.getOperand(ArgI).isReg() ? I.getOperand(ArgI).getReg() : Register(0);
1391 SPIRVType *DefType =
1392 SrcReg.isValid() ? GR.getSPIRVTypeForVReg(SrcReg) : nullptr;
1393 if (!DefType || DefType->getOpcode() != SPIRV::OpTypeVector)
1395 "cannot select G_UNMERGE_VALUES with a non-vector argument");
1396
1397 SPIRVType *ScalarType =
1398 GR.getSPIRVTypeForVReg(DefType->getOperand(1).getReg());
1399 MachineBasicBlock &BB = *I.getParent();
1400 bool Res = false;
1401 for (unsigned i = 0; i < I.getNumDefs(); ++i) {
1402 Register ResVReg = I.getOperand(i).getReg();
1403 SPIRVType *ResType = GR.getSPIRVTypeForVReg(ResVReg);
1404 if (!ResType) {
1405 // There was no "assign type" actions, let's fix this now
1406 ResType = ScalarType;
1407 MRI->setRegClass(ResVReg, GR.getRegClass(ResType));
1408 MRI->setType(ResVReg, LLT::scalar(GR.getScalarOrVectorBitWidth(ResType)));
1409 GR.assignSPIRVTypeToVReg(ResType, ResVReg, *GR.CurMF);
1410 }
1411 auto MIB =
1412 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
1413 .addDef(ResVReg)
1414 .addUse(GR.getSPIRVTypeID(ResType))
1415 .addUse(SrcReg)
1416 .addImm(static_cast<int64_t>(i));
1417 Res |= MIB.constrainAllUses(TII, TRI, RBI);
1418 }
1419 return Res;
1420}
1421
1422bool SPIRVInstructionSelector::selectFence(MachineInstr &I) const {
1423 AtomicOrdering AO = AtomicOrdering(I.getOperand(0).getImm());
1424 uint32_t MemSem = static_cast<uint32_t>(getMemSemantics(AO));
1425 auto MemSemConstant = buildI32Constant(MemSem, I);
1426 Register MemSemReg = MemSemConstant.first;
1427 bool Result = MemSemConstant.second;
1428 SyncScope::ID Ord = SyncScope::ID(I.getOperand(1).getImm());
1429 uint32_t Scope = static_cast<uint32_t>(
1430 getMemScope(GR.CurMF->getFunction().getContext(), Ord));
1431 auto ScopeConstant = buildI32Constant(Scope, I);
1432 Register ScopeReg = ScopeConstant.first;
1433 Result &= ScopeConstant.second;
1434 MachineBasicBlock &BB = *I.getParent();
1435 return Result &&
1436 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpMemoryBarrier))
1437 .addUse(ScopeReg)
1438 .addUse(MemSemReg)
1439 .constrainAllUses(TII, TRI, RBI);
1440}
1441
1442bool SPIRVInstructionSelector::selectOverflowArith(Register ResVReg,
1443 const SPIRVType *ResType,
1444 MachineInstr &I,
1445 unsigned Opcode) const {
1446 Type *ResTy = nullptr;
1447 StringRef ResName;
1448 if (!GR.findValueAttrs(&I, ResTy, ResName))
1450 "Not enough info to select the arithmetic with overflow instruction");
1451 if (!ResTy || !ResTy->isStructTy())
1452 report_fatal_error("Expect struct type result for the arithmetic "
1453 "with overflow instruction");
1454 // "Result Type must be from OpTypeStruct. The struct must have two members,
1455 // and the two members must be the same type."
1456 Type *ResElemTy = cast<StructType>(ResTy)->getElementType(0);
1457 ResTy = StructType::get(ResElemTy, ResElemTy);
1458 // Build SPIR-V types and constant(s) if needed.
1459 MachineIRBuilder MIRBuilder(I);
1460 SPIRVType *StructType = GR.getOrCreateSPIRVType(
1461 ResTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false);
1462 assert(I.getNumDefs() > 1 && "Not enought operands");
1463 SPIRVType *BoolType = GR.getOrCreateSPIRVBoolType(I, TII);
1464 unsigned N = GR.getScalarOrVectorComponentCount(ResType);
1465 if (N > 1)
1466 BoolType = GR.getOrCreateSPIRVVectorType(BoolType, N, I, TII);
1467 Register BoolTypeReg = GR.getSPIRVTypeID(BoolType);
1468 Register ZeroReg = buildZerosVal(ResType, I);
1469 // A new virtual register to store the result struct.
1470 Register StructVReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
1471 MRI->setRegClass(StructVReg, &SPIRV::IDRegClass);
1472 // Build the result name if needed.
1473 if (ResName.size() > 0)
1474 buildOpName(StructVReg, ResName, MIRBuilder);
1475 // Build the arithmetic with overflow instruction.
1476 MachineBasicBlock &BB = *I.getParent();
1477 auto MIB =
1478 BuildMI(BB, MIRBuilder.getInsertPt(), I.getDebugLoc(), TII.get(Opcode))
1479 .addDef(StructVReg)
1480 .addUse(GR.getSPIRVTypeID(StructType));
1481 for (unsigned i = I.getNumDefs(); i < I.getNumOperands(); ++i)
1482 MIB.addUse(I.getOperand(i).getReg());
1483 bool Result = MIB.constrainAllUses(TII, TRI, RBI);
1484 // Build instructions to extract fields of the instruction's result.
1485 // A new virtual register to store the higher part of the result struct.
1486 Register HigherVReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
1487 MRI->setRegClass(HigherVReg, &SPIRV::iIDRegClass);
1488 for (unsigned i = 0; i < I.getNumDefs(); ++i) {
1489 auto MIB =
1490 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
1491 .addDef(i == 1 ? HigherVReg : I.getOperand(i).getReg())
1492 .addUse(GR.getSPIRVTypeID(ResType))
1493 .addUse(StructVReg)
1494 .addImm(i);
1495 Result &= MIB.constrainAllUses(TII, TRI, RBI);
1496 }
1497 // Build boolean value from the higher part.
1498 return Result && BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpINotEqual))
1499 .addDef(I.getOperand(1).getReg())
1500 .addUse(BoolTypeReg)
1501 .addUse(HigherVReg)
1502 .addUse(ZeroReg)
1503 .constrainAllUses(TII, TRI, RBI);
1504}
1505
1506bool SPIRVInstructionSelector::selectAtomicCmpXchg(Register ResVReg,
1507 const SPIRVType *ResType,
1508 MachineInstr &I) const {
1509 bool Result = true;
1510 Register ScopeReg;
1511 Register MemSemEqReg;
1512 Register MemSemNeqReg;
1513 Register Ptr = I.getOperand(2).getReg();
1514 if (!isa<GIntrinsic>(I)) {
1515 assert(I.hasOneMemOperand());
1516 const MachineMemOperand *MemOp = *I.memoperands_begin();
1517 unsigned Scope = static_cast<uint32_t>(getMemScope(
1518 GR.CurMF->getFunction().getContext(), MemOp->getSyncScopeID()));
1519 auto ScopeConstant = buildI32Constant(Scope, I);
1520 ScopeReg = ScopeConstant.first;
1521 Result &= ScopeConstant.second;
1522
1523 unsigned ScSem = static_cast<uint32_t>(
1524 getMemSemanticsForStorageClass(GR.getPointerStorageClass(Ptr)));
1525 AtomicOrdering AO = MemOp->getSuccessOrdering();
1526 unsigned MemSemEq = static_cast<uint32_t>(getMemSemantics(AO)) | ScSem;
1527 auto MemSemEqConstant = buildI32Constant(MemSemEq, I);
1528 MemSemEqReg = MemSemEqConstant.first;
1529 Result &= MemSemEqConstant.second;
1530 AtomicOrdering FO = MemOp->getFailureOrdering();
1531 unsigned MemSemNeq = static_cast<uint32_t>(getMemSemantics(FO)) | ScSem;
1532 if (MemSemEq == MemSemNeq)
1533 MemSemNeqReg = MemSemEqReg;
1534 else {
1535 auto MemSemNeqConstant = buildI32Constant(MemSemEq, I);
1536 MemSemNeqReg = MemSemNeqConstant.first;
1537 Result &= MemSemNeqConstant.second;
1538 }
1539 } else {
1540 ScopeReg = I.getOperand(5).getReg();
1541 MemSemEqReg = I.getOperand(6).getReg();
1542 MemSemNeqReg = I.getOperand(7).getReg();
1543 }
1544
1545 Register Cmp = I.getOperand(3).getReg();
1546 Register Val = I.getOperand(4).getReg();
1547 SPIRVType *SpvValTy = GR.getSPIRVTypeForVReg(Val);
1548 Register ACmpRes = createVirtualRegister(SpvValTy, &GR, MRI, *I.getMF());
1549 const DebugLoc &DL = I.getDebugLoc();
1550 Result &=
1551 BuildMI(*I.getParent(), I, DL, TII.get(SPIRV::OpAtomicCompareExchange))
1552 .addDef(ACmpRes)
1553 .addUse(GR.getSPIRVTypeID(SpvValTy))
1554 .addUse(Ptr)
1555 .addUse(ScopeReg)
1556 .addUse(MemSemEqReg)
1557 .addUse(MemSemNeqReg)
1558 .addUse(Val)
1559 .addUse(Cmp)
1560 .constrainAllUses(TII, TRI, RBI);
1561 SPIRVType *BoolTy = GR.getOrCreateSPIRVBoolType(I, TII);
1562 Register CmpSuccReg = createVirtualRegister(BoolTy, &GR, MRI, *I.getMF());
1563 Result &= BuildMI(*I.getParent(), I, DL, TII.get(SPIRV::OpIEqual))
1564 .addDef(CmpSuccReg)
1565 .addUse(GR.getSPIRVTypeID(BoolTy))
1566 .addUse(ACmpRes)
1567 .addUse(Cmp)
1568 .constrainAllUses(TII, TRI, RBI);
1569 Register TmpReg = createVirtualRegister(ResType, &GR, MRI, *I.getMF());
1570 Result &= BuildMI(*I.getParent(), I, DL, TII.get(SPIRV::OpCompositeInsert))
1571 .addDef(TmpReg)
1572 .addUse(GR.getSPIRVTypeID(ResType))
1573 .addUse(ACmpRes)
1574 .addUse(GR.getOrCreateUndef(I, ResType, TII))
1575 .addImm(0)
1576 .constrainAllUses(TII, TRI, RBI);
1577 return Result &&
1578 BuildMI(*I.getParent(), I, DL, TII.get(SPIRV::OpCompositeInsert))
1579 .addDef(ResVReg)
1580 .addUse(GR.getSPIRVTypeID(ResType))
1581 .addUse(CmpSuccReg)
1582 .addUse(TmpReg)
1583 .addImm(1)
1584 .constrainAllUses(TII, TRI, RBI);
1585}
1586
1587static bool isUSMStorageClass(SPIRV::StorageClass::StorageClass SC) {
1588 switch (SC) {
1589 case SPIRV::StorageClass::DeviceOnlyINTEL:
1590 case SPIRV::StorageClass::HostOnlyINTEL:
1591 return true;
1592 default:
1593 return false;
1594 }
1595}
1596
1597// Returns true ResVReg is referred only from global vars and OpName's.
1599 bool IsGRef = false;
1600 bool IsAllowedRefs =
1601 llvm::all_of(MRI->use_instructions(ResVReg), [&IsGRef](auto const &It) {
1602 unsigned Opcode = It.getOpcode();
1603 if (Opcode == SPIRV::OpConstantComposite ||
1604 Opcode == SPIRV::OpVariable ||
1605 isSpvIntrinsic(It, Intrinsic::spv_init_global))
1606 return IsGRef = true;
1607 return Opcode == SPIRV::OpName;
1608 });
1609 return IsAllowedRefs && IsGRef;
1610}
1611
1612Register SPIRVInstructionSelector::getUcharPtrTypeReg(
1613 MachineInstr &I, SPIRV::StorageClass::StorageClass SC) const {
1614 return GR.getSPIRVTypeID(GR.getOrCreateSPIRVPointerType(
1615 Type::getInt8Ty(I.getMF()->getFunction().getContext()), I, SC));
1616}
1617
1619SPIRVInstructionSelector::buildSpecConstantOp(MachineInstr &I, Register Dest,
1620 Register Src, Register DestType,
1621 uint32_t Opcode) const {
1622 return BuildMI(*I.getParent(), I, I.getDebugLoc(),
1623 TII.get(SPIRV::OpSpecConstantOp))
1624 .addDef(Dest)
1625 .addUse(DestType)
1626 .addImm(Opcode)
1627 .addUse(Src);
1628}
1629
1631SPIRVInstructionSelector::buildConstGenericPtr(MachineInstr &I, Register SrcPtr,
1632 SPIRVType *SrcPtrTy) const {
1633 SPIRVType *GenericPtrTy =
1634 GR.changePointerStorageClass(SrcPtrTy, SPIRV::StorageClass::Generic, I);
1635 Register Tmp = MRI->createVirtualRegister(&SPIRV::pIDRegClass);
1637 SPIRV::StorageClass::Generic),
1638 GR.getPointerSize()));
1639 MachineFunction *MF = I.getParent()->getParent();
1640 GR.assignSPIRVTypeToVReg(GenericPtrTy, Tmp, *MF);
1641 MachineInstrBuilder MIB = buildSpecConstantOp(
1642 I, Tmp, SrcPtr, GR.getSPIRVTypeID(GenericPtrTy),
1643 static_cast<uint32_t>(SPIRV::Opcode::PtrCastToGeneric));
1644 GR.add(MIB.getInstr(), MIB);
1645 return MIB;
1646}
1647
1648// In SPIR-V address space casting can only happen to and from the Generic
1649// storage class. We can also only cast Workgroup, CrossWorkgroup, or Function
1650// pointers to and from Generic pointers. As such, we can convert e.g. from
1651// Workgroup to Function by going via a Generic pointer as an intermediary. All
1652// other combinations can only be done by a bitcast, and are probably not safe.
1653bool SPIRVInstructionSelector::selectAddrSpaceCast(Register ResVReg,
1654 const SPIRVType *ResType,
1655 MachineInstr &I) const {
1656 MachineBasicBlock &BB = *I.getParent();
1657 const DebugLoc &DL = I.getDebugLoc();
1658
1659 Register SrcPtr = I.getOperand(1).getReg();
1660 SPIRVType *SrcPtrTy = GR.getSPIRVTypeForVReg(SrcPtr);
1661
1662 // don't generate a cast for a null that may be represented by OpTypeInt
1663 if (SrcPtrTy->getOpcode() != SPIRV::OpTypePointer ||
1664 ResType->getOpcode() != SPIRV::OpTypePointer)
1665 return BuildCOPY(ResVReg, SrcPtr, I);
1666
1667 SPIRV::StorageClass::StorageClass SrcSC = GR.getPointerStorageClass(SrcPtrTy);
1668 SPIRV::StorageClass::StorageClass DstSC = GR.getPointerStorageClass(ResType);
1669
1670 if (isASCastInGVar(MRI, ResVReg)) {
1671 // AddrSpaceCast uses within OpVariable and OpConstantComposite instructions
1672 // are expressed by OpSpecConstantOp with an Opcode.
1673 // TODO: maybe insert a check whether the Kernel capability was declared and
1674 // so PtrCastToGeneric/GenericCastToPtr are available.
1675 unsigned SpecOpcode =
1676 DstSC == SPIRV::StorageClass::Generic && isGenericCastablePtr(SrcSC)
1677 ? static_cast<uint32_t>(SPIRV::Opcode::PtrCastToGeneric)
1678 : (SrcSC == SPIRV::StorageClass::Generic &&
1680 ? static_cast<uint32_t>(SPIRV::Opcode::GenericCastToPtr)
1681 : 0);
1682 // TODO: OpConstantComposite expects i8*, so we are forced to forget a
1683 // correct value of ResType and use general i8* instead. Maybe this should
1684 // be addressed in the emit-intrinsic step to infer a correct
1685 // OpConstantComposite type.
1686 if (SpecOpcode) {
1687 return buildSpecConstantOp(I, ResVReg, SrcPtr,
1688 getUcharPtrTypeReg(I, DstSC), SpecOpcode)
1689 .constrainAllUses(TII, TRI, RBI);
1690 } else if (isGenericCastablePtr(SrcSC) && isGenericCastablePtr(DstSC)) {
1691 MachineInstrBuilder MIB = buildConstGenericPtr(I, SrcPtr, SrcPtrTy);
1692 return MIB.constrainAllUses(TII, TRI, RBI) &&
1693 buildSpecConstantOp(
1694 I, ResVReg, MIB->getOperand(0).getReg(),
1695 getUcharPtrTypeReg(I, DstSC),
1696 static_cast<uint32_t>(SPIRV::Opcode::GenericCastToPtr))
1697 .constrainAllUses(TII, TRI, RBI);
1698 }
1699 }
1700
1701 // don't generate a cast between identical storage classes
1702 if (SrcSC == DstSC)
1703 return BuildCOPY(ResVReg, SrcPtr, I);
1704
1705 if ((SrcSC == SPIRV::StorageClass::Function &&
1706 DstSC == SPIRV::StorageClass::Private) ||
1707 (DstSC == SPIRV::StorageClass::Function &&
1708 SrcSC == SPIRV::StorageClass::Private))
1709 return BuildCOPY(ResVReg, SrcPtr, I);
1710
1711 // Casting from an eligible pointer to Generic.
1712 if (DstSC == SPIRV::StorageClass::Generic && isGenericCastablePtr(SrcSC))
1713 return selectUnOp(ResVReg, ResType, I, SPIRV::OpPtrCastToGeneric);
1714 // Casting from Generic to an eligible pointer.
1715 if (SrcSC == SPIRV::StorageClass::Generic && isGenericCastablePtr(DstSC))
1716 return selectUnOp(ResVReg, ResType, I, SPIRV::OpGenericCastToPtr);
1717 // Casting between 2 eligible pointers using Generic as an intermediary.
1718 if (isGenericCastablePtr(SrcSC) && isGenericCastablePtr(DstSC)) {
1719 SPIRVType *GenericPtrTy =
1720 GR.changePointerStorageClass(SrcPtrTy, SPIRV::StorageClass::Generic, I);
1721 Register Tmp = createVirtualRegister(GenericPtrTy, &GR, MRI, MRI->getMF());
1722 bool Result = BuildMI(BB, I, DL, TII.get(SPIRV::OpPtrCastToGeneric))
1723 .addDef(Tmp)
1724 .addUse(GR.getSPIRVTypeID(GenericPtrTy))
1725 .addUse(SrcPtr)
1726 .constrainAllUses(TII, TRI, RBI);
1727 return Result && BuildMI(BB, I, DL, TII.get(SPIRV::OpGenericCastToPtr))
1728 .addDef(ResVReg)
1729 .addUse(GR.getSPIRVTypeID(ResType))
1730 .addUse(Tmp)
1731 .constrainAllUses(TII, TRI, RBI);
1732 }
1733
1734 // Check if instructions from the SPV_INTEL_usm_storage_classes extension may
1735 // be applied
1736 if (isUSMStorageClass(SrcSC) && DstSC == SPIRV::StorageClass::CrossWorkgroup)
1737 return selectUnOp(ResVReg, ResType, I,
1738 SPIRV::OpPtrCastToCrossWorkgroupINTEL);
1739 if (SrcSC == SPIRV::StorageClass::CrossWorkgroup && isUSMStorageClass(DstSC))
1740 return selectUnOp(ResVReg, ResType, I,
1741 SPIRV::OpCrossWorkgroupCastToPtrINTEL);
1742 if (isUSMStorageClass(SrcSC) && DstSC == SPIRV::StorageClass::Generic)
1743 return selectUnOp(ResVReg, ResType, I, SPIRV::OpPtrCastToGeneric);
1744 if (SrcSC == SPIRV::StorageClass::Generic && isUSMStorageClass(DstSC))
1745 return selectUnOp(ResVReg, ResType, I, SPIRV::OpGenericCastToPtr);
1746
1747 // Bitcast for pointers requires that the address spaces must match
1748 return false;
1749}
1750
1751static unsigned getFCmpOpcode(unsigned PredNum) {
1752 auto Pred = static_cast<CmpInst::Predicate>(PredNum);
1753 switch (Pred) {
1754 case CmpInst::FCMP_OEQ:
1755 return SPIRV::OpFOrdEqual;
1756 case CmpInst::FCMP_OGE:
1757 return SPIRV::OpFOrdGreaterThanEqual;
1758 case CmpInst::FCMP_OGT:
1759 return SPIRV::OpFOrdGreaterThan;
1760 case CmpInst::FCMP_OLE:
1761 return SPIRV::OpFOrdLessThanEqual;
1762 case CmpInst::FCMP_OLT:
1763 return SPIRV::OpFOrdLessThan;
1764 case CmpInst::FCMP_ONE:
1765 return SPIRV::OpFOrdNotEqual;
1766 case CmpInst::FCMP_ORD:
1767 return SPIRV::OpOrdered;
1768 case CmpInst::FCMP_UEQ:
1769 return SPIRV::OpFUnordEqual;
1770 case CmpInst::FCMP_UGE:
1771 return SPIRV::OpFUnordGreaterThanEqual;
1772 case CmpInst::FCMP_UGT:
1773 return SPIRV::OpFUnordGreaterThan;
1774 case CmpInst::FCMP_ULE:
1775 return SPIRV::OpFUnordLessThanEqual;
1776 case CmpInst::FCMP_ULT:
1777 return SPIRV::OpFUnordLessThan;
1778 case CmpInst::FCMP_UNE:
1779 return SPIRV::OpFUnordNotEqual;
1780 case CmpInst::FCMP_UNO:
1781 return SPIRV::OpUnordered;
1782 default:
1783 llvm_unreachable("Unknown predicate type for FCmp");
1784 }
1785}
1786
1787static unsigned getICmpOpcode(unsigned PredNum) {
1788 auto Pred = static_cast<CmpInst::Predicate>(PredNum);
1789 switch (Pred) {
1790 case CmpInst::ICMP_EQ:
1791 return SPIRV::OpIEqual;
1792 case CmpInst::ICMP_NE:
1793 return SPIRV::OpINotEqual;
1794 case CmpInst::ICMP_SGE:
1795 return SPIRV::OpSGreaterThanEqual;
1796 case CmpInst::ICMP_SGT:
1797 return SPIRV::OpSGreaterThan;
1798 case CmpInst::ICMP_SLE:
1799 return SPIRV::OpSLessThanEqual;
1800 case CmpInst::ICMP_SLT:
1801 return SPIRV::OpSLessThan;
1802 case CmpInst::ICMP_UGE:
1803 return SPIRV::OpUGreaterThanEqual;
1804 case CmpInst::ICMP_UGT:
1805 return SPIRV::OpUGreaterThan;
1806 case CmpInst::ICMP_ULE:
1807 return SPIRV::OpULessThanEqual;
1808 case CmpInst::ICMP_ULT:
1809 return SPIRV::OpULessThan;
1810 default:
1811 llvm_unreachable("Unknown predicate type for ICmp");
1812 }
1813}
1814
1815static unsigned getPtrCmpOpcode(unsigned Pred) {
1816 switch (static_cast<CmpInst::Predicate>(Pred)) {
1817 case CmpInst::ICMP_EQ:
1818 return SPIRV::OpPtrEqual;
1819 case CmpInst::ICMP_NE:
1820 return SPIRV::OpPtrNotEqual;
1821 default:
1822 llvm_unreachable("Unknown predicate type for pointer comparison");
1823 }
1824}
1825
1826// Return the logical operation, or abort if none exists.
1827static unsigned getBoolCmpOpcode(unsigned PredNum) {
1828 auto Pred = static_cast<CmpInst::Predicate>(PredNum);
1829 switch (Pred) {
1830 case CmpInst::ICMP_EQ:
1831 return SPIRV::OpLogicalEqual;
1832 case CmpInst::ICMP_NE:
1833 return SPIRV::OpLogicalNotEqual;
1834 default:
1835 llvm_unreachable("Unknown predicate type for Bool comparison");
1836 }
1837}
1838
1839static APFloat getZeroFP(const Type *LLVMFloatTy) {
1840 if (!LLVMFloatTy)
1841 return APFloat::getZero(APFloat::IEEEsingle());
1842 switch (LLVMFloatTy->getScalarType()->getTypeID()) {
1843 case Type::HalfTyID:
1844 return APFloat::getZero(APFloat::IEEEhalf());
1845 default:
1846 case Type::FloatTyID:
1847 return APFloat::getZero(APFloat::IEEEsingle());
1848 case Type::DoubleTyID:
1849 return APFloat::getZero(APFloat::IEEEdouble());
1850 }
1851}
1852
1853static APFloat getOneFP(const Type *LLVMFloatTy) {
1854 if (!LLVMFloatTy)
1855 return APFloat::getOne(APFloat::IEEEsingle());
1856 switch (LLVMFloatTy->getScalarType()->getTypeID()) {
1857 case Type::HalfTyID:
1858 return APFloat::getOne(APFloat::IEEEhalf());
1859 default:
1860 case Type::FloatTyID:
1861 return APFloat::getOne(APFloat::IEEEsingle());
1862 case Type::DoubleTyID:
1863 return APFloat::getOne(APFloat::IEEEdouble());
1864 }
1865}
1866
1867bool SPIRVInstructionSelector::selectAnyOrAll(Register ResVReg,
1868 const SPIRVType *ResType,
1869 MachineInstr &I,
1870 unsigned OpAnyOrAll) const {
1871 assert(I.getNumOperands() == 3);
1872 assert(I.getOperand(2).isReg());
1873 MachineBasicBlock &BB = *I.getParent();
1874 Register InputRegister = I.getOperand(2).getReg();
1875 SPIRVType *InputType = GR.getSPIRVTypeForVReg(InputRegister);
1876
1877 if (!InputType)
1878 report_fatal_error("Input Type could not be determined.");
1879
1880 bool IsBoolTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeBool);
1881 bool IsVectorTy = InputType->getOpcode() == SPIRV::OpTypeVector;
1882 if (IsBoolTy && !IsVectorTy) {
1883 assert(ResVReg == I.getOperand(0).getReg());
1884 return BuildCOPY(ResVReg, InputRegister, I);
1885 }
1886
1887 bool IsFloatTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeFloat);
1888 unsigned SpirvNotEqualId =
1889 IsFloatTy ? SPIRV::OpFOrdNotEqual : SPIRV::OpINotEqual;
1890 SPIRVType *SpvBoolScalarTy = GR.getOrCreateSPIRVBoolType(I, TII);
1891 SPIRVType *SpvBoolTy = SpvBoolScalarTy;
1892 Register NotEqualReg = ResVReg;
1893
1894 if (IsVectorTy) {
1895 NotEqualReg =
1896 IsBoolTy ? InputRegister
1897 : createVirtualRegister(SpvBoolTy, &GR, MRI, MRI->getMF());
1898 const unsigned NumElts = InputType->getOperand(2).getImm();
1899 SpvBoolTy = GR.getOrCreateSPIRVVectorType(SpvBoolTy, NumElts, I, TII);
1900 }
1901
1902 bool Result = true;
1903 if (!IsBoolTy) {
1904 Register ConstZeroReg =
1905 IsFloatTy ? buildZerosValF(InputType, I) : buildZerosVal(InputType, I);
1906
1907 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SpirvNotEqualId))
1908 .addDef(NotEqualReg)
1909 .addUse(GR.getSPIRVTypeID(SpvBoolTy))
1910 .addUse(InputRegister)
1911 .addUse(ConstZeroReg)
1912 .constrainAllUses(TII, TRI, RBI);
1913 }
1914
1915 if (!IsVectorTy)
1916 return Result;
1917
1918 return Result && BuildMI(BB, I, I.getDebugLoc(), TII.get(OpAnyOrAll))
1919 .addDef(ResVReg)
1920 .addUse(GR.getSPIRVTypeID(SpvBoolScalarTy))
1921 .addUse(NotEqualReg)
1922 .constrainAllUses(TII, TRI, RBI);
1923}
1924
1925bool SPIRVInstructionSelector::selectAll(Register ResVReg,
1926 const SPIRVType *ResType,
1927 MachineInstr &I) const {
1928 return selectAnyOrAll(ResVReg, ResType, I, SPIRV::OpAll);
1929}
1930
1931bool SPIRVInstructionSelector::selectAny(Register ResVReg,
1932 const SPIRVType *ResType,
1933 MachineInstr &I) const {
1934 return selectAnyOrAll(ResVReg, ResType, I, SPIRV::OpAny);
1935}
1936
1937// Select the OpDot instruction for the given float dot
1938bool SPIRVInstructionSelector::selectFloatDot(Register ResVReg,
1939 const SPIRVType *ResType,
1940 MachineInstr &I) const {
1941 assert(I.getNumOperands() == 4);
1942 assert(I.getOperand(2).isReg());
1943 assert(I.getOperand(3).isReg());
1944
1945 [[maybe_unused]] SPIRVType *VecType =
1946 GR.getSPIRVTypeForVReg(I.getOperand(2).getReg());
1947
1948 assert(VecType->getOpcode() == SPIRV::OpTypeVector &&
1949 GR.getScalarOrVectorComponentCount(VecType) > 1 &&
1950 "dot product requires a vector of at least 2 components");
1951
1952 [[maybe_unused]] SPIRVType *EltType =
1953 GR.getSPIRVTypeForVReg(VecType->getOperand(1).getReg());
1954
1955 assert(EltType->getOpcode() == SPIRV::OpTypeFloat);
1956
1957 MachineBasicBlock &BB = *I.getParent();
1958 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpDot))
1959 .addDef(ResVReg)
1960 .addUse(GR.getSPIRVTypeID(ResType))
1961 .addUse(I.getOperand(2).getReg())
1962 .addUse(I.getOperand(3).getReg())
1963 .constrainAllUses(TII, TRI, RBI);
1964}
1965
1966bool SPIRVInstructionSelector::selectIntegerDot(Register ResVReg,
1967 const SPIRVType *ResType,
1968 MachineInstr &I,
1969 bool Signed) const {
1970 assert(I.getNumOperands() == 4);
1971 assert(I.getOperand(2).isReg());
1972 assert(I.getOperand(3).isReg());
1973 MachineBasicBlock &BB = *I.getParent();
1974
1975 auto DotOp = Signed ? SPIRV::OpSDot : SPIRV::OpUDot;
1976 return BuildMI(BB, I, I.getDebugLoc(), TII.get(DotOp))
1977 .addDef(ResVReg)
1978 .addUse(GR.getSPIRVTypeID(ResType))
1979 .addUse(I.getOperand(2).getReg())
1980 .addUse(I.getOperand(3).getReg())
1981 .constrainAllUses(TII, TRI, RBI);
1982}
1983
1984// Since pre-1.6 SPIRV has no integer dot implementation,
1985// expand by piecewise multiplying and adding the results
1986bool SPIRVInstructionSelector::selectIntegerDotExpansion(
1987 Register ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
1988 assert(I.getNumOperands() == 4);
1989 assert(I.getOperand(2).isReg());
1990 assert(I.getOperand(3).isReg());
1991 MachineBasicBlock &BB = *I.getParent();
1992
1993 // Multiply the vectors, then sum the results
1994 Register Vec0 = I.getOperand(2).getReg();
1995 Register Vec1 = I.getOperand(3).getReg();
1996 Register TmpVec = MRI->createVirtualRegister(GR.getRegClass(ResType));
1997 SPIRVType *VecType = GR.getSPIRVTypeForVReg(Vec0);
1998
1999 bool Result = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIMulV))
2000 .addDef(TmpVec)
2001 .addUse(GR.getSPIRVTypeID(VecType))
2002 .addUse(Vec0)
2003 .addUse(Vec1)
2004 .constrainAllUses(TII, TRI, RBI);
2005
2006 assert(VecType->getOpcode() == SPIRV::OpTypeVector &&
2007 GR.getScalarOrVectorComponentCount(VecType) > 1 &&
2008 "dot product requires a vector of at least 2 components");
2009
2010 Register Res = MRI->createVirtualRegister(GR.getRegClass(ResType));
2011 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
2012 .addDef(Res)
2013 .addUse(GR.getSPIRVTypeID(ResType))
2014 .addUse(TmpVec)
2015 .addImm(0)
2016 .constrainAllUses(TII, TRI, RBI);
2017
2018 for (unsigned i = 1; i < GR.getScalarOrVectorComponentCount(VecType); i++) {
2019 Register Elt = MRI->createVirtualRegister(GR.getRegClass(ResType));
2020
2021 Result &=
2022 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
2023 .addDef(Elt)
2024 .addUse(GR.getSPIRVTypeID(ResType))
2025 .addUse(TmpVec)
2026 .addImm(i)
2027 .constrainAllUses(TII, TRI, RBI);
2028
2029 Register Sum = i < GR.getScalarOrVectorComponentCount(VecType) - 1
2030 ? MRI->createVirtualRegister(GR.getRegClass(ResType))
2031 : ResVReg;
2032
2033 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIAddS))
2034 .addDef(Sum)
2035 .addUse(GR.getSPIRVTypeID(ResType))
2036 .addUse(Res)
2037 .addUse(Elt)
2038 .constrainAllUses(TII, TRI, RBI);
2039 Res = Sum;
2040 }
2041
2042 return Result;
2043}
2044
2045template <bool Signed>
2046bool SPIRVInstructionSelector::selectDot4AddPacked(Register ResVReg,
2047 const SPIRVType *ResType,
2048 MachineInstr &I) const {
2049 assert(I.getNumOperands() == 5);
2050 assert(I.getOperand(2).isReg());
2051 assert(I.getOperand(3).isReg());
2052 assert(I.getOperand(4).isReg());
2053 MachineBasicBlock &BB = *I.getParent();
2054
2055 Register Acc = I.getOperand(2).getReg();
2056 Register X = I.getOperand(3).getReg();
2057 Register Y = I.getOperand(4).getReg();
2058
2059 auto DotOp = Signed ? SPIRV::OpSDot : SPIRV::OpUDot;
2060 Register Dot = MRI->createVirtualRegister(GR.getRegClass(ResType));
2061 bool Result = BuildMI(BB, I, I.getDebugLoc(), TII.get(DotOp))
2062 .addDef(Dot)
2063 .addUse(GR.getSPIRVTypeID(ResType))
2064 .addUse(X)
2065 .addUse(Y)
2066 .constrainAllUses(TII, TRI, RBI);
2067
2068 return Result && BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIAddS))
2069 .addDef(ResVReg)
2070 .addUse(GR.getSPIRVTypeID(ResType))
2071 .addUse(Dot)
2072 .addUse(Acc)
2073 .constrainAllUses(TII, TRI, RBI);
2074}
2075
2076// Since pre-1.6 SPIRV has no DotProductInput4x8BitPacked implementation,
2077// extract the elements of the packed inputs, multiply them and add the result
2078// to the accumulator.
2079template <bool Signed>
2080bool SPIRVInstructionSelector::selectDot4AddPackedExpansion(
2081 Register ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
2082 assert(I.getNumOperands() == 5);
2083 assert(I.getOperand(2).isReg());
2084 assert(I.getOperand(3).isReg());
2085 assert(I.getOperand(4).isReg());
2086 MachineBasicBlock &BB = *I.getParent();
2087
2088 bool Result = true;
2089
2090 Register Acc = I.getOperand(2).getReg();
2091 Register X = I.getOperand(3).getReg();
2092 Register Y = I.getOperand(4).getReg();
2093
2094 SPIRVType *EltType = GR.getOrCreateSPIRVIntegerType(8, I, TII);
2095 auto ExtractOp =
2096 Signed ? SPIRV::OpBitFieldSExtract : SPIRV::OpBitFieldUExtract;
2097
2098 bool ZeroAsNull = !STI.isShader();
2099 // Extract the i8 element, multiply and add it to the accumulator
2100 for (unsigned i = 0; i < 4; i++) {
2101 // A[i]
2102 Register AElt = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2103 Result &=
2104 BuildMI(BB, I, I.getDebugLoc(), TII.get(ExtractOp))
2105 .addDef(AElt)
2106 .addUse(GR.getSPIRVTypeID(ResType))
2107 .addUse(X)
2108 .addUse(GR.getOrCreateConstInt(i * 8, I, EltType, TII, ZeroAsNull))
2109 .addUse(GR.getOrCreateConstInt(8, I, EltType, TII, ZeroAsNull))
2110 .constrainAllUses(TII, TRI, RBI);
2111
2112 // B[i]
2113 Register BElt = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2114 Result &=
2115 BuildMI(BB, I, I.getDebugLoc(), TII.get(ExtractOp))
2116 .addDef(BElt)
2117 .addUse(GR.getSPIRVTypeID(ResType))
2118 .addUse(Y)
2119 .addUse(GR.getOrCreateConstInt(i * 8, I, EltType, TII, ZeroAsNull))
2120 .addUse(GR.getOrCreateConstInt(8, I, EltType, TII, ZeroAsNull))
2121 .constrainAllUses(TII, TRI, RBI);
2122
2123 // A[i] * B[i]
2124 Register Mul = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2125 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIMulS))
2126 .addDef(Mul)
2127 .addUse(GR.getSPIRVTypeID(ResType))
2128 .addUse(AElt)
2129 .addUse(BElt)
2130 .constrainAllUses(TII, TRI, RBI);
2131
2132 // Discard 24 highest-bits so that stored i32 register is i8 equivalent
2133 Register MaskMul = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2134 Result &=
2135 BuildMI(BB, I, I.getDebugLoc(), TII.get(ExtractOp))
2136 .addDef(MaskMul)
2137 .addUse(GR.getSPIRVTypeID(ResType))
2138 .addUse(Mul)
2139 .addUse(GR.getOrCreateConstInt(0, I, EltType, TII, ZeroAsNull))
2140 .addUse(GR.getOrCreateConstInt(8, I, EltType, TII, ZeroAsNull))
2141 .constrainAllUses(TII, TRI, RBI);
2142
2143 // Acc = Acc + A[i] * B[i]
2144 Register Sum =
2145 i < 3 ? MRI->createVirtualRegister(&SPIRV::IDRegClass) : ResVReg;
2146 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIAddS))
2147 .addDef(Sum)
2148 .addUse(GR.getSPIRVTypeID(ResType))
2149 .addUse(Acc)
2150 .addUse(MaskMul)
2151 .constrainAllUses(TII, TRI, RBI);
2152
2153 Acc = Sum;
2154 }
2155
2156 return Result;
2157}
2158
2159/// Transform saturate(x) to clamp(x, 0.0f, 1.0f) as SPIRV
2160/// does not have a saturate builtin.
2161bool SPIRVInstructionSelector::selectSaturate(Register ResVReg,
2162 const SPIRVType *ResType,
2163 MachineInstr &I) const {
2164 assert(I.getNumOperands() == 3);
2165 assert(I.getOperand(2).isReg());
2166 MachineBasicBlock &BB = *I.getParent();
2167 Register VZero = buildZerosValF(ResType, I);
2168 Register VOne = buildOnesValF(ResType, I);
2169
2170 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
2171 .addDef(ResVReg)
2172 .addUse(GR.getSPIRVTypeID(ResType))
2173 .addImm(static_cast<uint32_t>(SPIRV::InstructionSet::GLSL_std_450))
2174 .addImm(GL::FClamp)
2175 .addUse(I.getOperand(2).getReg())
2176 .addUse(VZero)
2177 .addUse(VOne)
2178 .constrainAllUses(TII, TRI, RBI);
2179}
2180
2181bool SPIRVInstructionSelector::selectSign(Register ResVReg,
2182 const SPIRVType *ResType,
2183 MachineInstr &I) const {
2184 assert(I.getNumOperands() == 3);
2185 assert(I.getOperand(2).isReg());
2186 MachineBasicBlock &BB = *I.getParent();
2187 Register InputRegister = I.getOperand(2).getReg();
2188 SPIRVType *InputType = GR.getSPIRVTypeForVReg(InputRegister);
2189 auto &DL = I.getDebugLoc();
2190
2191 if (!InputType)
2192 report_fatal_error("Input Type could not be determined.");
2193
2194 bool IsFloatTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeFloat);
2195
2196 unsigned SignBitWidth = GR.getScalarOrVectorBitWidth(InputType);
2197 unsigned ResBitWidth = GR.getScalarOrVectorBitWidth(ResType);
2198
2199 bool NeedsConversion = IsFloatTy || SignBitWidth != ResBitWidth;
2200
2201 auto SignOpcode = IsFloatTy ? GL::FSign : GL::SSign;
2202 Register SignReg = NeedsConversion
2203 ? MRI->createVirtualRegister(&SPIRV::IDRegClass)
2204 : ResVReg;
2205
2206 bool Result =
2207 BuildMI(BB, I, DL, TII.get(SPIRV::OpExtInst))
2208 .addDef(SignReg)
2209 .addUse(GR.getSPIRVTypeID(InputType))
2210 .addImm(static_cast<uint32_t>(SPIRV::InstructionSet::GLSL_std_450))
2211 .addImm(SignOpcode)
2212 .addUse(InputRegister)
2213 .constrainAllUses(TII, TRI, RBI);
2214
2215 if (NeedsConversion) {
2216 auto ConvertOpcode = IsFloatTy ? SPIRV::OpConvertFToS : SPIRV::OpSConvert;
2217 Result &= BuildMI(*I.getParent(), I, DL, TII.get(ConvertOpcode))
2218 .addDef(ResVReg)
2219 .addUse(GR.getSPIRVTypeID(ResType))
2220 .addUse(SignReg)
2221 .constrainAllUses(TII, TRI, RBI);
2222 }
2223
2224 return Result;
2225}
2226
2227bool SPIRVInstructionSelector::selectWaveOpInst(Register ResVReg,
2228 const SPIRVType *ResType,
2229 MachineInstr &I,
2230 unsigned Opcode) const {
2231 MachineBasicBlock &BB = *I.getParent();
2232 SPIRVType *IntTy = GR.getOrCreateSPIRVIntegerType(32, I, TII);
2233
2234 auto BMI = BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2235 .addDef(ResVReg)
2236 .addUse(GR.getSPIRVTypeID(ResType))
2237 .addUse(GR.getOrCreateConstInt(SPIRV::Scope::Subgroup, I,
2238 IntTy, TII, !STI.isShader()));
2239
2240 for (unsigned J = 2; J < I.getNumOperands(); J++) {
2241 BMI.addUse(I.getOperand(J).getReg());
2242 }
2243
2244 return BMI.constrainAllUses(TII, TRI, RBI);
2245}
2246
2247bool SPIRVInstructionSelector::selectWaveActiveCountBits(
2248 Register ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
2249
2250 SPIRVType *IntTy = GR.getOrCreateSPIRVIntegerType(32, I, TII);
2251 SPIRVType *BallotType = GR.getOrCreateSPIRVVectorType(IntTy, 4, I, TII);
2252 Register BallotReg = MRI->createVirtualRegister(GR.getRegClass(BallotType));
2253 bool Result = selectWaveOpInst(BallotReg, BallotType, I,
2254 SPIRV::OpGroupNonUniformBallot);
2255
2256 MachineBasicBlock &BB = *I.getParent();
2257 Result &= BuildMI(BB, I, I.getDebugLoc(),
2258 TII.get(SPIRV::OpGroupNonUniformBallotBitCount))
2259 .addDef(ResVReg)
2260 .addUse(GR.getSPIRVTypeID(ResType))
2261 .addUse(GR.getOrCreateConstInt(SPIRV::Scope::Subgroup, I, IntTy,
2262 TII, !STI.isShader()))
2263 .addImm(SPIRV::GroupOperation::Reduce)
2264 .addUse(BallotReg)
2265 .constrainAllUses(TII, TRI, RBI);
2266
2267 return Result;
2268}
2269
2270bool SPIRVInstructionSelector::selectWaveReduceMax(Register ResVReg,
2271 const SPIRVType *ResType,
2272 MachineInstr &I,
2273 bool IsUnsigned) const {
2274 assert(I.getNumOperands() == 3);
2275 assert(I.getOperand(2).isReg());
2276 MachineBasicBlock &BB = *I.getParent();
2277 Register InputRegister = I.getOperand(2).getReg();
2278 SPIRVType *InputType = GR.getSPIRVTypeForVReg(InputRegister);
2279
2280 if (!InputType)
2281 report_fatal_error("Input Type could not be determined.");
2282
2283 SPIRVType *IntTy = GR.getOrCreateSPIRVIntegerType(32, I, TII);
2284 // Retreive the operation to use based on input type
2285 bool IsFloatTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeFloat);
2286 auto IntegerOpcodeType =
2287 IsUnsigned ? SPIRV::OpGroupNonUniformUMax : SPIRV::OpGroupNonUniformSMax;
2288 auto Opcode = IsFloatTy ? SPIRV::OpGroupNonUniformFMax : IntegerOpcodeType;
2289 return BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2290 .addDef(ResVReg)
2291 .addUse(GR.getSPIRVTypeID(ResType))
2292 .addUse(GR.getOrCreateConstInt(SPIRV::Scope::Subgroup, I, IntTy, TII,
2293 !STI.isShader()))
2294 .addImm(SPIRV::GroupOperation::Reduce)
2295 .addUse(I.getOperand(2).getReg())
2296 .constrainAllUses(TII, TRI, RBI);
2297}
2298
2299bool SPIRVInstructionSelector::selectWaveReduceSum(Register ResVReg,
2300 const SPIRVType *ResType,
2301 MachineInstr &I) const {
2302 assert(I.getNumOperands() == 3);
2303 assert(I.getOperand(2).isReg());
2304 MachineBasicBlock &BB = *I.getParent();
2305 Register InputRegister = I.getOperand(2).getReg();
2306 SPIRVType *InputType = GR.getSPIRVTypeForVReg(InputRegister);
2307
2308 if (!InputType)
2309 report_fatal_error("Input Type could not be determined.");
2310
2311 SPIRVType *IntTy = GR.getOrCreateSPIRVIntegerType(32, I, TII);
2312 // Retreive the operation to use based on input type
2313 bool IsFloatTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeFloat);
2314 auto Opcode =
2315 IsFloatTy ? SPIRV::OpGroupNonUniformFAdd : SPIRV::OpGroupNonUniformIAdd;
2316 return BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2317 .addDef(ResVReg)
2318 .addUse(GR.getSPIRVTypeID(ResType))
2319 .addUse(GR.getOrCreateConstInt(SPIRV::Scope::Subgroup, I, IntTy, TII,
2320 !STI.isShader()))
2321 .addImm(SPIRV::GroupOperation::Reduce)
2322 .addUse(I.getOperand(2).getReg());
2323}
2324
2325bool SPIRVInstructionSelector::selectBitreverse(Register ResVReg,
2326 const SPIRVType *ResType,
2327 MachineInstr &I) const {
2328 MachineBasicBlock &BB = *I.getParent();
2329 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpBitReverse))
2330 .addDef(ResVReg)
2331 .addUse(GR.getSPIRVTypeID(ResType))
2332 .addUse(I.getOperand(1).getReg())
2333 .constrainAllUses(TII, TRI, RBI);
2334}
2335
2336bool SPIRVInstructionSelector::selectFreeze(Register ResVReg,
2337 const SPIRVType *ResType,
2338 MachineInstr &I) const {
2339 // There is no way to implement `freeze` correctly without support on SPIR-V
2340 // standard side, but we may at least address a simple (static) case when
2341 // undef/poison value presence is obvious. The main benefit of even
2342 // incomplete `freeze` support is preventing of translation from crashing due
2343 // to lack of support on legalization and instruction selection steps.
2344 if (!I.getOperand(0).isReg() || !I.getOperand(1).isReg())
2345 return false;
2346 Register OpReg = I.getOperand(1).getReg();
2347 if (MachineInstr *Def = MRI->getVRegDef(OpReg)) {
2348 if (Def->getOpcode() == TargetOpcode::COPY)
2349 Def = MRI->getVRegDef(Def->getOperand(1).getReg());
2350 Register Reg;
2351 switch (Def->getOpcode()) {
2352 case SPIRV::ASSIGN_TYPE:
2353 if (MachineInstr *AssignToDef =
2354 MRI->getVRegDef(Def->getOperand(1).getReg())) {
2355 if (AssignToDef->getOpcode() == TargetOpcode::G_IMPLICIT_DEF)
2356 Reg = Def->getOperand(2).getReg();
2357 }
2358 break;
2359 case SPIRV::OpUndef:
2360 Reg = Def->getOperand(1).getReg();
2361 break;
2362 }
2363 unsigned DestOpCode;
2364 if (Reg.isValid()) {
2365 DestOpCode = SPIRV::OpConstantNull;
2366 } else {
2367 DestOpCode = TargetOpcode::COPY;
2368 Reg = OpReg;
2369 }
2370 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(DestOpCode))
2371 .addDef(I.getOperand(0).getReg())
2372 .addUse(Reg)
2373 .constrainAllUses(TII, TRI, RBI);
2374 }
2375 return false;
2376}
2377
2378bool SPIRVInstructionSelector::selectBuildVector(Register ResVReg,
2379 const SPIRVType *ResType,
2380 MachineInstr &I) const {
2381 unsigned N = 0;
2382 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2383 N = GR.getScalarOrVectorComponentCount(ResType);
2384 else if (ResType->getOpcode() == SPIRV::OpTypeArray)
2385 N = getArrayComponentCount(MRI, ResType);
2386 else
2387 report_fatal_error("Cannot select G_BUILD_VECTOR with a non-vector result");
2388 if (I.getNumExplicitOperands() - I.getNumExplicitDefs() != N)
2389 report_fatal_error("G_BUILD_VECTOR and the result type are inconsistent");
2390
2391 // check if we may construct a constant vector
2392 bool IsConst = true;
2393 for (unsigned i = I.getNumExplicitDefs();
2394 i < I.getNumExplicitOperands() && IsConst; ++i)
2395 if (!isConstReg(MRI, I.getOperand(i).getReg()))
2396 IsConst = false;
2397
2398 if (!IsConst && N < 2)
2400 "There must be at least two constituent operands in a vector");
2401
2402 MRI->setRegClass(ResVReg, GR.getRegClass(ResType));
2403 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
2404 TII.get(IsConst ? SPIRV::OpConstantComposite
2405 : SPIRV::OpCompositeConstruct))
2406 .addDef(ResVReg)
2407 .addUse(GR.getSPIRVTypeID(ResType));
2408 for (unsigned i = I.getNumExplicitDefs(); i < I.getNumExplicitOperands(); ++i)
2409 MIB.addUse(I.getOperand(i).getReg());
2410 return MIB.constrainAllUses(TII, TRI, RBI);
2411}
2412
2413bool SPIRVInstructionSelector::selectSplatVector(Register ResVReg,
2414 const SPIRVType *ResType,
2415 MachineInstr &I) const {
2416 unsigned N = 0;
2417 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2418 N = GR.getScalarOrVectorComponentCount(ResType);
2419 else if (ResType->getOpcode() == SPIRV::OpTypeArray)
2420 N = getArrayComponentCount(MRI, ResType);
2421 else
2422 report_fatal_error("Cannot select G_SPLAT_VECTOR with a non-vector result");
2423
2424 unsigned OpIdx = I.getNumExplicitDefs();
2425 if (!I.getOperand(OpIdx).isReg())
2426 report_fatal_error("Unexpected argument in G_SPLAT_VECTOR");
2427
2428 // check if we may construct a constant vector
2429 Register OpReg = I.getOperand(OpIdx).getReg();
2430 bool IsConst = isConstReg(MRI, OpReg);
2431
2432 if (!IsConst && N < 2)
2434 "There must be at least two constituent operands in a vector");
2435
2436 MRI->setRegClass(ResVReg, GR.getRegClass(ResType));
2437 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
2438 TII.get(IsConst ? SPIRV::OpConstantComposite
2439 : SPIRV::OpCompositeConstruct))
2440 .addDef(ResVReg)
2441 .addUse(GR.getSPIRVTypeID(ResType));
2442 for (unsigned i = 0; i < N; ++i)
2443 MIB.addUse(OpReg);
2444 return MIB.constrainAllUses(TII, TRI, RBI);
2445}
2446
2447bool SPIRVInstructionSelector::selectDiscard(Register ResVReg,
2448 const SPIRVType *ResType,
2449 MachineInstr &I) const {
2450
2451 unsigned Opcode;
2452
2453 if (STI.canUseExtension(
2454 SPIRV::Extension::SPV_EXT_demote_to_helper_invocation) ||
2455 STI.isAtLeastSPIRVVer(llvm::VersionTuple(1, 6))) {
2456 Opcode = SPIRV::OpDemoteToHelperInvocation;
2457 } else {
2458 Opcode = SPIRV::OpKill;
2459 // OpKill must be the last operation of any basic block.
2460 if (MachineInstr *NextI = I.getNextNode()) {
2461 GR.invalidateMachineInstr(NextI);
2462 NextI->removeFromParent();
2463 }
2464 }
2465
2466 MachineBasicBlock &BB = *I.getParent();
2467 return BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2468 .constrainAllUses(TII, TRI, RBI);
2469}
2470
2471bool SPIRVInstructionSelector::selectCmp(Register ResVReg,
2472 const SPIRVType *ResType,
2473 unsigned CmpOpc,
2474 MachineInstr &I) const {
2475 Register Cmp0 = I.getOperand(2).getReg();
2476 Register Cmp1 = I.getOperand(3).getReg();
2477 assert(GR.getSPIRVTypeForVReg(Cmp0)->getOpcode() ==
2478 GR.getSPIRVTypeForVReg(Cmp1)->getOpcode() &&
2479 "CMP operands should have the same type");
2480 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(CmpOpc))
2481 .addDef(ResVReg)
2482 .addUse(GR.getSPIRVTypeID(ResType))
2483 .addUse(Cmp0)
2484 .addUse(Cmp1)
2485 .constrainAllUses(TII, TRI, RBI);
2486}
2487
2488bool SPIRVInstructionSelector::selectICmp(Register ResVReg,
2489 const SPIRVType *ResType,
2490 MachineInstr &I) const {
2491 auto Pred = I.getOperand(1).getPredicate();
2492 unsigned CmpOpc;
2493
2494 Register CmpOperand = I.getOperand(2).getReg();
2495 if (GR.isScalarOfType(CmpOperand, SPIRV::OpTypePointer))
2496 CmpOpc = getPtrCmpOpcode(Pred);
2497 else if (GR.isScalarOrVectorOfType(CmpOperand, SPIRV::OpTypeBool))
2498 CmpOpc = getBoolCmpOpcode(Pred);
2499 else
2500 CmpOpc = getICmpOpcode(Pred);
2501 return selectCmp(ResVReg, ResType, CmpOpc, I);
2502}
2503
2504std::pair<Register, bool>
2505SPIRVInstructionSelector::buildI32Constant(uint32_t Val, MachineInstr &I,
2506 const SPIRVType *ResType) const {
2507 Type *LLVMTy = IntegerType::get(GR.CurMF->getFunction().getContext(), 32);
2508 const SPIRVType *SpvI32Ty =
2509 ResType ? ResType : GR.getOrCreateSPIRVIntegerType(32, I, TII);
2510 // Find a constant in DT or build a new one.
2511 auto ConstInt = ConstantInt::get(LLVMTy, Val);
2512 Register NewReg = GR.find(ConstInt, GR.CurMF);
2513 bool Result = true;
2514 if (!NewReg.isValid()) {
2515 NewReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
2516 MachineBasicBlock &BB = *I.getParent();
2517 MachineInstr *MI =
2518 Val == 0
2519 ? BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpConstantNull))
2520 .addDef(NewReg)
2521 .addUse(GR.getSPIRVTypeID(SpvI32Ty))
2522 : BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpConstantI))
2523 .addDef(NewReg)
2524 .addUse(GR.getSPIRVTypeID(SpvI32Ty))
2525 .addImm(APInt(32, Val).getZExtValue());
2527 GR.add(ConstInt, MI);
2528 }
2529 return {NewReg, Result};
2530}
2531
2532bool SPIRVInstructionSelector::selectFCmp(Register ResVReg,
2533 const SPIRVType *ResType,
2534 MachineInstr &I) const {
2535 unsigned CmpOp = getFCmpOpcode(I.getOperand(1).getPredicate());
2536 return selectCmp(ResVReg, ResType, CmpOp, I);
2537}
2538
2539Register SPIRVInstructionSelector::buildZerosVal(const SPIRVType *ResType,
2540 MachineInstr &I) const {
2541 // OpenCL uses nulls for Zero. In HLSL we don't use null constants.
2542 bool ZeroAsNull = !STI.isShader();
2543 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2544 return GR.getOrCreateConstVector(0UL, I, ResType, TII, ZeroAsNull);
2545 return GR.getOrCreateConstInt(0, I, ResType, TII, ZeroAsNull);
2546}
2547
2548Register SPIRVInstructionSelector::buildZerosValF(const SPIRVType *ResType,
2549 MachineInstr &I) const {
2550 // OpenCL uses nulls for Zero. In HLSL we don't use null constants.
2551 bool ZeroAsNull = !STI.isShader();
2552 APFloat VZero = getZeroFP(GR.getTypeForSPIRVType(ResType));
2553 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2554 return GR.getOrCreateConstVector(VZero, I, ResType, TII, ZeroAsNull);
2555 return GR.getOrCreateConstFP(VZero, I, ResType, TII, ZeroAsNull);
2556}
2557
2558Register SPIRVInstructionSelector::buildOnesValF(const SPIRVType *ResType,
2559 MachineInstr &I) const {
2560 // OpenCL uses nulls for Zero. In HLSL we don't use null constants.
2561 bool ZeroAsNull = !STI.isShader();
2562 APFloat VOne = getOneFP(GR.getTypeForSPIRVType(ResType));
2563 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2564 return GR.getOrCreateConstVector(VOne, I, ResType, TII, ZeroAsNull);
2565 return GR.getOrCreateConstFP(VOne, I, ResType, TII, ZeroAsNull);
2566}
2567
2568Register SPIRVInstructionSelector::buildOnesVal(bool AllOnes,
2569 const SPIRVType *ResType,
2570 MachineInstr &I) const {
2571 unsigned BitWidth = GR.getScalarOrVectorBitWidth(ResType);
2572 APInt One =
2573 AllOnes ? APInt::getAllOnes(BitWidth) : APInt::getOneBitSet(BitWidth, 0);
2574 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2575 return GR.getOrCreateConstVector(One.getZExtValue(), I, ResType, TII);
2576 return GR.getOrCreateConstInt(One.getZExtValue(), I, ResType, TII);
2577}
2578
2579bool SPIRVInstructionSelector::selectSelect(Register ResVReg,
2580 const SPIRVType *ResType,
2581 MachineInstr &I) const {
2582 Register SelectFirstArg = I.getOperand(2).getReg();
2583 Register SelectSecondArg = I.getOperand(3).getReg();
2584 assert(ResType == GR.getSPIRVTypeForVReg(SelectFirstArg) &&
2585 ResType == GR.getSPIRVTypeForVReg(SelectSecondArg));
2586
2587 bool IsFloatTy =
2588 GR.isScalarOrVectorOfType(SelectFirstArg, SPIRV::OpTypeFloat);
2589 bool IsPtrTy =
2590 GR.isScalarOrVectorOfType(SelectFirstArg, SPIRV::OpTypePointer);
2591 bool IsVectorTy = GR.getSPIRVTypeForVReg(SelectFirstArg)->getOpcode() ==
2592 SPIRV::OpTypeVector;
2593
2594 bool IsScalarBool =
2595 GR.isScalarOfType(I.getOperand(1).getReg(), SPIRV::OpTypeBool);
2596 unsigned Opcode;
2597 if (IsVectorTy) {
2598 if (IsFloatTy) {
2599 Opcode = IsScalarBool ? SPIRV::OpSelectVFSCond : SPIRV::OpSelectVFVCond;
2600 } else if (IsPtrTy) {
2601 Opcode = IsScalarBool ? SPIRV::OpSelectVPSCond : SPIRV::OpSelectVPVCond;
2602 } else {
2603 Opcode = IsScalarBool ? SPIRV::OpSelectVISCond : SPIRV::OpSelectVIVCond;
2604 }
2605 } else {
2606 if (IsFloatTy) {
2607 Opcode = IsScalarBool ? SPIRV::OpSelectSFSCond : SPIRV::OpSelectVFVCond;
2608 } else if (IsPtrTy) {
2609 Opcode = IsScalarBool ? SPIRV::OpSelectSPSCond : SPIRV::OpSelectVPVCond;
2610 } else {
2611 Opcode = IsScalarBool ? SPIRV::OpSelectSISCond : SPIRV::OpSelectVIVCond;
2612 }
2613 }
2614 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcode))
2615 .addDef(ResVReg)
2616 .addUse(GR.getSPIRVTypeID(ResType))
2617 .addUse(I.getOperand(1).getReg())
2618 .addUse(SelectFirstArg)
2619 .addUse(SelectSecondArg)
2620 .constrainAllUses(TII, TRI, RBI);
2621}
2622
2623bool SPIRVInstructionSelector::selectSelectDefaultArgs(Register ResVReg,
2624 const SPIRVType *ResType,
2625 MachineInstr &I,
2626 bool IsSigned) const {
2627 // To extend a bool, we need to use OpSelect between constants.
2628 Register ZeroReg = buildZerosVal(ResType, I);
2629 Register OneReg = buildOnesVal(IsSigned, ResType, I);
2630 bool IsScalarBool =
2631 GR.isScalarOfType(I.getOperand(1).getReg(), SPIRV::OpTypeBool);
2632 unsigned Opcode =
2633 IsScalarBool ? SPIRV::OpSelectSISCond : SPIRV::OpSelectVIVCond;
2634 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcode))
2635 .addDef(ResVReg)
2636 .addUse(GR.getSPIRVTypeID(ResType))
2637 .addUse(I.getOperand(1).getReg())
2638 .addUse(OneReg)
2639 .addUse(ZeroReg)
2640 .constrainAllUses(TII, TRI, RBI);
2641}
2642
2643bool SPIRVInstructionSelector::selectIToF(Register ResVReg,
2644 const SPIRVType *ResType,
2645 MachineInstr &I, bool IsSigned,
2646 unsigned Opcode) const {
2647 Register SrcReg = I.getOperand(1).getReg();
2648 // We can convert bool value directly to float type without OpConvert*ToF,
2649 // however the translator generates OpSelect+OpConvert*ToF, so we do the same.
2650 if (GR.isScalarOrVectorOfType(I.getOperand(1).getReg(), SPIRV::OpTypeBool)) {
2651 unsigned BitWidth = GR.getScalarOrVectorBitWidth(ResType);
2652 SPIRVType *TmpType = GR.getOrCreateSPIRVIntegerType(BitWidth, I, TII);
2653 if (ResType->getOpcode() == SPIRV::OpTypeVector) {
2654 const unsigned NumElts = ResType->getOperand(2).getImm();
2655 TmpType = GR.getOrCreateSPIRVVectorType(TmpType, NumElts, I, TII);
2656 }
2657 SrcReg = createVirtualRegister(TmpType, &GR, MRI, MRI->getMF());
2658 selectSelectDefaultArgs(SrcReg, TmpType, I, false);
2659 }
2660 return selectOpWithSrcs(ResVReg, ResType, I, {SrcReg}, Opcode);
2661}
2662
2663bool SPIRVInstructionSelector::selectExt(Register ResVReg,
2664 const SPIRVType *ResType,
2665 MachineInstr &I, bool IsSigned) const {
2666 Register SrcReg = I.getOperand(1).getReg();
2667 if (GR.isScalarOrVectorOfType(SrcReg, SPIRV::OpTypeBool))
2668 return selectSelectDefaultArgs(ResVReg, ResType, I, IsSigned);
2669
2670 SPIRVType *SrcType = GR.getSPIRVTypeForVReg(SrcReg);
2671 if (SrcType == ResType)
2672 return BuildCOPY(ResVReg, SrcReg, I);
2673
2674 unsigned Opcode = IsSigned ? SPIRV::OpSConvert : SPIRV::OpUConvert;
2675 return selectUnOp(ResVReg, ResType, I, Opcode);
2676}
2677
2678bool SPIRVInstructionSelector::selectSUCmp(Register ResVReg,
2679 const SPIRVType *ResType,
2680 MachineInstr &I,
2681 bool IsSigned) const {
2682 MachineIRBuilder MIRBuilder(I);
2683 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
2684 MachineBasicBlock &BB = *I.getParent();
2685 // Ensure we have bool.
2686 SPIRVType *BoolType = GR.getOrCreateSPIRVBoolType(I, TII);
2687 unsigned N = GR.getScalarOrVectorComponentCount(ResType);
2688 if (N > 1)
2689 BoolType = GR.getOrCreateSPIRVVectorType(BoolType, N, I, TII);
2690 Register BoolTypeReg = GR.getSPIRVTypeID(BoolType);
2691 // Build less-than-equal and less-than.
2692 // TODO: replace with one-liner createVirtualRegister() from
2693 // llvm/lib/Target/SPIRV/SPIRVUtils.cpp when PR #116609 is merged.
2694 Register IsLessEqReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
2695 MRI->setType(IsLessEqReg, LLT::scalar(64));
2696 GR.assignSPIRVTypeToVReg(ResType, IsLessEqReg, MIRBuilder.getMF());
2697 bool Result = BuildMI(BB, I, I.getDebugLoc(),
2698 TII.get(IsSigned ? SPIRV::OpSLessThanEqual
2699 : SPIRV::OpULessThanEqual))
2700 .addDef(IsLessEqReg)
2701 .addUse(BoolTypeReg)
2702 .addUse(I.getOperand(1).getReg())
2703 .addUse(I.getOperand(2).getReg())
2704 .constrainAllUses(TII, TRI, RBI);
2705 Register IsLessReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
2706 MRI->setType(IsLessReg, LLT::scalar(64));
2707 GR.assignSPIRVTypeToVReg(ResType, IsLessReg, MIRBuilder.getMF());
2708 Result &= BuildMI(BB, I, I.getDebugLoc(),
2709 TII.get(IsSigned ? SPIRV::OpSLessThan : SPIRV::OpULessThan))
2710 .addDef(IsLessReg)
2711 .addUse(BoolTypeReg)
2712 .addUse(I.getOperand(1).getReg())
2713 .addUse(I.getOperand(2).getReg())
2714 .constrainAllUses(TII, TRI, RBI);
2715 // Build selects.
2716 Register ResTypeReg = GR.getSPIRVTypeID(ResType);
2717 Register NegOneOrZeroReg =
2718 MRI->createVirtualRegister(GR.getRegClass(ResType));
2719 MRI->setType(NegOneOrZeroReg, LLT::scalar(64));
2720 GR.assignSPIRVTypeToVReg(ResType, NegOneOrZeroReg, MIRBuilder.getMF());
2721 unsigned SelectOpcode =
2722 N > 1 ? SPIRV::OpSelectVIVCond : SPIRV::OpSelectSISCond;
2723 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SelectOpcode))
2724 .addDef(NegOneOrZeroReg)
2725 .addUse(ResTypeReg)
2726 .addUse(IsLessReg)
2727 .addUse(buildOnesVal(true, ResType, I)) // -1
2728 .addUse(buildZerosVal(ResType, I))
2729 .constrainAllUses(TII, TRI, RBI);
2730 return Result & BuildMI(BB, I, I.getDebugLoc(), TII.get(SelectOpcode))
2731 .addDef(ResVReg)
2732 .addUse(ResTypeReg)
2733 .addUse(IsLessEqReg)
2734 .addUse(NegOneOrZeroReg) // -1 or 0
2735 .addUse(buildOnesVal(false, ResType, I))
2736 .constrainAllUses(TII, TRI, RBI);
2737}
2738
2739bool SPIRVInstructionSelector::selectIntToBool(Register IntReg,
2740 Register ResVReg,
2741 MachineInstr &I,
2742 const SPIRVType *IntTy,
2743 const SPIRVType *BoolTy) const {
2744 // To truncate to a bool, we use OpBitwiseAnd 1 and OpINotEqual to zero.
2745 Register BitIntReg = createVirtualRegister(IntTy, &GR, MRI, MRI->getMF());
2746 bool IsVectorTy = IntTy->getOpcode() == SPIRV::OpTypeVector;
2747 unsigned Opcode = IsVectorTy ? SPIRV::OpBitwiseAndV : SPIRV::OpBitwiseAndS;
2748 Register Zero = buildZerosVal(IntTy, I);
2749 Register One = buildOnesVal(false, IntTy, I);
2750 MachineBasicBlock &BB = *I.getParent();
2751 bool Result = BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2752 .addDef(BitIntReg)
2753 .addUse(GR.getSPIRVTypeID(IntTy))
2754 .addUse(IntReg)
2755 .addUse(One)
2756 .constrainAllUses(TII, TRI, RBI);
2757 return Result && BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpINotEqual))
2758 .addDef(ResVReg)
2759 .addUse(GR.getSPIRVTypeID(BoolTy))
2760 .addUse(BitIntReg)
2761 .addUse(Zero)
2762 .constrainAllUses(TII, TRI, RBI);
2763}
2764
2765bool SPIRVInstructionSelector::selectTrunc(Register ResVReg,
2766 const SPIRVType *ResType,
2767 MachineInstr &I) const {
2768 Register IntReg = I.getOperand(1).getReg();
2769 const SPIRVType *ArgType = GR.getSPIRVTypeForVReg(IntReg);
2770 if (GR.isScalarOrVectorOfType(ResVReg, SPIRV::OpTypeBool))
2771 return selectIntToBool(IntReg, ResVReg, I, ArgType, ResType);
2772 if (ArgType == ResType)
2773 return BuildCOPY(ResVReg, IntReg, I);
2774 bool IsSigned = GR.isScalarOrVectorSigned(ResType);
2775 unsigned Opcode = IsSigned ? SPIRV::OpSConvert : SPIRV::OpUConvert;
2776 return selectUnOp(ResVReg, ResType, I, Opcode);
2777}
2778
2779bool SPIRVInstructionSelector::selectConst(Register ResVReg,
2780 const SPIRVType *ResType,
2781 MachineInstr &I) const {
2782 unsigned Opcode = I.getOpcode();
2783 unsigned TpOpcode = ResType->getOpcode();
2784 Register Reg;
2785 if (TpOpcode == SPIRV::OpTypePointer || TpOpcode == SPIRV::OpTypeEvent) {
2786 assert(Opcode == TargetOpcode::G_CONSTANT &&
2787 I.getOperand(1).getCImm()->isZero());
2788 MachineBasicBlock &DepMBB = I.getMF()->front();
2789 MachineIRBuilder MIRBuilder(DepMBB, DepMBB.getFirstNonPHI());
2790 Reg = GR.getOrCreateConstNullPtr(MIRBuilder, ResType);
2791 } else if (Opcode == TargetOpcode::G_FCONSTANT) {
2792 Reg = GR.getOrCreateConstFP(I.getOperand(1).getFPImm()->getValue(), I,
2793 ResType, TII, !STI.isShader());
2794 } else {
2795 Reg = GR.getOrCreateConstInt(I.getOperand(1).getCImm()->getZExtValue(), I,
2796 ResType, TII, !STI.isShader());
2797 }
2798 return Reg == ResVReg ? true : BuildCOPY(ResVReg, Reg, I);
2799}
2800
2801bool SPIRVInstructionSelector::selectOpUndef(Register ResVReg,
2802 const SPIRVType *ResType,
2803 MachineInstr &I) const {
2804 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpUndef))
2805 .addDef(ResVReg)
2806 .addUse(GR.getSPIRVTypeID(ResType))
2807 .constrainAllUses(TII, TRI, RBI);
2808}
2809
2810bool SPIRVInstructionSelector::selectInsertVal(Register ResVReg,
2811 const SPIRVType *ResType,
2812 MachineInstr &I) const {
2813 MachineBasicBlock &BB = *I.getParent();
2814 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeInsert))
2815 .addDef(ResVReg)
2816 .addUse(GR.getSPIRVTypeID(ResType))
2817 // object to insert
2818 .addUse(I.getOperand(3).getReg())
2819 // composite to insert into
2820 .addUse(I.getOperand(2).getReg());
2821 for (unsigned i = 4; i < I.getNumOperands(); i++)
2822 MIB.addImm(foldImm(I.getOperand(i), MRI));
2823 return MIB.constrainAllUses(TII, TRI, RBI);
2824}
2825
2826bool SPIRVInstructionSelector::selectExtractVal(Register ResVReg,
2827 const SPIRVType *ResType,
2828 MachineInstr &I) const {
2829 MachineBasicBlock &BB = *I.getParent();
2830 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
2831 .addDef(ResVReg)
2832 .addUse(GR.getSPIRVTypeID(ResType))
2833 .addUse(I.getOperand(2).getReg());
2834 for (unsigned i = 3; i < I.getNumOperands(); i++)
2835 MIB.addImm(foldImm(I.getOperand(i), MRI));
2836 return MIB.constrainAllUses(TII, TRI, RBI);
2837}
2838
2839bool SPIRVInstructionSelector::selectInsertElt(Register ResVReg,
2840 const SPIRVType *ResType,
2841 MachineInstr &I) const {
2842 if (getImm(I.getOperand(4), MRI))
2843 return selectInsertVal(ResVReg, ResType, I);
2844 MachineBasicBlock &BB = *I.getParent();
2845 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpVectorInsertDynamic))
2846 .addDef(ResVReg)
2847 .addUse(GR.getSPIRVTypeID(ResType))
2848 .addUse(I.getOperand(2).getReg())
2849 .addUse(I.getOperand(3).getReg())
2850 .addUse(I.getOperand(4).getReg())
2851 .constrainAllUses(TII, TRI, RBI);
2852}
2853
2854bool SPIRVInstructionSelector::selectExtractElt(Register ResVReg,
2855 const SPIRVType *ResType,
2856 MachineInstr &I) const {
2857 if (getImm(I.getOperand(3), MRI))
2858 return selectExtractVal(ResVReg, ResType, I);
2859 MachineBasicBlock &BB = *I.getParent();
2860 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpVectorExtractDynamic))
2861 .addDef(ResVReg)
2862 .addUse(GR.getSPIRVTypeID(ResType))
2863 .addUse(I.getOperand(2).getReg())
2864 .addUse(I.getOperand(3).getReg())
2865 .constrainAllUses(TII, TRI, RBI);
2866}
2867
2868bool SPIRVInstructionSelector::selectGEP(Register ResVReg,
2869 const SPIRVType *ResType,
2870 MachineInstr &I) const {
2871 const bool IsGEPInBounds = I.getOperand(2).getImm();
2872
2873 // OpAccessChain could be used for OpenCL, but the SPIRV-LLVM Translator only
2874 // relies on PtrAccessChain, so we'll try not to deviate. For Vulkan however,
2875 // we have to use Op[InBounds]AccessChain.
2876 const unsigned Opcode = STI.isLogicalSPIRV()
2877 ? (IsGEPInBounds ? SPIRV::OpInBoundsAccessChain
2878 : SPIRV::OpAccessChain)
2879 : (IsGEPInBounds ? SPIRV::OpInBoundsPtrAccessChain
2880 : SPIRV::OpPtrAccessChain);
2881
2882 auto Res = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcode))
2883 .addDef(ResVReg)
2884 .addUse(GR.getSPIRVTypeID(ResType))
2885 // Object to get a pointer to.
2886 .addUse(I.getOperand(3).getReg());
2887 // Adding indices.
2888 const unsigned StartingIndex =
2889 (Opcode == SPIRV::OpAccessChain || Opcode == SPIRV::OpInBoundsAccessChain)
2890 ? 5
2891 : 4;
2892 for (unsigned i = StartingIndex; i < I.getNumExplicitOperands(); ++i)
2893 Res.addUse(I.getOperand(i).getReg());
2894 return Res.constrainAllUses(TII, TRI, RBI);
2895}
2896
2897// Maybe wrap a value into OpSpecConstantOp
2898bool SPIRVInstructionSelector::wrapIntoSpecConstantOp(
2899 MachineInstr &I, SmallVector<Register> &CompositeArgs) const {
2900 bool Result = true;
2901 unsigned Lim = I.getNumExplicitOperands();
2902 for (unsigned i = I.getNumExplicitDefs() + 1; i < Lim; ++i) {
2903 Register OpReg = I.getOperand(i).getReg();
2904 MachineInstr *OpDefine = MRI->getVRegDef(OpReg);
2905 SPIRVType *OpType = GR.getSPIRVTypeForVReg(OpReg);
2907 if (!OpDefine || !OpType || isConstReg(MRI, OpDefine, Visited) ||
2908 OpDefine->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST ||
2909 GR.isAggregateType(OpType)) {
2910 // The case of G_ADDRSPACE_CAST inside spv_const_composite() is processed
2911 // by selectAddrSpaceCast()
2912 CompositeArgs.push_back(OpReg);
2913 continue;
2914 }
2915 MachineFunction *MF = I.getMF();
2916 Register WrapReg = GR.find(OpDefine, MF);
2917 if (WrapReg.isValid()) {
2918 CompositeArgs.push_back(WrapReg);
2919 continue;
2920 }
2921 // Create a new register for the wrapper
2922 WrapReg = MRI->createVirtualRegister(GR.getRegClass(OpType));
2923 CompositeArgs.push_back(WrapReg);
2924 // Decorate the wrapper register and generate a new instruction
2925 MRI->setType(WrapReg, LLT::pointer(0, 64));
2926 GR.assignSPIRVTypeToVReg(OpType, WrapReg, *MF);
2927 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
2928 TII.get(SPIRV::OpSpecConstantOp))
2929 .addDef(WrapReg)
2930 .addUse(GR.getSPIRVTypeID(OpType))
2931 .addImm(static_cast<uint32_t>(SPIRV::Opcode::Bitcast))
2932 .addUse(OpReg);
2933 GR.add(OpDefine, MIB);
2934 Result = MIB.constrainAllUses(TII, TRI, RBI);
2935 if (!Result)
2936 break;
2937 }
2938 return Result;
2939}
2940
2941bool SPIRVInstructionSelector::selectIntrinsic(Register ResVReg,
2942 const SPIRVType *ResType,
2943 MachineInstr &I) const {
2944 MachineBasicBlock &BB = *I.getParent();
2945 Intrinsic::ID IID = cast<GIntrinsic>(I).getIntrinsicID();
2946 switch (IID) {
2947 case Intrinsic::spv_load:
2948 return selectLoad(ResVReg, ResType, I);
2949 case Intrinsic::spv_store:
2950 return selectStore(I);
2951 case Intrinsic::spv_extractv:
2952 return selectExtractVal(ResVReg, ResType, I);
2953 case Intrinsic::spv_insertv:
2954 return selectInsertVal(ResVReg, ResType, I);
2955 case Intrinsic::spv_extractelt:
2956 return selectExtractElt(ResVReg, ResType, I);
2957 case Intrinsic::spv_insertelt:
2958 return selectInsertElt(ResVReg, ResType, I);
2959 case Intrinsic::spv_gep:
2960 return selectGEP(ResVReg, ResType, I);
2961 case Intrinsic::spv_unref_global:
2962 case Intrinsic::spv_init_global: {
2963 MachineInstr *MI = MRI->getVRegDef(I.getOperand(1).getReg());
2964 MachineInstr *Init = I.getNumExplicitOperands() > 2
2965 ? MRI->getVRegDef(I.getOperand(2).getReg())
2966 : nullptr;
2967 assert(MI);
2968 Register GVarVReg = MI->getOperand(0).getReg();
2969 bool Res = selectGlobalValue(GVarVReg, *MI, Init);
2970 // We violate SSA form by inserting OpVariable and still having a gMIR
2971 // instruction %vreg = G_GLOBAL_VALUE @gvar. We need to fix this by erasing
2972 // the duplicated definition.
2973 if (MI->getOpcode() == TargetOpcode::G_GLOBAL_VALUE) {
2974 GR.invalidateMachineInstr(MI);
2975 MI->removeFromParent();
2976 }
2977 return Res;
2978 }
2979 case Intrinsic::spv_undef: {
2980 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpUndef))
2981 .addDef(ResVReg)
2982 .addUse(GR.getSPIRVTypeID(ResType));
2983 return MIB.constrainAllUses(TII, TRI, RBI);
2984 }
2985 case Intrinsic::spv_const_composite: {
2986 // If no values are attached, the composite is null constant.
2987 bool IsNull = I.getNumExplicitDefs() + 1 == I.getNumExplicitOperands();
2988 SmallVector<Register> CompositeArgs;
2989 MRI->setRegClass(ResVReg, GR.getRegClass(ResType));
2990
2991 // skip type MD node we already used when generated assign.type for this
2992 if (!IsNull) {
2993 if (!wrapIntoSpecConstantOp(I, CompositeArgs))
2994 return false;
2995 MachineIRBuilder MIR(I);
2997 MIR, SPIRV::OpConstantComposite, 3,
2998 SPIRV::OpConstantCompositeContinuedINTEL, CompositeArgs, ResVReg,
2999 GR.getSPIRVTypeID(ResType));
3000 for (auto *Instr : Instructions) {
3001 Instr->setDebugLoc(I.getDebugLoc());
3002 if (!constrainSelectedInstRegOperands(*Instr, TII, TRI, RBI))
3003 return false;
3004 }
3005 return true;
3006 } else {
3007 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpConstantNull))
3008 .addDef(ResVReg)
3009 .addUse(GR.getSPIRVTypeID(ResType));
3010 return MIB.constrainAllUses(TII, TRI, RBI);
3011 }
3012 }
3013 case Intrinsic::spv_assign_name: {
3014 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpName));
3015 MIB.addUse(I.getOperand(I.getNumExplicitDefs() + 1).getReg());
3016 for (unsigned i = I.getNumExplicitDefs() + 2;
3017 i < I.getNumExplicitOperands(); ++i) {
3018 MIB.addImm(I.getOperand(i).getImm());
3019 }
3020 return MIB.constrainAllUses(TII, TRI, RBI);
3021 }
3022 case Intrinsic::spv_switch: {
3023 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpSwitch));
3024 for (unsigned i = 1; i < I.getNumExplicitOperands(); ++i) {
3025 if (I.getOperand(i).isReg())
3026 MIB.addReg(I.getOperand(i).getReg());
3027 else if (I.getOperand(i).isCImm())
3028 addNumImm(I.getOperand(i).getCImm()->getValue(), MIB);
3029 else if (I.getOperand(i).isMBB())
3030 MIB.addMBB(I.getOperand(i).getMBB());
3031 else
3032 llvm_unreachable("Unexpected OpSwitch operand");
3033 }
3034 return MIB.constrainAllUses(TII, TRI, RBI);
3035 }
3036 case Intrinsic::spv_loop_merge: {
3037 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpLoopMerge));
3038 for (unsigned i = 1; i < I.getNumExplicitOperands(); ++i) {
3039 if (I.getOperand(i).isMBB())
3040 MIB.addMBB(I.getOperand(i).getMBB());
3041 else
3042 MIB.addImm(foldImm(I.getOperand(i), MRI));
3043 }
3044 return MIB.constrainAllUses(TII, TRI, RBI);
3045 }
3046 case Intrinsic::spv_selection_merge: {
3047 auto MIB =
3048 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpSelectionMerge));
3049 assert(I.getOperand(1).isMBB() &&
3050 "operand 1 to spv_selection_merge must be a basic block");
3051 MIB.addMBB(I.getOperand(1).getMBB());
3052 MIB.addImm(getSelectionOperandForImm(I.getOperand(2).getImm()));
3053 return MIB.constrainAllUses(TII, TRI, RBI);
3054 }
3055 case Intrinsic::spv_cmpxchg:
3056 return selectAtomicCmpXchg(ResVReg, ResType, I);
3057 case Intrinsic::spv_unreachable:
3058 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpUnreachable))
3059 .constrainAllUses(TII, TRI, RBI);
3060 case Intrinsic::spv_alloca:
3061 return selectFrameIndex(ResVReg, ResType, I);
3062 case Intrinsic::spv_alloca_array:
3063 return selectAllocaArray(ResVReg, ResType, I);
3064 case Intrinsic::spv_assume:
3065 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume))
3066 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpAssumeTrueKHR))
3067 .addUse(I.getOperand(1).getReg())
3068 .constrainAllUses(TII, TRI, RBI);
3069 break;
3070 case Intrinsic::spv_expect:
3071 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume))
3072 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExpectKHR))
3073 .addDef(ResVReg)
3074 .addUse(GR.getSPIRVTypeID(ResType))
3075 .addUse(I.getOperand(2).getReg())
3076 .addUse(I.getOperand(3).getReg())
3077 .constrainAllUses(TII, TRI, RBI);
3078 break;
3079 case Intrinsic::arithmetic_fence:
3080 if (STI.canUseExtension(SPIRV::Extension::SPV_EXT_arithmetic_fence))
3081 return BuildMI(BB, I, I.getDebugLoc(),
3082 TII.get(SPIRV::OpArithmeticFenceEXT))
3083 .addDef(ResVReg)
3084 .addUse(GR.getSPIRVTypeID(ResType))
3085 .addUse(I.getOperand(2).getReg())
3086 .constrainAllUses(TII, TRI, RBI);
3087 else
3088 return BuildCOPY(ResVReg, I.getOperand(2).getReg(), I);
3089 break;
3090 case Intrinsic::spv_thread_id:
3091 // The HLSL SV_DispatchThreadID semantic is lowered to llvm.spv.thread.id
3092 // intrinsic in LLVM IR for SPIR-V backend.
3093 //
3094 // In SPIR-V backend, llvm.spv.thread.id is now correctly translated to a
3095 // `GlobalInvocationId` builtin variable
3096 return loadVec3BuiltinInputID(SPIRV::BuiltIn::GlobalInvocationId, ResVReg,
3097 ResType, I);
3098 case Intrinsic::spv_thread_id_in_group:
3099 // The HLSL SV_GroupThreadId semantic is lowered to
3100 // llvm.spv.thread.id.in.group intrinsic in LLVM IR for SPIR-V backend.
3101 //
3102 // In SPIR-V backend, llvm.spv.thread.id.in.group is now correctly
3103 // translated to a `LocalInvocationId` builtin variable
3104 return loadVec3BuiltinInputID(SPIRV::BuiltIn::LocalInvocationId, ResVReg,
3105 ResType, I);
3106 case Intrinsic::spv_group_id:
3107 // The HLSL SV_GroupId semantic is lowered to
3108 // llvm.spv.group.id intrinsic in LLVM IR for SPIR-V backend.
3109 //
3110 // In SPIR-V backend, llvm.spv.group.id is now translated to a `WorkgroupId`
3111 // builtin variable
3112 return loadVec3BuiltinInputID(SPIRV::BuiltIn::WorkgroupId, ResVReg, ResType,
3113 I);
3114 case Intrinsic::spv_flattened_thread_id_in_group:
3115 // The HLSL SV_GroupIndex semantic is lowered to
3116 // llvm.spv.flattened.thread.id.in.group() intrinsic in LLVM IR for SPIR-V
3117 // backend.
3118 //
3119 // In SPIR-V backend, llvm.spv.flattened.thread.id.in.group is translated to
3120 // a `LocalInvocationIndex` builtin variable
3121 return loadBuiltinInputID(SPIRV::BuiltIn::LocalInvocationIndex, ResVReg,
3122 ResType, I);
3123 case Intrinsic::spv_workgroup_size:
3124 return loadVec3BuiltinInputID(SPIRV::BuiltIn::WorkgroupSize, ResVReg,
3125 ResType, I);
3126 case Intrinsic::spv_global_size:
3127 return loadVec3BuiltinInputID(SPIRV::BuiltIn::GlobalSize, ResVReg, ResType,
3128 I);
3129 case Intrinsic::spv_global_offset:
3130 return loadVec3BuiltinInputID(SPIRV::BuiltIn::GlobalOffset, ResVReg,
3131 ResType, I);
3132 case Intrinsic::spv_num_workgroups:
3133 return loadVec3BuiltinInputID(SPIRV::BuiltIn::NumWorkgroups, ResVReg,
3134 ResType, I);
3135 case Intrinsic::spv_subgroup_size:
3136 return loadBuiltinInputID(SPIRV::BuiltIn::SubgroupSize, ResVReg, ResType,
3137 I);
3138 case Intrinsic::spv_num_subgroups:
3139 return loadBuiltinInputID(SPIRV::BuiltIn::NumSubgroups, ResVReg, ResType,
3140 I);
3141 case Intrinsic::spv_subgroup_id:
3142 return loadBuiltinInputID(SPIRV::BuiltIn::SubgroupId, ResVReg, ResType, I);
3143 case Intrinsic::spv_subgroup_local_invocation_id:
3144 return loadBuiltinInputID(SPIRV::BuiltIn::SubgroupLocalInvocationId,
3145 ResVReg, ResType, I);
3146 case Intrinsic::spv_subgroup_max_size:
3147 return loadBuiltinInputID(SPIRV::BuiltIn::SubgroupMaxSize, ResVReg, ResType,
3148 I);
3149 case Intrinsic::spv_fdot:
3150 return selectFloatDot(ResVReg, ResType, I);
3151 case Intrinsic::spv_udot:
3152 case Intrinsic::spv_sdot:
3153 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_integer_dot_product) ||
3154 STI.isAtLeastSPIRVVer(VersionTuple(1, 6)))
3155 return selectIntegerDot(ResVReg, ResType, I,
3156 /*Signed=*/IID == Intrinsic::spv_sdot);
3157 return selectIntegerDotExpansion(ResVReg, ResType, I);
3158 case Intrinsic::spv_dot4add_i8packed:
3159 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_integer_dot_product) ||
3160 STI.isAtLeastSPIRVVer(VersionTuple(1, 6)))
3161 return selectDot4AddPacked<true>(ResVReg, ResType, I);
3162 return selectDot4AddPackedExpansion<true>(ResVReg, ResType, I);
3163 case Intrinsic::spv_dot4add_u8packed:
3164 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_integer_dot_product) ||
3165 STI.isAtLeastSPIRVVer(VersionTuple(1, 6)))
3166 return selectDot4AddPacked<false>(ResVReg, ResType, I);
3167 return selectDot4AddPackedExpansion<false>(ResVReg, ResType, I);
3168 case Intrinsic::spv_all:
3169 return selectAll(ResVReg, ResType, I);
3170 case Intrinsic::spv_any:
3171 return selectAny(ResVReg, ResType, I);
3172 case Intrinsic::spv_cross:
3173 return selectExtInst(ResVReg, ResType, I, CL::cross, GL::Cross);
3174 case Intrinsic::spv_distance:
3175 return selectExtInst(ResVReg, ResType, I, CL::distance, GL::Distance);
3176 case Intrinsic::spv_lerp:
3177 return selectExtInst(ResVReg, ResType, I, CL::mix, GL::FMix);
3178 case Intrinsic::spv_length:
3179 return selectExtInst(ResVReg, ResType, I, CL::length, GL::Length);
3180 case Intrinsic::spv_degrees:
3181 return selectExtInst(ResVReg, ResType, I, CL::degrees, GL::Degrees);
3182 case Intrinsic::spv_faceforward:
3183 return selectExtInst(ResVReg, ResType, I, GL::FaceForward);
3184 case Intrinsic::spv_frac:
3185 return selectExtInst(ResVReg, ResType, I, CL::fract, GL::Fract);
3186 case Intrinsic::spv_normalize:
3187 return selectExtInst(ResVReg, ResType, I, CL::normalize, GL::Normalize);
3188 case Intrinsic::spv_refract:
3189 return selectExtInst(ResVReg, ResType, I, GL::Refract);
3190 case Intrinsic::spv_reflect:
3191 return selectExtInst(ResVReg, ResType, I, GL::Reflect);
3192 case Intrinsic::spv_rsqrt:
3193 return selectExtInst(ResVReg, ResType, I, CL::rsqrt, GL::InverseSqrt);
3194 case Intrinsic::spv_sign:
3195 return selectSign(ResVReg, ResType, I);
3196 case Intrinsic::spv_smoothstep:
3197 return selectExtInst(ResVReg, ResType, I, CL::smoothstep, GL::SmoothStep);
3198 case Intrinsic::spv_firstbituhigh: // There is no CL equivalent of FindUMsb
3199 return selectFirstBitHigh(ResVReg, ResType, I, /*IsSigned=*/false);
3200 case Intrinsic::spv_firstbitshigh: // There is no CL equivalent of FindSMsb
3201 return selectFirstBitHigh(ResVReg, ResType, I, /*IsSigned=*/true);
3202 case Intrinsic::spv_firstbitlow: // There is no CL equivlent of FindILsb
3203 return selectFirstBitLow(ResVReg, ResType, I);
3204 case Intrinsic::spv_group_memory_barrier_with_group_sync: {
3205 bool Result = true;
3206 auto MemSemConstant =
3207 buildI32Constant(SPIRV::MemorySemantics::SequentiallyConsistent, I);
3208 Register MemSemReg = MemSemConstant.first;
3209 Result &= MemSemConstant.second;
3210 auto ScopeConstant = buildI32Constant(SPIRV::Scope::Workgroup, I);
3211 Register ScopeReg = ScopeConstant.first;
3212 Result &= ScopeConstant.second;
3213 MachineBasicBlock &BB = *I.getParent();
3214 return Result &&
3215 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpControlBarrier))
3216 .addUse(ScopeReg)
3217 .addUse(ScopeReg)
3218 .addUse(MemSemReg)
3219 .constrainAllUses(TII, TRI, RBI);
3220 }
3221 case Intrinsic::spv_generic_cast_to_ptr_explicit: {
3222 Register PtrReg = I.getOperand(I.getNumExplicitDefs() + 1).getReg();
3223 SPIRV::StorageClass::StorageClass ResSC =
3224 GR.getPointerStorageClass(ResType);
3225 if (!isGenericCastablePtr(ResSC))
3226 report_fatal_error("The target storage class is not castable from the "
3227 "Generic storage class");
3228 return BuildMI(BB, I, I.getDebugLoc(),
3229 TII.get(SPIRV::OpGenericCastToPtrExplicit))
3230 .addDef(ResVReg)
3231 .addUse(GR.getSPIRVTypeID(ResType))
3232 .addUse(PtrReg)
3233 .addImm(ResSC)
3234 .constrainAllUses(TII, TRI, RBI);
3235 }
3236 case Intrinsic::spv_lifetime_start:
3237 case Intrinsic::spv_lifetime_end: {
3238 unsigned Op = IID == Intrinsic::spv_lifetime_start ? SPIRV::OpLifetimeStart
3239 : SPIRV::OpLifetimeStop;
3240 int64_t Size = I.getOperand(I.getNumExplicitDefs() + 1).getImm();
3241 Register PtrReg = I.getOperand(I.getNumExplicitDefs() + 2).getReg();
3242 if (Size == -1)
3243 Size = 0;
3244 return BuildMI(BB, I, I.getDebugLoc(), TII.get(Op))
3245 .addUse(PtrReg)
3246 .addImm(Size)
3247 .constrainAllUses(TII, TRI, RBI);
3248 }
3249 case Intrinsic::spv_saturate:
3250 return selectSaturate(ResVReg, ResType, I);
3251 case Intrinsic::spv_nclamp:
3252 return selectExtInst(ResVReg, ResType, I, CL::fclamp, GL::NClamp);
3253 case Intrinsic::spv_uclamp:
3254 return selectExtInst(ResVReg, ResType, I, CL::u_clamp, GL::UClamp);
3255 case Intrinsic::spv_sclamp:
3256 return selectExtInst(ResVReg, ResType, I, CL::s_clamp, GL::SClamp);
3257 case Intrinsic::spv_wave_active_countbits:
3258 return selectWaveActiveCountBits(ResVReg, ResType, I);
3259 case Intrinsic::spv_wave_all:
3260 return selectWaveOpInst(ResVReg, ResType, I, SPIRV::OpGroupNonUniformAll);
3261 case Intrinsic::spv_wave_any:
3262 return selectWaveOpInst(ResVReg, ResType, I, SPIRV::OpGroupNonUniformAny);
3263 case Intrinsic::spv_wave_is_first_lane:
3264 return selectWaveOpInst(ResVReg, ResType, I, SPIRV::OpGroupNonUniformElect);
3265 case Intrinsic::spv_wave_reduce_umax:
3266 return selectWaveReduceMax(ResVReg, ResType, I, /*IsUnsigned*/ true);
3267 case Intrinsic::spv_wave_reduce_max:
3268 return selectWaveReduceMax(ResVReg, ResType, I, /*IsUnsigned*/ false);
3269 case Intrinsic::spv_wave_reduce_sum:
3270 return selectWaveReduceSum(ResVReg, ResType, I);
3271 case Intrinsic::spv_wave_readlane:
3272 return selectWaveOpInst(ResVReg, ResType, I,
3273 SPIRV::OpGroupNonUniformShuffle);
3274 case Intrinsic::spv_step:
3275 return selectExtInst(ResVReg, ResType, I, CL::step, GL::Step);
3276 case Intrinsic::spv_radians:
3277 return selectExtInst(ResVReg, ResType, I, CL::radians, GL::Radians);
3278 // Discard intrinsics which we do not expect to actually represent code after
3279 // lowering or intrinsics which are not implemented but should not crash when
3280 // found in a customer's LLVM IR input.
3281 case Intrinsic::instrprof_increment:
3282 case Intrinsic::instrprof_increment_step:
3283 case Intrinsic::instrprof_value_profile:
3284 break;
3285 // Discard internal intrinsics.
3286 case Intrinsic::spv_value_md:
3287 break;
3288 case Intrinsic::spv_resource_handlefrombinding: {
3289 return selectHandleFromBinding(ResVReg, ResType, I);
3290 }
3291 case Intrinsic::spv_resource_store_typedbuffer: {
3292 return selectImageWriteIntrinsic(I);
3293 }
3294 case Intrinsic::spv_resource_load_typedbuffer: {
3295 return selectReadImageIntrinsic(ResVReg, ResType, I);
3296 }
3297 case Intrinsic::spv_resource_getpointer: {
3298 return selectResourceGetPointer(ResVReg, ResType, I);
3299 }
3300 case Intrinsic::spv_discard: {
3301 return selectDiscard(ResVReg, ResType, I);
3302 }
3303 case Intrinsic::modf: {
3304 return selectModf(ResVReg, ResType, I);
3305 }
3306 default: {
3307 std::string DiagMsg;
3308 raw_string_ostream OS(DiagMsg);
3309 I.print(OS);
3310 DiagMsg = "Intrinsic selection not implemented: " + DiagMsg;
3311 report_fatal_error(DiagMsg.c_str(), false);
3312 }
3313 }
3314 return true;
3315}
3316
3317bool SPIRVInstructionSelector::selectHandleFromBinding(Register &ResVReg,
3318 const SPIRVType *ResType,
3319 MachineInstr &I) const {
3320 // The images need to be loaded in the same basic block as their use. We defer
3321 // loading the image to the intrinsic that uses it.
3322 if (ResType->getOpcode() == SPIRV::OpTypeImage)
3323 return true;
3324
3325 return loadHandleBeforePosition(ResVReg, GR.getSPIRVTypeForVReg(ResVReg),
3326 *cast<GIntrinsic>(&I), I);
3327}
3328
3329bool SPIRVInstructionSelector::selectReadImageIntrinsic(
3330 Register &ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
3331
3332 // If the load of the image is in a different basic block, then
3333 // this will generate invalid code. A proper solution is to move
3334 // the OpLoad from selectHandleFromBinding here. However, to do
3335 // that we will need to change the return type of the intrinsic.
3336 // We will do that when we can, but for now trying to move forward with other
3337 // issues.
3338 Register ImageReg = I.getOperand(2).getReg();
3339 auto *ImageDef = cast<GIntrinsic>(getVRegDef(*MRI, ImageReg));
3340 Register NewImageReg = MRI->createVirtualRegister(MRI->getRegClass(ImageReg));
3341 if (!loadHandleBeforePosition(NewImageReg, GR.getSPIRVTypeForVReg(ImageReg),
3342 *ImageDef, I)) {
3343 return false;
3344 }
3345
3346 Register IdxReg = I.getOperand(3).getReg();
3347 DebugLoc Loc = I.getDebugLoc();
3348 MachineInstr &Pos = I;
3349
3350 return generateImageRead(ResVReg, ResType, NewImageReg, IdxReg, Loc, Pos);
3351}
3352
3353bool SPIRVInstructionSelector::generateImageRead(Register &ResVReg,
3354 const SPIRVType *ResType,
3355 Register ImageReg,
3356 Register IdxReg, DebugLoc Loc,
3357 MachineInstr &Pos) const {
3358 SPIRVType *ImageType = GR.getSPIRVTypeForVReg(ImageReg);
3359 assert(ImageType && ImageType->getOpcode() == SPIRV::OpTypeImage &&
3360 "ImageReg is not an image type.");
3361 bool IsSignedInteger =
3362 sampledTypeIsSignedInteger(GR.getTypeForSPIRVType(ImageType));
3363
3364 uint64_t ResultSize = GR.getScalarOrVectorComponentCount(ResType);
3365 if (ResultSize == 4) {
3366 auto BMI = BuildMI(*Pos.getParent(), Pos, Loc, TII.get(SPIRV::OpImageRead))
3367 .addDef(ResVReg)
3368 .addUse(GR.getSPIRVTypeID(ResType))
3369 .addUse(ImageReg)
3370 .addUse(IdxReg);
3371
3372 if (IsSignedInteger)
3373 BMI.addImm(0x1000); // SignExtend
3374 return BMI.constrainAllUses(TII, TRI, RBI);
3375 }
3376
3377 SPIRVType *ReadType = widenTypeToVec4(ResType, Pos);
3378 Register ReadReg = MRI->createVirtualRegister(GR.getRegClass(ReadType));
3379 auto BMI = BuildMI(*Pos.getParent(), Pos, Loc, TII.get(SPIRV::OpImageRead))
3380 .addDef(ReadReg)
3381 .addUse(GR.getSPIRVTypeID(ReadType))
3382 .addUse(ImageReg)
3383 .addUse(IdxReg);
3384 if (IsSignedInteger)
3385 BMI.addImm(0x1000); // SignExtend
3386 bool Succeed = BMI.constrainAllUses(TII, TRI, RBI);
3387 if (!Succeed)
3388 return false;
3389
3390 if (ResultSize == 1) {
3391 return BuildMI(*Pos.getParent(), Pos, Loc,
3392 TII.get(SPIRV::OpCompositeExtract))
3393 .addDef(ResVReg)
3394 .addUse(GR.getSPIRVTypeID(ResType))
3395 .addUse(ReadReg)
3396 .addImm(0)
3397 .constrainAllUses(TII, TRI, RBI);
3398 }
3399 return extractSubvector(ResVReg, ResType, ReadReg, Pos);
3400}
3401
3402bool SPIRVInstructionSelector::selectResourceGetPointer(
3403 Register &ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
3404 Register ResourcePtr = I.getOperand(2).getReg();
3405 SPIRVType *RegType = GR.getSPIRVTypeForVReg(ResourcePtr, I.getMF());
3406 if (RegType->getOpcode() == SPIRV::OpTypeImage) {
3407 // For texel buffers, the index into the image is part of the OpImageRead or
3408 // OpImageWrite instructions. So we will do nothing in this case. This
3409 // intrinsic will be combined with the load or store when selecting the load
3410 // or store.
3411 return true;
3412 }
3413
3414 assert(ResType->getOpcode() == SPIRV::OpTypePointer);
3415 MachineIRBuilder MIRBuilder(I);
3416
3417 Register IndexReg = I.getOperand(3).getReg();
3418 Register ZeroReg =
3419 buildZerosVal(GR.getOrCreateSPIRVIntegerType(32, I, TII), I);
3420 return BuildMI(*I.getParent(), I, I.getDebugLoc(),
3421 TII.get(SPIRV::OpAccessChain))
3422 .addDef(ResVReg)
3423 .addUse(GR.getSPIRVTypeID(ResType))
3424 .addUse(ResourcePtr)
3425 .addUse(ZeroReg)
3426 .addUse(IndexReg)
3427 .constrainAllUses(TII, TRI, RBI);
3428}
3429
3430bool SPIRVInstructionSelector::extractSubvector(
3431 Register &ResVReg, const SPIRVType *ResType, Register &ReadReg,
3433 SPIRVType *InputType = GR.getResultType(ReadReg);
3434 [[maybe_unused]] uint64_t InputSize =
3435 GR.getScalarOrVectorComponentCount(InputType);
3436 uint64_t ResultSize = GR.getScalarOrVectorComponentCount(ResType);
3437 assert(InputSize > 1 && "The input must be a vector.");
3438 assert(ResultSize > 1 && "The result must be a vector.");
3439 assert(ResultSize < InputSize &&
3440 "Cannot extract more element than there are in the input.");
3441 SmallVector<Register> ComponentRegisters;
3442 SPIRVType *ScalarType = GR.getScalarOrVectorComponentType(ResType);
3443 const TargetRegisterClass *ScalarRegClass = GR.getRegClass(ScalarType);
3444 for (uint64_t I = 0; I < ResultSize; I++) {
3445 Register ComponentReg = MRI->createVirtualRegister(ScalarRegClass);
3446 bool Succeed = BuildMI(*InsertionPoint.getParent(), InsertionPoint,
3447 InsertionPoint.getDebugLoc(),
3448 TII.get(SPIRV::OpCompositeExtract))
3449 .addDef(ComponentReg)
3450 .addUse(ScalarType->getOperand(0).getReg())
3451 .addUse(ReadReg)
3452 .addImm(I)
3453 .constrainAllUses(TII, TRI, RBI);
3454 if (!Succeed)
3455 return false;
3456 ComponentRegisters.emplace_back(ComponentReg);
3457 }
3458
3460 InsertionPoint.getDebugLoc(),
3461 TII.get(SPIRV::OpCompositeConstruct))
3462 .addDef(ResVReg)
3463 .addUse(GR.getSPIRVTypeID(ResType));
3464
3465 for (Register ComponentReg : ComponentRegisters)
3466 MIB.addUse(ComponentReg);
3467 return MIB.constrainAllUses(TII, TRI, RBI);
3468}
3469
3470bool SPIRVInstructionSelector::selectImageWriteIntrinsic(
3471 MachineInstr &I) const {
3472 // If the load of the image is in a different basic block, then
3473 // this will generate invalid code. A proper solution is to move
3474 // the OpLoad from selectHandleFromBinding here. However, to do
3475 // that we will need to change the return type of the intrinsic.
3476 // We will do that when we can, but for now trying to move forward with other
3477 // issues.
3478 Register ImageReg = I.getOperand(1).getReg();
3479 auto *ImageDef = cast<GIntrinsic>(getVRegDef(*MRI, ImageReg));
3480 Register NewImageReg = MRI->createVirtualRegister(MRI->getRegClass(ImageReg));
3481 if (!loadHandleBeforePosition(NewImageReg, GR.getSPIRVTypeForVReg(ImageReg),
3482 *ImageDef, I)) {
3483 return false;
3484 }
3485
3486 Register CoordinateReg = I.getOperand(2).getReg();
3487 Register DataReg = I.getOperand(3).getReg();
3488 assert(GR.getResultType(DataReg)->getOpcode() == SPIRV::OpTypeVector);
3489 assert(GR.getScalarOrVectorComponentCount(GR.getResultType(DataReg)) == 4);
3490 return BuildMI(*I.getParent(), I, I.getDebugLoc(),
3491 TII.get(SPIRV::OpImageWrite))
3492 .addUse(NewImageReg)
3493 .addUse(CoordinateReg)
3494 .addUse(DataReg)
3495 .constrainAllUses(TII, TRI, RBI);
3496}
3497
3498Register SPIRVInstructionSelector::buildPointerToResource(
3499 const SPIRVType *SpirvResType, SPIRV::StorageClass::StorageClass SC,
3500 uint32_t Set, uint32_t Binding, uint32_t ArraySize, Register IndexReg,
3501 bool IsNonUniform, StringRef Name, MachineIRBuilder MIRBuilder) const {
3502 const Type *ResType = GR.getTypeForSPIRVType(SpirvResType);
3503 if (ArraySize == 1) {
3504 SPIRVType *PtrType =
3505 GR.getOrCreateSPIRVPointerType(ResType, MIRBuilder, SC);
3506 assert(GR.getPointeeType(PtrType) == SpirvResType &&
3507 "SpirvResType did not have an explicit layout.");
3508 return GR.getOrCreateGlobalVariableWithBinding(PtrType, Set, Binding, Name,
3509 MIRBuilder);
3510 }
3511
3512 const Type *VarType = ArrayType::get(const_cast<Type *>(ResType), ArraySize);
3513 SPIRVType *VarPointerType =
3514 GR.getOrCreateSPIRVPointerType(VarType, MIRBuilder, SC);
3515 Register VarReg = GR.getOrCreateGlobalVariableWithBinding(
3516 VarPointerType, Set, Binding, Name, MIRBuilder);
3517
3518 SPIRVType *ResPointerType =
3519 GR.getOrCreateSPIRVPointerType(ResType, MIRBuilder, SC);
3520
3521 Register AcReg = MRI->createVirtualRegister(GR.getRegClass(ResPointerType));
3522 if (IsNonUniform) {
3523 // It is unclear which value needs to be marked an non-uniform, so both
3524 // the index and the access changed are decorated as non-uniform.
3525 buildOpDecorate(IndexReg, MIRBuilder, SPIRV::Decoration::NonUniformEXT, {});
3526 buildOpDecorate(AcReg, MIRBuilder, SPIRV::Decoration::NonUniformEXT, {});
3527 }
3528
3529 MIRBuilder.buildInstr(SPIRV::OpAccessChain)
3530 .addDef(AcReg)
3531 .addUse(GR.getSPIRVTypeID(ResPointerType))
3532 .addUse(VarReg)
3533 .addUse(IndexReg);
3534
3535 return AcReg;
3536}
3537
3538bool SPIRVInstructionSelector::selectFirstBitSet16(
3539 Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
3540 unsigned ExtendOpcode, unsigned BitSetOpcode) const {
3541 Register ExtReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
3542 bool Result = selectOpWithSrcs(ExtReg, ResType, I, {I.getOperand(2).getReg()},
3543 ExtendOpcode);
3544
3545 return Result &&
3546 selectFirstBitSet32(ResVReg, ResType, I, ExtReg, BitSetOpcode);
3547}
3548
3549bool SPIRVInstructionSelector::selectFirstBitSet32(
3550 Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
3551 Register SrcReg, unsigned BitSetOpcode) const {
3552 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
3553 .addDef(ResVReg)
3554 .addUse(GR.getSPIRVTypeID(ResType))
3555 .addImm(static_cast<uint32_t>(SPIRV::InstructionSet::GLSL_std_450))
3556 .addImm(BitSetOpcode)
3557 .addUse(SrcReg)
3558 .constrainAllUses(TII, TRI, RBI);
3559}
3560
3561bool SPIRVInstructionSelector::selectFirstBitSet64Overflow(
3562 Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
3563 Register SrcReg, unsigned BitSetOpcode, bool SwapPrimarySide) const {
3564
3565 // SPIR-V allow vectors of size 2,3,4 only. Calling with a larger vectors
3566 // requires creating a param register and return register with an invalid
3567 // vector size. If that is resolved, then this function can be used for
3568 // vectors of any component size.
3569 unsigned ComponentCount = GR.getScalarOrVectorComponentCount(ResType);
3570 assert(ComponentCount < 5 && "Vec 5+ will generate invalid SPIR-V ops");
3571
3572 MachineIRBuilder MIRBuilder(I);
3573 SPIRVType *BaseType = GR.retrieveScalarOrVectorIntType(ResType);
3574 SPIRVType *I64Type = GR.getOrCreateSPIRVIntegerType(64, MIRBuilder);
3575 SPIRVType *I64x2Type =
3576 GR.getOrCreateSPIRVVectorType(I64Type, 2, MIRBuilder, false);
3577 SPIRVType *Vec2ResType =
3578 GR.getOrCreateSPIRVVectorType(BaseType, 2, MIRBuilder, false);
3579
3580 std::vector<Register> PartialRegs;
3581
3582 // Loops 0, 2, 4, ... but stops one loop early when ComponentCount is odd
3583 unsigned CurrentComponent = 0;
3584 for (; CurrentComponent + 1 < ComponentCount; CurrentComponent += 2) {
3585 // This register holds the firstbitX result for each of the i64x2 vectors
3586 // extracted from SrcReg
3587 Register BitSetResult =
3588 MRI->createVirtualRegister(GR.getRegClass(I64x2Type));
3589
3590 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
3591 TII.get(SPIRV::OpVectorShuffle))
3592 .addDef(BitSetResult)
3593 .addUse(GR.getSPIRVTypeID(I64x2Type))
3594 .addUse(SrcReg)
3595 .addUse(SrcReg)
3596 .addImm(CurrentComponent)
3597 .addImm(CurrentComponent + 1);
3598
3599 if (!MIB.constrainAllUses(TII, TRI, RBI))
3600 return false;
3601
3602 Register SubVecBitSetReg =
3603 MRI->createVirtualRegister(GR.getRegClass(Vec2ResType));
3604
3605 if (!selectFirstBitSet64(SubVecBitSetReg, Vec2ResType, I, BitSetResult,
3606 BitSetOpcode, SwapPrimarySide))
3607 return false;
3608
3609 PartialRegs.push_back(SubVecBitSetReg);
3610 }
3611
3612 // On odd component counts we need to handle one more component
3613 if (CurrentComponent != ComponentCount) {
3614 bool ZeroAsNull = !STI.isShader();
3615 Register FinalElemReg = MRI->createVirtualRegister(GR.getRegClass(I64Type));
3616 Register ConstIntLastIdx = GR.getOrCreateConstInt(
3617 ComponentCount - 1, I, BaseType, TII, ZeroAsNull);
3618
3619 if (!selectOpWithSrcs(FinalElemReg, I64Type, I, {SrcReg, ConstIntLastIdx},
3620 SPIRV::OpVectorExtractDynamic))
3621 return false;
3622
3623 Register FinalElemBitSetReg =
3624 MRI->createVirtualRegister(GR.getRegClass(BaseType));
3625
3626 if (!selectFirstBitSet64(FinalElemBitSetReg, BaseType, I, FinalElemReg,
3627 BitSetOpcode, SwapPrimarySide))
3628 return false;
3629
3630 PartialRegs.push_back(FinalElemBitSetReg);
3631 }
3632
3633 // Join all the resulting registers back into the return type in order
3634 // (ie i32x2, i32x2, i32x1 -> i32x5)
3635 return selectOpWithSrcs(ResVReg, ResType, I, std::move(PartialRegs),
3636 SPIRV::OpCompositeConstruct);
3637}
3638
3639bool SPIRVInstructionSelector::selectFirstBitSet64(
3640 Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
3641 Register SrcReg, unsigned BitSetOpcode, bool SwapPrimarySide) const {
3642 unsigned ComponentCount = GR.getScalarOrVectorComponentCount(ResType);
3643 SPIRVType *BaseType = GR.retrieveScalarOrVectorIntType(ResType);
3644 bool ZeroAsNull = !STI.isShader();
3645 Register ConstIntZero =
3646 GR.getOrCreateConstInt(0, I, BaseType, TII, ZeroAsNull);
3647 Register ConstIntOne =
3648 GR.getOrCreateConstInt(1, I, BaseType, TII, ZeroAsNull);
3649
3650 // SPIRV doesn't support vectors with more than 4 components. Since the
3651 // algoritm below converts i64 -> i32x2 and i64x4 -> i32x8 it can only
3652 // operate on vectors with 2 or less components. When largers vectors are
3653 // seen. Split them, recurse, then recombine them.
3654 if (ComponentCount > 2) {
3655 return selectFirstBitSet64Overflow(ResVReg, ResType, I, SrcReg,
3656 BitSetOpcode, SwapPrimarySide);
3657 }
3658
3659 // 1. Split int64 into 2 pieces using a bitcast
3660 MachineIRBuilder MIRBuilder(I);
3661 SPIRVType *PostCastType = GR.getOrCreateSPIRVVectorType(
3662 BaseType, 2 * ComponentCount, MIRBuilder, false);
3663 Register BitcastReg =
3664 MRI->createVirtualRegister(GR.getRegClass(PostCastType));
3665
3666 if (!selectOpWithSrcs(BitcastReg, PostCastType, I, {SrcReg},
3667 SPIRV::OpBitcast))
3668 return false;
3669
3670 // 2. Find the first set bit from the primary side for all the pieces in #1
3671 Register FBSReg = MRI->createVirtualRegister(GR.getRegClass(PostCastType));
3672 if (!selectFirstBitSet32(FBSReg, PostCastType, I, BitcastReg, BitSetOpcode))
3673 return false;
3674
3675 // 3. Split result vector into high bits and low bits
3676 Register HighReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
3677 Register LowReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
3678
3679 bool IsScalarRes = ResType->getOpcode() != SPIRV::OpTypeVector;
3680 if (IsScalarRes) {
3681 // if scalar do a vector extract
3682 if (!selectOpWithSrcs(HighReg, ResType, I, {FBSReg, ConstIntZero},
3683 SPIRV::OpVectorExtractDynamic))
3684 return false;
3685 if (!selectOpWithSrcs(LowReg, ResType, I, {FBSReg, ConstIntOne},
3686 SPIRV::OpVectorExtractDynamic))
3687 return false;
3688 } else {
3689 // if vector do a shufflevector
3690 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
3691 TII.get(SPIRV::OpVectorShuffle))
3692 .addDef(HighReg)
3693 .addUse(GR.getSPIRVTypeID(ResType))
3694 .addUse(FBSReg)
3695 // Per the spec, repeat the vector if only one vec is needed
3696 .addUse(FBSReg);
3697
3698 // high bits are stored in even indexes. Extract them from FBSReg
3699 for (unsigned J = 0; J < ComponentCount * 2; J += 2) {
3700 MIB.addImm(J);
3701 }
3702
3703 if (!MIB.constrainAllUses(TII, TRI, RBI))
3704 return false;
3705
3706 MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
3707 TII.get(SPIRV::OpVectorShuffle))
3708 .addDef(LowReg)
3709 .addUse(GR.getSPIRVTypeID(ResType))
3710 .addUse(FBSReg)
3711 // Per the spec, repeat the vector if only one vec is needed
3712 .addUse(FBSReg);
3713
3714 // low bits are stored in odd indexes. Extract them from FBSReg
3715 for (unsigned J = 1; J < ComponentCount * 2; J += 2) {
3716 MIB.addImm(J);
3717 }
3718 if (!MIB.constrainAllUses(TII, TRI, RBI))
3719 return false;
3720 }
3721
3722 // 4. Check the result. When primary bits == -1 use secondary, otherwise use
3723 // primary
3724 SPIRVType *BoolType = GR.getOrCreateSPIRVBoolType(I, TII);
3725 Register NegOneReg;
3726 Register Reg0;
3727 Register Reg32;
3728 unsigned SelectOp;
3729 unsigned AddOp;
3730
3731 if (IsScalarRes) {
3732 NegOneReg =
3733 GR.getOrCreateConstInt((unsigned)-1, I, ResType, TII, ZeroAsNull);
3734 Reg0 = GR.getOrCreateConstInt(0, I, ResType, TII, ZeroAsNull);
3735 Reg32 = GR.getOrCreateConstInt(32, I, ResType, TII, ZeroAsNull);
3736 SelectOp = SPIRV::OpSelectSISCond;
3737 AddOp = SPIRV::OpIAddS;
3738 } else {
3739 BoolType = GR.getOrCreateSPIRVVectorType(BoolType, ComponentCount,
3740 MIRBuilder, false);
3741 NegOneReg =
3742 GR.getOrCreateConstVector((unsigned)-1, I, ResType, TII, ZeroAsNull);
3743 Reg0 = GR.getOrCreateConstVector(0, I, ResType, TII, ZeroAsNull);
3744 Reg32 = GR.getOrCreateConstVector(32, I, ResType, TII, ZeroAsNull);
3745 SelectOp = SPIRV::OpSelectVIVCond;
3746 AddOp = SPIRV::OpIAddV;
3747 }
3748
3749 Register PrimaryReg = HighReg;
3750 Register SecondaryReg = LowReg;
3751 Register PrimaryShiftReg = Reg32;
3752 Register SecondaryShiftReg = Reg0;
3753
3754 // By default the emitted opcodes check for the set bit from the MSB side.
3755 // Setting SwapPrimarySide checks the set bit from the LSB side
3756 if (SwapPrimarySide) {
3757 PrimaryReg = LowReg;
3758 SecondaryReg = HighReg;
3759 PrimaryShiftReg = Reg0;
3760 SecondaryShiftReg = Reg32;
3761 }
3762
3763 // Check if the primary bits are == -1
3764 Register BReg = MRI->createVirtualRegister(GR.getRegClass(BoolType));
3765 if (!selectOpWithSrcs(BReg, BoolType, I, {PrimaryReg, NegOneReg},
3766 SPIRV::OpIEqual))
3767 return false;
3768
3769 // Select secondary bits if true in BReg, otherwise primary bits
3770 Register TmpReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
3771 if (!selectOpWithSrcs(TmpReg, ResType, I, {BReg, SecondaryReg, PrimaryReg},
3772 SelectOp))
3773 return false;
3774
3775 // 5. Add 32 when high bits are used, otherwise 0 for low bits
3776 Register ValReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
3777 if (!selectOpWithSrcs(ValReg, ResType, I,
3778 {BReg, SecondaryShiftReg, PrimaryShiftReg}, SelectOp))
3779 return false;
3780
3781 return selectOpWithSrcs(ResVReg, ResType, I, {ValReg, TmpReg}, AddOp);
3782}
3783
3784bool SPIRVInstructionSelector::selectFirstBitHigh(Register ResVReg,
3785 const SPIRVType *ResType,
3786 MachineInstr &I,
3787 bool IsSigned) const {
3788 // FindUMsb and FindSMsb intrinsics only support 32 bit integers
3789 Register OpReg = I.getOperand(2).getReg();
3790 SPIRVType *OpType = GR.getSPIRVTypeForVReg(OpReg);
3791 // zero or sign extend
3792 unsigned ExtendOpcode = IsSigned ? SPIRV::OpSConvert : SPIRV::OpUConvert;
3793 unsigned BitSetOpcode = IsSigned ? GL::FindSMsb : GL::FindUMsb;
3794
3795 switch (GR.getScalarOrVectorBitWidth(OpType)) {
3796 case 16:
3797 return selectFirstBitSet16(ResVReg, ResType, I, ExtendOpcode, BitSetOpcode);
3798 case 32:
3799 return selectFirstBitSet32(ResVReg, ResType, I, OpReg, BitSetOpcode);
3800 case 64:
3801 return selectFirstBitSet64(ResVReg, ResType, I, OpReg, BitSetOpcode,
3802 /*SwapPrimarySide=*/false);
3803 default:
3805 "spv_firstbituhigh and spv_firstbitshigh only support 16,32,64 bits.");
3806 }
3807}
3808
3809bool SPIRVInstructionSelector::selectFirstBitLow(Register ResVReg,
3810 const SPIRVType *ResType,
3811 MachineInstr &I) const {
3812 // FindILsb intrinsic only supports 32 bit integers
3813 Register OpReg = I.getOperand(2).getReg();
3814 SPIRVType *OpType = GR.getSPIRVTypeForVReg(OpReg);
3815 // OpUConvert treats the operand bits as an unsigned i16 and zero extends it
3816 // to an unsigned i32. As this leaves all the least significant bits unchanged
3817 // so the first set bit from the LSB side doesn't change.
3818 unsigned ExtendOpcode = SPIRV::OpUConvert;
3819 unsigned BitSetOpcode = GL::FindILsb;
3820
3821 switch (GR.getScalarOrVectorBitWidth(OpType)) {
3822 case 16:
3823 return selectFirstBitSet16(ResVReg, ResType, I, ExtendOpcode, BitSetOpcode);
3824 case 32:
3825 return selectFirstBitSet32(ResVReg, ResType, I, OpReg, BitSetOpcode);
3826 case 64:
3827 return selectFirstBitSet64(ResVReg, ResType, I, OpReg, BitSetOpcode,
3828 /*SwapPrimarySide=*/true);
3829 default:
3830 report_fatal_error("spv_firstbitlow only supports 16,32,64 bits.");
3831 }
3832}
3833
3834bool SPIRVInstructionSelector::selectAllocaArray(Register ResVReg,
3835 const SPIRVType *ResType,
3836 MachineInstr &I) const {
3837 // there was an allocation size parameter to the allocation instruction
3838 // that is not 1
3839 MachineBasicBlock &BB = *I.getParent();
3840 bool Res = BuildMI(BB, I, I.getDebugLoc(),
3841 TII.get(SPIRV::OpVariableLengthArrayINTEL))
3842 .addDef(ResVReg)
3843 .addUse(GR.getSPIRVTypeID(ResType))
3844 .addUse(I.getOperand(2).getReg())
3845 .constrainAllUses(TII, TRI, RBI);
3846 if (!STI.isShader()) {
3847 unsigned Alignment = I.getOperand(3).getImm();
3848 buildOpDecorate(ResVReg, I, TII, SPIRV::Decoration::Alignment, {Alignment});
3849 }
3850 return Res;
3851}
3852
3853bool SPIRVInstructionSelector::selectFrameIndex(Register ResVReg,
3854 const SPIRVType *ResType,
3855 MachineInstr &I) const {
3856 // Change order of instructions if needed: all OpVariable instructions in a
3857 // function must be the first instructions in the first block
3858 auto It = getOpVariableMBBIt(I);
3859 bool Res = BuildMI(*It->getParent(), It, It->getDebugLoc(),
3860 TII.get(SPIRV::OpVariable))
3861 .addDef(ResVReg)
3862 .addUse(GR.getSPIRVTypeID(ResType))
3863 .addImm(static_cast<uint32_t>(SPIRV::StorageClass::Function))
3864 .constrainAllUses(TII, TRI, RBI);
3865 if (!STI.isShader()) {
3866 unsigned Alignment = I.getOperand(2).getImm();
3867 buildOpDecorate(ResVReg, *It, TII, SPIRV::Decoration::Alignment,
3868 {Alignment});
3869 }
3870 return Res;
3871}
3872
3873bool SPIRVInstructionSelector::selectBranch(MachineInstr &I) const {
3874 // InstructionSelector walks backwards through the instructions. We can use
3875 // both a G_BR and a G_BRCOND to create an OpBranchConditional. We hit G_BR
3876 // first, so can generate an OpBranchConditional here. If there is no
3877 // G_BRCOND, we just use OpBranch for a regular unconditional branch.
3878 const MachineInstr *PrevI = I.getPrevNode();
3879 MachineBasicBlock &MBB = *I.getParent();
3880 if (PrevI != nullptr && PrevI->getOpcode() == TargetOpcode::G_BRCOND) {
3881 return BuildMI(MBB, I, I.getDebugLoc(), TII.get(SPIRV::OpBranchConditional))
3882 .addUse(PrevI->getOperand(0).getReg())
3883 .addMBB(PrevI->getOperand(1).getMBB())
3884 .addMBB(I.getOperand(0).getMBB())
3885 .constrainAllUses(TII, TRI, RBI);
3886 }
3887 return BuildMI(MBB, I, I.getDebugLoc(), TII.get(SPIRV::OpBranch))
3888 .addMBB(I.getOperand(0).getMBB())
3889 .constrainAllUses(TII, TRI, RBI);
3890}
3891
3892bool SPIRVInstructionSelector::selectBranchCond(MachineInstr &I) const {
3893 // InstructionSelector walks backwards through the instructions. For an
3894 // explicit conditional branch with no fallthrough, we use both a G_BR and a
3895 // G_BRCOND to create an OpBranchConditional. We should hit G_BR first, and
3896 // generate the OpBranchConditional in selectBranch above.
3897 //
3898 // If an OpBranchConditional has been generated, we simply return, as the work
3899 // is alread done. If there is no OpBranchConditional, LLVM must be relying on
3900 // implicit fallthrough to the next basic block, so we need to create an
3901 // OpBranchConditional with an explicit "false" argument pointing to the next
3902 // basic block that LLVM would fall through to.
3903 const MachineInstr *NextI = I.getNextNode();
3904 // Check if this has already been successfully selected.
3905 if (NextI != nullptr && NextI->getOpcode() == SPIRV::OpBranchConditional)
3906 return true;
3907 // Must be relying on implicit block fallthrough, so generate an
3908 // OpBranchConditional with the "next" basic block as the "false" target.
3909 MachineBasicBlock &MBB = *I.getParent();
3910 unsigned NextMBBNum = MBB.getNextNode()->getNumber();
3911 MachineBasicBlock *NextMBB = I.getMF()->getBlockNumbered(NextMBBNum);
3912 return BuildMI(MBB, I, I.getDebugLoc(), TII.get(SPIRV::OpBranchConditional))
3913 .addUse(I.getOperand(0).getReg())
3914 .addMBB(I.getOperand(1).getMBB())
3915 .addMBB(NextMBB)
3916 .constrainAllUses(TII, TRI, RBI);
3917}
3918
3919bool SPIRVInstructionSelector::selectPhi(Register ResVReg,
3920 const SPIRVType *ResType,
3921 MachineInstr &I) const {
3922 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpPhi))
3923 .addDef(ResVReg)
3924 .addUse(GR.getSPIRVTypeID(ResType));
3925 const unsigned NumOps = I.getNumOperands();
3926 for (unsigned i = 1; i < NumOps; i += 2) {
3927 MIB.addUse(I.getOperand(i + 0).getReg());
3928 MIB.addMBB(I.getOperand(i + 1).getMBB());
3929 }
3930 bool Res = MIB.constrainAllUses(TII, TRI, RBI);
3931 MIB->setDesc(TII.get(TargetOpcode::PHI));
3932 MIB->removeOperand(1);
3933 return Res;
3934}
3935
3936bool SPIRVInstructionSelector::selectGlobalValue(
3937 Register ResVReg, MachineInstr &I, const MachineInstr *Init) const {
3938 // FIXME: don't use MachineIRBuilder here, replace it with BuildMI.
3939 MachineIRBuilder MIRBuilder(I);
3940 const GlobalValue *GV = I.getOperand(1).getGlobal();
3941 Type *GVType = toTypedPointer(GR.getDeducedGlobalValueType(GV));
3942
3943 std::string GlobalIdent;
3944 if (!GV->hasName()) {
3945 unsigned &ID = UnnamedGlobalIDs[GV];
3946 if (ID == 0)
3947 ID = UnnamedGlobalIDs.size();
3948 GlobalIdent = "__unnamed_" + Twine(ID).str();
3949 } else {
3950 GlobalIdent = GV->getName();
3951 }
3952
3953 // Behaviour of functions as operands depends on availability of the
3954 // corresponding extension (SPV_INTEL_function_pointers):
3955 // - If there is an extension to operate with functions as operands:
3956 // We create a proper constant operand and evaluate a correct type for a
3957 // function pointer.
3958 // - Without the required extension:
3959 // We have functions as operands in tests with blocks of instruction e.g. in
3960 // transcoding/global_block.ll. These operands are not used and should be
3961 // substituted by zero constants. Their type is expected to be always
3962 // OpTypePointer Function %uchar.
3963 if (isa<Function>(GV)) {
3964 const Constant *ConstVal = GV;
3965 MachineBasicBlock &BB = *I.getParent();
3966 Register NewReg = GR.find(ConstVal, GR.CurMF);
3967 if (!NewReg.isValid()) {
3968 Register NewReg = ResVReg;
3969 const Function *GVFun =
3970 STI.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)
3971 ? dyn_cast<Function>(GV)
3972 : nullptr;
3973 SPIRVType *ResType = GR.getOrCreateSPIRVPointerType(
3974 GVType, I,
3975 GVFun ? SPIRV::StorageClass::CodeSectionINTEL
3977 if (GVFun) {
3978 // References to a function via function pointers generate virtual
3979 // registers without a definition. We will resolve it later, during
3980 // module analysis stage.
3981 Register ResTypeReg = GR.getSPIRVTypeID(ResType);
3982 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
3983 Register FuncVReg =
3984 MRI->createGenericVirtualRegister(GR.getRegType(ResType));
3985 MRI->setRegClass(FuncVReg, &SPIRV::pIDRegClass);
3986 MachineInstrBuilder MIB1 =
3987 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpUndef))
3988 .addDef(FuncVReg)
3989 .addUse(ResTypeReg);
3990 MachineInstrBuilder MIB2 =
3991 BuildMI(BB, I, I.getDebugLoc(),
3992 TII.get(SPIRV::OpConstantFunctionPointerINTEL))
3993 .addDef(NewReg)
3994 .addUse(ResTypeReg)
3995 .addUse(FuncVReg);
3996 GR.add(ConstVal, MIB2);
3997 // mapping the function pointer to the used Function
3998 GR.recordFunctionPointer(&MIB2.getInstr()->getOperand(2), GVFun);
3999 return MIB1.constrainAllUses(TII, TRI, RBI) &&
4000 MIB2.constrainAllUses(TII, TRI, RBI);
4001 }
4002 MachineInstrBuilder MIB3 =
4003 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpConstantNull))
4004 .addDef(NewReg)
4005 .addUse(GR.getSPIRVTypeID(ResType));
4006 GR.add(ConstVal, MIB3);
4007 return MIB3.constrainAllUses(TII, TRI, RBI);
4008 }
4009 assert(NewReg != ResVReg);
4010 return BuildCOPY(ResVReg, NewReg, I);
4011 }
4012 auto GlobalVar = cast<GlobalVariable>(GV);
4013 assert(GlobalVar->getName() != "llvm.global.annotations");
4014
4015 // Skip empty declaration for GVs with initializers till we get the decl with
4016 // passed initializer.
4017 if (hasInitializer(GlobalVar) && !Init)
4018 return true;
4019
4020 bool HasLnkTy = !GV->hasInternalLinkage() && !GV->hasPrivateLinkage() &&
4021 !GV->hasHiddenVisibility();
4022 SPIRV::LinkageType::LinkageType LnkType =
4024 ? SPIRV::LinkageType::Import
4025 : (GV->hasLinkOnceODRLinkage() &&
4026 STI.canUseExtension(SPIRV::Extension::SPV_KHR_linkonce_odr)
4027 ? SPIRV::LinkageType::LinkOnceODR
4028 : SPIRV::LinkageType::Export);
4029
4030 const unsigned AddrSpace = GV->getAddressSpace();
4031 SPIRV::StorageClass::StorageClass StorageClass =
4032 addressSpaceToStorageClass(AddrSpace, STI);
4033 SPIRVType *ResType = GR.getOrCreateSPIRVPointerType(GVType, I, StorageClass);
4034 Register Reg = GR.buildGlobalVariable(
4035 ResVReg, ResType, GlobalIdent, GV, StorageClass, Init,
4036 GlobalVar->isConstant(), HasLnkTy, LnkType, MIRBuilder, true);
4037 return Reg.isValid();
4038}
4039
4040bool SPIRVInstructionSelector::selectLog10(Register ResVReg,
4041 const SPIRVType *ResType,
4042 MachineInstr &I) const {
4043 if (STI.canUseExtInstSet(SPIRV::InstructionSet::OpenCL_std)) {
4044 return selectExtInst(ResVReg, ResType, I, CL::log10);
4045 }
4046
4047 // There is no log10 instruction in the GLSL Extended Instruction set, so it
4048 // is implemented as:
4049 // log10(x) = log2(x) * (1 / log2(10))
4050 // = log2(x) * 0.30103
4051
4052 MachineIRBuilder MIRBuilder(I);
4053 MachineBasicBlock &BB = *I.getParent();
4054
4055 // Build log2(x).
4056 Register VarReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
4057 bool Result =
4058 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
4059 .addDef(VarReg)
4060 .addUse(GR.getSPIRVTypeID(ResType))
4061 .addImm(static_cast<uint32_t>(SPIRV::InstructionSet::GLSL_std_450))
4062 .addImm(GL::Log2)
4063 .add(I.getOperand(1))
4064 .constrainAllUses(TII, TRI, RBI);
4065
4066 // Build 0.30103.
4067 assert(ResType->getOpcode() == SPIRV::OpTypeVector ||
4068 ResType->getOpcode() == SPIRV::OpTypeFloat);
4069 // TODO: Add matrix implementation once supported by the HLSL frontend.
4070 const SPIRVType *SpirvScalarType =
4071 ResType->getOpcode() == SPIRV::OpTypeVector
4072 ? GR.getSPIRVTypeForVReg(ResType->getOperand(1).getReg())
4073 : ResType;
4074 Register ScaleReg =
4075 GR.buildConstantFP(APFloat(0.30103f), MIRBuilder, SpirvScalarType);
4076
4077 // Multiply log2(x) by 0.30103 to get log10(x) result.
4078 auto Opcode = ResType->getOpcode() == SPIRV::OpTypeVector
4079 ? SPIRV::OpVectorTimesScalar
4080 : SPIRV::OpFMulS;
4081 return Result && BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
4082 .addDef(ResVReg)
4083 .addUse(GR.getSPIRVTypeID(ResType))
4084 .addUse(VarReg)
4085 .addUse(ScaleReg)
4086 .constrainAllUses(TII, TRI, RBI);
4087}
4088
4089bool SPIRVInstructionSelector::selectModf(Register ResVReg,
4090 const SPIRVType *ResType,
4091 MachineInstr &I) const {
4092 // llvm.modf has a single arg --the number to be decomposed-- and returns a
4093 // struct { restype, restype }, while OpenCLLIB::modf has two args --the
4094 // number to be decomposed and a pointer--, returns the fractional part and
4095 // the integral part is stored in the pointer argument. Therefore, we can't
4096 // use directly the OpenCLLIB::modf intrinsic. However, we can do some
4097 // scaffolding to make it work. The idea is to create an alloca instruction
4098 // to get a ptr, pass this ptr to OpenCL::modf, and then load the value
4099 // from this ptr to place it in the struct. llvm.modf returns the fractional
4100 // part as the first element of the result, and the integral part as the
4101 // second element of the result.
4102
4103 // At this point, the return type is not a struct anymore, but rather two
4104 // independent elements of SPIRVResType. We can get each independent element
4105 // from I.getDefs() or I.getOperands().
4106 if (STI.canUseExtInstSet(SPIRV::InstructionSet::OpenCL_std)) {
4107 MachineIRBuilder MIRBuilder(I);
4108 // Get pointer type for alloca variable.
4109 const SPIRVType *PtrType = GR.getOrCreateSPIRVPointerType(
4110 ResType, MIRBuilder, SPIRV::StorageClass::Function);
4111 // Create new register for the pointer type of alloca variable.
4112 Register PtrTyReg =
4113 MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
4114 MIRBuilder.getMRI()->setType(
4115 PtrTyReg,
4116 LLT::pointer(storageClassToAddressSpace(SPIRV::StorageClass::Function),
4117 GR.getPointerSize()));
4118 // Assign SPIR-V type of the pointer type of the alloca variable to the
4119 // new register.
4120 GR.assignSPIRVTypeToVReg(PtrType, PtrTyReg, MIRBuilder.getMF());
4121 MachineBasicBlock &EntryBB = I.getMF()->front();
4124 auto AllocaMIB =
4125 BuildMI(EntryBB, VarPos, I.getDebugLoc(), TII.get(SPIRV::OpVariable))
4126 .addDef(PtrTyReg)
4127 .addUse(GR.getSPIRVTypeID(PtrType))
4128 .addImm(static_cast<uint32_t>(SPIRV::StorageClass::Function));
4129 Register Variable = AllocaMIB->getOperand(0).getReg();
4130 // Modf must have 4 operands, the first two are the 2 parts of the result,
4131 // the third is the operand, and the last one is the floating point value.
4132 assert(I.getNumOperands() == 4 &&
4133 "Expected 4 operands for modf instruction");
4134 MachineBasicBlock &BB = *I.getParent();
4135 // Create the OpenCLLIB::modf instruction.
4136 auto MIB =
4137 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
4138 .addDef(ResVReg)
4139 .addUse(GR.getSPIRVTypeID(ResType))
4140 .addImm(static_cast<uint32_t>(SPIRV::InstructionSet::OpenCL_std))
4141 .addImm(CL::modf)
4142 .setMIFlags(I.getFlags())
4143 .add(I.getOperand(3)) // Floating point value.
4144 .addUse(Variable); // Pointer to integral part.
4145 // Assign the integral part stored in the ptr to the second element of the
4146 // result.
4147 Register IntegralPartReg = I.getOperand(1).getReg();
4148 if (IntegralPartReg.isValid()) {
4149 // Load the value from the pointer to integral part.
4150 auto LoadMIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpLoad))
4151 .addDef(IntegralPartReg)
4152 .addUse(GR.getSPIRVTypeID(ResType))
4153 .addUse(Variable);
4154 return LoadMIB.constrainAllUses(TII, TRI, RBI);
4155 }
4156
4157 return MIB.constrainAllUses(TII, TRI, RBI);
4158 } else if (STI.canUseExtInstSet(SPIRV::InstructionSet::GLSL_std_450)) {
4159 assert(false && "GLSL::Modf is deprecated.");
4160 // FIXME: GL::Modf is deprecated, use Modfstruct instead.
4161 return false;
4162 }
4163 return false;
4164}
4165
4166// Generate the instructions to load 3-element vector builtin input
4167// IDs/Indices.
4168// Like: GlobalInvocationId, LocalInvocationId, etc....
4169
4170bool SPIRVInstructionSelector::loadVec3BuiltinInputID(
4171 SPIRV::BuiltIn::BuiltIn BuiltInValue, Register ResVReg,
4172 const SPIRVType *ResType, MachineInstr &I) const {
4173 MachineIRBuilder MIRBuilder(I);
4174 const SPIRVType *Vec3Ty =
4175 GR.getOrCreateSPIRVVectorType(ResType, 3, MIRBuilder, false);
4176 const SPIRVType *PtrType = GR.getOrCreateSPIRVPointerType(
4177 Vec3Ty, MIRBuilder, SPIRV::StorageClass::Input);
4178
4179 // Create new register for the input ID builtin variable.
4180 Register NewRegister =
4181 MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
4182 MIRBuilder.getMRI()->setType(NewRegister, LLT::pointer(0, 64));
4183 GR.assignSPIRVTypeToVReg(PtrType, NewRegister, MIRBuilder.getMF());
4184
4185 // Build global variable with the necessary decorations for the input ID
4186 // builtin variable.
4187 Register Variable = GR.buildGlobalVariable(
4188 NewRegister, PtrType, getLinkStringForBuiltIn(BuiltInValue), nullptr,
4189 SPIRV::StorageClass::Input, nullptr, true, false,
4190 SPIRV::LinkageType::Import, MIRBuilder, false);
4191
4192 // Create new register for loading value.
4193 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
4194 Register LoadedRegister = MRI->createVirtualRegister(&SPIRV::iIDRegClass);
4195 MIRBuilder.getMRI()->setType(LoadedRegister, LLT::pointer(0, 64));
4196 GR.assignSPIRVTypeToVReg(Vec3Ty, LoadedRegister, MIRBuilder.getMF());
4197
4198 // Load v3uint value from the global variable.
4199 bool Result =
4200 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpLoad))
4201 .addDef(LoadedRegister)
4202 .addUse(GR.getSPIRVTypeID(Vec3Ty))
4203 .addUse(Variable);
4204
4205 // Get the input ID index. Expecting operand is a constant immediate value,
4206 // wrapped in a type assignment.
4207 assert(I.getOperand(2).isReg());
4208 const uint32_t ThreadId = foldImm(I.getOperand(2), MRI);
4209
4210 // Extract the input ID from the loaded vector value.
4211 MachineBasicBlock &BB = *I.getParent();
4212 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
4213 .addDef(ResVReg)
4214 .addUse(GR.getSPIRVTypeID(ResType))
4215 .addUse(LoadedRegister)
4216 .addImm(ThreadId);
4217 return Result && MIB.constrainAllUses(TII, TRI, RBI);
4218}
4219
4220// Generate the instructions to load 32-bit integer builtin input IDs/Indices.
4221// Like LocalInvocationIndex
4222bool SPIRVInstructionSelector::loadBuiltinInputID(
4223 SPIRV::BuiltIn::BuiltIn BuiltInValue, Register ResVReg,
4224 const SPIRVType *ResType, MachineInstr &I) const {
4225 MachineIRBuilder MIRBuilder(I);
4226 const SPIRVType *PtrType = GR.getOrCreateSPIRVPointerType(
4227 ResType, MIRBuilder, SPIRV::StorageClass::Input);
4228
4229 // Create new register for the input ID builtin variable.
4230 Register NewRegister =
4231 MIRBuilder.getMRI()->createVirtualRegister(GR.getRegClass(PtrType));
4232 MIRBuilder.getMRI()->setType(
4233 NewRegister,
4234 LLT::pointer(storageClassToAddressSpace(SPIRV::StorageClass::Input),
4235 GR.getPointerSize()));
4236 GR.assignSPIRVTypeToVReg(PtrType, NewRegister, MIRBuilder.getMF());
4237
4238 // Build global variable with the necessary decorations for the input ID
4239 // builtin variable.
4240 Register Variable = GR.buildGlobalVariable(
4241 NewRegister, PtrType, getLinkStringForBuiltIn(BuiltInValue), nullptr,
4242 SPIRV::StorageClass::Input, nullptr, true, false,
4243 SPIRV::LinkageType::Import, MIRBuilder, false);
4244
4245 // Load uint value from the global variable.
4246 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpLoad))
4247 .addDef(ResVReg)
4248 .addUse(GR.getSPIRVTypeID(ResType))
4249 .addUse(Variable);
4250
4251 return MIB.constrainAllUses(TII, TRI, RBI);
4252}
4253
4254SPIRVType *SPIRVInstructionSelector::widenTypeToVec4(const SPIRVType *Type,
4255 MachineInstr &I) const {
4256 MachineIRBuilder MIRBuilder(I);
4257 if (Type->getOpcode() != SPIRV::OpTypeVector)
4258 return GR.getOrCreateSPIRVVectorType(Type, 4, MIRBuilder, false);
4259
4260 uint64_t VectorSize = Type->getOperand(2).getImm();
4261 if (VectorSize == 4)
4262 return Type;
4263
4264 Register ScalarTypeReg = Type->getOperand(1).getReg();
4265 const SPIRVType *ScalarType = GR.getSPIRVTypeForVReg(ScalarTypeReg);
4266 return GR.getOrCreateSPIRVVectorType(ScalarType, 4, MIRBuilder, false);
4267}
4268
4269bool SPIRVInstructionSelector::loadHandleBeforePosition(
4270 Register &HandleReg, const SPIRVType *ResType, GIntrinsic &HandleDef,
4271 MachineInstr &Pos) const {
4272
4273 assert(HandleDef.getIntrinsicID() ==
4274 Intrinsic::spv_resource_handlefrombinding);
4275 uint32_t Set = foldImm(HandleDef.getOperand(2), MRI);
4276 uint32_t Binding = foldImm(HandleDef.getOperand(3), MRI);
4277 uint32_t ArraySize = foldImm(HandleDef.getOperand(4), MRI);
4278 Register IndexReg = HandleDef.getOperand(5).getReg();
4279 // FIXME: The IsNonUniform flag needs to be set based on resource analysis.
4280 // https://github.com/llvm/llvm-project/issues/155701
4281 bool IsNonUniform = false;
4282 std::string Name =
4283 getStringValueFromReg(HandleDef.getOperand(6).getReg(), *MRI);
4284
4285 bool IsStructuredBuffer = ResType->getOpcode() == SPIRV::OpTypePointer;
4286 MachineIRBuilder MIRBuilder(HandleDef);
4287 SPIRVType *VarType = ResType;
4288 SPIRV::StorageClass::StorageClass SC = SPIRV::StorageClass::UniformConstant;
4289
4290 if (IsStructuredBuffer) {
4291 VarType = GR.getPointeeType(ResType);
4292 SC = GR.getPointerStorageClass(ResType);
4293 }
4294
4295 Register VarReg =
4296 buildPointerToResource(VarType, SC, Set, Binding, ArraySize, IndexReg,
4297 IsNonUniform, Name, MIRBuilder);
4298
4299 if (IsNonUniform)
4300 buildOpDecorate(HandleReg, HandleDef, TII, SPIRV::Decoration::NonUniformEXT,
4301 {});
4302
4303 // The handle for the buffer is the pointer to the resource. For an image, the
4304 // handle is the image object. So images get an extra load.
4305 uint32_t LoadOpcode =
4306 IsStructuredBuffer ? SPIRV::OpCopyObject : SPIRV::OpLoad;
4307 GR.assignSPIRVTypeToVReg(ResType, HandleReg, *Pos.getMF());
4308 return BuildMI(*Pos.getParent(), Pos, HandleDef.getDebugLoc(),
4309 TII.get(LoadOpcode))
4310 .addDef(HandleReg)
4311 .addUse(GR.getSPIRVTypeID(ResType))
4312 .addUse(VarReg)
4313 .constrainAllUses(TII, TRI, RBI);
4314}
4315
4316namespace llvm {
4319 const SPIRVSubtarget &Subtarget,
4320 const RegisterBankInfo &RBI) {
4321 return new SPIRVInstructionSelector(TM, Subtarget, RBI);
4322}
4323} // namespace llvm
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
static bool selectUnmergeValues(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
DXIL Resource Implicit Binding
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
uint64_t Size
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define DEBUG_TYPE
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
Register const TargetRegisterInfo * TRI
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
static StringRef getName(Value *V)
std::vector< std::pair< SPIRV::InstructionSet::InstructionSet, uint32_t > > ExtInstList
#define GET_GLOBALISEL_PREDICATES_INIT
#define GET_GLOBALISEL_TEMPORARIES_INIT
static APFloat getOneFP(const Type *LLVMFloatTy)
static bool isUSMStorageClass(SPIRV::StorageClass::StorageClass SC)
static bool isASCastInGVar(MachineRegisterInfo *MRI, Register ResVReg)
static bool mayApplyGenericSelection(unsigned Opcode)
static APFloat getZeroFP(const Type *LLVMFloatTy)
static unsigned getFCmpOpcode(unsigned PredNum)
static unsigned getBoolCmpOpcode(unsigned PredNum)
static unsigned getICmpOpcode(unsigned PredNum)
static void addMemoryOperands(MachineMemOperand *MemOp, MachineInstrBuilder &MIB, MachineIRBuilder &MIRBuilder, SPIRVGlobalRegistry &GR)
static bool isConstReg(MachineRegisterInfo *MRI, MachineInstr *OpDef, SmallPtrSet< SPIRVType *, 4 > &Visited)
static unsigned getPtrCmpOpcode(unsigned Pred)
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
raw_pwrite_stream & OS
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition: Debug.h:119
BinaryOperator * Mul
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition: APFloat.h:1088
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition: APFloat.h:1079
Class for arbitrary precision integers.
Definition: APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:234
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1540
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:678
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:681
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:707
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:708
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:684
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:693
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:682
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:683
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:702
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:701
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:705
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:692
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:686
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:689
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:703
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:690
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:685
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:687
@ ICMP_EQ
equal
Definition: InstrTypes.h:699
@ ICMP_NE
not equal
Definition: InstrTypes.h:700
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:706
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:694
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:704
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:691
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:688
This is an important base class in LLVM.
Definition: Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:124
const Function & getFunction() const
Definition: Function.h:164
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:359
Represents a call to an intrinsic.
Intrinsic::ID getIntrinsicID() const
bool hasPrivateLinkage() const
Definition: GlobalValue.h:529
bool hasHiddenVisibility() const
Definition: GlobalValue.h:252
bool isDeclarationForLinker() const
Definition: GlobalValue.h:625
unsigned getAddressSpace() const
Definition: GlobalValue.h:207
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:663
bool hasInternalLinkage() const
Definition: GlobalValue.h:528
bool hasLinkOnceODRLinkage() const
Definition: GlobalValue.h:521
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:60
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:319
constexpr bool isScalar() const
Definition: LowLevelType.h:147
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
Definition: LowLevelType.h:43
constexpr bool isVector() const
Definition: LowLevelType.h:149
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
Definition: LowLevelType.h:58
constexpr bool isPointer() const
Definition: LowLevelType.h:150
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
Definition: LowLevelType.h:101
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Helper class to build MachineInstr.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineFunction & getMF()
Getter for the function we currently build.
MachineRegisterInfo * getMRI()
Getter for MRI.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
bool constrainAllUses(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
Definition: MachineInstr.h:72
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:587
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:359
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI unsigned getNumExplicitDefs() const
Returns the number of non-implicit definitions.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:511
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:595
A description of a memory reference used in the backend.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
Register getReg() const
getReg - Returns the register number.
defusechain_iterator - This class provides iterator support for machine operands in the function that...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI void setType(Register VReg, LLT Ty)
Set the low-level type of VReg to Ty.
Analysis providing profile information.
Holds all the information related to register banks.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:67
constexpr bool isValid() const
Definition: Register.h:107
MachineInstr * getOrAddMemAliasingINTELInst(MachineIRBuilder &MIRBuilder, const MDNode *AliasingListMD)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:401
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:476
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
Class to represent struct types.
Definition: DerivedTypes.h:218
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:414
Class to represent target extensions types, which are generally unintrospectable from target-independ...
Definition: DerivedTypes.h:781
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
@ HalfTyID
16-bit floating point type
Definition: Type.h:56
@ FloatTyID
32-bit floating point type
Definition: Type.h:58
@ DoubleTyID
64-bit floating point type
Definition: Type.h:59
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:261
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:136
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:352
bool hasName() const
Definition: Value.h:262
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:322
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:30
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:359
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:662
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsConst[]
Key for Kernel::Arg::Metadata::mIsConst.
Reg
All possible values of the reg field in the ModR/M byte.
StorageClass
Definition: XCOFF.h:171
NodeAddr< InstrNode * > Instr
Definition: RDFGraph.h:389
NodeAddr< DefNode * > Def
Definition: RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void buildOpName(Register Target, const StringRef &Name, MachineIRBuilder &MIRBuilder)
Definition: SPIRVUtils.cpp:113
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:1744
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool isTypeFoldingSupported(unsigned Opcode)
Definition: SPIRVUtils.cpp:958
void addNumImm(const APInt &Imm, MachineInstrBuilder &MIB)
Definition: SPIRVUtils.cpp:93
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition: Utils.cpp:1723
LLVM_ABI bool constrainSelectedInstRegOperands(MachineInstr &I, const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
Mutate the newly-selected instruction I to constrain its (possibly generic) virtual register operands...
Definition: Utils.cpp:155
bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel.
Definition: TargetOpcodes.h:30
unsigned getArrayComponentCount(const MachineRegisterInfo *MRI, const MachineInstr *ResType)
Definition: SPIRVUtils.cpp:995
uint64_t getIConstVal(Register ConstReg, const MachineRegisterInfo *MRI)
Definition: SPIRVUtils.cpp:368
SmallVector< MachineInstr *, 4 > createContinuedInstructions(MachineIRBuilder &MIRBuilder, unsigned Opcode, unsigned MinWC, unsigned ContinuedOpcode, ArrayRef< Register > Args, Register ReturnRegister, Register TypeID)
Definition: SPIRVUtils.cpp:859
SPIRV::MemorySemantics::MemorySemantics getMemSemanticsForStorageClass(SPIRV::StorageClass::StorageClass SC)
Definition: SPIRVUtils.cpp:283
constexpr unsigned storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC)
Definition: SPIRVUtils.h:191
MachineBasicBlock::iterator getFirstValidInstructionInsertPoint(MachineBasicBlock &BB)
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, const std::vector< uint32_t > &DecArgs, StringRef StrImm)
Definition: SPIRVUtils.cpp:140
MachineBasicBlock::iterator getOpVariableMBBIt(MachineInstr &I)
Definition: SPIRVUtils.cpp:211
Register createVirtualRegister(SPIRVType *SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF)
Definition: SPIRVUtils.cpp:794
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
Definition: SPIRVUtils.cpp:976
Type * toTypedPointer(Type *Ty)
Definition: SPIRVUtils.h:385
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition: Error.cpp:167
constexpr bool isGenericCastablePtr(SPIRV::StorageClass::StorageClass SC)
Definition: SPIRVUtils.h:176
MachineInstr * passCopy(MachineInstr *Def, const MachineRegisterInfo *MRI)
Definition: SPIRVUtils.cpp:963
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
Definition: SPIRVUtils.cpp:245
AtomicOrdering
Atomic ordering for LLVM's memory model.
SPIRV::Scope::Scope getMemScope(LLVMContext &Ctx, SyncScope::ID Id)
Definition: SPIRVUtils.cpp:319
InstructionSelector * createSPIRVInstructionSelector(const SPIRVTargetMachine &TM, const SPIRVSubtarget &Subtarget, const RegisterBankInfo &RBI)
std::string getStringValueFromReg(Register Reg, MachineRegisterInfo &MRI)
Definition: SPIRVUtils.cpp:83
int64_t foldImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
Definition: SPIRVUtils.cpp:985
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:223
bool hasInitializer(const GlobalVariable *GV)
Definition: SPIRVUtils.h:273
MachineInstr * getVRegDef(MachineRegisterInfo &MRI, Register Reg)
Definition: SPIRVUtils.cpp:747
SPIRV::MemorySemantics::MemorySemantics getMemSemantics(AtomicOrdering Ord)
Definition: SPIRVUtils.cpp:301
std::string getLinkStringForBuiltIn(SPIRV::BuiltIn::BuiltIn BuiltInValue)
LLVM_ABI bool isTriviallyDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Check whether an instruction MI is dead: it only defines dead virtual registers, and doesn't have oth...
Definition: Utils.cpp:222
#define N