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