LLVM 24.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
94void SPIRVGlobalRegistry::constrainSelectedInstRegOperands(
95 MachineInstrBuilder &MIB) const {
96 const auto &ST = CurMF->getSubtarget();
97 MIB.constrainAllUses(*ST.getInstrInfo(), *ST.getRegisterInfo(),
98 *ST.getRegBankInfo());
99}
100
104 const SPIRVInstrInfo &TII) {
106 assignSPIRVTypeToVReg(SpirvType, VReg, *CurMF);
107 return SpirvType;
108}
109
111 const Type *Type, Register VReg, MachineIRBuilder &MIRBuilder,
112 SPIRV::AccessQualifier::AccessQualifier AccessQual, bool EmitIR) {
113 SPIRVTypeInst SpirvType =
114 getOrCreateSPIRVType(Type, MIRBuilder, AccessQual, EmitIR);
115 assignSPIRVTypeToVReg(SpirvType, VReg, MIRBuilder.getMF());
116 return SpirvType;
117}
118
120 Register VReg,
121 const MachineFunction &MF) {
122 VRegToTypeMap[&MF][VReg] = SpirvType;
123}
124
126 auto Res = MRI.createGenericVirtualRegister(LLT::scalar(64));
127 MRI.setRegClass(Res, &SPIRV::TYPERegClass);
128 return Res;
129}
130
132 return createTypeVReg(MIRBuilder.getMF().getRegInfo());
133}
134
135SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeBool(MachineIRBuilder &MIRBuilder) {
136 return createConstOrTypeAtFunctionEntry(
137 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
138 return MIRBuilder.buildInstr(SPIRV::OpTypeBool)
139 .addDef(createTypeVReg(MIRBuilder));
140 });
141}
142
143unsigned SPIRVGlobalRegistry::adjustOpTypeIntWidth(unsigned Width) const {
144 const SPIRVSubtarget &ST = cast<SPIRVSubtarget>(CurMF->getSubtarget());
145 if (ST.canUseExtension(
146 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers) ||
147 (Width == 4 && ST.canUseExtension(SPIRV::Extension::SPV_INTEL_int4)))
148 return Width;
149 if (Width <= 8)
150 return 8;
151 else if (Width <= 16)
152 return 16;
153 else if (Width <= 32)
154 return 32;
155 else if (Width <= 64)
156 return 64;
157 else if (Width <= 128)
158 return 128;
159 reportFatalUsageError("Unsupported Integer width!");
160}
161
162SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeInt(unsigned Width,
163 MachineIRBuilder &MIRBuilder,
164 bool IsSigned) {
165 Width = adjustOpTypeIntWidth(Width);
166 const SPIRVSubtarget &ST =
168 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
169 &MIRBuilder) {
170 if (Width == 4 && ST.canUseExtension(SPIRV::Extension::SPV_INTEL_int4)) {
171 MIRBuilder.buildInstr(SPIRV::OpExtension)
172 .addImm(SPIRV::Extension::SPV_INTEL_int4);
173 MIRBuilder.buildInstr(SPIRV::OpCapability)
174 .addImm(SPIRV::Capability::Int4TypeINTEL);
175 } else if ((!isPowerOf2_32(Width) || Width < 8) &&
176 ST.canUseExtension(
177 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers)) {
178 MIRBuilder.buildInstr(SPIRV::OpExtension)
179 .addImm(SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers);
180 MIRBuilder.buildInstr(SPIRV::OpCapability)
181 .addImm(SPIRV::Capability::ArbitraryPrecisionIntegersALTERA);
182 }
183 return MIRBuilder.buildInstr(SPIRV::OpTypeInt)
184 .addDef(createTypeVReg(MIRBuilder))
185 .addImm(Width)
186 .addImm(IsSigned ? 1 : 0);
187 });
188}
189
191SPIRVGlobalRegistry::getOpTypeFloat(uint32_t Width,
192 MachineIRBuilder &MIRBuilder) {
193 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
194 &MIRBuilder) {
195 return MIRBuilder.buildInstr(SPIRV::OpTypeFloat)
196 .addDef(createTypeVReg(MIRBuilder))
197 .addImm(Width);
198 });
199}
200
202SPIRVGlobalRegistry::getOpTypeFloat(uint32_t Width,
203 MachineIRBuilder &MIRBuilder,
204 SPIRV::FPEncoding::FPEncoding FPEncode) {
205 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
206 &MIRBuilder) {
207 return MIRBuilder.buildInstr(SPIRV::OpTypeFloat)
208 .addDef(createTypeVReg(MIRBuilder))
209 .addImm(Width)
210 .addImm(FPEncode);
211 });
212}
213
214SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeVoid(MachineIRBuilder &MIRBuilder) {
215 return createConstOrTypeAtFunctionEntry(
216 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
217 return MIRBuilder.buildInstr(SPIRV::OpTypeVoid)
218 .addDef(createTypeVReg(MIRBuilder));
219 });
220}
221
223 // Other maps that may hold MachineInstr*:
224 // - VRegToTypeMap: We cannot remove the definitions of `MI` from
225 // VRegToTypeMap because some calls to invalidateMachineInstr are replacing MI
226 // with another instruction defining the same register. We expect that if MI
227 // is a type instruction, and it is still referenced in VRegToTypeMap, then
228 // those registers are dead or the VRegToTypeMap is out-of-date. We do not
229 // expect passes to ask for the SPIR-V type of a dead register. If the
230 // VRegToTypeMap is out-of-date already, then there was an error before. We
231 // cannot add an assert to verify this because the VRegToTypeMap can be
232 // out-of-date.
233 // - FunctionToInstr & FunctionToInstrRev: At this point, we should not be
234 // deleting functions. No need to update.
235 // - AliasInstMDMap: Would require a linear search, and the Intel Alias
236 // instruction are not instructions instruction selection will be able to
237 // remove.
238
239 const SPIRVSubtarget &ST = MI->getMF()->getSubtarget<SPIRVSubtarget>();
240 [[maybe_unused]] const SPIRVInstrInfo *TII = ST.getInstrInfo();
241 assert(!TII->isAliasingInstr(*MI) &&
242 "Cannot invalidate aliasing instructions.");
243 assert(MI->getOpcode() != SPIRV::OpFunction &&
244 "Cannot invalidate OpFunction.");
245
246 if (MI->getOpcode() == SPIRV::OpFunctionCall) {
247 if (const auto *F = dyn_cast<Function>(MI->getOperand(2).getGlobal())) {
248 auto It = ForwardCalls.find(F);
249 if (It != ForwardCalls.end()) {
250 It->second.erase(MI);
251 if (It->second.empty())
252 ForwardCalls.erase(It);
253 }
254 }
255 }
256
257 const MachineFunction *MF = MI->getMF();
258 auto It = LastInsertedTypeMap.find(MF);
259 if (It != LastInsertedTypeMap.end() && It->second == MI)
260 LastInsertedTypeMap.erase(MF);
261 // remove from the duplicate tracker to avoid incorrect reuse
262 erase(MI);
263}
264
265const MachineInstr *SPIRVGlobalRegistry::createConstOrTypeAtFunctionEntry(
266 MachineIRBuilder &MIRBuilder,
267 std::function<MachineInstr *(MachineIRBuilder &)> Op) {
268 auto oldInsertPoint = MIRBuilder.getInsertPt();
269 MachineBasicBlock *OldMBB = &MIRBuilder.getMBB();
270 MachineBasicBlock *NewMBB = &*MIRBuilder.getMF().begin();
271
272 auto LastInsertedType = LastInsertedTypeMap.find(CurMF);
273 if (LastInsertedType != LastInsertedTypeMap.end()) {
274 auto It = LastInsertedType->second->getIterator();
275 // It might happen that this instruction was removed from the first MBB,
276 // hence the Parent's check.
278 if (It->getParent() != NewMBB)
279 InsertAt = oldInsertPoint->getParent() == NewMBB
280 ? oldInsertPoint
281 : getInsertPtValidEnd(NewMBB);
282 else if (It->getNextNode())
283 InsertAt = It->getNextNode()->getIterator();
284 else
285 InsertAt = getInsertPtValidEnd(NewMBB);
286 MIRBuilder.setInsertPt(*NewMBB, InsertAt);
287 } else {
288 MIRBuilder.setInsertPt(*NewMBB, NewMBB->begin());
289 auto Result = LastInsertedTypeMap.try_emplace(CurMF, nullptr);
290 assert(Result.second);
291 LastInsertedType = Result.first;
292 }
293
294 MachineInstr *ConstOrType = Op(MIRBuilder);
295 // We expect all users of this function to insert definitions at the insertion
296 // point set above that is always the first MBB.
297 assert(ConstOrType->getParent() == NewMBB);
298 LastInsertedType->second = ConstOrType;
299 // Advance past any continued instructions so that the next type/constant
300 // is inserted after the full group, preserving required adjacency.
301 while (auto *Next = LastInsertedType->second->getNextNode()) {
302 unsigned Opc = Next->getOpcode();
303 if (Opc == SPIRV::OpTypeStructContinuedINTEL ||
304 Opc == SPIRV::OpConstantCompositeContinuedINTEL ||
305 Opc == SPIRV::OpSpecConstantCompositeContinuedINTEL ||
306 Opc == SPIRV::OpCompositeConstructContinuedINTEL)
307 LastInsertedType->second = Next;
308 else
309 break;
310 }
311
312 MIRBuilder.setInsertPt(*OldMBB, oldInsertPoint);
313 return ConstOrType;
314}
315
317SPIRVGlobalRegistry::getOpTypeVector(uint32_t NumElems, SPIRVTypeInst ElemType,
318 MachineIRBuilder &MIRBuilder) {
319 assert(NumElems >= 2 && "SPIR-V OpTypeVector requires at least 2 components");
320
321 if (ElemType.isPointer()) {
322 if (!cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget())
323 .canUseExtension(
324 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
325 const Function &F = MIRBuilder.getMF().getFunction();
326 F.getContext().diagnose(DiagnosticInfoUnsupported(
327 F,
328 "Vector of pointers requires SPV_INTEL_masked_gather_scatter "
329 "extension",
330 DebugLoc(), DS_Error));
331 }
332 } else {
333 [[maybe_unused]] auto EleOpc = ElemType->getOpcode();
334 assert((EleOpc == SPIRV::OpTypeInt || EleOpc == SPIRV::OpTypeFloat ||
335 EleOpc == SPIRV::OpTypeBool) &&
336 "Invalid vector element type");
337 }
338
339 return createConstOrTypeAtFunctionEntry(
340 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
341 return MIRBuilder.buildInstr(SPIRV::OpTypeVector)
342 .addDef(createTypeVReg(MIRBuilder))
343 .addUse(getSPIRVTypeID(ElemType))
344 .addImm(NumElems);
345 });
346}
347
349 SPIRVTypeInst SpvType,
350 const SPIRVInstrInfo &TII,
351 bool ZeroAsNull) {
352 LLVMContext &Ctx = CurMF->getFunction().getContext();
353 auto *const CF = ConstantFP::get(Ctx, Val);
354 const MachineInstr *MI = findMI(CF, CurMF);
355 if (MI && (MI->getOpcode() == SPIRV::OpConstantNull ||
356 MI->getOpcode() == SPIRV::OpConstantF))
357 return MI->getOperand(0).getReg();
358 return createConstFP(CF, I, SpvType, TII, ZeroAsNull);
359}
360
363 SPIRVTypeInst SpvType,
364 const SPIRVInstrInfo &TII,
365 bool ZeroAsNull) {
366 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
367 LLT LLTy = LLT::scalar(BitWidth);
368 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
369 CurMF->getRegInfo().setRegClass(Res, &SPIRV::fIDRegClass);
370 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
371
372 MachineInstr *DepMI =
373 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
374 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
375 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
376 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
378 // In OpenCL OpConstantNull - Scalar floating point: +0.0 (all bits 0)
379 if (CF->getValue().isPosZero() && ZeroAsNull) {
380 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
381 .addDef(Res)
382 .addUse(getSPIRVTypeID(SpvType));
383 } else {
384 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantF)
385 .addDef(Res)
386 .addUse(getSPIRVTypeID(SpvType));
389 MIB);
390 }
391 constrainSelectedInstRegOperands(MIB);
392 return MIB;
393 });
394 add(CF, Const);
395 return Res;
396}
397
399 SPIRVTypeInst SpvType,
400 const SPIRVInstrInfo &TII,
401 bool ZeroAsNull) {
403 SpvType, TII, ZeroAsNull);
404}
405
408 SPIRVTypeInst SpvType,
409 const SPIRVInstrInfo &TII,
410 bool ZeroAsNull) {
411 auto *const CI = ConstantInt::get(
413 const MachineInstr *MI = findMI(CI, CurMF);
414 if (MI && (MI->getOpcode() == SPIRV::OpConstantNull ||
415 MI->getOpcode() == SPIRV::OpConstantI))
416 return MI->getOperand(0).getReg();
417 return createConstInt(CI, I, SpvType, TII, ZeroAsNull);
418}
419
422 SPIRVTypeInst SpvType,
423 const SPIRVInstrInfo &TII,
424 bool ZeroAsNull) {
425 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
426 LLT LLTy = LLT::scalar(BitWidth);
427 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
428 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
430
431 MachineInstr *DepMI =
432 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
433 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
434 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
435 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
437 if (BitWidth == 1) {
438 MIB = MIRBuilder
439 .buildInstr(CI->isZero() ? SPIRV::OpConstantFalse
440 : SPIRV::OpConstantTrue)
441 .addDef(Res)
442 .addUse(getSPIRVTypeID(SpvType));
443 } else if (!CI->isZero() || !ZeroAsNull) {
444 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantI)
445 .addDef(Res)
446 .addUse(getSPIRVTypeID(SpvType));
447 addNumImm(CI->getValue(), MIB);
448 } else {
449 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
450 .addDef(Res)
451 .addUse(getSPIRVTypeID(SpvType));
452 }
453 constrainSelectedInstRegOperands(MIB);
454 return MIB;
455 });
456 add(CI, Const);
457 return Res;
458}
459
461 MachineIRBuilder &MIRBuilder,
462 SPIRVTypeInst SpvType,
463 bool EmitIR, bool ZeroAsNull) {
464 assert(SpvType);
465 auto &MF = MIRBuilder.getMF();
467 // TODO: Avoid implicit trunc?
468 // See https://github.com/llvm/llvm-project/issues/112510.
469 auto *const CI = ConstantInt::get(const_cast<IntegerType *>(Ty), Val,
470 /*IsSigned=*/false, /*ImplicitTrunc=*/true);
471 Register Res = find(CI, &MF);
472 if (Res.isValid())
473 return Res;
474
475 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
476 LLT LLTy = LLT::scalar(BitWidth);
477 MachineRegisterInfo &MRI = MF.getRegInfo();
478 Res = MRI.createGenericVirtualRegister(LLTy);
479 MRI.setRegClass(Res, &SPIRV::iIDRegClass);
480 assignTypeToVReg(Ty, Res, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
481 EmitIR);
482
483 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
484 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
485 if (EmitIR)
486 return MIRBuilder.buildConstant(Res, *CI);
487 Register SpvTypeReg = getSPIRVTypeID(SpvType);
489 if (Val || !ZeroAsNull) {
490 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantI)
491 .addDef(Res)
492 .addUse(SpvTypeReg);
493 addNumImm(APInt(BitWidth, Val), MIB);
494 } else {
495 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
496 .addDef(Res)
497 .addUse(SpvTypeReg);
498 }
499 constrainSelectedInstRegOperands(MIB);
500 return MIB;
501 });
502 add(CI, Const);
503 return Res;
504}
505
507 MachineIRBuilder &MIRBuilder,
508 SPIRVTypeInst SpvType) {
509 auto &MF = MIRBuilder.getMF();
510 LLVMContext &Ctx = MF.getFunction().getContext();
511 if (!SpvType)
512 SpvType = getOrCreateSPIRVType(Type::getFloatTy(Ctx), MIRBuilder,
513 SPIRV::AccessQualifier::ReadWrite, true);
514 auto *const CF = ConstantFP::get(Ctx, Val);
515 Register Res = find(CF, &MF);
516 if (Res.isValid())
517 return Res;
518
520 Res = MF.getRegInfo().createGenericVirtualRegister(LLTy);
521 MF.getRegInfo().setRegClass(Res, &SPIRV::fIDRegClass);
522 assignSPIRVTypeToVReg(SpvType, Res, MF);
523
524 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
525 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
527 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantF)
528 .addDef(Res)
529 .addUse(getSPIRVTypeID(SpvType));
530 addNumImm(CF->getValueAPF().bitcastToAPInt(), MIB);
531 return MIB;
532 });
533 add(CF, Const);
534 return Res;
535}
536
537Register SPIRVGlobalRegistry::getOrCreateBaseRegister(
538 Constant *Val, MachineInstr &I, SPIRVTypeInst SpvType,
539 const SPIRVInstrInfo &TII, unsigned BitWidth, bool ZeroAsNull) {
540 SPIRVTypeInst Type = SpvType;
541 if (SpvType->getOpcode() == SPIRV::OpTypeVector ||
542 SpvType->getOpcode() == SPIRV::OpTypeArray) {
543 auto EleTypeReg = SpvType->getOperand(1).getReg();
544 Type = getSPIRVTypeForVReg(EleTypeReg);
545 }
546 if (Type->getOpcode() == SPIRV::OpTypeFloat) {
548 return getOrCreateConstFP(cast<ConstantFP>(Val)->getValue(), I, SpvBaseType,
549 TII, ZeroAsNull);
550 }
551 assert(Type->getOpcode() == SPIRV::OpTypeInt);
552 SPIRVTypeInst SpvBaseType = getOrCreateSPIRVIntegerType(BitWidth, I, TII);
553 return getOrCreateConstInt(Val->getUniqueInteger(), I, SpvBaseType, TII,
554 ZeroAsNull);
555}
556
557Register SPIRVGlobalRegistry::getOrCreateCompositeOrNull(
558 Constant *Val, MachineInstr &I, SPIRVTypeInst SpvType,
559 const SPIRVInstrInfo &TII, Constant *CA, unsigned BitWidth,
560 unsigned ElemCnt, bool ZeroAsNull) {
561 if (Register R = find(CA, CurMF); R.isValid())
562 return R;
563
564 bool IsNull = Val->isNullValue() && ZeroAsNull;
565 Register ElemReg;
566 if (!IsNull)
567 ElemReg =
568 getOrCreateBaseRegister(Val, I, SpvType, TII, BitWidth, ZeroAsNull);
569
570 LLT LLTy = LLT::scalar(64);
571 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
572 CurMF->getRegInfo().setRegClass(Res, getRegClass(SpvType));
573 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
574
575 MachineInstr *DepMI =
576 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
577 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
578 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
579 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
580 MachineInstrBuilder MIB;
581 if (!IsNull) {
582 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantComposite)
583 .addDef(Res)
584 .addUse(getSPIRVTypeID(SpvType));
585 for (unsigned i = 0; i < ElemCnt; ++i)
586 MIB.addUse(ElemReg);
587 } else {
588 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
589 .addDef(Res)
590 .addUse(getSPIRVTypeID(SpvType));
591 }
592 constrainSelectedInstRegOperands(MIB);
593 return MIB;
594 });
595 add(CA, NewMI);
596 return Res;
597}
598
601 SPIRVTypeInst SpvType,
602 const SPIRVInstrInfo &TII,
603 bool ZeroAsNull) {
605 I, SpvType, TII, ZeroAsNull);
606}
607
610 SPIRVTypeInst SpvType,
611 const SPIRVInstrInfo &TII,
612 bool ZeroAsNull) {
613 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
614 assert(LLVMTy->isVectorTy() &&
615 "Expected vector type for constant vector creation");
616 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
617 Type *LLVMBaseTy = LLVMVecTy->getElementType();
618 assert(LLVMBaseTy->isIntegerTy() &&
619 "Expected integer element type for APInt constant vector");
620 auto *ConstVal = cast<ConstantInt>(ConstantInt::get(LLVMBaseTy, Val));
621 auto *ConstVec =
622 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstVal);
623 unsigned BW = getScalarOrVectorBitWidth(SpvType);
624 return getOrCreateCompositeOrNull(ConstVal, I, SpvType, TII, ConstVec, BW,
626 ZeroAsNull);
627}
628
631 SPIRVTypeInst SpvType,
632 const SPIRVInstrInfo &TII,
633 bool ZeroAsNull) {
634 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
635 assert(LLVMTy->isVectorTy());
636 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
637 Type *LLVMBaseTy = LLVMVecTy->getElementType();
638 assert(LLVMBaseTy->isFloatingPointTy());
639 auto *ConstVal = ConstantFP::get(LLVMBaseTy, Val);
640 auto *ConstVec =
641 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstVal);
642 unsigned BW = getScalarOrVectorBitWidth(SpvType);
643 return getOrCreateCompositeOrNull(ConstVal, I, SpvType, TII, ConstVec, BW,
645 ZeroAsNull);
646}
647
649 uint64_t Val, size_t Num, MachineInstr &I, SPIRVTypeInst SpvType,
650 const SPIRVInstrInfo &TII) {
651 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
652 assert(LLVMTy->isArrayTy());
653 const ArrayType *LLVMArrTy = cast<ArrayType>(LLVMTy);
654 Type *LLVMBaseTy = LLVMArrTy->getElementType();
655 Constant *CI = ConstantInt::get(LLVMBaseTy, Val);
656 SPIRVTypeInst SpvBaseTy =
658 unsigned BW = getScalarOrVectorBitWidth(SpvBaseTy);
659 // The following is reasonably unique key that is better that [Val]. The naive
660 // alternative would be something along the lines of:
661 // SmallVector<Constant *> NumCI(Num, CI);
662 // Constant *UniqueKey =
663 // ConstantArray::get(const_cast<ArrayType*>(LLVMArrTy), NumCI);
664 // that would be a truly unique but dangerous key, because it could lead to
665 // the creation of constants of arbitrary length (that is, the parameter of
666 // memset) which were missing in the original module.
667 Type *I64Ty = Type::getInt64Ty(LLVMBaseTy->getContext());
669 {PoisonValue::get(const_cast<ArrayType *>(LLVMArrTy)),
670 ConstantInt::get(LLVMBaseTy, Val), ConstantInt::get(I64Ty, Num)});
671 return getOrCreateCompositeOrNull(CI, I, SpvType, TII, UniqueKey, BW,
672 LLVMArrTy->getNumElements());
673}
674
675Register SPIRVGlobalRegistry::getOrCreateIntCompositeOrNull(
676 uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType,
677 bool EmitIR, Constant *CA, unsigned BitWidth, unsigned ElemCnt) {
678 if (Register R = find(CA, CurMF); R.isValid())
679 return R;
680
681 Register ElemReg;
682 if (Val || EmitIR) {
683 SPIRVTypeInst SpvBaseType =
685 ElemReg = buildConstantInt(Val, MIRBuilder, SpvBaseType, EmitIR);
686 }
687 LLT LLTy = EmitIR ? LLT::fixed_vector(ElemCnt, BitWidth) : LLT::scalar(64);
688 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
689 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
690 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
691
692 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
693 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
694 if (EmitIR)
695 return MIRBuilder.buildSplatBuildVector(Res, ElemReg);
696
697 if (Val) {
698 auto MIB = MIRBuilder.buildInstr(SPIRV::OpConstantComposite)
699 .addDef(Res)
700 .addUse(getSPIRVTypeID(SpvType));
701 for (unsigned i = 0; i < ElemCnt; ++i)
702 MIB.addUse(ElemReg);
703 return MIB;
704 }
705
706 return MIRBuilder.buildInstr(SPIRV::OpConstantNull)
707 .addDef(Res)
708 .addUse(getSPIRVTypeID(SpvType));
709 });
710 add(CA, NewMI);
711 return Res;
712}
713
715 uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType,
716 bool EmitIR) {
717 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
718 assert(LLVMTy->isVectorTy());
719 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
720 Type *LLVMBaseTy = LLVMVecTy->getElementType();
721 const auto ConstInt = ConstantInt::get(LLVMBaseTy, Val);
722 auto ConstVec =
723 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstInt);
724 unsigned BW = getScalarOrVectorBitWidth(SpvType);
725 return getOrCreateIntCompositeOrNull(
726 Val, MIRBuilder, SpvType, EmitIR, ConstVec, BW,
728}
729
732 SPIRVTypeInst SpvType) {
733 const Type *Ty = getTypeForSPIRVType(SpvType);
734 unsigned AddressSpace = typeToAddressSpace(Ty);
735 Type *ElemTy = ::getPointeeType(Ty);
736 assert(ElemTy);
739 Register Res = find(CP, CurMF);
740 if (Res.isValid())
741 return Res;
742
744 Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
745 CurMF->getRegInfo().setRegClass(Res, &SPIRV::pIDRegClass);
746 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
747
748 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
749 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
750 return MIRBuilder.buildInstr(SPIRV::OpConstantNull)
751 .addDef(Res)
752 .addUse(getSPIRVTypeID(SpvType));
753 });
754 add(CP, NewMI);
755 return Res;
756}
757
760 unsigned Param, unsigned FilerMode,
761 MachineIRBuilder &MIRBuilder) {
762 auto Sampler =
763 ResReg.isValid()
764 ? ResReg
765 : MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
766 SPIRVTypeInst TypeSampler = getOrCreateOpTypeSampler(MIRBuilder);
767 Register TypeSamplerReg = getSPIRVTypeID(TypeSampler);
768 // We cannot use createOpType() logic here, because of the
769 // GlobalISel/IRTranslator.cpp check for a tail call that expects that
770 // MIRBuilder.getInsertPt() has a previous instruction. If this constant is
771 // inserted as a result of "__translate_sampler_initializer()" this would
772 // break this IRTranslator assumption.
773 MIRBuilder.buildInstr(SPIRV::OpConstantSampler)
775 .addUse(TypeSamplerReg)
777 .addImm(Param)
778 .addImm(FilerMode);
779 return Sampler;
780}
781
784 const GlobalValue *GV, SPIRV::StorageClass::StorageClass Storage,
785 const MachineInstr *Init, bool IsConst,
786 const std::optional<SPIRV::LinkageType::LinkageType> &LinkageType,
787 MachineIRBuilder &MIRBuilder, bool IsInstSelector) {
788 const GlobalVariable *GVar = nullptr;
789 if (GV) {
791 } else {
792 // If GV is not passed explicitly, use the name to find or construct
793 // the global variable.
794 Module *M = MIRBuilder.getMF().getFunction().getParent();
795 GVar = M->getGlobalVariable(Name);
796 if (GVar == nullptr) {
797 const Type *Ty = getTypeForSPIRVType(BaseType); // TODO: check type.
798 if (auto *TPTy = dyn_cast<TypedPointerType>(Ty))
799 Ty = PointerType::get(M->getContext(), TPTy->getAddressSpace());
800 // Module takes ownership of the global var.
801 GVar = new GlobalVariable(*M, const_cast<Type *>(Ty), false,
803 Twine(Name));
804 }
805 GV = GVar;
806 }
807
808 const MachineFunction *MF = &MIRBuilder.getMF();
809 Register Reg = find(GVar, MF);
810 if (Reg.isValid()) {
811 if (Reg != ResVReg)
812 MIRBuilder.buildCopy(ResVReg, Reg);
813 return ResVReg;
814 }
815
816 // Emit the OpVariable into the entry block to ensure the def dominates
817 // all uses across all MBBs.
818 MachineBasicBlock &EntryBB = MIRBuilder.getMF().front();
819 MachineIRBuilder GVBuilder(MIRBuilder.getState());
820 if (&GVBuilder.getMBB() != &EntryBB)
821 GVBuilder.setInsertPt(EntryBB, EntryBB.getFirstTerminator());
822
823 // Pointers to opaque types stay typed even with the extension on, so emit the
824 // untyped variant only when the result is actually an untyped pointer.
825 const bool UseUntypedPointers =
826 BaseType->getOpcode() == SPIRV::OpTypeUntypedPointerKHR;
827 const unsigned VariableOpcode =
828 UseUntypedPointers ? SPIRV::OpUntypedVariableKHR : SPIRV::OpVariable;
829
830 auto MIB = GVBuilder.buildInstr(VariableOpcode)
831 .addDef(ResVReg)
833 .addImm(static_cast<uint32_t>(Storage));
834
835 // OpUntypedVariableKHR takes an extra Data Type operand right after the
836 // storage class, holding the global's value type.
837 if (UseUntypedPointers) {
839 if (!DataType)
840 DataType = getOrCreateSPIRVType(GV->getValueType(), GVBuilder,
841 SPIRV::AccessQualifier::ReadWrite,
842 /*EmitIR=*/false);
843 if (!DataType) {
844 const Function &F = MIRBuilder.getMF().getFunction();
845 F.getContext().diagnose(DiagnosticInfoUnsupported(
846 F,
847 "Could not deduce the data type of untyped global variable '" +
848 GVar->getName() + "'",
849 DebugLoc(), DS_Error));
850 // Recover with i8 so that codegen can finish and report the error.
851 DataType =
852 getOrCreateSPIRVType(Type::getInt8Ty(F.getContext()), GVBuilder,
853 SPIRV::AccessQualifier::ReadWrite,
854 /*EmitIR=*/false);
855 }
856 MIB.addUse(getSPIRVTypeID(DataType));
857 }
858
859 if (Init)
860 MIB.addUse(Init->getOperand(0).getReg());
861 // ISel may introduce a new register on this step, so we need to add it to
862 // DT and correct its type avoiding fails on the next stage.
863 if (IsInstSelector) {
864 constrainSelectedInstRegOperands(MIB);
865 }
866 add(GVar, MIB);
867
868 Reg = MIB->getOperand(0).getReg();
869 addGlobalObject(GVar, MF, Reg);
870
871 // Set to Reg the same type as ResVReg has.
872 auto MRI = MIRBuilder.getMRI();
873 if (Reg != ResVReg) {
874 LLT RegLLTy =
875 LLT::pointer(MRI->getType(ResVReg).getAddressSpace(), getPointerSize());
876 MRI->setType(Reg, RegLLTy);
877 assignSPIRVTypeToVReg(BaseType, Reg, MIRBuilder.getMF());
878 } else {
879 // Our knowledge about the type may be updated.
880 // If that's the case, we need to update a type
881 // associated with the register.
882 SPIRVTypeInst DefType = getSPIRVTypeForVReg(ResVReg);
883 if (!DefType || DefType != SPIRVTypeInst(BaseType))
884 assignSPIRVTypeToVReg(BaseType, Reg, MIRBuilder.getMF());
885 }
886
887 // If it's a global variable with name, output OpName for it.
888 if (GVar && GVar->hasName())
889 buildOpName(Reg, GVar->getName(), MIRBuilder);
890
891 // Output decorations for the GV.
892 // TODO: maybe move to GenerateDecorations pass.
893 const SPIRVSubtarget &ST =
895 if (IsConst && !ST.isShader())
896 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::Constant, {});
897
898 if (GVar && GVar->getAlign().valueOrOne().value() != 1 && !ST.isShader()) {
899 unsigned Alignment = (unsigned)GVar->getAlign().valueOrOne().value();
900 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::Alignment, {Alignment});
901 }
902
903 if (LinkageType)
904 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
905 {static_cast<uint32_t>(*LinkageType)}, Name);
906
907 SPIRV::BuiltIn::BuiltIn BuiltInId;
908 if (getSpirvBuiltInIdByName(Name, BuiltInId))
909 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::BuiltIn,
910 {static_cast<uint32_t>(BuiltInId)});
911
912 // If it's a global variable with "spirv.Decorations" metadata node
913 // recognize it as a SPIR-V friendly LLVM IR and parse "spirv.Decorations"
914 // arguments.
915 MDNode *GVarMD = nullptr;
916 if (GVar && (GVarMD = GVar->getMetadata("spirv.Decorations")) != nullptr)
917 buildOpSpirvDecorations(Reg, MIRBuilder, GVarMD, ST);
918
919 return Reg;
920}
921
922// Returns a name based on the Type. Notes that this does not look at
923// decorations, and will return the same string for two types that are the same
924// except for decorations.
926 SPIRVTypeInst VarType, uint32_t Set, uint32_t Binding, StringRef Name,
927 MachineIRBuilder &MIRBuilder) {
928 Register VarReg =
929 MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
930
931 buildGlobalVariable(VarReg, VarType, Name, nullptr,
932 getPointerStorageClass(VarType), nullptr, false,
933 std::nullopt, MIRBuilder, false);
934
935 buildOpDecorate(VarReg, MIRBuilder, SPIRV::Decoration::DescriptorSet, {Set});
936 buildOpDecorate(VarReg, MIRBuilder, SPIRV::Decoration::Binding, {Binding});
937 return VarReg;
938}
939
940// TODO: Double check the calls to getOpTypeArray to make sure that `ElemType`
941// is explicitly laid out when required.
942SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeArray(uint32_t NumElems,
943 SPIRVTypeInst ElemType,
944 MachineIRBuilder &MIRBuilder,
945 bool ExplicitLayoutRequired,
946 bool EmitIR) {
947 assert((ElemType->getOpcode() != SPIRV::OpTypeVoid) &&
948 "Invalid array element type");
949 SPIRVTypeInst SpvTypeInt32 = getOrCreateSPIRVIntegerType(32, MIRBuilder);
950 SPIRVTypeInst ArrayType = nullptr;
951 const SPIRVSubtarget &ST =
953 if (NumElems != 0) {
954 Register NumElementsVReg =
955 buildConstantInt(NumElems, MIRBuilder, SpvTypeInt32, EmitIR);
956 ArrayType = createConstOrTypeAtFunctionEntry(
957 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
958 return MIRBuilder.buildInstr(SPIRV::OpTypeArray)
959 .addDef(createTypeVReg(MIRBuilder))
960 .addUse(getSPIRVTypeID(ElemType))
961 .addUse(NumElementsVReg);
962 });
963 } else if (ST.getTargetTriple().getVendor() == Triple::VendorType::AMD) {
964 // We set the array size to the token UINT64_MAX value, which is generally
965 // illegal (the maximum legal size is 61-bits) for the foreseeable future.
966 SPIRVTypeInst SpvTypeInt64 = getOrCreateSPIRVIntegerType(64, MIRBuilder);
967 Register NumElementsVReg =
968 buildConstantInt(UINT64_MAX, MIRBuilder, SpvTypeInt64, EmitIR);
969 ArrayType = createConstOrTypeAtFunctionEntry(
970 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
971 return MIRBuilder.buildInstr(SPIRV::OpTypeArray)
972 .addDef(createTypeVReg(MIRBuilder))
973 .addUse(getSPIRVTypeID(ElemType))
974 .addUse(NumElementsVReg);
975 });
976 } else {
977 if (!ST.isShader()) {
979 "Runtime arrays are not allowed in non-shader "
980 "SPIR-V modules");
981 return nullptr;
982 }
983 ArrayType = createConstOrTypeAtFunctionEntry(
984 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
985 return MIRBuilder.buildInstr(SPIRV::OpTypeRuntimeArray)
986 .addDef(createTypeVReg(MIRBuilder))
987 .addUse(getSPIRVTypeID(ElemType));
988 });
989 }
990
991 if (ExplicitLayoutRequired && !isResourceType(ElemType)) {
992 Type *ET = const_cast<Type *>(getTypeForSPIRVType(ElemType));
993 addArrayStrideDecorations(ArrayType->defs().begin()->getReg(), ET,
994 MIRBuilder);
995 }
996
997 return ArrayType;
998}
999
1001SPIRVGlobalRegistry::getOpTypeOpaque(const StructType *Ty,
1002 MachineIRBuilder &MIRBuilder) {
1003 assert(Ty->hasName());
1004 StringRef Name = Ty->hasName() ? Ty->getName() : "";
1005 Register ResVReg = createTypeVReg(MIRBuilder);
1006 return createConstOrTypeAtFunctionEntry(
1007 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1008 auto MIB = MIRBuilder.buildInstr(SPIRV::OpTypeOpaque).addDef(ResVReg);
1009 addStringImm(Name, MIB);
1010 buildOpName(ResVReg, Name, MIRBuilder);
1011 return MIB;
1012 });
1013}
1014
1015SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeStruct(
1016 const StructType *Ty, MachineIRBuilder &MIRBuilder,
1017 SPIRV::AccessQualifier::AccessQualifier AccQual,
1018 StructOffsetDecorator Decorator, bool EmitIR) {
1019 Type *OriginalElementType = nullptr;
1020 uint64_t TotalSize = 0;
1021 if (matchPeeledArrayPattern(Ty, OriginalElementType, TotalSize)) {
1022 SPIRVTypeInst ElementSPIRVType = findSPIRVType(
1023 OriginalElementType, MIRBuilder, AccQual,
1024 /* ExplicitLayoutRequired= */ Decorator != nullptr, EmitIR);
1025 return getOpTypeArray(TotalSize, ElementSPIRVType, MIRBuilder,
1026 /*ExplicitLayoutRequired=*/Decorator != nullptr,
1027 EmitIR);
1028 }
1029
1030 const SPIRVSubtarget &ST =
1031 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
1032 SmallVector<Register, 4> FieldTypes;
1033 constexpr unsigned MaxWordCount = UINT16_MAX;
1034 const size_t NumElements = Ty->getNumElements();
1035
1036 size_t MaxNumElements = MaxWordCount - 2;
1037 size_t SPIRVStructNumElements = NumElements;
1038 if (NumElements > MaxNumElements) {
1039 // Do adjustments for continued instructions.
1040 SPIRVStructNumElements = MaxNumElements;
1041 MaxNumElements = MaxWordCount - 1;
1042 }
1043
1044 for (const auto &Elem : Ty->elements()) {
1045 SPIRVTypeInst ElemTy = findSPIRVType(
1046 toTypedPointer(Elem), MIRBuilder, AccQual,
1047 /* ExplicitLayoutRequired= */ Decorator != nullptr, EmitIR);
1048 assert(ElemTy && ElemTy->getOpcode() != SPIRV::OpTypeVoid &&
1049 "Invalid struct element type");
1050 FieldTypes.push_back(getSPIRVTypeID(ElemTy));
1051 }
1052 Register ResVReg = createTypeVReg(MIRBuilder);
1053 if (Ty->hasName())
1054 buildOpName(ResVReg, Ty->getName(), MIRBuilder);
1055 if (Ty->isPacked() && !ST.isShader())
1056 buildOpDecorate(ResVReg, MIRBuilder, SPIRV::Decoration::CPacked, {});
1057
1058 SPIRVTypeInst SPVType = createConstOrTypeAtFunctionEntry(
1059 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1060 auto MIBStruct =
1061 MIRBuilder.buildInstr(SPIRV::OpTypeStruct).addDef(ResVReg);
1062 for (size_t I = 0; I < SPIRVStructNumElements; ++I)
1063 MIBStruct.addUse(FieldTypes[I]);
1064 for (size_t I = SPIRVStructNumElements; I < NumElements;
1065 I += MaxNumElements) {
1066 auto MIBCont =
1067 MIRBuilder.buildInstr(SPIRV::OpTypeStructContinuedINTEL);
1068 for (size_t J = I; J < std::min(I + MaxNumElements, NumElements); ++J)
1069 MIBCont.addUse(FieldTypes[J]);
1070 }
1071 return MIBStruct;
1072 });
1073
1074 if (Decorator)
1075 Decorator(SPVType->defs().begin()->getReg());
1076
1077 return SPVType;
1078}
1079
1080SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateSpecialType(
1081 const Type *Ty, MachineIRBuilder &MIRBuilder,
1082 SPIRV::AccessQualifier::AccessQualifier AccQual) {
1083 assert(isSpecialOpaqueType(Ty) && "Not a special opaque builtin type");
1084 return SPIRV::lowerBuiltinType(Ty, AccQual, MIRBuilder, this);
1085}
1086
1087SPIRVTypeInst SPIRVGlobalRegistry::getOpTypePointer(
1088 SPIRV::StorageClass::StorageClass SC, SPIRVTypeInst ElemType,
1089 MachineIRBuilder &MIRBuilder, Register Reg) {
1090 // Check if we should use untyped pointers.
1091 const SPIRVSubtarget &ST =
1092 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
1093 if (shouldUseUntypedPointer(ElemType, ST))
1094 return getOrCreateSPIRVUntypedPointerType(SC, MIRBuilder);
1095
1096 if (!Reg.isValid())
1097 Reg = createTypeVReg(MIRBuilder);
1098
1099 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
1100 &MIRBuilder) {
1101 return MIRBuilder.buildInstr(SPIRV::OpTypePointer)
1102 .addDef(Reg)
1103 .addImm(static_cast<uint32_t>(SC))
1104 .addUse(getSPIRVTypeID(ElemType));
1105 });
1106}
1107
1108SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeFunction(
1109 const FunctionType *Ty, SPIRVTypeInst RetType,
1110 const SmallVectorImpl<SPIRVTypeInst> &ArgTypes,
1111 MachineIRBuilder &MIRBuilder) {
1112 const SPIRVSubtarget *ST =
1113 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
1114 if (Ty->isVarArg() && ST->isShader()) {
1115 Function &Fn = MIRBuilder.getMF().getFunction();
1116 Ty->getContext().diagnose(DiagnosticInfoUnsupported(
1117 Fn, "SPIR-V shaders do not support variadic functions",
1118 MIRBuilder.getDebugLoc()));
1119 }
1120 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
1121 &MIRBuilder) {
1122 auto MIB = MIRBuilder.buildInstr(SPIRV::OpTypeFunction)
1123 .addDef(createTypeVReg(MIRBuilder))
1124 .addUse(getSPIRVTypeID(RetType));
1125 for (auto &ArgType : ArgTypes)
1126 MIB.addUse(getSPIRVTypeID(ArgType));
1127 return MIB;
1128 });
1129}
1130
1132 const Type *Ty, SPIRVTypeInst RetType,
1133 const SmallVectorImpl<SPIRVTypeInst> &ArgTypes,
1134 MachineIRBuilder &MIRBuilder) {
1135 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
1136 return MI;
1137 const MachineInstr *NewMI =
1138 getOpTypeFunction(cast<FunctionType>(Ty), RetType, ArgTypes, MIRBuilder);
1139 add(Ty, false, NewMI);
1140 return finishCreatingSPIRVType(Ty, NewMI);
1141}
1142
1143SPIRVTypeInst SPIRVGlobalRegistry::findSPIRVType(
1144 const Type *Ty, MachineIRBuilder &MIRBuilder,
1145 SPIRV::AccessQualifier::AccessQualifier AccQual,
1146 bool ExplicitLayoutRequired, bool EmitIR) {
1147 // Treat <1 x T> as T.
1148 if (auto *FVT = dyn_cast<FixedVectorType>(Ty);
1149 FVT && FVT->getNumElements() == 1)
1150 return findSPIRVType(FVT->getElementType(), MIRBuilder, AccQual,
1151 ExplicitLayoutRequired, EmitIR);
1152 Ty = adjustIntTypeByWidth(Ty);
1153 // TODO: findMI needs to know if a layout is required.
1154 if (const MachineInstr *MI =
1155 findMI(Ty, ExplicitLayoutRequired, &MIRBuilder.getMF()))
1156 return MI;
1157 if (auto It = ForwardPointerTypes.find(Ty); It != ForwardPointerTypes.end())
1158 return It->second;
1159 return restOfCreateSPIRVType(Ty, MIRBuilder, AccQual, ExplicitLayoutRequired,
1160 EmitIR);
1161}
1162
1164 assert(SpirvType && "Attempting to get type id for nullptr type.");
1165 if (SpirvType->getOpcode() == SPIRV::OpTypeForwardPointer ||
1166 SpirvType->getOpcode() == SPIRV::OpTypeStructContinuedINTEL)
1167 return SpirvType->uses().begin()->getReg();
1168 return SpirvType->defs().begin()->getReg();
1169}
1170
1171// We need to use a new LLVM integer type if there is a mismatch between
1172// number of bits in LLVM and SPIRV integer types to let DuplicateTracker
1173// ensure uniqueness of a SPIRV type by the corresponding LLVM type. Without
1174// such an adjustment SPIRVGlobalRegistry::getOpTypeInt() could create the
1175// same "OpTypeInt 8" type for a series of LLVM integer types with number of
1176// bits less than 8. This would lead to duplicate type definitions
1177// eventually due to the method that DuplicateTracker utilizes to reason
1178// about uniqueness of type records.
1179const Type *SPIRVGlobalRegistry::adjustIntTypeByWidth(const Type *Ty) const {
1180 if (auto IType = dyn_cast<IntegerType>(Ty)) {
1181 unsigned SrcBitWidth = IType->getBitWidth();
1182 if (SrcBitWidth > 1) {
1183 unsigned BitWidth = adjustOpTypeIntWidth(SrcBitWidth);
1184 // Maybe change source LLVM type to keep DuplicateTracker consistent.
1185 if (SrcBitWidth != BitWidth)
1186 Ty = IntegerType::get(Ty->getContext(), BitWidth);
1187 }
1188 }
1189 return Ty;
1190}
1191
1192SPIRVTypeInst SPIRVGlobalRegistry::createSPIRVType(
1193 const Type *Ty, MachineIRBuilder &MIRBuilder,
1194 SPIRV::AccessQualifier::AccessQualifier AccQual,
1195 bool ExplicitLayoutRequired, bool EmitIR) {
1196 if (isSpecialOpaqueType(Ty))
1197 return getOrCreateSpecialType(Ty, MIRBuilder, AccQual);
1198
1199 if (const MachineInstr *MI =
1200 findMI(Ty, ExplicitLayoutRequired, &MIRBuilder.getMF()))
1201 return MI;
1202
1203 if (auto IType = dyn_cast<IntegerType>(Ty)) {
1204 const unsigned Width = IType->getBitWidth();
1205 return Width == 1 ? getOpTypeBool(MIRBuilder)
1206 : getOpTypeInt(Width, MIRBuilder, false);
1207 }
1208 if (Ty->isFloatingPointTy()) {
1209 if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty())
1210 llvm::reportFatalUsageError("fp128 is not supported in SPIR-V");
1211 if (Ty->isBFloatTy()) {
1212 return getOpTypeFloat(Ty->getPrimitiveSizeInBits(), MIRBuilder,
1213 SPIRV::FPEncoding::BFloat16KHR);
1214 } else {
1215 return getOpTypeFloat(Ty->getPrimitiveSizeInBits(), MIRBuilder);
1216 }
1217 }
1218 if (Ty->isVoidTy())
1219 return getOpTypeVoid(MIRBuilder);
1220 if (Ty->isVectorTy()) {
1221 SPIRVTypeInst El =
1222 findSPIRVType(cast<FixedVectorType>(Ty)->getElementType(), MIRBuilder,
1223 AccQual, ExplicitLayoutRequired, EmitIR);
1224 return getOpTypeVector(cast<FixedVectorType>(Ty)->getNumElements(), El,
1225 MIRBuilder);
1226 }
1227 if (Ty->isArrayTy()) {
1228 SPIRVTypeInst El = findSPIRVType(Ty->getArrayElementType(), MIRBuilder,
1229 AccQual, ExplicitLayoutRequired, EmitIR);
1230 return getOpTypeArray(Ty->getArrayNumElements(), El, MIRBuilder,
1231 ExplicitLayoutRequired, EmitIR);
1232 }
1233 if (auto SType = dyn_cast<StructType>(Ty)) {
1234 if (SType->isOpaque())
1235 return getOpTypeOpaque(SType, MIRBuilder);
1236
1237 StructOffsetDecorator Decorator = nullptr;
1238 if (ExplicitLayoutRequired) {
1239 Decorator = [&MIRBuilder, SType, this](Register Reg) {
1240 addStructOffsetDecorations(Reg, const_cast<StructType *>(SType),
1241 MIRBuilder);
1242 };
1243 }
1244 return getOpTypeStruct(SType, MIRBuilder, AccQual, std::move(Decorator),
1245 EmitIR);
1246 }
1247 if (auto FType = dyn_cast<FunctionType>(Ty)) {
1248 SPIRVTypeInst RetTy =
1249 findSPIRVType(FType->getReturnType(), MIRBuilder, AccQual,
1250 ExplicitLayoutRequired, EmitIR);
1252 for (const auto &ParamTy : FType->params())
1253 ParamTypes.push_back(findSPIRVType(ParamTy, MIRBuilder, AccQual,
1254 ExplicitLayoutRequired, EmitIR));
1255 return getOpTypeFunction(FType, RetTy, ParamTypes, MIRBuilder);
1256 }
1257
1258 unsigned AddrSpace = typeToAddressSpace(Ty);
1259
1260 // Get access to information about available extensions
1261 const SPIRVSubtarget *ST =
1262 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
1263 auto SC = addressSpaceToStorageClass(AddrSpace, *ST);
1264
1265 SPIRVTypeInst SpvElementType = nullptr;
1266 Type *ElemTy = ::getPointeeType(Ty);
1267 if (ElemTy && isa<FunctionType>(ElemTy) &&
1268 !ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
1269 ElemTy = nullptr;
1270 if (ElemTy)
1271 SpvElementType = getOrCreateSPIRVType(ElemTy, MIRBuilder, AccQual, EmitIR);
1272 else
1273 SpvElementType = getOrCreateSPIRVIntegerType(8, MIRBuilder);
1274
1275 if (!ElemTy) {
1276 ElemTy = Type::getInt8Ty(MIRBuilder.getContext());
1277 }
1278
1279 // If we have forward pointer associated with this type, use its register
1280 // operand to create OpTypePointer.
1281 if (auto It = ForwardPointerTypes.find(Ty); It != ForwardPointerTypes.end()) {
1282 Register Reg = getSPIRVTypeID(It->second);
1283 // TODO: what does getOpTypePointer do?
1284 return getOpTypePointer(SC, SpvElementType, MIRBuilder, Reg);
1285 }
1286
1287 return getOrCreateSPIRVPointerType(ElemTy, MIRBuilder, SC);
1288}
1289
1290SPIRVTypeInst SPIRVGlobalRegistry::restOfCreateSPIRVType(
1291 const Type *Ty, MachineIRBuilder &MIRBuilder,
1292 SPIRV::AccessQualifier::AccessQualifier AccessQual,
1293 bool ExplicitLayoutRequired, bool EmitIR) {
1294 // TODO: Could this create a problem if one requires an explicit layout, and
1295 // the next time it does not?
1296 if (TypesInProcessing.count(Ty) && !isPointerTyOrWrapper(Ty))
1297 return nullptr;
1298 TypesInProcessing.insert(Ty);
1299 SPIRVTypeInst SpirvType = createSPIRVType(Ty, MIRBuilder, AccessQual,
1300 ExplicitLayoutRequired, EmitIR);
1301 TypesInProcessing.erase(Ty);
1302 VRegToTypeMap[&MIRBuilder.getMF()][getSPIRVTypeID(SpirvType)] = SpirvType;
1303
1304 // TODO: We could end up with two SPIR-V types pointing to the same llvm type.
1305 // Is that a problem?
1306 SPIRVToLLVMType[SpirvType] = unifyPtrType(Ty);
1307
1308 if (SpirvType->getOpcode() == SPIRV::OpTypeForwardPointer ||
1309 findMI(Ty, false, &MIRBuilder.getMF()) || isSpecialOpaqueType(Ty))
1310 return SpirvType;
1311
1312 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
1313 ExtTy && isTypedPointerWrapper(ExtTy))
1314 add(ExtTy->getTypeParameter(0), ExtTy->getIntParameter(0), SpirvType);
1315 else if (!isPointerTy(Ty))
1316 add(Ty, ExplicitLayoutRequired, SpirvType);
1317 else if (isTypedPointerTy(Ty))
1318 add(cast<TypedPointerType>(Ty)->getElementType(),
1319 getPointerAddressSpace(Ty), SpirvType);
1320 else
1322 getPointerAddressSpace(Ty), SpirvType);
1323 return SpirvType;
1324}
1325
1328 const MachineFunction *MF) const {
1329 auto t = VRegToTypeMap.find(MF ? MF : CurMF);
1330 if (t != VRegToTypeMap.end()) {
1331 auto tt = t->second.find(VReg);
1332 if (tt != t->second.end())
1333 return tt->second;
1334 }
1335 return nullptr;
1336}
1337
1339 MachineFunction *MF) {
1340 if (!MF)
1341 MF = CurMF;
1342 MachineInstr *Instr = getVRegDef(MF->getRegInfo(), VReg);
1343 return getSPIRVTypeForVReg(Instr->getOperand(1).getReg(), MF);
1344}
1345
1347 const Type *Ty, MachineIRBuilder &MIRBuilder,
1348 SPIRV::AccessQualifier::AccessQualifier AccessQual,
1349 bool ExplicitLayoutRequired, bool EmitIR) {
1350 // SPIR-V doesn't support single-element vectors. Treat <1 x T> as T.
1351 if (auto *FVT = dyn_cast<FixedVectorType>(Ty);
1352 FVT && FVT->getNumElements() == 1)
1353 return getOrCreateSPIRVType(FVT->getElementType(), MIRBuilder, AccessQual,
1354 ExplicitLayoutRequired, EmitIR);
1355 const MachineFunction *MF = &MIRBuilder.getMF();
1356 Register Reg;
1357 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
1358 ExtTy && isTypedPointerWrapper(ExtTy))
1359 Reg = find(ExtTy->getTypeParameter(0), ExtTy->getIntParameter(0), MF);
1360 else if (!isPointerTy(Ty))
1361 Reg = find(Ty = adjustIntTypeByWidth(Ty), ExplicitLayoutRequired, MF);
1362 else if (isTypedPointerTy(Ty))
1363 Reg = find(cast<TypedPointerType>(Ty)->getElementType(),
1364 getPointerAddressSpace(Ty), MF);
1365 else
1366 Reg = find(Type::getInt8Ty(MIRBuilder.getMF().getFunction().getContext()),
1367 getPointerAddressSpace(Ty), MF);
1368 if (Reg.isValid() && !isSpecialOpaqueType(Ty))
1369 return getSPIRVTypeForVReg(Reg);
1370
1371 TypesInProcessing.clear();
1372 SPIRVTypeInst STy = restOfCreateSPIRVType(Ty, MIRBuilder, AccessQual,
1373 ExplicitLayoutRequired, EmitIR);
1374 // Create normal pointer types for the corresponding OpTypeForwardPointers.
1375 for (auto &CU : ForwardPointerTypes) {
1376 // Pointer type themselves do not require an explicit layout. The types
1377 // they pointer to might, but that is taken care of when creating the type.
1378 bool PtrNeedsLayout = false;
1379 const Type *Ty2 = CU.first;
1380 SPIRVTypeInst STy2 = CU.second;
1381 if ((Reg = find(Ty2, PtrNeedsLayout, MF)).isValid())
1382 STy2 = getSPIRVTypeForVReg(Reg);
1383 else
1384 STy2 = restOfCreateSPIRVType(Ty2, MIRBuilder, AccessQual, PtrNeedsLayout,
1385 EmitIR);
1386 if (Ty == Ty2)
1387 STy = STy2;
1388 }
1389 ForwardPointerTypes.clear();
1390 return STy;
1391}
1392
1394 unsigned TypeOpcode) const {
1396 assert(Type && "isScalarOfType VReg has no type assigned");
1397 return Type->getOpcode() == TypeOpcode;
1398}
1399
1401 unsigned TypeOpcode) const {
1403 assert(Type && "isScalarOrVectorOfType VReg has no type assigned");
1404 if (Type->getOpcode() == TypeOpcode)
1405 return true;
1406 if (Type->getOpcode() == SPIRV::OpTypeVector) {
1407 Register ScalarTypeVReg = Type->getOperand(1).getReg();
1408 SPIRVTypeInst ScalarType = getSPIRVTypeForVReg(ScalarTypeVReg);
1409 return ScalarType->getOpcode() == TypeOpcode;
1410 }
1411 return false;
1412}
1413
1415 switch (Type->getOpcode()) {
1416 case SPIRV::OpTypeImage:
1417 case SPIRV::OpTypeSampler:
1418 case SPIRV::OpTypeSampledImage:
1419 return true;
1420 case SPIRV::OpTypeStruct:
1421 return hasBlockDecoration(Type);
1422 default:
1423 return false;
1424 }
1425 return false;
1426}
1427unsigned
1431
1432unsigned
1434 if (!Type)
1435 return 0;
1436 return Type->getOpcode() == SPIRV::OpTypeVector
1437 ? static_cast<unsigned>(Type->getOperand(2).getImm())
1438 : 1;
1439}
1440
1443 if (!Type)
1444 return nullptr;
1445 Register ScalarReg = Type->getOpcode() == SPIRV::OpTypeVector
1446 ? Type->getOperand(1).getReg()
1447 : Type->getOperand(0).getReg();
1448 SPIRVTypeInst ScalarType = getSPIRVTypeForVReg(ScalarReg);
1449 assert(isScalarOrVectorOfType(Type->getOperand(0).getReg(),
1450 ScalarType->getOpcode()));
1451 return ScalarType;
1452}
1453
1454unsigned
1456 assert(Type && "Invalid Type pointer");
1458 if (ScalarType->getOpcode() == SPIRV::OpTypeInt ||
1459 ScalarType->getOpcode() == SPIRV::OpTypeFloat)
1460 return ScalarType->getOperand(1).getImm();
1461 if (ScalarType->getOpcode() == SPIRV::OpTypeBool)
1462 return 1;
1463 llvm_unreachable("Attempting to get bit width of non-integer/float type.");
1464}
1465
1467 SPIRVTypeInst Type) const {
1468 assert(Type && "Invalid Type pointer");
1469 unsigned NumElements = getScalarOrVectorComponentCount(Type);
1471 return ScalarType->getOpcode() == SPIRV::OpTypeInt ||
1472 ScalarType->getOpcode() == SPIRV::OpTypeFloat
1473 ? NumElements * ScalarType->getOperand(1).getImm()
1474 : 0;
1475}
1476
1478 // A function pointer has to keep its function type, which an untyped pointer
1479 // cannot express.
1480 if (ElemType && ElemType->getOpcode() == SPIRV::OpTypeFunction)
1481 return true;
1482 auto It = SPIRVToLLVMType.find(ElemType);
1483 return It != SPIRVToLLVMType.end() && It->second &&
1484 isSpecialOpaqueType(It->second);
1485}
1486
1488 SPIRVTypeInst ElemType, const SPIRVSubtarget &ST) const {
1489 // Shaders keep typed pointers, as this implementation targets compute.
1490 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_untyped_pointers) &&
1491 !ST.isShader() && !shouldKeepTypedPtrType(ElemType);
1492}
1493
1497 return ScalarType && ScalarType->getOpcode() == SPIRV::OpTypeInt ? ScalarType
1498 : nullptr;
1499}
1500
1503 return IntType && IntType->getOperand(2).getImm() != 0;
1504}
1505
1507 return PtrType && PtrType->getOpcode() == SPIRV::OpTypePointer
1508 ? getSPIRVTypeForVReg(PtrType->getOperand(2).getReg())
1509 : nullptr;
1510}
1511
1513 SPIRVTypeInst Type2) const {
1514 if (!Type1 || !Type2)
1515 return false;
1516 // Ignore difference between <1.5 and >=1.5 protocol versions:
1517 // it's valid if either Result Type or Operand is a pointer, and the other
1518 // is a pointer, an integer scalar, or an integer vector.
1519 if (Type1.isPointer() &&
1520 (Type2.isPointer() || retrieveScalarOrVectorIntType(Type2)))
1521 return true;
1522 if (Type2.isPointer() &&
1523 (Type1.isPointer() || retrieveScalarOrVectorIntType(Type1)))
1524 return true;
1525 unsigned Bits1 = getNumScalarOrVectorTotalBitWidth(Type1),
1526 Bits2 = getNumScalarOrVectorTotalBitWidth(Type2);
1527 return Bits1 > 0 && Bits1 == Bits2;
1528}
1529
1530SPIRV::StorageClass::StorageClass
1533 assert(Type && Type.isPointer() && Type->getOperand(1).isImm() &&
1534 "Pointer type is expected");
1536}
1537
1538SPIRV::StorageClass::StorageClass
1540 return static_cast<SPIRV::StorageClass::StorageClass>(
1541 Type->getOperand(1).getImm());
1542}
1543
1545 MachineIRBuilder &MIRBuilder, Type *ElemType,
1546 SPIRV::StorageClass::StorageClass SC, bool IsWritable, bool EmitIr) {
1547 auto Key = SPIRV::irhandle_vkbuffer(ElemType, SC, IsWritable);
1548 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1549 return MI;
1550
1551 bool ExplicitLayoutRequired = storageClassRequiresExplictLayout(SC);
1552 // We need to get the SPIR-V type for the element here, so we can add the
1553 // decoration to it.
1554 auto *T = StructType::create(ElemType);
1555 SPIRVTypeInst BlockType =
1556 getOrCreateSPIRVType(T, MIRBuilder, SPIRV::AccessQualifier::None,
1557 ExplicitLayoutRequired, EmitIr);
1558
1559 buildOpDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1560 SPIRV::Decoration::Block, {});
1561
1562 if (!IsWritable) {
1563 buildOpMemberDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1564 SPIRV::Decoration::NonWritable, 0, {});
1565 }
1566
1567 SPIRVTypeInst R =
1568 getOrCreateSPIRVPointerTypeInternal(BlockType, MIRBuilder, SC);
1569 add(Key, R);
1570 return R;
1571}
1572
1576 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1577 return MI;
1578 auto *T = Type::getInt8Ty(MIRBuilder.getContext());
1579 SPIRVTypeInst R = getOrCreateSPIRVIntegerType(8, MIRBuilder);
1580 finishCreatingSPIRVType(T, R);
1581 add(Key, R);
1582 return R;
1583}
1584
1586 MachineIRBuilder &MIRBuilder, Type *T) {
1587 const auto SC = SPIRV::StorageClass::PushConstant;
1588
1589 auto Key = SPIRV::irhandle_vkbuffer(T, SC, /* IsWritable= */ false);
1590 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1591 return MI;
1592
1593 // We need to get the SPIR-V type for the element here, so we can add the
1594 // decoration to it.
1596 T, MIRBuilder, SPIRV::AccessQualifier::None,
1597 /* ExplicitLayoutRequired= */ true, /* EmitIr= */ false);
1598
1599 buildOpDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1600 SPIRV::Decoration::Block, {});
1601 SPIRVTypeInst R = BlockType;
1602 add(Key, R);
1603 return R;
1604}
1605
1607 MachineIRBuilder &MIRBuilder, const TargetExtType *T, bool EmitIr) {
1608 auto Key = SPIRV::handle(T);
1609 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1610 return MI;
1611
1612 StructType *ST = cast<StructType>(T->getTypeParameter(0));
1613 ArrayRef<uint32_t> Offsets = T->int_params().slice(1);
1614 assert(ST->getNumElements() == Offsets.size());
1615
1616 StructOffsetDecorator Decorator = [&MIRBuilder, &Offsets](Register Reg) {
1617 for (uint32_t I = 0; I < Offsets.size(); ++I) {
1618 buildOpMemberDecorate(Reg, MIRBuilder, SPIRV::Decoration::Offset, I,
1619 {Offsets[I]});
1620 }
1621 };
1622
1623 // We need a new OpTypeStruct instruction because decorations will be
1624 // different from a struct with an explicit layout created from a different
1625 // entry point.
1626 SPIRVTypeInst SPIRVStructType =
1627 getOpTypeStruct(ST, MIRBuilder, SPIRV::AccessQualifier::None,
1628 std::move(Decorator), EmitIr);
1629 add(Key, SPIRVStructType);
1630 return SPIRVStructType;
1631}
1632
1634 const TargetExtType *ExtensionType,
1635 const SPIRV::AccessQualifier::AccessQualifier Qualifier,
1636 MachineIRBuilder &MIRBuilder) {
1637 assert(ExtensionType->getNumTypeParameters() == 1 &&
1638 "SPIR-V image builtin type must have sampled type parameter!");
1639 const SPIRVTypeInst SampledType =
1640 getOrCreateSPIRVType(ExtensionType->getTypeParameter(0), MIRBuilder,
1641 SPIRV::AccessQualifier::ReadWrite, true);
1642 assert((ExtensionType->getNumIntParameters() == 7 ||
1643 ExtensionType->getNumIntParameters() == 6) &&
1644 "Invalid number of parameters for SPIR-V image builtin!");
1645
1646 SPIRV::AccessQualifier::AccessQualifier accessQualifier =
1647 SPIRV::AccessQualifier::None;
1648 if (ExtensionType->getNumIntParameters() == 7) {
1649 accessQualifier = Qualifier == SPIRV::AccessQualifier::WriteOnly
1650 ? SPIRV::AccessQualifier::WriteOnly
1651 : SPIRV::AccessQualifier::AccessQualifier(
1652 ExtensionType->getIntParameter(6));
1653 }
1654
1655 // Create or get an existing type from GlobalRegistry.
1656 SPIRVTypeInst R = getOrCreateOpTypeImage(
1657 MIRBuilder, SampledType,
1658 SPIRV::Dim::Dim(ExtensionType->getIntParameter(0)),
1659 ExtensionType->getIntParameter(1), ExtensionType->getIntParameter(2),
1660 ExtensionType->getIntParameter(3), ExtensionType->getIntParameter(4),
1661 SPIRV::ImageFormat::ImageFormat(ExtensionType->getIntParameter(5)),
1662 accessQualifier);
1663 SPIRVToLLVMType[R] = ExtensionType;
1664 return R;
1665}
1666
1667SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateOpTypeImage(
1668 MachineIRBuilder &MIRBuilder, SPIRVTypeInst SampledType,
1669 SPIRV::Dim::Dim Dim, uint32_t Depth, uint32_t Arrayed,
1670 uint32_t Multisampled, uint32_t Sampled,
1671 SPIRV::ImageFormat::ImageFormat ImageFormat,
1672 SPIRV::AccessQualifier::AccessQualifier AccessQual) {
1673 auto Key = SPIRV::irhandle_image(SPIRVToLLVMType.lookup(SampledType), Dim,
1674 Depth, Arrayed, Multisampled, Sampled,
1675 ImageFormat, AccessQual);
1676 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1677 return MI;
1678 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1679 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1680 auto MIB =
1681 MIRBuilder.buildInstr(SPIRV::OpTypeImage)
1682 .addDef(createTypeVReg(MIRBuilder))
1683 .addUse(getSPIRVTypeID(SampledType))
1684 .addImm(Dim)
1685 .addImm(Depth) // Depth (whether or not it is a Depth image).
1686 .addImm(Arrayed) // Arrayed.
1687 .addImm(Multisampled) // Multisampled (0 = only single-sample).
1688 .addImm(Sampled) // Sampled (0 = usage known at runtime).
1689 .addImm(ImageFormat);
1690 if (AccessQual != SPIRV::AccessQualifier::None)
1691 MIB.addImm(AccessQual);
1692 return MIB;
1693 });
1694 add(Key, NewMI);
1695 return NewMI;
1696}
1697
1701 const MachineFunction *MF = &MIRBuilder.getMF();
1702 if (const MachineInstr *MI = findMI(Key, MF))
1703 return MI;
1704 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1705 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1706 return MIRBuilder.buildInstr(SPIRV::OpTypeSampler)
1707 .addDef(createTypeVReg(MIRBuilder));
1708 });
1709 add(Key, NewMI);
1710 return NewMI;
1711}
1712
1714 MachineIRBuilder &MIRBuilder,
1715 SPIRV::AccessQualifier::AccessQualifier AccessQual) {
1716 auto Key = SPIRV::irhandle_pipe(AccessQual);
1717 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1718 return MI;
1719 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1720 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1721 return MIRBuilder.buildInstr(SPIRV::OpTypePipe)
1722 .addDef(createTypeVReg(MIRBuilder))
1723 .addImm(AccessQual);
1724 });
1725 add(Key, NewMI);
1726 return NewMI;
1727}
1728
1730 MachineIRBuilder &MIRBuilder) {
1731 auto Key = SPIRV::irhandle_event();
1732 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1733 return MI;
1734 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1735 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1736 return MIRBuilder.buildInstr(SPIRV::OpTypeDeviceEvent)
1737 .addDef(createTypeVReg(MIRBuilder));
1738 });
1739 add(Key, NewMI);
1740 return NewMI;
1741}
1742
1744 SPIRVTypeInst ImageType, MachineIRBuilder &MIRBuilder) {
1746 SPIRVToLLVMType.lookup(MIRBuilder.getMF().getRegInfo().getVRegDef(
1747 ImageType->getOperand(1).getReg())),
1748 ImageType);
1749 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1750 return MI;
1751 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1752 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1753 return MIRBuilder.buildInstr(SPIRV::OpTypeSampledImage)
1754 .addDef(createTypeVReg(MIRBuilder))
1755 .addUse(getSPIRVTypeID(ImageType));
1756 });
1757 add(Key, NewMI);
1758 return NewMI;
1759}
1760
1762 MachineIRBuilder &MIRBuilder, const TargetExtType *ExtensionType,
1763 SPIRVTypeInst ElemType, uint32_t Scope, uint32_t Rows, uint32_t Columns,
1764 uint32_t Use, bool EmitIR) {
1765 if (const MachineInstr *MI =
1766 findMI(ExtensionType, false, &MIRBuilder.getMF()))
1767 return MI;
1768 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1769 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1770 SPIRVTypeInst SpvTypeInt32 =
1771 getOrCreateSPIRVIntegerType(32, MIRBuilder);
1772 const Type *ET = getTypeForSPIRVType(ElemType);
1773 if (ET->isIntegerTy() && ET->getIntegerBitWidth() == 4 &&
1775 .canUseExtension(SPIRV::Extension::SPV_INTEL_int4)) {
1776 MIRBuilder.buildInstr(SPIRV::OpCapability)
1777 .addImm(SPIRV::Capability::Int4CooperativeMatrixINTEL);
1778 }
1779 return MIRBuilder.buildInstr(SPIRV::OpTypeCooperativeMatrixKHR)
1780 .addDef(createTypeVReg(MIRBuilder))
1781 .addUse(getSPIRVTypeID(ElemType))
1782 .addUse(buildConstantInt(Scope, MIRBuilder, SpvTypeInt32, EmitIR))
1783 .addUse(buildConstantInt(Rows, MIRBuilder, SpvTypeInt32, EmitIR))
1784 .addUse(buildConstantInt(Columns, MIRBuilder, SpvTypeInt32, EmitIR))
1785 .addUse(buildConstantInt(Use, MIRBuilder, SpvTypeInt32, EmitIR));
1786 });
1787 add(ExtensionType, false, NewMI);
1788 return NewMI;
1789}
1790
1792 const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode) {
1793 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
1794 return MI;
1795 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1796 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1797 return MIRBuilder.buildInstr(Opcode).addDef(createTypeVReg(MIRBuilder));
1798 });
1799 add(Ty, false, NewMI);
1800 return NewMI;
1801}
1802
1804 const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode,
1806 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
1807 return MI;
1808 Register ResVReg = createTypeVReg(MIRBuilder);
1809 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1810 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1811 MachineInstrBuilder MIB = MIRBuilder.buildInstr(SPIRV::UNKNOWN_type)
1812 .addDef(ResVReg)
1813 .addImm(Opcode);
1814 for (MCOperand Operand : Operands) {
1815 if (Operand.isReg()) {
1816 MIB.addUse(Operand.getReg());
1817 } else if (Operand.isImm()) {
1818 MIB.addImm(Operand.getImm());
1819 }
1820 }
1821 return MIB;
1822 });
1823 add(Ty, false, NewMI);
1824 return NewMI;
1825}
1826
1827// Returns nullptr if unable to recognize SPIRV type name
1829 StringRef TypeStr, MachineIRBuilder &MIRBuilder, bool EmitIR,
1830 SPIRV::StorageClass::StorageClass SC,
1831 SPIRV::AccessQualifier::AccessQualifier AQ) {
1832 unsigned VecElts = 0;
1833 auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
1834
1835 // Parse strings representing either a SPIR-V or OpenCL builtin type.
1836 if (hasBuiltinTypePrefix(TypeStr))
1838 TypeStr.str(), MIRBuilder.getContext()),
1839 MIRBuilder, AQ, false, true);
1840
1841 // Parse type name in either "typeN" or "type vector[N]" format, where
1842 // N is the number of elements of the vector.
1843 Type *Ty;
1844
1845 Ty = parseBasicTypeName(TypeStr, Ctx);
1846 if (!Ty)
1847 // Unable to recognize SPIRV type name
1848 return nullptr;
1849
1850 SPIRVTypeInst SpirvTy = getOrCreateSPIRVType(Ty, MIRBuilder, AQ, false, true);
1851
1852 // Handle "type*" or "type* vector[N]".
1853 if (TypeStr.consume_front("*"))
1854 SpirvTy = getOrCreateSPIRVPointerType(Ty, MIRBuilder, SC);
1855
1856 // Handle "typeN*" or "type vector[N]*".
1857 bool IsPtrToVec = TypeStr.consume_back("*");
1858
1859 if (TypeStr.consume_front(" vector[")) {
1860 TypeStr = TypeStr.substr(0, TypeStr.find(']'));
1861 }
1862 TypeStr.getAsInteger(10, VecElts);
1863 if (VecElts > 0)
1864 SpirvTy = getOrCreateSPIRVVectorType(SpirvTy, VecElts, MIRBuilder, EmitIR);
1865
1866 if (IsPtrToVec)
1867 SpirvTy = getOrCreateSPIRVPointerType(SpirvTy, MIRBuilder, SC);
1868
1869 return SpirvTy;
1870}
1871
1874 MachineIRBuilder &MIRBuilder) {
1875 return getOrCreateSPIRVType(
1877 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, true);
1878}
1879
1881SPIRVGlobalRegistry::finishCreatingSPIRVType(const Type *LLVMTy,
1882 SPIRVTypeInst SpirvType) {
1883 assert(CurMF == SpirvType->getMF());
1884 VRegToTypeMap[CurMF][getSPIRVTypeID(SpirvType)] = SpirvType;
1885 SPIRVToLLVMType[SpirvType] = unifyPtrType(LLVMTy);
1886 return SpirvType;
1887}
1888
1891 const SPIRVInstrInfo &TII,
1892 unsigned SPIRVOPcode, Type *Ty) {
1893 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
1894 return MI;
1895 MachineBasicBlock &DepMBB = I.getMF()->front();
1896 MachineIRBuilder MIRBuilder(DepMBB, DepMBB.getFirstNonPHI());
1897 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1898 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1899 auto NewTypeMI = BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
1900 MIRBuilder.getDL(), TII.get(SPIRVOPcode))
1901 .addDef(createTypeVReg(CurMF->getRegInfo()))
1902 .addImm(BitWidth);
1903 // Don't add Encoding to FP type
1904 if (!Ty->isFloatTy()) {
1905 return NewTypeMI.addImm(0);
1906 } else {
1907 return NewTypeMI;
1908 }
1909 });
1910 add(Ty, false, NewMI);
1911 return finishCreatingSPIRVType(Ty, NewMI);
1912}
1913
1915 unsigned BitWidth, MachineInstr &I, const SPIRVInstrInfo &TII) {
1916 // Maybe adjust bit width to keep DuplicateTracker consistent. Without
1917 // such an adjustment SPIRVGlobalRegistry::getOpTypeInt() could create, for
1918 // example, the same "OpTypeInt 8" type for a series of LLVM integer types
1919 // with number of bits less than 8, causing duplicate type definitions.
1920 if (BitWidth > 1)
1921 BitWidth = adjustOpTypeIntWidth(BitWidth);
1922 Type *LLVMTy = IntegerType::get(CurMF->getFunction().getContext(), BitWidth);
1923 return getOrCreateSPIRVType(BitWidth, I, TII, SPIRV::OpTypeInt, LLVMTy);
1924}
1925
1927 unsigned BitWidth, MachineInstr &I, const SPIRVInstrInfo &TII) {
1928 LLVMContext &Ctx = CurMF->getFunction().getContext();
1929 Type *LLVMTy;
1930 switch (BitWidth) {
1931 case 16:
1932 LLVMTy = Type::getHalfTy(Ctx);
1933 break;
1934 case 32:
1935 LLVMTy = Type::getFloatTy(Ctx);
1936 break;
1937 case 64:
1938 LLVMTy = Type::getDoubleTy(Ctx);
1939 break;
1940 default:
1941 llvm_unreachable("Bit width is of unexpected size.");
1942 }
1943 return getOrCreateSPIRVType(BitWidth, I, TII, SPIRV::OpTypeFloat, LLVMTy);
1944}
1945
1948 bool EmitIR) {
1949 return getOrCreateSPIRVType(
1950 IntegerType::get(MIRBuilder.getMF().getFunction().getContext(), 1),
1951 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, EmitIR);
1952}
1953
1956 const SPIRVInstrInfo &TII) {
1957 Type *Ty = IntegerType::get(CurMF->getFunction().getContext(), 1);
1958 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
1959 return MI;
1960 MachineBasicBlock &DepMBB = I.getMF()->front();
1961 MachineIRBuilder MIRBuilder(DepMBB, DepMBB.getFirstNonPHI());
1962 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1963 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1964 return BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
1965 MIRBuilder.getDL(), TII.get(SPIRV::OpTypeBool))
1966 .addDef(createTypeVReg(CurMF->getRegInfo()));
1967 });
1968 add(Ty, false, NewMI);
1969 return finishCreatingSPIRVType(Ty, NewMI);
1970}
1971
1973 SPIRVTypeInst BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder,
1974 bool EmitIR) {
1975 return getOrCreateSPIRVType(
1977 NumElements),
1978 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, EmitIR);
1979}
1980
1982 SPIRVTypeInst BaseType, unsigned NumElements, MachineInstr &I,
1983 const SPIRVInstrInfo &TII) {
1984 // At this point of time all 1-element vectors are resolved. Add assertion
1985 // to fire if anything changes.
1986 assert(NumElements >= 2 && "SPIR-V vectors must have at least 2 components");
1988 const_cast<Type *>(getTypeForSPIRVType(BaseType)), NumElements);
1989 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
1990 return MI;
1991 MachineInstr *DepMI =
1992 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(BaseType));
1993 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
1994 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1995 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1996 return BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
1997 MIRBuilder.getDL(), TII.get(SPIRV::OpTypeVector))
1998 .addDef(createTypeVReg(CurMF->getRegInfo()))
2000 .addImm(NumElements);
2001 });
2002 add(Ty, false, NewMI);
2003 return finishCreatingSPIRVType(Ty, NewMI);
2004}
2005
2007 const Type *BaseType, MachineInstr &I, SPIRV::StorageClass::StorageClass SC,
2008 bool ForceTyped) {
2009 MachineIRBuilder MIRBuilder(I);
2010 return getOrCreateSPIRVPointerType(BaseType, MIRBuilder, SC, ForceTyped);
2011}
2012
2014 const Type *BaseType, MachineIRBuilder &MIRBuilder,
2015 SPIRV::StorageClass::StorageClass SC, bool ForceTyped) {
2016 if (BaseType->isFunctionTy() &&
2017 !cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget())
2018 .canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)) {
2019 const Function &F = MIRBuilder.getMF().getFunction();
2020 F.getContext().diagnose(
2022 "Function used as a data pointer requires "
2023 "SPV_INTEL_function_pointers extension",
2024 DebugLoc(), DS_Error));
2025 }
2026 // TODO: Need to check if EmitIr should always be true.
2027 SPIRVTypeInst SpirvBaseType = getOrCreateSPIRVType(
2028 BaseType, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
2030 assert(SpirvBaseType);
2031 return getOrCreateSPIRVPointerTypeInternal(SpirvBaseType, MIRBuilder, SC,
2032 ForceTyped);
2033}
2034
2036 SPIRVTypeInst PtrType, SPIRV::StorageClass::StorageClass SC,
2037 MachineInstr &I) {
2038 [[maybe_unused]] SPIRV::StorageClass::StorageClass OldSC =
2039 getPointerStorageClass(PtrType);
2042
2043 SPIRVTypeInst PointeeType = getPointeeType(PtrType);
2044 MachineIRBuilder MIRBuilder(I);
2045 return getOrCreateSPIRVPointerTypeInternal(PointeeType, MIRBuilder, SC);
2046}
2047
2050 SPIRV::StorageClass::StorageClass SC) {
2051 const Type *LLVMType = getTypeForSPIRVType(BaseType);
2053 SPIRVTypeInst R = getOrCreateSPIRVPointerType(LLVMType, MIRBuilder, SC);
2054 assert(
2055 (R->getOpcode() == SPIRV::OpTypeUntypedPointerKHR ||
2056 getPointeeType(R) == BaseType) &&
2057 "The base type was not correctly laid out for the given storage class.");
2058 return R;
2059}
2060
2061SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateSPIRVPointerTypeInternal(
2063 SPIRV::StorageClass::StorageClass SC, bool ForceTyped) {
2064 // Check if we should use untyped pointers.
2065 const SPIRVSubtarget &ST =
2066 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
2067 if (!ForceTyped && shouldUseUntypedPointer(BaseType, ST))
2068 return getOrCreateSPIRVUntypedPointerType(SC, MIRBuilder);
2069
2070 const Type *PointerElementType = getTypeForSPIRVType(BaseType);
2072 if (const MachineInstr *MI = findMI(PointerElementType, AddressSpace, CurMF))
2073 return MI;
2074 Type *Ty = TypedPointerType::get(const_cast<Type *>(PointerElementType),
2075 AddressSpace);
2076 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2077 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2078 return BuildMI(MIRBuilder.getMBB(), MIRBuilder.getInsertPt(),
2079 MIRBuilder.getDebugLoc(),
2080 MIRBuilder.getTII().get(SPIRV::OpTypePointer))
2082 .addImm(static_cast<uint32_t>(SC))
2084 });
2085 add(PointerElementType, AddressSpace, NewMI);
2086 return finishCreatingSPIRVType(Ty, NewMI);
2087}
2088
2090 SPIRV::StorageClass::StorageClass SC, MachineIRBuilder &MIRBuilder) {
2091 [[maybe_unused]] const SPIRVSubtarget &ST =
2092 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
2093 assert(ST.canUseExtension(SPIRV::Extension::SPV_KHR_untyped_pointers) &&
2094 !ST.isShader() && "Untyped pointers are not available");
2096 // Use STK_UntypedPointer handle keyed by address space only.
2098 if (const MachineInstr *MI = findMI(Handle, CurMF))
2099 return MI;
2100
2101 Type *Ty = PointerType::get(MIRBuilder.getMF().getFunction().getContext(),
2102 AddressSpace);
2103 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2104 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2105 return BuildMI(MIRBuilder.getMBB(), MIRBuilder.getInsertPt(),
2106 MIRBuilder.getDebugLoc(),
2107 MIRBuilder.getTII().get(SPIRV::OpTypeUntypedPointerKHR))
2108 .addDef(createTypeVReg(CurMF->getRegInfo()))
2109 .addImm(static_cast<uint32_t>(SC));
2110 });
2111 add(Handle, NewMI);
2112 return finishCreatingSPIRVType(Ty, NewMI);
2113}
2114
2116 SPIRVTypeInst SpvType,
2117 const SPIRVInstrInfo &TII) {
2118 UndefValue *UV =
2119 UndefValue::get(const_cast<Type *>(getTypeForSPIRVType(SpvType)));
2120 Register Res = find(UV, CurMF);
2121 if (Res.isValid())
2122 return Res;
2123
2124 LLT LLTy = LLT::scalar(64);
2125 Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
2126 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
2127 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
2128
2129 MachineInstr *DepMI =
2130 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
2131 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
2132 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2133 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2134 auto MIB = BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
2135 MIRBuilder.getDL(), TII.get(SPIRV::OpUndef))
2136 .addDef(Res)
2137 .addUse(getSPIRVTypeID(SpvType));
2138 constrainSelectedInstRegOperands(MIB);
2139 return MIB;
2140 });
2141 add(UV, NewMI);
2142 return Res;
2143}
2144
2145const TargetRegisterClass *
2147 unsigned Opcode = SpvType->getOpcode();
2148 switch (Opcode) {
2149 case SPIRV::OpTypeFloat:
2150 return &SPIRV::fIDRegClass;
2151 case SPIRV::OpTypePointer:
2152 return &SPIRV::pIDRegClass;
2153 case SPIRV::OpTypeVector: {
2155 unsigned ElemOpcode = ElemType ? ElemType->getOpcode() : 0;
2156 if (ElemOpcode == SPIRV::OpTypeFloat)
2157 return &SPIRV::vfIDRegClass;
2158 if (ElemOpcode == SPIRV::OpTypePointer)
2159 return &SPIRV::vpIDRegClass;
2160 return &SPIRV::viIDRegClass;
2161 }
2162 }
2163 return &SPIRV::iIDRegClass;
2164}
2165
2166inline unsigned getAS(SPIRVTypeInst SpvType) {
2168 static_cast<SPIRV::StorageClass::StorageClass>(
2169 SpvType->getOperand(1).getImm()));
2170}
2171
2173 unsigned Opcode = SpvType ? SpvType->getOpcode() : 0;
2174 switch (Opcode) {
2175 case SPIRV::OpTypeInt:
2176 case SPIRV::OpTypeFloat:
2177 case SPIRV::OpTypeBool:
2178 return LLT::scalar(getScalarOrVectorBitWidth(SpvType));
2179 case SPIRV::OpTypePointer:
2180 case SPIRV::OpTypeUntypedPointerKHR:
2181 return LLT::pointer(getAS(SpvType), getPointerSize());
2182 case SPIRV::OpTypeVector: {
2184 LLT ET;
2185 switch (ElemType ? ElemType->getOpcode() : 0) {
2186 case SPIRV::OpTypePointer:
2187 case SPIRV::OpTypeUntypedPointerKHR:
2188 ET = LLT::pointer(getAS(ElemType), getPointerSize());
2189 break;
2190 case SPIRV::OpTypeInt:
2191 case SPIRV::OpTypeFloat:
2192 case SPIRV::OpTypeBool:
2193 ET = LLT::scalar(getScalarOrVectorBitWidth(ElemType));
2194 break;
2195 default:
2196 ET = LLT::scalar(64);
2197 }
2199 }
2200 }
2201 return LLT::scalar(64);
2202}
2203
2204// Aliasing list MD contains several scope MD nodes whithin it. Each scope MD
2205// has a selfreference and an extra MD node for aliasing domain and also it
2206// can contain an optional string operand. Domain MD contains a self-reference
2207// with an optional string operand. Here we unfold the list, creating SPIR-V
2208// aliasing instructions.
2209// TODO: add support for an optional string operand.
2211 MachineIRBuilder &MIRBuilder, const MDNode *AliasingListMD) {
2212 if (AliasingListMD->getNumOperands() == 0)
2213 return nullptr;
2214 if (auto L = AliasInstMDMap.find(AliasingListMD); L != AliasInstMDMap.end())
2215 return L->second;
2216
2218 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
2219 for (const MDOperand &MDListOp : AliasingListMD->operands()) {
2220 if (MDNode *ScopeMD = dyn_cast<MDNode>(MDListOp)) {
2221 if (ScopeMD->getNumOperands() < 2)
2222 return nullptr;
2223 MDNode *DomainMD = dyn_cast<MDNode>(ScopeMD->getOperand(1));
2224 if (!DomainMD)
2225 return nullptr;
2226 auto *Domain = [&] {
2227 auto D = AliasInstMDMap.find(DomainMD);
2228 if (D != AliasInstMDMap.end())
2229 return D->second;
2230 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2231 auto MIB =
2232 MIRBuilder.buildInstr(SPIRV::OpAliasDomainDeclINTEL).addDef(Ret);
2233 return MIB.getInstr();
2234 }();
2235 AliasInstMDMap.insert(std::make_pair(DomainMD, Domain));
2236 auto *Scope = [&] {
2237 auto S = AliasInstMDMap.find(ScopeMD);
2238 if (S != AliasInstMDMap.end())
2239 return S->second;
2240 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2241 auto MIB = MIRBuilder.buildInstr(SPIRV::OpAliasScopeDeclINTEL)
2242 .addDef(Ret)
2243 .addUse(Domain->getOperand(0).getReg());
2244 return MIB.getInstr();
2245 }();
2246 AliasInstMDMap.insert(std::make_pair(ScopeMD, Scope));
2247 ScopeList.push_back(Scope);
2248 }
2249 }
2250
2251 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2252 auto MIB =
2253 MIRBuilder.buildInstr(SPIRV::OpAliasScopeListDeclINTEL).addDef(Ret);
2254 for (auto *Scope : ScopeList)
2255 MIB.addUse(Scope->getOperand(0).getReg());
2256 auto List = MIB.getInstr();
2257 AliasInstMDMap.insert(std::make_pair(AliasingListMD, List));
2258 return List;
2259}
2260
2262 Register Reg, MachineIRBuilder &MIRBuilder, uint32_t Dec,
2263 const MDNode *AliasingListMD) {
2264 MachineInstr *AliasList =
2265 getOrAddMemAliasingINTELInst(MIRBuilder, AliasingListMD);
2266 if (!AliasList)
2267 return;
2268 MIRBuilder.buildInstr(SPIRV::OpDecorateId)
2269 .addUse(Reg)
2270 .addImm(Dec)
2271 .addUse(AliasList->getOperand(0).getReg());
2272}
2274 bool DeleteOld) {
2275 Old->replaceAllUsesWith(New);
2276 updateIfExistDeducedElementType(Old, New, DeleteOld);
2277 updateIfExistAssignPtrTypeInstr(Old, New, DeleteOld);
2278}
2279
2281 Value *Arg) {
2282 Value *OfType = getNormalizedPoisonValue(Ty);
2283 CallInst *AssignCI = nullptr;
2284 if (Arg->getType()->isAggregateType() && Ty->isAggregateType() &&
2285 allowEmitFakeUse(Arg)) {
2286 LLVMContext &Ctx = Arg->getContext();
2289 MDString::get(Ctx, Arg->getName())};
2290 B.CreateIntrinsic(Intrinsic::spv_value_md,
2291 {MetadataAsValue::get(Ctx, MDTuple::get(Ctx, ArgMDs))});
2292 AssignCI = B.CreateIntrinsicWithoutFolding(Intrinsic::fake_use, {Arg});
2293 } else {
2294 AssignCI = buildIntrWithMD(Intrinsic::spv_assign_type, {Arg->getType()},
2295 OfType, Arg, {}, B);
2296 }
2297 addAssignPtrTypeInstr(Arg, AssignCI);
2298}
2299
2301 Value *Arg) {
2302 Value *OfType = PoisonValue::get(ElemTy);
2303 CallInst *AssignPtrTyCI = findAssignPtrTypeInstr(Arg);
2304 Function *CurrF =
2305 B.GetInsertBlock() ? B.GetInsertBlock()->getParent() : nullptr;
2306 if (AssignPtrTyCI == nullptr ||
2307 AssignPtrTyCI->getParent()->getParent() != CurrF) {
2308 AssignPtrTyCI = buildIntrWithMD(
2309 Intrinsic::spv_assign_ptr_type, {Arg->getType()}, OfType, Arg,
2310 {B.getInt32(getPointerAddressSpace(Arg->getType()))}, B);
2311 addDeducedElementType(AssignPtrTyCI, ElemTy);
2312 addDeducedElementType(Arg, ElemTy);
2313 addAssignPtrTypeInstr(Arg, AssignPtrTyCI);
2314 } else {
2315 updateAssignType(AssignPtrTyCI, Arg, OfType);
2316 }
2317}
2318
2320 Value *OfType) {
2321 AssignCI->setArgOperand(1, buildMD(OfType));
2322 if (cast<IntrinsicInst>(AssignCI)->getIntrinsicID() !=
2323 Intrinsic::spv_assign_ptr_type)
2324 return;
2325
2326 // update association with the pointee type
2327 Type *ElemTy = OfType->getType();
2328 addDeducedElementType(AssignCI, ElemTy);
2329 addDeducedElementType(Arg, ElemTy);
2330}
2331
2332void SPIRVGlobalRegistry::addStructOffsetDecorations(
2333 Register Reg, StructType *Ty, MachineIRBuilder &MIRBuilder) {
2334 ArrayRef<TypeSize> Offsets = DL.getStructLayout(Ty)->getMemberOffsets();
2335 for (uint32_t I = 0; I < Ty->getNumElements(); ++I) {
2336 buildOpMemberDecorate(Reg, MIRBuilder, SPIRV::Decoration::Offset, I,
2337 {static_cast<uint32_t>(Offsets[I])});
2338 }
2339}
2340
2341void SPIRVGlobalRegistry::addArrayStrideDecorations(
2342 Register Reg, Type *ElementType, MachineIRBuilder &MIRBuilder) {
2343 uint32_t SizeInBytes = DL.getTypeAllocSize(ElementType);
2344 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::ArrayStride,
2345 {SizeInBytes});
2346}
2347
2348bool SPIRVGlobalRegistry::hasBlockDecoration(SPIRVTypeInst Type) const {
2350 for (const MachineInstr &Use :
2351 Type->getMF()->getRegInfo().use_instructions(Def)) {
2352 if (Use.getOpcode() != SPIRV::OpDecorate)
2353 continue;
2354
2355 if (Use.getOperand(1).getImm() == SPIRV::Decoration::Block)
2356 return true;
2357 }
2358 return false;
2359}
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
static constexpr Value * getValue(Ty &ValueOrUse)
#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_>.
SI Fold Operands
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)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
APInt bitcastToAPInt() const
Definition APFloat.h:1467
bool isPosZero() const
Definition APFloat.h:1586
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
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:643
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
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
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,...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
Diagnostic information for unsupported feature in backend.
Class to represent fixed width SIMD vectors.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
Class to represent function types.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:353
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
Type * getValueType() const
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:2893
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:348
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:89
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
Metadata node.
Definition Metadata.h:1069
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1424
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
Tracking metadata reference owned by Metadata.
Definition Metadata.h:891
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:615
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1513
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.
void constrainAllUses(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) const
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:111
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:911
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
void assignSPIRVTypeToVReg(SPIRVTypeInst Type, Register VReg, const MachineFunction &MF)
SPIRVTypeInst getOrCreateOpTypeFunctionWithArgs(const Type *Ty, SPIRVTypeInst RetType, const SmallVectorImpl< SPIRVTypeInst > &ArgTypes, MachineIRBuilder &MIRBuilder)
SPIRVTypeInst getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC, bool ForceTyped=false)
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
const Type * getTypeForSPIRVType(SPIRVTypeInst Ty) const
bool isBitcastCompatible(SPIRVTypeInst Type1, SPIRVTypeInst Type2) const
void addDeducedElementType(Value *Val, Type *Ty)
bool shouldKeepTypedPtrType(SPIRVTypeInst ElemType) const
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)
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)
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
SPIRVTypeInst getOrCreateSPIRVUntypedPointerType(SPIRV::StorageClass::StorageClass SC, MachineIRBuilder &MIRBuilder)
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
bool shouldUseUntypedPointer(SPIRVTypeInst ElemType, const SPIRVSubtarget &ST) 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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition StringRef.h:691
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
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:597
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:661
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:683
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:760
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:310
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:279
Type * getArrayElementType() const
Definition Type.h:425
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
LLVM_ABI uint64_t getArrayNumElements() const
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition Type.h:164
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:319
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:287
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:286
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:284
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:1631
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:553
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:319
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_untyped_pointer(unsigned AddressSpace)
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
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:82
This is an optimization pass for GlobalISel generic memory operations.
void addStringImm(StringRef Str, MCInst &Inst)
bool isTypedPointerWrapper(const TargetExtType *ExtTy)
Definition SPIRVUtils.h:421
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:392
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)
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)
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
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:245
bool getSpirvBuiltInIdByName(llvm::StringRef Name, SPIRV::BuiltIn::BuiltIn &BI)
MetadataAsValue * buildMD(Value *Arg)
Definition SPIRVUtils.h:531
bool isTypedPointerTy(const Type *T)
Definition SPIRVUtils.h:370
void buildOpName(Register Target, StringRef Name, MachineIRBuilder &MIRBuilder)
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
Type * getTypedPointerWrapper(Type *ElemTy, unsigned AS)
Definition SPIRVUtils.h:416
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:476
bool isSpecialOpaqueType(const Type *Ty)
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:380
MachineBasicBlock::iterator getInsertPtValidEnd(MachineBasicBlock *MBB)
const Type * unifyPtrType(const Type *Ty)
Definition SPIRVUtils.h:503
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)
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)
void buildOpMemberDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, uint32_t Member, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
bool isPointerTyOrWrapper(const Type *Ty)
Definition SPIRVUtils.h:428
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)
PoisonValue * getNormalizedPoisonValue(Type *Ty)
Definition SPIRVUtils.h:527
MachineInstr * getVRegDef(MachineRegisterInfo &MRI, Register Reg)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
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