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