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