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