LLVM 24.0.0git
SPIRVModuleAnalysis.cpp
Go to the documentation of this file.
1//===- SPIRVModuleAnalysis.cpp - analysis of global instrs & regs - 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// The analysis collects instructions that should be output at the module level
10// and performs the global register numbering.
11//
12// The results of this analysis are used in AsmPrinter to rename registers
13// globally and to output required instructions at the module level.
14//
15//===----------------------------------------------------------------------===//
16
17// TODO: Per LLVM best practices, the report_fatal_error (deprecated) /
18// ReportFatalUsageError calls in this file should be replaced with the
19// Diagnostic infrastructure (e.g. the reportUnsupported function below).
20
21#include "SPIRVModuleAnalysis.h"
24#include "SPIRV.h"
25#include "SPIRVSubtarget.h"
26#include "SPIRVTargetMachine.h"
27#include "SPIRVUtils.h"
28#include "llvm/ADT/STLExtras.h"
33
34using namespace llvm;
35
36#define DEBUG_TYPE "spirv-module-analysis"
37
39
41 "SPIRV module analysis", true, true)
42
44 const Function &Func = MI.getMF()->getFunction();
45 Func.getContext().diagnose(
46 DiagnosticInfoUnsupported(Func, Msg, MI.getDebugLoc()));
47}
48
49// Retrieve an unsigned from an MDNode with a list of them as operands.
50static unsigned getMetadataUInt(MDNode *MdNode, unsigned OpIndex,
51 unsigned DefaultVal = 0) {
52 if (MdNode && OpIndex < MdNode->getNumOperands()) {
53 const auto &Op = MdNode->getOperand(OpIndex);
54 return mdconst::extract<ConstantInt>(Op)->getZExtValue();
55 }
56 return DefaultVal;
57}
58
59// Return true if Cap should be avoided when another option enables the feature.
61 SPIRV::Capability::Capability Cap) {
62 return Cap == (ST.isShader() ? SPIRV::Capability::Kernel
63 : SPIRV::Capability::Shader) ||
64 is_contained(ST.getCLOpts().avoid_capabilities, Cap);
65}
66
68getSymbolicOperandRequirements(SPIRV::OperandCategory::OperandCategory Category,
69 unsigned i, const SPIRVSubtarget &ST,
71 VersionTuple ReqMinVer = getSymbolicOperandMinVersion(Category, i);
72 VersionTuple ReqMaxVer = getSymbolicOperandMaxVersion(Category, i);
73 VersionTuple SPIRVVersion = ST.getSPIRVVersion();
74 bool MinVerOK = SPIRVVersion.empty() || SPIRVVersion >= ReqMinVer;
75 bool MaxVerOK =
76 ReqMaxVer.empty() || SPIRVVersion.empty() || SPIRVVersion <= ReqMaxVer;
77 bool VerOK = MinVerOK && MaxVerOK;
79 ExtensionList ReqExts = getSymbolicOperandExtensions(Category, i);
80 // A met minimum version makes the extension unnecessary.
81 if (VerOK && !ReqMinVer.empty())
82 ReqExts.clear();
83 if (ReqCaps.empty()) {
84 if (ReqExts.empty()) {
85 if (VerOK)
86 return {true, {}, {}, ReqMinVer, ReqMaxVer};
87 return {false, {}, {}, VersionTuple(), VersionTuple()};
88 }
89 } else if (VerOK) {
90 if (ReqCaps.size() == 1) {
91 auto Cap = ReqCaps[0];
92 if (Reqs.isCapabilityAvailable(Cap)) {
94 SPIRV::OperandCategory::CapabilityOperand, Cap));
95 return {true, {Cap}, std::move(ReqExts), ReqMinVer, ReqMaxVer};
96 }
97 } else {
98 // By SPIR-V specification: "If an instruction, enumerant, or other
99 // feature specifies multiple enabling capabilities, only one such
100 // capability needs to be declared to use the feature." However, one
101 // capability may be preferred over another. We use command line
102 // argument(s) and AvoidCapabilities to avoid selection of certain
103 // capabilities if there are other options.
104 CapabilityList UseCaps;
105 for (auto Cap : ReqCaps)
106 if (Reqs.isCapabilityAvailable(Cap))
107 UseCaps.push_back(Cap);
108 for (size_t i = 0, Sz = UseCaps.size(); i < Sz; ++i) {
109 auto Cap = UseCaps[i];
110 if (i == Sz - 1 || !shouldAvoidCapability(ST, Cap)) {
112 SPIRV::OperandCategory::CapabilityOperand, Cap));
113 return {true, {Cap}, std::move(ReqExts), ReqMinVer, ReqMaxVer};
114 }
115 }
116 }
117 }
118 // If there are no capabilities, or we can't satisfy the version or
119 // capability requirements, use the list of extensions (if the subtarget
120 // can handle them all). Without an extension the version must hold. An
121 // extension stands in for an unmet version.
122 if ((!ReqExts.empty() || VerOK) &&
123 llvm::all_of(ReqExts, [&ST](const SPIRV::Extension::Extension &Ext) {
124 return ST.canUseExtension(Ext);
125 })) {
126 if (VerOK)
127 return {true, {}, std::move(ReqExts), ReqMinVer, ReqMaxVer};
128 return {true, {}, std::move(ReqExts), VersionTuple(), VersionTuple()};
129 }
130 return {false, {}, {}, VersionTuple(), VersionTuple()};
131}
132
133void SPIRVModuleAnalysisImpl::setBaseInfo(const Module &M) {
134 MAI.MaxID = 0;
135 for (int i = 0; i < SPIRV::NUM_MODULE_SECTIONS; i++)
136 MAI.MS[i].clear();
137 MAI.RegisterAliasTable.clear();
138 MAI.InstrsToDelete.clear();
139 MAI.MBBNames.clear();
140 MAI.GlobalObjMap.clear();
141 MAI.GlobalVarList.clear();
142 MAI.ExtInstSetMap.clear();
143 MAI.InstrAuxDataRecords.clear();
144 MAI.DebugValueMIs.clear();
145 MAI.Reqs.clear();
146 MAI.Reqs.initAvailableCapabilities(*ST);
147
148 // TODO: determine memory model and source language from the configuratoin.
149 if (auto MemModel = M.getNamedMetadata("spirv.MemoryModel")) {
150 auto MemMD = MemModel->getOperand(0);
151 MAI.Addr = static_cast<SPIRV::AddressingModel::AddressingModel>(
152 getMetadataUInt(MemMD, 0));
153 MAI.Mem =
154 static_cast<SPIRV::MemoryModel::MemoryModel>(getMetadataUInt(MemMD, 1));
155 } else {
156 // TODO: Add support for VulkanMemoryModel.
157 MAI.Mem = ST->isShader() ? SPIRV::MemoryModel::GLSL450
158 : SPIRV::MemoryModel::OpenCL;
159 if (MAI.Mem == SPIRV::MemoryModel::OpenCL) {
160 unsigned PtrSize = ST->getPointerSize();
161 MAI.Addr = PtrSize == 32 ? SPIRV::AddressingModel::Physical32
162 : PtrSize == 64 ? SPIRV::AddressingModel::Physical64
163 : SPIRV::AddressingModel::Logical;
164 } else {
165 // TODO: Add support for PhysicalStorageBufferAddress.
166 MAI.Addr = SPIRV::AddressingModel::Logical;
167 }
168 }
169 // Get the OpenCL version number from metadata.
170 // TODO: support other source languages.
171 if (auto VerNode = M.getNamedMetadata("opencl.ocl.version")) {
172 MAI.SrcLang = SPIRV::SourceLanguage::OpenCL_C;
173 // Construct version literal in accordance with SPIRV-LLVM-Translator.
174 // TODO: support multiple OCL version metadata.
175 assert(VerNode->getNumOperands() > 0 && "Invalid SPIR");
176 auto VersionMD = VerNode->getOperand(0);
177 unsigned MajorNum = getMetadataUInt(VersionMD, 0, 2);
178 unsigned MinorNum = getMetadataUInt(VersionMD, 1);
179 unsigned RevNum = getMetadataUInt(VersionMD, 2);
180 // Prevent Major part of OpenCL version to be 0
181 MAI.SrcLangVersion =
182 (std::max(1U, MajorNum) * 100 + MinorNum) * 1000 + RevNum;
183 // When opencl.cxx.version is also present, validate compatibility
184 // and use C++ for OpenCL as source language with the C++ version.
185 if (auto *CxxVerNode = M.getNamedMetadata("opencl.cxx.version")) {
186 assert(CxxVerNode->getNumOperands() > 0 && "Invalid SPIR");
187 auto *CxxMD = CxxVerNode->getOperand(0);
188 unsigned CxxVer =
189 (getMetadataUInt(CxxMD, 0) * 100 + getMetadataUInt(CxxMD, 1)) * 1000 +
190 getMetadataUInt(CxxMD, 2);
191 if ((MAI.SrcLangVersion == 200000 && CxxVer == 100000) ||
192 (MAI.SrcLangVersion == 300000 && CxxVer == 202100000)) {
193 MAI.SrcLang = SPIRV::SourceLanguage::CPP_for_OpenCL;
194 MAI.SrcLangVersion = CxxVer;
195 } else {
197 "opencl cxx version is not compatible with opencl c version!");
198 }
199 }
200 } else {
201 // If there is no information about OpenCL version we are forced to generate
202 // OpenCL 1.0 by default for the OpenCL environment to avoid puzzling
203 // run-times with Unknown/0.0 version output. For a reference, LLVM-SPIRV
204 // Translator avoids potential issues with run-times in a similar manner.
205 if (!ST->isShader()) {
206 MAI.SrcLang = SPIRV::SourceLanguage::OpenCL_CPP;
207 MAI.SrcLangVersion = 100000;
208 } else {
209 MAI.SrcLang = SPIRV::SourceLanguage::Unknown;
210 MAI.SrcLangVersion = 0;
211 }
212 }
213
214 if (auto ExtNode = M.getNamedMetadata("opencl.used.extensions")) {
215 for (unsigned I = 0, E = ExtNode->getNumOperands(); I != E; ++I) {
216 MDNode *MD = ExtNode->getOperand(I);
217 if (!MD || MD->getNumOperands() == 0)
218 continue;
219 for (unsigned J = 0, N = MD->getNumOperands(); J != N; ++J)
220 MAI.SrcExt.insert(cast<MDString>(MD->getOperand(J))->getString());
221 }
222 }
223
224 // Update required capabilities for this memory model, addressing model and
225 // source language.
226 MAI.Reqs.getAndAddRequirements(SPIRV::OperandCategory::MemoryModelOperand,
227 MAI.Mem, *ST);
228 MAI.Reqs.getAndAddRequirements(SPIRV::OperandCategory::SourceLanguageOperand,
229 MAI.SrcLang, *ST);
230 MAI.Reqs.getAndAddRequirements(SPIRV::OperandCategory::AddressingModelOperand,
231 MAI.Addr, *ST);
232
233 if (MAI.Mem == SPIRV::MemoryModel::VulkanKHR)
234 MAI.Reqs.addExtension(SPIRV::Extension::SPV_KHR_vulkan_memory_model);
235
236 if (!ST->isShader()) {
237 // TODO: check if it's required by default.
238 MAI.ExtInstSetMap[static_cast<unsigned>(
239 SPIRV::InstructionSet::OpenCL_std)] = MAI.getNextIDRegister();
240 }
241}
242
243// Appends the signature of the decoration instructions that decorate R to
244// Signature.
246 InstrSignature &Signature) {
247 for (MachineInstr &UseMI : MRI.use_instructions(R)) {
248 // We don't handle OpDecorateId because getting the register alias for the
249 // ID can cause problems, and we do not need it for now.
250 if (UseMI.getOpcode() != SPIRV::OpDecorate &&
251 UseMI.getOpcode() != SPIRV::OpMemberDecorate)
252 continue;
253
254 for (unsigned I = 0; I < UseMI.getNumOperands(); ++I) {
255 const MachineOperand &MO = UseMI.getOperand(I);
256 if (MO.isReg())
257 continue;
258 Signature.push_back(hash_value(MO));
259 }
260 }
261}
262
263// Returns a representation of an instruction as a vector of MachineOperand
264// hash values, see llvm::hash_value(const MachineOperand &MO) for details.
265// This creates a signature of the instruction with the same content
266// that MachineOperand::isIdenticalTo uses for comparison.
269 bool UseDefReg) {
270 Register DefReg;
271 InstrSignature Signature{MI.getOpcode()};
272 for (unsigned i = 0; i < MI.getNumOperands(); ++i) {
273 // The only decorations that can be applied more than once to a given <id>
274 // or structure member are FuncParamAttr (38), UserSemantic (5635),
275 // CacheControlLoadINTEL (6442), and CacheControlStoreINTEL (6443). For all
276 // the rest of decorations, we will only add to the signature the Opcode,
277 // the id to which it applies, and the decoration id, disregarding any
278 // decoration flags. This will ensure that any subsequent decoration with
279 // the same id will be deemed as a duplicate. Then, at the call site, we
280 // will be able to handle duplicates in the best way.
281 unsigned Opcode = MI.getOpcode();
282 if ((Opcode == SPIRV::OpDecorate) && i >= 2) {
283 unsigned DecorationID = MI.getOperand(1).getImm();
284 if (DecorationID != SPIRV::Decoration::FuncParamAttr &&
285 DecorationID != SPIRV::Decoration::UserSemantic &&
286 DecorationID != SPIRV::Decoration::CacheControlLoadINTEL &&
287 DecorationID != SPIRV::Decoration::CacheControlStoreINTEL)
288 continue;
289 }
290 const MachineOperand &MO = MI.getOperand(i);
291 size_t h;
292 if (MO.isReg()) {
293 if (!UseDefReg && MO.isDef()) {
294 assert(!DefReg.isValid() && "Multiple def registers.");
295 DefReg = MO.getReg();
296 continue;
297 }
298 Register RegAlias = MAI.getRegisterAlias(MI.getMF(), MO.getReg());
299 if (!RegAlias.isValid()) {
300 LLVM_DEBUG({
301 dbgs() << "Unexpectedly, no global id found for the operand ";
302 MO.print(dbgs());
303 dbgs() << "\nInstruction: ";
304 MI.print(dbgs());
305 dbgs() << "\n";
306 });
307 report_fatal_error("All v-regs must have been mapped to global id's");
308 }
309 // mimic llvm::hash_value(const MachineOperand &MO)
310 h = hash_combine(MO.getType(), (unsigned)RegAlias, MO.getSubReg(),
311 MO.isDef());
312 } else {
313 h = hash_value(MO);
314 }
315 Signature.push_back(h);
316 }
317
318 if (DefReg.isValid()) {
319 // Decorations change the semantics of the current instruction. So two
320 // identical instruction with different decorations cannot be merged. That
321 // is why we add the decorations to the signature.
322 appendDecorationsForReg(MI.getMF()->getRegInfo(), DefReg, Signature);
323 }
324 return Signature;
325}
326
327// Operand index of Invoke in device enqueue instructions, 0 if none.
328static unsigned getInvokeOperandIdx(unsigned Opcode) {
329 switch (Opcode) {
330 case SPIRV::OpEnqueueKernel:
331 return 8;
332 case SPIRV::OpGetKernelNDrangeSubGroupCount:
333 case SPIRV::OpGetKernelNDrangeMaxSubGroupSize:
334 return 3;
335 case SPIRV::OpGetKernelWorkGroupSize:
336 case SPIRV::OpGetKernelPreferredWorkGroupSizeMultiple:
337 return 2;
338 default:
339 return 0;
340 }
341}
342
343bool SPIRVModuleAnalysisImpl::isDeclSection(const MachineRegisterInfo &MRI,
344 const MachineInstr &MI) {
345 unsigned Opcode = MI.getOpcode();
346 switch (Opcode) {
347 case SPIRV::OpTypeForwardPointer:
348 // omit now, collect later
349 return false;
350 case SPIRV::OpVariable:
351 case SPIRV::OpUntypedVariableKHR:
352 return static_cast<SPIRV::StorageClass::StorageClass>(
353 MI.getOperand(2).getImm()) != SPIRV::StorageClass::Function;
354 case SPIRV::OpFunction:
355 case SPIRV::OpFunctionParameter:
356 return true;
357 }
358 if (GR->hasConstFunPtr() && Opcode == SPIRV::OpUndef) {
359 // The OpUndef may be a placeholder for a function reference recorded by
360 // selectGlobalValue. Skip emitting it if any user consumes it as a
361 // function-pointer-like operand (OpConstantFunctionPointerINTEL operand 2,
362 // or the Invoke operand of a device enqueue instruction). The rewrite
363 // happens in visitFunPtrUse, which aliases the OpUndef's vreg to the
364 // function's global <id>.
365 Register DefReg = MI.getOperand(0).getReg();
366 if (GR->getFunctionDefinitionByUse(&MI.getOperand(0))) {
367 for (MachineInstr &UseMI : MRI.use_instructions(DefReg)) {
368 unsigned UseOp = UseMI.getOpcode();
369 if (UseOp == SPIRV::OpConstantFunctionPointerINTEL ||
370 getInvokeOperandIdx(UseOp)) {
371 MAI.setSkipEmission(&MI);
372 return false;
373 }
374 }
375 }
376 for (MachineInstr &UseMI : MRI.use_instructions(DefReg)) {
377 if (UseMI.getOpcode() != SPIRV::OpConstantFunctionPointerINTEL)
378 continue;
379 // it's a dummy definition, FP constant refers to a function,
380 // and this is resolved in another way; let's skip this definition
381 assert(UseMI.getOperand(2).isReg() &&
382 UseMI.getOperand(2).getReg() == DefReg);
383 MAI.setSkipEmission(&MI);
384 return false;
385 }
386 }
387 return TII->isTypeDeclInstr(MI) || TII->isConstantInstr(MI) ||
388 TII->isInlineAsmDefInstr(MI);
389}
390
391// This is a special case of a function pointer referring to a possibly
392// forward function declaration. The operand is a dummy OpUndef that
393// requires a special treatment.
394// FunPtrOp is the MachineOperand previously recorded via
395// SPIRVGlobalRegistry::recordFunctionPointer, identifying which Function
396// this placeholder refers to.
397void SPIRVModuleAnalysisImpl::visitFunPtrUse(
398 Register OpReg, const MachineOperand *FunPtrOp,
399 InstrGRegsMap &SignatureToGReg,
400 std::map<const Value *, MCRegister> &GlobalToGReg,
401 const MachineFunction *MF) {
402 const MachineOperand *OpFunDef = GR->getFunctionDefinitionByUse(FunPtrOp);
403 assert(OpFunDef && OpFunDef->isReg());
404 // find the actual function definition and number it globally in advance
405 const MachineInstr *OpDefMI = OpFunDef->getParent();
406 assert(OpDefMI && OpDefMI->getOpcode() == SPIRV::OpFunction);
407 const MachineFunction *FunDefMF = OpDefMI->getParent()->getParent();
408 const MachineRegisterInfo &FunDefMRI = FunDefMF->getRegInfo();
409 do {
410 visitDecl(FunDefMRI, SignatureToGReg, GlobalToGReg, FunDefMF, *OpDefMI);
411 OpDefMI = OpDefMI->getNextNode();
412 } while (OpDefMI && (OpDefMI->getOpcode() == SPIRV::OpFunction ||
413 OpDefMI->getOpcode() == SPIRV::OpFunctionParameter));
414 // associate the function pointer with the newly assigned global number
415 MCRegister GlobalFunDefReg =
416 MAI.getRegisterAlias(FunDefMF, OpFunDef->getReg());
417 assert(GlobalFunDefReg.isValid() &&
418 "Function definition must refer to a global register");
419 MAI.setRegisterAlias(MF, OpReg, GlobalFunDefReg);
420}
421
422// Depth first recursive traversal of dependencies. Repeated visits are guarded
423// by MAI.hasRegisterAlias().
424void SPIRVModuleAnalysisImpl::visitDecl(
425 const MachineRegisterInfo &MRI, InstrGRegsMap &SignatureToGReg,
426 std::map<const Value *, MCRegister> &GlobalToGReg,
427 const MachineFunction *MF, const MachineInstr &MI) {
428 unsigned Opcode = MI.getOpcode();
429
430 // Process each operand of the instruction to resolve dependencies
431 for (const MachineOperand &MO : MI.operands()) {
432 if (!MO.isReg() || MO.isDef())
433 continue;
434 Register OpReg = MO.getReg();
435 // Handle function pointers special case
436 if (Opcode == SPIRV::OpConstantFunctionPointerINTEL &&
437 MRI.getRegClass(OpReg) == &SPIRV::pIDRegClass) {
438 visitFunPtrUse(OpReg, &MI.getOperand(2), SignatureToGReg, GlobalToGReg,
439 MF);
440 continue;
441 }
442 // Skip already processed instructions
443 if (MAI.hasRegisterAlias(MF, MO.getReg()))
444 continue;
445 // Recursively visit dependencies
446 if (const MachineInstr *OpDefMI = MRI.getUniqueVRegDef(OpReg)) {
447 if (isDeclSection(MRI, *OpDefMI))
448 visitDecl(MRI, SignatureToGReg, GlobalToGReg, MF, *OpDefMI);
449 continue;
450 }
451 // Handle the unexpected case of no unique definition for the SPIR-V
452 // instruction
453 LLVM_DEBUG({
454 dbgs() << "Unexpectedly, no unique definition for the operand ";
455 MO.print(dbgs());
456 dbgs() << "\nInstruction: ";
457 MI.print(dbgs());
458 dbgs() << "\n";
459 });
461 "No unique definition is found for the virtual register");
462 }
463
464 MCRegister GReg;
465 bool IsFunDef = false;
466 if (TII->isSpecConstantInstr(MI)) {
467 GReg = MAI.getNextIDRegister();
468 MAI.MS[SPIRV::MB_TypeConstVars].push_back(&MI);
469 } else if (Opcode == SPIRV::OpFunction ||
470 Opcode == SPIRV::OpFunctionParameter) {
471 GReg = handleFunctionOrParameter(MF, MI, GlobalToGReg, IsFunDef);
472 } else if (Opcode == SPIRV::OpTypeStruct ||
473 Opcode == SPIRV::OpConstantComposite) {
474 GReg = handleTypeDeclOrConstant(MI, SignatureToGReg);
475 const MachineInstr *NextInstr = MI.getNextNode();
476 while (NextInstr &&
477 ((Opcode == SPIRV::OpTypeStruct &&
478 NextInstr->getOpcode() == SPIRV::OpTypeStructContinuedINTEL) ||
479 (Opcode == SPIRV::OpConstantComposite &&
480 NextInstr->getOpcode() ==
481 SPIRV::OpConstantCompositeContinuedINTEL))) {
482 MCRegister Tmp = handleTypeDeclOrConstant(*NextInstr, SignatureToGReg);
483 MAI.setRegisterAlias(MF, NextInstr->getOperand(0).getReg(), Tmp);
484 MAI.setSkipEmission(NextInstr);
485 NextInstr = NextInstr->getNextNode();
486 }
487 } else if (TII->isTypeDeclInstr(MI) || TII->isConstantInstr(MI) ||
488 TII->isInlineAsmDefInstr(MI)) {
489 GReg = handleTypeDeclOrConstant(MI, SignatureToGReg);
490 } else if (Opcode == SPIRV::OpVariable ||
491 Opcode == SPIRV::OpUntypedVariableKHR) {
492 GReg = handleVariable(MF, MI, GlobalToGReg);
493 } else {
494 LLVM_DEBUG({
495 dbgs() << "\nInstruction: ";
496 MI.print(dbgs());
497 dbgs() << "\n";
498 });
499 llvm_unreachable("Unexpected instruction is visited");
500 }
501 MAI.setRegisterAlias(MF, MI.getOperand(0).getReg(), GReg);
502 if (!IsFunDef)
503 MAI.setSkipEmission(&MI);
504}
505
506MCRegister SPIRVModuleAnalysisImpl::handleFunctionOrParameter(
507 const MachineFunction *MF, const MachineInstr &MI,
508 std::map<const Value *, MCRegister> &GlobalToGReg, bool &IsFunDef) {
509 const Value *GObj = GR->getGlobalObject(MF, MI.getOperand(0).getReg());
510 assert(GObj && "Unregistered global definition");
511 const Function *F = dyn_cast<Function>(GObj);
512 if (!F)
513 F = dyn_cast<Argument>(GObj)->getParent();
514 assert(F && "Expected a reference to a function or an argument");
515 IsFunDef = !F->isDeclaration();
516 auto [It, Inserted] = GlobalToGReg.try_emplace(GObj);
517 if (!Inserted)
518 return It->second;
519 MCRegister GReg = MAI.getNextIDRegister();
520 It->second = GReg;
521 if (!IsFunDef)
522 MAI.MS[SPIRV::MB_ExtFuncDecls].push_back(&MI);
523 return GReg;
524}
525
526MCRegister SPIRVModuleAnalysisImpl::handleTypeDeclOrConstant(
527 const MachineInstr &MI, InstrGRegsMap &SignatureToGReg) {
528 InstrSignature MISign = instrToSignature(MI, MAI, false);
529 auto [It, Inserted] = SignatureToGReg.try_emplace(MISign);
530 if (!Inserted)
531 return It->second;
532 MCRegister GReg = MAI.getNextIDRegister();
533 It->second = GReg;
534 MAI.MS[SPIRV::MB_TypeConstVars].push_back(&MI);
535 return GReg;
536}
537
538MCRegister SPIRVModuleAnalysisImpl::handleVariable(
539 const MachineFunction *MF, const MachineInstr &MI,
540 std::map<const Value *, MCRegister> &GlobalToGReg) {
541 MAI.GlobalVarList.push_back(&MI);
542 const Value *GObj = GR->getGlobalObject(MF, MI.getOperand(0).getReg());
543 assert(GObj && "Unregistered global definition");
544 auto [It, Inserted] = GlobalToGReg.try_emplace(GObj);
545 if (!Inserted)
546 return It->second;
547 MCRegister GReg = MAI.getNextIDRegister();
548 It->second = GReg;
549 MAI.MS[SPIRV::MB_TypeConstVars].push_back(&MI);
550 if (const auto *GV = dyn_cast<GlobalVariable>(GObj))
551 MAI.GlobalObjMap[GV] = GReg;
552 return GReg;
553}
554
555void SPIRVModuleAnalysisImpl::collectDeclarations(const Module &M) {
556 InstrGRegsMap SignatureToGReg;
557 std::map<const Value *, MCRegister> GlobalToGReg;
558 for (const Function &F : M) {
559 MachineFunction *MF = GetMF(F);
560 if (!MF)
561 continue;
562 const MachineRegisterInfo &MRI = MF->getRegInfo();
563 unsigned PastHeader = 0;
564 for (MachineBasicBlock &MBB : *MF) {
565 for (MachineInstr &MI : MBB) {
566 if (MI.getNumOperands() == 0)
567 continue;
568 unsigned Opcode = MI.getOpcode();
569 if (Opcode == SPIRV::OpFunction) {
570 if (PastHeader == 0) {
571 PastHeader = 1;
572 continue;
573 }
574 } else if (Opcode == SPIRV::OpFunctionParameter) {
575 if (PastHeader < 2)
576 continue;
577 } else if (PastHeader > 0) {
578 PastHeader = 2;
579 }
580
581 const MachineOperand &DefMO = MI.getOperand(0);
582 switch (Opcode) {
583 case SPIRV::OpExtension:
584 MAI.Reqs.addExtension(SPIRV::Extension::Extension(DefMO.getImm()));
585 MAI.setSkipEmission(&MI);
586 break;
587 case SPIRV::OpCapability:
588 MAI.Reqs.addCapability(SPIRV::Capability::Capability(DefMO.getImm()));
589 MAI.setSkipEmission(&MI);
590 if (PastHeader > 0)
591 PastHeader = 2;
592 break;
593 default:
594 if (DefMO.isReg() && isDeclSection(MRI, MI) &&
595 !MAI.hasRegisterAlias(MF, DefMO.getReg()))
596 visitDecl(MRI, SignatureToGReg, GlobalToGReg, MF, MI);
597 // Device enqueue instructions are not decls, but their Invoke
598 // operand may be a function-pointer placeholder OpUndef. Resolve it
599 // to the OpFunction's global <id> via visitFunPtrUse.
600 if (unsigned InvokeIdx = getInvokeOperandIdx(Opcode)) {
601 const MachineOperand &InvokeMO = MI.getOperand(InvokeIdx);
602 if (InvokeMO.isReg()) {
603 Register InvokeReg = InvokeMO.getReg();
604 if (!MAI.hasRegisterAlias(MF, InvokeReg)) {
605 if (const MachineInstr *DefMI =
606 MRI.getUniqueVRegDef(InvokeReg)) {
607 if (DefMI->getOpcode() == SPIRV::OpUndef) {
608 const MachineOperand *FunPtrOp = &DefMI->getOperand(0);
609 if (GR->getFunctionDefinitionByUse(FunPtrOp))
610 visitFunPtrUse(InvokeReg, FunPtrOp, SignatureToGReg,
611 GlobalToGReg, MF);
612 }
613 }
614 }
615 }
616 }
617 }
618 }
619 }
620 }
621}
622
623// Look for IDs declared with Import linkage, and map the corresponding function
624// to the register defining that variable (which will usually be the result of
625// an OpFunction). This lets us call externally imported functions using
626// the correct ID registers.
627void SPIRVModuleAnalysisImpl::collectFuncNames(MachineInstr &MI,
628 const Function *F) {
629 if (MI.getOpcode() == SPIRV::OpDecorate) {
630 // If it's got Import linkage.
631 auto Dec = MI.getOperand(1).getImm();
632 if (Dec == SPIRV::Decoration::LinkageAttributes) {
633 auto Lnk = MI.getOperand(MI.getNumOperands() - 1).getImm();
634 if (Lnk == SPIRV::LinkageType::Import) {
635 // Map imported function name to function ID register.
636 const Function *ImportedFunc =
637 F->getParent()->getFunction(getStringImm(MI, 2));
638 Register Target = MI.getOperand(0).getReg();
639 MAI.GlobalObjMap[ImportedFunc] =
640 MAI.getRegisterAlias(MI.getMF(), Target);
641 }
642 }
643 } else if (MI.getOpcode() == SPIRV::OpFunction) {
644 // Record all internal OpFunction declarations.
645 Register Reg = MI.defs().begin()->getReg();
646 MCRegister GlobalReg = MAI.getRegisterAlias(MI.getMF(), Reg);
647 assert(GlobalReg.isValid());
648 MAI.GlobalObjMap[F] = GlobalReg;
649 }
650}
651
652// Collect the given instruction in the specified MS. We assume global register
653// numbering has already occurred by this point. We can directly compare reg
654// arguments when detecting duplicates.
657 bool Append = true) {
658 MAI.setSkipEmission(&MI);
659 InstrSignature MISign = instrToSignature(MI, MAI, true);
660 auto FoundMI = IS.insert(std::move(MISign));
661 if (!FoundMI.second) {
662 if (MI.getOpcode() == SPIRV::OpDecorate) {
663 assert(MI.getNumOperands() >= 2 &&
664 "Decoration instructions must have at least 2 operands");
665 assert(MSType == SPIRV::MB_Annotations &&
666 "Only OpDecorate instructions can be duplicates");
667 // For FPFastMathMode decoration, we need to merge the flags of the
668 // duplicate decoration with the original one, so we need to find the
669 // original instruction that has the same signature. For the rest of
670 // instructions, we will simply skip the duplicate.
671 if (MI.getOperand(1).getImm() != SPIRV::Decoration::FPFastMathMode)
672 return; // Skip duplicates of other decorations.
673
674 const SPIRV::InstrList &Decorations = MAI.MS[MSType];
675 for (const MachineInstr *OrigMI : Decorations) {
676 if (instrToSignature(*OrigMI, MAI, true) == MISign) {
677 assert(OrigMI->getNumOperands() == MI.getNumOperands() &&
678 "Original instruction must have the same number of operands");
679 assert(
680 OrigMI->getNumOperands() == 3 &&
681 "FPFastMathMode decoration must have 3 operands for OpDecorate");
682 unsigned OrigFlags = OrigMI->getOperand(2).getImm();
683 unsigned NewFlags = MI.getOperand(2).getImm();
684 if (OrigFlags == NewFlags)
685 return; // No need to merge, the flags are the same.
686
687 // Emit warning about possible conflict between flags.
688 unsigned FinalFlags = OrigFlags | NewFlags;
689 llvm::errs()
690 << "Warning: Conflicting FPFastMathMode decoration flags "
691 "in instruction: "
692 << *OrigMI << "Original flags: " << OrigFlags
693 << ", new flags: " << NewFlags
694 << ". They will be merged on a best effort basis, but not "
695 "validated. Final flags: "
696 << FinalFlags << "\n";
697 MachineInstr *OrigMINonConst = const_cast<MachineInstr *>(OrigMI);
698 MachineOperand &OrigFlagsOp = OrigMINonConst->getOperand(2);
699 OrigFlagsOp = MachineOperand::CreateImm(FinalFlags);
700 return; // Merge done, so we found a duplicate; don't add it to MAI.MS
701 }
702 }
703 assert(false && "No original instruction found for the duplicate "
704 "OpDecorate, but we found one in IS.");
705 }
706 return; // insert failed, so we found a duplicate; don't add it to MAI.MS
707 }
708 // No duplicates, so add it.
709 if (Append)
710 MAI.MS[MSType].push_back(&MI);
711 else
712 MAI.MS[MSType].insert(MAI.MS[MSType].begin(), &MI);
713}
714
715// Some global instructions make reference to function-local ID regs, so cannot
716// be correctly collected until these registers are globally numbered.
717void SPIRVModuleAnalysisImpl::processOtherInstrs(const Module &M) {
719 for (const Function &F : M) {
720 if (F.isDeclaration())
721 continue;
722 MachineFunction *MF = GetMF(F);
723 assert(MF);
724
725 for (MachineBasicBlock &MBB : *MF)
726 for (MachineInstr &MI : MBB) {
727 if (MI.isDebugValueLike()) {
728 MAI.DebugValueMIs.push_back(&MI);
729 continue;
730 }
731 if (MAI.getSkipEmission(&MI))
732 continue;
733 const unsigned OpCode = MI.getOpcode();
734 if (OpCode == SPIRV::OpString) {
736 } else if (OpCode == SPIRV::OpExtInst && MI.getOperand(2).isImm() &&
737 MI.getOperand(2).getImm() ==
738 SPIRV::InstructionSet::
739 NonSemantic_Shader_DebugInfo_100) {
740 // TODO: This branch is dead. SPIRVNonSemanticDebugHandler emits NSDI
741 // instructions directly as MCInsts at print time; no
742 // MachineInstructions with the NSDI ext set are created anymore.
743 // Remove this block and
744 // MB_NonSemanticGlobalDI once per-function NSDI emission is confirmed
745 // not to need MIR routing.
746 MachineOperand Ins = MI.getOperand(3);
747 namespace NS = SPIRV::NonSemanticExtInst;
748 static constexpr int64_t GlobalNonSemanticDITy[] = {
749 NS::DebugSource, NS::DebugCompilationUnit, NS::DebugInfoNone,
750 NS::DebugTypeBasic, NS::DebugTypePointer};
751 bool IsGlobalDI = false;
752 for (unsigned Idx = 0; Idx < std::size(GlobalNonSemanticDITy); ++Idx)
753 IsGlobalDI |= Ins.getImm() == GlobalNonSemanticDITy[Idx];
754 if (IsGlobalDI)
756 } else if (OpCode == SPIRV::OpName || OpCode == SPIRV::OpMemberName) {
758 } else if (OpCode == SPIRV::OpEntryPoint) {
760 } else if (TII->isAliasingInstr(MI)) {
762 } else if (TII->isDecorationInstr(MI)) {
763 if (MI.getOpcode() == SPIRV::OpDecorate &&
764 MI.getOperand(1).getImm() ==
765 static_cast<unsigned>(
766 SPIRV::Decoration::AuxDataInstructionMetadata)) {
767 MAI.setSkipEmission(&MI);
768 std::string Str = getStringImm(MI, 2);
770 auto MaybeKind =
771 StringSwitch<std::optional<AMDMD>>(Str)
772 .Case("amdgpu.no.fine.grained.memory",
773 AMDMD::NoFineGrainedMemory)
774 .Case("amdgpu.no.remote.memory", AMDMD::NoRemoteMemory)
775 .Case("atomic.ignore.denormal.mode",
776 AMDMD::IgnoreDenormalMode)
777 .Default(std::nullopt);
778 if (MaybeKind)
779 MAI.InstrAuxDataRecords.push_back(
780 {MF, MI.getOperand(0).getReg(), *MaybeKind});
781 continue;
782 }
784 collectFuncNames(MI, &F);
785 } else if (TII->isConstantInstr(MI)) {
786 // Now OpSpecConstant*s are not in DT,
787 // but they need to be collected anyway.
789 } else if (OpCode == SPIRV::OpFunction) {
790 collectFuncNames(MI, &F);
791 } else if (OpCode == SPIRV::OpTypeForwardPointer) {
793 }
794 }
795 }
796 // Selection order can place a scope/list ahead of a domain/scope it
797 // references. The dependency meanwhile is domain -> scope -> list, so sort
798 // the def before its uses.
799 auto AliasingTier = [](const MachineInstr *MI) {
800 switch (MI->getOpcode()) {
801 case SPIRV::OpAliasDomainDeclINTEL:
802 return 0;
803 case SPIRV::OpAliasScopeDeclINTEL:
804 return 1;
805 case SPIRV::OpAliasScopeListDeclINTEL:
806 return 2;
807 default:
808 llvm_unreachable("unexpected aliasing instruction");
809 }
810 };
812 [&](const MachineInstr *LHS, const MachineInstr *RHS) {
813 return AliasingTier(LHS) < AliasingTier(RHS);
814 });
815}
816
817// Number registers in all functions globally from 0 onwards and store
818// the result in global register alias table. Some registers are already
819// numbered.
820void SPIRVModuleAnalysisImpl::numberRegistersGlobally(const Module &M) {
821 for (const Function &F : M) {
822 if (F.isDeclaration())
823 continue;
824 MachineFunction *MF = GetMF(F);
825 assert(MF);
826 for (MachineBasicBlock &MBB : *MF) {
827 for (MachineInstr &MI : MBB) {
828 for (MachineOperand &Op : MI.operands()) {
829 if (!Op.isReg())
830 continue;
831 Register Reg = Op.getReg();
832 if (MAI.hasRegisterAlias(MF, Reg))
833 continue;
834 MCRegister NewReg = MAI.getNextIDRegister();
835 MAI.setRegisterAlias(MF, Reg, NewReg);
836 }
837 if (MI.getOpcode() != SPIRV::OpExtInst)
838 continue;
839 auto Set = MI.getOperand(2).getImm();
840 auto [It, Inserted] = MAI.ExtInstSetMap.try_emplace(Set);
841 if (Inserted)
842 It->second = MAI.getNextIDRegister();
843 }
844 }
845 }
846}
847
849 const SPIRVSubtarget &ST,
850 StringRef Feature) {
851 if (!ST.isAtLeastSPIRVVer(VersionTuple(1, 3)))
852 report_fatal_error(Twine(Feature) + " requires SPIR-V 1.3", false);
853 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_quad_control))
854 report_fatal_error(Twine(Feature) + " requires the following SPIR-V "
855 "extension: SPV_KHR_quad_control",
856 false);
857 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_maximal_reconvergence))
858 report_fatal_error("SPV_KHR_quad_control requires the following SPIR-V "
859 "extension: SPV_KHR_maximal_reconvergence",
860 false);
861 Reqs.addExtension(SPIRV::Extension::SPV_KHR_quad_control);
862 Reqs.addExtension(SPIRV::Extension::SPV_KHR_maximal_reconvergence);
863}
864
865// RequirementHandler implementations.
867 SPIRV::OperandCategory::OperandCategory Category, uint32_t i,
868 const SPIRVSubtarget &ST) {
869 if (Category == SPIRV::OperandCategory::ExecutionModeOperand &&
870 (i == SPIRV::ExecutionMode::QuadDerivativesKHR ||
871 i == SPIRV::ExecutionMode::RequireFullQuadsKHR))
873 getSymbolicOperandMnemonic(Category, i));
874 if (Category == SPIRV::OperandCategory::ExecutionModeOperand &&
875 (i == SPIRV::ExecutionMode::DerivativeGroupQuadsKHR ||
876 i == SPIRV::ExecutionMode::DerivativeGroupLinearKHR) &&
877 !ST.canUseExtension(SPIRV::Extension::SPV_KHR_compute_shader_derivatives))
879 " requires the following SPIR-V extension: "
880 "SPV_KHR_compute_shader_derivatives",
881 false);
882 addRequirements(getSymbolicOperandRequirements(Category, i, ST, *this));
883}
884
885void SPIRV::RequirementHandler::recursiveAddCapabilities(
886 const CapabilityList &ToPrune) {
887 for (const auto &Cap : ToPrune) {
888 AllCaps.insert(Cap);
889 CapabilityList ImplicitDecls =
890 getSymbolicOperandCapabilities(OperandCategory::CapabilityOperand, Cap);
891 recursiveAddCapabilities(ImplicitDecls);
892 }
893}
894
896 for (const auto &Cap : ToAdd) {
897 bool IsNewlyInserted = AllCaps.insert(Cap).second;
898 if (!IsNewlyInserted) // Don't re-add if it's already been declared.
899 continue;
900 CapabilityList ImplicitDecls =
901 getSymbolicOperandCapabilities(OperandCategory::CapabilityOperand, Cap);
902 recursiveAddCapabilities(ImplicitDecls);
903 MinimalCaps.push_back(Cap);
904 }
905}
906
908 const SPIRV::Requirements &Req) {
909 if (!Req.IsSatisfiable)
910 report_fatal_error("Adding SPIR-V requirements this target can't satisfy.");
911
912 if (Req.Cap.has_value())
913 addCapabilities({Req.Cap.value()});
914
915 addExtensions(Req.Exts);
916
917 if (!Req.MinVer.empty()) {
918 if (!MaxVersion.empty() && Req.MinVer > MaxVersion) {
919 LLVM_DEBUG(dbgs() << "Conflicting version requirements: >= " << Req.MinVer
920 << " and <= " << MaxVersion << "\n");
921 report_fatal_error("Adding SPIR-V requirements that can't be satisfied.");
922 }
923
924 if (MinVersion.empty() || Req.MinVer > MinVersion)
925 MinVersion = Req.MinVer;
926 }
927
928 if (!Req.MaxVer.empty()) {
929 if (!MinVersion.empty() && Req.MaxVer < MinVersion) {
930 LLVM_DEBUG(dbgs() << "Conflicting version requirements: <= " << Req.MaxVer
931 << " and >= " << MinVersion << "\n");
932 report_fatal_error("Adding SPIR-V requirements that can't be satisfied.");
933 }
934
935 if (MaxVersion.empty() || Req.MaxVer < MaxVersion)
936 MaxVersion = Req.MaxVer;
937 }
938}
939
941 const SPIRVSubtarget &ST) const {
942 // Report as many errors as possible before aborting the compilation.
943 bool IsSatisfiable = true;
944 auto TargetVer = ST.getSPIRVVersion();
945
946 if (!MaxVersion.empty() && !TargetVer.empty() && MaxVersion < TargetVer) {
948 dbgs() << "Target SPIR-V version too high for required features\n"
949 << "Required max version: " << MaxVersion << " target version "
950 << TargetVer << "\n");
951 IsSatisfiable = false;
952 }
953
954 if (!MinVersion.empty() && !TargetVer.empty() && MinVersion > TargetVer) {
955 LLVM_DEBUG(dbgs() << "Target SPIR-V version too low for required features\n"
956 << "Required min version: " << MinVersion
957 << " target version " << TargetVer << "\n");
958 IsSatisfiable = false;
959 }
960
961 if (!MinVersion.empty() && !MaxVersion.empty() && MinVersion > MaxVersion) {
963 dbgs()
964 << "Version is too low for some features and too high for others.\n"
965 << "Required SPIR-V min version: " << MinVersion
966 << " required SPIR-V max version " << MaxVersion << "\n");
967 IsSatisfiable = false;
968 }
969
970 for (auto Cap : MinimalCaps) {
971 if (AvailableCaps.contains(Cap) && !shouldAvoidCapability(ST, Cap))
972 continue;
973 LLVM_DEBUG(dbgs() << "Capability not supported: "
975 OperandCategory::CapabilityOperand, Cap)
976 << "\n");
977 IsSatisfiable = false;
978 }
979
980 for (auto Ext : AllExtensions) {
981 if (ST.canUseExtension(Ext))
982 continue;
983 LLVM_DEBUG(dbgs() << "Extension not supported: "
985 OperandCategory::ExtensionOperand, Ext)
986 << "\n");
987 IsSatisfiable = false;
988 }
989
990 if (!IsSatisfiable)
991 report_fatal_error("Unable to meet SPIR-V requirements for this target.");
992}
993
994// Add the given capabilities and all their implicitly defined capabilities too.
996 for (const auto Cap : ToAdd)
997 if (AvailableCaps.insert(Cap).second)
999 SPIRV::OperandCategory::CapabilityOperand, Cap));
1000}
1001
1003 const Capability::Capability ToRemove,
1004 const Capability::Capability IfPresent) {
1005 if (AllCaps.contains(IfPresent)) {
1006 AllCaps.erase(ToRemove);
1007 llvm::erase(MinimalCaps, ToRemove);
1008 }
1009}
1010
1011namespace llvm {
1012namespace SPIRV {
1014 // Provided by both all supported Vulkan versions and OpenCl.
1015 addAvailableCaps({Capability::Shader, Capability::Linkage, Capability::Int8,
1016 Capability::Int16});
1017
1018 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 3)))
1019 addAvailableCaps({Capability::GroupNonUniform,
1020 Capability::GroupNonUniformVote,
1021 Capability::GroupNonUniformArithmetic,
1022 Capability::GroupNonUniformBallot,
1023 Capability::GroupNonUniformClustered,
1024 Capability::GroupNonUniformShuffle,
1025 Capability::GroupNonUniformShuffleRelative,
1026 Capability::GroupNonUniformQuad});
1027
1028 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 6)))
1029 addAvailableCaps({Capability::DotProduct, Capability::DotProductInputAll,
1030 Capability::DotProductInput4x8Bit,
1031 Capability::DotProductInput4x8BitPacked,
1032 Capability::DemoteToHelperInvocation});
1033
1034 // Add capabilities enabled by extensions.
1035 for (auto Extension : ST.getAllAvailableExtensions()) {
1036 CapabilityList EnabledCapabilities =
1038 addAvailableCaps(EnabledCapabilities);
1039 }
1040
1041 // EXT and NV use the same capability.
1042 if (ST.canUseExtension(Extension::SPV_EXT_shader_subgroup_partitioned))
1043 addAvailableCaps({Capability::GroupNonUniformPartitionedNV});
1044
1045 if (!ST.isShader()) {
1046 initAvailableCapabilitiesForOpenCL(ST);
1047 return;
1048 }
1049
1050 if (ST.isShader()) {
1051 initAvailableCapabilitiesForVulkan(ST);
1052 return;
1053 }
1054
1055 report_fatal_error("Unimplemented environment for SPIR-V generation.");
1056}
1057
1058void RequirementHandler::initAvailableCapabilitiesForOpenCL(
1059 const SPIRVSubtarget &ST) {
1060 // Add the min requirements for different OpenCL and SPIR-V versions.
1061 addAvailableCaps({Capability::Addresses, Capability::Float16Buffer,
1062 Capability::Kernel, Capability::Vector16,
1063 Capability::Groups, Capability::GenericPointer,
1064 Capability::StorageImageWriteWithoutFormat,
1065 Capability::StorageImageReadWithoutFormat});
1066 if (ST.hasOpenCLFullProfile())
1067 addAvailableCaps({Capability::Int64, Capability::Int64Atomics});
1068 if (ST.hasOpenCLImageSupport()) {
1069 addAvailableCaps({Capability::ImageBasic, Capability::LiteralSampler,
1070 Capability::Image1D, Capability::SampledBuffer,
1071 Capability::ImageBuffer});
1072 if (ST.isAtLeastOpenCLVer(VersionTuple(2, 0)))
1073 addAvailableCaps({Capability::ImageReadWrite});
1074 }
1075 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 1)) &&
1076 ST.isAtLeastOpenCLVer(VersionTuple(2, 2)))
1077 addAvailableCaps({Capability::SubgroupDispatch, Capability::PipeStorage});
1078 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 4)))
1079 addAvailableCaps({Capability::DenormPreserve, Capability::DenormFlushToZero,
1080 Capability::SignedZeroInfNanPreserve,
1081 Capability::RoundingModeRTE,
1082 Capability::RoundingModeRTZ});
1083 // TODO: verify if this needs some checks.
1084 addAvailableCaps({Capability::Float16, Capability::Float64});
1085
1086 // TODO: add OpenCL extensions.
1087}
1088
1089void RequirementHandler::initAvailableCapabilitiesForVulkan(
1090 const SPIRVSubtarget &ST) {
1091
1092 // Core in Vulkan 1.1 and earlier.
1093 addAvailableCaps({Capability::Int64,
1094 Capability::Geometry,
1095 Capability::Float16,
1096 Capability::Float64,
1097 Capability::GroupNonUniform,
1098 Capability::Image1D,
1099 Capability::SampledBuffer,
1100 Capability::ImageBuffer,
1101 Capability::UniformBufferArrayDynamicIndexing,
1102 Capability::SampledImageArrayDynamicIndexing,
1103 Capability::StorageBufferArrayDynamicIndexing,
1104 Capability::StorageImageArrayDynamicIndexing,
1105 Capability::DerivativeControl,
1106 Capability::SampleRateShading,
1107 Capability::MinLod,
1108 Capability::ImageQuery,
1109 Capability::ImageGatherExtended,
1110 Capability::Addresses,
1111 Capability::VulkanMemoryModelKHR,
1112 Capability::StorageImageExtendedFormats,
1113 Capability::StorageImageMultisample,
1114 Capability::ImageMSArray});
1115
1116 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 3)) ||
1117 ST.canUseExtension(Extension::SPV_KHR_variable_pointers))
1118 addAvailableCaps({Capability::VariablePointersStorageBuffer,
1119 Capability::VariablePointers});
1120
1121 // Became core in Vulkan 1.1.
1122 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 3)))
1123 addAvailableCaps({Capability::DrawParameters, Capability::MultiView});
1124
1125 // Became core in Vulkan 1.2
1126 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 5))) {
1128 {Capability::Int64Atomics, Capability::ShaderNonUniformEXT,
1129 Capability::RuntimeDescriptorArrayEXT,
1130 Capability::InputAttachmentArrayDynamicIndexingEXT,
1131 Capability::UniformTexelBufferArrayDynamicIndexingEXT,
1132 Capability::StorageTexelBufferArrayDynamicIndexingEXT,
1133 Capability::UniformBufferArrayNonUniformIndexingEXT,
1134 Capability::SampledImageArrayNonUniformIndexingEXT,
1135 Capability::StorageBufferArrayNonUniformIndexingEXT,
1136 Capability::StorageImageArrayNonUniformIndexingEXT,
1137 Capability::InputAttachmentArrayNonUniformIndexingEXT,
1138 Capability::UniformTexelBufferArrayNonUniformIndexingEXT,
1139 Capability::StorageTexelBufferArrayNonUniformIndexingEXT});
1140 }
1141
1142 // Became core in Vulkan 1.3
1143 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 6)))
1144 addAvailableCaps({Capability::StorageImageWriteWithoutFormat,
1145 Capability::StorageImageReadWithoutFormat});
1146}
1147
1148} // namespace SPIRV
1149} // namespace llvm
1150
1151// Add a capability that became core in SPIR-V 1.3. Earlier versions require
1152// the extension that introduced it.
1154 const SPIRVSubtarget &ST,
1155 SPIRV::Capability::Capability Cap,
1156 SPIRV::Extension::Extension Ext) {
1157 Reqs.addCapability(Cap);
1158 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 3)))
1159 return;
1160 if (!ST.canUseExtension(Ext))
1162 Twine("capability ") +
1164 SPIRV::OperandCategory::CapabilityOperand, Cap) +
1165 " requires SPIR-V 1.3 or the following SPIR-V extension: " +
1166 getSymbolicOperandMnemonic(SPIRV::OperandCategory::ExtensionOperand,
1167 Ext),
1168 false);
1169 Reqs.addExtension(Ext);
1170}
1171
1172// Add the required capabilities from a decoration instruction (including
1173// BuiltIns).
1174static void addOpDecorateReqs(const MachineInstr &MI, unsigned DecIndex,
1176 const SPIRVSubtarget &ST) {
1177 int64_t DecOp = MI.getOperand(DecIndex).getImm();
1178 auto Dec = static_cast<SPIRV::Decoration::Decoration>(DecOp);
1180 SPIRV::OperandCategory::DecorationOperand, Dec, ST, Reqs));
1181
1182 if (Dec == SPIRV::Decoration::BuiltIn) {
1183 int64_t BuiltInOp = MI.getOperand(DecIndex + 1).getImm();
1184 auto BuiltIn = static_cast<SPIRV::BuiltIn::BuiltIn>(BuiltInOp);
1185 if ((BuiltIn == SPIRV::BuiltIn::BaryCoordKHR ||
1186 BuiltIn == SPIRV::BuiltIn::BaryCoordNoPerspKHR) &&
1187 !ST.canUseExtension(
1188 SPIRV::Extension::SPV_KHR_fragment_shader_barycentric))
1190 "Barycentric built-ins require the following SPIR-V extension: "
1191 "SPV_KHR_fragment_shader_barycentric",
1192 false);
1193 if (BuiltIn == SPIRV::BuiltIn::FragStencilRefEXT &&
1194 !ST.canUseExtension(SPIRV::Extension::SPV_EXT_shader_stencil_export))
1196 "FragStencilRefEXT requires the following SPIR-V extension: "
1197 "SPV_EXT_shader_stencil_export",
1198 false);
1199 switch (BuiltIn) {
1200 case SPIRV::BuiltIn::BaseVertex:
1201 case SPIRV::BuiltIn::BaseInstance:
1203 Reqs, ST, SPIRV::Capability::DrawParameters,
1204 SPIRV::Extension::SPV_KHR_shader_draw_parameters);
1205 break;
1206 case SPIRV::BuiltIn::ViewIndex:
1207 addCoreInSPIRV13Capability(Reqs, ST, SPIRV::Capability::MultiView,
1208 SPIRV::Extension::SPV_KHR_multiview);
1209 break;
1210 default:
1212 SPIRV::OperandCategory::BuiltInOperand, BuiltIn, ST, Reqs));
1213 break;
1214 }
1215 } else if (Dec == SPIRV::Decoration::LinkageAttributes) {
1216 int64_t LinkageOp = MI.getOperand(MI.getNumOperands() - 1).getImm();
1217 SPIRV::LinkageType::LinkageType LnkType =
1218 static_cast<SPIRV::LinkageType::LinkageType>(LinkageOp);
1219 if (LnkType == SPIRV::LinkageType::LinkOnceODR)
1220 Reqs.addExtension(SPIRV::Extension::SPV_KHR_linkonce_odr);
1221 else if (LnkType == SPIRV::LinkageType::WeakAMD) {
1222 Reqs.addExtension(SPIRV::Extension::SPV_AMD_weak_linkage);
1223 Reqs.addCapability(SPIRV::Capability::WeakLinkageAMD);
1224 }
1225 } else if (Dec == SPIRV::Decoration::CacheControlLoadINTEL ||
1226 Dec == SPIRV::Decoration::CacheControlStoreINTEL) {
1227 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_cache_controls);
1228 } else if (Dec == SPIRV::Decoration::HostAccessINTEL) {
1229 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_global_variable_host_access);
1230 } else if (Dec == SPIRV::Decoration::InitModeINTEL ||
1231 Dec == SPIRV::Decoration::ImplementInRegisterMapINTEL) {
1232 Reqs.addExtension(
1233 SPIRV::Extension::SPV_INTEL_global_variable_fpga_decorations);
1234 } else if (Dec == SPIRV::Decoration::NonUniformEXT) {
1235 Reqs.addRequirements(SPIRV::Capability::ShaderNonUniformEXT);
1236 } else if (Dec == SPIRV::Decoration::FPMaxErrorDecorationINTEL) {
1237 Reqs.addRequirements(SPIRV::Capability::FPMaxErrorINTEL);
1238 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_fp_max_error);
1239 } else if (Dec == SPIRV::Decoration::FPFastMathMode) {
1240 if (ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2)) {
1241 Reqs.addRequirements(SPIRV::Capability::FloatControls2);
1242 Reqs.addExtension(SPIRV::Extension::SPV_KHR_float_controls2);
1243 }
1244 }
1245}
1246
1247// Add requirements for image handling.
1250 const SPIRVSubtarget &ST) {
1251 assert(MI.getNumOperands() >= 8 && "Insufficient operands for OpTypeImage");
1252 // The operand indices used here are based on the OpTypeImage layout, which
1253 // the MachineInstr follows as well.
1254 int64_t ImgFormatOp = MI.getOperand(7).getImm();
1255 auto ImgFormat = static_cast<SPIRV::ImageFormat::ImageFormat>(ImgFormatOp);
1256 Reqs.getAndAddRequirements(SPIRV::OperandCategory::ImageFormatOperand,
1257 ImgFormat, ST);
1258
1259 bool IsArrayed = MI.getOperand(4).getImm() == 1;
1260 bool IsMultisampled = MI.getOperand(5).getImm() == 1;
1261 bool NoSampler = MI.getOperand(6).getImm() == 2;
1262 // Add dimension requirements.
1263 assert(MI.getOperand(2).isImm());
1264 switch (MI.getOperand(2).getImm()) {
1265 case SPIRV::Dim::DIM_1D:
1266 Reqs.addRequirements(NoSampler ? SPIRV::Capability::Image1D
1267 : SPIRV::Capability::Sampled1D);
1268 break;
1269 case SPIRV::Dim::DIM_2D:
1270 if (IsMultisampled && NoSampler)
1271 Reqs.addRequirements(SPIRV::Capability::StorageImageMultisample);
1272 if (IsMultisampled && IsArrayed)
1273 Reqs.addRequirements(SPIRV::Capability::ImageMSArray);
1274 break;
1275 case SPIRV::Dim::DIM_3D:
1276 break;
1277 case SPIRV::Dim::DIM_Cube:
1278 Reqs.addRequirements(SPIRV::Capability::Shader);
1279 if (IsArrayed)
1280 Reqs.addRequirements(NoSampler ? SPIRV::Capability::ImageCubeArray
1281 : SPIRV::Capability::SampledCubeArray);
1282 break;
1283 case SPIRV::Dim::DIM_Rect:
1284 Reqs.addRequirements(NoSampler ? SPIRV::Capability::ImageRect
1285 : SPIRV::Capability::SampledRect);
1286 break;
1287 case SPIRV::Dim::DIM_Buffer:
1288 Reqs.addRequirements(NoSampler ? SPIRV::Capability::ImageBuffer
1289 : SPIRV::Capability::SampledBuffer);
1290 break;
1291 case SPIRV::Dim::DIM_SubpassData:
1292 Reqs.addRequirements(SPIRV::Capability::InputAttachment);
1293 break;
1294 }
1295
1296 // Has optional access qualifier.
1297 if (!ST.isShader()) {
1298 if (MI.getNumOperands() > 8 &&
1299 MI.getOperand(8).getImm() == SPIRV::AccessQualifier::ReadWrite)
1300 Reqs.addRequirements(SPIRV::Capability::ImageReadWrite);
1301 else
1302 Reqs.addRequirements(SPIRV::Capability::ImageBasic);
1303 }
1304}
1305
1306static bool isBFloat16Type(SPIRVTypeInst TypeDef) {
1307 return TypeDef && TypeDef->getNumOperands() == 3 &&
1308 TypeDef->getOpcode() == SPIRV::OpTypeFloat &&
1309 TypeDef->getOperand(1).getImm() == 16 &&
1310 TypeDef->getOperand(2).getImm() == SPIRV::FPEncoding::BFloat16KHR;
1311}
1312
1313// Adds the requirements for bfloat16 arithmetic. Prefers
1314// SPV_EXT_bfloat16_arithmetic and falls back to the legacy
1315// SPV_INTEL_bfloat16_arithmetic which enables the same capability.
1317 const SPIRVSubtarget &ST) {
1318 if (ST.canUseExtension(SPIRV::Extension::SPV_EXT_bfloat16_arithmetic)) {
1319 Reqs.addExtension(SPIRV::Extension::SPV_EXT_bfloat16_arithmetic);
1320 Reqs.addCapability(SPIRV::Capability::BFloat16ArithmeticEXT);
1321 return true;
1322 }
1323 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_bfloat16_arithmetic)) {
1324 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_bfloat16_arithmetic);
1325 Reqs.addCapability(SPIRV::Capability::BFloat16ArithmeticINTEL);
1326 return true;
1327 }
1328 return false;
1329}
1330
1331// Registers created after isel (e.g. by MachineCSE) may lack registry entries.
1332// Fall back to the defining instruction's result type.
1334 const SPIRVGlobalRegistry *GR) {
1335 if (SPIRVTypeInst Ty = GR->getSPIRVTypeForVReg(Reg, &MF))
1336 return Ty;
1337 const MachineRegisterInfo &MRI = MF.getRegInfo();
1338 return MRI.getVRegDef(MRI.getVRegDef(Reg)->getOperand(1).getReg());
1339}
1340
1341// Add requirements for handling atomic float instructions
1342#define ATOM_FLT_REQ_EXT_MSG(ExtName) \
1343 "The atomic float instruction requires the following SPIR-V " \
1344 "extension: SPV_EXT_shader_atomic_float" ExtName
1347 const SPIRVSubtarget &ST) {
1348 SPIRVTypeInst VecTypeDef =
1349 MI.getMF()->getRegInfo().getVRegDef(MI.getOperand(1).getReg());
1350
1351 const unsigned Rank = VecTypeDef->getOperand(2).getImm();
1352 if (Rank != 2 && Rank != 4)
1353 reportFatalUsageError("Result type of an atomic vector float instruction "
1354 "must be a 2-component or 4 component vector");
1355
1356 SPIRVTypeInst EltTypeDef =
1357 MI.getMF()->getRegInfo().getVRegDef(VecTypeDef->getOperand(1).getReg());
1358
1359 if (EltTypeDef->getOpcode() != SPIRV::OpTypeFloat ||
1360 EltTypeDef->getOperand(1).getImm() != 16)
1362 "The element type for the result type of an atomic vector float "
1363 "instruction must be a 16-bit floating-point scalar");
1364
1365 // The extension is defined for fp16, but the AMD target lets a bf16 vector
1366 // use the same instruction so it can lower to a packed bf16 atomic.
1367 if (isBFloat16Type(EltTypeDef) &&
1368 ST.getTargetTriple().getVendor() != Triple::AMD)
1370 "The element type for the result type of an atomic vector float "
1371 "instruction cannot be a bfloat16 scalar");
1372 if (!ST.canUseExtension(SPIRV::Extension::SPV_NV_shader_atomic_fp16_vector))
1374 "The atomic float16 vector instruction requires the following SPIR-V "
1375 "extension: SPV_NV_shader_atomic_fp16_vector");
1376
1377 Reqs.addExtension(SPIRV::Extension::SPV_NV_shader_atomic_fp16_vector);
1378 Reqs.addCapability(SPIRV::Capability::AtomicFloat16VectorNV);
1379}
1380
1383 const SPIRVSubtarget &ST) {
1384 assert(MI.getOperand(1).isReg() &&
1385 "Expect register operand in atomic float instruction");
1386 Register TypeReg = MI.getOperand(1).getReg();
1387 SPIRVTypeInst TypeDef = MI.getMF()->getRegInfo().getVRegDef(TypeReg);
1388
1389 if (isVectorType(TypeDef))
1390 return AddAtomicVectorFloatRequirements(MI, Reqs, ST);
1391
1392 if (TypeDef->getOpcode() != SPIRV::OpTypeFloat)
1393 report_fatal_error("Result type of an atomic float instruction must be a "
1394 "floating-point type scalar");
1395
1396 unsigned BitWidth = TypeDef->getOperand(1).getImm();
1397 unsigned Op = MI.getOpcode();
1398 if (Op == SPIRV::OpAtomicFAddEXT) {
1399 if (!ST.canUseExtension(SPIRV::Extension::SPV_EXT_shader_atomic_float_add))
1401 Reqs.addExtension(SPIRV::Extension::SPV_EXT_shader_atomic_float_add);
1402 switch (BitWidth) {
1403 case 16:
1404 if (isBFloat16Type(TypeDef)) {
1405 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics))
1407 "The atomic bfloat16 instruction requires the following SPIR-V "
1408 "extension: SPV_INTEL_16bit_atomics",
1409 false);
1410 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics);
1411 Reqs.addCapability(SPIRV::Capability::AtomicBFloat16AddINTEL);
1412 } else {
1413 if (!ST.canUseExtension(
1414 SPIRV::Extension::SPV_EXT_shader_atomic_float16_add))
1415 report_fatal_error(ATOM_FLT_REQ_EXT_MSG("16_add"), false);
1416 Reqs.addExtension(SPIRV::Extension::SPV_EXT_shader_atomic_float16_add);
1417 Reqs.addCapability(SPIRV::Capability::AtomicFloat16AddEXT);
1418 }
1419 break;
1420 case 32:
1421 Reqs.addCapability(SPIRV::Capability::AtomicFloat32AddEXT);
1422 break;
1423 case 64:
1424 Reqs.addCapability(SPIRV::Capability::AtomicFloat64AddEXT);
1425 break;
1426 default:
1428 "Unexpected floating-point type width in atomic float instruction");
1429 }
1430 } else {
1431 if (!ST.canUseExtension(
1432 SPIRV::Extension::SPV_EXT_shader_atomic_float_min_max))
1433 report_fatal_error(ATOM_FLT_REQ_EXT_MSG("_min_max"), false);
1434 Reqs.addExtension(SPIRV::Extension::SPV_EXT_shader_atomic_float_min_max);
1435 switch (BitWidth) {
1436 case 16:
1437 if (isBFloat16Type(TypeDef)) {
1438 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics))
1440 "The atomic bfloat16 instruction requires the following SPIR-V "
1441 "extension: SPV_INTEL_16bit_atomics",
1442 false);
1443 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics);
1444 Reqs.addCapability(SPIRV::Capability::AtomicBFloat16MinMaxINTEL);
1445 } else {
1446 Reqs.addCapability(SPIRV::Capability::AtomicFloat16MinMaxEXT);
1447 }
1448 break;
1449 case 32:
1450 Reqs.addCapability(SPIRV::Capability::AtomicFloat32MinMaxEXT);
1451 break;
1452 case 64:
1453 Reqs.addCapability(SPIRV::Capability::AtomicFloat64MinMaxEXT);
1454 break;
1455 default:
1457 "Unexpected floating-point type width in atomic float instruction");
1458 }
1459 }
1460}
1461
1463 if (ImageInst->getOpcode() != SPIRV::OpTypeImage)
1464 return false;
1465 uint32_t Dim = ImageInst->getOperand(2).getImm();
1466 uint32_t Sampled = ImageInst->getOperand(6).getImm();
1467 return Dim == SPIRV::Dim::DIM_Buffer && Sampled == 1;
1468}
1469
1471 if (ImageInst->getOpcode() != SPIRV::OpTypeImage)
1472 return false;
1473 uint32_t Dim = ImageInst->getOperand(2).getImm();
1474 uint32_t Sampled = ImageInst->getOperand(6).getImm();
1475 return Dim == SPIRV::Dim::DIM_Buffer && Sampled == 2;
1476}
1477
1479 if (ImageInst->getOpcode() != SPIRV::OpTypeImage)
1480 return false;
1481 uint32_t Dim = ImageInst->getOperand(2).getImm();
1482 uint32_t Sampled = ImageInst->getOperand(6).getImm();
1483 return Dim != SPIRV::Dim::DIM_Buffer && Sampled == 1;
1484}
1485
1487 if (ImageInst->getOpcode() != SPIRV::OpTypeImage)
1488 return false;
1489 uint32_t Dim = ImageInst->getOperand(2).getImm();
1490 uint32_t Sampled = ImageInst->getOperand(6).getImm();
1491 return Dim == SPIRV::Dim::DIM_SubpassData && Sampled == 2;
1492}
1493
1495 if (ImageInst->getOpcode() != SPIRV::OpTypeImage)
1496 return false;
1497 uint32_t Dim = ImageInst->getOperand(2).getImm();
1498 uint32_t Sampled = ImageInst->getOperand(6).getImm();
1499 return Dim != SPIRV::Dim::DIM_Buffer && Sampled == 2;
1500}
1501
1502bool isCombinedImageSampler(MachineInstr *SampledImageInst) {
1503 if (SampledImageInst->getOpcode() != SPIRV::OpTypeSampledImage)
1504 return false;
1505
1506 const MachineRegisterInfo &MRI = SampledImageInst->getMF()->getRegInfo();
1507 Register ImageReg = SampledImageInst->getOperand(1).getReg();
1508 auto *ImageInst = MRI.getUniqueVRegDef(ImageReg);
1509 return isSampledImage(ImageInst);
1510}
1511
1513 for (const auto &MI : MRI.reg_instructions(Reg)) {
1514 if (MI.getOpcode() != SPIRV::OpDecorate)
1515 continue;
1516
1517 uint32_t Dec = MI.getOperand(1).getImm();
1518 if (Dec == SPIRV::Decoration::NonUniformEXT)
1519 return true;
1520 }
1521 return false;
1522}
1523
1526 const SPIRVSubtarget &Subtarget) {
1527 const MachineRegisterInfo &MRI = Instr.getMF()->getRegInfo();
1528 // Get the result type. If it is an image type, then the shader uses
1529 // descriptor indexing. The appropriate capabilities will be added based
1530 // on the specifics of the image.
1531 Register ResTypeReg = Instr.getOperand(1).getReg();
1532 MachineInstr *ResTypeInst = MRI.getUniqueVRegDef(ResTypeReg);
1533
1534 assert(ResTypeInst->getOpcode() == SPIRV::OpTypePointer);
1535 uint32_t StorageClass = ResTypeInst->getOperand(1).getImm();
1536 if (StorageClass != SPIRV::StorageClass::StorageClass::UniformConstant &&
1537 StorageClass != SPIRV::StorageClass::StorageClass::Uniform &&
1538 StorageClass != SPIRV::StorageClass::StorageClass::StorageBuffer) {
1539 return;
1540 }
1541
1542 bool IsNonUniform =
1543 hasNonUniformDecoration(Instr.getOperand(0).getReg(), MRI);
1544
1545 auto FirstIndexReg = Instr.getOperand(3).getReg();
1546 bool FirstIndexIsConstant =
1547 Subtarget.getInstrInfo()->isConstantInstr(*MRI.getVRegDef(FirstIndexReg));
1548
1549 if (StorageClass == SPIRV::StorageClass::StorageClass::StorageBuffer) {
1550 if (IsNonUniform)
1551 Handler.addRequirements(
1552 SPIRV::Capability::StorageBufferArrayNonUniformIndexingEXT);
1553 else if (!FirstIndexIsConstant)
1554 Handler.addRequirements(
1555 SPIRV::Capability::StorageBufferArrayDynamicIndexing);
1556 return;
1557 }
1558
1559 Register PointeeTypeReg = ResTypeInst->getOperand(2).getReg();
1560 MachineInstr *PointeeType = MRI.getUniqueVRegDef(PointeeTypeReg);
1561 if (PointeeType->getOpcode() != SPIRV::OpTypeImage &&
1562 PointeeType->getOpcode() != SPIRV::OpTypeSampledImage &&
1563 PointeeType->getOpcode() != SPIRV::OpTypeSampler) {
1564 return;
1565 }
1566
1567 if (isUniformTexelBuffer(PointeeType)) {
1568 if (IsNonUniform)
1569 Handler.addRequirements(
1570 SPIRV::Capability::UniformTexelBufferArrayNonUniformIndexingEXT);
1571 else if (!FirstIndexIsConstant)
1572 Handler.addRequirements(
1573 SPIRV::Capability::UniformTexelBufferArrayDynamicIndexingEXT);
1574 } else if (isInputAttachment(PointeeType)) {
1575 if (IsNonUniform)
1576 Handler.addRequirements(
1577 SPIRV::Capability::InputAttachmentArrayNonUniformIndexingEXT);
1578 else if (!FirstIndexIsConstant)
1579 Handler.addRequirements(
1580 SPIRV::Capability::InputAttachmentArrayDynamicIndexingEXT);
1581 } else if (isStorageTexelBuffer(PointeeType)) {
1582 if (IsNonUniform)
1583 Handler.addRequirements(
1584 SPIRV::Capability::StorageTexelBufferArrayNonUniformIndexingEXT);
1585 else if (!FirstIndexIsConstant)
1586 Handler.addRequirements(
1587 SPIRV::Capability::StorageTexelBufferArrayDynamicIndexingEXT);
1588 } else if (isSampledImage(PointeeType) ||
1589 isCombinedImageSampler(PointeeType) ||
1590 PointeeType->getOpcode() == SPIRV::OpTypeSampler) {
1591 if (IsNonUniform)
1592 Handler.addRequirements(
1593 SPIRV::Capability::SampledImageArrayNonUniformIndexingEXT);
1594 else if (!FirstIndexIsConstant)
1595 Handler.addRequirements(
1596 SPIRV::Capability::SampledImageArrayDynamicIndexing);
1597 } else if (isStorageImage(PointeeType)) {
1598 if (IsNonUniform)
1599 Handler.addRequirements(
1600 SPIRV::Capability::StorageImageArrayNonUniformIndexingEXT);
1601 else if (!FirstIndexIsConstant)
1602 Handler.addRequirements(
1603 SPIRV::Capability::StorageImageArrayDynamicIndexing);
1604 }
1605}
1606
1608 if (TypeInst->getOpcode() != SPIRV::OpTypeImage)
1609 return false;
1610 assert(TypeInst->getOperand(7).isImm() && "The image format must be an imm.");
1611 return TypeInst->getOperand(7).getImm() == 0;
1612}
1613
1616 const SPIRVSubtarget &ST) {
1617 if (ST.canUseExtension(SPIRV::Extension::SPV_KHR_integer_dot_product))
1618 Reqs.addExtension(SPIRV::Extension::SPV_KHR_integer_dot_product);
1619 Reqs.addCapability(SPIRV::Capability::DotProduct);
1620
1621 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1622 assert(MI.getOperand(2).isReg() && "Unexpected operand in dot");
1623 SPIRVTypeInst TypeDef = getRegType(MI.getOperand(2).getReg(), *MI.getMF(),
1624 ST.getSPIRVGlobalRegistry());
1625 assert(TypeDef && "Unexpected type instruction for dot input");
1626 if (TypeDef->getOpcode() == SPIRV::OpTypeInt) {
1627 assert(TypeDef->getOperand(1).getImm() == 32);
1628 Reqs.addCapability(SPIRV::Capability::DotProductInput4x8BitPacked);
1629 } else if (isVectorType(TypeDef)) {
1630 SPIRVTypeInst ScalarTypeDef =
1631 MRI.getVRegDef(TypeDef->getOperand(1).getReg());
1632 assert(ScalarTypeDef->getOpcode() == SPIRV::OpTypeInt);
1633 if (ScalarTypeDef->getOperand(1).getImm() == 8) {
1634 assert(TypeDef->getOperand(2).getImm() == 4 &&
1635 "Dot operand of 8-bit integer type requires 4 components");
1636 Reqs.addCapability(SPIRV::Capability::DotProductInput4x8Bit);
1637 } else {
1638 Reqs.addCapability(SPIRV::Capability::DotProductInputAll);
1639 }
1640 }
1641}
1642
1645 const SPIRVSubtarget &ST) {
1646 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
1647 SPIRVTypeInst PtrType =
1648 GR->getSPIRVTypeForVReg(MI.getOperand(4).getReg(), MI.getMF());
1649 if (PtrType) {
1650 MachineOperand ASOp = PtrType->getOperand(1);
1651 if (ASOp.isImm()) {
1652 unsigned AddrSpace = ASOp.getImm();
1653 if (AddrSpace != SPIRV::StorageClass::UniformConstant) {
1654 if (!ST.canUseExtension(
1656 SPV_EXT_relaxed_printf_string_address_space)) {
1657 report_fatal_error("SPV_EXT_relaxed_printf_string_address_space is "
1658 "required because printf uses a format string not "
1659 "in constant address space.",
1660 false);
1661 }
1662 Reqs.addExtension(
1663 SPIRV::Extension::SPV_EXT_relaxed_printf_string_address_space);
1664 }
1665 }
1666 }
1667}
1668
1671 const SPIRVSubtarget &ST, unsigned OpIdx) {
1672 if (MI.getNumOperands() <= OpIdx)
1673 return;
1674 uint32_t Mask = MI.getOperand(OpIdx).getImm();
1675 for (uint32_t I = 0; I < 32; ++I)
1676 if (Mask & (1U << I))
1677 Reqs.getAndAddRequirements(SPIRV::OperandCategory::ImageOperandOperand,
1678 1U << I, ST);
1679}
1680
1681static inline void maybeAddScatterGatherReq(const MachineInstr &MI,
1683 const SPIRVSubtarget &ST) {
1684 assert(MI.getOperand(1).isReg());
1685 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1686 SPIRVTypeInst ElemTypeDef = MRI.getVRegDef(MI.getOperand(1).getReg());
1687 if (ElemTypeDef->getOpcode() == SPIRV::OpTypePointer &&
1688 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
1689 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_masked_gather_scatter);
1690 Reqs.addCapability(SPIRV::Capability::MaskedGatherScatterINTEL);
1691 }
1692}
1693
1696 const SPIRVSubtarget &ST) {
1697 SPIRV::RequirementHandler &Reqs = MAI.Reqs;
1698 unsigned Op = MI.getOpcode();
1699 switch (Op) {
1700 case SPIRV::OpMemoryModel: {
1701 int64_t Addr = MI.getOperand(0).getImm();
1702 Reqs.getAndAddRequirements(SPIRV::OperandCategory::AddressingModelOperand,
1703 Addr, ST);
1704 int64_t Mem = MI.getOperand(1).getImm();
1705 Reqs.getAndAddRequirements(SPIRV::OperandCategory::MemoryModelOperand, Mem,
1706 ST);
1707 break;
1708 }
1709 case SPIRV::OpEntryPoint: {
1710 int64_t Exe = MI.getOperand(0).getImm();
1711 Reqs.getAndAddRequirements(SPIRV::OperandCategory::ExecutionModelOperand,
1712 Exe, ST);
1713 break;
1714 }
1715 case SPIRV::OpExecutionMode:
1716 case SPIRV::OpExecutionModeId: {
1717 int64_t Exe = MI.getOperand(1).getImm();
1718 Reqs.getAndAddRequirements(SPIRV::OperandCategory::ExecutionModeOperand,
1719 Exe, ST);
1720 break;
1721 }
1722 case SPIRV::OpTypeMatrix:
1723 Reqs.addCapability(SPIRV::Capability::Matrix);
1724 break;
1725 case SPIRV::OpTypeInt: {
1726 unsigned BitWidth = MI.getOperand(1).getImm();
1727 if (BitWidth == 64)
1728 Reqs.addCapability(SPIRV::Capability::Int64);
1729 else if (BitWidth == 16)
1730 Reqs.addCapability(SPIRV::Capability::Int16);
1731 else if (BitWidth == 8)
1732 Reqs.addCapability(SPIRV::Capability::Int8);
1733 else if (BitWidth == 4 &&
1734 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_int4)) {
1735 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_int4);
1736 Reqs.addCapability(SPIRV::Capability::Int4TypeINTEL);
1737 } else if (BitWidth != 32) {
1738 if (!ST.canUseExtension(
1739 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers))
1741 "OpTypeInt type with a width other than 8, 16, 32 or 64 bits "
1742 "requires the following SPIR-V extension: "
1743 "SPV_ALTERA_arbitrary_precision_integers");
1744 Reqs.addExtension(
1745 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers);
1746 Reqs.addCapability(SPIRV::Capability::ArbitraryPrecisionIntegersALTERA);
1747 }
1748 break;
1749 }
1750 case SPIRV::OpDot: {
1751 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1752 SPIRVTypeInst TypeDef = MRI.getVRegDef(MI.getOperand(1).getReg());
1753 if (isBFloat16Type(TypeDef))
1754 Reqs.addCapability(SPIRV::Capability::BFloat16DotProductKHR);
1755 break;
1756 }
1757 case SPIRV::OpTypeFloat: {
1758 unsigned BitWidth = MI.getOperand(1).getImm();
1759 if (BitWidth == 64)
1760 Reqs.addCapability(SPIRV::Capability::Float64);
1761 else if (BitWidth == 16) {
1762 if (isBFloat16Type(&MI)) {
1763 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_bfloat16))
1764 report_fatal_error("OpTypeFloat type with bfloat requires the "
1765 "following SPIR-V extension: SPV_KHR_bfloat16",
1766 false);
1767 Reqs.addExtension(SPIRV::Extension::SPV_KHR_bfloat16);
1768 Reqs.addCapability(SPIRV::Capability::BFloat16TypeKHR);
1769 } else {
1770 Reqs.addCapability(SPIRV::Capability::Float16);
1771 }
1772 }
1773 break;
1774 }
1775 case SPIRV::OpTypeVector: {
1776 unsigned NumComponents = MI.getOperand(2).getImm();
1777 if (NumComponents == 8 || NumComponents == 16)
1778 Reqs.addCapability(SPIRV::Capability::Vector16);
1779 else if (requiresLongVectorEXT(NumComponents))
1780 // Such widths are only expressible as OpTypeVectorIdEXT.
1782 "OpTypeVector with " + Twine(NumComponents) +
1783 " components requires the following SPIR-V extension: "
1784 "SPV_EXT_long_vector");
1785
1786 maybeAddScatterGatherReq(MI, Reqs, ST);
1787 break;
1788 }
1789 case SPIRV::OpTypeVectorIdEXT: {
1790 if (!ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector))
1791 reportFatalUsageError("OpTypeVectorIdEXT requires the following SPIR-V "
1792 "extension: SPV_EXT_long_vector extension");
1793 Reqs.addExtension(SPIRV::Extension::SPV_EXT_long_vector);
1794 Reqs.addCapability(SPIRV::Capability::LongVectorEXT);
1795 maybeAddScatterGatherReq(MI, Reqs, ST);
1796 break;
1797 }
1798 case SPIRV::OpTypePointer: {
1799 auto SC = MI.getOperand(1).getImm();
1800 Reqs.getAndAddRequirements(SPIRV::OperandCategory::StorageClassOperand, SC,
1801 ST);
1802 // If it's a type of pointer to float16 targeting OpenCL, add Float16Buffer
1803 // capability.
1804 if (ST.isShader())
1805 break;
1806 assert(MI.getOperand(2).isReg());
1807 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1808 SPIRVTypeInst TypeDef = MRI.getVRegDef(MI.getOperand(2).getReg());
1809 if ((TypeDef->getNumOperands() == 2) &&
1810 (TypeDef->getOpcode() == SPIRV::OpTypeFloat) &&
1811 (TypeDef->getOperand(1).getImm() == 16))
1812 Reqs.addCapability(SPIRV::Capability::Float16Buffer);
1813 break;
1814 }
1815 case SPIRV::OpExtInst: {
1816 if (MI.getOperand(2).getImm() ==
1817 static_cast<int64_t>(
1818 SPIRV::InstructionSet::NonSemantic_Shader_DebugInfo_100)) {
1819 Reqs.addExtension(SPIRV::Extension::SPV_KHR_non_semantic_info);
1820 break;
1821 }
1822 if (MI.getOperand(2).getImm() ==
1823 static_cast<int64_t>(SPIRV::InstructionSet::NonSemantic_DebugBreak)) {
1824 // Non-semantic instruction sets no longer require
1825 // SPV_KHR_non_semantic_info as of SPIR-V 1.6
1826 if (!ST.isAtLeastSPIRVVer(VersionTuple(1, 6)))
1827 Reqs.addExtension(SPIRV::Extension::SPV_KHR_non_semantic_info);
1828 break;
1829 }
1830 if (MI.getOperand(3).getImm() ==
1831 static_cast<int64_t>(SPIRV::OpenCLExtInst::printf)) {
1832 addPrintfRequirements(MI, Reqs, ST);
1833 break;
1834 }
1835 if (MI.getOperand(2).getImm() ==
1836 static_cast<int64_t>(SPIRV::InstructionSet::OpenCL_std)) {
1837 const MachineFunction *MF = MI.getMF();
1838 const MachineRegisterInfo &MRI = MF->getRegInfo();
1839 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
1840
1841 auto IsBFloat16 = [&](SPIRVTypeInst TypeDef) {
1842 if (TypeDef && TypeDef->getOpcode() == SPIRV::OpTypeVector)
1843 TypeDef = MRI.getVRegDef(TypeDef->getOperand(1).getReg());
1844 return isBFloat16Type(TypeDef);
1845 };
1846
1847 // Result type is operand 1; arguments start at operand 4.
1848 bool UsesBFloat16 = IsBFloat16(MRI.getVRegDef(MI.getOperand(1).getReg()));
1849 for (unsigned I = 4, E = MI.getNumOperands(); I < E && !UsesBFloat16;
1850 ++I) {
1851 const MachineOperand &MO = MI.getOperand(I);
1852 if (MO.isReg())
1853 UsesBFloat16 = IsBFloat16(GR->getResultType(
1854 MO.getReg(), const_cast<MachineFunction *>(MF)));
1855 }
1856
1857 if (UsesBFloat16 && !addBFloat16ArithmeticRequirements(Reqs, ST))
1859 MI, "OpenCL Extended instructions with bfloat16 require the "
1860 "following SPIR-V extension: SPV_EXT_bfloat16_arithmetic");
1861 }
1862 break;
1863 }
1864 case SPIRV::OpAliasDomainDeclINTEL:
1865 case SPIRV::OpAliasScopeDeclINTEL:
1866 case SPIRV::OpAliasScopeListDeclINTEL: {
1867 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing);
1868 Reqs.addCapability(SPIRV::Capability::MemoryAccessAliasingINTEL);
1869 break;
1870 }
1871 case SPIRV::OpBitReverse:
1872 case SPIRV::OpBitFieldInsert:
1873 case SPIRV::OpBitFieldSExtract:
1874 case SPIRV::OpBitFieldUExtract:
1875 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_bit_instructions)) {
1876 Reqs.addCapability(SPIRV::Capability::Shader);
1877 break;
1878 }
1879 Reqs.addExtension(SPIRV::Extension::SPV_KHR_bit_instructions);
1880 Reqs.addCapability(SPIRV::Capability::BitInstructions);
1881 break;
1882 case SPIRV::OpTypeRuntimeArray:
1883 Reqs.addCapability(SPIRV::Capability::Shader);
1884 break;
1885 case SPIRV::OpTypeOpaque:
1886 case SPIRV::OpTypeEvent:
1887 Reqs.addCapability(SPIRV::Capability::Kernel);
1888 break;
1889 case SPIRV::OpTypePipe:
1890 case SPIRV::OpTypeReserveId:
1891 Reqs.addCapability(SPIRV::Capability::Pipes);
1892 break;
1893 case SPIRV::OpTypePipeStorage:
1894 Reqs.addCapability(SPIRV::Capability::PipeStorage);
1895 break;
1896 case SPIRV::OpTypeDeviceEvent:
1897 case SPIRV::OpTypeQueue:
1898 case SPIRV::OpBuildNDRange:
1899 case SPIRV::OpEnqueueKernel:
1900 case SPIRV::OpGetKernelNDrangeSubGroupCount:
1901 case SPIRV::OpGetKernelNDrangeMaxSubGroupSize:
1902 case SPIRV::OpGetKernelWorkGroupSize:
1903 case SPIRV::OpGetKernelPreferredWorkGroupSizeMultiple:
1904 Reqs.addCapability(SPIRV::Capability::DeviceEnqueue);
1905 break;
1906 case SPIRV::OpDecorate:
1907 case SPIRV::OpDecorateId:
1908 case SPIRV::OpDecorateString:
1909 addOpDecorateReqs(MI, 1, Reqs, ST);
1910 break;
1911 case SPIRV::OpMemberDecorate:
1912 case SPIRV::OpMemberDecorateString:
1913 addOpDecorateReqs(MI, 2, Reqs, ST);
1914 break;
1915 case SPIRV::OpInBoundsPtrAccessChain:
1916 Reqs.addCapability(SPIRV::Capability::Addresses);
1917 break;
1918 case SPIRV::OpConstantSampler:
1919 Reqs.addCapability(SPIRV::Capability::LiteralSampler);
1920 break;
1921 case SPIRV::OpInBoundsAccessChain:
1922 case SPIRV::OpAccessChain:
1923 addOpAccessChainReqs(MI, Reqs, ST);
1924 break;
1925 case SPIRV::OpTypeImage:
1926 addOpTypeImageReqs(MI, Reqs, ST);
1927 break;
1928 case SPIRV::OpTypeSampler:
1929 if (!ST.isShader()) {
1930 Reqs.addCapability(SPIRV::Capability::ImageBasic);
1931 }
1932 break;
1933 case SPIRV::OpTypeForwardPointer:
1934 // TODO: check if it's OpenCL's kernel.
1935 Reqs.addCapability(SPIRV::Capability::Addresses);
1936 break;
1937 case SPIRV::OpAtomicFlagTestAndSet:
1938 case SPIRV::OpAtomicLoad:
1939 case SPIRV::OpAtomicStore:
1940 case SPIRV::OpAtomicExchange:
1941 case SPIRV::OpAtomicCompareExchange:
1942 case SPIRV::OpAtomicCompareExchangeWeak:
1943 case SPIRV::OpAtomicIIncrement:
1944 case SPIRV::OpAtomicIDecrement:
1945 case SPIRV::OpAtomicIAdd:
1946 case SPIRV::OpAtomicISub:
1947 case SPIRV::OpAtomicUMin:
1948 case SPIRV::OpAtomicUMax:
1949 case SPIRV::OpAtomicSMin:
1950 case SPIRV::OpAtomicSMax:
1951 case SPIRV::OpAtomicAnd:
1952 case SPIRV::OpAtomicOr:
1953 case SPIRV::OpAtomicXor: {
1954 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1955 SPIRVTypeInst TypeDef;
1956 if (Op == SPIRV::OpAtomicStore) {
1957 assert(MI.getOperand(3).isReg());
1958 TypeDef = getRegType(MI.getOperand(3).getReg(), *MI.getMF(),
1959 ST.getSPIRVGlobalRegistry());
1960 assert(TypeDef && "Unexpected type instruction for OpAtomicStore");
1961 } else {
1962 assert(MI.getOperand(1).isReg() && "Unexpected operand in atomic");
1963 TypeDef = MRI.getVRegDef(MI.getOperand(1).getReg());
1964 }
1965
1966 if (TypeDef->getOpcode() == SPIRV::OpTypeInt) {
1967 unsigned BitWidth = TypeDef->getOperand(1).getImm();
1968 if (BitWidth == 64)
1969 Reqs.addCapability(SPIRV::Capability::Int64Atomics);
1970 else if (BitWidth == 16) {
1971 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics))
1973 "16-bit integer atomic operations require the following SPIR-V "
1974 "extension: SPV_INTEL_16bit_atomics",
1975 false);
1976 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics);
1977 switch (Op) {
1978 case SPIRV::OpAtomicLoad:
1979 case SPIRV::OpAtomicStore:
1980 case SPIRV::OpAtomicExchange:
1981 case SPIRV::OpAtomicCompareExchange:
1982 case SPIRV::OpAtomicCompareExchangeWeak:
1983 Reqs.addCapability(
1984 SPIRV::Capability::AtomicInt16CompareExchangeINTEL);
1985 break;
1986 default:
1987 Reqs.addCapability(SPIRV::Capability::Int16AtomicsINTEL);
1988 break;
1989 }
1990 }
1991 } else if (isBFloat16Type(TypeDef)) {
1992 if (is_contained({SPIRV::OpAtomicLoad, SPIRV::OpAtomicStore,
1993 SPIRV::OpAtomicExchange},
1994 Op)) {
1995 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics))
1997 "The atomic bfloat16 instruction requires the following SPIR-V "
1998 "extension: SPV_INTEL_16bit_atomics",
1999 false);
2000 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics);
2001 Reqs.addCapability(SPIRV::Capability::AtomicBFloat16LoadStoreINTEL);
2002 }
2003 }
2004 break;
2005 }
2006 case SPIRV::OpGroupNonUniformIAdd:
2007 case SPIRV::OpGroupNonUniformFAdd:
2008 case SPIRV::OpGroupNonUniformIMul:
2009 case SPIRV::OpGroupNonUniformFMul:
2010 case SPIRV::OpGroupNonUniformSMin:
2011 case SPIRV::OpGroupNonUniformUMin:
2012 case SPIRV::OpGroupNonUniformFMin:
2013 case SPIRV::OpGroupNonUniformSMax:
2014 case SPIRV::OpGroupNonUniformUMax:
2015 case SPIRV::OpGroupNonUniformFMax:
2016 case SPIRV::OpGroupNonUniformBitwiseAnd:
2017 case SPIRV::OpGroupNonUniformBitwiseOr:
2018 case SPIRV::OpGroupNonUniformBitwiseXor:
2019 case SPIRV::OpGroupNonUniformLogicalAnd:
2020 case SPIRV::OpGroupNonUniformLogicalOr:
2021 case SPIRV::OpGroupNonUniformLogicalXor: {
2022 assert(MI.getOperand(3).isImm());
2023 int64_t GroupOp = MI.getOperand(3).getImm();
2024 switch (GroupOp) {
2025 case SPIRV::GroupOperation::Reduce:
2026 case SPIRV::GroupOperation::InclusiveScan:
2027 case SPIRV::GroupOperation::ExclusiveScan:
2028 Reqs.addCapability(SPIRV::Capability::GroupNonUniformArithmetic);
2029 break;
2030 case SPIRV::GroupOperation::ClusteredReduce:
2031 Reqs.addCapability(SPIRV::Capability::GroupNonUniformClustered);
2032 break;
2033 case SPIRV::GroupOperation::PartitionedReduceNV:
2034 case SPIRV::GroupOperation::PartitionedInclusiveScanNV:
2035 case SPIRV::GroupOperation::PartitionedExclusiveScanNV:
2036 if (ST.canUseExtension(
2037 SPIRV::Extension::SPV_EXT_shader_subgroup_partitioned))
2038 Reqs.addExtension(
2039 SPIRV::Extension::SPV_EXT_shader_subgroup_partitioned);
2040 else
2041 Reqs.addExtension(SPIRV::Extension::SPV_NV_shader_subgroup_partitioned);
2042 Reqs.addCapability(SPIRV::Capability::GroupNonUniformPartitionedNV);
2043 break;
2044 }
2045 break;
2046 }
2047 case SPIRV::OpGroupNonUniformQuadSwap:
2048 Reqs.addCapability(SPIRV::Capability::GroupNonUniformQuad);
2049 break;
2050 case SPIRV::OpImageQueryLod:
2051 Reqs.addCapability(SPIRV::Capability::ImageQuery);
2052 break;
2053 case SPIRV::OpImageQuerySize:
2054 case SPIRV::OpImageQuerySizeLod:
2055 case SPIRV::OpImageQueryLevels:
2056 case SPIRV::OpImageQuerySamples:
2057 if (ST.isShader())
2058 Reqs.addCapability(SPIRV::Capability::ImageQuery);
2059 break;
2060 case SPIRV::OpImageQueryFormat: {
2061 Register ResultReg = MI.getOperand(0).getReg();
2062 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2063 static const unsigned CompareOps[] = {
2064 SPIRV::OpIEqual, SPIRV::OpINotEqual,
2065 SPIRV::OpUGreaterThan, SPIRV::OpUGreaterThanEqual,
2066 SPIRV::OpULessThan, SPIRV::OpULessThanEqual,
2067 SPIRV::OpSGreaterThan, SPIRV::OpSGreaterThanEqual,
2068 SPIRV::OpSLessThan, SPIRV::OpSLessThanEqual};
2069
2070 auto CheckAndAddExtension = [&](int64_t ImmVal) {
2071 if (ImmVal == 4323 || ImmVal == 4324) {
2072 if (ST.canUseExtension(SPIRV::Extension::SPV_EXT_image_raw10_raw12))
2073 Reqs.addExtension(SPIRV::Extension::SPV_EXT_image_raw10_raw12);
2074 else
2075 report_fatal_error("This requires the "
2076 "SPV_EXT_image_raw10_raw12 extension");
2077 }
2078 };
2079
2080 for (MachineInstr &UseInst : MRI.use_instructions(ResultReg)) {
2081 unsigned Opc = UseInst.getOpcode();
2082
2083 if (Opc == SPIRV::OpSwitch) {
2084 for (const MachineOperand &Op : UseInst.operands())
2085 if (Op.isImm())
2086 CheckAndAddExtension(Op.getImm());
2087 } else if (llvm::is_contained(CompareOps, Opc)) {
2088 for (unsigned i = 1; i < UseInst.getNumOperands(); ++i) {
2089 Register UseReg = UseInst.getOperand(i).getReg();
2090 MachineInstr *ConstInst = MRI.getVRegDef(UseReg);
2091 if (ConstInst && ConstInst->getOpcode() == SPIRV::OpConstantI) {
2092 int64_t ImmVal = ConstInst->getOperand(2).getImm();
2093 if (ImmVal)
2094 CheckAndAddExtension(ImmVal);
2095 }
2096 }
2097 }
2098 }
2099 break;
2100 }
2101
2102 case SPIRV::OpGroupNonUniformShuffle:
2103 case SPIRV::OpGroupNonUniformShuffleXor:
2104 Reqs.addCapability(SPIRV::Capability::GroupNonUniformShuffle);
2105 break;
2106 case SPIRV::OpGroupNonUniformShuffleUp:
2107 case SPIRV::OpGroupNonUniformShuffleDown:
2108 Reqs.addCapability(SPIRV::Capability::GroupNonUniformShuffleRelative);
2109 break;
2110 case SPIRV::OpGroupAll:
2111 case SPIRV::OpGroupAny:
2112 case SPIRV::OpGroupBroadcast:
2113 case SPIRV::OpGroupIAdd:
2114 case SPIRV::OpGroupFAdd:
2115 case SPIRV::OpGroupFMin:
2116 case SPIRV::OpGroupUMin:
2117 case SPIRV::OpGroupSMin:
2118 case SPIRV::OpGroupFMax:
2119 case SPIRV::OpGroupUMax:
2120 case SPIRV::OpGroupSMax:
2121 Reqs.addCapability(SPIRV::Capability::Groups);
2122 break;
2123 case SPIRV::OpGroupNonUniformElect:
2124 Reqs.addCapability(SPIRV::Capability::GroupNonUniform);
2125 break;
2126 case SPIRV::OpGroupNonUniformAll:
2127 case SPIRV::OpGroupNonUniformAny:
2128 case SPIRV::OpGroupNonUniformAllEqual:
2129 Reqs.addCapability(SPIRV::Capability::GroupNonUniformVote);
2130 break;
2131 case SPIRV::OpGroupNonUniformBroadcast:
2132 case SPIRV::OpGroupNonUniformBroadcastFirst:
2133 case SPIRV::OpGroupNonUniformBallot:
2134 case SPIRV::OpGroupNonUniformInverseBallot:
2135 case SPIRV::OpGroupNonUniformBallotBitExtract:
2136 case SPIRV::OpGroupNonUniformBallotBitCount:
2137 case SPIRV::OpGroupNonUniformBallotFindLSB:
2138 case SPIRV::OpGroupNonUniformBallotFindMSB:
2139 Reqs.addCapability(SPIRV::Capability::GroupNonUniformBallot);
2140 break;
2141 case SPIRV::OpSubgroupShuffleINTEL:
2142 case SPIRV::OpSubgroupShuffleDownINTEL:
2143 case SPIRV::OpSubgroupShuffleUpINTEL:
2144 case SPIRV::OpSubgroupShuffleXorINTEL:
2145 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_subgroups)) {
2146 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_subgroups);
2147 Reqs.addCapability(SPIRV::Capability::SubgroupShuffleINTEL);
2148 }
2149 break;
2150 case SPIRV::OpSubgroupBlockReadINTEL:
2151 case SPIRV::OpSubgroupBlockWriteINTEL:
2152 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_subgroups)) {
2153 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_subgroups);
2154 Reqs.addCapability(SPIRV::Capability::SubgroupBufferBlockIOINTEL);
2155 }
2156 break;
2157 case SPIRV::OpSubgroupImageBlockReadINTEL:
2158 case SPIRV::OpSubgroupImageBlockWriteINTEL:
2159 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_subgroups)) {
2160 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_subgroups);
2161 Reqs.addCapability(SPIRV::Capability::SubgroupImageBlockIOINTEL);
2162 }
2163 break;
2164 case SPIRV::OpSubgroupImageMediaBlockReadINTEL:
2165 case SPIRV::OpSubgroupImageMediaBlockWriteINTEL:
2166 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_media_block_io)) {
2167 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_media_block_io);
2168 Reqs.addCapability(SPIRV::Capability::SubgroupImageMediaBlockIOINTEL);
2169 }
2170 break;
2171 case SPIRV::OpAssumeTrueKHR:
2172 case SPIRV::OpExpectKHR:
2173 if (ST.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume)) {
2174 Reqs.addExtension(SPIRV::Extension::SPV_KHR_expect_assume);
2175 Reqs.addCapability(SPIRV::Capability::ExpectAssumeKHR);
2176 }
2177 break;
2178 case SPIRV::OpFmaKHR:
2179 if (ST.canUseExtension(SPIRV::Extension::SPV_KHR_fma)) {
2180 Reqs.addExtension(SPIRV::Extension::SPV_KHR_fma);
2181 Reqs.addCapability(SPIRV::Capability::FmaKHR);
2182 }
2183 break;
2184 case SPIRV::OpPtrCastToCrossWorkgroupINTEL:
2185 case SPIRV::OpCrossWorkgroupCastToPtrINTEL:
2186 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_usm_storage_classes)) {
2187 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_usm_storage_classes);
2188 Reqs.addCapability(SPIRV::Capability::USMStorageClassesINTEL);
2189 }
2190 break;
2191 case SPIRV::OpConstantFunctionPointerINTEL:
2192 case SPIRV::OpFunctionPointerCallINTEL:
2193 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)) {
2194 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
2195 Reqs.addCapability(SPIRV::Capability::FunctionPointersINTEL);
2196 }
2197 break;
2198 case SPIRV::OpGroupNonUniformQuadAllKHR:
2199 addQuadControlRequirements(Reqs, ST, "OpGroupNonUniformQuadAllKHR");
2200 Reqs.addCapability(SPIRV::Capability::QuadControlKHR);
2201 break;
2202 case SPIRV::OpGroupNonUniformRotateKHR:
2203 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_subgroup_rotate))
2204 report_fatal_error("OpGroupNonUniformRotateKHR instruction requires the "
2205 "following SPIR-V extension: SPV_KHR_subgroup_rotate",
2206 false);
2207 Reqs.addExtension(SPIRV::Extension::SPV_KHR_subgroup_rotate);
2208 Reqs.addCapability(SPIRV::Capability::GroupNonUniformRotateKHR);
2209 Reqs.addCapability(SPIRV::Capability::GroupNonUniform);
2210 break;
2211 case SPIRV::OpFixedCosALTERA:
2212 case SPIRV::OpFixedSinALTERA:
2213 case SPIRV::OpFixedCosPiALTERA:
2214 case SPIRV::OpFixedSinPiALTERA:
2215 case SPIRV::OpFixedExpALTERA:
2216 case SPIRV::OpFixedLogALTERA:
2217 case SPIRV::OpFixedRecipALTERA:
2218 case SPIRV::OpFixedSqrtALTERA:
2219 case SPIRV::OpFixedSinCosALTERA:
2220 case SPIRV::OpFixedSinCosPiALTERA:
2221 case SPIRV::OpFixedRsqrtALTERA:
2222 if (!ST.canUseExtension(
2223 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_fixed_point))
2224 report_fatal_error("This instruction requires the "
2225 "following SPIR-V extension: "
2226 "SPV_ALTERA_arbitrary_precision_fixed_point",
2227 false);
2228 Reqs.addExtension(
2229 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_fixed_point);
2230 Reqs.addCapability(SPIRV::Capability::ArbitraryPrecisionFixedPointALTERA);
2231 break;
2232 case SPIRV::OpGroupIMulKHR:
2233 case SPIRV::OpGroupFMulKHR:
2234 case SPIRV::OpGroupBitwiseAndKHR:
2235 case SPIRV::OpGroupBitwiseOrKHR:
2236 case SPIRV::OpGroupBitwiseXorKHR:
2237 case SPIRV::OpGroupLogicalAndKHR:
2238 case SPIRV::OpGroupLogicalOrKHR:
2239 case SPIRV::OpGroupLogicalXorKHR:
2240 if (ST.canUseExtension(
2241 SPIRV::Extension::SPV_KHR_uniform_group_instructions)) {
2242 Reqs.addExtension(SPIRV::Extension::SPV_KHR_uniform_group_instructions);
2243 Reqs.addCapability(SPIRV::Capability::GroupUniformArithmeticKHR);
2244 }
2245 break;
2246 case SPIRV::OpReadClockKHR:
2247 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_shader_clock))
2248 report_fatal_error("OpReadClockKHR instruction requires the "
2249 "following SPIR-V extension: SPV_KHR_shader_clock",
2250 false);
2251 Reqs.addExtension(SPIRV::Extension::SPV_KHR_shader_clock);
2252 Reqs.addCapability(SPIRV::Capability::ShaderClockKHR);
2253 break;
2254 case SPIRV::OpAbortKHR:
2255 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort))
2256 report_fatal_error("OpAbortKHR instruction requires the "
2257 "following SPIR-V extension: SPV_KHR_abort",
2258 false);
2259 Reqs.addExtension(SPIRV::Extension::SPV_KHR_abort);
2260 Reqs.addCapability(SPIRV::Capability::AbortKHR);
2261 break;
2262 case SPIRV::OpPoisonKHR:
2263 case SPIRV::OpFreezeKHR:
2264 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze))
2265 report_fatal_error("OpPoisonKHR/OpFreezeKHR instruction requires the "
2266 "following SPIR-V extension: SPV_KHR_poison_freeze",
2267 false);
2268 Reqs.addExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
2269 Reqs.addCapability(SPIRV::Capability::PoisonFreezeKHR);
2270 break;
2271 case SPIRV::OpAtomicFAddEXT:
2272 case SPIRV::OpAtomicFMinEXT:
2273 case SPIRV::OpAtomicFMaxEXT:
2274 AddAtomicFloatRequirements(MI, Reqs, ST);
2275 break;
2276 case SPIRV::OpConvertBF16ToFINTEL:
2277 case SPIRV::OpConvertFToBF16INTEL:
2278 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_bfloat16_conversion)) {
2279 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_bfloat16_conversion);
2280 Reqs.addCapability(SPIRV::Capability::BFloat16ConversionINTEL);
2281 }
2282 break;
2283 case SPIRV::OpRoundFToTF32INTEL:
2284 if (ST.canUseExtension(
2285 SPIRV::Extension::SPV_INTEL_tensor_float32_conversion)) {
2286 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_tensor_float32_conversion);
2287 Reqs.addCapability(SPIRV::Capability::TensorFloat32RoundingINTEL);
2288 }
2289 break;
2290 case SPIRV::OpVariableLengthArrayINTEL:
2291 case SPIRV::OpSaveMemoryINTEL:
2292 case SPIRV::OpRestoreMemoryINTEL:
2293 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_variable_length_array)) {
2294 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_variable_length_array);
2295 Reqs.addCapability(SPIRV::Capability::VariableLengthArrayINTEL);
2296 }
2297 break;
2298 case SPIRV::OpUntypedVariableLengthArrayINTEL:
2299 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_variable_length_array)) {
2300 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_variable_length_array);
2301 Reqs.addCapability(SPIRV::Capability::UntypedVariableLengthArrayINTEL);
2302 }
2303 break;
2304 case SPIRV::OpAsmTargetINTEL:
2305 case SPIRV::OpAsmINTEL:
2306 case SPIRV::OpAsmCallINTEL:
2307 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_inline_assembly)) {
2308 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_inline_assembly);
2309 Reqs.addCapability(SPIRV::Capability::AsmINTEL);
2310 }
2311 break;
2312 case SPIRV::OpTypeCooperativeMatrixKHR: {
2313 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix))
2315 "OpTypeCooperativeMatrixKHR type requires the "
2316 "following SPIR-V extension: SPV_KHR_cooperative_matrix",
2317 false);
2318 Reqs.addExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix);
2319 Reqs.addCapability(SPIRV::Capability::CooperativeMatrixKHR);
2320 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2321 SPIRVTypeInst TypeDef = MRI.getVRegDef(MI.getOperand(1).getReg());
2322 if (isBFloat16Type(TypeDef))
2323 Reqs.addCapability(SPIRV::Capability::BFloat16CooperativeMatrixKHR);
2324 break;
2325 }
2326 case SPIRV::OpArithmeticFenceEXT:
2327 if (!ST.canUseExtension(SPIRV::Extension::SPV_EXT_arithmetic_fence))
2328 report_fatal_error("OpArithmeticFenceEXT requires the "
2329 "following SPIR-V extension: SPV_EXT_arithmetic_fence",
2330 false);
2331 Reqs.addExtension(SPIRV::Extension::SPV_EXT_arithmetic_fence);
2332 Reqs.addCapability(SPIRV::Capability::ArithmeticFenceEXT);
2333 break;
2334 case SPIRV::OpControlBarrierArriveINTEL:
2335 case SPIRV::OpControlBarrierWaitINTEL:
2336 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_split_barrier)) {
2337 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_split_barrier);
2338 Reqs.addCapability(SPIRV::Capability::SplitBarrierINTEL);
2339 }
2340 break;
2341 case SPIRV::OpCooperativeMatrixMulAddKHR: {
2342 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix))
2343 report_fatal_error("Cooperative matrix instructions require the "
2344 "following SPIR-V extension: "
2345 "SPV_KHR_cooperative_matrix",
2346 false);
2347 Reqs.addExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix);
2348 Reqs.addCapability(SPIRV::Capability::CooperativeMatrixKHR);
2349 constexpr unsigned MulAddMaxSize = 6;
2350 if (MI.getNumOperands() != MulAddMaxSize)
2351 break;
2352 const int64_t CoopOperands = MI.getOperand(MulAddMaxSize - 1).getImm();
2353 if (CoopOperands &
2354 SPIRV::CooperativeMatrixOperands::MatrixAAndBTF32ComponentsINTEL) {
2355 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix))
2356 report_fatal_error("MatrixAAndBTF32ComponentsINTEL type interpretation "
2357 "require the following SPIR-V extension: "
2358 "SPV_INTEL_joint_matrix",
2359 false);
2360 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2361 Reqs.addCapability(
2362 SPIRV::Capability::CooperativeMatrixTF32ComponentTypeINTEL);
2363 }
2364 if (CoopOperands & SPIRV::CooperativeMatrixOperands::
2365 MatrixAAndBBFloat16ComponentsINTEL ||
2366 CoopOperands &
2367 SPIRV::CooperativeMatrixOperands::MatrixCBFloat16ComponentsINTEL ||
2368 CoopOperands & SPIRV::CooperativeMatrixOperands::
2369 MatrixResultBFloat16ComponentsINTEL) {
2370 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix))
2371 report_fatal_error("***BF16ComponentsINTEL type interpretations "
2372 "require the following SPIR-V extension: "
2373 "SPV_INTEL_joint_matrix",
2374 false);
2375 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2376 Reqs.addCapability(
2377 SPIRV::Capability::CooperativeMatrixBFloat16ComponentTypeINTEL);
2378 }
2379 break;
2380 }
2381 case SPIRV::OpCooperativeMatrixLoadKHR:
2382 case SPIRV::OpCooperativeMatrixStoreKHR:
2383 case SPIRV::OpCooperativeMatrixLoadCheckedINTEL:
2384 case SPIRV::OpCooperativeMatrixStoreCheckedINTEL:
2385 case SPIRV::OpCooperativeMatrixPrefetchINTEL: {
2386 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix))
2387 report_fatal_error("Cooperative matrix instructions require the "
2388 "following SPIR-V extension: "
2389 "SPV_KHR_cooperative_matrix",
2390 false);
2391 Reqs.addExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix);
2392 Reqs.addCapability(SPIRV::Capability::CooperativeMatrixKHR);
2393
2394 // Check Layout operand in case if it's not a standard one and add the
2395 // appropriate capability.
2396 unsigned LayoutNum;
2397 switch (Op) {
2398 case SPIRV::OpCooperativeMatrixLoadKHR:
2399 LayoutNum = 3;
2400 break;
2401 case SPIRV::OpCooperativeMatrixStoreKHR:
2402 LayoutNum = 2;
2403 break;
2404 case SPIRV::OpCooperativeMatrixLoadCheckedINTEL:
2405 LayoutNum = 5;
2406 break;
2407 case SPIRV::OpCooperativeMatrixStoreCheckedINTEL:
2408 case SPIRV::OpCooperativeMatrixPrefetchINTEL:
2409 LayoutNum = 4;
2410 break;
2411 default:
2412 llvm_unreachable("unexpected cooperative matrix opcode");
2413 }
2414 Register RegLayout = MI.getOperand(LayoutNum).getReg();
2415 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2416 MachineInstr *MILayout = MRI.getUniqueVRegDef(RegLayout);
2417 if (MILayout->getOpcode() == SPIRV::OpConstantI) {
2418 const unsigned LayoutVal = MILayout->getOperand(2).getImm();
2419 if (LayoutVal ==
2420 static_cast<unsigned>(SPIRV::CooperativeMatrixLayout::PackedINTEL)) {
2421 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix))
2422 report_fatal_error("PackedINTEL layout require the following SPIR-V "
2423 "extension: SPV_INTEL_joint_matrix",
2424 false);
2425 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2426 Reqs.addCapability(SPIRV::Capability::PackedCooperativeMatrixINTEL);
2427 }
2428 }
2429
2430 // Nothing to do.
2431 if (Op == SPIRV::OpCooperativeMatrixLoadKHR ||
2432 Op == SPIRV::OpCooperativeMatrixStoreKHR)
2433 break;
2434
2435 std::string InstName;
2436 switch (Op) {
2437 case SPIRV::OpCooperativeMatrixPrefetchINTEL:
2438 InstName = "OpCooperativeMatrixPrefetchINTEL";
2439 break;
2440 case SPIRV::OpCooperativeMatrixLoadCheckedINTEL:
2441 InstName = "OpCooperativeMatrixLoadCheckedINTEL";
2442 break;
2443 case SPIRV::OpCooperativeMatrixStoreCheckedINTEL:
2444 InstName = "OpCooperativeMatrixStoreCheckedINTEL";
2445 break;
2446 }
2447
2448 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix)) {
2449 const std::string ErrorMsg =
2450 InstName + " instruction requires the "
2451 "following SPIR-V extension: SPV_INTEL_joint_matrix";
2452 report_fatal_error(ErrorMsg.c_str(), false);
2453 }
2454 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2455 if (Op == SPIRV::OpCooperativeMatrixPrefetchINTEL) {
2456 Reqs.addCapability(SPIRV::Capability::CooperativeMatrixPrefetchINTEL);
2457 break;
2458 }
2459 Reqs.addCapability(
2460 SPIRV::Capability::CooperativeMatrixCheckedInstructionsINTEL);
2461 break;
2462 }
2463 case SPIRV::OpCooperativeMatrixConstructCheckedINTEL:
2464 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix))
2465 report_fatal_error("OpCooperativeMatrixConstructCheckedINTEL "
2466 "instructions require the following SPIR-V extension: "
2467 "SPV_INTEL_joint_matrix",
2468 false);
2469 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2470 Reqs.addCapability(
2471 SPIRV::Capability::CooperativeMatrixCheckedInstructionsINTEL);
2472 break;
2473 case SPIRV::OpReadPipeBlockingALTERA:
2474 case SPIRV::OpWritePipeBlockingALTERA:
2475 if (ST.canUseExtension(SPIRV::Extension::SPV_ALTERA_blocking_pipes)) {
2476 Reqs.addExtension(SPIRV::Extension::SPV_ALTERA_blocking_pipes);
2477 Reqs.addCapability(SPIRV::Capability::BlockingPipesALTERA);
2478 }
2479 break;
2480 case SPIRV::OpCooperativeMatrixGetElementCoordINTEL:
2481 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix))
2482 report_fatal_error("OpCooperativeMatrixGetElementCoordINTEL requires the "
2483 "following SPIR-V extension: SPV_INTEL_joint_matrix",
2484 false);
2485 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2486 Reqs.addCapability(
2487 SPIRV::Capability::CooperativeMatrixInvocationInstructionsINTEL);
2488 break;
2489 case SPIRV::OpConvertHandleToImageINTEL:
2490 case SPIRV::OpConvertHandleToSamplerINTEL:
2491 case SPIRV::OpConvertHandleToSampledImageINTEL: {
2492 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_bindless_images))
2493 report_fatal_error("OpConvertHandleTo[Image/Sampler/SampledImage]INTEL "
2494 "instructions require the following SPIR-V extension: "
2495 "SPV_INTEL_bindless_images",
2496 false);
2497 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
2498 SPIRV::AddressingModel::AddressingModel AddrModel = MAI.Addr;
2499 SPIRVTypeInst TyDef = GR->getSPIRVTypeForVReg(MI.getOperand(1).getReg());
2500 if (Op == SPIRV::OpConvertHandleToImageINTEL &&
2501 TyDef->getOpcode() != SPIRV::OpTypeImage) {
2502 report_fatal_error("Incorrect return type for the instruction "
2503 "OpConvertHandleToImageINTEL",
2504 false);
2505 } else if (Op == SPIRV::OpConvertHandleToSamplerINTEL &&
2506 TyDef->getOpcode() != SPIRV::OpTypeSampler) {
2507 report_fatal_error("Incorrect return type for the instruction "
2508 "OpConvertHandleToSamplerINTEL",
2509 false);
2510 } else if (Op == SPIRV::OpConvertHandleToSampledImageINTEL &&
2511 TyDef->getOpcode() != SPIRV::OpTypeSampledImage) {
2512 report_fatal_error("Incorrect return type for the instruction "
2513 "OpConvertHandleToSampledImageINTEL",
2514 false);
2515 }
2516 SPIRVTypeInst SpvTy =
2517 getRegType(MI.getOperand(2).getReg(), *MI.getMF(), GR);
2518 unsigned Bitwidth = GR->getScalarOrVectorBitWidth(SpvTy);
2519 if (!(Bitwidth == 32 && AddrModel == SPIRV::AddressingModel::Physical32) &&
2520 !(Bitwidth == 64 && AddrModel == SPIRV::AddressingModel::Physical64)) {
2522 "Parameter value must be a 32-bit scalar in case of "
2523 "Physical32 addressing model or a 64-bit scalar in case of "
2524 "Physical64 addressing model",
2525 false);
2526 }
2527 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_bindless_images);
2528 Reqs.addCapability(SPIRV::Capability::BindlessImagesINTEL);
2529 break;
2530 }
2531 case SPIRV::OpSubgroup2DBlockLoadINTEL:
2532 case SPIRV::OpSubgroup2DBlockLoadTransposeINTEL:
2533 case SPIRV::OpSubgroup2DBlockLoadTransformINTEL:
2534 case SPIRV::OpSubgroup2DBlockPrefetchINTEL:
2535 case SPIRV::OpSubgroup2DBlockStoreINTEL: {
2536 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_2d_block_io))
2537 report_fatal_error("OpSubgroup2DBlock[Load/LoadTranspose/LoadTransform/"
2538 "Prefetch/Store]INTEL instructions require the "
2539 "following SPIR-V extension: SPV_INTEL_2d_block_io",
2540 false);
2541 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_2d_block_io);
2542 Reqs.addCapability(SPIRV::Capability::Subgroup2DBlockIOINTEL);
2543
2544 if (Op == SPIRV::OpSubgroup2DBlockLoadTransposeINTEL) {
2545 Reqs.addCapability(SPIRV::Capability::Subgroup2DBlockTransposeINTEL);
2546 break;
2547 }
2548 if (Op == SPIRV::OpSubgroup2DBlockLoadTransformINTEL) {
2549 Reqs.addCapability(SPIRV::Capability::Subgroup2DBlockTransformINTEL);
2550 break;
2551 }
2552 break;
2553 }
2554 case SPIRV::OpKill: {
2555 Reqs.addCapability(SPIRV::Capability::Shader);
2556 } break;
2557 case SPIRV::OpDemoteToHelperInvocation:
2558 Reqs.addCapability(SPIRV::Capability::DemoteToHelperInvocation);
2559
2560 if (ST.canUseExtension(
2561 SPIRV::Extension::SPV_EXT_demote_to_helper_invocation)) {
2562 if (!ST.isAtLeastSPIRVVer(llvm::VersionTuple(1, 6)))
2563 Reqs.addExtension(
2564 SPIRV::Extension::SPV_EXT_demote_to_helper_invocation);
2565 }
2566 break;
2567 case SPIRV::OpSDot:
2568 case SPIRV::OpUDot:
2569 case SPIRV::OpSUDot:
2570 case SPIRV::OpSDotAccSat:
2571 case SPIRV::OpUDotAccSat:
2572 case SPIRV::OpSUDotAccSat:
2573 AddDotProductRequirements(MI, Reqs, ST);
2574 break;
2575 case SPIRV::OpImageSampleImplicitLod:
2576 case SPIRV::OpImageFetch:
2577 Reqs.addCapability(SPIRV::Capability::Shader);
2578 addImageOperandReqs(MI, Reqs, ST, 4);
2579 break;
2580 case SPIRV::OpImageSampleExplicitLod:
2581 addImageOperandReqs(MI, Reqs, ST, 4);
2582 break;
2583 case SPIRV::OpImageSampleDrefImplicitLod:
2584 case SPIRV::OpImageSampleDrefExplicitLod:
2585 case SPIRV::OpImageDrefGather:
2586 case SPIRV::OpImageGather:
2587 Reqs.addCapability(SPIRV::Capability::Shader);
2588 addImageOperandReqs(MI, Reqs, ST, 5);
2589 break;
2590 case SPIRV::OpImageRead: {
2591 Register ImageReg = MI.getOperand(2).getReg();
2592 SPIRVTypeInst TypeDef = ST.getSPIRVGlobalRegistry()->getResultType(
2593 ImageReg, const_cast<MachineFunction *>(MI.getMF()));
2594 // OpImageRead and OpImageWrite can use Unknown Image Formats
2595 // when the Kernel capability is declared. In the OpenCL environment we are
2596 // not allowed to produce
2597 // StorageImageReadWithoutFormat/StorageImageWriteWithoutFormat, see
2598 // https://github.com/KhronosGroup/SPIRV-Headers/issues/487
2599
2600 if (isImageTypeWithUnknownFormat(TypeDef) && ST.isShader())
2601 Reqs.addCapability(SPIRV::Capability::StorageImageReadWithoutFormat);
2602 break;
2603 }
2604 case SPIRV::OpImageWrite: {
2605 Register ImageReg = MI.getOperand(0).getReg();
2606 SPIRVTypeInst TypeDef = ST.getSPIRVGlobalRegistry()->getResultType(
2607 ImageReg, const_cast<MachineFunction *>(MI.getMF()));
2608 // OpImageRead and OpImageWrite can use Unknown Image Formats
2609 // when the Kernel capability is declared. In the OpenCL environment we are
2610 // not allowed to produce
2611 // StorageImageReadWithoutFormat/StorageImageWriteWithoutFormat, see
2612 // https://github.com/KhronosGroup/SPIRV-Headers/issues/487
2613
2614 if (isImageTypeWithUnknownFormat(TypeDef) && ST.isShader())
2615 Reqs.addCapability(SPIRV::Capability::StorageImageWriteWithoutFormat);
2616 break;
2617 }
2618 case SPIRV::OpTypeStructContinuedINTEL:
2619 case SPIRV::OpConstantCompositeContinuedINTEL:
2620 case SPIRV::OpSpecConstantCompositeContinuedINTEL:
2621 case SPIRV::OpCompositeConstructContinuedINTEL: {
2622 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_long_composites))
2624 "Continued instructions require the "
2625 "following SPIR-V extension: SPV_INTEL_long_composites",
2626 false);
2627 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_long_composites);
2628 Reqs.addCapability(SPIRV::Capability::LongCompositesINTEL);
2629 break;
2630 }
2631 case SPIRV::OpArbitraryFloatEQALTERA:
2632 case SPIRV::OpArbitraryFloatGEALTERA:
2633 case SPIRV::OpArbitraryFloatGTALTERA:
2634 case SPIRV::OpArbitraryFloatLEALTERA:
2635 case SPIRV::OpArbitraryFloatLTALTERA:
2636 case SPIRV::OpArbitraryFloatCbrtALTERA:
2637 case SPIRV::OpArbitraryFloatCosALTERA:
2638 case SPIRV::OpArbitraryFloatCosPiALTERA:
2639 case SPIRV::OpArbitraryFloatExp10ALTERA:
2640 case SPIRV::OpArbitraryFloatExp2ALTERA:
2641 case SPIRV::OpArbitraryFloatExpALTERA:
2642 case SPIRV::OpArbitraryFloatExpm1ALTERA:
2643 case SPIRV::OpArbitraryFloatHypotALTERA:
2644 case SPIRV::OpArbitraryFloatLog10ALTERA:
2645 case SPIRV::OpArbitraryFloatLog1pALTERA:
2646 case SPIRV::OpArbitraryFloatLog2ALTERA:
2647 case SPIRV::OpArbitraryFloatLogALTERA:
2648 case SPIRV::OpArbitraryFloatRecipALTERA:
2649 case SPIRV::OpArbitraryFloatSinCosALTERA:
2650 case SPIRV::OpArbitraryFloatSinCosPiALTERA:
2651 case SPIRV::OpArbitraryFloatSinALTERA:
2652 case SPIRV::OpArbitraryFloatSinPiALTERA:
2653 case SPIRV::OpArbitraryFloatSqrtALTERA:
2654 case SPIRV::OpArbitraryFloatACosALTERA:
2655 case SPIRV::OpArbitraryFloatACosPiALTERA:
2656 case SPIRV::OpArbitraryFloatAddALTERA:
2657 case SPIRV::OpArbitraryFloatASinALTERA:
2658 case SPIRV::OpArbitraryFloatASinPiALTERA:
2659 case SPIRV::OpArbitraryFloatATan2ALTERA:
2660 case SPIRV::OpArbitraryFloatATanALTERA:
2661 case SPIRV::OpArbitraryFloatATanPiALTERA:
2662 case SPIRV::OpArbitraryFloatCastFromIntALTERA:
2663 case SPIRV::OpArbitraryFloatCastALTERA:
2664 case SPIRV::OpArbitraryFloatCastToIntALTERA:
2665 case SPIRV::OpArbitraryFloatDivALTERA:
2666 case SPIRV::OpArbitraryFloatMulALTERA:
2667 case SPIRV::OpArbitraryFloatPowALTERA:
2668 case SPIRV::OpArbitraryFloatPowNALTERA:
2669 case SPIRV::OpArbitraryFloatPowRALTERA:
2670 case SPIRV::OpArbitraryFloatRSqrtALTERA:
2671 case SPIRV::OpArbitraryFloatSubALTERA: {
2672 if (!ST.canUseExtension(
2673 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_floating_point))
2675 "Floating point instructions can't be translated correctly without "
2676 "enabled SPV_ALTERA_arbitrary_precision_floating_point extension!",
2677 false);
2678 Reqs.addExtension(
2679 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_floating_point);
2680 Reqs.addCapability(
2681 SPIRV::Capability::ArbitraryPrecisionFloatingPointALTERA);
2682 break;
2683 }
2684 case SPIRV::OpSubgroupMatrixMultiplyAccumulateINTEL: {
2685 if (!ST.canUseExtension(
2686 SPIRV::Extension::SPV_INTEL_subgroup_matrix_multiply_accumulate))
2688 "OpSubgroupMatrixMultiplyAccumulateINTEL instruction requires the "
2689 "following SPIR-V "
2690 "extension: SPV_INTEL_subgroup_matrix_multiply_accumulate",
2691 false);
2692 Reqs.addExtension(
2693 SPIRV::Extension::SPV_INTEL_subgroup_matrix_multiply_accumulate);
2694 Reqs.addCapability(
2695 SPIRV::Capability::SubgroupMatrixMultiplyAccumulateINTEL);
2696 break;
2697 }
2698 case SPIRV::OpBitwiseFunctionINTEL: {
2699 if (!ST.canUseExtension(
2700 SPIRV::Extension::SPV_INTEL_ternary_bitwise_function))
2702 "OpBitwiseFunctionINTEL instruction requires the following SPIR-V "
2703 "extension: SPV_INTEL_ternary_bitwise_function",
2704 false);
2705 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_ternary_bitwise_function);
2706 Reqs.addCapability(SPIRV::Capability::TernaryBitwiseFunctionINTEL);
2707 break;
2708 }
2709 case SPIRV::OpCopyMemorySized: {
2710 Reqs.addCapability(SPIRV::Capability::Addresses);
2711 // TODO: Add UntypedPointersKHR when implemented.
2712 break;
2713 }
2714 case SPIRV::OpTypeUntypedPointerKHR:
2715 Reqs.getAndAddRequirements(SPIRV::OperandCategory::StorageClassOperand,
2716 MI.getOperand(1).getImm(), ST);
2717 [[fallthrough]];
2718 case SPIRV::OpUntypedVariableKHR:
2719 case SPIRV::OpUntypedAccessChainKHR:
2720 case SPIRV::OpUntypedInBoundsAccessChainKHR:
2721 case SPIRV::OpUntypedPtrAccessChainKHR:
2722 case SPIRV::OpUntypedInBoundsPtrAccessChainKHR:
2723 case SPIRV::OpUntypedPrefetchKHR:
2724 case SPIRV::OpUntypedGroupAsyncCopyKHR: {
2725 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_untyped_pointers))
2726 report_fatal_error("Untyped pointer instructions require the following "
2727 "SPIR-V extension: SPV_KHR_untyped_pointers",
2728 false);
2729 Reqs.addExtension(SPIRV::Extension::SPV_KHR_untyped_pointers);
2730 Reqs.addCapability(SPIRV::Capability::UntypedPointersKHR);
2731 break;
2732 }
2733 case SPIRV::OpPredicatedLoadINTEL:
2734 case SPIRV::OpPredicatedStoreINTEL: {
2735 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_predicated_io))
2737 "OpPredicated[Load/Store]INTEL instructions require "
2738 "the following SPIR-V extension: SPV_INTEL_predicated_io",
2739 false);
2740 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_predicated_io);
2741 Reqs.addCapability(SPIRV::Capability::PredicatedIOINTEL);
2742 break;
2743 }
2744 case SPIRV::OpFAddS:
2745 case SPIRV::OpFSubS:
2746 case SPIRV::OpFMulS:
2747 case SPIRV::OpFDivS:
2748 case SPIRV::OpFRemS:
2749 case SPIRV::OpFMod:
2750 case SPIRV::OpFNegate:
2751 case SPIRV::OpFAddV:
2752 case SPIRV::OpFSubV:
2753 case SPIRV::OpFMulV:
2754 case SPIRV::OpFDivV:
2755 case SPIRV::OpFRemV:
2756 case SPIRV::OpFNegateV: {
2757 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2758 SPIRVTypeInst TypeDef = MRI.getVRegDef(MI.getOperand(1).getReg());
2759 if (isVectorType(TypeDef))
2760 TypeDef = MRI.getVRegDef(TypeDef->getOperand(1).getReg());
2761 if (isBFloat16Type(TypeDef) && !addBFloat16ArithmeticRequirements(Reqs, ST))
2763 "Arithmetic instructions with bfloat16 arguments require the "
2764 "following SPIR-V extension: SPV_EXT_bfloat16_arithmetic",
2765 false);
2766 break;
2767 }
2768 case SPIRV::OpOrdered:
2769 case SPIRV::OpUnordered:
2770 case SPIRV::OpFOrdEqual:
2771 case SPIRV::OpFOrdNotEqual:
2772 case SPIRV::OpFOrdLessThan:
2773 case SPIRV::OpFOrdLessThanEqual:
2774 case SPIRV::OpFOrdGreaterThan:
2775 case SPIRV::OpFOrdGreaterThanEqual:
2776 case SPIRV::OpFUnordEqual:
2777 case SPIRV::OpFUnordNotEqual:
2778 case SPIRV::OpFUnordLessThan:
2779 case SPIRV::OpFUnordLessThanEqual:
2780 case SPIRV::OpFUnordGreaterThan:
2781 case SPIRV::OpFUnordGreaterThanEqual: {
2782 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2783 SPIRVTypeInst TypeDef = getRegType(MI.getOperand(2).getReg(), *MI.getMF(),
2784 ST.getSPIRVGlobalRegistry());
2785 assert(TypeDef && "Unexpected type instruction for comparison operand");
2786 if (isVectorType(TypeDef))
2787 TypeDef = MRI.getVRegDef(TypeDef->getOperand(1).getReg());
2788 if (isBFloat16Type(TypeDef) && !addBFloat16ArithmeticRequirements(Reqs, ST))
2790 "Relational instructions with bfloat16 arguments require the "
2791 "following SPIR-V extension: SPV_EXT_bfloat16_arithmetic",
2792 false);
2793 break;
2794 }
2795 case SPIRV::OpDPdxCoarse:
2796 case SPIRV::OpDPdyCoarse:
2797 case SPIRV::OpDPdxFine:
2798 case SPIRV::OpDPdyFine: {
2799 Reqs.addCapability(SPIRV::Capability::DerivativeControl);
2800 break;
2801 }
2802 case SPIRV::OpLoopControlINTEL: {
2803 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_unstructured_loop_controls);
2804 Reqs.addCapability(SPIRV::Capability::UnstructuredLoopControlsINTEL);
2805 break;
2806 }
2807
2808 default:
2809 break;
2810 }
2811
2812 // If we require capability Shader, then we can remove the requirement for
2813 // the BitInstructions capability, since Shader is a superset capability
2814 // of BitInstructions.
2815 Reqs.removeCapabilityIf(SPIRV::Capability::BitInstructions,
2816 SPIRV::Capability::Shader);
2817}
2818
2820 MachineFunctionGetter GetMF, const SPIRVSubtarget &ST) {
2821 // Collect requirements for existing instructions.
2822 for (const Function &F : M) {
2823 MachineFunction *MF = GetMF(F);
2824 if (!MF)
2825 continue;
2826 for (const MachineBasicBlock &MBB : *MF)
2827 for (const MachineInstr &MI : MBB)
2828 addInstrRequirements(MI, MAI, ST);
2829 }
2830 // Collect requirements for OpExecutionMode instructions.
2831 auto Node = M.getNamedMetadata("spirv.ExecutionMode");
2832 if (Node) {
2833 bool RequireFloatControls = false, RequireIntelFloatControls2 = false,
2834 RequireKHRFloatControls2 = false,
2835 VerLower14 = !ST.isAtLeastSPIRVVer(VersionTuple(1, 4));
2836 bool HasIntelFloatControls2 =
2837 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_float_controls2);
2838 bool HasKHRFloatControls2 =
2839 ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2);
2840 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
2841 MDNode *MDN = cast<MDNode>(Node->getOperand(i));
2842 const MDOperand &MDOp = MDN->getOperand(1);
2843 if (auto *CMeta = dyn_cast<ConstantAsMetadata>(MDOp)) {
2844 Constant *C = CMeta->getValue();
2845 if (ConstantInt *Const = dyn_cast<ConstantInt>(C)) {
2846 auto EM = Const->getZExtValue();
2847 // SPV_KHR_float_controls is not available until v1.4:
2848 // add SPV_KHR_float_controls if the version is too low
2849 switch (EM) {
2850 case SPIRV::ExecutionMode::DenormPreserve:
2851 case SPIRV::ExecutionMode::DenormFlushToZero:
2852 case SPIRV::ExecutionMode::RoundingModeRTE:
2853 case SPIRV::ExecutionMode::RoundingModeRTZ:
2854 RequireFloatControls = VerLower14;
2856 SPIRV::OperandCategory::ExecutionModeOperand, EM, ST);
2857 break;
2858 case SPIRV::ExecutionMode::RoundingModeRTPINTEL:
2859 case SPIRV::ExecutionMode::RoundingModeRTNINTEL:
2860 case SPIRV::ExecutionMode::FloatingPointModeALTINTEL:
2861 case SPIRV::ExecutionMode::FloatingPointModeIEEEINTEL:
2862 if (HasIntelFloatControls2) {
2863 RequireIntelFloatControls2 = true;
2865 SPIRV::OperandCategory::ExecutionModeOperand, EM, ST);
2866 }
2867 break;
2868 case SPIRV::ExecutionMode::FPFastMathDefault: {
2869 if (HasKHRFloatControls2) {
2870 RequireKHRFloatControls2 = true;
2872 SPIRV::OperandCategory::ExecutionModeOperand, EM, ST);
2873 }
2874 break;
2875 }
2876 case SPIRV::ExecutionMode::ContractionOff:
2877 case SPIRV::ExecutionMode::SignedZeroInfNanPreserve:
2878 if (HasKHRFloatControls2) {
2879 RequireKHRFloatControls2 = true;
2881 SPIRV::OperandCategory::ExecutionModeOperand,
2882 SPIRV::ExecutionMode::FPFastMathDefault, ST);
2883 } else {
2885 SPIRV::OperandCategory::ExecutionModeOperand, EM, ST);
2886 }
2887 break;
2888 default:
2890 SPIRV::OperandCategory::ExecutionModeOperand, EM, ST);
2891 }
2892 }
2893 }
2894 }
2895 if (RequireFloatControls &&
2896 ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls))
2897 MAI.Reqs.addExtension(SPIRV::Extension::SPV_KHR_float_controls);
2898 if (RequireIntelFloatControls2)
2899 MAI.Reqs.addExtension(SPIRV::Extension::SPV_INTEL_float_controls2);
2900 if (RequireKHRFloatControls2)
2901 MAI.Reqs.addExtension(SPIRV::Extension::SPV_KHR_float_controls2);
2902 }
2903 for (const Function &F : M) {
2904 if (F.isDeclaration())
2905 continue;
2906 if (F.getMetadata("reqd_work_group_size"))
2908 SPIRV::OperandCategory::ExecutionModeOperand,
2909 SPIRV::ExecutionMode::LocalSize, ST);
2910 if (F.getFnAttribute("hlsl.numthreads").isValid()) {
2912 SPIRV::OperandCategory::ExecutionModeOperand,
2913 SPIRV::ExecutionMode::LocalSize, ST);
2914 }
2915 if (F.getFnAttribute("enable-maximal-reconvergence").getValueAsBool()) {
2916 MAI.Reqs.addExtension(SPIRV::Extension::SPV_KHR_maximal_reconvergence);
2917 }
2918 if (F.getMetadata("work_group_size_hint"))
2920 SPIRV::OperandCategory::ExecutionModeOperand,
2921 SPIRV::ExecutionMode::LocalSizeHint, ST);
2922 if (F.getMetadata("intel_reqd_sub_group_size") ||
2923 F.getMetadata("reqd_sub_group_size"))
2925 SPIRV::OperandCategory::ExecutionModeOperand,
2926 SPIRV::ExecutionMode::SubgroupSize, ST);
2927 if (F.getMetadata("max_work_group_size"))
2929 SPIRV::OperandCategory::ExecutionModeOperand,
2930 SPIRV::ExecutionMode::MaxWorkgroupSizeINTEL, ST);
2931 if (F.getMetadata("vec_type_hint"))
2933 SPIRV::OperandCategory::ExecutionModeOperand,
2934 SPIRV::ExecutionMode::VecTypeHint, ST);
2935
2936 if (F.hasOptNone()) {
2937 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_optnone)) {
2938 MAI.Reqs.addExtension(SPIRV::Extension::SPV_INTEL_optnone);
2939 MAI.Reqs.addCapability(SPIRV::Capability::OptNoneINTEL);
2940 } else if (ST.canUseExtension(SPIRV::Extension::SPV_EXT_optnone)) {
2941 MAI.Reqs.addExtension(SPIRV::Extension::SPV_EXT_optnone);
2942 MAI.Reqs.addCapability(SPIRV::Capability::OptNoneEXT);
2943 }
2944 }
2945 }
2946}
2947
2948static unsigned getFastMathFlags(const MachineInstr &I,
2949 const SPIRVSubtarget &ST) {
2950 unsigned Flags = SPIRV::FPFastMathMode::None;
2951 bool CanUseKHRFloatControls2 =
2952 ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2);
2953 if (I.getFlag(MachineInstr::MIFlag::FmNoNans))
2954 Flags |= SPIRV::FPFastMathMode::NotNaN;
2955 if (I.getFlag(MachineInstr::MIFlag::FmNoInfs))
2956 Flags |= SPIRV::FPFastMathMode::NotInf;
2957 if (I.getFlag(MachineInstr::MIFlag::FmNsz))
2958 Flags |= SPIRV::FPFastMathMode::NSZ;
2959 if (I.getFlag(MachineInstr::MIFlag::FmArcp))
2960 Flags |= SPIRV::FPFastMathMode::AllowRecip;
2961 if (I.getFlag(MachineInstr::MIFlag::FmContract) && CanUseKHRFloatControls2)
2962 Flags |= SPIRV::FPFastMathMode::AllowContract;
2963 if (I.getFlag(MachineInstr::MIFlag::FmReassoc)) {
2964 if (CanUseKHRFloatControls2)
2965 // LLVM reassoc maps to SPIRV transform, see
2966 // https://github.com/KhronosGroup/SPIRV-Registry/issues/326 for details.
2967 // Because we are enabling AllowTransform, we must enable AllowReassoc and
2968 // AllowContract too, as required by SPIRV spec. Also, we used to map
2969 // MIFlag::FmReassoc to FPFastMathMode::Fast, which now should instead by
2970 // replaced by turning all the other bits instead. Therefore, we're
2971 // enabling every bit here except None and Fast.
2972 Flags |= SPIRV::FPFastMathMode::NotNaN | SPIRV::FPFastMathMode::NotInf |
2973 SPIRV::FPFastMathMode::NSZ | SPIRV::FPFastMathMode::AllowRecip |
2974 SPIRV::FPFastMathMode::AllowTransform |
2975 SPIRV::FPFastMathMode::AllowReassoc |
2976 SPIRV::FPFastMathMode::AllowContract;
2977 else
2978 Flags |= SPIRV::FPFastMathMode::Fast;
2979 }
2980
2981 if (CanUseKHRFloatControls2) {
2982 // Error out if SPIRV::FPFastMathMode::Fast is enabled.
2983 assert(!(Flags & SPIRV::FPFastMathMode::Fast) &&
2984 "SPIRV::FPFastMathMode::Fast is deprecated and should not be used "
2985 "anymore.");
2986
2987 // Error out if AllowTransform is enabled without AllowReassoc and
2988 // AllowContract.
2989 assert((!(Flags & SPIRV::FPFastMathMode::AllowTransform) ||
2990 ((Flags & SPIRV::FPFastMathMode::AllowReassoc &&
2991 Flags & SPIRV::FPFastMathMode::AllowContract))) &&
2992 "SPIRV::FPFastMathMode::AllowTransform requires AllowReassoc and "
2993 "AllowContract flags to be enabled as well.");
2994 }
2995
2996 return Flags;
2997}
2998
3000 if (ST.isKernel())
3001 return true;
3002 if (ST.getSPIRVVersion() < VersionTuple(1, 2))
3003 return false;
3004 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2);
3005}
3006
3008 MachineInstr &I, const SPIRVSubtarget &ST, const SPIRVInstrInfo &TII,
3010 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec) {
3011 bool Changed = false;
3012 // Insert after I so that the decorated register is defined before its use.
3013 MachineBasicBlock::iterator InsertPt = std::next(I.getIterator());
3014 auto Decorate = [&](SPIRV::Decoration::Decoration Dec,
3015 ArrayRef<uint32_t> DecArgs) {
3016 MachineIRBuilder MIRBuilder(*I.getParent(), InsertPt);
3017 MIRBuilder.setDebugLoc(I.getDebugLoc());
3018 buildOpDecorate(I.getOperand(0).getReg(), MIRBuilder, Dec, DecArgs);
3019 Changed = true;
3020 };
3021 if (TII.canUseIntegerWrapDecoration(I)) {
3022 if (I.getFlag(MachineInstr::MIFlag::NoSWrap) &&
3024 SPIRV::OperandCategory::DecorationOperand,
3025 SPIRV::Decoration::NoSignedWrap, ST, Reqs)
3026 .IsSatisfiable)
3027 Decorate(SPIRV::Decoration::NoSignedWrap, {});
3028 if (I.getFlag(MachineInstr::MIFlag::NoUWrap) &&
3030 SPIRV::OperandCategory::DecorationOperand,
3031 SPIRV::Decoration::NoUnsignedWrap, ST, Reqs)
3032 .IsSatisfiable)
3033 Decorate(SPIRV::Decoration::NoUnsignedWrap, {});
3034 }
3035 // In Kernel environments, FPFastMathMode on OpExtInst is valid per core
3036 // spec. For other instruction types, SPV_KHR_float_controls2 is required.
3037 bool CanUseFM =
3038 TII.canUseFastMathFlags(
3039 I, ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2)) ||
3040 (ST.isKernel() && I.getOpcode() == SPIRV::OpExtInst);
3041 if (!CanUseFM)
3042 return Changed;
3043
3044 unsigned FMFlags = getFastMathFlags(I, ST);
3045 if (FMFlags == SPIRV::FPFastMathMode::None) {
3046 // We also need to check if any FPFastMathDefault info was set for the
3047 // types used in this instruction.
3048 if (FPFastMathDefaultInfoVec.empty())
3049 return Changed;
3050
3051 // Use the first operand's FP type for arithmetic and comparisons,
3052 // and the result type for calls and extended instructions.
3053 SPIRVTypeInst FPType =
3054 I.getOpcode() == SPIRV::OpExtInst ||
3055 I.getOpcode() == SPIRV::OpFunctionCall
3056 ? I.getMF()->getRegInfo().getVRegDef(I.getOperand(1).getReg())
3057 : getRegType(I.getOperand(2).getReg(), *I.getMF(), GR);
3058 const Type *Ty = GR->getTypeForSPIRVType(FPType);
3059 Ty = Ty->isVectorTy() ? cast<VectorType>(Ty)->getElementType() : Ty;
3060
3061 // Match instruction type with the FPFastMathDefaultInfoVec.
3062 bool Emit = false;
3063 for (SPIRV::FPFastMathDefaultInfo &Elem : FPFastMathDefaultInfoVec) {
3064 if (Ty == Elem.Ty) {
3065 FMFlags = Elem.FastMathFlags;
3066 Emit = Elem.ContractionOff || Elem.SignedZeroInfNanPreserve ||
3067 Elem.FPFastMathDefault;
3068 break;
3069 }
3070 }
3071
3072 if (FMFlags == SPIRV::FPFastMathMode::None && !Emit)
3073 return Changed;
3074 }
3076 Decorate(SPIRV::Decoration::FPFastMathMode, {FMFlags});
3077 return Changed;
3078}
3079
3080static void addMBBNames(const Module &M, MachineFunctionGetter GetMF,
3082 for (const Function &F : M) {
3083 MachineFunction *MF = GetMF(F);
3084 if (!MF)
3085 continue;
3086 if (MF->getFunction()
3088 .isValid())
3089 continue;
3090 for (const auto &MBB : *MF) {
3091 if (!MBB.hasName() || MBB.empty())
3092 continue;
3093 MAI.MBBNames.emplace_back(MAI.getOrCreateMBBRegister(MBB), MBB.getName());
3094 }
3095 }
3096}
3097
3099 const Module &M,
3100 SPIRV::FPFastMathDefaultInfoMapTy &FPFastMathDefaultInfoMap,
3101 const Function *F) {
3102 auto it = FPFastMathDefaultInfoMap.find(F);
3103 if (it != FPFastMathDefaultInfoMap.end())
3104 return it->second;
3105
3106 // If the map does not contain the entry, create a new one. Initialize it to
3107 // contain all 3 elements sorted by bit width of target type: {half, float,
3108 // double}.
3109 SPIRV::FPFastMathDefaultInfoVector FPFastMathDefaultInfoVec;
3110 FPFastMathDefaultInfoVec.emplace_back(Type::getHalfTy(M.getContext()),
3111 SPIRV::FPFastMathMode::None);
3112 FPFastMathDefaultInfoVec.emplace_back(Type::getFloatTy(M.getContext()),
3113 SPIRV::FPFastMathMode::None);
3114 FPFastMathDefaultInfoVec.emplace_back(Type::getDoubleTy(M.getContext()),
3115 SPIRV::FPFastMathMode::None);
3116 return FPFastMathDefaultInfoMap[F] = std::move(FPFastMathDefaultInfoVec);
3117}
3118
3120 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec,
3121 const Type *Ty) {
3122 size_t BitWidth = Ty->getScalarSizeInBits();
3123 int Index =
3125 BitWidth);
3126 assert(Index >= 0 && Index < 3 &&
3127 "Expected FPFastMathDefaultInfo for half, float, or double");
3128 assert(FPFastMathDefaultInfoVec.size() == 3 &&
3129 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3130 return FPFastMathDefaultInfoVec[Index];
3131}
3132
3134 const Module &M,
3135 SPIRV::FPFastMathDefaultInfoMapTy &FPFastMathDefaultInfoMap,
3136 const SPIRVSubtarget &ST, const Function *OnlyF = nullptr) {
3137 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2))
3138 return;
3139
3140 // Store the FPFastMathDefaultInfo in the FPFastMathDefaultInfoMap.
3141 // We need the entry point (function) as the key, and the target
3142 // type and flags as the value.
3143 // We also need to check ContractionOff and SignedZeroInfNanPreserve
3144 // execution modes, as they are now deprecated and must be replaced
3145 // with FPFastMathDefaultInfo.
3146 auto Node = M.getNamedMetadata("spirv.ExecutionMode");
3147 if (!Node)
3148 return;
3149
3150 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
3151 MDNode *MDN = cast<MDNode>(Node->getOperand(i));
3152 assert(MDN->getNumOperands() >= 2 && "Expected at least 2 operands");
3153 const Function *F = cast<Function>(
3154 cast<ConstantAsMetadata>(MDN->getOperand(0))->getValue());
3155 if (OnlyF && F != OnlyF)
3156 continue;
3157 const auto EM =
3159 cast<ConstantAsMetadata>(MDN->getOperand(1))->getValue())
3160 ->getZExtValue();
3161 if (EM == SPIRV::ExecutionMode::FPFastMathDefault) {
3162 assert(MDN->getNumOperands() == 4 &&
3163 "Expected 4 operands for FPFastMathDefault");
3164
3165 const Type *T = cast<ValueAsMetadata>(MDN->getOperand(2))->getType();
3166 unsigned Flags =
3168 cast<ConstantAsMetadata>(MDN->getOperand(3))->getValue())
3169 ->getZExtValue();
3170 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3171 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3173 getFPFastMathDefaultInfo(FPFastMathDefaultInfoVec, T);
3174 Info.FastMathFlags = Flags;
3175 Info.FPFastMathDefault = true;
3176 } else if (EM == SPIRV::ExecutionMode::ContractionOff) {
3177 assert(MDN->getNumOperands() == 2 &&
3178 "Expected no operands for ContractionOff");
3179
3180 // We need to save this info for every possible FP type, i.e. {half,
3181 // float, double, fp128}.
3182 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3183 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3184 for (SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3185 Info.ContractionOff = true;
3186 }
3187 } else if (EM == SPIRV::ExecutionMode::SignedZeroInfNanPreserve) {
3188 assert(MDN->getNumOperands() == 3 &&
3189 "Expected 1 operand for SignedZeroInfNanPreserve");
3190 unsigned TargetWidth =
3192 cast<ConstantAsMetadata>(MDN->getOperand(2))->getValue())
3193 ->getZExtValue();
3194 // We need to save this info only for the FP type with TargetWidth.
3195 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3196 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3199 assert(Index >= 0 && Index < 3 &&
3200 "Expected FPFastMathDefaultInfo for half, float, or double");
3201 assert(FPFastMathDefaultInfoVec.size() == 3 &&
3202 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3203 FPFastMathDefaultInfoVec[Index].SignedZeroInfNanPreserve = true;
3204 }
3205 }
3206}
3207
3211 : ST(&ST), GR(ST.getSPIRVGlobalRegistry()), TII(ST.getInstrInfo()),
3212 MAI(MAI), GetMF(GetMF) {}
3213
3215 setBaseInfo(M);
3216
3217 addMBBNames(M, GetMF, MAI);
3218 collectFPFastMathDefaults(M, MAI.FPFastMathDefaultInfoMap, *ST);
3219
3220 collectReqs(M, MAI, GetMF, *ST);
3221
3222 // Process type/const/global var/func decl instructions, number their
3223 // destination registers from 0 to N, collect Extensions and Capabilities.
3224 collectDeclarations(M);
3225
3226 // Number rest of registers from N+1 onwards.
3227 numberRegistersGlobally(M);
3228
3229 // Collect OpName, OpEntryPoint, OpDecorate etc, process other instructions.
3230 processOtherInstrs(M);
3231
3232 // If there are no entry points, we need the Linkage capability.
3233 if (MAI.MS[SPIRV::MB_EntryPoints].empty())
3234 MAI.Reqs.addCapability(SPIRV::Capability::Linkage);
3235
3236 // Set maximum ID used.
3237 GR->setBound(MAI.MaxID);
3238}
3239
3244
3246 SPIRVTargetMachine &TM =
3250 *TM.getSubtargetImpl(), MAI,
3251 [&MMI](const Function &F) { return MMI.getMachineFunction(F); })
3252 .run(M);
3253 return false;
3254}
3255
3256AnalysisKey SPIRVModuleAnalysis::Key;
3257
3260 const auto &TM = static_cast<const SPIRVTargetMachine &>(
3261 MAM.getResult<MachineModuleAnalysis>(M).getMMI().getTarget());
3263 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
3264 Result MAI;
3265 SPIRVModuleAnalysisImpl(*TM.getSubtargetImpl(), MAI,
3266 [&FAM](const Function &F) -> MachineFunction * {
3267 MachineFunctionAnalysis::Result *MFA =
3268 FAM.getCachedResult<MachineFunctionAnalysis>(
3269 const_cast<Function &>(F));
3270 assert((MFA || F.isDeclaration()) &&
3271 "Missing MachineFunction for definition");
3272 return MFA ? &MFA->getMF() : nullptr;
3273 })
3274 .run(M);
3275 return MAI;
3276}
3277
3279 const auto &ST = MF.getSubtarget<SPIRVSubtarget>();
3280 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
3281 const SPIRVInstrInfo &TII = *ST.getInstrInfo();
3284 SPIRV::FPFastMathDefaultInfoMapTy FPFastMathDefaultInfoMap;
3285 const Function &F = MF.getFunction();
3286 collectFPFastMathDefaults(*F.getParent(), FPFastMathDefaultInfoMap, ST, &F);
3287 // Add decorations related to MI flags.
3288 bool Changed = false;
3289 for (auto &MBB : MF)
3290 for (auto &MI : make_early_inc_range(MBB))
3291 Changed |= handleMIFlagDecoration(MI, ST, TII, Reqs, GR,
3292 FPFastMathDefaultInfoMap[&F]);
3293 return Changed;
3294}
3295
3296namespace {
3297class SPIRVPrepareModuleAnalysisLegacy : public MachineFunctionPass {
3298public:
3299 static char ID;
3300 SPIRVPrepareModuleAnalysisLegacy() : MachineFunctionPass(ID) {}
3301 bool runOnMachineFunction(MachineFunction &MF) override {
3302 return prepareModuleAnalysis(MF);
3303 }
3304};
3305} // namespace
3306
3307char SPIRVPrepareModuleAnalysisLegacy::ID = 0;
3308
3309INITIALIZE_PASS(SPIRVPrepareModuleAnalysisLegacy,
3310 "spirv-prepare-module-analysis",
3311 "SPIRV prepare module analysis", false, false)
3312
3314 return new SPIRVPrepareModuleAnalysisLegacy();
3315}
3316
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock & MBB
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
static Register UseReg(const MachineOperand &MO)
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
#define ATOM_FLT_REQ_EXT_MSG(ExtName)
static bool isFastMathModeAvailable(const SPIRVSubtarget &ST)
static void addMBBNames(const Module &M, MachineFunctionGetter GetMF, SPIRV::ModuleAnalysisInfo &MAI)
static void maybeAddScatterGatherReq(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static void addImageOperandReqs(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST, unsigned OpIdx)
bool isStorageImage(MachineInstr *ImageInst)
bool isInputAttachment(MachineInstr *ImageInst)
static bool isBFloat16Type(SPIRVTypeInst TypeDef)
static bool handleMIFlagDecoration(MachineInstr &I, const SPIRVSubtarget &ST, const SPIRVInstrInfo &TII, SPIRV::RequirementHandler &Reqs, const SPIRVGlobalRegistry *GR, SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec)
bool isSampledImage(MachineInstr *ImageInst)
static bool addBFloat16ArithmeticRequirements(SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static unsigned getInvokeOperandIdx(unsigned Opcode)
static SPIRV::FPFastMathDefaultInfo & getFPFastMathDefaultInfo(SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec, const Type *Ty)
static void collectFPFastMathDefaults(const Module &M, SPIRV::FPFastMathDefaultInfoMapTy &FPFastMathDefaultInfoMap, const SPIRVSubtarget &ST, const Function *OnlyF=nullptr)
static void collectOtherInstr(MachineInstr &MI, SPIRV::ModuleAnalysisInfo &MAI, SPIRV::ModuleSectionType MSType, InstrTraces &IS, bool Append=true)
void addPrintfRequirements(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static void addOpTypeImageReqs(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static void addQuadControlRequirements(SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST, StringRef Feature)
static bool isImageTypeWithUnknownFormat(SPIRVTypeInst TypeInst)
bool isUniformTexelBuffer(MachineInstr *ImageInst)
bool isStorageTexelBuffer(MachineInstr *ImageInst)
static void AddAtomicFloatRequirements(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
bool isCombinedImageSampler(MachineInstr *SampledImageInst)
bool hasNonUniformDecoration(Register Reg, const MachineRegisterInfo &MRI)
const char * Msg
void addInstrRequirements(const MachineInstr &MI, SPIRV::ModuleAnalysisInfo &MAI, const SPIRVSubtarget &ST)
static void collectReqs(const Module &M, SPIRV::ModuleAnalysisInfo &MAI, MachineFunctionGetter GetMF, const SPIRVSubtarget &ST)
static void addOpDecorateReqs(const MachineInstr &MI, unsigned DecIndex, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static InstrSignature instrToSignature(const MachineInstr &MI, SPIRV::ModuleAnalysisInfo &MAI, bool UseDefReg)
static void AddDotProductRequirements(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static SPIRV::Requirements getSymbolicOperandRequirements(SPIRV::OperandCategory::OperandCategory Category, unsigned i, const SPIRVSubtarget &ST, SPIRV::RequirementHandler &Reqs)
static SPIRVTypeInst getRegType(Register Reg, const MachineFunction &MF, const SPIRVGlobalRegistry *GR)
static unsigned getMetadataUInt(MDNode *MdNode, unsigned OpIndex, unsigned DefaultVal=0)
static void addCoreInSPIRV13Capability(SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST, SPIRV::Capability::Capability Cap, SPIRV::Extension::Extension Ext)
void addOpAccessChainReqs(const MachineInstr &Instr, SPIRV::RequirementHandler &Handler, const SPIRVSubtarget &Subtarget)
static bool prepareModuleAnalysis(MachineFunction &MF)
static void appendDecorationsForReg(const MachineRegisterInfo &MRI, Register R, InstrSignature &Signature)
static SPIRV::FPFastMathDefaultInfoVector & getOrCreateFPFastMathDefaultInfoVec(const Module &M, SPIRV::FPFastMathDefaultInfoMapTy &FPFastMathDefaultInfoMap, const Function *F)
static bool shouldAvoidCapability(const SPIRVSubtarget &ST, SPIRV::Capability::Capability Cap)
static void AddAtomicVectorFloatRequirements(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static unsigned getFastMathFlags(const MachineInstr &I, const SPIRVSubtarget &ST)
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition SPIRVUtils.h:554
This file contains some templates that are useful if you are working with the STL at all.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
#define LLVM_DEBUG(...)
Definition Debug.h:119
Target-Independent Code Generator Pass Configuration Options pass.
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
Value * RHS
Value * LHS
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:263
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This is an important base class in LLVM.
Definition Constant.h:44
Diagnostic information for unsupported feature in backend.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isValid() const
Definition MCRegister.h:84
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Helper class to build MachineInstr.
void setDebugLoc(const DebugLoc &DL)
Set the debug location to DL for all the next build instructions.
Register getReg(unsigned Idx) const
Get the register for the operand index.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const MachineOperand & getOperand(unsigned i) const
An analysis that produces MachineModuleInfo for a module.
This class contains meta information specific to a module.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_ABI void print(raw_ostream &os, const TargetRegisterInfo *TRI=nullptr) const
Print the MachineOperand to os.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static MachineOperand CreateImm(int64_t Val)
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
iterator find(const KeyT &Key)
Definition MapVector.h:157
iterator end()
Definition MapVector.h:70
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
unsigned getScalarOrVectorBitWidth(SPIRVTypeInst Type) const
SPIRVTypeInst getResultType(Register VReg, MachineFunction *MF=nullptr)
const Type * getTypeForSPIRVType(SPIRVTypeInst Ty) const
SPIRVTypeInst getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
SPIRVModuleAnalysisImpl(const SPIRVSubtarget &ST, SPIRV::ModuleAnalysisInfo &MAI, MachineFunctionGetter GetMF)
SPIRV::ModuleAnalysisInfo Result
Result run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const SPIRVSubtarget * getSubtargetImpl() const
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Target-Independent Code Generator Pass Configuration Options.
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
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
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
Represents a version number in the form major[.minor[.subminor[.build]]].
bool empty() const
Determine whether this version information is empty (e.g., all version components are zero).
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
MapVector< const Function *, FPFastMathDefaultInfoVector > FPFastMathDefaultInfoMapTy
SmallVector< const MachineInstr * > InstrList
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
Definition STLExtras.h:2132
std::string getStringImm(const MachineInstr &MI, unsigned StartIndex)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
hash_code hash_value(const FixedPointSemantics &Val)
ExtensionList getSymbolicOperandExtensions(SPIRV::OperandCategory::OperandCategory Category, uint32_t Value)
CapabilityList getSymbolicOperandCapabilities(SPIRV::OperandCategory::OperandCategory Category, uint32_t Value)
SmallVector< SPIRV::Extension::Extension, 8 > ExtensionList
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
SmallVector< size_t > InstrSignature
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
static void reportUnsupported(MachineIRBuilder &MIRBuilder, const Twine &Msg)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
bool isVectorType(SPIRVTypeInst SPVTy)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
VersionTuple getSymbolicOperandMaxVersion(SPIRV::OperandCategory::OperandCategory Category, uint32_t Value)
function_ref< MachineFunction *(const Function &)> MachineFunctionGetter
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
CapabilityList getCapabilitiesEnabledByExtension(SPIRV::Extension::Extension Extension)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
FunctionPass * createSPIRVPrepareModuleAnalysisLegacyPass()
std::string getSymbolicOperandMnemonic(SPIRV::OperandCategory::OperandCategory Category, int32_t Value)
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool requiresLongVectorEXT(unsigned NumComponents, bool CanUseVector16=true)
Definition SPIRVUtils.h:509
DWARFExpression::Operation Op
VersionTuple getSymbolicOperandMinVersion(SPIRV::OperandCategory::OperandCategory Category, uint32_t Value)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
std::map< SmallVector< size_t >, MCRegister > InstrGRegsMap
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
SmallVector< SPIRV::Capability::Capability, 8 > CapabilityList
std::set< InstrSignature > InstrTraces
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
static size_t computeFPFastMathDefaultInfoVecIndex(size_t BitWidth)
Definition SPIRVUtils.h:149
void setSkipEmission(const MachineInstr *MI)
MCRegister getRegisterAlias(const MachineFunction *MF, Register Reg)
MCRegister getOrCreateMBBRegister(const MachineBasicBlock &MBB)
InstrList MS[NUM_MODULE_SECTIONS]
AddressingModel::AddressingModel Addr
SmallVector< std::pair< MCRegister, StringRef > > MBBNames
void checkSatisfiable(const SPIRVSubtarget &ST) const
void getAndAddRequirements(SPIRV::OperandCategory::OperandCategory Category, uint32_t i, const SPIRVSubtarget &ST)
void addRequirements(const Requirements &Req)
bool isCapabilityAvailable(Capability::Capability Cap) const
void removeCapabilityIf(const Capability::Capability ToRemove, const Capability::Capability IfPresent)
void addExtensions(const ExtensionList &ToAdd)
void addAvailableCaps(const CapabilityList &ToAdd)
void addExtension(Extension::Extension ToAdd)
void initAvailableCapabilities(const SPIRVSubtarget &ST)
void addCapability(Capability::Capability ToAdd)
void addCapabilities(const CapabilityList &ToAdd)
const std::optional< Capability::Capability > Cap