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