LLVM 23.0.0git
SPIRVGlobalRegistry.cpp
Go to the documentation of this file.
1//===-- SPIRVGlobalRegistry.cpp - SPIR-V Global Registry --------*- 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 contains the implementation of the SPIRVGlobalRegistry class,
10// which is used to maintain rich type information required for SPIR-V even
11// after lowering from LLVM IR to GMIR. It can convert an llvm::Type into
12// an OpTypeXXX instruction, and map it to a virtual register. Also it builds
13// and supports consistency of constants and global variables.
14//
15//===----------------------------------------------------------------------===//
16
17#include "SPIRVGlobalRegistry.h"
18#include "SPIRV.h"
19#include "SPIRVBuiltins.h"
20#include "SPIRVSubtarget.h"
21#include "SPIRVUtils.h"
22#include "llvm/ADT/APInt.h"
23#include "llvm/IR/Constants.h"
25#include "llvm/IR/Function.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/IntrinsicsSPIRV.h"
29#include "llvm/IR/Type.h"
32#include <cassert>
33#include <functional>
34
35using namespace llvm;
36
37static bool allowEmitFakeUse(const Value *Arg) {
38 if (isSpvIntrinsic(Arg))
39 return false;
41 return false;
42 if (const auto *LI = dyn_cast<LoadInst>(Arg))
43 if (LI->getType()->isAggregateType())
44 return false;
45 return true;
46}
47
48static unsigned typeToAddressSpace(const Type *Ty) {
49 if (auto PType = dyn_cast<TypedPointerType>(Ty))
50 return PType->getAddressSpace();
51 if (auto PType = dyn_cast<PointerType>(Ty))
52 return PType->getAddressSpace();
53 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
54 ExtTy && isTypedPointerWrapper(ExtTy))
55 return ExtTy->getIntParameter(0);
56 reportFatalInternalError("Unable to convert LLVM type to SPIRVType");
57}
58
59static bool
60storageClassRequiresExplictLayout(SPIRV::StorageClass::StorageClass SC) {
61 switch (SC) {
62 case SPIRV::StorageClass::Uniform:
63 case SPIRV::StorageClass::PushConstant:
64 case SPIRV::StorageClass::StorageBuffer:
65 case SPIRV::StorageClass::PhysicalStorageBufferEXT:
66 return true;
67 case SPIRV::StorageClass::UniformConstant:
68 case SPIRV::StorageClass::Input:
69 case SPIRV::StorageClass::Output:
70 case SPIRV::StorageClass::Workgroup:
71 case SPIRV::StorageClass::CrossWorkgroup:
72 case SPIRV::StorageClass::Private:
73 case SPIRV::StorageClass::Function:
74 case SPIRV::StorageClass::Generic:
75 case SPIRV::StorageClass::AtomicCounter:
76 case SPIRV::StorageClass::Image:
77 case SPIRV::StorageClass::CallableDataNV:
78 case SPIRV::StorageClass::IncomingCallableDataNV:
79 case SPIRV::StorageClass::RayPayloadNV:
80 case SPIRV::StorageClass::HitAttributeNV:
81 case SPIRV::StorageClass::IncomingRayPayloadNV:
82 case SPIRV::StorageClass::ShaderRecordBufferNV:
83 case SPIRV::StorageClass::CodeSectionINTEL:
84 case SPIRV::StorageClass::DeviceOnlyINTEL:
85 case SPIRV::StorageClass::HostOnlyINTEL:
86 return false;
87 }
88 llvm_unreachable("Unknown SPIRV::StorageClass enum");
89}
90
92 : DL(DL), Bound(0), CurMF(nullptr) {}
93
97 const SPIRVInstrInfo &TII) {
99 assignSPIRVTypeToVReg(SpirvType, VReg, *CurMF);
100 return SpirvType;
101}
102
106 const SPIRVInstrInfo &TII) {
108 assignSPIRVTypeToVReg(SpirvType, VReg, *CurMF);
109 return SpirvType;
110}
111
113 SPIRVTypeInst BaseType, unsigned NumElements, Register VReg,
114 MachineInstr &I, const SPIRVInstrInfo &TII) {
115 SPIRVTypeInst SpirvType =
117 assignSPIRVTypeToVReg(SpirvType, VReg, *CurMF);
118 return SpirvType;
119}
120
122 const Type *Type, Register VReg, MachineIRBuilder &MIRBuilder,
123 SPIRV::AccessQualifier::AccessQualifier AccessQual, bool EmitIR) {
124 SPIRVTypeInst SpirvType =
125 getOrCreateSPIRVType(Type, MIRBuilder, AccessQual, EmitIR);
126 assignSPIRVTypeToVReg(SpirvType, VReg, MIRBuilder.getMF());
127 return SpirvType;
128}
129
131 Register VReg,
132 const MachineFunction &MF) {
133 VRegToTypeMap[&MF][VReg] = SpirvType;
134}
135
137 auto Res = MRI.createGenericVirtualRegister(LLT::scalar(64));
138 MRI.setRegClass(Res, &SPIRV::TYPERegClass);
139 return Res;
140}
141
143 return createTypeVReg(MIRBuilder.getMF().getRegInfo());
144}
145
146SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeBool(MachineIRBuilder &MIRBuilder) {
147 return createConstOrTypeAtFunctionEntry(
148 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
149 return MIRBuilder.buildInstr(SPIRV::OpTypeBool)
150 .addDef(createTypeVReg(MIRBuilder));
151 });
152}
153
154unsigned SPIRVGlobalRegistry::adjustOpTypeIntWidth(unsigned Width) const {
155 const SPIRVSubtarget &ST = cast<SPIRVSubtarget>(CurMF->getSubtarget());
156 if (ST.canUseExtension(
157 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers) ||
158 (Width == 4 && ST.canUseExtension(SPIRV::Extension::SPV_INTEL_int4)))
159 return Width;
160 if (Width <= 8)
161 return 8;
162 else if (Width <= 16)
163 return 16;
164 else if (Width <= 32)
165 return 32;
166 else if (Width <= 64)
167 return 64;
168 else if (Width <= 128)
169 return 128;
170 reportFatalUsageError("Unsupported Integer width!");
171}
172
173SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeInt(unsigned Width,
174 MachineIRBuilder &MIRBuilder,
175 bool IsSigned) {
176 Width = adjustOpTypeIntWidth(Width);
177 const SPIRVSubtarget &ST =
179 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
180 &MIRBuilder) {
181 if (Width == 4 && ST.canUseExtension(SPIRV::Extension::SPV_INTEL_int4)) {
182 MIRBuilder.buildInstr(SPIRV::OpExtension)
183 .addImm(SPIRV::Extension::SPV_INTEL_int4);
184 MIRBuilder.buildInstr(SPIRV::OpCapability)
185 .addImm(SPIRV::Capability::Int4TypeINTEL);
186 } else if ((!isPowerOf2_32(Width) || Width < 8) &&
187 ST.canUseExtension(
188 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers)) {
189 MIRBuilder.buildInstr(SPIRV::OpExtension)
190 .addImm(SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers);
191 MIRBuilder.buildInstr(SPIRV::OpCapability)
192 .addImm(SPIRV::Capability::ArbitraryPrecisionIntegersALTERA);
193 }
194 return MIRBuilder.buildInstr(SPIRV::OpTypeInt)
195 .addDef(createTypeVReg(MIRBuilder))
196 .addImm(Width)
197 .addImm(IsSigned ? 1 : 0);
198 });
199}
200
202SPIRVGlobalRegistry::getOpTypeFloat(uint32_t Width,
203 MachineIRBuilder &MIRBuilder) {
204 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
205 &MIRBuilder) {
206 return MIRBuilder.buildInstr(SPIRV::OpTypeFloat)
207 .addDef(createTypeVReg(MIRBuilder))
208 .addImm(Width);
209 });
210}
211
213SPIRVGlobalRegistry::getOpTypeFloat(uint32_t Width,
214 MachineIRBuilder &MIRBuilder,
215 SPIRV::FPEncoding::FPEncoding FPEncode) {
216 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
217 &MIRBuilder) {
218 return MIRBuilder.buildInstr(SPIRV::OpTypeFloat)
219 .addDef(createTypeVReg(MIRBuilder))
220 .addImm(Width)
221 .addImm(FPEncode);
222 });
223}
224
225SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeVoid(MachineIRBuilder &MIRBuilder) {
226 return createConstOrTypeAtFunctionEntry(
227 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
228 return MIRBuilder.buildInstr(SPIRV::OpTypeVoid)
229 .addDef(createTypeVReg(MIRBuilder));
230 });
231}
232
234 // Other maps that may hold MachineInstr*:
235 // - VRegToTypeMap: We cannot remove the definitions of `MI` from
236 // VRegToTypeMap because some calls to invalidateMachineInstr are replacing MI
237 // with another instruction defining the same register. We expect that if MI
238 // is a type instruction, and it is still referenced in VRegToTypeMap, then
239 // those registers are dead or the VRegToTypeMap is out-of-date. We do not
240 // expect passes to ask for the SPIR-V type of a dead register. If the
241 // VRegToTypeMap is out-of-date already, then there was an error before. We
242 // cannot add an assert to verify this because the VRegToTypeMap can be
243 // out-of-date.
244 // - FunctionToInstr & FunctionToInstrRev: At this point, we should not be
245 // deleting functions. No need to update.
246 // - AliasInstMDMap: Would require a linear search, and the Intel Alias
247 // instruction are not instructions instruction selection will be able to
248 // remove.
249
250 const SPIRVSubtarget &ST = MI->getMF()->getSubtarget<SPIRVSubtarget>();
251 [[maybe_unused]] const SPIRVInstrInfo *TII = ST.getInstrInfo();
252 assert(!TII->isAliasingInstr(*MI) &&
253 "Cannot invalidate aliasing instructions.");
254 assert(MI->getOpcode() != SPIRV::OpFunction &&
255 "Cannot invalidate OpFunction.");
256
257 if (MI->getOpcode() == SPIRV::OpFunctionCall) {
258 if (const auto *F = dyn_cast<Function>(MI->getOperand(2).getGlobal())) {
259 auto It = ForwardCalls.find(F);
260 if (It != ForwardCalls.end()) {
261 It->second.erase(MI);
262 if (It->second.empty())
263 ForwardCalls.erase(It);
264 }
265 }
266 }
267
268 const MachineFunction *MF = MI->getMF();
269 auto It = LastInsertedTypeMap.find(MF);
270 if (It != LastInsertedTypeMap.end() && It->second == MI)
271 LastInsertedTypeMap.erase(MF);
272 // remove from the duplicate tracker to avoid incorrect reuse
273 erase(MI);
274}
275
276const MachineInstr *SPIRVGlobalRegistry::createConstOrTypeAtFunctionEntry(
277 MachineIRBuilder &MIRBuilder,
278 std::function<MachineInstr *(MachineIRBuilder &)> Op) {
279 auto oldInsertPoint = MIRBuilder.getInsertPt();
280 MachineBasicBlock *OldMBB = &MIRBuilder.getMBB();
281 MachineBasicBlock *NewMBB = &*MIRBuilder.getMF().begin();
282
283 auto LastInsertedType = LastInsertedTypeMap.find(CurMF);
284 if (LastInsertedType != LastInsertedTypeMap.end()) {
285 auto It = LastInsertedType->second->getIterator();
286 // It might happen that this instruction was removed from the first MBB,
287 // hence the Parent's check.
289 if (It->getParent() != NewMBB)
290 InsertAt = oldInsertPoint->getParent() == NewMBB
291 ? oldInsertPoint
292 : getInsertPtValidEnd(NewMBB);
293 else if (It->getNextNode())
294 InsertAt = It->getNextNode()->getIterator();
295 else
296 InsertAt = getInsertPtValidEnd(NewMBB);
297 MIRBuilder.setInsertPt(*NewMBB, InsertAt);
298 } else {
299 MIRBuilder.setInsertPt(*NewMBB, NewMBB->begin());
300 auto Result = LastInsertedTypeMap.try_emplace(CurMF, nullptr);
301 assert(Result.second);
302 LastInsertedType = Result.first;
303 }
304
305 MachineInstr *ConstOrType = Op(MIRBuilder);
306 // We expect all users of this function to insert definitions at the insertion
307 // point set above that is always the first MBB.
308 assert(ConstOrType->getParent() == NewMBB);
309 LastInsertedType->second = ConstOrType;
310 // Advance past any continued instructions so that the next type/constant
311 // is inserted after the full group, preserving required adjacency.
312 while (auto *Next = LastInsertedType->second->getNextNode()) {
313 unsigned Opc = Next->getOpcode();
314 if (Opc == SPIRV::OpTypeStructContinuedINTEL ||
315 Opc == SPIRV::OpConstantCompositeContinuedINTEL ||
316 Opc == SPIRV::OpSpecConstantCompositeContinuedINTEL ||
317 Opc == SPIRV::OpCompositeConstructContinuedINTEL)
318 LastInsertedType->second = Next;
319 else
320 break;
321 }
322
323 MIRBuilder.setInsertPt(*OldMBB, oldInsertPoint);
324 return ConstOrType;
325}
326
328SPIRVGlobalRegistry::getOpTypeVector(uint32_t NumElems, SPIRVTypeInst ElemType,
329 MachineIRBuilder &MIRBuilder) {
330 auto EleOpc = ElemType->getOpcode();
331 assert(NumElems >= 2 && "SPIR-V OpTypeVector requires at least 2 components");
332
333 if (EleOpc == SPIRV::OpTypePointer) {
334 if (!cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget())
335 .canUseExtension(
336 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
337 const Function &F = MIRBuilder.getMF().getFunction();
338 F.getContext().diagnose(DiagnosticInfoUnsupported(
339 F,
340 "Vector of pointers requires SPV_INTEL_masked_gather_scatter "
341 "extension",
342 DebugLoc(), DS_Error));
343 }
344 } else {
345 assert((EleOpc == SPIRV::OpTypeInt || EleOpc == SPIRV::OpTypeFloat ||
346 EleOpc == SPIRV::OpTypeBool) &&
347 "Invalid vector element type");
348 }
349
350 return createConstOrTypeAtFunctionEntry(
351 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
352 return MIRBuilder.buildInstr(SPIRV::OpTypeVector)
353 .addDef(createTypeVReg(MIRBuilder))
354 .addUse(getSPIRVTypeID(ElemType))
355 .addImm(NumElems);
356 });
357}
358
360 SPIRVTypeInst SpvType,
361 const SPIRVInstrInfo &TII,
362 bool ZeroAsNull) {
363 LLVMContext &Ctx = CurMF->getFunction().getContext();
364 auto *const CF = ConstantFP::get(Ctx, Val);
365 const MachineInstr *MI = findMI(CF, CurMF);
366 if (MI && (MI->getOpcode() == SPIRV::OpConstantNull ||
367 MI->getOpcode() == SPIRV::OpConstantF))
368 return MI->getOperand(0).getReg();
369 return createConstFP(CF, I, SpvType, TII, ZeroAsNull);
370}
371
374 SPIRVTypeInst SpvType,
375 const SPIRVInstrInfo &TII,
376 bool ZeroAsNull) {
377 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
378 LLT LLTy = LLT::scalar(BitWidth);
379 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
380 CurMF->getRegInfo().setRegClass(Res, &SPIRV::fIDRegClass);
381 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
382
383 MachineInstr *DepMI =
384 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
385 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
386 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
387 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
389 // In OpenCL OpConstantNull - Scalar floating point: +0.0 (all bits 0)
390 if (CF->getValue().isPosZero() && ZeroAsNull) {
391 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
392 .addDef(Res)
393 .addUse(getSPIRVTypeID(SpvType));
394 } else {
395 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantF)
396 .addDef(Res)
397 .addUse(getSPIRVTypeID(SpvType));
400 MIB);
401 }
402 const auto &ST = CurMF->getSubtarget();
403 constrainSelectedInstRegOperands(*MIB, *ST.getInstrInfo(),
404 *ST.getRegisterInfo(),
405 *ST.getRegBankInfo());
406 return MIB;
407 });
408 add(CF, Const);
409 return Res;
410}
411
413 SPIRVTypeInst SpvType,
414 const SPIRVInstrInfo &TII,
415 bool ZeroAsNull) {
417 SpvType, TII, ZeroAsNull);
418}
419
422 SPIRVTypeInst SpvType,
423 const SPIRVInstrInfo &TII,
424 bool ZeroAsNull) {
425 auto *const CI = ConstantInt::get(
426 cast<IntegerType>(getTypeForSPIRVType(SpvType))->getContext(), Val);
427 const MachineInstr *MI = findMI(CI, CurMF);
428 if (MI && (MI->getOpcode() == SPIRV::OpConstantNull ||
429 MI->getOpcode() == SPIRV::OpConstantI))
430 return MI->getOperand(0).getReg();
431 return createConstInt(CI, I, SpvType, TII, ZeroAsNull);
432}
433
436 SPIRVTypeInst SpvType,
437 const SPIRVInstrInfo &TII,
438 bool ZeroAsNull) {
439 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
440 LLT LLTy = LLT::scalar(BitWidth);
441 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
442 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
444
445 MachineInstr *DepMI =
446 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
447 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
448 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
449 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
451 if (BitWidth == 1) {
452 MIB = MIRBuilder
453 .buildInstr(CI->isZero() ? SPIRV::OpConstantFalse
454 : SPIRV::OpConstantTrue)
455 .addDef(Res)
456 .addUse(getSPIRVTypeID(SpvType));
457 } else if (!CI->isZero() || !ZeroAsNull) {
458 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantI)
459 .addDef(Res)
460 .addUse(getSPIRVTypeID(SpvType));
461 addNumImm(CI->getValue(), MIB);
462 } else {
463 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
464 .addDef(Res)
465 .addUse(getSPIRVTypeID(SpvType));
466 }
467 const auto &ST = CurMF->getSubtarget();
468 constrainSelectedInstRegOperands(*MIB, *ST.getInstrInfo(),
469 *ST.getRegisterInfo(),
470 *ST.getRegBankInfo());
471 return MIB;
472 });
473 add(CI, Const);
474 return Res;
475}
476
478 MachineIRBuilder &MIRBuilder,
479 SPIRVTypeInst SpvType,
480 bool EmitIR, bool ZeroAsNull) {
481 assert(SpvType);
482 auto &MF = MIRBuilder.getMF();
484 // TODO: Avoid implicit trunc?
485 // See https://github.com/llvm/llvm-project/issues/112510.
486 auto *const CI = ConstantInt::get(const_cast<IntegerType *>(Ty), Val,
487 /*IsSigned=*/false, /*ImplicitTrunc=*/true);
488 Register Res = find(CI, &MF);
489 if (Res.isValid())
490 return Res;
491
492 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
493 LLT LLTy = LLT::scalar(BitWidth);
494 MachineRegisterInfo &MRI = MF.getRegInfo();
495 Res = MRI.createGenericVirtualRegister(LLTy);
496 MRI.setRegClass(Res, &SPIRV::iIDRegClass);
497 assignTypeToVReg(Ty, Res, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
498 EmitIR);
499
500 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
501 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
502 if (EmitIR)
503 return MIRBuilder.buildConstant(Res, *CI);
504 Register SpvTypeReg = getSPIRVTypeID(SpvType);
506 if (Val || !ZeroAsNull) {
507 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantI)
508 .addDef(Res)
509 .addUse(SpvTypeReg);
510 addNumImm(APInt(BitWidth, Val), MIB);
511 } else {
512 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
513 .addDef(Res)
514 .addUse(SpvTypeReg);
515 }
516 const auto &Subtarget = CurMF->getSubtarget();
517 constrainSelectedInstRegOperands(*MIB, *Subtarget.getInstrInfo(),
518 *Subtarget.getRegisterInfo(),
519 *Subtarget.getRegBankInfo());
520 return MIB;
521 });
522 add(CI, Const);
523 return Res;
524}
525
527 MachineIRBuilder &MIRBuilder,
528 SPIRVTypeInst SpvType) {
529 auto &MF = MIRBuilder.getMF();
530 LLVMContext &Ctx = MF.getFunction().getContext();
531 if (!SpvType)
532 SpvType = getOrCreateSPIRVType(Type::getFloatTy(Ctx), MIRBuilder,
533 SPIRV::AccessQualifier::ReadWrite, true);
534 auto *const CF = ConstantFP::get(Ctx, Val);
535 Register Res = find(CF, &MF);
536 if (Res.isValid())
537 return Res;
538
540 Res = MF.getRegInfo().createGenericVirtualRegister(LLTy);
541 MF.getRegInfo().setRegClass(Res, &SPIRV::fIDRegClass);
542 assignSPIRVTypeToVReg(SpvType, Res, MF);
543
544 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
545 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
547 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantF)
548 .addDef(Res)
549 .addUse(getSPIRVTypeID(SpvType));
550 addNumImm(CF->getValueAPF().bitcastToAPInt(), MIB);
551 return MIB;
552 });
553 add(CF, Const);
554 return Res;
555}
556
557Register SPIRVGlobalRegistry::getOrCreateBaseRegister(
558 Constant *Val, MachineInstr &I, SPIRVTypeInst SpvType,
559 const SPIRVInstrInfo &TII, unsigned BitWidth, bool ZeroAsNull) {
560 SPIRVTypeInst Type = SpvType;
561 if (SpvType->getOpcode() == SPIRV::OpTypeVector ||
562 SpvType->getOpcode() == SPIRV::OpTypeArray) {
563 auto EleTypeReg = SpvType->getOperand(1).getReg();
564 Type = getSPIRVTypeForVReg(EleTypeReg);
565 }
566 if (Type->getOpcode() == SPIRV::OpTypeFloat) {
568 return getOrCreateConstFP(cast<ConstantFP>(Val)->getValue(), I, SpvBaseType,
569 TII, ZeroAsNull);
570 }
571 assert(Type->getOpcode() == SPIRV::OpTypeInt);
572 SPIRVTypeInst SpvBaseType = getOrCreateSPIRVIntegerType(BitWidth, I, TII);
573 return getOrCreateConstInt(Val->getUniqueInteger(), I, SpvBaseType, TII,
574 ZeroAsNull);
575}
576
577Register SPIRVGlobalRegistry::getOrCreateCompositeOrNull(
578 Constant *Val, MachineInstr &I, SPIRVTypeInst SpvType,
579 const SPIRVInstrInfo &TII, Constant *CA, unsigned BitWidth,
580 unsigned ElemCnt, bool ZeroAsNull) {
581 if (Register R = find(CA, CurMF); R.isValid())
582 return R;
583
584 bool IsNull = Val->isNullValue() && ZeroAsNull;
585 Register ElemReg;
586 if (!IsNull)
587 ElemReg =
588 getOrCreateBaseRegister(Val, I, SpvType, TII, BitWidth, ZeroAsNull);
589
590 LLT LLTy = LLT::scalar(64);
591 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
592 CurMF->getRegInfo().setRegClass(Res, getRegClass(SpvType));
593 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
594
595 MachineInstr *DepMI =
596 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
597 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
598 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
599 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
600 MachineInstrBuilder MIB;
601 if (!IsNull) {
602 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantComposite)
603 .addDef(Res)
604 .addUse(getSPIRVTypeID(SpvType));
605 for (unsigned i = 0; i < ElemCnt; ++i)
606 MIB.addUse(ElemReg);
607 } else {
608 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
609 .addDef(Res)
610 .addUse(getSPIRVTypeID(SpvType));
611 }
612 const auto &Subtarget = CurMF->getSubtarget();
613 constrainSelectedInstRegOperands(*MIB, *Subtarget.getInstrInfo(),
614 *Subtarget.getRegisterInfo(),
615 *Subtarget.getRegBankInfo());
616 return MIB;
617 });
618 add(CA, NewMI);
619 return Res;
620}
621
624 SPIRVTypeInst SpvType,
625 const SPIRVInstrInfo &TII,
626 bool ZeroAsNull) {
628 I, SpvType, TII, ZeroAsNull);
629}
630
633 SPIRVTypeInst SpvType,
634 const SPIRVInstrInfo &TII,
635 bool ZeroAsNull) {
636 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
637 assert(LLVMTy->isVectorTy() &&
638 "Expected vector type for constant vector creation");
639 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
640 Type *LLVMBaseTy = LLVMVecTy->getElementType();
641 assert(LLVMBaseTy->isIntegerTy() &&
642 "Expected integer element type for APInt constant vector");
643 auto *ConstVal = cast<ConstantInt>(ConstantInt::get(LLVMBaseTy, Val));
644 auto *ConstVec =
645 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstVal);
646 unsigned BW = getScalarOrVectorBitWidth(SpvType);
647 return getOrCreateCompositeOrNull(ConstVal, I, SpvType, TII, ConstVec, BW,
648 SpvType->getOperand(2).getImm(),
649 ZeroAsNull);
650}
651
654 SPIRVTypeInst SpvType,
655 const SPIRVInstrInfo &TII,
656 bool ZeroAsNull) {
657 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
658 assert(LLVMTy->isVectorTy());
659 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
660 Type *LLVMBaseTy = LLVMVecTy->getElementType();
661 assert(LLVMBaseTy->isFloatingPointTy());
662 auto *ConstVal = ConstantFP::get(LLVMBaseTy, Val);
663 auto *ConstVec =
664 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstVal);
665 unsigned BW = getScalarOrVectorBitWidth(SpvType);
666 return getOrCreateCompositeOrNull(ConstVal, I, SpvType, TII, ConstVec, BW,
667 SpvType->getOperand(2).getImm(),
668 ZeroAsNull);
669}
670
672 uint64_t Val, size_t Num, MachineInstr &I, SPIRVTypeInst SpvType,
673 const SPIRVInstrInfo &TII) {
674 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
675 assert(LLVMTy->isArrayTy());
676 const ArrayType *LLVMArrTy = cast<ArrayType>(LLVMTy);
677 Type *LLVMBaseTy = LLVMArrTy->getElementType();
678 Constant *CI = ConstantInt::get(LLVMBaseTy, Val);
679 SPIRVTypeInst SpvBaseTy =
681 unsigned BW = getScalarOrVectorBitWidth(SpvBaseTy);
682 // The following is reasonably unique key that is better that [Val]. The naive
683 // alternative would be something along the lines of:
684 // SmallVector<Constant *> NumCI(Num, CI);
685 // Constant *UniqueKey =
686 // ConstantArray::get(const_cast<ArrayType*>(LLVMArrTy), NumCI);
687 // that would be a truly unique but dangerous key, because it could lead to
688 // the creation of constants of arbitrary length (that is, the parameter of
689 // memset) which were missing in the original module.
690 Type *I64Ty = Type::getInt64Ty(LLVMBaseTy->getContext());
692 {PoisonValue::get(const_cast<ArrayType *>(LLVMArrTy)),
693 ConstantInt::get(LLVMBaseTy, Val), ConstantInt::get(I64Ty, Num)});
694 return getOrCreateCompositeOrNull(CI, I, SpvType, TII, UniqueKey, BW,
695 LLVMArrTy->getNumElements());
696}
697
698Register SPIRVGlobalRegistry::getOrCreateIntCompositeOrNull(
699 uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType,
700 bool EmitIR, Constant *CA, unsigned BitWidth, unsigned ElemCnt) {
701 if (Register R = find(CA, CurMF); R.isValid())
702 return R;
703
704 Register ElemReg;
705 if (Val || EmitIR) {
706 SPIRVTypeInst SpvBaseType =
708 ElemReg = buildConstantInt(Val, MIRBuilder, SpvBaseType, EmitIR);
709 }
710 LLT LLTy = EmitIR ? LLT::fixed_vector(ElemCnt, BitWidth) : LLT::scalar(64);
711 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
712 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
713 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
714
715 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
716 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
717 if (EmitIR)
718 return MIRBuilder.buildSplatBuildVector(Res, ElemReg);
719
720 if (Val) {
721 auto MIB = MIRBuilder.buildInstr(SPIRV::OpConstantComposite)
722 .addDef(Res)
723 .addUse(getSPIRVTypeID(SpvType));
724 for (unsigned i = 0; i < ElemCnt; ++i)
725 MIB.addUse(ElemReg);
726 return MIB;
727 }
728
729 return MIRBuilder.buildInstr(SPIRV::OpConstantNull)
730 .addDef(Res)
731 .addUse(getSPIRVTypeID(SpvType));
732 });
733 add(CA, NewMI);
734 return Res;
735}
736
738 uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType,
739 bool EmitIR) {
740 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
741 assert(LLVMTy->isVectorTy());
742 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
743 Type *LLVMBaseTy = LLVMVecTy->getElementType();
744 const auto ConstInt = ConstantInt::get(LLVMBaseTy, Val);
745 auto ConstVec =
746 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstInt);
747 unsigned BW = getScalarOrVectorBitWidth(SpvType);
748 return getOrCreateIntCompositeOrNull(Val, MIRBuilder, SpvType, EmitIR,
749 ConstVec, BW,
750 SpvType->getOperand(2).getImm());
751}
752
755 SPIRVTypeInst SpvType) {
756 const Type *Ty = getTypeForSPIRVType(SpvType);
757 unsigned AddressSpace = typeToAddressSpace(Ty);
758 Type *ElemTy = ::getPointeeType(Ty);
759 assert(ElemTy);
762 Register Res = find(CP, CurMF);
763 if (Res.isValid())
764 return Res;
765
767 Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
768 CurMF->getRegInfo().setRegClass(Res, &SPIRV::pIDRegClass);
769 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
770
771 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
772 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
773 return MIRBuilder.buildInstr(SPIRV::OpConstantNull)
774 .addDef(Res)
775 .addUse(getSPIRVTypeID(SpvType));
776 });
777 add(CP, NewMI);
778 return Res;
779}
780
783 unsigned Param, unsigned FilerMode,
784 MachineIRBuilder &MIRBuilder) {
785 auto Sampler =
786 ResReg.isValid()
787 ? ResReg
788 : MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
789 SPIRVTypeInst TypeSampler = getOrCreateOpTypeSampler(MIRBuilder);
790 Register TypeSamplerReg = getSPIRVTypeID(TypeSampler);
791 // We cannot use createOpType() logic here, because of the
792 // GlobalISel/IRTranslator.cpp check for a tail call that expects that
793 // MIRBuilder.getInsertPt() has a previous instruction. If this constant is
794 // inserted as a result of "__translate_sampler_initializer()" this would
795 // break this IRTranslator assumption.
796 MIRBuilder.buildInstr(SPIRV::OpConstantSampler)
798 .addUse(TypeSamplerReg)
800 .addImm(Param)
801 .addImm(FilerMode);
802 return Sampler;
803}
804
807 const GlobalValue *GV, SPIRV::StorageClass::StorageClass Storage,
808 const MachineInstr *Init, bool IsConst,
809 const std::optional<SPIRV::LinkageType::LinkageType> &LinkageType,
810 MachineIRBuilder &MIRBuilder, bool IsInstSelector) {
811 const GlobalVariable *GVar = nullptr;
812 if (GV) {
814 } else {
815 // If GV is not passed explicitly, use the name to find or construct
816 // the global variable.
817 Module *M = MIRBuilder.getMF().getFunction().getParent();
818 GVar = M->getGlobalVariable(Name);
819 if (GVar == nullptr) {
820 const Type *Ty = getTypeForSPIRVType(BaseType); // TODO: check type.
821 // Module takes ownership of the global var.
822 GVar = new GlobalVariable(*M, const_cast<Type *>(Ty), false,
824 Twine(Name));
825 }
826 GV = GVar;
827 }
828
829 const MachineFunction *MF = &MIRBuilder.getMF();
830 Register Reg = find(GVar, MF);
831 if (Reg.isValid()) {
832 if (Reg != ResVReg)
833 MIRBuilder.buildCopy(ResVReg, Reg);
834 return ResVReg;
835 }
836
837 // Emit the OpVariable into the entry block to ensure the def dominates
838 // all uses across all MBBs.
839 MachineBasicBlock &EntryBB = MIRBuilder.getMF().front();
840 MachineIRBuilder GVBuilder(MIRBuilder.getState());
841 if (&GVBuilder.getMBB() != &EntryBB)
842 GVBuilder.setInsertPt(EntryBB, EntryBB.getFirstTerminator());
843
844 auto MIB = GVBuilder.buildInstr(SPIRV::OpVariable)
845 .addDef(ResVReg)
847 .addImm(static_cast<uint32_t>(Storage));
848 if (Init)
849 MIB.addUse(Init->getOperand(0).getReg());
850 // ISel may introduce a new register on this step, so we need to add it to
851 // DT and correct its type avoiding fails on the next stage.
852 if (IsInstSelector) {
853 const auto &Subtarget = CurMF->getSubtarget();
854 constrainSelectedInstRegOperands(*MIB, *Subtarget.getInstrInfo(),
855 *Subtarget.getRegisterInfo(),
856 *Subtarget.getRegBankInfo());
857 }
858 add(GVar, MIB);
859
860 Reg = MIB->getOperand(0).getReg();
861 addGlobalObject(GVar, MF, Reg);
862
863 // Set to Reg the same type as ResVReg has.
864 auto MRI = MIRBuilder.getMRI();
865 if (Reg != ResVReg) {
866 LLT RegLLTy =
867 LLT::pointer(MRI->getType(ResVReg).getAddressSpace(), getPointerSize());
868 MRI->setType(Reg, RegLLTy);
869 assignSPIRVTypeToVReg(BaseType, Reg, MIRBuilder.getMF());
870 } else {
871 // Our knowledge about the type may be updated.
872 // If that's the case, we need to update a type
873 // associated with the register.
874 SPIRVTypeInst DefType = getSPIRVTypeForVReg(ResVReg);
875 if (!DefType || DefType != SPIRVTypeInst(BaseType))
876 assignSPIRVTypeToVReg(BaseType, Reg, MIRBuilder.getMF());
877 }
878
879 // If it's a global variable with name, output OpName for it.
880 if (GVar && GVar->hasName())
881 buildOpName(Reg, GVar->getName(), MIRBuilder);
882
883 // Output decorations for the GV.
884 // TODO: maybe move to GenerateDecorations pass.
885 const SPIRVSubtarget &ST =
887 if (IsConst && !ST.isShader())
888 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::Constant, {});
889
890 if (GVar && GVar->getAlign().valueOrOne().value() != 1 && !ST.isShader()) {
891 unsigned Alignment = (unsigned)GVar->getAlign().valueOrOne().value();
892 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::Alignment, {Alignment});
893 }
894
895 if (LinkageType)
896 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
897 {static_cast<uint32_t>(*LinkageType)}, Name);
898
899 SPIRV::BuiltIn::BuiltIn BuiltInId;
900 if (getSpirvBuiltInIdByName(Name, BuiltInId))
901 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::BuiltIn,
902 {static_cast<uint32_t>(BuiltInId)});
903
904 // If it's a global variable with "spirv.Decorations" metadata node
905 // recognize it as a SPIR-V friendly LLVM IR and parse "spirv.Decorations"
906 // arguments.
907 MDNode *GVarMD = nullptr;
908 if (GVar && (GVarMD = GVar->getMetadata("spirv.Decorations")) != nullptr)
909 buildOpSpirvDecorations(Reg, MIRBuilder, GVarMD, ST);
910
911 return Reg;
912}
913
914// Returns a name based on the Type. Notes that this does not look at
915// decorations, and will return the same string for two types that are the same
916// except for decorations.
918 SPIRVTypeInst VarType, uint32_t Set, uint32_t Binding, StringRef Name,
919 MachineIRBuilder &MIRBuilder) {
920 Register VarReg =
921 MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
922
923 buildGlobalVariable(VarReg, VarType, Name, nullptr,
924 getPointerStorageClass(VarType), nullptr, false,
925 std::nullopt, MIRBuilder, false);
926
927 buildOpDecorate(VarReg, MIRBuilder, SPIRV::Decoration::DescriptorSet, {Set});
928 buildOpDecorate(VarReg, MIRBuilder, SPIRV::Decoration::Binding, {Binding});
929 return VarReg;
930}
931
932// TODO: Double check the calls to getOpTypeArray to make sure that `ElemType`
933// is explicitly laid out when required.
934SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeArray(uint32_t NumElems,
935 SPIRVTypeInst ElemType,
936 MachineIRBuilder &MIRBuilder,
937 bool ExplicitLayoutRequired,
938 bool EmitIR) {
939 assert((ElemType->getOpcode() != SPIRV::OpTypeVoid) &&
940 "Invalid array element type");
941 SPIRVTypeInst SpvTypeInt32 = getOrCreateSPIRVIntegerType(32, MIRBuilder);
942 SPIRVTypeInst ArrayType = nullptr;
943 const SPIRVSubtarget &ST =
945 if (NumElems != 0) {
946 Register NumElementsVReg =
947 buildConstantInt(NumElems, MIRBuilder, SpvTypeInt32, EmitIR);
948 ArrayType = createConstOrTypeAtFunctionEntry(
949 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
950 return MIRBuilder.buildInstr(SPIRV::OpTypeArray)
951 .addDef(createTypeVReg(MIRBuilder))
952 .addUse(getSPIRVTypeID(ElemType))
953 .addUse(NumElementsVReg);
954 });
955 } else if (ST.getTargetTriple().getVendor() == Triple::VendorType::AMD) {
956 // We set the array size to the token UINT64_MAX value, which is generally
957 // illegal (the maximum legal size is 61-bits) for the foreseeable future.
958 SPIRVTypeInst SpvTypeInt64 = getOrCreateSPIRVIntegerType(64, MIRBuilder);
959 Register NumElementsVReg =
960 buildConstantInt(UINT64_MAX, MIRBuilder, SpvTypeInt64, EmitIR);
961 ArrayType = createConstOrTypeAtFunctionEntry(
962 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
963 return MIRBuilder.buildInstr(SPIRV::OpTypeArray)
964 .addDef(createTypeVReg(MIRBuilder))
965 .addUse(getSPIRVTypeID(ElemType))
966 .addUse(NumElementsVReg);
967 });
968 } else {
969 if (!ST.isShader()) {
971 "Runtime arrays are not allowed in non-shader "
972 "SPIR-V modules");
973 return nullptr;
974 }
975 ArrayType = createConstOrTypeAtFunctionEntry(
976 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
977 return MIRBuilder.buildInstr(SPIRV::OpTypeRuntimeArray)
978 .addDef(createTypeVReg(MIRBuilder))
979 .addUse(getSPIRVTypeID(ElemType));
980 });
981 }
982
983 if (ExplicitLayoutRequired && !isResourceType(ElemType)) {
984 Type *ET = const_cast<Type *>(getTypeForSPIRVType(ElemType));
985 addArrayStrideDecorations(ArrayType->defs().begin()->getReg(), ET,
986 MIRBuilder);
987 }
988
989 return ArrayType;
990}
991
993SPIRVGlobalRegistry::getOpTypeOpaque(const StructType *Ty,
994 MachineIRBuilder &MIRBuilder) {
995 assert(Ty->hasName());
996 const StringRef Name = Ty->hasName() ? Ty->getName() : "";
997 Register ResVReg = createTypeVReg(MIRBuilder);
998 return createConstOrTypeAtFunctionEntry(
999 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1000 auto MIB = MIRBuilder.buildInstr(SPIRV::OpTypeOpaque).addDef(ResVReg);
1001 addStringImm(Name, MIB);
1002 buildOpName(ResVReg, Name, MIRBuilder);
1003 return MIB;
1004 });
1005}
1006
1007SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeStruct(
1008 const StructType *Ty, MachineIRBuilder &MIRBuilder,
1009 SPIRV::AccessQualifier::AccessQualifier AccQual,
1010 StructOffsetDecorator Decorator, bool EmitIR) {
1011 Type *OriginalElementType = nullptr;
1012 uint64_t TotalSize = 0;
1013 if (matchPeeledArrayPattern(Ty, OriginalElementType, TotalSize)) {
1014 SPIRVTypeInst ElementSPIRVType = findSPIRVType(
1015 OriginalElementType, MIRBuilder, AccQual,
1016 /* ExplicitLayoutRequired= */ Decorator != nullptr, EmitIR);
1017 return getOpTypeArray(TotalSize, ElementSPIRVType, MIRBuilder,
1018 /*ExplicitLayoutRequired=*/Decorator != nullptr,
1019 EmitIR);
1020 }
1021
1022 const SPIRVSubtarget &ST =
1023 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
1024 SmallVector<Register, 4> FieldTypes;
1025 constexpr unsigned MaxWordCount = UINT16_MAX;
1026 const size_t NumElements = Ty->getNumElements();
1027
1028 size_t MaxNumElements = MaxWordCount - 2;
1029 size_t SPIRVStructNumElements = NumElements;
1030 if (NumElements > MaxNumElements) {
1031 // Do adjustments for continued instructions.
1032 SPIRVStructNumElements = MaxNumElements;
1033 MaxNumElements = MaxWordCount - 1;
1034 }
1035
1036 for (const auto &Elem : Ty->elements()) {
1037 SPIRVTypeInst ElemTy = findSPIRVType(
1038 toTypedPointer(Elem), MIRBuilder, AccQual,
1039 /* ExplicitLayoutRequired= */ Decorator != nullptr, EmitIR);
1040 assert(ElemTy && ElemTy->getOpcode() != SPIRV::OpTypeVoid &&
1041 "Invalid struct element type");
1042 FieldTypes.push_back(getSPIRVTypeID(ElemTy));
1043 }
1044 Register ResVReg = createTypeVReg(MIRBuilder);
1045 if (Ty->hasName())
1046 buildOpName(ResVReg, Ty->getName(), MIRBuilder);
1047 if (Ty->isPacked() && !ST.isShader())
1048 buildOpDecorate(ResVReg, MIRBuilder, SPIRV::Decoration::CPacked, {});
1049
1050 SPIRVTypeInst SPVType = createConstOrTypeAtFunctionEntry(
1051 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1052 auto MIBStruct =
1053 MIRBuilder.buildInstr(SPIRV::OpTypeStruct).addDef(ResVReg);
1054 for (size_t I = 0; I < SPIRVStructNumElements; ++I)
1055 MIBStruct.addUse(FieldTypes[I]);
1056 for (size_t I = SPIRVStructNumElements; I < NumElements;
1057 I += MaxNumElements) {
1058 auto MIBCont =
1059 MIRBuilder.buildInstr(SPIRV::OpTypeStructContinuedINTEL);
1060 for (size_t J = I; J < std::min(I + MaxNumElements, NumElements); ++J)
1061 MIBCont.addUse(FieldTypes[J]);
1062 }
1063 return MIBStruct;
1064 });
1065
1066 if (Decorator)
1067 Decorator(SPVType->defs().begin()->getReg());
1068
1069 return SPVType;
1070}
1071
1072SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateSpecialType(
1073 const Type *Ty, MachineIRBuilder &MIRBuilder,
1074 SPIRV::AccessQualifier::AccessQualifier AccQual) {
1075 assert(isSpecialOpaqueType(Ty) && "Not a special opaque builtin type");
1076 return SPIRV::lowerBuiltinType(Ty, AccQual, MIRBuilder, this);
1077}
1078
1079SPIRVTypeInst SPIRVGlobalRegistry::getOpTypePointer(
1080 SPIRV::StorageClass::StorageClass SC, SPIRVTypeInst ElemType,
1081 MachineIRBuilder &MIRBuilder, Register Reg) {
1082 if (!Reg.isValid())
1083 Reg = createTypeVReg(MIRBuilder);
1084
1085 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
1086 &MIRBuilder) {
1087 return MIRBuilder.buildInstr(SPIRV::OpTypePointer)
1088 .addDef(Reg)
1089 .addImm(static_cast<uint32_t>(SC))
1090 .addUse(getSPIRVTypeID(ElemType));
1091 });
1092}
1093
1094SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeForwardPointer(
1095 SPIRV::StorageClass::StorageClass SC, MachineIRBuilder &MIRBuilder) {
1096 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
1097 &MIRBuilder) {
1098 return MIRBuilder.buildInstr(SPIRV::OpTypeForwardPointer)
1099 .addUse(createTypeVReg(MIRBuilder))
1100 .addImm(static_cast<uint32_t>(SC));
1101 });
1102}
1103
1104SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeFunction(
1105 const FunctionType *Ty, SPIRVTypeInst RetType,
1106 const SmallVectorImpl<SPIRVTypeInst> &ArgTypes,
1107 MachineIRBuilder &MIRBuilder) {
1108 const SPIRVSubtarget *ST =
1109 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
1110 if (Ty->isVarArg() && ST->isShader()) {
1111 Function &Fn = MIRBuilder.getMF().getFunction();
1112 Ty->getContext().diagnose(DiagnosticInfoUnsupported(
1113 Fn, "SPIR-V shaders do not support variadic functions",
1114 MIRBuilder.getDebugLoc()));
1115 }
1116 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
1117 &MIRBuilder) {
1118 auto MIB = MIRBuilder.buildInstr(SPIRV::OpTypeFunction)
1119 .addDef(createTypeVReg(MIRBuilder))
1120 .addUse(getSPIRVTypeID(RetType));
1121 for (auto &ArgType : ArgTypes)
1122 MIB.addUse(getSPIRVTypeID(ArgType));
1123 return MIB;
1124 });
1125}
1126
1128 const Type *Ty, SPIRVTypeInst RetType,
1129 const SmallVectorImpl<SPIRVTypeInst> &ArgTypes,
1130 MachineIRBuilder &MIRBuilder) {
1131 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
1132 return MI;
1133 const MachineInstr *NewMI =
1134 getOpTypeFunction(cast<FunctionType>(Ty), RetType, ArgTypes, MIRBuilder);
1135 add(Ty, false, NewMI);
1136 return finishCreatingSPIRVType(Ty, NewMI);
1137}
1138
1139SPIRVTypeInst SPIRVGlobalRegistry::findSPIRVType(
1140 const Type *Ty, MachineIRBuilder &MIRBuilder,
1141 SPIRV::AccessQualifier::AccessQualifier AccQual,
1142 bool ExplicitLayoutRequired, bool EmitIR) {
1143 // Treat <1 x T> as T.
1144 if (auto *FVT = dyn_cast<FixedVectorType>(Ty);
1145 FVT && FVT->getNumElements() == 1)
1146 return findSPIRVType(FVT->getElementType(), MIRBuilder, AccQual,
1147 ExplicitLayoutRequired, EmitIR);
1148 Ty = adjustIntTypeByWidth(Ty);
1149 // TODO: findMI needs to know if a layout is required.
1150 if (const MachineInstr *MI =
1151 findMI(Ty, ExplicitLayoutRequired, &MIRBuilder.getMF()))
1152 return MI;
1153 if (auto It = ForwardPointerTypes.find(Ty); It != ForwardPointerTypes.end())
1154 return It->second;
1155 return restOfCreateSPIRVType(Ty, MIRBuilder, AccQual, ExplicitLayoutRequired,
1156 EmitIR);
1157}
1158
1160 assert(SpirvType && "Attempting to get type id for nullptr type.");
1161 if (SpirvType->getOpcode() == SPIRV::OpTypeForwardPointer ||
1162 SpirvType->getOpcode() == SPIRV::OpTypeStructContinuedINTEL)
1163 return SpirvType->uses().begin()->getReg();
1164 return SpirvType->defs().begin()->getReg();
1165}
1166
1167// We need to use a new LLVM integer type if there is a mismatch between
1168// number of bits in LLVM and SPIRV integer types to let DuplicateTracker
1169// ensure uniqueness of a SPIRV type by the corresponding LLVM type. Without
1170// such an adjustment SPIRVGlobalRegistry::getOpTypeInt() could create the
1171// same "OpTypeInt 8" type for a series of LLVM integer types with number of
1172// bits less than 8. This would lead to duplicate type definitions
1173// eventually due to the method that DuplicateTracker utilizes to reason
1174// about uniqueness of type records.
1175const Type *SPIRVGlobalRegistry::adjustIntTypeByWidth(const Type *Ty) const {
1176 if (auto IType = dyn_cast<IntegerType>(Ty)) {
1177 unsigned SrcBitWidth = IType->getBitWidth();
1178 if (SrcBitWidth > 1) {
1179 unsigned BitWidth = adjustOpTypeIntWidth(SrcBitWidth);
1180 // Maybe change source LLVM type to keep DuplicateTracker consistent.
1181 if (SrcBitWidth != BitWidth)
1182 Ty = IntegerType::get(Ty->getContext(), BitWidth);
1183 }
1184 }
1185 return Ty;
1186}
1187
1188SPIRVTypeInst SPIRVGlobalRegistry::createSPIRVType(
1189 const Type *Ty, MachineIRBuilder &MIRBuilder,
1190 SPIRV::AccessQualifier::AccessQualifier AccQual,
1191 bool ExplicitLayoutRequired, bool EmitIR) {
1192 if (isSpecialOpaqueType(Ty))
1193 return getOrCreateSpecialType(Ty, MIRBuilder, AccQual);
1194
1195 if (const MachineInstr *MI =
1196 findMI(Ty, ExplicitLayoutRequired, &MIRBuilder.getMF()))
1197 return MI;
1198
1199 if (auto IType = dyn_cast<IntegerType>(Ty)) {
1200 const unsigned Width = IType->getBitWidth();
1201 return Width == 1 ? getOpTypeBool(MIRBuilder)
1202 : getOpTypeInt(Width, MIRBuilder, false);
1203 }
1204 if (Ty->isFloatingPointTy()) {
1205 if (Ty->isBFloatTy()) {
1206 return getOpTypeFloat(Ty->getPrimitiveSizeInBits(), MIRBuilder,
1207 SPIRV::FPEncoding::BFloat16KHR);
1208 } else {
1209 return getOpTypeFloat(Ty->getPrimitiveSizeInBits(), MIRBuilder);
1210 }
1211 }
1212 if (Ty->isVoidTy())
1213 return getOpTypeVoid(MIRBuilder);
1214 if (Ty->isVectorTy()) {
1215 SPIRVTypeInst El =
1216 findSPIRVType(cast<FixedVectorType>(Ty)->getElementType(), MIRBuilder,
1217 AccQual, ExplicitLayoutRequired, EmitIR);
1218 return getOpTypeVector(cast<FixedVectorType>(Ty)->getNumElements(), El,
1219 MIRBuilder);
1220 }
1221 if (Ty->isArrayTy()) {
1222 SPIRVTypeInst El = findSPIRVType(Ty->getArrayElementType(), MIRBuilder,
1223 AccQual, ExplicitLayoutRequired, EmitIR);
1224 return getOpTypeArray(Ty->getArrayNumElements(), El, MIRBuilder,
1225 ExplicitLayoutRequired, EmitIR);
1226 }
1227 if (auto SType = dyn_cast<StructType>(Ty)) {
1228 if (SType->isOpaque())
1229 return getOpTypeOpaque(SType, MIRBuilder);
1230
1231 StructOffsetDecorator Decorator = nullptr;
1232 if (ExplicitLayoutRequired) {
1233 Decorator = [&MIRBuilder, SType, this](Register Reg) {
1234 addStructOffsetDecorations(Reg, const_cast<StructType *>(SType),
1235 MIRBuilder);
1236 };
1237 }
1238 return getOpTypeStruct(SType, MIRBuilder, AccQual, std::move(Decorator),
1239 EmitIR);
1240 }
1241 if (auto FType = dyn_cast<FunctionType>(Ty)) {
1242 SPIRVTypeInst RetTy =
1243 findSPIRVType(FType->getReturnType(), MIRBuilder, AccQual,
1244 ExplicitLayoutRequired, EmitIR);
1246 for (const auto &ParamTy : FType->params())
1247 ParamTypes.push_back(findSPIRVType(ParamTy, MIRBuilder, AccQual,
1248 ExplicitLayoutRequired, EmitIR));
1249 return getOpTypeFunction(FType, RetTy, ParamTypes, MIRBuilder);
1250 }
1251
1252 unsigned AddrSpace = typeToAddressSpace(Ty);
1253
1254 // Get access to information about available extensions
1255 const SPIRVSubtarget *ST =
1256 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
1257 auto SC = addressSpaceToStorageClass(AddrSpace, *ST);
1258
1259 SPIRVTypeInst SpvElementType = nullptr;
1260 Type *ElemTy = ::getPointeeType(Ty);
1261 if (ElemTy && isa<FunctionType>(ElemTy) &&
1262 !ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
1263 ElemTy = nullptr;
1264 if (ElemTy)
1265 SpvElementType = getOrCreateSPIRVType(ElemTy, MIRBuilder, AccQual, EmitIR);
1266 else
1267 SpvElementType = getOrCreateSPIRVIntegerType(8, MIRBuilder);
1268
1269 if (!ElemTy) {
1270 ElemTy = Type::getInt8Ty(MIRBuilder.getContext());
1271 }
1272
1273 // If we have forward pointer associated with this type, use its register
1274 // operand to create OpTypePointer.
1275 if (auto It = ForwardPointerTypes.find(Ty); It != ForwardPointerTypes.end()) {
1276 Register Reg = getSPIRVTypeID(It->second);
1277 // TODO: what does getOpTypePointer do?
1278 return getOpTypePointer(SC, SpvElementType, MIRBuilder, Reg);
1279 }
1280
1281 return getOrCreateSPIRVPointerType(ElemTy, MIRBuilder, SC);
1282}
1283
1284SPIRVTypeInst SPIRVGlobalRegistry::restOfCreateSPIRVType(
1285 const Type *Ty, MachineIRBuilder &MIRBuilder,
1286 SPIRV::AccessQualifier::AccessQualifier AccessQual,
1287 bool ExplicitLayoutRequired, bool EmitIR) {
1288 // TODO: Could this create a problem if one requires an explicit layout, and
1289 // the next time it does not?
1290 if (TypesInProcessing.count(Ty) && !isPointerTyOrWrapper(Ty))
1291 return nullptr;
1292 TypesInProcessing.insert(Ty);
1293 SPIRVTypeInst SpirvType = createSPIRVType(Ty, MIRBuilder, AccessQual,
1294 ExplicitLayoutRequired, EmitIR);
1295 TypesInProcessing.erase(Ty);
1296 VRegToTypeMap[&MIRBuilder.getMF()][getSPIRVTypeID(SpirvType)] = SpirvType;
1297
1298 // TODO: We could end up with two SPIR-V types pointing to the same llvm type.
1299 // Is that a problem?
1300 SPIRVToLLVMType[SpirvType] = unifyPtrType(Ty);
1301
1302 if (SpirvType->getOpcode() == SPIRV::OpTypeForwardPointer ||
1303 findMI(Ty, false, &MIRBuilder.getMF()) || isSpecialOpaqueType(Ty))
1304 return SpirvType;
1305
1306 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
1307 ExtTy && isTypedPointerWrapper(ExtTy))
1308 add(ExtTy->getTypeParameter(0), ExtTy->getIntParameter(0), SpirvType);
1309 else if (!isPointerTy(Ty))
1310 add(Ty, ExplicitLayoutRequired, SpirvType);
1311 else if (isTypedPointerTy(Ty))
1312 add(cast<TypedPointerType>(Ty)->getElementType(),
1313 getPointerAddressSpace(Ty), SpirvType);
1314 else
1316 getPointerAddressSpace(Ty), SpirvType);
1317 return SpirvType;
1318}
1319
1322 const MachineFunction *MF) const {
1323 auto t = VRegToTypeMap.find(MF ? MF : CurMF);
1324 if (t != VRegToTypeMap.end()) {
1325 auto tt = t->second.find(VReg);
1326 if (tt != t->second.end())
1327 return tt->second;
1328 }
1329 return nullptr;
1330}
1331
1333 MachineFunction *MF) {
1334 if (!MF)
1335 MF = CurMF;
1336 MachineInstr *Instr = getVRegDef(MF->getRegInfo(), VReg);
1337 return getSPIRVTypeForVReg(Instr->getOperand(1).getReg(), MF);
1338}
1339
1341 const Type *Ty, MachineIRBuilder &MIRBuilder,
1342 SPIRV::AccessQualifier::AccessQualifier AccessQual,
1343 bool ExplicitLayoutRequired, bool EmitIR) {
1344 // SPIR-V doesn't support single-element vectors. Treat <1 x T> as T.
1345 if (auto *FVT = dyn_cast<FixedVectorType>(Ty);
1346 FVT && FVT->getNumElements() == 1)
1347 return getOrCreateSPIRVType(FVT->getElementType(), MIRBuilder, AccessQual,
1348 ExplicitLayoutRequired, EmitIR);
1349 const MachineFunction *MF = &MIRBuilder.getMF();
1350 Register Reg;
1351 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
1352 ExtTy && isTypedPointerWrapper(ExtTy))
1353 Reg = find(ExtTy->getTypeParameter(0), ExtTy->getIntParameter(0), MF);
1354 else if (!isPointerTy(Ty))
1355 Reg = find(Ty = adjustIntTypeByWidth(Ty), ExplicitLayoutRequired, MF);
1356 else if (isTypedPointerTy(Ty))
1357 Reg = find(cast<TypedPointerType>(Ty)->getElementType(),
1358 getPointerAddressSpace(Ty), MF);
1359 else
1360 Reg = find(Type::getInt8Ty(MIRBuilder.getMF().getFunction().getContext()),
1361 getPointerAddressSpace(Ty), MF);
1362 if (Reg.isValid() && !isSpecialOpaqueType(Ty))
1363 return getSPIRVTypeForVReg(Reg);
1364
1365 TypesInProcessing.clear();
1366 SPIRVTypeInst STy = restOfCreateSPIRVType(Ty, MIRBuilder, AccessQual,
1367 ExplicitLayoutRequired, EmitIR);
1368 // Create normal pointer types for the corresponding OpTypeForwardPointers.
1369 for (auto &CU : ForwardPointerTypes) {
1370 // Pointer type themselves do not require an explicit layout. The types
1371 // they pointer to might, but that is taken care of when creating the type.
1372 bool PtrNeedsLayout = false;
1373 const Type *Ty2 = CU.first;
1374 SPIRVTypeInst STy2 = CU.second;
1375 if ((Reg = find(Ty2, PtrNeedsLayout, MF)).isValid())
1376 STy2 = getSPIRVTypeForVReg(Reg);
1377 else
1378 STy2 = restOfCreateSPIRVType(Ty2, MIRBuilder, AccessQual, PtrNeedsLayout,
1379 EmitIR);
1380 if (Ty == Ty2)
1381 STy = STy2;
1382 }
1383 ForwardPointerTypes.clear();
1384 return STy;
1385}
1386
1388 unsigned TypeOpcode) const {
1390 assert(Type && "isScalarOfType VReg has no type assigned");
1391 return Type->getOpcode() == TypeOpcode;
1392}
1393
1395 unsigned TypeOpcode) const {
1397 assert(Type && "isScalarOrVectorOfType VReg has no type assigned");
1398 if (Type->getOpcode() == TypeOpcode)
1399 return true;
1400 if (Type->getOpcode() == SPIRV::OpTypeVector) {
1401 Register ScalarTypeVReg = Type->getOperand(1).getReg();
1402 SPIRVTypeInst ScalarType = getSPIRVTypeForVReg(ScalarTypeVReg);
1403 return ScalarType->getOpcode() == TypeOpcode;
1404 }
1405 return false;
1406}
1407
1409 switch (Type->getOpcode()) {
1410 case SPIRV::OpTypeImage:
1411 case SPIRV::OpTypeSampler:
1412 case SPIRV::OpTypeSampledImage:
1413 return true;
1414 case SPIRV::OpTypeStruct:
1415 return hasBlockDecoration(Type);
1416 default:
1417 return false;
1418 }
1419 return false;
1420}
1421unsigned
1425
1426unsigned
1428 if (!Type)
1429 return 0;
1430 return Type->getOpcode() == SPIRV::OpTypeVector
1431 ? static_cast<unsigned>(Type->getOperand(2).getImm())
1432 : 1;
1433}
1434
1437 if (!Type)
1438 return nullptr;
1439 Register ScalarReg = Type->getOpcode() == SPIRV::OpTypeVector
1440 ? Type->getOperand(1).getReg()
1441 : Type->getOperand(0).getReg();
1442 SPIRVTypeInst ScalarType = getSPIRVTypeForVReg(ScalarReg);
1443 assert(isScalarOrVectorOfType(Type->getOperand(0).getReg(),
1444 ScalarType->getOpcode()));
1445 return ScalarType;
1446}
1447
1448unsigned
1450 assert(Type && "Invalid Type pointer");
1451 if (Type->getOpcode() == SPIRV::OpTypeVector) {
1452 auto EleTypeReg = Type->getOperand(1).getReg();
1453 Type = getSPIRVTypeForVReg(EleTypeReg);
1454 }
1455 if (Type->getOpcode() == SPIRV::OpTypeInt ||
1456 Type->getOpcode() == SPIRV::OpTypeFloat)
1457 return Type->getOperand(1).getImm();
1458 if (Type->getOpcode() == SPIRV::OpTypeBool)
1459 return 1;
1460 llvm_unreachable("Attempting to get bit width of non-integer/float type.");
1461}
1462
1464 SPIRVTypeInst Type) const {
1465 assert(Type && "Invalid Type pointer");
1466 unsigned NumElements = 1;
1467 if (Type->getOpcode() == SPIRV::OpTypeVector) {
1468 NumElements = static_cast<unsigned>(Type->getOperand(2).getImm());
1469 Type = getSPIRVTypeForVReg(Type->getOperand(1).getReg());
1470 }
1471 return Type->getOpcode() == SPIRV::OpTypeInt ||
1472 Type->getOpcode() == SPIRV::OpTypeFloat
1473 ? NumElements * Type->getOperand(1).getImm()
1474 : 0;
1475}
1476
1479 if (Type && Type->getOpcode() == SPIRV::OpTypeVector)
1480 Type = getSPIRVTypeForVReg(Type->getOperand(1).getReg());
1481 return Type && Type->getOpcode() == SPIRV::OpTypeInt ? Type : nullptr;
1482}
1483
1486 return IntType && IntType->getOperand(2).getImm() != 0;
1487}
1488
1490 return PtrType && PtrType->getOpcode() == SPIRV::OpTypePointer
1491 ? getSPIRVTypeForVReg(PtrType->getOperand(2).getReg())
1492 : nullptr;
1493}
1494
1497 return ElemType ? ElemType->getOpcode() : 0;
1498}
1499
1501 SPIRVTypeInst Type2) const {
1502 if (!Type1 || !Type2)
1503 return false;
1504 auto Op1 = Type1->getOpcode(), Op2 = Type2->getOpcode();
1505 // Ignore difference between <1.5 and >=1.5 protocol versions:
1506 // it's valid if either Result Type or Operand is a pointer, and the other
1507 // is a pointer, an integer scalar, or an integer vector.
1508 if (Op1 == SPIRV::OpTypePointer &&
1509 (Op2 == SPIRV::OpTypePointer || retrieveScalarOrVectorIntType(Type2)))
1510 return true;
1511 if (Op2 == SPIRV::OpTypePointer &&
1512 (Op1 == SPIRV::OpTypePointer || retrieveScalarOrVectorIntType(Type1)))
1513 return true;
1514 unsigned Bits1 = getNumScalarOrVectorTotalBitWidth(Type1),
1515 Bits2 = getNumScalarOrVectorTotalBitWidth(Type2);
1516 return Bits1 > 0 && Bits1 == Bits2;
1517}
1518
1519SPIRV::StorageClass::StorageClass
1522 assert(Type && Type->getOpcode() == SPIRV::OpTypePointer &&
1523 Type->getOperand(1).isImm() && "Pointer type is expected");
1525}
1526
1527SPIRV::StorageClass::StorageClass
1529 return static_cast<SPIRV::StorageClass::StorageClass>(
1530 Type->getOperand(1).getImm());
1531}
1532
1534 MachineIRBuilder &MIRBuilder, Type *ElemType,
1535 SPIRV::StorageClass::StorageClass SC, bool IsWritable, bool EmitIr) {
1536 auto Key = SPIRV::irhandle_vkbuffer(ElemType, SC, IsWritable);
1537 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1538 return MI;
1539
1540 bool ExplicitLayoutRequired = storageClassRequiresExplictLayout(SC);
1541 // We need to get the SPIR-V type for the element here, so we can add the
1542 // decoration to it.
1543 auto *T = StructType::create(ElemType);
1544 SPIRVTypeInst BlockType =
1545 getOrCreateSPIRVType(T, MIRBuilder, SPIRV::AccessQualifier::None,
1546 ExplicitLayoutRequired, EmitIr);
1547
1548 buildOpDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1549 SPIRV::Decoration::Block, {});
1550
1551 if (!IsWritable) {
1552 buildOpMemberDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1553 SPIRV::Decoration::NonWritable, 0, {});
1554 }
1555
1556 SPIRVTypeInst R =
1557 getOrCreateSPIRVPointerTypeInternal(BlockType, MIRBuilder, SC);
1558 add(Key, R);
1559 return R;
1560}
1561
1565 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1566 return MI;
1567 auto *T = Type::getInt8Ty(MIRBuilder.getContext());
1568 SPIRVTypeInst R = getOrCreateSPIRVIntegerType(8, MIRBuilder);
1569 finishCreatingSPIRVType(T, R);
1570 add(Key, R);
1571 return R;
1572}
1573
1575 MachineIRBuilder &MIRBuilder, Type *T) {
1576 const auto SC = SPIRV::StorageClass::PushConstant;
1577
1578 auto Key = SPIRV::irhandle_vkbuffer(T, SC, /* IsWritable= */ false);
1579 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1580 return MI;
1581
1582 // We need to get the SPIR-V type for the element here, so we can add the
1583 // decoration to it.
1585 T, MIRBuilder, SPIRV::AccessQualifier::None,
1586 /* ExplicitLayoutRequired= */ true, /* EmitIr= */ false);
1587
1588 buildOpDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1589 SPIRV::Decoration::Block, {});
1590 SPIRVTypeInst R = BlockType;
1591 add(Key, R);
1592 return R;
1593}
1594
1596 MachineIRBuilder &MIRBuilder, const TargetExtType *T, bool EmitIr) {
1597 auto Key = SPIRV::handle(T);
1598 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1599 return MI;
1600
1601 StructType *ST = cast<StructType>(T->getTypeParameter(0));
1602 ArrayRef<uint32_t> Offsets = T->int_params().slice(1);
1603 assert(ST->getNumElements() == Offsets.size());
1604
1605 StructOffsetDecorator Decorator = [&MIRBuilder, &Offsets](Register Reg) {
1606 for (uint32_t I = 0; I < Offsets.size(); ++I) {
1607 buildOpMemberDecorate(Reg, MIRBuilder, SPIRV::Decoration::Offset, I,
1608 {Offsets[I]});
1609 }
1610 };
1611
1612 // We need a new OpTypeStruct instruction because decorations will be
1613 // different from a struct with an explicit layout created from a different
1614 // entry point.
1615 SPIRVTypeInst SPIRVStructType =
1616 getOpTypeStruct(ST, MIRBuilder, SPIRV::AccessQualifier::None,
1617 std::move(Decorator), EmitIr);
1618 add(Key, SPIRVStructType);
1619 return SPIRVStructType;
1620}
1621
1623 const TargetExtType *ExtensionType,
1624 const SPIRV::AccessQualifier::AccessQualifier Qualifier,
1625 MachineIRBuilder &MIRBuilder) {
1626 assert(ExtensionType->getNumTypeParameters() == 1 &&
1627 "SPIR-V image builtin type must have sampled type parameter!");
1628 const SPIRVTypeInst SampledType =
1629 getOrCreateSPIRVType(ExtensionType->getTypeParameter(0), MIRBuilder,
1630 SPIRV::AccessQualifier::ReadWrite, true);
1631 assert((ExtensionType->getNumIntParameters() == 7 ||
1632 ExtensionType->getNumIntParameters() == 6) &&
1633 "Invalid number of parameters for SPIR-V image builtin!");
1634
1635 SPIRV::AccessQualifier::AccessQualifier accessQualifier =
1636 SPIRV::AccessQualifier::None;
1637 if (ExtensionType->getNumIntParameters() == 7) {
1638 accessQualifier = Qualifier == SPIRV::AccessQualifier::WriteOnly
1639 ? SPIRV::AccessQualifier::WriteOnly
1640 : SPIRV::AccessQualifier::AccessQualifier(
1641 ExtensionType->getIntParameter(6));
1642 }
1643
1644 // Create or get an existing type from GlobalRegistry.
1645 SPIRVTypeInst R = getOrCreateOpTypeImage(
1646 MIRBuilder, SampledType,
1647 SPIRV::Dim::Dim(ExtensionType->getIntParameter(0)),
1648 ExtensionType->getIntParameter(1), ExtensionType->getIntParameter(2),
1649 ExtensionType->getIntParameter(3), ExtensionType->getIntParameter(4),
1650 SPIRV::ImageFormat::ImageFormat(ExtensionType->getIntParameter(5)),
1651 accessQualifier);
1652 SPIRVToLLVMType[R] = ExtensionType;
1653 return R;
1654}
1655
1656SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateOpTypeImage(
1657 MachineIRBuilder &MIRBuilder, SPIRVTypeInst SampledType,
1658 SPIRV::Dim::Dim Dim, uint32_t Depth, uint32_t Arrayed,
1659 uint32_t Multisampled, uint32_t Sampled,
1660 SPIRV::ImageFormat::ImageFormat ImageFormat,
1661 SPIRV::AccessQualifier::AccessQualifier AccessQual) {
1662 auto Key = SPIRV::irhandle_image(SPIRVToLLVMType.lookup(SampledType), Dim,
1663 Depth, Arrayed, Multisampled, Sampled,
1664 ImageFormat, AccessQual);
1665 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1666 return MI;
1667 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1668 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1669 auto MIB =
1670 MIRBuilder.buildInstr(SPIRV::OpTypeImage)
1671 .addDef(createTypeVReg(MIRBuilder))
1672 .addUse(getSPIRVTypeID(SampledType))
1673 .addImm(Dim)
1674 .addImm(Depth) // Depth (whether or not it is a Depth image).
1675 .addImm(Arrayed) // Arrayed.
1676 .addImm(Multisampled) // Multisampled (0 = only single-sample).
1677 .addImm(Sampled) // Sampled (0 = usage known at runtime).
1678 .addImm(ImageFormat);
1679 if (AccessQual != SPIRV::AccessQualifier::None)
1680 MIB.addImm(AccessQual);
1681 return MIB;
1682 });
1683 add(Key, NewMI);
1684 return NewMI;
1685}
1686
1690 const MachineFunction *MF = &MIRBuilder.getMF();
1691 if (const MachineInstr *MI = findMI(Key, MF))
1692 return MI;
1693 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1694 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1695 return MIRBuilder.buildInstr(SPIRV::OpTypeSampler)
1696 .addDef(createTypeVReg(MIRBuilder));
1697 });
1698 add(Key, NewMI);
1699 return NewMI;
1700}
1701
1703 MachineIRBuilder &MIRBuilder,
1704 SPIRV::AccessQualifier::AccessQualifier AccessQual) {
1705 auto Key = SPIRV::irhandle_pipe(AccessQual);
1706 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1707 return MI;
1708 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1709 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1710 return MIRBuilder.buildInstr(SPIRV::OpTypePipe)
1711 .addDef(createTypeVReg(MIRBuilder))
1712 .addImm(AccessQual);
1713 });
1714 add(Key, NewMI);
1715 return NewMI;
1716}
1717
1719 MachineIRBuilder &MIRBuilder) {
1720 auto Key = SPIRV::irhandle_event();
1721 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1722 return MI;
1723 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1724 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1725 return MIRBuilder.buildInstr(SPIRV::OpTypeDeviceEvent)
1726 .addDef(createTypeVReg(MIRBuilder));
1727 });
1728 add(Key, NewMI);
1729 return NewMI;
1730}
1731
1733 SPIRVTypeInst ImageType, MachineIRBuilder &MIRBuilder) {
1735 SPIRVToLLVMType.lookup(MIRBuilder.getMF().getRegInfo().getVRegDef(
1736 ImageType->getOperand(1).getReg())),
1737 ImageType);
1738 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1739 return MI;
1740 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1741 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1742 return MIRBuilder.buildInstr(SPIRV::OpTypeSampledImage)
1743 .addDef(createTypeVReg(MIRBuilder))
1744 .addUse(getSPIRVTypeID(ImageType));
1745 });
1746 add(Key, NewMI);
1747 return NewMI;
1748}
1749
1751 MachineIRBuilder &MIRBuilder, const TargetExtType *ExtensionType,
1752 SPIRVTypeInst ElemType, uint32_t Scope, uint32_t Rows, uint32_t Columns,
1753 uint32_t Use, bool EmitIR) {
1754 if (const MachineInstr *MI =
1755 findMI(ExtensionType, false, &MIRBuilder.getMF()))
1756 return MI;
1757 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1758 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1759 SPIRVTypeInst SpvTypeInt32 =
1760 getOrCreateSPIRVIntegerType(32, MIRBuilder);
1761 const Type *ET = getTypeForSPIRVType(ElemType);
1762 if (ET->isIntegerTy() && ET->getIntegerBitWidth() == 4 &&
1764 .canUseExtension(SPIRV::Extension::SPV_INTEL_int4)) {
1765 MIRBuilder.buildInstr(SPIRV::OpCapability)
1766 .addImm(SPIRV::Capability::Int4CooperativeMatrixINTEL);
1767 }
1768 return MIRBuilder.buildInstr(SPIRV::OpTypeCooperativeMatrixKHR)
1769 .addDef(createTypeVReg(MIRBuilder))
1770 .addUse(getSPIRVTypeID(ElemType))
1771 .addUse(buildConstantInt(Scope, MIRBuilder, SpvTypeInt32, EmitIR))
1772 .addUse(buildConstantInt(Rows, MIRBuilder, SpvTypeInt32, EmitIR))
1773 .addUse(buildConstantInt(Columns, MIRBuilder, SpvTypeInt32, EmitIR))
1774 .addUse(buildConstantInt(Use, MIRBuilder, SpvTypeInt32, EmitIR));
1775 });
1776 add(ExtensionType, false, NewMI);
1777 return NewMI;
1778}
1779
1781 const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode) {
1782 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
1783 return MI;
1784 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1785 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1786 return MIRBuilder.buildInstr(Opcode).addDef(createTypeVReg(MIRBuilder));
1787 });
1788 add(Ty, false, NewMI);
1789 return NewMI;
1790}
1791
1793 const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode,
1794 const ArrayRef<MCOperand> Operands) {
1795 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
1796 return MI;
1797 Register ResVReg = createTypeVReg(MIRBuilder);
1798 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1799 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1800 MachineInstrBuilder MIB = MIRBuilder.buildInstr(SPIRV::UNKNOWN_type)
1801 .addDef(ResVReg)
1802 .addImm(Opcode);
1803 for (MCOperand Operand : Operands) {
1804 if (Operand.isReg()) {
1805 MIB.addUse(Operand.getReg());
1806 } else if (Operand.isImm()) {
1807 MIB.addImm(Operand.getImm());
1808 }
1809 }
1810 return MIB;
1811 });
1812 add(Ty, false, NewMI);
1813 return NewMI;
1814}
1815
1816// Returns nullptr if unable to recognize SPIRV type name
1818 StringRef TypeStr, MachineIRBuilder &MIRBuilder, bool EmitIR,
1819 SPIRV::StorageClass::StorageClass SC,
1820 SPIRV::AccessQualifier::AccessQualifier AQ) {
1821 unsigned VecElts = 0;
1822 auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
1823
1824 // Parse strings representing either a SPIR-V or OpenCL builtin type.
1825 if (hasBuiltinTypePrefix(TypeStr))
1827 TypeStr.str(), MIRBuilder.getContext()),
1828 MIRBuilder, AQ, false, true);
1829
1830 // Parse type name in either "typeN" or "type vector[N]" format, where
1831 // N is the number of elements of the vector.
1832 Type *Ty;
1833
1834 Ty = parseBasicTypeName(TypeStr, Ctx);
1835 if (!Ty)
1836 // Unable to recognize SPIRV type name
1837 return nullptr;
1838
1839 SPIRVTypeInst SpirvTy = getOrCreateSPIRVType(Ty, MIRBuilder, AQ, false, true);
1840
1841 // Handle "type*" or "type* vector[N]".
1842 if (TypeStr.consume_front("*"))
1843 SpirvTy = getOrCreateSPIRVPointerType(Ty, MIRBuilder, SC);
1844
1845 // Handle "typeN*" or "type vector[N]*".
1846 bool IsPtrToVec = TypeStr.consume_back("*");
1847
1848 if (TypeStr.consume_front(" vector[")) {
1849 TypeStr = TypeStr.substr(0, TypeStr.find(']'));
1850 }
1851 TypeStr.getAsInteger(10, VecElts);
1852 if (VecElts > 0)
1853 SpirvTy = getOrCreateSPIRVVectorType(SpirvTy, VecElts, MIRBuilder, EmitIR);
1854
1855 if (IsPtrToVec)
1856 SpirvTy = getOrCreateSPIRVPointerType(SpirvTy, MIRBuilder, SC);
1857
1858 return SpirvTy;
1859}
1860
1863 MachineIRBuilder &MIRBuilder) {
1864 return getOrCreateSPIRVType(
1866 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, true);
1867}
1868
1870SPIRVGlobalRegistry::finishCreatingSPIRVType(const Type *LLVMTy,
1871 SPIRVTypeInst SpirvType) {
1872 assert(CurMF == SpirvType->getMF());
1873 VRegToTypeMap[CurMF][getSPIRVTypeID(SpirvType)] = SpirvType;
1874 SPIRVToLLVMType[SpirvType] = unifyPtrType(LLVMTy);
1875 return SpirvType;
1876}
1877
1880 const SPIRVInstrInfo &TII,
1881 unsigned SPIRVOPcode, Type *Ty) {
1882 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
1883 return MI;
1884 MachineBasicBlock &DepMBB = I.getMF()->front();
1885 MachineIRBuilder MIRBuilder(DepMBB, DepMBB.getFirstNonPHI());
1886 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1887 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1888 auto NewTypeMI = BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
1889 MIRBuilder.getDL(), TII.get(SPIRVOPcode))
1890 .addDef(createTypeVReg(CurMF->getRegInfo()))
1891 .addImm(BitWidth);
1892 // Don't add Encoding to FP type
1893 if (!Ty->isFloatTy()) {
1894 return NewTypeMI.addImm(0);
1895 } else {
1896 return NewTypeMI;
1897 }
1898 });
1899 add(Ty, false, NewMI);
1900 return finishCreatingSPIRVType(Ty, NewMI);
1901}
1902
1904 unsigned BitWidth, MachineInstr &I, const SPIRVInstrInfo &TII) {
1905 // Maybe adjust bit width to keep DuplicateTracker consistent. Without
1906 // such an adjustment SPIRVGlobalRegistry::getOpTypeInt() could create, for
1907 // example, the same "OpTypeInt 8" type for a series of LLVM integer types
1908 // with number of bits less than 8, causing duplicate type definitions.
1909 if (BitWidth > 1)
1910 BitWidth = adjustOpTypeIntWidth(BitWidth);
1911 Type *LLVMTy = IntegerType::get(CurMF->getFunction().getContext(), BitWidth);
1912 return getOrCreateSPIRVType(BitWidth, I, TII, SPIRV::OpTypeInt, LLVMTy);
1913}
1914
1916 unsigned BitWidth, MachineInstr &I, const SPIRVInstrInfo &TII) {
1917 LLVMContext &Ctx = CurMF->getFunction().getContext();
1918 Type *LLVMTy;
1919 switch (BitWidth) {
1920 case 16:
1921 LLVMTy = Type::getHalfTy(Ctx);
1922 break;
1923 case 32:
1924 LLVMTy = Type::getFloatTy(Ctx);
1925 break;
1926 case 64:
1927 LLVMTy = Type::getDoubleTy(Ctx);
1928 break;
1929 default:
1930 llvm_unreachable("Bit width is of unexpected size.");
1931 }
1932 return getOrCreateSPIRVType(BitWidth, I, TII, SPIRV::OpTypeFloat, LLVMTy);
1933}
1934
1937 bool EmitIR) {
1938 return getOrCreateSPIRVType(
1939 IntegerType::get(MIRBuilder.getMF().getFunction().getContext(), 1),
1940 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, EmitIR);
1941}
1942
1945 const SPIRVInstrInfo &TII) {
1946 Type *Ty = IntegerType::get(CurMF->getFunction().getContext(), 1);
1947 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
1948 return MI;
1949 MachineBasicBlock &DepMBB = I.getMF()->front();
1950 MachineIRBuilder MIRBuilder(DepMBB, DepMBB.getFirstNonPHI());
1951 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1952 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1953 return BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
1954 MIRBuilder.getDL(), TII.get(SPIRV::OpTypeBool))
1955 .addDef(createTypeVReg(CurMF->getRegInfo()));
1956 });
1957 add(Ty, false, NewMI);
1958 return finishCreatingSPIRVType(Ty, NewMI);
1959}
1960
1962 SPIRVTypeInst BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder,
1963 bool EmitIR) {
1964 return getOrCreateSPIRVType(
1966 NumElements),
1967 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, EmitIR);
1968}
1969
1971 SPIRVTypeInst BaseType, unsigned NumElements, MachineInstr &I,
1972 const SPIRVInstrInfo &TII) {
1973 // At this point of time all 1-element vectors are resolved. Add assertion
1974 // to fire if anything changes.
1975 assert(NumElements >= 2 && "SPIR-V vectors must have at least 2 components");
1977 const_cast<Type *>(getTypeForSPIRVType(BaseType)), NumElements);
1978 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
1979 return MI;
1980 MachineInstr *DepMI =
1981 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(BaseType));
1982 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
1983 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1984 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1985 return BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
1986 MIRBuilder.getDL(), TII.get(SPIRV::OpTypeVector))
1987 .addDef(createTypeVReg(CurMF->getRegInfo()))
1989 .addImm(NumElements);
1990 });
1991 add(Ty, false, NewMI);
1992 return finishCreatingSPIRVType(Ty, NewMI);
1993}
1994
1996 const Type *BaseType, MachineInstr &I,
1997 SPIRV::StorageClass::StorageClass SC) {
1998 MachineIRBuilder MIRBuilder(I);
1999 return getOrCreateSPIRVPointerType(BaseType, MIRBuilder, SC);
2000}
2001
2003 const Type *BaseType, MachineIRBuilder &MIRBuilder,
2004 SPIRV::StorageClass::StorageClass SC) {
2005 // TODO: Need to check if EmitIr should always be true.
2006 SPIRVTypeInst SpirvBaseType = getOrCreateSPIRVType(
2007 BaseType, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
2009 assert(SpirvBaseType);
2010 return getOrCreateSPIRVPointerTypeInternal(SpirvBaseType, MIRBuilder, SC);
2011}
2012
2014 SPIRVTypeInst PtrType, SPIRV::StorageClass::StorageClass SC,
2015 MachineInstr &I) {
2016 [[maybe_unused]] SPIRV::StorageClass::StorageClass OldSC =
2017 getPointerStorageClass(PtrType);
2020
2021 SPIRVTypeInst PointeeType = getPointeeType(PtrType);
2022 MachineIRBuilder MIRBuilder(I);
2023 return getOrCreateSPIRVPointerTypeInternal(PointeeType, MIRBuilder, SC);
2024}
2025
2028 SPIRV::StorageClass::StorageClass SC) {
2029 const Type *LLVMType = getTypeForSPIRVType(BaseType);
2031 SPIRVTypeInst R = getOrCreateSPIRVPointerType(LLVMType, MIRBuilder, SC);
2032 assert(
2033 getPointeeType(R) == BaseType &&
2034 "The base type was not correctly laid out for the given storage class.");
2035 return R;
2036}
2037
2038SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateSPIRVPointerTypeInternal(
2040 SPIRV::StorageClass::StorageClass SC) {
2041 const Type *PointerElementType = getTypeForSPIRVType(BaseType);
2043 if (const MachineInstr *MI = findMI(PointerElementType, AddressSpace, CurMF))
2044 return MI;
2045 Type *Ty = TypedPointerType::get(const_cast<Type *>(PointerElementType),
2046 AddressSpace);
2047 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2048 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2049 return BuildMI(MIRBuilder.getMBB(), MIRBuilder.getInsertPt(),
2050 MIRBuilder.getDebugLoc(),
2051 MIRBuilder.getTII().get(SPIRV::OpTypePointer))
2053 .addImm(static_cast<uint32_t>(SC))
2055 });
2056 add(PointerElementType, AddressSpace, NewMI);
2057 return finishCreatingSPIRVType(Ty, NewMI);
2058}
2059
2061 SPIRVTypeInst SpvType,
2062 const SPIRVInstrInfo &TII) {
2063 UndefValue *UV =
2064 UndefValue::get(const_cast<Type *>(getTypeForSPIRVType(SpvType)));
2065 Register Res = find(UV, CurMF);
2066 if (Res.isValid())
2067 return Res;
2068
2069 LLT LLTy = LLT::scalar(64);
2070 Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
2071 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
2072 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
2073
2074 MachineInstr *DepMI =
2075 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
2076 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
2077 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2078 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2079 auto MIB = BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
2080 MIRBuilder.getDL(), TII.get(SPIRV::OpUndef))
2081 .addDef(Res)
2082 .addUse(getSPIRVTypeID(SpvType));
2083 const auto &ST = CurMF->getSubtarget();
2084 constrainSelectedInstRegOperands(*MIB, *ST.getInstrInfo(),
2085 *ST.getRegisterInfo(),
2086 *ST.getRegBankInfo());
2087 return MIB;
2088 });
2089 add(UV, NewMI);
2090 return Res;
2091}
2092
2093const TargetRegisterClass *
2095 unsigned Opcode = SpvType->getOpcode();
2096 switch (Opcode) {
2097 case SPIRV::OpTypeFloat:
2098 return &SPIRV::fIDRegClass;
2099 case SPIRV::OpTypePointer:
2100 return &SPIRV::pIDRegClass;
2101 case SPIRV::OpTypeVector: {
2102 SPIRVTypeInst ElemType =
2103 getSPIRVTypeForVReg(SpvType->getOperand(1).getReg());
2104 unsigned ElemOpcode = ElemType ? ElemType->getOpcode() : 0;
2105 if (ElemOpcode == SPIRV::OpTypeFloat)
2106 return &SPIRV::vfIDRegClass;
2107 if (ElemOpcode == SPIRV::OpTypePointer)
2108 return &SPIRV::vpIDRegClass;
2109 return &SPIRV::vIDRegClass;
2110 }
2111 }
2112 return &SPIRV::iIDRegClass;
2113}
2114
2115inline unsigned getAS(SPIRVTypeInst SpvType) {
2117 static_cast<SPIRV::StorageClass::StorageClass>(
2118 SpvType->getOperand(1).getImm()));
2119}
2120
2122 unsigned Opcode = SpvType ? SpvType->getOpcode() : 0;
2123 switch (Opcode) {
2124 case SPIRV::OpTypeInt:
2125 case SPIRV::OpTypeFloat:
2126 case SPIRV::OpTypeBool:
2127 return LLT::scalar(getScalarOrVectorBitWidth(SpvType));
2128 case SPIRV::OpTypePointer:
2129 return LLT::pointer(getAS(SpvType), getPointerSize());
2130 case SPIRV::OpTypeVector: {
2131 SPIRVTypeInst ElemType =
2132 getSPIRVTypeForVReg(SpvType->getOperand(1).getReg());
2133 LLT ET;
2134 switch (ElemType ? ElemType->getOpcode() : 0) {
2135 case SPIRV::OpTypePointer:
2136 ET = LLT::pointer(getAS(ElemType), getPointerSize());
2137 break;
2138 case SPIRV::OpTypeInt:
2139 case SPIRV::OpTypeFloat:
2140 case SPIRV::OpTypeBool:
2141 ET = LLT::scalar(getScalarOrVectorBitWidth(ElemType));
2142 break;
2143 default:
2144 ET = LLT::scalar(64);
2145 }
2146 return LLT::fixed_vector(
2147 static_cast<unsigned>(SpvType->getOperand(2).getImm()), ET);
2148 }
2149 }
2150 return LLT::scalar(64);
2151}
2152
2153// Aliasing list MD contains several scope MD nodes whithin it. Each scope MD
2154// has a selfreference and an extra MD node for aliasing domain and also it
2155// can contain an optional string operand. Domain MD contains a self-reference
2156// with an optional string operand. Here we unfold the list, creating SPIR-V
2157// aliasing instructions.
2158// TODO: add support for an optional string operand.
2160 MachineIRBuilder &MIRBuilder, const MDNode *AliasingListMD) {
2161 if (AliasingListMD->getNumOperands() == 0)
2162 return nullptr;
2163 if (auto L = AliasInstMDMap.find(AliasingListMD); L != AliasInstMDMap.end())
2164 return L->second;
2165
2167 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
2168 for (const MDOperand &MDListOp : AliasingListMD->operands()) {
2169 if (MDNode *ScopeMD = dyn_cast<MDNode>(MDListOp)) {
2170 if (ScopeMD->getNumOperands() < 2)
2171 return nullptr;
2172 MDNode *DomainMD = dyn_cast<MDNode>(ScopeMD->getOperand(1));
2173 if (!DomainMD)
2174 return nullptr;
2175 auto *Domain = [&] {
2176 auto D = AliasInstMDMap.find(DomainMD);
2177 if (D != AliasInstMDMap.end())
2178 return D->second;
2179 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2180 auto MIB =
2181 MIRBuilder.buildInstr(SPIRV::OpAliasDomainDeclINTEL).addDef(Ret);
2182 return MIB.getInstr();
2183 }();
2184 AliasInstMDMap.insert(std::make_pair(DomainMD, Domain));
2185 auto *Scope = [&] {
2186 auto S = AliasInstMDMap.find(ScopeMD);
2187 if (S != AliasInstMDMap.end())
2188 return S->second;
2189 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2190 auto MIB = MIRBuilder.buildInstr(SPIRV::OpAliasScopeDeclINTEL)
2191 .addDef(Ret)
2192 .addUse(Domain->getOperand(0).getReg());
2193 return MIB.getInstr();
2194 }();
2195 AliasInstMDMap.insert(std::make_pair(ScopeMD, Scope));
2196 ScopeList.push_back(Scope);
2197 }
2198 }
2199
2200 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2201 auto MIB =
2202 MIRBuilder.buildInstr(SPIRV::OpAliasScopeListDeclINTEL).addDef(Ret);
2203 for (auto *Scope : ScopeList)
2204 MIB.addUse(Scope->getOperand(0).getReg());
2205 auto List = MIB.getInstr();
2206 AliasInstMDMap.insert(std::make_pair(AliasingListMD, List));
2207 return List;
2208}
2209
2211 Register Reg, MachineIRBuilder &MIRBuilder, uint32_t Dec,
2212 const MDNode *AliasingListMD) {
2213 MachineInstr *AliasList =
2214 getOrAddMemAliasingINTELInst(MIRBuilder, AliasingListMD);
2215 if (!AliasList)
2216 return;
2217 MIRBuilder.buildInstr(SPIRV::OpDecorateId)
2218 .addUse(Reg)
2219 .addImm(Dec)
2220 .addUse(AliasList->getOperand(0).getReg());
2221}
2223 bool DeleteOld) {
2224 Old->replaceAllUsesWith(New);
2225 updateIfExistDeducedElementType(Old, New, DeleteOld);
2226 updateIfExistAssignPtrTypeInstr(Old, New, DeleteOld);
2227}
2228
2230 Value *Arg) {
2231 Value *OfType = getNormalizedPoisonValue(Ty);
2232 CallInst *AssignCI = nullptr;
2233 if (Arg->getType()->isAggregateType() && Ty->isAggregateType() &&
2234 allowEmitFakeUse(Arg)) {
2235 LLVMContext &Ctx = Arg->getContext();
2238 MDString::get(Ctx, Arg->getName())};
2239 B.CreateIntrinsic(Intrinsic::spv_value_md,
2240 {MetadataAsValue::get(Ctx, MDTuple::get(Ctx, ArgMDs))});
2241 AssignCI = B.CreateIntrinsic(Intrinsic::fake_use, {Arg});
2242 } else {
2243 AssignCI = buildIntrWithMD(Intrinsic::spv_assign_type, {Arg->getType()},
2244 OfType, Arg, {}, B);
2245 }
2246 addAssignPtrTypeInstr(Arg, AssignCI);
2247}
2248
2250 Value *Arg) {
2251 Value *OfType = PoisonValue::get(ElemTy);
2252 CallInst *AssignPtrTyCI = findAssignPtrTypeInstr(Arg);
2253 Function *CurrF =
2254 B.GetInsertBlock() ? B.GetInsertBlock()->getParent() : nullptr;
2255 if (AssignPtrTyCI == nullptr ||
2256 AssignPtrTyCI->getParent()->getParent() != CurrF) {
2257 AssignPtrTyCI = buildIntrWithMD(
2258 Intrinsic::spv_assign_ptr_type, {Arg->getType()}, OfType, Arg,
2259 {B.getInt32(getPointerAddressSpace(Arg->getType()))}, B);
2260 addDeducedElementType(AssignPtrTyCI, ElemTy);
2261 addDeducedElementType(Arg, ElemTy);
2262 addAssignPtrTypeInstr(Arg, AssignPtrTyCI);
2263 } else {
2264 updateAssignType(AssignPtrTyCI, Arg, OfType);
2265 }
2266}
2267
2269 Value *OfType) {
2270 AssignCI->setArgOperand(1, buildMD(OfType));
2271 if (cast<IntrinsicInst>(AssignCI)->getIntrinsicID() !=
2272 Intrinsic::spv_assign_ptr_type)
2273 return;
2274
2275 // update association with the pointee type
2276 Type *ElemTy = OfType->getType();
2277 addDeducedElementType(AssignCI, ElemTy);
2278 addDeducedElementType(Arg, ElemTy);
2279}
2280
2281void SPIRVGlobalRegistry::addStructOffsetDecorations(
2282 Register Reg, StructType *Ty, MachineIRBuilder &MIRBuilder) {
2283 ArrayRef<TypeSize> Offsets = DL.getStructLayout(Ty)->getMemberOffsets();
2284 for (uint32_t I = 0; I < Ty->getNumElements(); ++I) {
2285 buildOpMemberDecorate(Reg, MIRBuilder, SPIRV::Decoration::Offset, I,
2286 {static_cast<uint32_t>(Offsets[I])});
2287 }
2288}
2289
2290void SPIRVGlobalRegistry::addArrayStrideDecorations(
2291 Register Reg, Type *ElementType, MachineIRBuilder &MIRBuilder) {
2292 uint32_t SizeInBytes = DL.getTypeSizeInBits(ElementType) / 8;
2293 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::ArrayStride,
2294 {SizeInBytes});
2295}
2296
2297bool SPIRVGlobalRegistry::hasBlockDecoration(SPIRVTypeInst Type) const {
2299 for (const MachineInstr &Use :
2300 Type->getMF()->getRegInfo().use_instructions(Def)) {
2301 if (Use.getOpcode() != SPIRV::OpDecorate)
2302 continue;
2303
2304 if (Use.getOperand(1).getImm() == SPIRV::Decoration::Block)
2305 return true;
2306 }
2307 return false;
2308}
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
static unsigned getNumElements(Type *Ty)
static bool storageClassRequiresExplictLayout(SPIRV::StorageClass::StorageClass SC)
static Register createTypeVReg(MachineRegisterInfo &MRI)
static bool allowEmitFakeUse(const Value *Arg)
static unsigned typeToAddressSpace(const Type *Ty)
unsigned getAS(SPIRVTypeInst SpvType)
APInt bitcastToAPInt() const
Definition APFloat.h:1408
bool isPosZero() const
Definition APFloat.h:1527
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1555
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Class to represent array types.
uint64_t getNumElements() const
Type * getElementType() const
void setArgOperand(unsigned i, Value *v)
This class represents a function call, abstracting a target machine's calling convention.
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValue() const
Definition Constants.h:464
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition Constants.h:629
static LLVM_ABI ConstantTargetNone * get(TargetExtType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
This is an important base class in LLVM.
Definition Constant.h:43
LLVM_ABI const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers,...
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constants.cpp:74
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Class to represent fixed width SIMD vectors.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:873
Class to represent function types.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
Module * getParent()
Get the module that this global value is contained inside of...
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
MaybeAlign getAlign() const
Returns the alignment of the given variable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2811
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:354
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:90
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
Metadata node.
Definition Metadata.h:1080
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1442
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1450
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1529
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
MachineInstrBundleIterator< MachineInstr > iterator
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
Helper class to build MachineInstr.
void setInsertPt(MachineBasicBlock &MBB, MachineBasicBlock::iterator II)
Set the insertion point before the specified position.
LLVMContext & getContext() const
const TargetInstrInfo & getTII()
MachineBasicBlock::iterator getInsertPt()
Current insertion point for new instructions.
MachineInstrBuilder buildSplatBuildVector(const DstOp &Res, const SrcOp &Src)
Build and insert Res = G_BUILD_VECTOR with Src replicated to fill the number of elements.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
const DebugLoc & getDL()
Getter for DebugLoc.
MachineFunction & getMF()
Getter for the function we currently build.
const MachineBasicBlock & getMBB() const
Getter for the basic block we currently build.
const DebugLoc & getDebugLoc()
Get the current instruction's debug location.
MachineRegisterInfo * getMRI()
Getter for MRI.
MachineIRBuilderState & getState()
Getter for the State.
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
LLVM_ABI void insert(mop_iterator InsertBefore, ArrayRef< MachineOperand > Ops)
Inserts Ops BEFORE It. Can untie/retie tied operands.
mop_range uses()
Returns all operands which may be register uses.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const MachineOperand & getOperand(unsigned i) const
int64_t getImm() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
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 setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
LLVM_ABI Register createGenericVirtualRegister(LLT Ty, StringRef Name="")
Create and return a new generic virtual register with low-level type Ty.
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:110
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
SPIRVTypeInst getImageType(const TargetExtType *ExtensionType, const SPIRV::AccessQualifier::AccessQualifier Qualifier, MachineIRBuilder &MIRBuilder)
bool isScalarOrVectorSigned(SPIRVTypeInst Type) const
void addAssignPtrTypeInstr(Value *Val, CallInst *AssignPtrTyCI)
SPIRVTypeInst getOrCreateOpTypeSampledImage(SPIRVTypeInst ImageType, MachineIRBuilder &MIRBuilder)
unsigned getNumScalarOrVectorTotalBitWidth(SPIRVTypeInst Type) const
SPIRVTypeInst assignVectTypeToVReg(SPIRVTypeInst BaseType, unsigned NumElements, Register VReg, MachineInstr &I, const SPIRVInstrInfo &TII)
void assignSPIRVTypeToVReg(SPIRVTypeInst Type, Register VReg, const MachineFunction &MF)
SPIRVTypeInst getOrCreateOpTypeFunctionWithArgs(const Type *Ty, SPIRVTypeInst RetType, const SmallVectorImpl< SPIRVTypeInst > &ArgTypes, MachineIRBuilder &MIRBuilder)
void buildAssignPtr(IRBuilder<> &B, Type *ElemTy, Value *Arg)
const TargetRegisterClass * getRegClass(SPIRVTypeInst SpvType) const
MachineInstr * getOrAddMemAliasingINTELInst(MachineIRBuilder &MIRBuilder, const MDNode *AliasingListMD)
unsigned getScalarOrVectorBitWidth(SPIRVTypeInst Type) const
SPIRVTypeInst getOrCreateSPIRVIntegerType(unsigned BitWidth, MachineIRBuilder &MIRBuilder)
SPIRVTypeInst getOrCreateSPIRVVectorType(SPIRVTypeInst BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder, bool EmitIR)
SPIRVTypeInst getOrCreateSPIRVTypeByName(StringRef TypeStr, MachineIRBuilder &MIRBuilder, bool EmitIR, SPIRV::StorageClass::StorageClass SC=SPIRV::StorageClass::Function, SPIRV::AccessQualifier::AccessQualifier AQ=SPIRV::AccessQualifier::ReadWrite)
Register buildGlobalVariable(Register Reg, SPIRVTypeInst BaseType, StringRef Name, const GlobalValue *GV, SPIRV::StorageClass::StorageClass Storage, const MachineInstr *Init, bool IsConst, const std::optional< SPIRV::LinkageType::LinkageType > &LinkageType, MachineIRBuilder &MIRBuilder, bool IsInstSelector)
SPIRVTypeInst assignIntTypeToVReg(unsigned BitWidth, Register VReg, MachineInstr &I, const SPIRVInstrInfo &TII)
SPIRVTypeInst getResultType(Register VReg, MachineFunction *MF=nullptr)
void replaceAllUsesWith(Value *Old, Value *New, bool DeleteOld=true)
SPIRVTypeInst getOrCreateOpTypeByOpcode(const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode)
unsigned getScalarOrVectorComponentCount(Register VReg) const
SPIRVTypeInst assignFloatTypeToVReg(unsigned BitWidth, Register VReg, MachineInstr &I, const SPIRVInstrInfo &TII)
const Type * getTypeForSPIRVType(SPIRVTypeInst Ty) const
bool isBitcastCompatible(SPIRVTypeInst Type1, SPIRVTypeInst Type2) const
void addDeducedElementType(Value *Val, Type *Ty)
SPIRVTypeInst getOrCreatePaddingType(MachineIRBuilder &MIRBuilder)
Register getOrCreateConstFP(APFloat Val, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull=true)
LLT getRegType(SPIRVTypeInst SpvType) const
void invalidateMachineInstr(MachineInstr *MI)
bool isResourceType(SPIRVTypeInst Type) const
SPIRVTypeInst getOrCreateSPIRVBoolType(MachineIRBuilder &MIRBuilder, bool EmitIR)
SPIRVTypeInst getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC)
void updateIfExistDeducedElementType(Value *OldVal, Value *NewVal, bool DeleteOld)
bool isScalarOfType(Register VReg, unsigned TypeOpcode) const
Register getSPIRVTypeID(SPIRVTypeInst SpirvType) const
Register getOrCreateConstInt(uint64_t Val, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull=true)
Register getOrCreateConstIntArray(uint64_t Val, size_t Num, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII)
unsigned getPointeeTypeOp(Register PtrReg)
SPIRVTypeInst retrieveScalarOrVectorIntType(SPIRVTypeInst Type) const
Register getOrCreateGlobalVariableWithBinding(SPIRVTypeInst VarType, uint32_t Set, uint32_t Binding, StringRef Name, MachineIRBuilder &MIRBuilder)
SPIRVTypeInst getOrCreateOpTypeCoopMatr(MachineIRBuilder &MIRBuilder, const TargetExtType *ExtensionType, SPIRVTypeInst ElemType, uint32_t Scope, uint32_t Rows, uint32_t Columns, uint32_t Use, bool EmitIR)
SPIRVTypeInst changePointerStorageClass(SPIRVTypeInst PtrType, SPIRV::StorageClass::StorageClass SC, MachineInstr &I)
SPIRVTypeInst getOrCreateUnknownType(const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode, const ArrayRef< MCOperand > Operands)
Register getOrCreateConstVector(uint64_t Val, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull=true)
Register buildConstantFP(APFloat Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType=nullptr)
SPIRVTypeInst getOrCreateOpTypePipe(MachineIRBuilder &MIRBuilder, SPIRV::AccessQualifier::AccessQualifier AccQual)
void addGlobalObject(const Value *V, const MachineFunction *MF, Register R)
SPIRVTypeInst getScalarOrVectorComponentType(SPIRVTypeInst Type) const
void buildAssignType(IRBuilder<> &B, Type *Ty, Value *Arg)
SPIRVTypeInst getOrCreateSPIRVFloatType(unsigned BitWidth, MachineInstr &I, const SPIRVInstrInfo &TII)
SPIRVTypeInst getOrCreateVulkanBufferType(MachineIRBuilder &MIRBuilder, Type *ElemType, SPIRV::StorageClass::StorageClass SC, bool IsWritable, bool EmitIr=false)
SPIRVTypeInst getPointeeType(SPIRVTypeInst PtrType)
SPIRVTypeInst getOrCreateSPIRVType(const Type *Type, MachineInstr &I, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
Register getOrCreateConsIntVector(uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType, bool EmitIR)
void updateIfExistAssignPtrTypeInstr(Value *OldVal, Value *NewVal, bool DeleteOld)
SPIRVTypeInst assignTypeToVReg(const Type *Type, Register VReg, MachineIRBuilder &MIRBuilder, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
bool isScalarOrVectorOfType(Register VReg, unsigned TypeOpcode) const
SPIRVTypeInst getOrCreateLayoutType(MachineIRBuilder &MIRBuilder, const TargetExtType *T, bool EmitIr=false)
Register createConstInt(const ConstantInt *CI, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull)
Register getOrCreateConstNullPtr(MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType)
SPIRVTypeInst getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
Register getOrCreateUndef(MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII)
SPIRVTypeInst getOrCreateOpTypeSampler(MachineIRBuilder &MIRBuilder)
void buildMemAliasingOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, uint32_t Dec, const MDNode *GVarMD)
SPIRV::StorageClass::StorageClass getPointerStorageClass(Register VReg) const
Register buildConstantSampler(Register Res, unsigned AddrMode, unsigned Param, unsigned FilerMode, MachineIRBuilder &MIRBuilder)
void updateAssignType(CallInst *AssignCI, Value *Arg, Value *OfType)
CallInst * findAssignPtrTypeInstr(const Value *Val)
Register buildConstantInt(uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType, bool EmitIR, bool ZeroAsNull=true)
SPIRVTypeInst getOrCreateVulkanPushConstantType(MachineIRBuilder &MIRBuilder, Type *ElemType)
Register createConstFP(const ConstantFP *CF, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull)
SPIRVTypeInst getOrCreateOpTypeDeviceEvent(MachineIRBuilder &MIRBuilder)
const MachineInstr * findMI(SPIRV::IRHandle Handle, const MachineFunction *MF)
bool erase(const MachineInstr *MI)
bool add(SPIRV::IRHandle Handle, const MachineInstr *MI)
Register find(SPIRV::IRHandle Handle, const MachineFunction *MF)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition StringRef.h:685
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:591
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:655
Class to represent struct types.
ArrayRef< Type * > elements() const
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:689
bool isPacked() const
unsigned getNumElements() const
Random access to the elements.
bool hasName() const
Return true if this is a named struct that has a non-empty name.
LLVM_ABI StringRef getName() const
Return the name for this struct type if it has an identity.
Definition Type.cpp:766
Class to represent target extensions types, which are generally unintrospectable from target-independ...
unsigned getNumIntParameters() const
Type * getTypeParameter(unsigned i) const
unsigned getNumTypeParameters() const
unsigned getIntParameter(unsigned i) const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:314
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:290
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:281
Type * getArrayElementType() const
Definition Type.h:427
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
LLVM_ABI uint64_t getArrayNumElements() const
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:311
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:201
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:321
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:291
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:290
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:288
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static LLVM_ABI TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
'undef' values are things that do not have specified contents.
Definition Constants.h:1606
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
static ConstantAsMetadata * getConstant(Value *C)
Definition Metadata.h:481
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Type * getElementType() const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
IteratorT begin() const
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
IRHandle handle(const Type *Ty)
IRHandle irhandle_sampled_image(const Type *SampledTy, const MachineInstr *ImageTy)
IRHandle irhandle_padding()
IRHandle irhandle_vkbuffer(const Type *ElementType, StorageClass::StorageClass SC, bool IsWriteable)
IRHandle irhandle_sampler()
TargetExtType * parseBuiltinTypeNameToTargetExtType(std::string TypeName, LLVMContext &Context)
Translates a string representing a SPIR-V or OpenCL builtin type to a TargetExtType that can be furth...
IRHandle irhandle_event()
SPIRVTypeInst lowerBuiltinType(const Type *OpaqueType, SPIRV::AccessQualifier::AccessQualifier AccessQual, MachineIRBuilder &MIRBuilder, SPIRVGlobalRegistry *GR)
IRHandle irhandle_pipe(uint8_t AQ)
IRHandle irhandle_image(const Type *SampledTy, unsigned Dim, unsigned Depth, unsigned Arrayed, unsigned MS, unsigned Sampled, unsigned ImageFormat, unsigned AQ=0)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
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 isTypedPointerWrapper(const TargetExtType *ExtTy)
Definition SPIRVUtils.h:411
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:375
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void addNumImm(const APInt &Imm, MachineInstrBuilder &MIB)
LLVM_ABI void 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
CallInst * buildIntrWithMD(Intrinsic::ID IntrID, ArrayRef< Type * > Types, Value *Arg, Value *Arg2, ArrayRef< Constant * > Imms, IRBuilder<> &B)
bool matchPeeledArrayPattern(const StructType *Ty, Type *&OriginalElementType, uint64_t &TotalSize)
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
constexpr unsigned storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC)
Definition SPIRVUtils.h:248
bool getSpirvBuiltInIdByName(llvm::StringRef Name, SPIRV::BuiltIn::BuiltIn &BI)
MetadataAsValue * buildMD(Value *Arg)
Definition SPIRVUtils.h:521
bool isTypedPointerTy(const Type *T)
Definition SPIRVUtils.h:359
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, const std::vector< uint32_t > &DecArgs, StringRef StrImm)
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
Type * getTypedPointerWrapper(Type *ElemTy, unsigned AS)
Definition SPIRVUtils.h:406
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
void buildOpMemberDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, uint32_t Member, const std::vector< uint32_t > &DecArgs, StringRef StrImm)
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:466
bool isSpecialOpaqueType(const Type *Ty)
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:369
MachineBasicBlock::iterator getInsertPtValidEnd(MachineBasicBlock *MBB)
const Type * unifyPtrType(const Type *Ty)
Definition SPIRVUtils.h:493
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
std::function< void(Register)> StructOffsetDecorator
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
void buildOpSpirvDecorations(Register Reg, MachineIRBuilder &MIRBuilder, const MDNode *GVarMD, const SPIRVSubtarget &ST)
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
Type * parseBasicTypeName(StringRef &TypeName, LLVMContext &Ctx)
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool hasBuiltinTypePrefix(StringRef Name)
bool isPointerTyOrWrapper(const Type *Ty)
Definition SPIRVUtils.h:418
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)
PoisonValue * getNormalizedPoisonValue(Type *Ty)
Definition SPIRVUtils.h:517
void addStringImm(const StringRef &Str, MCInst &Inst)
MachineInstr * getVRegDef(MachineRegisterInfo &MRI, Register Reg)
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130