yum-mirror/glslang
git clone https://git.yummers.dev/yum-mirror/glslang
4ede04ac
vulkan-sdk-1.4.363.0
1// 2// Copyright (C) 2014-2015 LunarG, Inc. 3// Copyright (C) 2015-2020 Google, Inc. 4// Copyright (C) 2017 ARM Limited. 5// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved. 6// 7// All rights reserved. 8// 9// Redistribution and use in source and binary forms, with or without 10// modification, are permitted provided that the following conditions 11// are met: 12// 13// Redistributions of source code must retain the above copyright 14// notice, this list of conditions and the following disclaimer. 15// 16// Redistributions in binary form must reproduce the above 17// copyright notice, this list of conditions and the following 18// disclaimer in the documentation and/or other materials provided 19// with the distribution. 20// 21// Neither the name of 3Dlabs Inc. Ltd. nor the names of its 22// contributors may be used to endorse or promote products derived 23// from this software without specific prior written permission. 24// 25// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 26// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 27// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 28// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 29// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 30// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 31// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 32// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 33// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 34// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 35// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 36// POSSIBILITY OF SUCH DAMAGE. 37 38// 39// "Builder" is an interface to fully build SPIR-V IR. Allocate one of 40// these to build (a thread safe) internal SPIR-V representation (IR), 41// and then dump it as a binary stream according to the SPIR-V specification. 42// 43// A Builder has a 1:1 relationship with a SPIR-V module. 44// 45 46#pragma once 47#ifndef SpvBuilder_H 48#define SpvBuilder_H 49 50#include "Logger.h" 51#define SPV_ENABLE_UTILITY_CODE 52#include "spirv.hpp11" 53#include "spvIR.h" 54#include "spvUtil.h" 55 56namespace spv { 57 #include "GLSL.ext.KHR.h" 58 #include "GLSL.ext.EXT.h" 59 #include "NonSemanticShaderDebugInfo.h" 60} 61 62#include <algorithm> 63#include <cstdint> 64#include <map> 65#include <memory> 66#include <set> 67#include <sstream> 68#include <stack> 69#include <unordered_map> 70#include <unordered_set> 71#include <map> 72 73namespace spv { 74 75typedef enum { 76 Spv_1_0 = (1 << 16), 77 Spv_1_1 = (1 << 16) | (1 << 8), 78 Spv_1_2 = (1 << 16) | (2 << 8), 79 Spv_1_3 = (1 << 16) | (3 << 8), 80 Spv_1_4 = (1 << 16) | (4 << 8), 81 Spv_1_5 = (1 << 16) | (5 << 8), 82 Spv_1_6 = (1 << 16) | (6 << 8), 83} SpvVersion; 84 85struct StructMemberDebugInfo { 86 std::string name {}; 87 int line {0}; 88 int column {0}; 89 // Set if the caller knows a better debug type than what is associated with the functional SPIR-V type. 90 spv::Id debugTypeOverride {0}; 91}; 92 93class Builder { 94 class CompositeConstantKey { 95 public: 96 enum Kind { 97 Key_Instruction, 98 Key_CompositeConstant, 99 }; 100 101 CompositeConstantKey( 102 Op typeClass, Instruction* instruction) 103 : kind(Key_Instruction) 104 , instruction(instruction) 105 , typeClass(typeClass) 106 , opcode(Op::OpNop) 107 , typeId(NoType) 108 , numMembers(0) 109 , comps() 110 {} 111 112 CompositeConstantKey( 113 Op typeClass, Op opcode, Id typeId, const std::vector<Id>& comps, size_t numMembers) 114 : kind(Key_CompositeConstant) 115 , instruction(nullptr) 116 , typeClass(typeClass) 117 , opcode(opcode) 118 , typeId(typeId) 119 , numMembers(numMembers) 120 , comps(comps) 121 {} 122 123 Instruction* getInstruction() const { 124 return instruction; 125 } 126 127 // Functor to hash an instruction key. 128 struct Hash { 129 size_t operator()(CompositeConstantKey const &key) const { 130 switch (key.kind) { 131 case Key_Instruction: 132 { 133 Instruction* constant = key.instruction; 134 size_t num_operands = constant->getNumOperands(); 135 size_t hash = std::hash<Op>()(key.typeClass) * 7 ^ 136 std::hash<Op>()(constant->getOpCode()) * 11 ^ 137 std::hash<Id>()(constant->getTypeId()) * 13 ^ 138 std::hash<size_t>()(num_operands) * 17; 139 for (size_t i = 0; i < num_operands; ++i) { 140 hash = hash * 19 ^ std::hash<Id>()(constant->getIdOperand(i)); 141 } 142 return hash; 143 } 144 case Key_CompositeConstant: 145 { 146 size_t hash = std::hash<Op>()(key.typeClass) * 7 ^ 147 std::hash<Op>()(key.opcode) * 11 ^ 148 std::hash<Id>()(key.typeId) * 13 ^ 149 std::hash<size_t>()(key.numMembers) * 17; 150 for (size_t i = 0; i < key.numMembers; ++i) { 151 hash = hash * 19 ^ std::hash<Id>()(key.comps[i]); 152 } 153 return hash; 154 } 155 } 156 return 0; 157 } 158 }; 159 160 // Functor to compare two instruction keys. 161 struct Equal { 162 bool operator() (CompositeConstantKey const &a, CompositeConstantKey const &b) const 163 { 164 if (a.typeClass != b.typeClass) 165 return false; 166 167 if (a.kind == b.kind) { 168 // we need only the Instruction case, as the other keys only used for searching 169 return 170 a.kind == Key_Instruction && 171 a.instruction == b.instruction; 172 } 173 const CompositeConstantKey* s = &a; 174 const CompositeConstantKey* o = &b; 175 176 if (s->kind == Key_CompositeConstant && o->kind == Key_Instruction) { 177 s = o; 178 o = &a; 179 } 180 181 // compare a composite constant with an instruction 182 if (s->kind == Key_Instruction && o->kind == Key_CompositeConstant) { 183 Instruction* constant = s->instruction; 184 if (constant->getTypeId() != o->typeId) 185 return false; 186 187 if (constant->getOpCode() != o->opcode) { 188 return false; 189 } 190 191 if (constant->getNumOperands() != (int)o->numMembers) 192 return false; 193 194 // same contents? 195 for (int op = 0; op < constant->getNumOperands(); ++op) { 196 if (constant->getIdOperand(op) != o->comps[op]) { 197 return false; 198 } 199 } 200 return true; 201 } 202 return false; 203 } 204 }; 205 206 private: 207 Kind kind; 208 Instruction* instruction; 209 Op typeClass; 210 Op opcode; 211 Id typeId; 212 size_t numMembers; 213 std::vector<Id> comps; 214 }; 215 216 class StructConstantKey { 217 public: 218 enum Kind { 219 Key_Instruction, 220 Key_StructConstant, 221 }; 222 223 StructConstantKey( 224 Instruction* instruction) 225 : kind(Key_Instruction) 226 , instruction(instruction) 227 , typeId(NoType) 228 , numMembers(0) 229 , comps() 230 {} 231 232 StructConstantKey( 233 Id typeId, const std::vector<Id>& comps, size_t numMembers) 234 : kind(Key_StructConstant) 235 , instruction(nullptr) 236 , typeId(typeId) 237 , numMembers(numMembers) 238 , comps(comps) 239 {} 240 241 Instruction* getInstruction() const { 242 return instruction; 243 } 244 245 // Functor to hash an instruction key. 246 struct Hash { 247 size_t operator()(StructConstantKey const &key) const { 248 switch (key.kind) { 249 case Key_Instruction: 250 { 251 Instruction* constant = key.instruction; 252 size_t hash = std::hash<Id>()(constant->getTypeId()) * 13; 253 for (size_t i = 0, n = constant->getNumOperands(); i < n; ++i) { 254 hash = hash * 19 ^ std::hash<Id>()(constant->getIdOperand(i)); 255 } 256 return hash; 257 } 258 case Key_StructConstant: 259 { 260 size_t hash = std::hash<Id>()(key.typeId) * 13; 261 for (size_t i = 0; i < key.numMembers; ++i) { 262 hash = hash * 19 ^ std::hash<Id>()(key.comps[i]); 263 } 264 return hash; 265 } 266 } 267 return 0; 268 } 269 }; 270 271 // Functor to compare two instruction keys. 272 struct Equal { 273 bool operator() (StructConstantKey const &a, StructConstantKey const &b) const 274 { 275 if (a.kind == b.kind) { 276 // we need only the Instruction case, as the other keys only used for searching 277 return 278 a.kind == Key_Instruction && 279 a.instruction == b.instruction; 280 } 281 const StructConstantKey* s = &a; 282 const StructConstantKey* o = &b; 283 284 if (s->kind == Key_StructConstant && o->kind == Key_Instruction) { 285 s = o; 286 o = &a; 287 } 288 289 // compare a composite constant with an instruction 290 if (s->kind == Key_Instruction && o->kind == Key_StructConstant) { 291 Instruction* constant = s->instruction; 292 if (constant->getTypeId() != o->typeId) 293 return false; 294 295 if (constant->getNumOperands() != (int)o->numMembers) 296 return false; 297 298 // same contents? 299 for (int op = 0; op < constant->getNumOperands(); ++op) { 300 if (constant->getIdOperand(op) != o->comps[op]) { 301 return false; 302 } 303 } 304 return true; 305 } 306 return false; 307 } 308 }; 309 310 private: 311 Kind kind; 312 Instruction* instruction; 313 Id typeId; 314 size_t numMembers; 315 std::vector<Id> comps; 316 }; 317 318public: 319 Builder(unsigned int spvVersion, unsigned int userNumber, SpvBuildLogger* logger); 320 virtual ~Builder(); 321 322 static const int maxMatrixSize = 4; 323 324 unsigned int getSpvVersion() const { return spvVersion; } 325 326 void setSource(spv::SourceLanguage lang, int version) 327 { 328 sourceLang = lang; 329 sourceVersion = version; 330 } 331 spv::Id getStringId(const std::string& str) 332 { 333 auto sItr = stringIds.find(str); 334 if (sItr != stringIds.end()) 335 return sItr->second; 336 spv::Id strId = getUniqueId(); 337 Instruction* fileString = new Instruction(strId, NoType, Op::OpString); 338 const char* file_c_str = str.c_str(); 339 fileString->addStringOperand(file_c_str); 340 strings.push_back(std::unique_ptr<Instruction>(fileString)); 341 module.mapInstruction(fileString); 342 stringIds[file_c_str] = strId; 343 return strId; 344 } 345 346 spv::Id getMainFileId() const { return mainFileId; } 347 348 // Initialize the main source file name 349 void setDebugMainSourceFile(const std::string& file) 350 { 351 if (trackDebugInfo) { 352 dirtyLineTracker = true; 353 mainFileId = getStringId(file); 354 currentFileId = mainFileId; 355 } 356 } 357 358 // Set the debug source location tracker in the builder. 359 // The upcoming instructions in basic blocks will be associated to this location. 360 void setDebugSourceLocation(int line, const char* filename) 361 { 362 if (trackDebugInfo) { 363 dirtyLineTracker = true; 364 if (line != 0) { 365 // TODO: This is special handling of some AST nodes having (untracked) line 0. 366 // But they should have a valid line number. 367 currentLine = line; 368 if (filename) { 369 currentFileId = getStringId(filename); 370 } 371 } 372 } 373 } 374 375 void setSourceText(const std::string& text) { sourceText = text; } 376 void addSourceExtension(const char* ext) { sourceExtensions.push_back(ext); } 377 void addModuleProcessed(const std::string& p) { moduleProcesses.push_back(p.c_str()); } 378 void setEmitSpirvDebugInfo() 379 { 380 trackDebugInfo = true; 381 emitSpirvDebugInfo = true; 382 } 383 void setEmitNonSemanticShaderDebugInfo(bool emitSourceText) 384 { 385 trackDebugInfo = true; 386 emitNonSemanticShaderDebugInfo = true; 387 importNonSemanticShaderDebugInfoInstructions(); 388 389 if (emitSourceText) { 390 emitNonSemanticShaderDebugSource = emitSourceText; 391 } 392 } 393 void addExtension(const char* ext) { extensions.insert(ext); } 394 void removeExtension(const char* ext) 395 { 396 extensions.erase(ext); 397 } 398 void addIncorporatedExtension(const char* ext, SpvVersion incorporatedVersion) 399 { 400 if (getSpvVersion() < static_cast<unsigned>(incorporatedVersion)) 401 addExtension(ext); 402 } 403 void promoteIncorporatedExtension(const char* baseExt, const char* promoExt, SpvVersion incorporatedVersion) 404 { 405 removeExtension(baseExt); 406 addIncorporatedExtension(promoExt, incorporatedVersion); 407 } 408 void addInclude(const std::string& name, const std::string& text) 409 { 410 spv::Id incId = getStringId(name); 411 includeFiles[incId] = &text; 412 } 413 Id import(const char*); 414 void setMemoryModel(spv::AddressingModel addr, spv::MemoryModel mem) 415 { 416 addressModel = addr; 417 memoryModel = mem; 418 } 419 420 void addCapability(spv::Capability cap) { capabilities.insert(cap); } 421 422 // To get a new <id> for anything needing a new one. 423 Id getUniqueId() { return ++uniqueId; } 424 425 // To get a set of new <id>s, e.g., for a set of function parameters 426 Id getUniqueIds(int numIds) 427 { 428 Id id = uniqueId + 1; 429 uniqueId += numIds; 430 return id; 431 } 432 433 // Maps the given OpType Id to a Non-Semantic DebugType Id. 434 Id getDebugType(Id type) { 435 if (auto it = debugTypeIdLookup.find(type); it != debugTypeIdLookup.end()) { 436 return it->second; 437 } 438 439 return NoType; 440 } 441 442 // Maps the given OpFunction Id to a Non-Semantic DebugFunction Id. 443 Id getDebugFunction(Id func) { 444 if (auto it = debugFuncIdLookup.find(func); it != debugFuncIdLookup.end()) { 445 return it->second; 446 } 447 448 return NoResult; 449 } 450 451 // For creating new types (will return old type if the requested one was already made). 452 Id makeVoidType(); 453 Id makeBoolType(); 454 Id makePointer(StorageClass, Id pointee); 455 Id makeForwardPointer(StorageClass); 456 Id makePointerFromForwardPointer(StorageClass, Id forwardPointerType, Id pointee); 457 Id makeUntypedPointer(StorageClass storageClass, bool setBufferPointer = false); 458 Id makeIntegerType(int width, bool hasSign); // generic 459 Id makeIntType(int width) { return makeIntegerType(width, true); } 460 Id makeUintType(int width) { return makeIntegerType(width, false); } 461 Id makeFloatType(int width); 462 Id makeBFloat16Type(); 463 Id makeFloatE5M2Type(); 464 Id makeFloatE4M3Type(); 465 Id makeFloatE2M1Type(); 466 Id makeFloatE3M2Type(); 467 Id makeFloatE2M3Type(); 468 Id makeFloatUE8M0Type(); 469 Id makeFloatMXINT8Type(); 470 Id makeFloatOcpMicroscalingType(uint32_t width, FPEncoding encoding, Capability cap); 471 Id makeStructType(const std::vector<Id>& members, const std::vector<spv::StructMemberDebugInfo>& memberDebugInfo, 472 const char* name, bool const compilerGenerated = true); 473 Id makeStructResultType(Id type0, Id type1); 474 Id makeVectorType(Id component, int size); 475 Id makeMatrixType(Id component, int cols, int rows); 476 Id makeArrayType(Id element, Id sizeId, int stride); // 0 stride means no stride decoration 477 Id makeRuntimeArray(Id element); 478 Id makeFunctionType(Id returnType, const std::vector<Id>& paramTypes); 479 Id makeImageType(Id sampledType, Dim, bool depth, bool arrayed, bool ms, unsigned sampled, ImageFormat format, const char* debugNames); 480 Id makeSamplerType(const char* debugName); 481 Id makeSampledImageType(Id imageType, const char* debugName); 482 Id makeCooperativeMatrixTypeKHR(Id component, Id scope, Id rows, Id cols, Id use); 483 Id makeCooperativeMatrixTypeNV(Id component, Id scope, Id rows, Id cols); 484 Id makeCooperativeMatrixTypeWithSameShape(Id component, Id otherType); 485 Id makeCooperativeVectorTypeNV(Id componentType, Id components); 486 Id makeTensorTypeARM(Id elementType, Id rank); 487 Id makeGenericType(spv::Op opcode, std::vector<spv::IdImmediate>& operands); 488 489 // SPIR-V NonSemantic Shader DebugInfo Instructions 490 Id makeDebugInfoNone(); 491 Id makeBoolDebugType(int const size); 492 Id makeIntegerDebugType(int const width, bool const hasSign); 493 Id makeFloatDebugType(int const width, Id const fpEncoding = NoType); 494 Id makeSequentialDebugType(Id const baseType, Id const componentCount, NonSemanticShaderDebugInfoInstructions const sequenceType); 495 Id makeArrayDebugType(Id const baseType, Id const componentCount); 496 Id makeVectorDebugType(Id const baseType, int const componentCount); 497 Id makeMatrixDebugType(Id const vectorType, int const vectorCount, bool columnMajor = true); 498 Id makeMemberDebugType(Id const memberType, StructMemberDebugInfo const& debugTypeLoc); 499 Id makeCompositeDebugType(std::vector<Id> const& memberTypes, std::vector<StructMemberDebugInfo> const& memberDebugInfo, 500 char const* const name, NonSemanticShaderDebugInfoDebugCompositeType const tag); 501 Id makeOpaqueDebugType(char const* const name); 502 Id makeVectorIdDebugType(Id componentType, Id componentCount); 503 Id makeCooperativeMatrixDebugTypeKHR(Id componentType, Id scope, Id rows, Id cols, Id use); 504 Id makePointerDebugType(StorageClass storageClass, Id const baseType); 505 Id makeForwardPointerDebugType(StorageClass storageClass); 506 Id makeDebugSource(const Id fileName); 507 Id makeDebugCompilationUnit(); 508 Id createDebugGlobalVariable(Id const type, char const*const name, Id const variable); 509 Id createDebugLocalVariable(Id type, char const*const name, size_t const argNumber = 0); 510 Id makeDebugExpression(); 511 Id makeDebugDeclare(Id const debugLocalVariable, Id const pointer); 512 Id makeDebugValue(Id const debugLocalVariable, Id const value); 513 Id makeDebugFunctionType(Id returnType, const std::vector<Id>& paramTypes); 514 Id makeDebugFunction(Function* function, Id nameId, Id funcTypeId); 515 Id makeDebugEntryPoint(Function* function, const char* compilerSignature, const char* commandLineArguments, 516 const char* currentWorkingDirectory = nullptr); 517 Id makeDebugLexicalBlock(uint32_t line, uint32_t column); 518 std::string unmangleFunctionName(std::string const& name) const; 519 520 // Initialize non-semantic debug information for a function, including those of: 521 // - The function definition 522 // - The function parameters 523 void setupFunctionDebugInfo(Function* function, const char* name, const std::vector<Id>& paramTypes, 524 const std::vector<char const*>& paramNames); 525 526 // accelerationStructureNV type 527 Id makeAccelerationStructureType(); 528 // rayQueryEXT type 529 Id makeRayQueryType(); 530 // hitObjectNV type 531 Id makeHitObjectNVType(); 532 // hitObjectEXT type 533 Id makeHitObjectEXTType(); 534 535 // For querying about types. 536 Id getTypeId(Id resultId) const { return module.getTypeId(resultId); } 537 Id getDerefTypeId(Id resultId) const; 538 Op getOpCode(Id id) const { return module.getInstruction(id)->getOpCode(); } 539 Op getTypeClass(Id typeId) const { return getOpCode(typeId); } 540 Op getMostBasicTypeClass(Id typeId) const; 541 unsigned int getNumComponents(Id resultId) const { return getNumTypeComponents(getTypeId(resultId)); } 542 unsigned int getNumTypeConstituents(Id typeId) const; 543 unsigned int getNumTypeComponents(Id typeId) const { return getNumTypeConstituents(typeId); } 544 Id getScalarTypeId(Id typeId) const; 545 Id getContainedTypeId(Id typeId) const; 546 Id getContainedTypeId(Id typeId, int) const; 547 StorageClass getTypeStorageClass(Id typeId) const { return module.getStorageClass(typeId); } 548 ImageFormat getImageTypeFormat(Id typeId) const 549 { return (ImageFormat)module.getInstruction(typeId)->getImmediateOperand(6); } 550 Id getResultingAccessChainType() const; 551 Id getIdOperand(Id resultId, int idx) { return module.getInstruction(resultId)->getIdOperand(idx); } 552 Id getCooperativeVectorNumComponents(Id typeId) const { return module.getInstruction(typeId)->getIdOperand(1); } 553 554 bool isPointer(Id resultId) const { return isPointerType(getTypeId(resultId)); } 555 bool isUntypedPointer(Id resultId) const 556 { 557 const Id tid = getTypeId(resultId); 558 // Expect that OpString have no type 559 if (tid == 0) 560 return false; 561 return isUntypedPointerType(tid); 562 } 563 bool isScalar(Id resultId) const { return isScalarType(getTypeId(resultId)); } 564 bool isVector(Id resultId) const { return isVectorType(getTypeId(resultId)); } 565 bool isMatrix(Id resultId) const { return isMatrixType(getTypeId(resultId)); } 566 bool isCooperativeMatrix(Id resultId)const { return isCooperativeMatrixType(getTypeId(resultId)); } 567 bool isCooperativeVector(Id resultId)const { return isCooperativeVectorType(getTypeId(resultId)); } 568 bool isAggregate(Id resultId) const { return isAggregateType(getTypeId(resultId)); } 569 bool isSampledImage(Id resultId) const { return isSampledImageType(getTypeId(resultId)); } 570 bool isTensorView(Id resultId)const { return isTensorViewType(getTypeId(resultId)); } 571 572 bool isBoolType(Id typeId) 573 { return groupedTypes[enumCast(Op::OpTypeBool)].size() > 0 && typeId == groupedTypes[enumCast(Op::OpTypeBool)].back()->getResultId(); } 574 bool isIntType(Id typeId) const 575 { return getTypeClass(typeId) == Op::OpTypeInt && module.getInstruction(typeId)->getImmediateOperand(1) != 0; } 576 bool isUintType(Id typeId) const 577 { return getTypeClass(typeId) == Op::OpTypeInt && module.getInstruction(typeId)->getImmediateOperand(1) == 0; } 578 bool isFloatType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeFloat; } 579 bool isPointerType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypePointer; } 580 bool isUntypedPointerType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeUntypedPointerKHR; } 581 bool isScalarType(Id typeId) const 582 { return getTypeClass(typeId) == Op::OpTypeFloat || getTypeClass(typeId) == Op::OpTypeInt || 583 getTypeClass(typeId) == Op::OpTypeBool; } 584 bool isVectorType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeVector; } 585 bool isMatrixType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeMatrix; } 586 bool isStructType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeStruct; } 587 bool isArrayType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeArray; } 588 bool isCooperativeMatrixType(Id typeId)const 589 { 590 return getTypeClass(typeId) == Op::OpTypeCooperativeMatrixKHR || getTypeClass(typeId) == Op::OpTypeCooperativeMatrixNV; 591 } 592 bool isTensorViewType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeTensorViewNV; } 593 bool isCooperativeVectorType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeCooperativeVectorNV; } 594 bool isTensorTypeARM(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeTensorARM; } 595 bool isAggregateType(Id typeId) const 596 { return isArrayType(typeId) || isStructType(typeId) || isCooperativeMatrixType(typeId); } 597 bool isImageType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeImage; } 598 bool isSamplerType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeSampler; } 599 bool isSampledImageType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeSampledImage; } 600 bool containsType(Id typeId, Op typeOp, unsigned int width) const; 601 bool containsPhysicalStorageBufferOrArray(Id typeId) const; 602 603 bool isConstantOpCode(Op opcode) const; 604 bool isSpecConstantOpCode(Op opcode) const; 605 bool isConstant(Id resultId) const { return isConstantOpCode(getOpCode(resultId)); } 606 bool isConstantScalar(Id resultId) const { return getOpCode(resultId) == Op::OpConstant; } 607 bool isSpecConstant(Id resultId) const { return isSpecConstantOpCode(getOpCode(resultId)); } 608 unsigned int getConstantScalar(Id resultId) const 609 { return module.getInstruction(resultId)->getImmediateOperand(0); } 610 StorageClass getStorageClass(Id resultId) const { return getTypeStorageClass(getTypeId(resultId)); } 611 612 bool isVariableOpCode(Op opcode) const { return opcode == Op::OpVariable; } 613 bool isVariable(Id resultId) const { return isVariableOpCode(getOpCode(resultId)); } 614 bool isGlobalStorage(Id resultId) const { return getStorageClass(resultId) != StorageClass::Function; } 615 bool isGlobalVariable(Id resultId) const { return isVariable(resultId) && isGlobalStorage(resultId); } 616 // See if a resultId is valid for use as an initializer. 617 bool isValidInitializer(Id resultId) const { return isConstant(resultId) || isGlobalVariable(resultId); } 618 619 int getScalarTypeWidth(Id typeId) const 620 { 621 Id scalarTypeId = getScalarTypeId(typeId); 622 assert(getTypeClass(scalarTypeId) == Op::OpTypeInt || getTypeClass(scalarTypeId) == Op::OpTypeFloat); 623 return module.getInstruction(scalarTypeId)->getImmediateOperand(0); 624 } 625 626 unsigned int getTypeNumColumns(Id typeId) const 627 { 628 assert(isMatrixType(typeId)); 629 return getNumTypeConstituents(typeId); 630 } 631 unsigned int getNumColumns(Id resultId) const { return getTypeNumColumns(getTypeId(resultId)); } 632 unsigned int getTypeNumRows(Id typeId) const 633 { 634 assert(isMatrixType(typeId)); 635 return getNumTypeComponents(getContainedTypeId(typeId)); 636 } 637 unsigned int getNumRows(Id resultId) const { return getTypeNumRows(getTypeId(resultId)); } 638 639 Dim getTypeDimensionality(Id typeId) const 640 { 641 assert(isImageType(typeId)); 642 return (Dim)module.getInstruction(typeId)->getImmediateOperand(1); 643 } 644 Id getImageType(Id resultId) const 645 { 646 Id typeId = getTypeId(resultId); 647 assert(isImageType(typeId) || isSampledImageType(typeId)); 648 return isSampledImageType(typeId) ? module.getInstruction(typeId)->getIdOperand(0) : typeId; 649 } 650 bool isArrayedImageType(Id typeId) const 651 { 652 assert(isImageType(typeId)); 653 return module.getInstruction(typeId)->getImmediateOperand(3) != 0; 654 } 655 656 // For making new constants (will return old constant if the requested one was already made). 657 Id makeNullConstant(Id typeId); 658 Id makeBoolConstant(bool b, bool specConstant = false); 659 Id makeIntConstant(Id typeId, unsigned value, bool specConstant); 660 Id makeInt64Constant(Id typeId, unsigned long long value, bool specConstant); 661 Id makeInt8Constant(int i, bool specConstant = false) 662 { return makeIntConstant(makeIntType(8), (unsigned)i, specConstant); } 663 Id makeUint8Constant(unsigned u, bool specConstant = false) 664 { return makeIntConstant(makeUintType(8), u, specConstant); } 665 Id makeInt16Constant(int i, bool specConstant = false) 666 { return makeIntConstant(makeIntType(16), (unsigned)i, specConstant); } 667 Id makeUint16Constant(unsigned u, bool specConstant = false) 668 { return makeIntConstant(makeUintType(16), u, specConstant); } 669 Id makeIntConstant(int i, bool specConstant = false) 670 { return makeIntConstant(makeIntType(32), (unsigned)i, specConstant); } 671 Id makeUintConstant(unsigned u, bool specConstant = false) 672 { return makeIntConstant(makeUintType(32), u, specConstant); } 673 Id makeUintConstant(Scope u, bool specConstant = false) 674 { return makeUintConstant((unsigned)u, specConstant); } 675 Id makeUintConstant(StorageClass u, bool specConstant = false) 676 { return makeUintConstant((unsigned)u, specConstant); } 677 Id makeUintConstant(MemorySemanticsMask u, bool specConstant = false) 678 { return makeUintConstant((unsigned)u, specConstant); } 679 Id makeUintConstant(SourceLanguage u, bool specConstant = false) 680 { return makeUintConstant((unsigned)u, specConstant); } 681 Id makeInt64Constant(long long i, bool specConstant = false) 682 { return makeInt64Constant(makeIntType(64), (unsigned long long)i, specConstant); } 683 Id makeUint64Constant(unsigned long long u, bool specConstant = false) 684 { return makeInt64Constant(makeUintType(64), u, specConstant); } 685 Id makeFloatConstant(float f, bool specConstant = false); 686 Id makeDoubleConstant(double d, bool specConstant = false); 687 Id makeFloat16Constant(float f16, bool specConstant = false); 688 Id makeBFloat16Constant(float bf16, bool specConstant = false); 689 Id makeFloatE5M2Constant(float fe5m2, bool specConstant = false); 690 Id makeFloatE4M3Constant(float fe4m3, bool specConstant = false); 691 Id makeFloatE2M1Constant(float fe2m1, bool specConstant = false); 692 Id makeFloatE3M2Constant(float fe3m2, bool specConstant = false); 693 Id makeFloatE2M3Constant(float fe2m3, bool specConstant = false); 694 Id makeFloatUE8M0Constant(float fue8m0, bool specConstant = false); 695 Id makeFloatMXINT8Constant(float mxint8, bool specConstant = false); 696 Id makeFpConstant(Id type, double d, bool specConstant = false); 697 698 Id importNonSemanticShaderDebugInfoInstructions(); 699 // Ensure the NonSemantic.Shader.DebugInfo import string names at least `version`. 700 // If the import instruction already exists, its name is patched in place. 701 // If it has not been created yet, importNonSemanticShaderDebugInfoInstructions() 702 // will use the updated version when it runs. 703 void requireNonSemanticShaderDebugInfoVersion(unsigned version); 704 705 // Turn the array of constants into a proper spv constant of the requested type. 706 Id makeCompositeConstant(Id type, const std::vector<Id>& comps, bool specConst = false); 707 708 // Methods for adding information outside the CFG. 709 Instruction* addEntryPoint(ExecutionModel, Function*, const char* name); 710 void addExecutionMode(Function*, ExecutionMode mode, int value1 = -1, int value2 = -1, int value3 = -1); 711 void addExecutionMode(Function*, ExecutionMode mode, const std::vector<unsigned>& literals); 712 void addExecutionModeId(Function*, ExecutionMode mode, const std::vector<Id>& operandIds); 713 void addName(Id, const char* name); 714 void addMemberName(Id, int member, const char* name); 715 void addDecoration(Id, Decoration, int num = -1); 716 void addDecoration(Id, Decoration, const char*); 717 void addDecoration(Id, Decoration, const std::vector<unsigned>& literals); 718 void addDecoration(Id, Decoration, const std::vector<const char*>& strings); 719 void addLinkageDecoration(Id id, const char* name, spv::LinkageType linkType); 720 void addDecorationId(Id id, Decoration, Id idDecoration); 721 void addDecorationId(Id id, Decoration, const std::vector<Id>& operandIds); 722 void addMemberDecoration(Id, unsigned int member, Decoration, int num = -1); 723 void addMemberDecoration(Id, unsigned int member, Decoration, const char*); 724 void addMemberDecoration(Id, unsigned int member, Decoration, const std::vector<unsigned>& literals); 725 void addMemberDecoration(Id, unsigned int member, Decoration, const std::vector<const char*>& strings); 726 void addMemberDecorationIdEXT(Id, unsigned int member, Decoration, const std::vector<unsigned>& operands); 727 728 // At the end of what block do the next create*() instructions go? 729 // Also reset current last DebugScope and current source line to unknown 730 void setBuildPoint(Block* bp) { 731 buildPoint = bp; 732 descHeapShiftedBaseCache.clear(); 733 dirtyLineTracker = true; 734 dirtyScopeTracker = true; 735 } 736 Block* getBuildPoint() const { return buildPoint; } 737 738 // Append an instruction to the end of the current build point. 739 // Optionally, additional debug info instructions may also be prepended. 740 void addInstruction(std::unique_ptr<Instruction> inst); 741 742 // Append an instruction to the end of the current build point without prepending any debug instructions. 743 // This is useful for insertion of some debug info instructions themselves or some control flow instructions 744 // that are attached to its predecessor instruction. 745 void addInstructionNoDebugInfo(std::unique_ptr<Instruction> inst); 746 747 // Make the entry-point function. The returned pointer is only valid 748 // for the lifetime of this builder. 749 Function* makeEntryPoint(const char*); 750 751 // Make a shader-style function, and create its entry block if entry is non-zero. 752 // Return the function, pass back the entry. 753 // The returned pointer is only valid for the lifetime of this builder. 754 Function* makeFunctionEntry(Decoration precision, Id returnType, const char* name, LinkageType linkType, 755 const std::vector<Id>& paramTypes, 756 const std::vector<std::vector<Decoration>>& precisions, Block** entry = nullptr); 757 758 // Create a return. An 'implicit' return is one not appearing in the source 759 // code. In the case of an implicit return, no post-return block is inserted. 760 void makeReturn(bool implicit, Id retVal = 0); 761 762 // Initialize state and generate instructions for new lexical scope 763 void enterLexicalBlock(uint32_t line, uint32_t column); 764 765 // Set state and generate instructions to exit current lexical scope 766 void leaveLexicalBlock(); 767 768 // Prepare builder for generation of instructions for a function. 769 void enterFunction(Function const* function); 770 771 // Generate all the code needed to finish up a function. 772 void leaveFunction(); 773 774 // Create block terminator instruction for certain statements like 775 // discard, terminate-invocation, terminateRayEXT, or ignoreIntersectionEXT 776 void makeStatementTerminator(spv::Op opcode, const char *name); 777 778 // Create block terminator instruction for statements that have input operands 779 // such as OpEmitMeshTasksEXT 780 void makeStatementTerminator(spv::Op opcode, const std::vector<Id>& operands, const char* name); 781 782 // Create a global/local constant. Because OpConstant is automatically emitted by getting the constant 783 // ids, this function only handles debug info. 784 void createConstVariable(Id type, const char* name, Id constant, bool isGlobal); 785 786 // Create a global or function local or IO variable. 787 Id createVariable(Decoration precision, StorageClass storageClass, Id type, const char* name = nullptr, 788 Id initializer = NoResult, bool const compilerGenerated = true); 789 790 // Create an untyped global or function local or IO variable. 791 Id createUntypedVariable(Decoration precision, StorageClass storageClass, const char* name = nullptr, 792 Id dataType = NoResult, Id initializer = NoResult); 793 794 // Create an intermediate with an undefined value. 795 Id createUndefined(Id type); 796 797 // Create load/store instruction with a remapped descriptor heap base. 798 Instruction* createDescHeapLoadStoreBaseRemap(Id base, Op op); 799 800 // Store into an Id and return the l-value 801 void createStore(Id rValue, Id lValue, spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMask::MaskNone, 802 spv::Scope scope = spv::Scope::Max, unsigned int alignment = 0); 803 804 // Load from an Id and return it 805 Id createLoad(Id lValue, spv::Decoration precision, 806 spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMask::MaskNone, 807 spv::Scope scope = spv::Scope::Max, unsigned int alignment = 0); 808 809 // Create an OpAccessChain instruction 810 Id createAccessChain(StorageClass, Id base, const std::vector<Id>& offsets); 811 812 // Create an OpUntypedAccessChainKHR instruction 813 Id createUntypedAccessChain(Id resultType, Id base, const std::vector<Id>& offsets, Id resultId = NoResult); 814 815 // Create an OpArrayLength instruction 816 Id createArrayLength(Id base, unsigned int member, unsigned int bits); 817 818 // Create an OpCooperativeMatrixLengthKHR instruction 819 Id createCooperativeMatrixLengthKHR(Id type); 820 // Create an OpCooperativeMatrixLengthNV instruction 821 Id createCooperativeMatrixLengthNV(Id type); 822 823 // Create an OpCompositeExtract instruction 824 Id createCompositeExtract(Id composite, Id typeId, unsigned index); 825 Id createCompositeExtract(Id composite, Id typeId, const std::vector<unsigned>& indexes); 826 Id createCompositeInsert(Id object, Id composite, Id typeId, unsigned index); 827 Id createCompositeInsert(Id object, Id composite, Id typeId, const std::vector<unsigned>& indexes); 828 829 Id createVectorExtractDynamic(Id vector, Id typeId, Id componentIndex); 830 Id createVectorInsertDynamic(Id vector, Id typeId, Id component, Id componentIndex); 831 832 void createNoResultOp(Op); 833 void createNoResultOp(Op, Id operand); 834 void createNoResultOp(Op, const std::vector<Id>& operands); 835 void createNoResultOp(Op, const std::vector<IdImmediate>& operands); 836 void createControlBarrier(Scope execution, Scope memory, MemorySemanticsMask); 837 void createSplitControlBarrier(Op op, Scope execution, Scope memory, MemorySemanticsMask memorySem); 838 void createMemoryBarrier(Scope executionScope, MemorySemanticsMask memorySemantics); 839 Id createUnaryOp(Op, Id typeId, Id operand); 840 Id createBinOp(Op, Id typeId, Id operand1, Id operand2); 841 Id createTriOp(Op, Id typeId, Id operand1, Id operand2, Id operand3); 842 Id createOp(Op, Id typeId, const std::vector<Id>& operands); 843 Id createOp(Op, Id typeId, const std::vector<IdImmediate>& operands); 844 Id createConstData(Op opCode, Id typeId, const std::vector<const char*> operands); 845 Id createFunctionCall(spv::Function*, const std::vector<spv::Id>&); 846 Id createSpecConstantOp(Op, Id typeId, const std::vector<spv::Id>& operands, const std::vector<unsigned>& literals); 847 Id createSpecConstantAlignTo(Id value, Id alignment); 848 Id createSpecConstantSelectMax(Id lhs, Id rhs); 849 850 // Take an rvalue (source) and a set of channels to extract from it to 851 // make a new rvalue, which is returned. 852 Id createRvalueSwizzle(Decoration precision, Id typeId, Id source, const std::vector<unsigned>& channels); 853 854 // Take a copy of an lvalue (target) and a source of components, and set the 855 // source components into the lvalue where the 'channels' say to put them. 856 // An updated version of the target is returned. 857 // (No true lvalue or stores are used.) 858 Id createLvalueSwizzle(Id typeId, Id target, Id source, const std::vector<unsigned>& channels); 859 860 // If both the id and precision are valid, the id 861 // gets tagged with the requested precision. 862 // The passed in id is always the returned id, to simplify use patterns. 863 Id setPrecision(Id id, Decoration precision) 864 { 865 if (precision != NoPrecision && id != NoResult) 866 addDecoration(id, precision); 867 868 return id; 869 } 870 871 // Can smear a scalar to a vector for the following forms: 872 // - promoteScalar(scalar, vector) // smear scalar to width of vector 873 // - promoteScalar(vector, scalar) // smear scalar to width of vector 874 // - promoteScalar(pointer, scalar) // smear scalar to width of what pointer points to 875 // - promoteScalar(scalar, scalar) // do nothing 876 // Other forms are not allowed. 877 // 878 // Generally, the type of 'scalar' does not need to be the same type as the components in 'vector'. 879 // The type of the created vector is a vector of components of the same type as the scalar. 880 // 881 // Note: One of the arguments will change, with the result coming back that way rather than 882 // through the return value. 883 void promoteScalar(Decoration precision, Id& left, Id& right); 884 885 // Make a value by smearing the scalar to fill the type. 886 // vectorType should be the correct type for making a vector of scalarVal. 887 // (No conversions are done.) 888 Id smearScalar(Decoration precision, Id scalarVal, Id vectorType); 889 890 // Create a call to a built-in function. 891 Id createBuiltinCall(Id resultType, Id builtins, int entryPoint, const std::vector<Id>& args); 892 893 // List of parameters used to create a texture operation 894 struct TextureParameters { 895 Id sampler; 896 Id coords; 897 Id bias; 898 Id lod; 899 Id Dref; 900 Id offset; 901 Id offsets; 902 Id gradX; 903 Id gradY; 904 Id sample; 905 Id component; 906 Id texelOut; 907 Id lodClamp; 908 Id granularity; 909 Id coarse; 910 Id gatherMode; 911 bool nonprivate; 912 bool volatil; 913 bool nontemporal; 914 }; 915 916 // Select the correct texture operation based on all inputs, and emit the correct instruction 917 Id createTextureCall(Decoration precision, Id resultType, bool sparse, bool fetch, bool proj, bool gather, 918 bool noImplicit, const TextureParameters&, ImageOperandsMask); 919 920 // Emit the OpTextureQuery* instruction that was passed in. 921 // Figure out the right return value and type, and return it. 922 Id createTextureQueryCall(Op, const TextureParameters&, bool isUnsignedResult); 923 924 Id createSamplePositionCall(Decoration precision, Id, Id); 925 926 Id createBitFieldExtractCall(Decoration precision, Id, Id, Id, bool isSigned); 927 Id createBitFieldInsertCall(Decoration precision, Id, Id, Id, Id); 928 929 // Reduction comparison for composites: For equal and not-equal resulting in a scalar. 930 Id createCompositeCompare(Decoration precision, Id, Id, bool /* true if for equal, false if for not-equal */); 931 932 // OpCompositeConstruct 933 Id createCompositeConstruct(Id typeId, const std::vector<Id>& constituents); 934 935 // vector or scalar constructor 936 Id createConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId); 937 938 // matrix constructor 939 Id createMatrixConstructor(Decoration precision, const std::vector<Id>& sources, Id constructee); 940 941 // coopmat conversion 942 Id createCooperativeMatrixConversion(Id typeId, Id source); 943 Id createCooperativeMatrixReduce(Op opcode, Id typeId, Id source, unsigned int mask, Id func); 944 Id createCooperativeMatrixPerElementOp(Id typeId, const std::vector<Id>& operands); 945 946 // Helper to use for building nested control flow with if-then-else. 947 class If { 948 public: 949 If(Id condition, SelectionControlMask ctrl, Builder& builder); 950 ~If() {} 951 952 void makeBeginElse(); 953 void makeEndIf(); 954 955 private: 956 If(const If&); 957 If& operator=(If&); 958 959 Builder& builder; 960 Id condition; 961 SelectionControlMask control; 962 Function* function; 963 Block* headerBlock; 964 Block* thenBlock; 965 Block* elseBlock; 966 Block* mergeBlock; 967 }; 968 969 // Make a switch statement. A switch has 'numSegments' of pieces of code, not containing 970 // any case/default labels, all separated by one or more case/default labels. Each possible 971 // case value v is a jump to the caseValues[v] segment. The defaultSegment is also in this 972 // number space. How to compute the value is given by 'condition', as in switch(condition). 973 // 974 // The SPIR-V Builder will maintain the stack of post-switch merge blocks for nested switches. 975 // 976 // Use a defaultSegment < 0 if there is no default segment (to branch to post switch). 977 // 978 // Returns the right set of basic blocks to start each code segment with, so that the caller's 979 // recursion stack can hold the memory for it. 980 // 981 void makeSwitch(Id condition, SelectionControlMask control, int numSegments, const std::vector<int>& caseValues, 982 const std::vector<int>& valueToSegment, int defaultSegment, std::vector<Block*>& segmentBB); 983 984 // Add a branch to the innermost switch's merge block. 985 void addSwitchBreak(bool implicit); 986 987 // Move to the next code segment, passing in the return argument in makeSwitch() 988 void nextSwitchSegment(std::vector<Block*>& segmentBB, int segment); 989 990 // Finish off the innermost switch. 991 void endSwitch(std::vector<Block*>& segmentBB); 992 993 struct LoopBlocks { 994 LoopBlocks(Block& head, Block& body, Block& merge, Block& continue_target) : 995 head(head), body(body), merge(merge), continue_target(continue_target) { } 996 Block &head, &body, &merge, &continue_target; 997 private: 998 LoopBlocks(); 999 LoopBlocks& operator=(const LoopBlocks&) = delete; 1000 }; 1001 1002 // Start a new loop and prepare the builder to generate code for it. Until 1003 // closeLoop() is called for this loop, createLoopContinue() and 1004 // createLoopExit() will target its corresponding blocks. 1005 LoopBlocks& makeNewLoop(); 1006 1007 // Create a new block in the function containing the build point. Memory is 1008 // owned by the function object. 1009 Block& makeNewBlock(); 1010 1011 // Add a branch to the continue_target of the current (innermost) loop. 1012 void createLoopContinue(); 1013 1014 // Add an exit (e.g. "break") from the innermost loop that we're currently 1015 // in. 1016 void createLoopExit(); 1017 1018 // Close the innermost loop that you're in 1019 void closeLoop(); 1020 1021 // 1022 // Access chain design for an R-Value vs. L-Value: 1023 // 1024 // There is a single access chain the builder is building at 1025 // any particular time. Such a chain can be used to either to a load or 1026 // a store, when desired. 1027 // 1028 // Expressions can be r-values, l-values, or both, or only r-values: 1029 // a[b.c].d = .... // l-value 1030 // ... = a[b.c].d; // r-value, that also looks like an l-value 1031 // ++a[b.c].d; // r-value and l-value 1032 // (x + y)[2]; // r-value only, can't possibly be l-value 1033 // 1034 // Computing an r-value means generating code. Hence, 1035 // r-values should only be computed when they are needed, not speculatively. 1036 // 1037 // Computing an l-value means saving away information for later use in the compiler, 1038 // no code is generated until the l-value is later dereferenced. It is okay 1039 // to speculatively generate an l-value, just not okay to speculatively dereference it. 1040 // 1041 // The base of the access chain (the left-most variable or expression 1042 // from which everything is based) can be set either as an l-value 1043 // or as an r-value. Most efficient would be to set an l-value if one 1044 // is available. If an expression was evaluated, the resulting r-value 1045 // can be set as the chain base. 1046 // 1047 // The users of this single access chain can save and restore if they 1048 // want to nest or manage multiple chains. 1049 // 1050 1051 struct AccessChain { 1052 Id base; // for l-values, pointer to the base object, for r-values, the base object 1053 std::vector<Id> indexChain; 1054 Id instr; // cache the instruction that generates this access chain 1055 std::vector<unsigned> swizzle; // each std::vector element selects the next GLSL component number 1056 Id component; // a dynamic component index, can coexist with a swizzle, 1057 // done after the swizzle, NoResult if not present 1058 Id preSwizzleBaseType; // dereferenced type, before swizzle or component is applied; 1059 // NoType unless a swizzle or component is present 1060 bool isRValue; // true if 'base' is an r-value, otherwise, base is an l-value 1061 unsigned int alignment; // bitwise OR of alignment values passed in. Accumulates worst alignment. 1062 // Only tracks base and (optional) component selection alignment. 1063 1064 struct DescHeapInfo { 1065 Id descHeapBaseTy; // for descriptor heap, record its base data type. 1066 Id descHeapBaseOffset; // byte offset applied to the heap base before descriptor lookup. 1067 std::vector<Id> descHeapIndexChain; 1068 Id descTy; // for target resource type 1069 StorageClass descStorageClass; // for descriptor heap, record its basic storage class. 1070 bool descReadonly; // for decorating OpBufferPointerEXT results. 1071 bool descWriteonly; // for decorating OpBufferPointerEXT results. 1072 std::vector<Instruction*> descHeapInstId; 1073 // for descriptor heap, record its data type for loading/store results. 1074 }; 1075 DescHeapInfo descHeapInfo; 1076 1077 // Accumulate whether anything in the chain of structures has coherent decorations. 1078 struct CoherentFlags { 1079 CoherentFlags() { clear(); } 1080 bool isVolatile() const { return volatil; } 1081 bool isNonUniform() const { return nonUniform; } 1082 bool anyCoherent() const { 1083 return coherent || devicecoherent || queuefamilycoherent || workgroupcoherent || 1084 subgroupcoherent || shadercallcoherent; 1085 } 1086 1087 unsigned coherent : 1; 1088 unsigned devicecoherent : 1; 1089 unsigned queuefamilycoherent : 1; 1090 unsigned workgroupcoherent : 1; 1091 unsigned subgroupcoherent : 1; 1092 unsigned shadercallcoherent : 1; 1093 unsigned nonprivate : 1; 1094 unsigned volatil : 1; 1095 unsigned nontemporal : 1; 1096 unsigned isImage : 1; 1097 unsigned nonUniform : 1; 1098 1099 void clear() { 1100 coherent = 0; 1101 devicecoherent = 0; 1102 queuefamilycoherent = 0; 1103 workgroupcoherent = 0; 1104 subgroupcoherent = 0; 1105 shadercallcoherent = 0; 1106 nonprivate = 0; 1107 volatil = 0; 1108 nontemporal = 0; 1109 isImage = 0; 1110 nonUniform = 0; 1111 } 1112 1113 CoherentFlags operator |=(const CoherentFlags &other) { 1114 coherent |= other.coherent; 1115 devicecoherent |= other.devicecoherent; 1116 queuefamilycoherent |= other.queuefamilycoherent; 1117 workgroupcoherent |= other.workgroupcoherent; 1118 subgroupcoherent |= other.subgroupcoherent; 1119 shadercallcoherent |= other.shadercallcoherent; 1120 nonprivate |= other.nonprivate; 1121 volatil |= other.volatil; 1122 nontemporal = other.nontemporal; 1123 isImage |= other.isImage; 1124 nonUniform |= other.nonUniform; 1125 return *this; 1126 } 1127 }; 1128 CoherentFlags coherentFlags; 1129 }; 1130 1131 // 1132 // the SPIR-V builder maintains a single active chain that 1133 // the following methods operate on 1134 // 1135 1136 // for external save and restore 1137 AccessChain getAccessChain() { return accessChain; } 1138 void setAccessChain(AccessChain newChain) { accessChain = newChain; } 1139 1140 // for EXT_descriptor_heap and EXT_structured_descriptor_heap 1141 Id getAccessChainDescHeapBaseType() const { return accessChain.descHeapInfo.descHeapBaseTy; } 1142 void setAccessChainDescHeapBaseType(Id baseType) { accessChain.descHeapInfo.descHeapBaseTy = baseType; } 1143 void setAccessChainDescHeapBaseOffset(Id baseOffset) { accessChain.descHeapInfo.descHeapBaseOffset = baseOffset; } 1144 const std::vector<Id>& getAccessChainDescHeapIndexChain() const { return accessChain.descHeapInfo.descHeapIndexChain; } 1145 void accessChainPushDescHeapIndex(Id index) { accessChain.descHeapInfo.descHeapIndexChain.push_back(index); } 1146 bool hasAccessChainIndex() const { return !accessChain.indexChain.empty(); } 1147 void moveAccessChainIndexToDescHeapIndexChain() 1148 { 1149 assert(accessChain.indexChain.size() == 1); 1150 accessChainPushDescHeapIndex(accessChain.indexChain.back()); 1151 accessChain.indexChain.pop_back(); 1152 } 1153 void setAccessChainDescHeapDescriptorType(Id descTy, StorageClass storageClass, bool readonly, bool writeonly) 1154 { 1155 accessChain.descHeapInfo.descTy = descTy; 1156 accessChain.descHeapInfo.descStorageClass = storageClass; 1157 accessChain.descHeapInfo.descReadonly = readonly; 1158 accessChain.descHeapInfo.descWriteonly = writeonly; 1159 } 1160 1161 // clear accessChain 1162 void clearAccessChain(); 1163 1164 Id createDescHeapAccessChain(); 1165 Id createConstantSizeOfEXT(Id typeId); 1166 1167 // set new base as an l-value base 1168 void setAccessChainLValue(Id lValue) 1169 { 1170 assert(isPointer(lValue) || isUntypedPointer(lValue)); 1171 accessChain.base = lValue; 1172 } 1173 1174 // set new base value as an r-value 1175 void setAccessChainRValue(Id rValue) 1176 { 1177 accessChain.isRValue = true; 1178 accessChain.base = rValue; 1179 } 1180 1181 // push offset onto the end of the chain 1182 void accessChainPush(Id offset, AccessChain::CoherentFlags coherentFlags, unsigned int alignment) 1183 { 1184 accessChain.indexChain.push_back(offset); 1185 accessChain.coherentFlags |= coherentFlags; 1186 accessChain.alignment |= alignment; 1187 } 1188 1189 // push new swizzle onto the end of any existing swizzle, merging into a single swizzle 1190 void accessChainPushSwizzle(std::vector<unsigned>& swizzle, Id preSwizzleBaseType, 1191 AccessChain::CoherentFlags coherentFlags, unsigned int alignment); 1192 1193 // push a dynamic component selection onto the access chain, only applicable with a 1194 // non-trivial swizzle or no swizzle 1195 void accessChainPushComponent(Id component, Id preSwizzleBaseType, AccessChain::CoherentFlags coherentFlags, 1196 unsigned int alignment) 1197 { 1198 if (accessChain.swizzle.size() != 1) { 1199 accessChain.component = component; 1200 if (accessChain.preSwizzleBaseType == NoType) 1201 accessChain.preSwizzleBaseType = preSwizzleBaseType; 1202 } 1203 accessChain.coherentFlags |= coherentFlags; 1204 accessChain.alignment |= alignment; 1205 } 1206 1207 // use accessChain and swizzle to store value 1208 void accessChainStore(Id rvalue, Decoration nonUniform, 1209 spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMask::MaskNone, 1210 spv::Scope scope = spv::Scope::Max, unsigned int alignment = 0); 1211 1212 // use accessChain and swizzle to load an r-value 1213 Id accessChainLoad(Decoration precision, Decoration l_nonUniform, Decoration r_nonUniform, Id ResultType, 1214 spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMask::MaskNone, spv::Scope scope = spv::Scope::Max, 1215 unsigned int alignment = 0); 1216 1217 // Return whether or not the access chain can be represented in SPIR-V 1218 // as an l-value. 1219 // E.g., a[3].yx cannot be, while a[3].y and a[3].y[x] can be. 1220 bool isSpvLvalue() const { return accessChain.swizzle.size() <= 1; } 1221 1222 // get the direct pointer for an l-value 1223 Id accessChainGetLValue(); 1224 1225 // Get the inferred SPIR-V type of the result of the current access chain, 1226 // based on the type of the base and the chain of dereferences. 1227 Id accessChainGetInferredType(); 1228 1229 // Add capabilities, extensions, remove unneeded decorations, etc., 1230 // based on the resulting SPIR-V. 1231 void postProcess(bool compileOnly); 1232 1233 // Prune unreachable blocks in the CFG and remove unneeded decorations. 1234 void postProcessCFG(); 1235 1236 // Add capabilities, extensions based on instructions in the module. 1237 void postProcessFeatures(); 1238 // Hook to visit each instruction in a block in a function 1239 void postProcess(Instruction&); 1240 // Hook to visit each non-32-bit sized float/int operation in a block. 1241 void postProcessType(const Instruction&, spv::Id typeId); 1242 // move OpSampledImage instructions to be next to their users. 1243 void postProcessSamplers(); 1244 1245 void dump(std::vector<unsigned int>&) const; 1246 1247 // Add a branch to the target block. 1248 // If set implicit, the branch instruction shouldn't have debug source location. 1249 void createBranch(bool implicit, Block* block); 1250 void createConditionalBranch(Id condition, Block* thenBlock, Block* elseBlock); 1251 void createLoopMerge(Block* mergeBlock, Block* continueBlock, LoopControlMask control, 1252 const std::vector<unsigned int>& operands); 1253 1254 // Sets to generate opcode for specialization constants. 1255 void setToSpecConstCodeGenMode() { generatingOpCodeForSpecConst = true; } 1256 // Sets to generate opcode for non-specialization constants (normal mode). 1257 void setToNormalCodeGenMode() { generatingOpCodeForSpecConst = false; } 1258 // Check if the builder is generating code for spec constants. 1259 bool isInSpecConstCodeGenMode() { return generatingOpCodeForSpecConst; } 1260 1261 void setUseReplicatedComposites(bool use) { useReplicatedComposites = use; } 1262 1263private: 1264 // Helper to get size of a scalar (in bytes) 1265 unsigned int postProcessGetLargestScalarSize(const Instruction& type); 1266 1267protected: 1268 Id findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned value); 1269 Id findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned v1, unsigned v2); 1270 Id findCompositeConstant(Op typeClass, Op opcode, Id typeId, const std::vector<Id>& comps, size_t numMembers); 1271 Id findStructConstant(Id typeId, const std::vector<Id>& comps, size_t numMembers); 1272 Id collapseAccessChain(); 1273 Id getOrCreateDescHeapByteArrayType(); 1274 void remapDynamicSwizzle(); 1275 void transferAccessChainSwizzle(bool dynamic); 1276 void simplifyAccessChainSwizzle(); 1277 void createAndSetNoPredecessorBlock(const char*); 1278 void createSelectionMerge(Block* mergeBlock, SelectionControlMask control); 1279 void dumpSourceInstructions(std::vector<unsigned int>&) const; 1280 void dumpSourceInstructions(const spv::Id fileId, const std::string& text, std::vector<unsigned int>&) const; 1281 template <class Range> void dumpInstructions(std::vector<unsigned int>& out, const Range& instructions) const; 1282 void dumpModuleProcesses(std::vector<unsigned int>&) const; 1283 spv::MemoryAccessMask sanitizeMemoryAccessForStorageClass(spv::MemoryAccessMask memoryAccess, StorageClass sc) 1284 const; 1285 struct DecorationInstructionLessThan { 1286 bool operator()(const std::unique_ptr<Instruction>& lhs, const std::unique_ptr<Instruction>& rhs) const; 1287 }; 1288 template <typename SpvUtilsType> 1289 Id makeFloatConstantHelper(float f, Id typeId, bool specConstant); 1290 1291 unsigned int spvVersion; // the version of SPIR-V to emit in the header 1292 SourceLanguage sourceLang; 1293 int sourceVersion; 1294 spv::Id nonSemanticShaderCompilationUnitId {0}; 1295 spv::Id nonSemanticShaderDebugInfo {0}; 1296 // Pointer to the OpExtInstImport instruction for NonSemantic.Shader.DebugInfo. 1297 // Kept so requireNonSemanticShaderDebugInfoVersion() can patch the name in place. 1298 Instruction* nonSemanticShaderDebugInfoImportInst {nullptr}; 1299 // Spec version encoded in the NonSemantic.Shader.DebugInfo import name. 1300 // Defaults to 100. Promoted to N the first time a version-N opcode is emitted. 1301 unsigned int nonSemanticShaderDebugInfoVersion{100}; 1302 spv::Id debugInfoNone {0}; 1303 spv::Id debugExpression {0}; // Debug expression with zero operations. 1304 std::string sourceText; 1305 1306 // True if an new OpLine/OpDebugLine may need to be inserted. Either: 1307 // 1. The current debug location changed 1308 // 2. The current build point changed 1309 bool dirtyLineTracker; 1310 int currentLine = 0; 1311 // OpString id of the current file name. Always 0 if debug info is off. 1312 spv::Id currentFileId = 0; 1313 // OpString id of the main file name. Always 0 if debug info is off. 1314 spv::Id mainFileId = 0; 1315 1316 // True if an new OpDebugScope may need to be inserted. Either: 1317 // 1. A new lexical block is pushed 1318 // 2. The current build point changed 1319 bool dirtyScopeTracker; 1320 std::stack<spv::Id> currentDebugScopeId; 1321 1322 // This flag toggles tracking of debug info while building the SPIR-V. 1323 bool trackDebugInfo = false; 1324 // This flag toggles emission of SPIR-V debug instructions, like OpLine and OpSource. 1325 bool emitSpirvDebugInfo = false; 1326 // This flag toggles emission of Non-Semantic Debug extension debug instructions. 1327 bool emitNonSemanticShaderDebugInfo = false; 1328 bool restoreNonSemanticShaderDebugInfo = false; 1329 bool emitNonSemanticShaderDebugSource = false; 1330 1331 std::set<std::string> extensions; 1332 std::vector<const char*> sourceExtensions; 1333 std::vector<const char*> moduleProcesses; 1334 AddressingModel addressModel; 1335 MemoryModel memoryModel; 1336 std::set<spv::Capability> capabilities; 1337 int builderNumber; 1338 Module module; 1339 Block* buildPoint; 1340 Id uniqueId; 1341 Function* entryPointFunction; 1342 // This tracks the current function being built, or nullptr if not in a function. 1343 Function const* currentFunction { nullptr }; 1344 bool generatingOpCodeForSpecConst; 1345 bool useReplicatedComposites { false }; 1346 AccessChain accessChain; 1347 1348 // special blocks of instructions for output 1349 std::vector<std::unique_ptr<Instruction> > strings; 1350 std::vector<std::unique_ptr<Instruction> > imports; 1351 std::vector<std::unique_ptr<Instruction> > entryPoints; 1352 std::vector<std::unique_ptr<Instruction> > executionModes; 1353 std::vector<std::unique_ptr<Instruction> > names; 1354 std::set<std::unique_ptr<Instruction>, DecorationInstructionLessThan> decorations; 1355 std::vector<std::unique_ptr<Instruction> > constantsTypesGlobals; 1356 std::vector<std::unique_ptr<Instruction> > externals; 1357 std::vector<std::unique_ptr<Function> > functions; 1358 1359 // not output, internally used for quick & dirty canonical (unique) creation 1360 1361 // Key for scalar constants (handles both 32-bit and 64-bit) 1362 struct ScalarConstantKey { 1363 unsigned int typeClass; // OpTypeInt, OpTypeFloat, OpTypeBool 1364 unsigned int opcode; // OpConstant, OpSpecConstant, OpConstantTrue, etc. 1365 Id typeId; // The specific type 1366 unsigned value1; // First operand (or only operand) 1367 unsigned value2; // Second operand (0 for single-operand constants) 1368 1369 bool operator==(const ScalarConstantKey& other) const { 1370 return typeClass == other.typeClass && 1371 opcode == other.opcode && 1372 typeId == other.typeId && 1373 value1 == other.value1 && 1374 value2 == other.value2; 1375 } 1376 }; 1377 1378 struct ScalarConstantKeyHash { 1379 // 64/32 bit mix function from MurmurHash3 1380 inline std::size_t hash_mix(std::size_t h) const { 1381 if constexpr (sizeof(std::size_t) == 8) { 1382 h ^= h >> 33; 1383 h *= UINT64_C(0xff51afd7ed558ccd); 1384 h ^= h >> 33; 1385 h *= UINT64_C(0xc4ceb9fe1a85ec53); 1386 h ^= h >> 33; 1387 return h; 1388 } else { 1389 h ^= h >> 16; 1390 h *= UINT32_C(0x85ebca6b); 1391 h ^= h >> 13; 1392 h *= UINT32_C(0xc2b2ae35); 1393 h ^= h >> 16; 1394 return h; 1395 } 1396 } 1397 1398 // Hash combine from boost 1399 inline std::size_t hash_combine(std::size_t seed, std::size_t v) const { 1400 return hash_mix(seed + 0x9e3779b9 + v); 1401 } 1402 1403 std::size_t operator()(const ScalarConstantKey& k) const { 1404 size_t hash1 = hash_combine(std::hash<unsigned>{}(k.typeClass), std::hash<unsigned>{}(k.opcode)); 1405 size_t hash2 = hash_combine(std::hash<Id>{}(k.value1), std::hash<unsigned>{}(k.value2)); 1406 size_t hash3 = hash_combine(hash1, hash2); 1407 return hash_combine(hash3, std::hash<unsigned>{}(k.typeId)); 1408 } 1409 }; 1410 1411 typedef std::unordered_set< 1412 CompositeConstantKey, 1413 CompositeConstantKey::Hash, 1414 CompositeConstantKey::Equal> CompositeConstantCache; 1415 1416 typedef std::unordered_set< 1417 StructConstantKey, 1418 StructConstantKey::Hash, 1419 StructConstantKey::Equal> StructConstantCache; 1420 1421 // map type opcodes to constant inst. 1422 CompositeConstantCache groupedCompositeConstants; 1423 // map struct-id to constant instructions 1424 StructConstantCache groupedStructConstants; 1425 // map type opcodes to type instructions 1426 std::unordered_map<unsigned int, std::vector<Instruction*>> groupedTypes; 1427 // map type opcodes to debug type instructions 1428 std::unordered_map<unsigned int, std::vector<Instruction*>> groupedDebugTypes; 1429 // list of OpConstantNull instructions 1430 std::vector<Instruction*> nullConstants; 1431 // map scalar constants to result IDs 1432 std::unordered_map<ScalarConstantKey, Id, ScalarConstantKeyHash> groupedScalarConstantResultIDs; 1433 // map type ids to OpConstantSizeOfEXT result IDs 1434 std::unordered_map<Id, Id> constantSizeOfEXTIds; 1435 1436 // Descriptor heap shifted base cache. 1437 std::map<std::pair<Id, Id>, Id> descHeapShiftedBaseCache; 1438 1439 // Descriptor heap byte array type. 1440 Id descHeapByteArrayType; 1441 1442 // Track which types have explicit layouts, to avoid reusing in storage classes without layout. 1443 // Currently only tracks array types. 1444 std::unordered_set<unsigned int> explicitlyLaidOut; 1445 1446 // stack of switches 1447 std::stack<Block*> switchMerges; 1448 1449 // Our loop stack. 1450 std::stack<LoopBlocks> loops; 1451 1452 // map from strings to their string ids 1453 std::unordered_map<std::string, spv::Id> stringIds; 1454 1455 // map from include file name ids to their contents 1456 std::map<spv::Id, const std::string*> includeFiles; 1457 1458 // maps from OpTypeXXX id to DebugTypeXXX id 1459 std::unordered_map<spv::Id, spv::Id> debugTypeIdLookup; 1460 1461 // maps from OpFunction id to DebugFunction id 1462 std::unordered_map<spv::Id, spv::Id> debugFuncIdLookup; 1463 1464 // map from file name string id to DebugSource id 1465 std::unordered_map<spv::Id, spv::Id> debugSourceId; 1466 1467 // The stream for outputting warnings and errors. 1468 SpvBuildLogger* logger; 1469}; // end Builder class 1470 1471} // end spv namespace 1472 1473#endif // SpvBuilder_H