yum-mirror/glslang
git clone https://git.yummers.dev/yum-mirror/glslang
08f27157
vulkan-sdk-1.4.350.0
1// 2// Copyright (C) 2014-2015 LunarG, Inc. 3// Copyright (C) 2015-2018 Google, Inc. 4// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved. 5// 6// All rights reserved. 7// 8// Redistribution and use in source and binary forms, with or without 9// modification, are permitted provided that the following conditions 10// are met: 11// 12// Redistributions of source code must retain the above copyright 13// notice, this list of conditions and the following disclaimer. 14// 15// Redistributions in binary form must reproduce the above 16// copyright notice, this list of conditions and the following 17// disclaimer in the documentation and/or other materials provided 18// with the distribution. 19// 20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its 21// contributors may be used to endorse or promote products derived 22// from this software without specific prior written permission. 23// 24// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 35// POSSIBILITY OF SUCH DAMAGE. 36 37// 38// Helper for making SPIR-V IR. Generally, this is documented in the header 39// SpvBuilder.h. 40// 41 42#include <cassert> 43#include <cstdlib> 44 45#include <unordered_set> 46#include <algorithm> 47 48#include "SpvBuilder.h" 49#include "spvUtil.h" 50#include "hex_float.h" 51 52#ifndef _WIN32 53#include <cstdio> 54#endif 55 56namespace spv { 57 58Builder :: Builder ( unsigned int spvVersion , unsigned int magicNumber , SpvBuildLogger * buildLogger ) : 59spvVersion ( spvVersion ) , 60sourceLang ( SourceLanguage :: Unknown ) , 61sourceVersion ( 0 ) , 62addressModel ( AddressingModel :: Logical ) , 63memoryModel ( MemoryModel :: GLSL450 ) , 64builderNumber ( magicNumber ) , 65buildPoint ( nullptr ) , 66uniqueId ( 0 ) , 67entryPointFunction ( nullptr ) , 68generatingOpCodeForSpecConst ( false ) , 69logger ( buildLogger ) 70{ 71clearAccessChain () ; 72} 73 74Builder ::~ Builder () 75{ 76} 77 78Id Builder :: import ( const char * name ) 79{ 80Instruction * import = new Instruction ( getUniqueId () , NoType , Op :: OpExtInstImport ) ; 81import -> addStringOperand ( name ) ; 82module . mapInstruction ( import ) ; 83 84imports . push_back ( std :: unique_ptr < Instruction > ( import )) ; 85return import -> getResultId () ; 86} 87 88// For creating new groupedTypes (will return old type if the requested one was already made). 89Id Builder :: makeVoidType () 90{ 91Instruction * type ; 92if ( groupedTypes [ enumCast ( Op :: OpTypeVoid )] . size () == 0 ) { 93Id typeId = getUniqueId () ; 94type = new Instruction ( typeId , NoType , Op :: OpTypeVoid ) ; 95groupedTypes [ enumCast ( Op :: OpTypeVoid )] . push_back ( type ) ; 96constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 97module . mapInstruction ( type ) ; 98// Core OpTypeVoid used for debug void type 99if ( emitNonSemanticShaderDebugInfo ) 100debugTypeIdLookup [ typeId ] = typeId ; 101} else 102type = groupedTypes [ enumCast ( Op :: OpTypeVoid )] . back () ; 103 104return type -> getResultId () ; 105} 106 107Id Builder :: makeBoolType () 108{ 109Instruction * type ; 110if ( groupedTypes [ enumCast ( Op :: OpTypeBool )] . size () == 0 ) { 111type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeBool ) ; 112groupedTypes [ enumCast ( Op :: OpTypeBool )] . push_back ( type ) ; 113constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 114module . mapInstruction ( type ) ; 115 116if ( emitNonSemanticShaderDebugInfo ) { 117auto const debugResultId = makeBoolDebugType ( 32 ) ; 118debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 119} 120 121} else 122type = groupedTypes [ enumCast ( Op :: OpTypeBool )] . back () ; 123 124 125return type -> getResultId () ; 126} 127 128Id Builder :: makeSamplerType ( const char * debugName ) 129{ 130Instruction * type ; 131if ( groupedTypes [ enumCast ( Op :: OpTypeSampler )] . size () == 0 ) { 132type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeSampler ) ; 133groupedTypes [ enumCast ( Op :: OpTypeSampler )] . push_back ( type ) ; 134constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 135module . mapInstruction ( type ) ; 136} else 137type = groupedTypes [ enumCast ( Op :: OpTypeSampler )] . back () ; 138 139if ( emitNonSemanticShaderDebugInfo ) 140{ 141auto const debugResultId = makeOpaqueDebugType ( debugName ) ; 142debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 143} 144 145return type -> getResultId () ; 146} 147 148Id Builder :: makePointer ( StorageClass storageClass , Id pointee ) 149{ 150// try to find it 151Instruction * type ; 152for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypePointer )] . size () ; ++ t ) { 153type = groupedTypes [ enumCast ( Op :: OpTypePointer )][ t ] ; 154if ( type -> getImmediateOperand ( 0 ) == ( unsigned ) storageClass && 155type -> getIdOperand ( 1 ) == pointee ) 156return type -> getResultId () ; 157} 158 159// not found, make it 160type = new Instruction ( getUniqueId () , NoType , Op :: OpTypePointer ) ; 161type -> reserveOperands ( 2 ) ; 162type -> addImmediateOperand ( storageClass ) ; 163type -> addIdOperand ( pointee ) ; 164groupedTypes [ enumCast ( Op :: OpTypePointer )] . push_back ( type ) ; 165constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 166module . mapInstruction ( type ) ; 167 168if ( emitNonSemanticShaderDebugInfo ) { 169const Id debugResultId = makePointerDebugType ( storageClass , pointee ) ; 170debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 171} 172 173return type -> getResultId () ; 174} 175 176Id Builder :: makeForwardPointer ( StorageClass storageClass ) 177{ 178// Caching/uniquifying doesn't work here, because we don't know the 179// pointee type and there can be multiple forward pointers of the same 180// storage type. Somebody higher up in the stack must keep track. 181Instruction * type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeForwardPointer ) ; 182type -> addImmediateOperand ( storageClass ) ; 183constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 184module . mapInstruction ( type ) ; 185 186if ( emitNonSemanticShaderDebugInfo ) { 187const Id debugResultId = makeForwardPointerDebugType ( storageClass ) ; 188debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 189} 190return type -> getResultId () ; 191} 192 193Id Builder :: makeUntypedPointer ( StorageClass storageClass , bool setBufferPointer ) 194{ 195// try to find it 196Instruction * type ; 197// both typeBufferEXT and UntypedPointer only contains storage class info. 198spv :: Op typeOp = setBufferPointer ? Op :: OpTypeBufferEXT : Op :: OpTypeUntypedPointerKHR ; 199for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( typeOp )] . size () ; ++ t ) { 200type = groupedTypes [ enumCast ( typeOp )][ t ] ; 201if ( type -> getImmediateOperand ( 0 ) == ( unsigned ) storageClass ) 202return type -> getResultId () ; 203} 204 205// not found, make it 206type = new Instruction ( getUniqueId () , NoType , typeOp ) ; 207type -> addImmediateOperand ( storageClass ) ; 208groupedTypes [ enumCast ( typeOp )] . push_back ( type ) ; 209constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 210module . mapInstruction ( type ) ; 211return type -> getResultId () ; 212} 213 214Id Builder :: makePointerFromForwardPointer ( StorageClass storageClass , Id forwardPointerType , Id pointee ) 215{ 216// try to find it 217Instruction * type ; 218for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypePointer )] . size () ; ++ t ) { 219type = groupedTypes [ enumCast ( Op :: OpTypePointer )][ t ] ; 220if ( type -> getImmediateOperand ( 0 ) == ( unsigned ) storageClass && 221type -> getIdOperand ( 1 ) == pointee ) 222return type -> getResultId () ; 223} 224 225type = new Instruction ( forwardPointerType , NoType , Op :: OpTypePointer ) ; 226type -> reserveOperands ( 2 ) ; 227type -> addImmediateOperand ( storageClass ) ; 228type -> addIdOperand ( pointee ) ; 229groupedTypes [ enumCast ( Op :: OpTypePointer )] . push_back ( type ) ; 230constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 231module . mapInstruction ( type ) ; 232 233// If we are emitting nonsemantic debuginfo, we need to patch the debug pointer type 234// that was emitted alongside the forward pointer, now that we have a pointee debug 235// type for it to point to. 236if ( emitNonSemanticShaderDebugInfo ) { 237Instruction * debugForwardPointer = module . getInstruction ( getDebugType ( forwardPointerType )) ; 238assert ( getDebugType ( pointee )) ; 239debugForwardPointer -> setIdOperand ( 2 , getDebugType ( pointee )) ; 240} 241 242return type -> getResultId () ; 243} 244 245Id Builder :: makeIntegerType ( int width , bool hasSign ) 246{ 247// try to find it 248Instruction * type ; 249for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeInt )] . size () ; ++ t ) { 250type = groupedTypes [ enumCast ( Op :: OpTypeInt )][ t ] ; 251if ( type -> getImmediateOperand ( 0 ) == ( unsigned ) width && 252type -> getImmediateOperand ( 1 ) == ( hasSign ? 1u : 0u )) 253return type -> getResultId () ; 254} 255 256// not found, make it 257type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeInt ) ; 258type -> reserveOperands ( 2 ) ; 259type -> addImmediateOperand ( width ) ; 260type -> addImmediateOperand ( hasSign ? 1 : 0 ) ; 261groupedTypes [ enumCast ( Op :: OpTypeInt )] . push_back ( type ) ; 262constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 263module . mapInstruction ( type ) ; 264 265// deal with capabilities 266switch ( width ) { 267case 8 : 268case 16 : 269// these are currently handled by storage-type declarations and post processing 270break ; 271case 64 : 272addCapability ( Capability :: Int64 ) ; 273break ; 274default : 275break ; 276} 277 278if ( emitNonSemanticShaderDebugInfo ) 279{ 280auto const debugResultId = makeIntegerDebugType ( width , hasSign ) ; 281debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 282} 283 284return type -> getResultId () ; 285} 286 287Id Builder :: makeFloatType ( int width ) 288{ 289// try to find it 290Instruction * type ; 291for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeFloat )] . size () ; ++ t ) { 292type = groupedTypes [ enumCast ( Op :: OpTypeFloat )][ t ] ; 293if ( type -> getNumOperands () != 1 ) { 294continue ; 295} 296if ( type -> getImmediateOperand ( 0 ) == ( unsigned ) width ) 297return type -> getResultId () ; 298} 299 300// not found, make it 301type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeFloat ) ; 302type -> addImmediateOperand ( width ) ; 303groupedTypes [ enumCast ( Op :: OpTypeFloat )] . push_back ( type ) ; 304constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 305module . mapInstruction ( type ) ; 306 307// deal with capabilities 308switch ( width ) { 309case 16 : 310// currently handled by storage-type declarations and post processing 311break ; 312case 64 : 313addCapability ( Capability :: Float64 ) ; 314break ; 315default : 316break ; 317} 318 319if ( emitNonSemanticShaderDebugInfo ) 320{ 321auto const debugResultId = makeFloatDebugType ( width ) ; 322debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 323} 324 325return type -> getResultId () ; 326} 327 328Id Builder :: makeBFloat16Type () 329{ 330// try to find it 331Instruction * type ; 332for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeFloat )] . size () ; ++ t ) { 333type = groupedTypes [ enumCast ( Op :: OpTypeFloat )][ t ] ; 334if ( type -> getNumOperands () != 2 ) { 335continue ; 336} 337if ( type -> getImmediateOperand ( 0 ) == ( unsigned ) 16 && 338type -> getImmediateOperand ( 1 ) == FPEncoding :: BFloat16KHR ) 339return type -> getResultId () ; 340} 341 342// not found, make it 343type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeFloat ) ; 344type -> addImmediateOperand ( 16 ) ; 345type -> addImmediateOperand ( FPEncoding :: BFloat16KHR ) ; 346groupedTypes [ enumCast ( Op :: OpTypeFloat )] . push_back ( type ) ; 347constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 348module . mapInstruction ( type ) ; 349 350addExtension ( spv :: E_SPV_KHR_bfloat16 ) ; 351addCapability ( Capability :: BFloat16TypeKHR ) ; 352 353if ( emitNonSemanticShaderDebugInfo ) { 354auto const debugResultId = makeFloatDebugType ( 16 , makeUintConstant (( unsigned ) FPEncoding :: BFloat16KHR )) ; 355debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 356} 357 358return type -> getResultId () ; 359} 360 361Id Builder :: makeFloatE5M2Type () 362{ 363// try to find it 364Instruction * type ; 365for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeFloat )] . size () ; ++ t ) { 366type = groupedTypes [ enumCast ( Op :: OpTypeFloat )][ t ] ; 367if ( type -> getNumOperands () != 2 ) { 368continue ; 369} 370if ( type -> getImmediateOperand ( 0 ) == ( unsigned ) 8 && 371type -> getImmediateOperand ( 1 ) == FPEncoding :: Float8E5M2EXT ) 372return type -> getResultId () ; 373} 374 375// not found, make it 376type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeFloat ) ; 377type -> addImmediateOperand ( 8 ) ; 378type -> addImmediateOperand ( FPEncoding :: Float8E5M2EXT ) ; 379groupedTypes [ enumCast ( Op :: OpTypeFloat )] . push_back ( type ) ; 380constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 381module . mapInstruction ( type ) ; 382 383addExtension ( spv :: E_SPV_EXT_float8 ) ; 384addCapability ( Capability :: Float8EXT ) ; 385 386if ( emitNonSemanticShaderDebugInfo ) { 387auto const debugResultId = makeFloatDebugType ( 8 , makeUintConstant (( unsigned ) FPEncoding :: Float8E5M2EXT )) ; 388debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 389} 390 391return type -> getResultId () ; 392} 393 394Id Builder :: makeFloatE4M3Type () 395{ 396// try to find it 397Instruction * type ; 398for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeFloat )] . size () ; ++ t ) { 399type = groupedTypes [ enumCast ( Op :: OpTypeFloat )][ t ] ; 400if ( type -> getNumOperands () != 2 ) { 401continue ; 402} 403if ( type -> getImmediateOperand ( 0 ) == ( unsigned ) 8 && 404type -> getImmediateOperand ( 1 ) == FPEncoding :: Float8E4M3EXT ) 405return type -> getResultId () ; 406} 407 408// not found, make it 409type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeFloat ) ; 410type -> addImmediateOperand ( 8 ) ; 411type -> addImmediateOperand ( FPEncoding :: Float8E4M3EXT ) ; 412groupedTypes [ enumCast ( Op :: OpTypeFloat )] . push_back ( type ) ; 413constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 414module . mapInstruction ( type ) ; 415 416addExtension ( spv :: E_SPV_EXT_float8 ) ; 417addCapability ( Capability :: Float8EXT ) ; 418 419if ( emitNonSemanticShaderDebugInfo ) { 420auto const debugResultId = makeFloatDebugType ( 8 , makeUintConstant (( unsigned ) FPEncoding :: Float8E4M3EXT )) ; 421debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 422} 423 424return type -> getResultId () ; 425} 426 427// Make a struct without checking for duplication. 428// See makeStructResultType() for non-decorated structs 429// needed as the result of some instructions, which does 430// check for duplicates. 431// For compiler-generated structs, debug info is ignored. 432Id Builder :: makeStructType ( const std :: vector < Id >& members , const std :: vector < spv :: StructMemberDebugInfo >& memberDebugInfo , 433const char * name , bool const compilerGenerated ) 434{ 435// Don't look for previous one, because in the general case, 436// structs can be duplicated except for decorations. 437 438// not found, make it 439Instruction * type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeStruct ) ; 440for ( int op = 0 ; op < ( int ) members . size () ; ++ op ) 441type -> addIdOperand ( members [ op ]) ; 442groupedTypes [ enumCast ( Op :: OpTypeStruct )] . push_back ( type ) ; 443constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 444module . mapInstruction ( type ) ; 445addName ( type -> getResultId () , name ) ; 446 447if ( emitNonSemanticShaderDebugInfo && ! compilerGenerated ) { 448assert ( members . size () == memberDebugInfo . size ()) ; 449auto const debugResultId = 450makeCompositeDebugType ( members , memberDebugInfo , name , NonSemanticShaderDebugInfoStructure ) ; 451debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 452} 453 454return type -> getResultId () ; 455} 456 457// Make a struct for the simple results of several instructions, 458// checking for duplication. 459Id Builder :: makeStructResultType ( Id type0 , Id type1 ) 460{ 461// try to find it 462Instruction * type ; 463for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeStruct )] . size () ; ++ t ) { 464type = groupedTypes [ enumCast ( Op :: OpTypeStruct )][ t ] ; 465if ( type -> getNumOperands () != 2 ) 466continue ; 467if ( type -> getIdOperand ( 0 ) != type0 || 468type -> getIdOperand ( 1 ) != type1 ) 469continue ; 470return type -> getResultId () ; 471} 472 473// not found, make it 474std :: vector < spv :: Id > members ; 475members . push_back ( type0 ) ; 476members . push_back ( type1 ) ; 477 478return makeStructType ( members , {} , "ResType" ) ; 479} 480 481Id Builder :: makeVectorType ( Id component , int size ) 482{ 483// try to find it 484Instruction * type ; 485for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeVector )] . size () ; ++ t ) { 486type = groupedTypes [ enumCast ( Op :: OpTypeVector )][ t ] ; 487if ( type -> getIdOperand ( 0 ) == component && 488type -> getImmediateOperand ( 1 ) == ( unsigned ) size ) 489return type -> getResultId () ; 490} 491 492// not found, make it 493type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeVector ) ; 494type -> reserveOperands ( 2 ) ; 495type -> addIdOperand ( component ) ; 496type -> addImmediateOperand ( size ) ; 497groupedTypes [ enumCast ( Op :: OpTypeVector )] . push_back ( type ) ; 498constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 499module . mapInstruction ( type ) ; 500 501if ( emitNonSemanticShaderDebugInfo ) 502{ 503auto const debugResultId = makeVectorDebugType ( component , size ) ; 504debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 505} 506 507return type -> getResultId () ; 508} 509 510Id Builder :: makeMatrixType ( Id component , int cols , int rows ) 511{ 512assert ( cols <= maxMatrixSize && rows <= maxMatrixSize ) ; 513 514Id column = makeVectorType ( component , rows ) ; 515 516// try to find it 517Instruction * type ; 518for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeMatrix )] . size () ; ++ t ) { 519type = groupedTypes [ enumCast ( Op :: OpTypeMatrix )][ t ] ; 520if ( type -> getIdOperand ( 0 ) == column && 521type -> getImmediateOperand ( 1 ) == ( unsigned ) cols ) 522return type -> getResultId () ; 523} 524 525// not found, make it 526type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeMatrix ) ; 527type -> reserveOperands ( 2 ) ; 528type -> addIdOperand ( column ) ; 529type -> addImmediateOperand ( cols ) ; 530groupedTypes [ enumCast ( Op :: OpTypeMatrix )] . push_back ( type ) ; 531constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 532module . mapInstruction ( type ) ; 533 534if ( emitNonSemanticShaderDebugInfo ) 535{ 536auto const debugResultId = makeMatrixDebugType ( column , cols ) ; 537debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 538} 539 540return type -> getResultId () ; 541} 542 543Id Builder :: makeCooperativeMatrixTypeKHR ( Id component , Id scope , Id rows , Id cols , Id use ) 544{ 545// try to find it 546Instruction * type ; 547for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeCooperativeMatrixKHR )] . size () ; ++ t ) { 548type = groupedTypes [ enumCast ( Op :: OpTypeCooperativeMatrixKHR )][ t ] ; 549if ( type -> getIdOperand ( 0 ) == component && 550type -> getIdOperand ( 1 ) == scope && 551type -> getIdOperand ( 2 ) == rows && 552type -> getIdOperand ( 3 ) == cols && 553type -> getIdOperand ( 4 ) == use ) 554return type -> getResultId () ; 555} 556 557// not found, make it 558type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeCooperativeMatrixKHR ) ; 559type -> reserveOperands ( 5 ) ; 560type -> addIdOperand ( component ) ; 561type -> addIdOperand ( scope ) ; 562type -> addIdOperand ( rows ) ; 563type -> addIdOperand ( cols ) ; 564type -> addIdOperand ( use ) ; 565groupedTypes [ enumCast ( Op :: OpTypeCooperativeMatrixKHR )] . push_back ( type ) ; 566constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 567module . mapInstruction ( type ) ; 568 569if ( emitNonSemanticShaderDebugInfo ) { 570auto const debugResultId = makeCooperativeMatrixDebugTypeKHR ( component , scope , rows , cols , use ) ; 571debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 572} 573 574return type -> getResultId () ; 575} 576 577Id Builder :: makeCooperativeMatrixTypeNV ( Id component , Id scope , Id rows , Id cols ) 578{ 579// try to find it 580Instruction * type ; 581for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeCooperativeMatrixNV )] . size () ; ++ t ) { 582type = groupedTypes [ enumCast ( Op :: OpTypeCooperativeMatrixNV )][ t ] ; 583if ( type -> getIdOperand ( 0 ) == component && type -> getIdOperand ( 1 ) == scope && type -> getIdOperand ( 2 ) == rows && 584type -> getIdOperand ( 3 ) == cols ) 585return type -> getResultId () ; 586} 587 588// not found, make it 589type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeCooperativeMatrixNV ) ; 590type -> reserveOperands ( 4 ) ; 591type -> addIdOperand ( component ) ; 592type -> addIdOperand ( scope ) ; 593type -> addIdOperand ( rows ) ; 594type -> addIdOperand ( cols ) ; 595groupedTypes [ enumCast ( Op :: OpTypeCooperativeMatrixNV )] . push_back ( type ) ; 596constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 597module . mapInstruction ( type ) ; 598 599return type -> getResultId () ; 600} 601 602Id Builder :: makeCooperativeMatrixTypeWithSameShape ( Id component , Id otherType ) 603{ 604Instruction * instr = module . getInstruction ( otherType ) ; 605if ( instr -> getOpCode () == Op :: OpTypeCooperativeMatrixNV ) { 606return makeCooperativeMatrixTypeNV ( component , instr -> getIdOperand ( 1 ) , instr -> getIdOperand ( 2 ) , instr -> getIdOperand ( 3 )) ; 607} else { 608assert ( instr -> getOpCode () == Op :: OpTypeCooperativeMatrixKHR ) ; 609return makeCooperativeMatrixTypeKHR ( component , instr -> getIdOperand ( 1 ) , instr -> getIdOperand ( 2 ) , instr -> getIdOperand ( 3 ) , instr -> getIdOperand ( 4 )) ; 610} 611} 612 613Id Builder :: makeCooperativeVectorTypeNV ( Id componentType , Id components ) 614{ 615// try to find it 616Instruction * type ; 617for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeCooperativeVectorNV )] . size () ; ++ t ) { 618type = groupedTypes [ enumCast ( Op :: OpTypeCooperativeVectorNV )][ t ] ; 619if ( type -> getIdOperand ( 0 ) == componentType && 620type -> getIdOperand ( 1 ) == components ) 621return type -> getResultId () ; 622} 623 624// not found, make it 625type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeCooperativeVectorNV ) ; 626type -> addIdOperand ( componentType ) ; 627type -> addIdOperand ( components ) ; 628groupedTypes [ enumCast ( Op :: OpTypeCooperativeVectorNV )] . push_back ( type ) ; 629constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 630module . mapInstruction ( type ) ; 631 632if ( emitNonSemanticShaderDebugInfo ) { 633auto const debugResultId = makeVectorIdDebugType ( componentType , components ) ; 634debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 635} 636 637return type -> getResultId () ; 638} 639 640Id Builder :: makeTensorTypeARM ( Id elementType , Id rank ) 641{ 642// See if an OpTypeTensorARM with same element type and rank already exists. 643for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeTensorARM )] . size () ; ++ t ) { 644const Instruction * type = groupedTypes [ enumCast ( Op :: OpTypeTensorARM )][ t ] ; 645if ( type -> getIdOperand ( 0 ) == elementType && type -> getIdOperand ( 1 ) == rank ) 646return type -> getResultId () ; 647} 648 649// Not found, make it. 650std :: unique_ptr < Instruction > type ( new Instruction ( getUniqueId () , NoType , Op :: OpTypeTensorARM )) ; 651type -> addIdOperand ( elementType ) ; 652type -> addIdOperand ( rank ) ; 653groupedTypes [ enumCast ( Op :: OpTypeTensorARM )] . push_back ( type . get ()) ; 654module . mapInstruction ( type . get ()) ; 655Id resultID = type -> getResultId () ; 656constantsTypesGlobals . push_back ( std :: move ( type )) ; 657return resultID ; 658} 659 660Id Builder :: makeGenericType ( spv :: Op opcode , std :: vector < spv :: IdImmediate >& operands ) 661{ 662// try to find it 663Instruction * type ; 664for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( opcode )] . size () ; ++ t ) { 665type = groupedTypes [ enumCast ( opcode )][ t ] ; 666if ( static_cast < size_t > ( type -> getNumOperands ()) != operands . size ()) 667continue ; // Number mismatch, find next 668 669bool match = true ; 670for ( int op = 0 ; match && op < ( int ) operands . size () ; ++ op ) { 671match = ( operands [ op ] . isId ? type -> getIdOperand ( op ) : type -> getImmediateOperand ( op )) == operands [ op ] . word ; 672} 673if ( match ) 674return type -> getResultId () ; 675} 676 677// not found, make it 678type = new Instruction ( getUniqueId () , NoType , opcode ) ; 679type -> reserveOperands ( operands . size ()) ; 680for ( size_t op = 0 ; op < operands . size () ; ++ op ) { 681if ( operands [ op ] . isId ) 682type -> addIdOperand ( operands [ op ] . word ) ; 683else 684type -> addImmediateOperand ( operands [ op ] . word ) ; 685} 686groupedTypes [ enumCast ( opcode )] . push_back ( type ) ; 687constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 688module . mapInstruction ( type ) ; 689 690return type -> getResultId () ; 691} 692 693// TODO: performance: track arrays per stride 694// If a stride is supplied (non-zero) make an array. 695// If no stride (0), reuse previous array types. 696// 'size' is an Id of a constant or specialization constant of the array size 697Id Builder :: makeArrayType ( Id element , Id sizeId , int stride ) 698{ 699Instruction * type ; 700if ( stride == 0 ) { 701// try to find existing type 702for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeArray )] . size () ; ++ t ) { 703type = groupedTypes [ enumCast ( Op :: OpTypeArray )][ t ] ; 704if ( type -> getIdOperand ( 0 ) == element && 705type -> getIdOperand ( 1 ) == sizeId && 706explicitlyLaidOut . find ( type -> getResultId ()) == explicitlyLaidOut . end ()) 707return type -> getResultId () ; 708} 709} 710 711// not found, make it 712type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeArray ) ; 713type -> reserveOperands ( 2 ) ; 714type -> addIdOperand ( element ) ; 715type -> addIdOperand ( sizeId ) ; 716groupedTypes [ enumCast ( Op :: OpTypeArray )] . push_back ( type ) ; 717constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 718module . mapInstruction ( type ) ; 719 720if ( stride != 0 ) { 721explicitlyLaidOut . insert ( type -> getResultId ()) ; 722} 723 724if ( emitNonSemanticShaderDebugInfo ) 725{ 726auto const debugResultId = makeArrayDebugType ( element , sizeId ) ; 727debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 728} 729 730return type -> getResultId () ; 731} 732 733Id Builder :: makeRuntimeArray ( Id element ) 734{ 735Instruction * type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeRuntimeArray ) ; 736type -> addIdOperand ( element ) ; 737constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 738module . mapInstruction ( type ) ; 739 740if ( emitNonSemanticShaderDebugInfo ) 741{ 742auto const debugResultId = makeArrayDebugType ( element , makeUintConstant ( 0 )) ; 743debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 744} 745 746return type -> getResultId () ; 747} 748 749Id Builder :: makeFunctionType ( Id returnType , const std :: vector < Id >& paramTypes ) 750{ 751// try to find it 752Instruction * type ; 753for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeFunction )] . size () ; ++ t ) { 754type = groupedTypes [ enumCast ( Op :: OpTypeFunction )][ t ] ; 755if ( type -> getIdOperand ( 0 ) != returnType || ( int ) paramTypes . size () != type -> getNumOperands () - 1 ) 756continue ; 757bool mismatch = false ; 758for ( int p = 0 ; p < ( int ) paramTypes . size () ; ++ p ) { 759if ( paramTypes [ p ] != type -> getIdOperand ( p + 1 )) { 760mismatch = true ; 761break ; 762} 763} 764if ( ! mismatch ) 765{ 766// If compiling HLSL, glslang will create a wrapper function around the entrypoint. Accordingly, a void(void) 767// function type is created for the wrapper function. However, nonsemantic shader debug information is disabled 768// while creating the HLSL wrapper. Consequently, if we encounter another void(void) function, we need to create 769// the associated debug function type if it hasn't been created yet. 770if ( emitNonSemanticShaderDebugInfo && getDebugType ( type -> getResultId ()) == NoType ) { 771assert ( sourceLang == spv :: SourceLanguage :: HLSL ) ; 772assert ( getTypeClass ( returnType ) == Op :: OpTypeVoid && paramTypes . size () == 0 ) ; 773 774Id id = makeDebugFunctionType ( returnType , {}) ; 775debugTypeIdLookup [ type -> getResultId ()] = id ; 776} 777return type -> getResultId () ; 778} 779} 780 781// not found, make it 782Id typeId = getUniqueId () ; 783type = new Instruction ( typeId , NoType , Op :: OpTypeFunction ) ; 784type -> reserveOperands ( paramTypes . size () + 1 ) ; 785type -> addIdOperand ( returnType ) ; 786for ( int p = 0 ; p < ( int ) paramTypes . size () ; ++ p ) 787type -> addIdOperand ( paramTypes [ p ]) ; 788groupedTypes [ enumCast ( Op :: OpTypeFunction )] . push_back ( type ) ; 789constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 790module . mapInstruction ( type ) ; 791 792// make debug type and map it 793if ( emitNonSemanticShaderDebugInfo ) { 794Id debugTypeId = makeDebugFunctionType ( returnType , paramTypes ) ; 795debugTypeIdLookup [ typeId ] = debugTypeId ; 796} 797 798return type -> getResultId () ; 799} 800 801Id Builder :: makeDebugFunctionType ( Id returnType , const std :: vector < Id >& paramTypes ) 802{ 803assert ( getDebugType ( returnType ) != NoType ) ; 804 805Id typeId = getUniqueId () ; 806auto type = new Instruction ( typeId , makeVoidType () , Op :: OpExtInst ) ; 807type -> reserveOperands ( paramTypes . size () + 4 ) ; 808type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 809type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypeFunction ) ; 810type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoFlagIsPublic )) ; 811type -> addIdOperand ( getDebugType ( returnType )) ; 812for ( auto const paramType : paramTypes ) { 813if ( isPointerType ( paramType ) || isArrayType ( paramType )) { 814type -> addIdOperand ( getDebugType ( getContainedTypeId ( paramType ))) ; 815} 816else { 817type -> addIdOperand ( getDebugType ( paramType )) ; 818} 819} 820constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 821module . mapInstruction ( type ) ; 822return typeId ; 823} 824 825Id Builder :: makeImageType ( Id sampledType , Dim dim , bool depth , bool arrayed , bool ms , unsigned sampled , 826ImageFormat format , const char * debugName ) 827{ 828assert ( sampled == 1 || sampled == 2 ) ; 829 830// try to find it 831Instruction * type ; 832for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeImage )] . size () ; ++ t ) { 833type = groupedTypes [ enumCast ( Op :: OpTypeImage )][ t ] ; 834if ( type -> getIdOperand ( 0 ) == sampledType && 835type -> getImmediateOperand ( 1 ) == ( unsigned int ) dim && 836type -> getImmediateOperand ( 2 ) == ( depth ? 1u : 0u ) && 837type -> getImmediateOperand ( 3 ) == ( arrayed ? 1u : 0u ) && 838type -> getImmediateOperand ( 4 ) == ( ms ? 1u : 0u ) && 839type -> getImmediateOperand ( 5 ) == sampled && 840type -> getImmediateOperand ( 6 ) == ( unsigned int ) format ) 841return type -> getResultId () ; 842} 843 844// not found, make it 845type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeImage ) ; 846type -> reserveOperands ( 7 ) ; 847type -> addIdOperand ( sampledType ) ; 848type -> addImmediateOperand ( dim ) ; 849type -> addImmediateOperand ( depth ? 1 : 0 ) ; 850type -> addImmediateOperand ( arrayed ? 1 : 0 ) ; 851type -> addImmediateOperand ( ms ? 1 : 0 ) ; 852type -> addImmediateOperand ( sampled ) ; 853type -> addImmediateOperand (( unsigned int ) format ) ; 854 855groupedTypes [ enumCast ( Op :: OpTypeImage )] . push_back ( type ) ; 856constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 857module . mapInstruction ( type ) ; 858 859// deal with capabilities 860switch ( dim ) { 861case Dim :: Buffer : 862if ( sampled == 1 ) 863addCapability ( Capability :: SampledBuffer ) ; 864else 865addCapability ( Capability :: ImageBuffer ) ; 866break ; 867case Dim :: Dim1D : 868if ( sampled == 1 ) 869addCapability ( Capability :: Sampled1D ) ; 870else 871addCapability ( Capability :: Image1D ) ; 872break ; 873case Dim :: Cube : 874if ( arrayed ) { 875if ( sampled == 1 ) 876addCapability ( Capability :: SampledCubeArray ) ; 877else 878addCapability ( Capability :: ImageCubeArray ) ; 879} 880break ; 881case Dim :: Rect : 882if ( sampled == 1 ) 883addCapability ( Capability :: SampledRect ) ; 884else 885addCapability ( Capability :: ImageRect ) ; 886break ; 887case Dim :: SubpassData : 888addCapability ( Capability :: InputAttachment ) ; 889break ; 890default : 891break ; 892} 893 894if ( ms ) { 895if ( sampled == 2 ) { 896// Images used with subpass data are not storage 897// images, so don't require the capability for them. 898if ( dim != Dim :: SubpassData ) 899addCapability ( Capability :: StorageImageMultisample ) ; 900if ( arrayed ) 901addCapability ( Capability :: ImageMSArray ) ; 902} 903} 904 905if ( emitNonSemanticShaderDebugInfo ) 906{ 907auto const debugResultId = makeOpaqueDebugType ( debugName ) ; 908debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 909} 910 911return type -> getResultId () ; 912} 913 914Id Builder :: makeSampledImageType ( Id imageType , const char * debugName ) 915{ 916// try to find it 917Instruction * type ; 918for ( int t = 0 ; t < ( int ) groupedTypes [ enumCast ( Op :: OpTypeSampledImage )] . size () ; ++ t ) { 919type = groupedTypes [ enumCast ( Op :: OpTypeSampledImage )][ t ] ; 920if ( type -> getIdOperand ( 0 ) == imageType ) 921return type -> getResultId () ; 922} 923 924// not found, make it 925type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeSampledImage ) ; 926type -> addIdOperand ( imageType ) ; 927 928groupedTypes [ enumCast ( Op :: OpTypeSampledImage )] . push_back ( type ) ; 929constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 930module . mapInstruction ( type ) ; 931 932if ( emitNonSemanticShaderDebugInfo ) 933{ 934auto const debugResultId = makeOpaqueDebugType ( debugName ) ; 935debugTypeIdLookup [ type -> getResultId ()] = debugResultId ; 936} 937 938return type -> getResultId () ; 939} 940 941Id Builder :: makeDebugInfoNone () 942{ 943if ( debugInfoNone != 0 ) 944return debugInfoNone ; 945 946Instruction * inst = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 947inst -> reserveOperands ( 2 ) ; 948inst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 949inst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugInfoNone ) ; 950 951constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( inst )) ; 952module . mapInstruction ( inst ) ; 953 954debugInfoNone = inst -> getResultId () ; 955 956return debugInfoNone ; 957} 958 959Id Builder :: makeBoolDebugType ( int const size ) 960{ 961// try to find it 962Instruction * type ; 963for ( int t = 0 ; t < ( int ) groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeBasic ] . size () ; ++ t ) { 964type = groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeBasic ][ t ] ; 965if ( type -> getIdOperand ( 0 ) == getStringId ( "bool" ) && 966type -> getIdOperand ( 1 ) == static_cast < unsigned int > ( size ) && 967type -> getIdOperand ( 2 ) == NonSemanticShaderDebugInfoBoolean ) 968return type -> getResultId () ; 969} 970 971type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 972type -> reserveOperands ( 6 ) ; 973type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 974type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypeBasic ) ; 975 976type -> addIdOperand ( getStringId ( "bool" )) ; // name id 977type -> addIdOperand ( makeUintConstant ( size )) ; // size id 978type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoBoolean )) ; // encoding id 979type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoNone )) ; // flags id 980 981groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeBasic ] . push_back ( type ) ; 982constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 983module . mapInstruction ( type ) ; 984 985return type -> getResultId () ; 986} 987 988Id Builder :: makeIntegerDebugType ( int const width , bool const hasSign ) 989{ 990const char * typeName = nullptr ; 991switch ( width ) { 992case 8 : typeName = hasSign ? "int8_t" : "uint8_t" ; break ; 993case 16 : typeName = hasSign ? "int16_t" : "uint16_t" ; break ; 994case 64 : typeName = hasSign ? "int64_t" : "uint64_t" ; break ; 995default : typeName = hasSign ? "int" : "uint" ; 996} 997auto nameId = getStringId ( typeName ) ; 998// try to find it 999Instruction * type ; 1000for ( int t = 0 ; t < ( int ) groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeBasic ] . size () ; ++ t ) { 1001type = groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeBasic ][ t ] ; 1002if ( type -> getIdOperand ( 0 ) == nameId && 1003type -> getIdOperand ( 1 ) == static_cast < unsigned int > ( width ) && 1004type -> getIdOperand ( 2 ) == ( hasSign ? NonSemanticShaderDebugInfoSigned : NonSemanticShaderDebugInfoUnsigned )) 1005return type -> getResultId () ; 1006} 1007 1008// not found, make it 1009type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1010type -> reserveOperands ( 6 ) ; 1011type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1012type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypeBasic ) ; 1013type -> addIdOperand ( nameId ) ; // name id 1014type -> addIdOperand ( makeUintConstant ( width )) ; // size id 1015if ( hasSign == true ) { 1016type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoSigned )) ; // encoding id 1017} else { 1018type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoUnsigned )) ; // encoding id 1019} 1020type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoNone )) ; // flags id 1021 1022groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeBasic ] . push_back ( type ) ; 1023constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1024module . mapInstruction ( type ) ; 1025 1026return type -> getResultId () ; 1027} 1028 1029Id Builder :: makeFloatDebugType ( int const width , Id const fpEncoding ) 1030{ 1031if ( fpEncoding != NoType ) 1032requireNonSemanticShaderDebugInfoVersion ( 101 ) ; 1033// Determine the debug type name. FP-encoded variants have distinct names. 1034// Id comparison works here because makeUintConstant deduplicates: two calls 1035// with the same value return the same Id. 1036const char * typeName = nullptr ; 1037if ( fpEncoding != NoType ) { 1038if ( fpEncoding == makeUintConstant (( unsigned ) FPEncoding :: BFloat16KHR )) 1039typeName = "bfloat16_t" ; 1040else if ( fpEncoding == makeUintConstant (( unsigned ) FPEncoding :: Float8E4M3EXT )) 1041typeName = "floate4m3_t" ; 1042else if ( fpEncoding == makeUintConstant (( unsigned ) FPEncoding :: Float8E5M2EXT )) 1043typeName = "floate5m2_t" ; 1044else 1045typeName = "float" ; 1046} else { 1047switch ( width ) { 1048case 16 : typeName = "float16_t" ; break ; 1049case 64 : typeName = "double" ; break ; 1050default : typeName = "float" ; break ; 1051} 1052} 1053auto nameId = getStringId ( typeName ) ; 1054// try to find it 1055Instruction * type ; 1056for ( int t = 0 ; t < ( int ) groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeBasic ] . size () ; ++ t ) { 1057type = groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeBasic ][ t ] ; 1058if ( type -> getIdOperand ( 0 ) == nameId && 1059type -> getIdOperand ( 1 ) == static_cast < unsigned int > ( width ) && 1060type -> getIdOperand ( 2 ) == NonSemanticShaderDebugInfoFloat ) { 1061if ( fpEncoding == NoType ) { 1062if ( type -> getNumOperands () == 6 ) 1063return type -> getResultId () ; 1064} else { 1065if ( type -> getNumOperands () == 7 && type -> getIdOperand ( 6 ) == fpEncoding ) 1066return type -> getResultId () ; 1067} 1068} 1069} 1070 1071// not found, make it 1072type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1073type -> reserveOperands ( fpEncoding == NoType ? 6 : 7 ) ; 1074type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1075type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypeBasic ) ; 1076type -> addIdOperand ( nameId ) ; // name id 1077type -> addIdOperand ( makeUintConstant ( width )) ; // size id 1078type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoFloat )) ; // encoding id 1079type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoNone )) ; // flags id 1080if ( fpEncoding != NoType ) 1081type -> addIdOperand ( fpEncoding ) ; // optional FPEncoding id (NSDI.101) 1082 1083groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeBasic ] . push_back ( type ) ; 1084constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1085module . mapInstruction ( type ) ; 1086 1087return type -> getResultId () ; 1088} 1089 1090Id Builder :: makeSequentialDebugType ( Id const baseType , Id const componentCount , NonSemanticShaderDebugInfoInstructions const sequenceType ) 1091{ 1092assert ( sequenceType == NonSemanticShaderDebugInfoDebugTypeArray || 1093sequenceType == NonSemanticShaderDebugInfoDebugTypeVector ) ; 1094 1095// try to find it 1096Instruction * type ; 1097for ( int t = 0 ; t < ( int ) groupedDebugTypes [ sequenceType ] . size () ; ++ t ) { 1098type = groupedDebugTypes [ sequenceType ][ t ] ; 1099if ( type -> getIdOperand ( 0 ) == baseType && 1100type -> getIdOperand ( 1 ) == makeUintConstant ( componentCount )) 1101return type -> getResultId () ; 1102} 1103 1104// not found, make it 1105type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1106type -> reserveOperands ( 4 ) ; 1107type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1108type -> addImmediateOperand ( sequenceType ) ; 1109type -> addIdOperand ( getDebugType ( baseType )) ; // base type 1110type -> addIdOperand ( componentCount ) ; // component count 1111 1112groupedDebugTypes [ sequenceType ] . push_back ( type ) ; 1113constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1114module . mapInstruction ( type ) ; 1115 1116return type -> getResultId () ; 1117} 1118 1119Id Builder :: makeArrayDebugType ( Id const baseType , Id const componentCount ) 1120{ 1121return makeSequentialDebugType ( baseType , componentCount , NonSemanticShaderDebugInfoDebugTypeArray ) ; 1122} 1123 1124Id Builder :: makeVectorDebugType ( Id const baseType , int const componentCount ) 1125{ 1126return makeSequentialDebugType ( baseType , makeUintConstant ( componentCount ) , NonSemanticShaderDebugInfoDebugTypeVector ) ; 1127} 1128 1129Id Builder :: makeMatrixDebugType ( Id const vectorType , int const vectorCount , bool columnMajor ) 1130{ 1131// try to find it 1132Instruction * type ; 1133for ( int t = 0 ; t < ( int ) groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeMatrix ] . size () ; ++ t ) { 1134type = groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeMatrix ][ t ] ; 1135if ( type -> getIdOperand ( 0 ) == vectorType && 1136type -> getIdOperand ( 1 ) == makeUintConstant ( vectorCount )) 1137return type -> getResultId () ; 1138} 1139 1140// not found, make it 1141type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1142type -> reserveOperands ( 5 ) ; 1143type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1144type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypeMatrix ) ; 1145type -> addIdOperand ( getDebugType ( vectorType )) ; // vector type id 1146type -> addIdOperand ( makeUintConstant ( vectorCount )) ; // component count id 1147type -> addIdOperand ( makeBoolConstant ( columnMajor )) ; // column-major id 1148 1149groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeMatrix ] . push_back ( type ) ; 1150constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1151module . mapInstruction ( type ) ; 1152 1153return type -> getResultId () ; 1154} 1155 1156// DebugTypeVectorIdEXT (NSDI.101 opcode 109): describes OpTypeVectorIdEXT and 1157// OpTypeCooperativeVectorNV types whose component count is a SPIR-V Id (not a 1158// literal), including specialization-constant component counts. 1159Id Builder :: makeVectorIdDebugType ( Id const componentType , Id const componentCount ) 1160{ 1161requireNonSemanticShaderDebugInfoVersion ( 101 ) ; 1162// try to find it 1163Instruction * type ; 1164for ( int t = 0 ; t < ( int ) groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeVectorIdEXT ] . size () ; ++ t ) { 1165type = groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeVectorIdEXT ][ t ] ; 1166if ( type -> getIdOperand ( 2 ) == getDebugType ( componentType ) && 1167type -> getIdOperand ( 3 ) == componentCount ) 1168return type -> getResultId () ; 1169} 1170 1171// not found, make it 1172type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1173type -> reserveOperands ( 4 ) ; 1174type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1175type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypeVectorIdEXT ) ; 1176type -> addIdOperand ( getDebugType ( componentType )) ; // component debug type 1177type -> addIdOperand ( componentCount ) ; // component count (constant instruction Id) 1178 1179groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeVectorIdEXT ] . push_back ( type ) ; 1180constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1181module . mapInstruction ( type ) ; 1182 1183return type -> getResultId () ; 1184} 1185 1186// DebugTypeCooperativeMatrixKHR (NSDI.101 opcode 110): describes 1187// OpTypeCooperativeMatrixKHR types. 1188Id Builder :: makeCooperativeMatrixDebugTypeKHR ( Id const componentType , Id const scope , 1189Id const rows , Id const cols , Id const use ) 1190{ 1191requireNonSemanticShaderDebugInfoVersion ( 101 ) ; 1192// try to find it 1193Instruction * type ; 1194for ( int t = 0 ; t < ( int ) groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeCooperativeMatrixKHR ] . size () ; ++ t ) { 1195type = groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeCooperativeMatrixKHR ][ t ] ; 1196if ( type -> getIdOperand ( 2 ) == getDebugType ( componentType ) && 1197type -> getIdOperand ( 3 ) == scope && 1198type -> getIdOperand ( 4 ) == rows && 1199type -> getIdOperand ( 5 ) == cols && 1200type -> getIdOperand ( 6 ) == use ) 1201return type -> getResultId () ; 1202} 1203 1204// not found, make it 1205type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1206type -> reserveOperands ( 7 ) ; 1207type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1208type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypeCooperativeMatrixKHR ) ; 1209type -> addIdOperand ( getDebugType ( componentType )) ; // component debug type 1210type -> addIdOperand ( scope ) ; // scope 1211type -> addIdOperand ( rows ) ; // rows 1212type -> addIdOperand ( cols ) ; // columns 1213type -> addIdOperand ( use ) ; // use (MatrixA, MatrixB, Accumulator) 1214 1215groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeCooperativeMatrixKHR ] . push_back ( type ) ; 1216constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1217module . mapInstruction ( type ) ; 1218 1219return type -> getResultId () ; 1220} 1221 1222Id Builder :: makeMemberDebugType ( Id const memberType , StructMemberDebugInfo const & debugTypeLoc ) 1223{ 1224assert ( getDebugType ( memberType ) != NoType ) ; 1225 1226Instruction * type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1227type -> reserveOperands ( 10 ) ; 1228type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1229type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypeMember ) ; 1230type -> addIdOperand ( getStringId ( debugTypeLoc . name )) ; // name id 1231type -> addIdOperand ( debugTypeLoc . debugTypeOverride != 0 ? debugTypeLoc . debugTypeOverride 1232: getDebugType ( memberType )) ; // type id 1233type -> addIdOperand ( makeDebugSource ( currentFileId )) ; // source id 1234type -> addIdOperand ( makeUintConstant ( debugTypeLoc . line )) ; // line id TODO: currentLine is always zero 1235type -> addIdOperand ( makeUintConstant ( debugTypeLoc . column )) ; // TODO: column id 1236type -> addIdOperand ( makeUintConstant ( 0 )) ; // TODO: offset id 1237type -> addIdOperand ( makeUintConstant ( 0 )) ; // TODO: size id 1238type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoFlagIsPublic )) ; // flags id 1239 1240groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeMember ] . push_back ( type ) ; 1241constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1242module . mapInstruction ( type ) ; 1243 1244return type -> getResultId () ; 1245} 1246 1247Id Builder :: makeCompositeDebugType ( std :: vector < Id > const & memberTypes , std :: vector < StructMemberDebugInfo > const & memberDebugInfo , 1248char const * const name , NonSemanticShaderDebugInfoDebugCompositeType const tag ) 1249{ 1250// Create the debug member types. 1251std :: vector < Id > memberDebugTypes ; 1252assert ( memberTypes . size () == memberDebugInfo . size ()) ; 1253for ( size_t i = 0 ; i < memberTypes . size () ; i ++ ) { 1254if ( getDebugType ( memberTypes [ i ]) != NoType ) { 1255memberDebugTypes . emplace_back ( makeMemberDebugType ( memberTypes [ i ] , memberDebugInfo [ i ])) ; 1256} 1257} 1258 1259// Create The structure debug type. 1260Instruction * type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1261type -> reserveOperands ( memberDebugTypes . size () + 11 ) ; 1262type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1263type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypeComposite ) ; 1264type -> addIdOperand ( getStringId ( name )) ; // name id 1265type -> addIdOperand ( makeUintConstant ( tag )) ; // tag id 1266type -> addIdOperand ( makeDebugSource ( currentFileId )) ; // source id 1267type -> addIdOperand ( makeUintConstant ( currentLine )) ; // line id TODO: currentLine always zero? 1268type -> addIdOperand ( makeUintConstant ( 0 )) ; // TODO: column id 1269type -> addIdOperand ( makeDebugCompilationUnit ()) ; // scope id 1270type -> addIdOperand ( getStringId ( name )) ; // linkage name id 1271type -> addIdOperand ( makeUintConstant ( 0 )) ; // TODO: size id 1272type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoFlagIsPublic )) ; // flags id 1273for ( auto const memberDebugType : memberDebugTypes ) { 1274type -> addIdOperand ( memberDebugType ) ; 1275} 1276 1277groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeComposite ] . push_back ( type ) ; 1278constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1279module . mapInstruction ( type ) ; 1280 1281return type -> getResultId () ; 1282} 1283 1284// The NonSemantic Shader Debug Info doesn't really have a dedicated opcode for opaque types. Instead, we use DebugTypeComposite. 1285// To represent a source language opaque type, this instruction must have no Members operands, Size operand must be 1286// DebugInfoNone, and Name must start with @ to avoid clashes with user defined names. 1287Id Builder :: makeOpaqueDebugType ( char const * const name ) 1288{ 1289// Create The structure debug type. 1290Instruction * type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1291type -> reserveOperands ( 11 ) ; 1292type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1293type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypeComposite ) ; 1294type -> addIdOperand ( getStringId ( name )) ; // name id 1295type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoStructure )) ; // tag id 1296type -> addIdOperand ( makeDebugSource ( currentFileId )) ; // source id 1297type -> addIdOperand ( makeUintConstant ( currentLine )) ; // line id TODO: currentLine always zero? 1298type -> addIdOperand ( makeUintConstant ( 0 )) ; // TODO: column id 1299type -> addIdOperand ( makeDebugCompilationUnit ()) ; // scope id 1300// Prepend '@' to opaque types. 1301type -> addIdOperand ( getStringId ( '@' + std :: string ( name ))) ; // linkage name id 1302type -> addIdOperand ( makeDebugInfoNone ()) ; // size id 1303type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoFlagIsPublic )) ; // flags id 1304 1305groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypeComposite ] . push_back ( type ) ; 1306constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1307module . mapInstruction ( type ) ; 1308 1309return type -> getResultId () ; 1310} 1311 1312Id Builder :: makePointerDebugType ( StorageClass storageClass , Id const baseType ) 1313{ 1314const Id debugBaseType = getDebugType ( baseType ) ; 1315if ( ! debugBaseType ) { 1316return makeDebugInfoNone () ; 1317} 1318const Id scID = makeUintConstant ( storageClass ) ; 1319for ( Instruction * otherType : groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypePointer ]) { 1320if ( otherType -> getIdOperand ( 2 ) == debugBaseType && 1321otherType -> getIdOperand ( 3 ) == scID ) { 1322return otherType -> getResultId () ; 1323} 1324} 1325 1326Instruction * type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1327type -> reserveOperands ( 5 ) ; 1328type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1329type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypePointer ) ; 1330type -> addIdOperand ( debugBaseType ) ; 1331type -> addIdOperand ( scID ) ; 1332type -> addIdOperand ( makeUintConstant ( 0 )) ; 1333 1334groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypePointer ] . push_back ( type ) ; 1335constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1336module . mapInstruction ( type ) ; 1337 1338return type -> getResultId () ; 1339} 1340 1341// Emit a OpExtInstWithForwardRefsKHR nonsemantic instruction for a pointer debug type 1342// where we don't have the pointee yet. Since we don't have the pointee yet, it just 1343// points to itself and we rely on patching it later. 1344Id Builder :: makeForwardPointerDebugType ( StorageClass storageClass ) 1345{ 1346const Id scID = makeUintConstant ( storageClass ) ; 1347 1348this -> addExtension ( spv :: E_SPV_KHR_relaxed_extended_instruction ) ; 1349 1350Instruction * type = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInstWithForwardRefsKHR ) ; 1351type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1352type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugTypePointer ) ; 1353type -> addIdOperand ( type -> getResultId ()) ; 1354type -> addIdOperand ( scID ) ; 1355type -> addIdOperand ( makeUintConstant ( 0 )) ; 1356 1357groupedDebugTypes [ NonSemanticShaderDebugInfoDebugTypePointer ] . push_back ( type ) ; 1358constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1359module . mapInstruction ( type ) ; 1360 1361return type -> getResultId () ; 1362} 1363 1364Id Builder :: makeDebugSource ( const Id fileName ) { 1365if ( debugSourceId . find ( fileName ) != debugSourceId . end ()) 1366return debugSourceId [ fileName ] ; 1367spv :: Id resultId = getUniqueId () ; 1368Instruction * sourceInst = new Instruction ( resultId , makeVoidType () , Op :: OpExtInst ) ; 1369sourceInst -> reserveOperands ( 3 ) ; 1370sourceInst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1371sourceInst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugSource ) ; 1372sourceInst -> addIdOperand ( fileName ) ; 1373constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( sourceInst )) ; 1374module . mapInstruction ( sourceInst ) ; 1375if ( emitNonSemanticShaderDebugSource ) { 1376const int maxWordCount = 0xFFFF ; 1377const int opSourceWordCount = 4 ; 1378const int nonNullBytesPerInstruction = 4 * ( maxWordCount - opSourceWordCount ) - 1 ; 1379auto processDebugSource = [ & ]( std :: string source ) { 1380if ( source . size () > 0 ) { 1381int nextByte = 0 ; 1382while (( int ) source . size () - nextByte > 0 ) { 1383auto subString = source . substr ( nextByte , nonNullBytesPerInstruction ) ; 1384auto sourceId = getStringId ( subString ) ; 1385if ( nextByte == 0 ) { 1386// DebugSource 1387sourceInst -> addIdOperand ( sourceId ) ; 1388} else { 1389// DebugSourceContinued 1390Instruction * sourceContinuedInst = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1391sourceContinuedInst -> reserveOperands ( 2 ) ; 1392sourceContinuedInst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1393sourceContinuedInst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugSourceContinued ) ; 1394sourceContinuedInst -> addIdOperand ( sourceId ) ; 1395constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( sourceContinuedInst )) ; 1396module . mapInstruction ( sourceContinuedInst ) ; 1397} 1398nextByte += nonNullBytesPerInstruction ; 1399} 1400} else { 1401auto sourceId = getStringId ( source ) ; 1402sourceInst -> addIdOperand ( sourceId ) ; 1403} 1404} ; 1405if ( fileName == mainFileId ) { 1406processDebugSource ( sourceText ) ; 1407} else { 1408auto incItr = includeFiles . find ( fileName ) ; 1409if ( incItr != includeFiles . end ()) { 1410processDebugSource ( * incItr -> second ) ; 1411} else { 1412// We omit the optional source text item if not available in glslang 1413} 1414} 1415} 1416debugSourceId [ fileName ] = resultId ; 1417return resultId ; 1418} 1419 1420Id Builder :: makeDebugCompilationUnit () { 1421if ( nonSemanticShaderCompilationUnitId != 0 ) 1422return nonSemanticShaderCompilationUnitId ; 1423spv :: Id resultId = getUniqueId () ; 1424Instruction * sourceInst = new Instruction ( resultId , makeVoidType () , Op :: OpExtInst ) ; 1425sourceInst -> reserveOperands ( 6 ) ; 1426sourceInst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1427sourceInst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugCompilationUnit ) ; 1428sourceInst -> addIdOperand ( makeUintConstant ( 1 )) ; // TODO(greg-lunarg): Get rid of magic number 1429sourceInst -> addIdOperand ( makeUintConstant ( 4 )) ; // TODO(greg-lunarg): Get rid of magic number 1430sourceInst -> addIdOperand ( makeDebugSource ( mainFileId )) ; 1431sourceInst -> addIdOperand ( makeUintConstant ( sourceLang )) ; 1432constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( sourceInst )) ; 1433module . mapInstruction ( sourceInst ) ; 1434nonSemanticShaderCompilationUnitId = resultId ; 1435 1436// In the case of non-semantic shader debug info, preserve source text for every include 1437// even if no debug scope or line record ends up referencing that file. 1438if ( emitNonSemanticShaderDebugSource ) { 1439for ( const auto & includeFile : includeFiles ) { 1440makeDebugSource ( includeFile . first ) ; 1441} 1442} 1443 1444// We can reasonably assume that makeDebugCompilationUnit will be called before any of 1445// debug-scope stack. Function scopes and lexical scopes will occur afterward. 1446assert ( currentDebugScopeId . empty ()) ; 1447currentDebugScopeId . push ( nonSemanticShaderCompilationUnitId ) ; 1448 1449return resultId ; 1450} 1451 1452Id Builder :: createDebugGlobalVariable ( Id const type , char const * const name , Id const variable ) 1453{ 1454assert ( type != 0 ) ; 1455 1456Instruction * inst = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1457inst -> reserveOperands ( 11 ) ; 1458inst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1459inst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugGlobalVariable ) ; 1460inst -> addIdOperand ( getStringId ( name )) ; // name id 1461inst -> addIdOperand ( type ) ; // type id 1462inst -> addIdOperand ( makeDebugSource ( currentFileId )) ; // source id 1463inst -> addIdOperand ( makeUintConstant ( currentLine )) ; // line id TODO: currentLine always zero? 1464inst -> addIdOperand ( makeUintConstant ( 0 )) ; // TODO: column id 1465inst -> addIdOperand ( makeDebugCompilationUnit ()) ; // scope id 1466inst -> addIdOperand ( getStringId ( name )) ; // linkage name id 1467inst -> addIdOperand ( variable ) ; // variable id 1468inst -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoFlagIsDefinition )) ; // flags id 1469 1470constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( inst )) ; 1471module . mapInstruction ( inst ) ; 1472 1473return inst -> getResultId () ; 1474} 1475 1476Id Builder :: createDebugLocalVariable ( Id type , char const * const name , size_t const argNumber ) 1477{ 1478assert ( name != nullptr ) ; 1479assert ( ! currentDebugScopeId . empty ()) ; 1480 1481Instruction * inst = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1482inst -> reserveOperands ( 9 ) ; 1483inst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1484inst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugLocalVariable ) ; 1485inst -> addIdOperand ( getStringId ( name )) ; // name id 1486inst -> addIdOperand ( type ) ; // type id 1487inst -> addIdOperand ( makeDebugSource ( currentFileId )) ; // source id 1488inst -> addIdOperand ( makeUintConstant ( currentLine )) ; // line id 1489inst -> addIdOperand ( makeUintConstant ( 0 )) ; // TODO: column id 1490inst -> addIdOperand ( currentDebugScopeId . top ()) ; // scope id 1491inst -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoFlagIsLocal )) ; // flags id 1492if ( argNumber != 0 ) { 1493inst -> addIdOperand ( makeUintConstant ( static_cast < unsigned int > ( argNumber ))) ; 1494} 1495 1496constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( inst )) ; 1497module . mapInstruction ( inst ) ; 1498 1499return inst -> getResultId () ; 1500} 1501 1502Id Builder :: makeDebugExpression () 1503{ 1504if ( debugExpression != 0 ) 1505return debugExpression ; 1506 1507Instruction * inst = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1508inst -> reserveOperands ( 2 ) ; 1509inst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1510inst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugExpression ) ; 1511 1512constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( inst )) ; 1513module . mapInstruction ( inst ) ; 1514 1515debugExpression = inst -> getResultId () ; 1516 1517return debugExpression ; 1518} 1519 1520Id Builder :: makeDebugDeclare ( Id const debugLocalVariable , Id const pointer ) 1521{ 1522Instruction * inst = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1523inst -> reserveOperands ( 5 ) ; 1524inst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1525inst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugDeclare ) ; 1526inst -> addIdOperand ( debugLocalVariable ) ; // debug local variable id 1527inst -> addIdOperand ( pointer ) ; // pointer to local variable id 1528inst -> addIdOperand ( makeDebugExpression ()) ; // expression id 1529addInstruction ( std :: unique_ptr < Instruction > ( inst )) ; 1530 1531return inst -> getResultId () ; 1532} 1533 1534Id Builder :: makeDebugValue ( Id const debugLocalVariable , Id const value ) 1535{ 1536Instruction * inst = new Instruction ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 1537inst -> reserveOperands ( 5 ) ; 1538inst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 1539inst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugValue ) ; 1540inst -> addIdOperand ( debugLocalVariable ) ; // debug local variable id 1541inst -> addIdOperand ( value ) ; // value of local variable id 1542inst -> addIdOperand ( makeDebugExpression ()) ; // expression id 1543addInstruction ( std :: unique_ptr < Instruction > ( inst )) ; 1544 1545return inst -> getResultId () ; 1546} 1547 1548Id Builder :: makeAccelerationStructureType () 1549{ 1550Instruction * type ; 1551if ( groupedTypes [ enumCast ( Op :: OpTypeAccelerationStructureKHR )] . size () == 0 ) { 1552type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeAccelerationStructureKHR ) ; 1553groupedTypes [ enumCast ( Op :: OpTypeAccelerationStructureKHR )] . push_back ( type ) ; 1554constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1555module . mapInstruction ( type ) ; 1556if ( emitNonSemanticShaderDebugInfo ) { 1557spv :: Id debugType = makeOpaqueDebugType ( "accelerationStructure" ) ; 1558debugTypeIdLookup [ type -> getResultId ()] = debugType ; 1559} 1560} else { 1561type = groupedTypes [ enumCast ( Op :: OpTypeAccelerationStructureKHR )] . back () ; 1562} 1563 1564return type -> getResultId () ; 1565} 1566 1567Id Builder :: makeRayQueryType () 1568{ 1569Instruction * type ; 1570if ( groupedTypes [ enumCast ( Op :: OpTypeRayQueryKHR )] . size () == 0 ) { 1571type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeRayQueryKHR ) ; 1572groupedTypes [ enumCast ( Op :: OpTypeRayQueryKHR )] . push_back ( type ) ; 1573constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1574module . mapInstruction ( type ) ; 1575if ( emitNonSemanticShaderDebugInfo ) { 1576spv :: Id debugType = makeOpaqueDebugType ( "rayQuery" ) ; 1577debugTypeIdLookup [ type -> getResultId ()] = debugType ; 1578} 1579} else { 1580type = groupedTypes [ enumCast ( Op :: OpTypeRayQueryKHR )] . back () ; 1581} 1582 1583return type -> getResultId () ; 1584} 1585 1586Id Builder :: makeHitObjectEXTType () 1587{ 1588Instruction * type ; 1589if ( groupedTypes [ enumCast ( Op :: OpTypeHitObjectEXT )] . size () == 0 ) { 1590type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeHitObjectEXT ) ; 1591groupedTypes [ enumCast ( Op :: OpTypeHitObjectEXT )] . push_back ( type ) ; 1592constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1593module . mapInstruction ( type ) ; 1594} else { 1595type = groupedTypes [ enumCast ( Op :: OpTypeHitObjectEXT )] . back () ; 1596} 1597 1598return type -> getResultId () ; 1599} 1600Id Builder :: makeHitObjectNVType () 1601{ 1602Instruction * type ; 1603if ( groupedTypes [ enumCast ( Op :: OpTypeHitObjectNV )] . size () == 0 ) { 1604type = new Instruction ( getUniqueId () , NoType , Op :: OpTypeHitObjectNV ) ; 1605groupedTypes [ enumCast ( Op :: OpTypeHitObjectNV )] . push_back ( type ) ; 1606constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 1607module . mapInstruction ( type ) ; 1608if ( emitNonSemanticShaderDebugInfo ) { 1609spv :: Id debugType = makeOpaqueDebugType ( "hitObjectNV" ) ; 1610debugTypeIdLookup [ type -> getResultId ()] = debugType ; 1611} 1612} else { 1613type = groupedTypes [ enumCast ( Op :: OpTypeHitObjectNV )] . back () ; 1614} 1615 1616return type -> getResultId () ; 1617} 1618 1619Id Builder :: getDerefTypeId ( Id resultId ) const 1620{ 1621Id typeId = getTypeId ( resultId ) ; 1622assert ( isPointerType ( typeId )) ; 1623 1624return module . getInstruction ( typeId ) -> getIdOperand ( 1 ) ; 1625} 1626 1627Op Builder :: getMostBasicTypeClass ( Id typeId ) const 1628{ 1629Instruction * instr = module . getInstruction ( typeId ) ; 1630 1631Op typeClass = instr -> getOpCode () ; 1632switch ( typeClass ) 1633{ 1634case Op :: OpTypeVector : 1635case Op :: OpTypeMatrix : 1636case Op :: OpTypeArray : 1637case Op :: OpTypeRuntimeArray : 1638return getMostBasicTypeClass ( instr -> getIdOperand ( 0 )) ; 1639case Op :: OpTypePointer : 1640return getMostBasicTypeClass ( instr -> getIdOperand ( 1 )) ; 1641default : 1642return typeClass ; 1643} 1644} 1645 1646unsigned int Builder :: getNumTypeConstituents ( Id typeId ) const 1647{ 1648Instruction * instr = module . getInstruction ( typeId ) ; 1649 1650switch ( instr -> getOpCode ()) 1651{ 1652case Op :: OpTypeBool : 1653case Op :: OpTypeInt : 1654case Op :: OpTypeFloat : 1655case Op :: OpTypePointer : 1656return 1 ; 1657case Op :: OpTypeVector : 1658case Op :: OpTypeMatrix : 1659return instr -> getImmediateOperand ( 1 ) ; 1660case Op :: OpTypeCooperativeVectorNV : 1661case Op :: OpTypeArray : 1662{ 1663Id lengthId = instr -> getIdOperand ( 1 ) ; 1664return module . getInstruction ( lengthId ) -> getImmediateOperand ( 0 ) ; 1665} 1666case Op :: OpTypeStruct : 1667return instr -> getNumOperands () ; 1668case Op :: OpTypeCooperativeMatrixKHR : 1669case Op :: OpTypeCooperativeMatrixNV : 1670// has only one constituent when used with OpCompositeConstruct. 1671return 1 ; 1672default : 1673assert ( 0 ) ; 1674return 1 ; 1675} 1676} 1677 1678// Return the lowest-level type of scalar that an homogeneous composite is made out of. 1679// Typically, this is just to find out if something is made out of ints or floats. 1680// However, it includes returning a structure, if say, it is an array of structure. 1681Id Builder :: getScalarTypeId ( Id typeId ) const 1682{ 1683Instruction * instr = module . getInstruction ( typeId ) ; 1684 1685Op typeClass = instr -> getOpCode () ; 1686switch ( typeClass ) 1687{ 1688case Op :: OpTypeVoid : 1689case Op :: OpTypeBool : 1690case Op :: OpTypeInt : 1691case Op :: OpTypeFloat : 1692case Op :: OpTypeStruct : 1693return instr -> getResultId () ; 1694case Op :: OpTypeVector : 1695case Op :: OpTypeMatrix : 1696case Op :: OpTypeArray : 1697case Op :: OpTypeRuntimeArray : 1698case Op :: OpTypePointer : 1699case Op :: OpTypeCooperativeVectorNV : 1700return getScalarTypeId ( getContainedTypeId ( typeId )) ; 1701default : 1702assert ( 0 ) ; 1703return NoResult ; 1704} 1705} 1706 1707// Return the type of 'member' of a composite. 1708Id Builder :: getContainedTypeId ( Id typeId , int member ) const 1709{ 1710Instruction * instr = module . getInstruction ( typeId ) ; 1711 1712Op typeClass = instr -> getOpCode () ; 1713switch ( typeClass ) 1714{ 1715case Op :: OpTypeVector : 1716case Op :: OpTypeMatrix : 1717case Op :: OpTypeArray : 1718case Op :: OpTypeRuntimeArray : 1719case Op :: OpTypeCooperativeMatrixKHR : 1720case Op :: OpTypeCooperativeMatrixNV : 1721case Op :: OpTypeCooperativeVectorNV : 1722return instr -> getIdOperand ( 0 ) ; 1723case Op :: OpTypePointer : 1724return instr -> getIdOperand ( 1 ) ; 1725case Op :: OpTypeStruct : 1726return instr -> getIdOperand ( member ) ; 1727default : 1728assert ( 0 ) ; 1729return NoResult ; 1730} 1731} 1732 1733// Figure out the final resulting type of the access chain. 1734Id Builder :: getResultingAccessChainType () const 1735{ 1736assert ( accessChain . base != NoResult ) ; 1737Id typeId = getTypeId ( accessChain . base ) ; 1738 1739assert ( isPointerType ( typeId )) ; 1740typeId = getContainedTypeId ( typeId ) ; 1741 1742for ( int i = 0 ; i < ( int ) accessChain . indexChain . size () ; ++ i ) { 1743if ( isStructType ( typeId )) { 1744assert ( isConstantScalar ( accessChain . indexChain [ i ])) ; 1745typeId = getContainedTypeId ( typeId , getConstantScalar ( accessChain . indexChain [ i ])) ; 1746} else 1747typeId = getContainedTypeId ( typeId , accessChain . indexChain [ i ]) ; 1748} 1749 1750return typeId ; 1751} 1752 1753// Return the immediately contained type of a given composite type. 1754Id Builder :: getContainedTypeId ( Id typeId ) const 1755{ 1756return getContainedTypeId ( typeId , 0 ) ; 1757} 1758 1759// Returns true if 'typeId' is or contains a scalar type declared with 'typeOp' 1760// of width 'width'. The 'width' is only consumed for int and float types. 1761// Returns false otherwise. 1762bool Builder :: containsType ( Id typeId , spv :: Op typeOp , unsigned int width ) const 1763{ 1764const Instruction & instr = * module . getInstruction ( typeId ) ; 1765 1766Op typeClass = instr . getOpCode () ; 1767switch ( typeClass ) 1768{ 1769case Op :: OpTypeInt : 1770case Op :: OpTypeFloat : 1771return typeClass == typeOp && instr . getImmediateOperand ( 0 ) == width ; 1772case Op :: OpTypeStruct : 1773for ( int m = 0 ; m < instr . getNumOperands () ; ++ m ) { 1774if ( containsType ( instr . getIdOperand ( m ) , typeOp , width )) 1775return true ; 1776} 1777return false ; 1778case Op :: OpTypePointer : 1779return false ; 1780case Op :: OpTypeVector : 1781case Op :: OpTypeMatrix : 1782case Op :: OpTypeArray : 1783case Op :: OpTypeRuntimeArray : 1784return containsType ( getContainedTypeId ( typeId ) , typeOp , width ) ; 1785default : 1786return typeClass == typeOp ; 1787} 1788} 1789 1790// return true if the type is a pointer to PhysicalStorageBufferEXT or an 1791// contains such a pointer. These require restrict/aliased decorations. 1792bool Builder :: containsPhysicalStorageBufferOrArray ( Id typeId ) const 1793{ 1794const Instruction & instr = * module . getInstruction ( typeId ) ; 1795 1796Op typeClass = instr . getOpCode () ; 1797switch ( typeClass ) 1798{ 1799case Op :: OpTypePointer : 1800return getTypeStorageClass ( typeId ) == StorageClass :: PhysicalStorageBufferEXT ; 1801case Op :: OpTypeArray : 1802return containsPhysicalStorageBufferOrArray ( getContainedTypeId ( typeId )) ; 1803case Op :: OpTypeStruct : 1804for ( int m = 0 ; m < instr . getNumOperands () ; ++ m ) { 1805if ( containsPhysicalStorageBufferOrArray ( instr . getIdOperand ( m ))) 1806return true ; 1807} 1808return false ; 1809default : 1810return false ; 1811} 1812} 1813 1814// See if a scalar constant of this type has already been created, so it 1815// can be reused rather than duplicated. (Required by the specification). 1816Id Builder :: findScalarConstant ( Op typeClass , Op opcode , Id typeId , unsigned value ) 1817{ 1818ScalarConstantKey key { enumCast ( typeClass ) , enumCast ( opcode ) , typeId , value , 0 } ; 1819auto it = groupedScalarConstantResultIDs . find ( key ) ; 1820return ( it != groupedScalarConstantResultIDs . end ()) ? it -> second : 0 ; 1821} 1822 1823// Version of findScalarConstant (see above) for scalars that take two operands (e.g. a 'double' or 'int64'). 1824Id Builder :: findScalarConstant ( Op typeClass , Op opcode , Id typeId , unsigned v1 , unsigned v2 ) 1825{ 1826ScalarConstantKey key { enumCast ( typeClass ) , enumCast ( opcode ) , typeId , v1 , v2 } ; 1827auto it = groupedScalarConstantResultIDs . find ( key ) ; 1828return ( it != groupedScalarConstantResultIDs . end ()) ? it -> second : 0 ; 1829} 1830 1831// Return true if consuming 'opcode' means consuming a constant. 1832// "constant" here means after final transform to executable code, 1833// the value consumed will be a constant, so includes specialization. 1834bool Builder :: isConstantOpCode ( Op opcode ) const 1835{ 1836switch ( opcode ) { 1837case Op :: OpUndef : 1838case Op :: OpConstantTrue : 1839case Op :: OpConstantFalse : 1840case Op :: OpConstant : 1841case Op :: OpConstantDataKHR : 1842case Op :: OpConstantComposite : 1843case Op :: OpConstantCompositeReplicateEXT : 1844case Op :: OpConstantSampler : 1845case Op :: OpConstantNull : 1846case Op :: OpSpecConstantTrue : 1847case Op :: OpSpecConstantFalse : 1848case Op :: OpSpecConstant : 1849case Op :: OpSpecConstantComposite : 1850case Op :: OpSpecConstantCompositeReplicateEXT : 1851case Op :: OpSpecConstantDataKHR : 1852case Op :: OpSpecConstantOp : 1853case Op :: OpConstantSizeOfEXT : 1854return true ; 1855default : 1856return false ; 1857} 1858} 1859 1860// Return true if consuming 'opcode' means consuming a specialization constant. 1861bool Builder :: isSpecConstantOpCode ( Op opcode ) const 1862{ 1863switch ( opcode ) { 1864case Op :: OpSpecConstantTrue : 1865case Op :: OpSpecConstantFalse : 1866case Op :: OpSpecConstant : 1867case Op :: OpSpecConstantComposite : 1868case Op :: OpSpecConstantDataKHR : 1869case Op :: OpSpecConstantOp : 1870case Op :: OpSpecConstantCompositeReplicateEXT : 1871return true ; 1872default : 1873return false ; 1874} 1875} 1876 1877Id Builder :: makeNullConstant ( Id typeId ) 1878{ 1879Instruction * constant ; 1880 1881// See if we already made it. 1882Id existing = NoResult ; 1883for ( int i = 0 ; i < ( int ) nullConstants . size () ; ++ i ) { 1884constant = nullConstants [ i ] ; 1885if ( constant -> getTypeId () == typeId ) 1886existing = constant -> getResultId () ; 1887} 1888 1889if ( existing != NoResult ) 1890return existing ; 1891 1892// Make it 1893Instruction * c = new Instruction ( getUniqueId () , typeId , Op :: OpConstantNull ) ; 1894constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 1895nullConstants . push_back ( c ) ; 1896module . mapInstruction ( c ) ; 1897 1898return c -> getResultId () ; 1899} 1900 1901Id Builder :: makeBoolConstant ( bool b , bool specConstant ) 1902{ 1903Id typeId = makeBoolType () ; 1904Op opcode = specConstant ? ( b ? Op :: OpSpecConstantTrue : Op :: OpSpecConstantFalse ) : ( b ? Op :: OpConstantTrue : Op :: OpConstantFalse ) ; 1905 1906// See if we already made it. Applies only to regular constants, because specialization constants 1907// must remain distinct for the purpose of applying a SpecId decoration. 1908if ( ! specConstant ) { 1909Id existing = findScalarConstant ( Op :: OpTypeBool , opcode , typeId , 0 ) ; 1910if ( existing ) 1911return existing ; 1912} 1913 1914// Make it 1915Instruction * c = new Instruction ( getUniqueId () , typeId , opcode ) ; 1916constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 1917module . mapInstruction ( c ) ; 1918 1919Id resultId = c -> getResultId () ; 1920if ( ! specConstant ) { 1921ScalarConstantKey key { enumCast ( Op :: OpTypeBool ) , enumCast ( opcode ) , typeId , 0 , 0 } ; 1922groupedScalarConstantResultIDs [ key ] = resultId ; 1923} 1924return resultId ; 1925} 1926 1927Id Builder :: makeIntConstant ( Id typeId , unsigned value , bool specConstant ) 1928{ 1929Op opcode = specConstant ? Op :: OpSpecConstant : Op :: OpConstant ; 1930 1931// See if we already made it. Applies only to regular constants, because specialization constants 1932// must remain distinct for the purpose of applying a SpecId decoration. 1933if ( ! specConstant ) { 1934Id existing = findScalarConstant ( Op :: OpTypeInt , opcode , typeId , value ) ; 1935if ( existing ) 1936return existing ; 1937} 1938 1939Instruction * c = new Instruction ( getUniqueId () , typeId , opcode ) ; 1940c -> addImmediateOperand ( value ) ; 1941constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 1942module . mapInstruction ( c ) ; 1943 1944Id resultId = c -> getResultId () ; 1945if ( ! specConstant ) { 1946ScalarConstantKey key { enumCast ( Op :: OpTypeInt ) , enumCast ( opcode ) , typeId , value , 0 } ; 1947groupedScalarConstantResultIDs [ key ] = resultId ; 1948} 1949return resultId ; 1950} 1951 1952Id Builder :: makeInt64Constant ( Id typeId , unsigned long long value , bool specConstant ) 1953{ 1954Op opcode = specConstant ? Op :: OpSpecConstant : Op :: OpConstant ; 1955 1956unsigned op1 = value & 0xFFFFFFFF ; 1957unsigned op2 = value >> 32 ; 1958 1959// See if we already made it. Applies only to regular constants, because specialization constants 1960// must remain distinct for the purpose of applying a SpecId decoration. 1961if ( ! specConstant ) { 1962Id existing = findScalarConstant ( Op :: OpTypeInt , opcode , typeId , op1 , op2 ) ; 1963if ( existing ) 1964return existing ; 1965} 1966 1967Instruction * c = new Instruction ( getUniqueId () , typeId , opcode ) ; 1968c -> reserveOperands ( 2 ) ; 1969c -> addImmediateOperand ( op1 ) ; 1970c -> addImmediateOperand ( op2 ) ; 1971constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 1972module . mapInstruction ( c ) ; 1973 1974Id resultId = c -> getResultId () ; 1975if ( ! specConstant ) { 1976ScalarConstantKey key { enumCast ( Op :: OpTypeInt ) , enumCast ( opcode ) , typeId , op1 , op2 } ; 1977groupedScalarConstantResultIDs [ key ] = resultId ; 1978} 1979return resultId ; 1980} 1981 1982Id Builder :: makeFloatConstant ( float f , bool specConstant ) 1983{ 1984Op opcode = specConstant ? Op :: OpSpecConstant : Op :: OpConstant ; 1985Id typeId = makeFloatType ( 32 ) ; 1986union { float fl ; unsigned int ui ; } u ; 1987u . fl = f ; 1988unsigned value = u . ui ; 1989 1990// See if we already made it. Applies only to regular constants, because specialization constants 1991// must remain distinct for the purpose of applying a SpecId decoration. 1992if ( ! specConstant ) { 1993Id existing = findScalarConstant ( Op :: OpTypeFloat , opcode , typeId , value ) ; 1994if ( existing ) 1995return existing ; 1996} 1997 1998Instruction * c = new Instruction ( getUniqueId () , typeId , opcode ) ; 1999c -> addImmediateOperand ( value ) ; 2000constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 2001module . mapInstruction ( c ) ; 2002 2003Id resultId = c -> getResultId () ; 2004if ( ! specConstant ) { 2005ScalarConstantKey key { enumCast ( Op :: OpTypeFloat ) , enumCast ( opcode ) , typeId , value , 0 } ; 2006groupedScalarConstantResultIDs [ key ] = resultId ; 2007} 2008return resultId ; 2009} 2010 2011Id Builder :: makeDoubleConstant ( double d , bool specConstant ) 2012{ 2013Op opcode = specConstant ? Op :: OpSpecConstant : Op :: OpConstant ; 2014Id typeId = makeFloatType ( 64 ) ; 2015union { double db ; unsigned long long ull ; } u ; 2016u . db = d ; 2017unsigned long long value = u . ull ; 2018unsigned op1 = value & 0xFFFFFFFF ; 2019unsigned op2 = value >> 32 ; 2020 2021// See if we already made it. Applies only to regular constants, because specialization constants 2022// must remain distinct for the purpose of applying a SpecId decoration. 2023if ( ! specConstant ) { 2024Id existing = findScalarConstant ( Op :: OpTypeFloat , opcode , typeId , op1 , op2 ) ; 2025if ( existing ) 2026return existing ; 2027} 2028 2029Instruction * c = new Instruction ( getUniqueId () , typeId , opcode ) ; 2030c -> reserveOperands ( 2 ) ; 2031c -> addImmediateOperand ( op1 ) ; 2032c -> addImmediateOperand ( op2 ) ; 2033constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 2034module . mapInstruction ( c ) ; 2035 2036Id resultId = c -> getResultId () ; 2037if ( ! specConstant ) { 2038ScalarConstantKey key { enumCast ( Op :: OpTypeFloat ) , enumCast ( opcode ) , typeId , op1 , op2 } ; 2039groupedScalarConstantResultIDs [ key ] = resultId ; 2040} 2041return resultId ; 2042} 2043 2044Id Builder :: makeFloat16Constant ( float f16 , bool specConstant ) 2045{ 2046Op opcode = specConstant ? Op :: OpSpecConstant : Op :: OpConstant ; 2047Id typeId = makeFloatType ( 16 ) ; 2048 2049spvutils :: HexFloat < spvutils :: FloatProxy < float >> fVal ( f16 ) ; 2050spvutils :: HexFloat < spvutils :: FloatProxy < spvutils :: Float16 >> f16Val ( 0 ) ; 2051fVal . castTo ( f16Val , spvutils :: kRoundToZero ) ; 2052 2053unsigned value = f16Val . value () . getAsFloat () . get_value () ; 2054 2055// See if we already made it. Applies only to regular constants, because specialization constants 2056// must remain distinct for the purpose of applying a SpecId decoration. 2057if ( ! specConstant ) { 2058Id existing = findScalarConstant ( Op :: OpTypeFloat , opcode , typeId , value ) ; 2059if ( existing ) 2060return existing ; 2061} 2062 2063Instruction * c = new Instruction ( getUniqueId () , typeId , opcode ) ; 2064c -> addImmediateOperand ( value ) ; 2065constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 2066module . mapInstruction ( c ) ; 2067 2068Id resultId = c -> getResultId () ; 2069if ( ! specConstant ) { 2070ScalarConstantKey key { enumCast ( Op :: OpTypeFloat ) , enumCast ( opcode ) , typeId , value , 0 } ; 2071groupedScalarConstantResultIDs [ key ] = resultId ; 2072} 2073return resultId ; 2074} 2075 2076Id Builder :: makeBFloat16Constant ( float bf16 , bool specConstant ) 2077{ 2078Op opcode = specConstant ? Op :: OpSpecConstant : Op :: OpConstant ; 2079Id typeId = makeBFloat16Type () ; 2080 2081union { 2082float f ; 2083uint32_t u ; 2084} un ; 2085un . f = bf16 ; 2086 2087// take high 16b of fp32 value. This is effectively round-to-zero, other than certain NaNs. 2088unsigned value = un . u >> 16 ; 2089 2090// See if we already made it. Applies only to regular constants, because specialization constants 2091// must remain distinct for the purpose of applying a SpecId decoration. 2092if ( ! specConstant ) { 2093Id existing = findScalarConstant ( Op :: OpTypeFloat , opcode , typeId , value ) ; 2094if ( existing ) 2095return existing ; 2096} 2097 2098Instruction * c = new Instruction ( getUniqueId () , typeId , opcode ) ; 2099c -> addImmediateOperand ( value ) ; 2100constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 2101module . mapInstruction ( c ) ; 2102 2103Id resultId = c -> getResultId () ; 2104if ( ! specConstant ) { 2105ScalarConstantKey key { enumCast ( Op :: OpTypeFloat ) , enumCast ( opcode ) , typeId , value , 0 } ; 2106groupedScalarConstantResultIDs [ key ] = resultId ; 2107} 2108return resultId ; 2109} 2110 2111Id Builder :: makeFloatE5M2Constant ( float fe5m2 , bool specConstant ) 2112{ 2113Op opcode = specConstant ? Op :: OpSpecConstant : Op :: OpConstant ; 2114Id typeId = makeFloatE5M2Type () ; 2115 2116spvutils :: HexFloat < spvutils :: FloatProxy < float >> fVal ( fe5m2 ) ; 2117spvutils :: HexFloat < spvutils :: FloatProxy < spvutils :: FloatE5M2 >> fe5m2Val ( 0 ) ; 2118fVal . castTo ( fe5m2Val , spvutils :: kRoundToZero ) ; 2119 2120unsigned value = fe5m2Val . value () . getAsFloat () . get_value () ; 2121 2122// See if we already made it. Applies only to regular constants, because specialization constants 2123// must remain distinct for the purpose of applying a SpecId decoration. 2124if ( ! specConstant ) { 2125Id existing = findScalarConstant ( Op :: OpTypeFloat , opcode , typeId , value ) ; 2126if ( existing ) 2127return existing ; 2128} 2129 2130Instruction * c = new Instruction ( getUniqueId () , typeId , opcode ) ; 2131c -> addImmediateOperand ( value ) ; 2132constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 2133module . mapInstruction ( c ) ; 2134 2135Id resultId = c -> getResultId () ; 2136if ( ! specConstant ) { 2137ScalarConstantKey key { enumCast ( Op :: OpTypeFloat ) , enumCast ( opcode ) , typeId , value , 0 } ; 2138groupedScalarConstantResultIDs [ key ] = resultId ; 2139} 2140return resultId ; 2141} 2142 2143Id Builder :: makeFloatE4M3Constant ( float fe4m3 , bool specConstant ) 2144{ 2145Op opcode = specConstant ? Op :: OpSpecConstant : Op :: OpConstant ; 2146Id typeId = makeFloatE4M3Type () ; 2147 2148spvutils :: HexFloat < spvutils :: FloatProxy < float >> fVal ( fe4m3 ) ; 2149spvutils :: HexFloat < spvutils :: FloatProxy < spvutils :: FloatE4M3 >> fe4m3Val ( 0 ) ; 2150fVal . castTo ( fe4m3Val , spvutils :: kRoundToZero ) ; 2151 2152unsigned value = fe4m3Val . value () . getAsFloat () . get_value () ; 2153 2154// See if we already made it. Applies only to regular constants, because specialization constants 2155// must remain distinct for the purpose of applying a SpecId decoration. 2156if ( ! specConstant ) { 2157Id existing = findScalarConstant ( Op :: OpTypeFloat , opcode , typeId , value ) ; 2158if ( existing ) 2159return existing ; 2160} 2161 2162Instruction * c = new Instruction ( getUniqueId () , typeId , opcode ) ; 2163c -> addImmediateOperand ( value ) ; 2164constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 2165module . mapInstruction ( c ) ; 2166 2167Id resultId = c -> getResultId () ; 2168if ( ! specConstant ) { 2169ScalarConstantKey key { enumCast ( Op :: OpTypeFloat ) , enumCast ( opcode ) , typeId , value , 0 } ; 2170groupedScalarConstantResultIDs [ key ] = resultId ; 2171} 2172return resultId ; 2173} 2174 2175Id Builder :: makeFpConstant ( Id type , double d , bool specConstant ) 2176{ 2177const int width = getScalarTypeWidth ( type ) ; 2178 2179assert ( isFloatType ( type )) ; 2180 2181switch ( width ) { 2182case 16 : 2183return makeFloat16Constant (( float ) d , specConstant ) ; 2184case 32 : 2185return makeFloatConstant (( float ) d , specConstant ) ; 2186case 64 : 2187return makeDoubleConstant ( d , specConstant ) ; 2188default : 2189break ; 2190} 2191 2192assert ( false ) ; 2193return NoResult ; 2194} 2195 2196Id Builder :: importNonSemanticShaderDebugInfoInstructions () 2197{ 2198assert ( emitNonSemanticShaderDebugInfo == true ) ; 2199 2200if ( nonSemanticShaderDebugInfo == 0 ) 2201{ 2202this -> addExtension ( spv :: E_SPV_KHR_non_semantic_info ) ; 2203// Create the import instruction directly so we can save a pointer for later 2204// patching by requireNonSemanticShaderDebugInfoVersion(). 2205std :: string importName = "NonSemantic.Shader.DebugInfo." + std :: to_string ( nonSemanticShaderDebugInfoVersion ) ; 2206auto * importInst = new Instruction ( getUniqueId () , NoType , Op :: OpExtInstImport ) ; 2207importInst -> addStringOperand ( importName . c_str ()) ; 2208module . mapInstruction ( importInst ) ; 2209imports . push_back ( std :: unique_ptr < Instruction > ( importInst )) ; 2210nonSemanticShaderDebugInfo = importInst -> getResultId () ; 2211nonSemanticShaderDebugInfoImportInst = importInst ; 2212} 2213 2214return nonSemanticShaderDebugInfo ; 2215} 2216 2217void Builder :: requireNonSemanticShaderDebugInfoVersion ( unsigned version ) 2218{ 2219if ( nonSemanticShaderDebugInfoVersion >= version ) 2220return ; 2221nonSemanticShaderDebugInfoVersion = version ; 2222if ( nonSemanticShaderDebugInfoImportInst != nullptr ) { 2223// The import instruction was already emitted with an older version string. 2224// Rebuild the string operands in place so all referencing OpExtInst instructions 2225// automatically pick up the new name without needing new IDs. 2226std :: string importName = "NonSemantic.Shader.DebugInfo." + std :: to_string ( version ) ; 2227nonSemanticShaderDebugInfoImportInst -> clearOperands () ; 2228nonSemanticShaderDebugInfoImportInst -> addStringOperand ( importName . c_str ()) ; 2229} 2230} 2231 2232Id Builder :: findCompositeConstant ( Op typeClass , Op opcode , Id typeId , const std :: vector < Id >& comps , size_t numMembers ) 2233{ 2234Instruction * constant = nullptr ; 2235bool found = false ; 2236for ( int i = 0 ; i < ( int ) groupedCompositeConstants [ enumCast ( typeClass )] . size () ; ++ i ) { 2237constant = groupedCompositeConstants [ enumCast ( typeClass )][ i ] ; 2238 2239if ( constant -> getTypeId () != typeId ) 2240continue ; 2241 2242if ( constant -> getOpCode () != opcode ) { 2243continue ; 2244} 2245 2246if ( constant -> getNumOperands () != ( int ) numMembers ) 2247continue ; 2248 2249// same contents? 2250bool mismatch = false ; 2251for ( int op = 0 ; op < constant -> getNumOperands () ; ++ op ) { 2252if ( constant -> getIdOperand ( op ) != comps [ op ]) { 2253mismatch = true ; 2254break ; 2255} 2256} 2257if ( ! mismatch ) { 2258found = true ; 2259break ; 2260} 2261} 2262 2263return found ? constant -> getResultId () : NoResult ; 2264} 2265 2266Id Builder :: findStructConstant ( Id typeId , const std :: vector < Id >& comps ) 2267{ 2268Instruction * constant = nullptr ; 2269bool found = false ; 2270for ( int i = 0 ; i < ( int ) groupedStructConstants [ typeId ] . size () ; ++ i ) { 2271constant = groupedStructConstants [ typeId ][ i ] ; 2272 2273// same contents? 2274bool mismatch = false ; 2275for ( int op = 0 ; op < constant -> getNumOperands () ; ++ op ) { 2276if ( constant -> getIdOperand ( op ) != comps [ op ]) { 2277mismatch = true ; 2278break ; 2279} 2280} 2281if ( ! mismatch ) { 2282found = true ; 2283break ; 2284} 2285} 2286 2287return found ? constant -> getResultId () : NoResult ; 2288} 2289 2290// Comments in header 2291Id Builder :: makeCompositeConstant ( Id typeId , const std :: vector < Id >& members , bool specConstant ) 2292{ 2293assert ( typeId ) ; 2294Op typeClass = getTypeClass ( typeId ) ; 2295 2296bool replicate = false ; 2297size_t numMembers = members . size () ; 2298if ( useReplicatedComposites || typeClass == Op :: OpTypeCooperativeVectorNV ) { 2299// use replicate if all members are the same 2300replicate = numMembers > 0 && 2301std :: equal ( members . begin () + 1 , members . end () , members . begin ()) ; 2302 2303if ( replicate ) { 2304numMembers = 1 ; 2305addCapability ( spv :: Capability :: ReplicatedCompositesEXT ) ; 2306addExtension ( spv :: E_SPV_EXT_replicated_composites ) ; 2307} 2308} 2309 2310Op opcode = replicate ? 2311( specConstant ? Op :: OpSpecConstantCompositeReplicateEXT : Op :: OpConstantCompositeReplicateEXT ) : 2312( specConstant ? Op :: OpSpecConstantComposite : Op :: OpConstantComposite ) ; 2313 2314switch ( typeClass ) { 2315case Op :: OpTypeVector : 2316case Op :: OpTypeArray : 2317case Op :: OpTypeMatrix : 2318case Op :: OpTypeCooperativeMatrixKHR : 2319case Op :: OpTypeCooperativeMatrixNV : 2320case Op :: OpTypeCooperativeVectorNV : 2321if ( ! specConstant ) { 2322Id existing = findCompositeConstant ( typeClass , opcode , typeId , members , numMembers ) ; 2323if ( existing ) 2324return existing ; 2325} 2326break ; 2327case Op :: OpTypeStruct : 2328if ( ! specConstant ) { 2329Id existing = findStructConstant ( typeId , members ) ; 2330if ( existing ) 2331return existing ; 2332} 2333break ; 2334default : 2335assert ( 0 ) ; 2336return makeFloatConstant ( 0.0 ) ; 2337} 2338 2339Instruction * c = new Instruction ( getUniqueId () , typeId , opcode ) ; 2340c -> reserveOperands ( members . size ()) ; 2341for ( size_t op = 0 ; op < numMembers ; ++ op ) 2342c -> addIdOperand ( members [ op ]) ; 2343constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( c )) ; 2344if ( typeClass == Op :: OpTypeStruct ) 2345groupedStructConstants [ typeId ] . push_back ( c ) ; 2346else 2347groupedCompositeConstants [ enumCast ( typeClass )] . push_back ( c ) ; 2348module . mapInstruction ( c ) ; 2349 2350return c -> getResultId () ; 2351} 2352 2353Instruction * Builder :: addEntryPoint ( ExecutionModel model , Function * function , const char * name ) 2354{ 2355Instruction * entryPoint = new Instruction ( Op :: OpEntryPoint ) ; 2356entryPoint -> reserveOperands ( 3 ) ; 2357entryPoint -> addImmediateOperand ( model ) ; 2358entryPoint -> addIdOperand ( function -> getId ()) ; 2359entryPoint -> addStringOperand ( name ) ; 2360 2361entryPoints . push_back ( std :: unique_ptr < Instruction > ( entryPoint )) ; 2362 2363return entryPoint ; 2364} 2365 2366// Currently relying on the fact that all 'value' of interest are small non-negative values. 2367void Builder :: addExecutionMode ( Function * entryPoint , ExecutionMode mode , int value1 , int value2 , int value3 ) 2368{ 2369// entryPoint can be null if we are in compile-only mode 2370if ( ! entryPoint ) 2371return ; 2372 2373Instruction * instr = new Instruction ( Op :: OpExecutionMode ) ; 2374instr -> reserveOperands ( 3 ) ; 2375instr -> addIdOperand ( entryPoint -> getId ()) ; 2376instr -> addImmediateOperand ( mode ) ; 2377if ( value1 >= 0 ) 2378instr -> addImmediateOperand ( value1 ) ; 2379if ( value2 >= 0 ) 2380instr -> addImmediateOperand ( value2 ) ; 2381if ( value3 >= 0 ) 2382instr -> addImmediateOperand ( value3 ) ; 2383 2384executionModes . push_back ( std :: unique_ptr < Instruction > ( instr )) ; 2385} 2386 2387void Builder :: addExecutionMode ( Function * entryPoint , ExecutionMode mode , const std :: vector < unsigned >& literals ) 2388{ 2389// entryPoint can be null if we are in compile-only mode 2390if ( ! entryPoint ) 2391return ; 2392 2393Instruction * instr = new Instruction ( Op :: OpExecutionMode ) ; 2394instr -> reserveOperands ( literals . size () + 2 ) ; 2395instr -> addIdOperand ( entryPoint -> getId ()) ; 2396instr -> addImmediateOperand ( mode ) ; 2397for ( auto literal : literals ) 2398instr -> addImmediateOperand ( literal ) ; 2399 2400executionModes . push_back ( std :: unique_ptr < Instruction > ( instr )) ; 2401} 2402 2403void Builder :: addExecutionModeId ( Function * entryPoint , ExecutionMode mode , const std :: vector < Id >& operandIds ) 2404{ 2405// entryPoint can be null if we are in compile-only mode 2406if ( ! entryPoint ) 2407return ; 2408 2409Instruction * instr = new Instruction ( Op :: OpExecutionModeId ) ; 2410instr -> reserveOperands ( operandIds . size () + 2 ) ; 2411instr -> addIdOperand ( entryPoint -> getId ()) ; 2412instr -> addImmediateOperand ( mode ) ; 2413for ( auto operandId : operandIds ) 2414instr -> addIdOperand ( operandId ) ; 2415 2416executionModes . push_back ( std :: unique_ptr < Instruction > ( instr )) ; 2417} 2418 2419void Builder :: addName ( Id id , const char * string ) 2420{ 2421Instruction * name = new Instruction ( Op :: OpName ) ; 2422name -> reserveOperands ( 2 ) ; 2423name -> addIdOperand ( id ) ; 2424name -> addStringOperand ( string ) ; 2425 2426names . push_back ( std :: unique_ptr < Instruction > ( name )) ; 2427} 2428 2429void Builder :: addMemberName ( Id id , int memberNumber , const char * string ) 2430{ 2431Instruction * name = new Instruction ( Op :: OpMemberName ) ; 2432name -> reserveOperands ( 3 ) ; 2433name -> addIdOperand ( id ) ; 2434name -> addImmediateOperand ( memberNumber ) ; 2435name -> addStringOperand ( string ) ; 2436 2437names . push_back ( std :: unique_ptr < Instruction > ( name )) ; 2438} 2439 2440void Builder :: addDecoration ( Id id , Decoration decoration , int num ) 2441{ 2442if ( decoration == spv :: Decoration :: Max ) 2443return ; 2444 2445Instruction * dec = new Instruction ( Op :: OpDecorate ) ; 2446dec -> reserveOperands ( 2 ) ; 2447dec -> addIdOperand ( id ) ; 2448dec -> addImmediateOperand ( decoration ) ; 2449if ( num >= 0 ) 2450dec -> addImmediateOperand ( num ) ; 2451 2452decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2453} 2454 2455void Builder :: addDecoration ( Id id , Decoration decoration , const char * s ) 2456{ 2457if ( decoration == spv :: Decoration :: Max ) 2458return ; 2459 2460Instruction * dec = new Instruction ( Op :: OpDecorateString ) ; 2461dec -> reserveOperands ( 3 ) ; 2462dec -> addIdOperand ( id ) ; 2463dec -> addImmediateOperand ( decoration ) ; 2464dec -> addStringOperand ( s ) ; 2465 2466decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2467} 2468 2469void Builder :: addDecoration ( Id id , Decoration decoration , const std :: vector < unsigned >& literals ) 2470{ 2471if ( decoration == spv :: Decoration :: Max ) 2472return ; 2473 2474Instruction * dec = new Instruction ( Op :: OpDecorate ) ; 2475dec -> reserveOperands ( literals . size () + 2 ) ; 2476dec -> addIdOperand ( id ) ; 2477dec -> addImmediateOperand ( decoration ) ; 2478for ( auto literal : literals ) 2479dec -> addImmediateOperand ( literal ) ; 2480 2481decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2482} 2483 2484void Builder :: addDecoration ( Id id , Decoration decoration , const std :: vector < const char *>& strings ) 2485{ 2486if ( decoration == spv :: Decoration :: Max ) 2487return ; 2488 2489Instruction * dec = new Instruction ( Op :: OpDecorateString ) ; 2490dec -> reserveOperands ( strings . size () + 2 ) ; 2491dec -> addIdOperand ( id ) ; 2492dec -> addImmediateOperand ( decoration ) ; 2493for ( auto string : strings ) 2494dec -> addStringOperand ( string ) ; 2495 2496decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2497} 2498 2499void Builder :: addLinkageDecoration ( Id id , const char * name , spv :: LinkageType linkType ) { 2500Instruction * dec = new Instruction ( Op :: OpDecorate ) ; 2501dec -> reserveOperands ( 4 ) ; 2502dec -> addIdOperand ( id ) ; 2503dec -> addImmediateOperand ( spv :: Decoration :: LinkageAttributes ) ; 2504dec -> addStringOperand ( name ) ; 2505dec -> addImmediateOperand ( linkType ) ; 2506 2507decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2508} 2509 2510void Builder :: addDecorationId ( Id id , Decoration decoration , Id idDecoration ) 2511{ 2512if ( decoration == spv :: Decoration :: Max ) 2513return ; 2514 2515Instruction * dec = new Instruction ( Op :: OpDecorateId ) ; 2516dec -> reserveOperands ( 3 ) ; 2517dec -> addIdOperand ( id ) ; 2518dec -> addImmediateOperand ( decoration ) ; 2519dec -> addIdOperand ( idDecoration ) ; 2520 2521decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2522} 2523 2524void Builder :: addDecorationId ( Id id , Decoration decoration , const std :: vector < Id >& operandIds ) 2525{ 2526if ( decoration == spv :: Decoration :: Max ) 2527return ; 2528 2529Instruction * dec = new Instruction ( Op :: OpDecorateId ) ; 2530dec -> reserveOperands ( operandIds . size () + 2 ) ; 2531dec -> addIdOperand ( id ) ; 2532dec -> addImmediateOperand ( decoration ) ; 2533 2534for ( auto operandId : operandIds ) 2535dec -> addIdOperand ( operandId ) ; 2536 2537decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2538} 2539 2540void Builder :: addMemberDecorationIdEXT ( Id id , unsigned int member , Decoration decoration , 2541const std :: vector < unsigned >& operands ) 2542{ 2543if ( decoration == spv :: Decoration :: Max ) 2544return ; 2545 2546Instruction * dec = new Instruction ( Op :: OpMemberDecorateIdEXT ) ; 2547dec -> reserveOperands ( operands . size () + 3 ) ; 2548dec -> addIdOperand ( id ) ; 2549dec -> addImmediateOperand ( member ) ; 2550dec -> addImmediateOperand ( decoration ) ; 2551for ( auto operand : operands ) 2552dec -> addIdOperand ( operand ) ; 2553 2554decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2555} 2556 2557void Builder :: addMemberDecoration ( Id id , unsigned int member , Decoration decoration , int num ) 2558{ 2559if ( decoration == spv :: Decoration :: Max ) 2560return ; 2561 2562Instruction * dec = new Instruction ( Op :: OpMemberDecorate ) ; 2563dec -> reserveOperands ( 3 ) ; 2564dec -> addIdOperand ( id ) ; 2565dec -> addImmediateOperand ( member ) ; 2566dec -> addImmediateOperand ( decoration ) ; 2567if ( num >= 0 ) 2568dec -> addImmediateOperand ( num ) ; 2569 2570decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2571} 2572 2573void Builder :: addMemberDecoration ( Id id , unsigned int member , Decoration decoration , const char * s ) 2574{ 2575if ( decoration == spv :: Decoration :: Max ) 2576return ; 2577 2578Instruction * dec = new Instruction ( Op :: OpMemberDecorateStringGOOGLE ) ; 2579dec -> reserveOperands ( 4 ) ; 2580dec -> addIdOperand ( id ) ; 2581dec -> addImmediateOperand ( member ) ; 2582dec -> addImmediateOperand ( decoration ) ; 2583dec -> addStringOperand ( s ) ; 2584 2585decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2586} 2587 2588void Builder :: addMemberDecoration ( Id id , unsigned int member , Decoration decoration , const std :: vector < unsigned >& literals ) 2589{ 2590if ( decoration == spv :: Decoration :: Max ) 2591return ; 2592 2593Instruction * dec = new Instruction ( Op :: OpMemberDecorate ) ; 2594dec -> reserveOperands ( literals . size () + 3 ) ; 2595dec -> addIdOperand ( id ) ; 2596dec -> addImmediateOperand ( member ) ; 2597dec -> addImmediateOperand ( decoration ) ; 2598for ( auto literal : literals ) 2599dec -> addImmediateOperand ( literal ) ; 2600 2601decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2602} 2603 2604void Builder :: addMemberDecoration ( Id id , unsigned int member , Decoration decoration , const std :: vector < const char *>& strings ) 2605{ 2606if ( decoration == spv :: Decoration :: Max ) 2607return ; 2608 2609Instruction * dec = new Instruction ( Op :: OpMemberDecorateString ) ; 2610dec -> reserveOperands ( strings . size () + 3 ) ; 2611dec -> addIdOperand ( id ) ; 2612dec -> addImmediateOperand ( member ) ; 2613dec -> addImmediateOperand ( decoration ) ; 2614for ( auto string : strings ) 2615dec -> addStringOperand ( string ) ; 2616 2617decorations . insert ( std :: unique_ptr < Instruction > ( dec )) ; 2618} 2619 2620void Builder :: addInstruction ( std :: unique_ptr < Instruction > inst ) { 2621// Phis must appear first in their block, don't insert line tracking instructions 2622// in front of them, just add the OpPhi and return. 2623if ( inst -> getOpCode () == Op :: OpPhi ) { 2624buildPoint -> addInstruction ( std :: move ( inst )) ; 2625return ; 2626} 2627// Optionally insert OpDebugScope 2628if ( emitNonSemanticShaderDebugInfo && dirtyScopeTracker ) { 2629if ( buildPoint -> updateDebugScope ( currentDebugScopeId . top ())) { 2630auto scopeInst = std :: make_unique < Instruction > ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 2631scopeInst -> reserveOperands ( 3 ) ; 2632scopeInst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 2633scopeInst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugScope ) ; 2634scopeInst -> addIdOperand ( currentDebugScopeId . top ()) ; 2635buildPoint -> addInstruction ( std :: move ( scopeInst )) ; 2636} 2637 2638dirtyScopeTracker = false ; 2639} 2640 2641// Insert OpLine/OpDebugLine if the debug source location has changed 2642if ( trackDebugInfo && dirtyLineTracker ) { 2643if ( buildPoint -> updateDebugSourceLocation ( currentLine , 0 , currentFileId )) { 2644if ( emitSpirvDebugInfo ) { 2645auto lineInst = std :: make_unique < Instruction > ( Op :: OpLine ) ; 2646lineInst -> reserveOperands ( 3 ) ; 2647lineInst -> addIdOperand ( currentFileId ) ; 2648lineInst -> addImmediateOperand ( currentLine ) ; 2649lineInst -> addImmediateOperand ( 0 ) ; 2650buildPoint -> addInstruction ( std :: move ( lineInst )) ; 2651} 2652if ( emitNonSemanticShaderDebugInfo ) { 2653auto lineInst = std :: make_unique < Instruction > ( getUniqueId () , makeVoidType () , Op :: OpExtInst ) ; 2654lineInst -> reserveOperands ( 7 ) ; 2655lineInst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 2656lineInst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugLine ) ; 2657lineInst -> addIdOperand ( makeDebugSource ( currentFileId )) ; 2658lineInst -> addIdOperand ( makeUintConstant ( currentLine )) ; 2659lineInst -> addIdOperand ( makeUintConstant ( currentLine )) ; 2660lineInst -> addIdOperand ( makeUintConstant ( 0 )) ; 2661lineInst -> addIdOperand ( makeUintConstant ( 0 )) ; 2662buildPoint -> addInstruction ( std :: move ( lineInst )) ; 2663} 2664} 2665 2666dirtyLineTracker = false ; 2667} 2668 2669buildPoint -> addInstruction ( std :: move ( inst )) ; 2670} 2671 2672void Builder :: addInstructionNoDebugInfo ( std :: unique_ptr < Instruction > inst ) { 2673buildPoint -> addInstruction ( std :: move ( inst )) ; 2674} 2675 2676// Comments in header 2677Function * Builder :: makeEntryPoint ( const char * entryPoint ) 2678{ 2679assert ( ! entryPointFunction ) ; 2680 2681auto const returnType = makeVoidType () ; 2682 2683restoreNonSemanticShaderDebugInfo = emitNonSemanticShaderDebugInfo ; 2684if ( sourceLang == spv :: SourceLanguage :: HLSL ) { 2685emitNonSemanticShaderDebugInfo = false ; 2686} 2687 2688Block * entry = nullptr ; 2689entryPointFunction = makeFunctionEntry ( NoPrecision , returnType , entryPoint , LinkageType :: Max , {} , {} , & entry ) ; 2690 2691emitNonSemanticShaderDebugInfo = restoreNonSemanticShaderDebugInfo ; 2692 2693return entryPointFunction ; 2694} 2695 2696// Comments in header 2697Function * Builder :: makeFunctionEntry ( Decoration precision , Id returnType , const char * name , LinkageType linkType , 2698const std :: vector < Id >& paramTypes , 2699const std :: vector < std :: vector < Decoration >>& decorations , Block ** entry ) 2700{ 2701// Make the function and initial instructions in it 2702Id typeId = makeFunctionType ( returnType , paramTypes ) ; 2703Id firstParamId = paramTypes . size () == 0 ? 0 : getUniqueIds (( int ) paramTypes . size ()) ; 2704Id funcId = getUniqueId () ; 2705Function * function = new Function ( funcId , returnType , typeId , firstParamId , linkType , name , module ) ; 2706 2707// Set up the precisions 2708setPrecision ( function -> getId () , precision ) ; 2709function -> setReturnPrecision ( precision ) ; 2710for ( unsigned p = 0 ; p < ( unsigned ) decorations . size () ; ++ p ) { 2711for ( int d = 0 ; d < ( int ) decorations [ p ] . size () ; ++ d ) { 2712addDecoration ( firstParamId + p , decorations [ p ][ d ]) ; 2713function -> addParamPrecision ( p , decorations [ p ][ d ]) ; 2714} 2715} 2716 2717// reset last debug scope 2718if ( emitNonSemanticShaderDebugInfo ) { 2719dirtyScopeTracker = true ; 2720} 2721 2722// CFG 2723assert ( entry != nullptr ) ; 2724* entry = new Block ( getUniqueId () , * function ) ; 2725function -> addBlock ( * entry ) ; 2726setBuildPoint ( * entry ) ; 2727 2728if ( name ) 2729addName ( function -> getId () , name ) ; 2730 2731functions . push_back ( std :: unique_ptr < Function > ( function )) ; 2732 2733return function ; 2734} 2735 2736void Builder :: setupFunctionDebugInfo ( Function * function , const char * name , const std :: vector < Id >& paramTypes , 2737const std :: vector < char const *>& paramNames ) 2738{ 2739 2740if ( ! emitNonSemanticShaderDebugInfo ) 2741return ; 2742 2743Id nameId = getStringId ( unmangleFunctionName ( name )) ; 2744Id funcTypeId = function -> getFuncTypeId () ; 2745assert ( getDebugType ( funcTypeId ) != NoType ) ; 2746Id funcId = function -> getId () ; 2747 2748assert ( funcId != 0 ) ; 2749 2750// Make the debug function instruction 2751Id debugFuncId = makeDebugFunction ( function , nameId , funcTypeId ) ; 2752debugFuncIdLookup [ funcId ] = debugFuncId ; 2753currentDebugScopeId . push ( debugFuncId ) ; 2754 2755// DebugScope and DebugLine for parameter DebugDeclares 2756assert ( paramTypes . size () == paramNames . size ()) ; 2757if (( int ) paramTypes . size () > 0 ) { 2758Id firstParamId = function -> getParamId ( 0 ) ; 2759 2760for ( size_t p = 0 ; p < paramTypes . size () ; ++ p ) { 2761bool passByRef = false ; 2762Id paramTypeId = paramTypes [ p ] ; 2763 2764// For pointer-typed parameters, they are actually passed by reference and we need unwrap the pointer to get the actual parameter type. 2765if ( isPointerType ( paramTypeId ) || isArrayType ( paramTypeId )) { 2766passByRef = true ; 2767paramTypeId = getContainedTypeId ( paramTypeId ) ; 2768} 2769 2770auto const & paramName = paramNames [ p ] ; 2771auto const debugLocalVariableId = createDebugLocalVariable ( getDebugType ( paramTypeId ) , paramName , p + 1 ) ; 2772auto const paramId = static_cast < Id > ( firstParamId + p ) ; 2773 2774if ( passByRef ) { 2775makeDebugDeclare ( debugLocalVariableId , paramId ) ; 2776} else { 2777makeDebugValue ( debugLocalVariableId , paramId ) ; 2778} 2779} 2780} 2781 2782// Clear debug scope stack 2783if ( emitNonSemanticShaderDebugInfo ) 2784currentDebugScopeId . pop () ; 2785} 2786 2787Id Builder :: makeDebugFunction ( [[ maybe_unused ]] Function * function , Id nameId , Id funcTypeId ) 2788{ 2789assert ( function != nullptr ) ; 2790assert ( nameId != 0 ) ; 2791assert ( funcTypeId != 0 ) ; 2792assert ( getDebugType ( funcTypeId ) != NoType ) ; 2793 2794Id funcId = getUniqueId () ; 2795auto type = new Instruction ( funcId , makeVoidType () , Op :: OpExtInst ) ; 2796type -> reserveOperands ( 11 ) ; 2797type -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 2798type -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugFunction ) ; 2799type -> addIdOperand ( nameId ) ; 2800type -> addIdOperand ( getDebugType ( funcTypeId )) ; 2801type -> addIdOperand ( makeDebugSource ( currentFileId )) ; // TODO: This points to file of definition instead of declaration 2802type -> addIdOperand ( makeUintConstant ( currentLine )) ; // TODO: This points to line of definition instead of declaration 2803type -> addIdOperand ( makeUintConstant ( 0 )) ; // column 2804type -> addIdOperand ( makeDebugCompilationUnit ()) ; // scope 2805type -> addIdOperand ( nameId ) ; // linkage name 2806type -> addIdOperand ( makeUintConstant ( NonSemanticShaderDebugInfoFlagIsPublic )) ; 2807type -> addIdOperand ( makeUintConstant ( currentLine )) ; 2808constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( type )) ; 2809module . mapInstruction ( type ) ; 2810return funcId ; 2811} 2812 2813Id Builder :: makeDebugLexicalBlock ( uint32_t line , uint32_t column ) { 2814assert ( ! currentDebugScopeId . empty ()) ; 2815 2816Id lexId = getUniqueId () ; 2817auto lex = new Instruction ( lexId , makeVoidType () , Op :: OpExtInst ) ; 2818lex -> reserveOperands ( 6 ) ; 2819lex -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 2820lex -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugLexicalBlock ) ; 2821lex -> addIdOperand ( makeDebugSource ( currentFileId )) ; 2822lex -> addIdOperand ( makeUintConstant ( line )) ; 2823lex -> addIdOperand ( makeUintConstant ( column )) ; // column 2824lex -> addIdOperand ( currentDebugScopeId . top ()) ; // scope 2825constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( lex )) ; 2826module . mapInstruction ( lex ) ; 2827return lexId ; 2828} 2829 2830std :: string Builder :: unmangleFunctionName ( std :: string const & name ) const 2831{ 2832assert ( name . length () > 0 ) ; 2833 2834if ( name . rfind ( '(' ) != std :: string :: npos ) { 2835return name . substr ( 0 , name . rfind ( '(' )) ; 2836} else { 2837return name ; 2838} 2839} 2840 2841// Comments in header 2842void Builder :: makeReturn ( bool implicit , Id retVal ) 2843{ 2844if ( retVal ) { 2845Instruction * inst = new Instruction ( NoResult , NoType , Op :: OpReturnValue ) ; 2846inst -> addIdOperand ( retVal ) ; 2847addInstruction ( std :: unique_ptr < Instruction > ( inst )) ; 2848} else 2849addInstruction ( std :: unique_ptr < Instruction > ( new Instruction ( NoResult , NoType , Op :: OpReturn ))) ; 2850 2851if ( ! implicit ) 2852createAndSetNoPredecessorBlock ( "post-return" ) ; 2853} 2854 2855// Comments in header 2856void Builder :: enterLexicalBlock ( uint32_t line , uint32_t column ) 2857{ 2858if ( ! emitNonSemanticShaderDebugInfo ) { 2859return ; 2860} 2861 2862// Generate new lexical scope debug instruction 2863Id lexId = makeDebugLexicalBlock ( line , column ) ; 2864currentDebugScopeId . push ( lexId ) ; 2865dirtyScopeTracker = true ; 2866} 2867 2868// Comments in header 2869void Builder :: leaveLexicalBlock () 2870{ 2871if ( ! emitNonSemanticShaderDebugInfo ) { 2872return ; 2873} 2874 2875// Pop current scope from stack and clear current scope 2876currentDebugScopeId . pop () ; 2877dirtyScopeTracker = true ; 2878} 2879 2880// Comments in header 2881void Builder :: enterFunction ( Function const * function ) 2882{ 2883currentFunction = function ; 2884 2885// Save and disable debugInfo for HLSL entry point function. It is a wrapper 2886// function with no user code in it. 2887restoreNonSemanticShaderDebugInfo = emitNonSemanticShaderDebugInfo ; 2888if ( sourceLang == spv :: SourceLanguage :: HLSL && function == entryPointFunction ) { 2889emitNonSemanticShaderDebugInfo = false ; 2890} 2891 2892if ( emitNonSemanticShaderDebugInfo ) { 2893// Initialize scope state 2894Id funcId = function -> getFuncId () ; 2895Id debugFuncId = getDebugFunction ( funcId ) ; 2896currentDebugScopeId . push ( debugFuncId ) ; 2897// Create DebugFunctionDefinition 2898spv :: Id resultId = getUniqueId () ; 2899Instruction * defInst = new Instruction ( resultId , makeVoidType () , Op :: OpExtInst ) ; 2900defInst -> reserveOperands ( 4 ) ; 2901defInst -> addIdOperand ( nonSemanticShaderDebugInfo ) ; 2902defInst -> addImmediateOperand ( NonSemanticShaderDebugInfoDebugFunctionDefinition ) ; 2903defInst -> addIdOperand ( debugFuncId ) ; 2904defInst -> addIdOperand ( funcId ) ; 2905addInstruction ( std :: unique_ptr < Instruction > ( defInst )) ; 2906} 2907 2908if ( auto linkType = function -> getLinkType () ; linkType != LinkageType :: Max ) { 2909Id funcId = function -> getFuncId () ; 2910addCapability ( Capability :: Linkage ) ; 2911addLinkageDecoration ( funcId , function -> getExportName () , linkType ) ; 2912} 2913} 2914 2915// Comments in header 2916void Builder :: leaveFunction () 2917{ 2918Block * block = buildPoint ; 2919Function & function = buildPoint -> getParent () ; 2920assert ( block ) ; 2921 2922// If our function did not contain a return, add a return void now. 2923if ( ! block -> isTerminated ()) { 2924if ( function . getReturnType () == makeVoidType ()) 2925makeReturn ( true ) ; 2926else { 2927makeReturn ( true , createUndefined ( function . getReturnType ())) ; 2928} 2929} 2930 2931// Clear function scope from debug scope stack 2932if ( emitNonSemanticShaderDebugInfo ) 2933currentDebugScopeId . pop () ; 2934 2935emitNonSemanticShaderDebugInfo = restoreNonSemanticShaderDebugInfo ; 2936 2937// Clear current function record 2938currentFunction = nullptr ; 2939} 2940 2941// Comments in header 2942void Builder :: makeStatementTerminator ( spv :: Op opcode , const char * name ) 2943{ 2944addInstruction ( std :: unique_ptr < Instruction > ( new Instruction ( opcode ))) ; 2945createAndSetNoPredecessorBlock ( name ) ; 2946} 2947 2948// Comments in header 2949void Builder :: makeStatementTerminator ( spv :: Op opcode , const std :: vector < Id >& operands , const char * name ) 2950{ 2951// It's assumed that the terminator instruction is always of void return type 2952// However in future if there is a need for non void return type, new helper 2953// methods can be created. 2954createNoResultOp ( opcode , operands ) ; 2955createAndSetNoPredecessorBlock ( name ) ; 2956} 2957 2958void Builder :: createConstVariable ( Id type , const char * name , Id constant , bool isGlobal ) 2959{ 2960if ( emitNonSemanticShaderDebugInfo ) { 2961Id debugType = getDebugType ( type ) ; 2962if ( isGlobal ) { 2963createDebugGlobalVariable ( debugType , name , constant ) ; 2964} 2965else { 2966auto debugLocal = createDebugLocalVariable ( debugType , name ) ; 2967makeDebugValue ( debugLocal , constant ) ; 2968} 2969} 2970} 2971 2972// Comments in header 2973Id Builder :: createUntypedVariable ( Decoration precision , StorageClass storageClass , const char * name , Id dataType , 2974Id initializer ) 2975{ 2976Id resultUntypedPointerType = makeUntypedPointer ( storageClass ) ; 2977Instruction * inst = new Instruction ( getUniqueId () , resultUntypedPointerType , Op :: OpUntypedVariableKHR ) ; 2978inst -> addImmediateOperand ( storageClass ) ; 2979if ( dataType != NoResult ) { 2980Id dataPointerType = makePointer ( storageClass , dataType ) ; 2981inst -> addIdOperand ( dataPointerType ) ; 2982} 2983if ( initializer != NoResult ) 2984inst -> addIdOperand ( initializer ) ; 2985 2986switch ( storageClass ) { 2987case StorageClass :: Function : 2988// Validation rules require the declaration in the entry block 2989buildPoint -> getParent () . addLocalVariable ( std :: unique_ptr < Instruction > ( inst )) ; 2990break ; 2991default : 2992constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( inst )) ; 2993module . mapInstruction ( inst ) ; 2994break ; 2995} 2996 2997if ( name ) 2998addName ( inst -> getResultId () , name ) ; 2999setPrecision ( inst -> getResultId () , precision ) ; 3000 3001return inst -> getResultId () ; 3002} 3003 3004// Comments in header 3005Id Builder :: createVariable ( Decoration precision , StorageClass storageClass , Id type , const char * name , Id initializer , 3006bool const compilerGenerated ) 3007{ 3008Id pointerType = makePointer ( storageClass , type ) ; 3009Instruction * inst = new Instruction ( getUniqueId () , pointerType , Op :: OpVariable ) ; 3010inst -> addImmediateOperand ( storageClass ) ; 3011if ( initializer != NoResult ) 3012inst -> addIdOperand ( initializer ) ; 3013 3014if ( storageClass == StorageClass :: Function ) { 3015// Validation rules require the declaration in the entry block 3016buildPoint -> getParent () . addLocalVariable ( std :: unique_ptr < Instruction > ( inst )) ; 3017} 3018else { 3019constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( inst )) ; 3020module . mapInstruction ( inst ) ; 3021} 3022 3023if ( emitNonSemanticShaderDebugInfo && ! compilerGenerated ) 3024{ 3025// For debug info, we prefer respecting how the variable is declared in source code. 3026// We may emulate some local variables as global variable with private storage in SPIR-V, but we still want to 3027// treat them as local variables in debug info. 3028if ( storageClass == StorageClass :: Function || ( currentFunction && storageClass == StorageClass :: Private )) { 3029auto const debugLocalVariableId = createDebugLocalVariable ( getDebugType ( type ) , name ) ; 3030makeDebugDeclare ( debugLocalVariableId , inst -> getResultId ()) ; 3031} 3032else { 3033createDebugGlobalVariable ( getDebugType ( type ) , name , inst -> getResultId ()) ; 3034} 3035} 3036 3037if ( name ) 3038addName ( inst -> getResultId () , name ) ; 3039setPrecision ( inst -> getResultId () , precision ) ; 3040 3041return inst -> getResultId () ; 3042} 3043 3044// Comments in header 3045Id Builder :: createUndefined ( Id type ) 3046{ 3047Instruction * inst = new Instruction ( getUniqueId () , type , Op :: OpUndef ) ; 3048addInstruction ( std :: unique_ptr < Instruction > ( inst )) ; 3049return inst -> getResultId () ; 3050} 3051 3052// av/vis/nonprivate are unnecessary and illegal for some storage classes. 3053spv :: MemoryAccessMask Builder :: sanitizeMemoryAccessForStorageClass ( spv :: MemoryAccessMask memoryAccess , StorageClass sc ) 3054const 3055{ 3056switch ( sc ) { 3057case spv :: StorageClass :: Uniform : 3058case spv :: StorageClass :: Workgroup : 3059case spv :: StorageClass :: StorageBuffer : 3060case spv :: StorageClass :: PhysicalStorageBufferEXT : 3061break ; 3062default : 3063memoryAccess = spv :: MemoryAccessMask ( memoryAccess & 3064~ ( spv :: MemoryAccessMask :: MakePointerAvailableKHR | 3065spv :: MemoryAccessMask :: MakePointerVisibleKHR | 3066spv :: MemoryAccessMask :: NonPrivatePointerKHR )) ; 3067break ; 3068} 3069return memoryAccess ; 3070} 3071 3072// Comments in header 3073void Builder :: createStore ( Id rValue , Id lValue , spv :: MemoryAccessMask memoryAccess , spv :: Scope scope , 3074unsigned int alignment ) 3075{ 3076Instruction * store = nullptr ; 3077if ( isUntypedPointer ( lValue )) 3078store = createDescHeapLoadStoreBaseRemap ( lValue , Op :: OpStore ) ; 3079else { 3080store = new Instruction ( Op :: OpStore ) ; 3081store -> reserveOperands ( 2 ) ; 3082store -> addIdOperand ( lValue ) ; 3083} 3084store -> addIdOperand ( rValue ) ; 3085 3086memoryAccess = sanitizeMemoryAccessForStorageClass ( memoryAccess , getStorageClass ( lValue )) ; 3087 3088if ( memoryAccess != MemoryAccessMask :: MaskNone ) { 3089store -> addImmediateOperand ( memoryAccess ) ; 3090if ( anySet ( memoryAccess , spv :: MemoryAccessMask :: Aligned )) { 3091store -> addImmediateOperand ( alignment ) ; 3092} 3093if ( anySet ( memoryAccess , spv :: MemoryAccessMask :: MakePointerAvailableKHR )) { 3094store -> addIdOperand ( makeUintConstant ( scope )) ; 3095} 3096} 3097 3098addInstruction ( std :: unique_ptr < Instruction > ( store )) ; 3099} 3100 3101// Comments in header 3102Id Builder :: createLoad ( Id lValue , spv :: Decoration precision , spv :: MemoryAccessMask memoryAccess , 3103spv :: Scope scope , unsigned int alignment ) 3104{ 3105Instruction * load = nullptr ; 3106if ( isUntypedPointer ( lValue )) 3107load = createDescHeapLoadStoreBaseRemap ( lValue , Op :: OpLoad ) ; 3108else { 3109load = new Instruction ( getUniqueId () , getDerefTypeId ( lValue ) , Op :: OpLoad ) ; 3110load -> addIdOperand ( lValue ) ; 3111} 3112 3113memoryAccess = sanitizeMemoryAccessForStorageClass ( memoryAccess , getStorageClass ( lValue )) ; 3114 3115if ( memoryAccess != MemoryAccessMask :: MaskNone ) { 3116load -> addImmediateOperand ( memoryAccess ) ; 3117if ( anySet ( memoryAccess , spv :: MemoryAccessMask :: Aligned )) { 3118load -> addImmediateOperand ( alignment ) ; 3119} 3120if ( anySet ( memoryAccess , spv :: MemoryAccessMask :: MakePointerVisibleKHR )) { 3121load -> addIdOperand ( makeUintConstant ( scope )) ; 3122} 3123} 3124 3125addInstruction ( std :: unique_ptr < Instruction > ( load )) ; 3126setPrecision ( load -> getResultId () , precision ) ; 3127 3128return load -> getResultId () ; 3129} 3130 3131Instruction * Builder :: createDescHeapLoadStoreBaseRemap ( Id baseId , Op op ) 3132{ 3133// could only be untypedAccessChain or BufferPointerEXT op. 3134spv :: Op instOp = module . getInstruction ( baseId ) -> getOpCode () ; 3135spv :: Id baseVal = baseId ; 3136// base type (from run time array) 3137spv :: Id resultTy = getIdOperand ( baseId , 0 ) ; 3138// Descriptor heap using run time array. 3139if ( accessChain . descHeapInfo . descHeapStorageClass != StorageClass :: Max ) 3140resultTy = getIdOperand ( resultTy , 0 ) ; 3141if ( instOp == Op :: OpBufferPointerEXT ) { 3142// get base structure type from run time array of buffer structure type. 3143// create an extra untyped access chain for buffer pointer. 3144resultTy = accessChain . descHeapInfo . descHeapBaseTy ; 3145Instruction * chain = new Instruction ( getUniqueId () , getTypeId ( baseId ) , Op :: OpUntypedAccessChainKHR ) ; 3146// base type. 3147chain -> addIdOperand ( resultTy ) ; 3148// base 3149chain -> addIdOperand ( baseId ) ; 3150// index 3151for ( int i = 0 ; i < ( int ) accessChain . indexChain . size () ; ++ i ) { 3152chain -> addIdOperand ( accessChain . indexChain [ i ]) ; 3153} 3154addInstruction ( std :: unique_ptr < Instruction > ( chain )) ; 3155baseVal = chain -> getResultId () ; 3156clearAccessChain () ; 3157} else if ( instOp != Op :: OpUntypedAccessChainKHR ) { 3158assert ( false && "Not a untyped load type" ) ; 3159} 3160 3161Instruction * inst = nullptr ; 3162if ( op == Op :: OpStore ) 3163inst = new Instruction ( Op :: OpStore ) ; 3164else { 3165inst = new Instruction ( getUniqueId () , resultTy , Op :: OpLoad ) ; 3166accessChain . descHeapInfo . descHeapInstId . push_back ( inst ) ; 3167} 3168inst -> addIdOperand ( baseVal ) ; 3169return inst ; 3170} 3171 3172uint32_t Builder :: isStructureHeapMember ( Id id , std :: vector < Id > indexChain , 3173unsigned int idx , spv :: BuiltIn * bt , uint32_t * firstArrIndex ) 3174{ 3175unsigned currentIdx = idx ; 3176// Process types, only array types could contain no constant id operands. 3177Id baseId = id ; 3178if ( baseId == NoType ) 3179return 0 ; 3180if ( isPointerType ( baseId )) 3181baseId = getContainedTypeId ( baseId ) ; 3182auto baseInst = module . getInstruction ( baseId ) ; 3183if ( baseInst -> getOpCode () == spv :: Op :: OpTypeArray || 3184baseInst -> getOpCode () == spv :: Op :: OpTypeRuntimeArray ) { 3185if ( firstArrIndex ) 3186* firstArrIndex = currentIdx ; 3187baseId = getContainedTypeId ( baseId ) ; 3188baseInst = module . getInstruction ( baseId ) ; 3189currentIdx ++ ; 3190} 3191if ( currentIdx >= indexChain . size ()) 3192return 0 ; 3193// Process index op. 3194auto indexInst = module . getInstruction ( indexChain [ currentIdx ]) ; 3195if ( indexInst -> getOpCode () != spv :: Op :: OpConstant ) 3196return 0 ; 3197auto index = indexInst -> getImmediateOperand ( 0 ) ; 3198for ( auto dec = decorations . begin () ; dec != decorations . end () ; dec ++ ) { 3199if ( dec -> get () -> getOpCode () == spv :: Op :: OpMemberDecorate && dec -> get () -> getIdOperand ( 0 ) == baseId && 3200dec -> get () -> getImmediateOperand ( 1 ) == index && 3201dec -> get () -> getImmediateOperand ( 2 ) == spv :: Decoration :: BuiltIn && 3202( dec -> get () -> getImmediateOperand ( 3 ) == ( unsigned ) spv :: BuiltIn :: ResourceHeapEXT || 3203dec -> get () -> getImmediateOperand ( 3 ) == ( unsigned ) spv :: BuiltIn :: SamplerHeapEXT )) { 3204if ( bt ) 3205* bt = ( spv :: BuiltIn ) dec -> get () -> getImmediateOperand ( 3 ) ; 3206return currentIdx ; 3207} 3208} 3209// New base. 3210if ( baseInst -> getOpCode () == spv :: Op :: OpTypeStruct ) { 3211if ( ! baseInst -> isIdOperand ( index ) || idx == indexChain . size () - 1 ) 3212return 0 ; 3213return isStructureHeapMember ( baseInst -> getIdOperand ( index ) , indexChain , currentIdx + 1 , bt , firstArrIndex ) ; 3214} 3215 3216return 0 ; 3217} 3218 3219// Comments in header 3220Id Builder :: createDescHeapAccessChain () 3221{ 3222uint32_t rsrcOffsetIdx = accessChain . descHeapInfo . structRsrcTyOffsetCount ; 3223if ( rsrcOffsetIdx != 0 ) 3224accessChain . base = accessChain . descHeapInfo . structRemappedBase ; 3225Id base = accessChain . base ; 3226Id untypedResultTy = accessChain . descHeapInfo . descHeapBaseTy ; 3227uint32_t explicitArrayStride = accessChain . descHeapInfo . descHeapBaseArrayStride ; 3228std :: vector < Id >& offsets = accessChain . indexChain ; 3229uint32_t firstArrIndex = accessChain . descHeapInfo . structRsrcTyFirstArrIndex ; 3230// both typeBufferEXT and UntypedPointer only contains storage class info. 3231StorageClass storageClass = ( StorageClass ) accessChain . descHeapInfo . descHeapStorageClass ; 3232Id resultTy = makeUntypedPointer ( storageClass == spv :: StorageClass :: StorageBuffer ? spv :: StorageClass :: StorageBuffer 3233: spv :: StorageClass :: Uniform ) ; 3234 3235// Make the untyped access chain instruction 3236Instruction * chain = new Instruction ( getUniqueId () , makeUntypedPointer ( getStorageClass ( base )) , Op :: OpUntypedAccessChainKHR ) ; 3237 3238if ( storageClass == spv :: StorageClass :: Uniform || storageClass == spv :: StorageClass :: StorageBuffer ) { 3239// For buffer and uniform heap, split first index as heap array index 3240// Insert BufferPointer op and construct another access chain with following indexes. 3241Id bufferTy = makeUntypedPointer ( storageClass , true ) ; 3242Id strideId = NoResult ; 3243if ( explicitArrayStride == 0 ) { 3244strideId = createConstantSizeOfEXT ( bufferTy ) ; 3245} else { 3246strideId = makeUintConstant ( explicitArrayStride ) ; 3247} 3248Id runtimeArrTy = makeRuntimeArray ( bufferTy ) ; 3249addDecorationId ( runtimeArrTy , spv :: Decoration :: ArrayStrideIdEXT , strideId ) ; 3250chain -> addIdOperand ( runtimeArrTy ) ; 3251chain -> addIdOperand ( base ) ; 3252// We would only re-target current member resource directly to resource/sampler heap base. 3253// So the previous access chain index towards final resource type is not needed? 3254// In current draft, only keep the first 'array index' into last access chain index. 3255// As those resource can't be declared as an array, in current first draft, array index will 3256// be the second index. This will be refined later. 3257chain -> addIdOperand ( offsets [ firstArrIndex ]) ; 3258if ( rsrcOffsetIdx != 0 ) { 3259for ( uint32_t i = 0 ; i < rsrcOffsetIdx + 1 ; i ++ ) { 3260if ( rsrcOffsetIdx + i + 1 < offsets . size ()) 3261offsets [ i ] = offsets [ i + rsrcOffsetIdx + 1 ] ; 3262} 3263} else { 3264for ( uint32_t i = 0 ; i < offsets . size () - 1 ; i ++ ) { 3265offsets [ i ] = offsets [ i + 1 ] ; 3266} 3267} 3268for ( uint32_t i = 0 ; i < rsrcOffsetIdx + 1 ; i ++ ) 3269offsets . pop_back () ; 3270addInstruction ( std :: unique_ptr < Instruction > ( chain )) ; 3271// Create OpBufferPointer for loading target buffer descriptor. 3272Instruction * bufferUntypedDataPtr = new Instruction ( getUniqueId () , resultTy , Op :: OpBufferPointerEXT ) ; 3273bufferUntypedDataPtr -> addIdOperand ( chain -> getResultId ()) ; 3274addInstruction ( std :: unique_ptr < Instruction > ( bufferUntypedDataPtr )) ; 3275// Final/Second untyped access chain loading will be created during loading, current results only 3276// refer to the loading 'base'. 3277return bufferUntypedDataPtr -> getResultId () ; 3278} else { 3279// image/sampler heap 3280Id strideId = NoResult ; 3281if ( explicitArrayStride == 0 ) { 3282strideId = createConstantSizeOfEXT ( untypedResultTy ) ; 3283} else { 3284strideId = makeUintConstant ( explicitArrayStride ) ; 3285} 3286Id runtimeArrTy = makeRuntimeArray ( untypedResultTy ) ; 3287addDecorationId ( runtimeArrTy , spv :: Decoration :: ArrayStrideIdEXT , strideId ) ; 3288chain -> addIdOperand ( runtimeArrTy ) ; 3289chain -> addIdOperand ( base ) ; 3290for ( int i = 0 ; i < ( int ) offsets . size () ; ++ i ) 3291chain -> addIdOperand ( offsets [ i ]) ; 3292addInstruction ( std :: unique_ptr < Instruction > ( chain )) ; 3293return chain -> getResultId () ; 3294} 3295} 3296 3297// Comments in header 3298Id Builder :: createAccessChain ( StorageClass storageClass , Id base , const std :: vector < Id >& offsets ) 3299{ 3300// Figure out the final resulting type. 3301Id typeId = getResultingAccessChainType () ; 3302typeId = makePointer ( storageClass , typeId ) ; 3303 3304// Make the instruction 3305Instruction * chain = new Instruction ( getUniqueId () , typeId , Op :: OpAccessChain ) ; 3306chain -> reserveOperands ( offsets . size () + 1 ) ; 3307chain -> addIdOperand ( base ) ; 3308for ( int i = 0 ; i < ( int ) offsets . size () ; ++ i ) 3309chain -> addIdOperand ( offsets [ i ]) ; 3310addInstruction ( std :: unique_ptr < Instruction > ( chain )) ; 3311 3312return chain -> getResultId () ; 3313} 3314 3315Id Builder :: createArrayLength ( Id base , unsigned int member , unsigned int bits ) 3316{ 3317spv :: Id intType = makeUintType ( bits ) ; 3318Instruction * length = new Instruction ( getUniqueId () , intType , Op :: OpArrayLength ) ; 3319length -> reserveOperands ( 2 ) ; 3320length -> addIdOperand ( base ) ; 3321length -> addImmediateOperand ( member ) ; 3322addInstruction ( std :: unique_ptr < Instruction > ( length )) ; 3323 3324return length -> getResultId () ; 3325} 3326 3327Id Builder :: createCooperativeMatrixLengthKHR ( Id type ) 3328{ 3329spv :: Id intType = makeUintType ( 32 ) ; 3330 3331// Generate code for spec constants if in spec constant operation 3332// generation mode. 3333if ( generatingOpCodeForSpecConst ) { 3334return createSpecConstantOp ( Op :: OpCooperativeMatrixLengthKHR , intType , std :: vector < Id > ( 1 , type ) , std :: vector < Id > ()) ; 3335} 3336 3337Instruction * length = new Instruction ( getUniqueId () , intType , Op :: OpCooperativeMatrixLengthKHR ) ; 3338length -> addIdOperand ( type ) ; 3339addInstruction ( std :: unique_ptr < Instruction > ( length )) ; 3340 3341return length -> getResultId () ; 3342} 3343 3344Id Builder :: createCooperativeMatrixLengthNV ( Id type ) 3345{ 3346spv :: Id intType = makeUintType ( 32 ) ; 3347 3348// Generate code for spec constants if in spec constant operation 3349// generation mode. 3350if ( generatingOpCodeForSpecConst ) { 3351return createSpecConstantOp ( Op :: OpCooperativeMatrixLengthNV , intType , std :: vector < Id > ( 1 , type ) , std :: vector < Id > ()) ; 3352} 3353 3354Instruction * length = new Instruction ( getUniqueId () , intType , Op :: OpCooperativeMatrixLengthNV ) ; 3355length -> addIdOperand ( type ) ; 3356addInstruction ( std :: unique_ptr < Instruction > ( length )) ; 3357 3358return length -> getResultId () ; 3359} 3360 3361Id Builder :: createCompositeExtract ( Id composite , Id typeId , unsigned index ) 3362{ 3363// Generate code for spec constants if in spec constant operation 3364// generation mode. 3365if ( generatingOpCodeForSpecConst ) { 3366return createSpecConstantOp ( Op :: OpCompositeExtract , typeId , std :: vector < Id > ( 1 , composite ) , 3367std :: vector < Id > ( 1 , index )) ; 3368} 3369Instruction * extract = new Instruction ( getUniqueId () , typeId , Op :: OpCompositeExtract ) ; 3370extract -> reserveOperands ( 2 ) ; 3371extract -> addIdOperand ( composite ) ; 3372extract -> addImmediateOperand ( index ) ; 3373addInstruction ( std :: unique_ptr < Instruction > ( extract )) ; 3374 3375return extract -> getResultId () ; 3376} 3377 3378Id Builder :: createCompositeExtract ( Id composite , Id typeId , const std :: vector < unsigned >& indexes ) 3379{ 3380// Generate code for spec constants if in spec constant operation 3381// generation mode. 3382if ( generatingOpCodeForSpecConst ) { 3383return createSpecConstantOp ( Op :: OpCompositeExtract , typeId , std :: vector < Id > ( 1 , composite ) , indexes ) ; 3384} 3385Instruction * extract = new Instruction ( getUniqueId () , typeId , Op :: OpCompositeExtract ) ; 3386extract -> reserveOperands ( indexes . size () + 1 ) ; 3387extract -> addIdOperand ( composite ) ; 3388for ( int i = 0 ; i < ( int ) indexes . size () ; ++ i ) 3389extract -> addImmediateOperand ( indexes [ i ]) ; 3390addInstruction ( std :: unique_ptr < Instruction > ( extract )) ; 3391 3392return extract -> getResultId () ; 3393} 3394 3395Id Builder :: createCompositeInsert ( Id object , Id composite , Id typeId , unsigned index ) 3396{ 3397Instruction * insert = new Instruction ( getUniqueId () , typeId , Op :: OpCompositeInsert ) ; 3398insert -> reserveOperands ( 3 ) ; 3399insert -> addIdOperand ( object ) ; 3400insert -> addIdOperand ( composite ) ; 3401insert -> addImmediateOperand ( index ) ; 3402addInstruction ( std :: unique_ptr < Instruction > ( insert )) ; 3403 3404return insert -> getResultId () ; 3405} 3406 3407Id Builder :: createCompositeInsert ( Id object , Id composite , Id typeId , const std :: vector < unsigned >& indexes ) 3408{ 3409Instruction * insert = new Instruction ( getUniqueId () , typeId , Op :: OpCompositeInsert ) ; 3410insert -> reserveOperands ( indexes . size () + 2 ) ; 3411insert -> addIdOperand ( object ) ; 3412insert -> addIdOperand ( composite ) ; 3413for ( int i = 0 ; i < ( int ) indexes . size () ; ++ i ) 3414insert -> addImmediateOperand ( indexes [ i ]) ; 3415addInstruction ( std :: unique_ptr < Instruction > ( insert )) ; 3416 3417return insert -> getResultId () ; 3418} 3419 3420Id Builder :: createVectorExtractDynamic ( Id vector , Id typeId , Id componentIndex ) 3421{ 3422Instruction * extract = new Instruction ( getUniqueId () , typeId , Op :: OpVectorExtractDynamic ) ; 3423extract -> reserveOperands ( 2 ) ; 3424extract -> addIdOperand ( vector ) ; 3425extract -> addIdOperand ( componentIndex ) ; 3426addInstruction ( std :: unique_ptr < Instruction > ( extract )) ; 3427 3428return extract -> getResultId () ; 3429} 3430 3431Id Builder :: createVectorInsertDynamic ( Id vector , Id typeId , Id component , Id componentIndex ) 3432{ 3433Instruction * insert = new Instruction ( getUniqueId () , typeId , Op :: OpVectorInsertDynamic ) ; 3434insert -> reserveOperands ( 3 ) ; 3435insert -> addIdOperand ( vector ) ; 3436insert -> addIdOperand ( component ) ; 3437insert -> addIdOperand ( componentIndex ) ; 3438addInstruction ( std :: unique_ptr < Instruction > ( insert )) ; 3439 3440return insert -> getResultId () ; 3441} 3442 3443// An opcode that has no operands, no result id, and no type 3444void Builder :: createNoResultOp ( Op opCode ) 3445{ 3446Instruction * op = new Instruction ( opCode ) ; 3447addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3448} 3449 3450// An opcode that has one id operand, no result id, and no type 3451void Builder :: createNoResultOp ( Op opCode , Id operand ) 3452{ 3453Instruction * op = new Instruction ( opCode ) ; 3454op -> addIdOperand ( operand ) ; 3455addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3456} 3457 3458// An opcode that has one or more operands, no result id, and no type 3459void Builder :: createNoResultOp ( Op opCode , const std :: vector < Id >& operands ) 3460{ 3461Instruction * op = new Instruction ( opCode ) ; 3462op -> reserveOperands ( operands . size ()) ; 3463for ( auto id : operands ) { 3464op -> addIdOperand ( id ) ; 3465} 3466addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3467} 3468 3469// An opcode that has multiple operands, no result id, and no type 3470void Builder :: createNoResultOp ( Op opCode , const std :: vector < IdImmediate >& operands ) 3471{ 3472Instruction * op = new Instruction ( opCode ) ; 3473op -> reserveOperands ( operands . size ()) ; 3474for ( auto it = operands . cbegin () ; it != operands . cend () ; ++ it ) { 3475if ( it -> isId ) 3476op -> addIdOperand ( it -> word ) ; 3477else 3478op -> addImmediateOperand ( it -> word ) ; 3479} 3480addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3481} 3482 3483void Builder :: createControlBarrier ( Scope execution , Scope memory , MemorySemanticsMask semantics ) 3484{ 3485Instruction * op = new Instruction ( Op :: OpControlBarrier ) ; 3486op -> reserveOperands ( 3 ) ; 3487op -> addIdOperand ( makeUintConstant ( execution )) ; 3488op -> addIdOperand ( makeUintConstant ( memory )) ; 3489op -> addIdOperand ( makeUintConstant ( semantics )) ; 3490addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3491} 3492 3493void Builder :: createMemoryBarrier ( Scope executionScope , MemorySemanticsMask memorySemantics ) 3494{ 3495Instruction * op = new Instruction ( Op :: OpMemoryBarrier ) ; 3496op -> reserveOperands ( 2 ) ; 3497op -> addIdOperand ( makeUintConstant (( unsigned ) executionScope )) ; 3498op -> addIdOperand ( makeUintConstant (( unsigned ) memorySemantics )) ; 3499addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3500} 3501 3502// An opcode that has one operands, a result id, and a type 3503Id Builder :: createUnaryOp ( Op opCode , Id typeId , Id operand ) 3504{ 3505// Generate code for spec constants if in spec constant operation 3506// generation mode. 3507if ( generatingOpCodeForSpecConst ) { 3508return createSpecConstantOp ( opCode , typeId , std :: vector < Id > ( 1 , operand ) , std :: vector < Id > ()) ; 3509} 3510Instruction * op = new Instruction ( getUniqueId () , typeId , opCode ) ; 3511op -> addIdOperand ( operand ) ; 3512addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3513 3514return op -> getResultId () ; 3515} 3516 3517Id Builder :: createBinOp ( Op opCode , Id typeId , Id left , Id right ) 3518{ 3519// Generate code for spec constants if in spec constant operation 3520// generation mode. 3521if ( generatingOpCodeForSpecConst ) { 3522std :: vector < Id > operands ( 2 ) ; 3523operands [ 0 ] = left ; operands [ 1 ] = right ; 3524return createSpecConstantOp ( opCode , typeId , operands , std :: vector < Id > ()) ; 3525} 3526Instruction * op = new Instruction ( getUniqueId () , typeId , opCode ) ; 3527op -> reserveOperands ( 2 ) ; 3528op -> addIdOperand ( left ) ; 3529op -> addIdOperand ( right ) ; 3530addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3531 3532return op -> getResultId () ; 3533} 3534 3535Id Builder :: createTriOp ( Op opCode , Id typeId , Id op1 , Id op2 , Id op3 ) 3536{ 3537// Generate code for spec constants if in spec constant operation 3538// generation mode. 3539if ( generatingOpCodeForSpecConst ) { 3540std :: vector < Id > operands ( 3 ) ; 3541operands [ 0 ] = op1 ; 3542operands [ 1 ] = op2 ; 3543operands [ 2 ] = op3 ; 3544return createSpecConstantOp ( 3545opCode , typeId , operands , std :: vector < Id > ()) ; 3546} 3547Instruction * op = new Instruction ( getUniqueId () , typeId , opCode ) ; 3548op -> reserveOperands ( 3 ) ; 3549op -> addIdOperand ( op1 ) ; 3550op -> addIdOperand ( op2 ) ; 3551op -> addIdOperand ( op3 ) ; 3552addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3553 3554return op -> getResultId () ; 3555} 3556 3557Id Builder :: createConstData ( Op opCode , Id typeId , const std :: vector < const char *> operands ) 3558{ 3559Instruction * op = new Instruction ( getUniqueId () , typeId , opCode ) ; 3560op -> reserveOperands ( operands . size ()) ; 3561for ( auto id : operands ) 3562op -> addStringOperand ( id ) ; 3563module . mapInstruction ( op ) ; 3564constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( op )) ; 3565 3566return op -> getResultId () ; 3567} 3568 3569Id Builder :: createOp ( Op opCode , Id typeId , const std :: vector < Id >& operands ) 3570{ 3571Instruction * op = new Instruction ( getUniqueId () , typeId , opCode ) ; 3572op -> reserveOperands ( operands . size ()) ; 3573for ( auto id : operands ) 3574op -> addIdOperand ( id ) ; 3575addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3576 3577return op -> getResultId () ; 3578} 3579 3580Id Builder :: createOp ( Op opCode , Id typeId , const std :: vector < IdImmediate >& operands ) 3581{ 3582Instruction * op = new Instruction ( getUniqueId () , typeId , opCode ) ; 3583op -> reserveOperands ( operands . size ()) ; 3584for ( auto it = operands . cbegin () ; it != operands . cend () ; ++ it ) { 3585if ( it -> isId ) 3586op -> addIdOperand ( it -> word ) ; 3587else 3588op -> addImmediateOperand ( it -> word ) ; 3589} 3590addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3591 3592return op -> getResultId () ; 3593} 3594 3595Id Builder :: createSpecConstantOp ( Op opCode , Id typeId , const std :: vector < Id >& operands , 3596const std :: vector < unsigned >& literals ) 3597{ 3598Instruction * op = new Instruction ( getUniqueId () , typeId , Op :: OpSpecConstantOp ) ; 3599op -> reserveOperands ( operands . size () + literals . size () + 1 ) ; 3600op -> addImmediateOperand (( unsigned ) opCode ) ; 3601for ( auto it = operands . cbegin () ; it != operands . cend () ; ++ it ) 3602op -> addIdOperand ( * it ) ; 3603for ( auto it = literals . cbegin () ; it != literals . cend () ; ++ it ) 3604op -> addImmediateOperand ( * it ) ; 3605module . mapInstruction ( op ) ; 3606constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( op )) ; 3607 3608// OpSpecConstantOp's using 8 or 16 bit types require the associated capability 3609if ( containsType ( typeId , Op :: OpTypeInt , 8 )) 3610addCapability ( Capability :: Int8 ) ; 3611if ( containsType ( typeId , Op :: OpTypeInt , 16 )) 3612addCapability ( Capability :: Int16 ) ; 3613if ( containsType ( typeId , Op :: OpTypeFloat , 16 )) 3614addCapability ( Capability :: Float16 ) ; 3615 3616return op -> getResultId () ; 3617} 3618 3619Id Builder :: createFunctionCall ( spv :: Function * function , const std :: vector < spv :: Id >& args ) 3620{ 3621Instruction * op = new Instruction ( getUniqueId () , function -> getReturnType () , Op :: OpFunctionCall ) ; 3622op -> reserveOperands ( args . size () + 1 ) ; 3623op -> addIdOperand ( function -> getId ()) ; 3624for ( int a = 0 ; a < ( int ) args . size () ; ++ a ) 3625op -> addIdOperand ( args [ a ]) ; 3626addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 3627 3628return op -> getResultId () ; 3629} 3630 3631// Comments in header 3632Id Builder :: createRvalueSwizzle ( Decoration precision , Id typeId , Id source , const std :: vector < unsigned >& channels ) 3633{ 3634if ( channels . size () == 1 ) 3635return setPrecision ( createCompositeExtract ( source , typeId , channels . front ()) , precision ) ; 3636 3637if ( generatingOpCodeForSpecConst ) { 3638std :: vector < Id > operands ( 2 ) ; 3639operands [ 0 ] = operands [ 1 ] = source ; 3640return setPrecision ( createSpecConstantOp ( Op :: OpVectorShuffle , typeId , operands , channels ) , precision ) ; 3641} 3642Instruction * swizzle = new Instruction ( getUniqueId () , typeId , Op :: OpVectorShuffle ) ; 3643assert ( isVector ( source )) ; 3644swizzle -> reserveOperands ( channels . size () + 2 ) ; 3645swizzle -> addIdOperand ( source ) ; 3646swizzle -> addIdOperand ( source ) ; 3647for ( int i = 0 ; i < ( int ) channels . size () ; ++ i ) 3648swizzle -> addImmediateOperand ( channels [ i ]) ; 3649addInstruction ( std :: unique_ptr < Instruction > ( swizzle )) ; 3650 3651return setPrecision ( swizzle -> getResultId () , precision ) ; 3652} 3653 3654// Comments in header 3655Id Builder :: createLvalueSwizzle ( Id typeId , Id target , Id source , const std :: vector < unsigned >& channels ) 3656{ 3657if ( channels . size () == 1 && getNumComponents ( source ) == 1 ) 3658return createCompositeInsert ( source , target , typeId , channels . front ()) ; 3659 3660Instruction * swizzle = new Instruction ( getUniqueId () , typeId , Op :: OpVectorShuffle ) ; 3661 3662assert ( isVector ( target )) ; 3663swizzle -> reserveOperands ( 2 ) ; 3664swizzle -> addIdOperand ( target ) ; 3665 3666assert ( getNumComponents ( source ) == channels . size ()) ; 3667assert ( isVector ( source )) ; 3668swizzle -> addIdOperand ( source ) ; 3669 3670// Set up an identity shuffle from the base value to the result value 3671unsigned int components [ 4 ] ; 3672int numTargetComponents = getNumComponents ( target ) ; 3673for ( int i = 0 ; i < numTargetComponents ; ++ i ) 3674components [ i ] = i ; 3675 3676// Punch in the l-value swizzle 3677for ( int i = 0 ; i < ( int ) channels . size () ; ++ i ) 3678components [ channels [ i ]] = numTargetComponents + i ; 3679 3680// finish the instruction with these components selectors 3681swizzle -> reserveOperands ( numTargetComponents ) ; 3682for ( int i = 0 ; i < numTargetComponents ; ++ i ) 3683swizzle -> addImmediateOperand ( components [ i ]) ; 3684addInstruction ( std :: unique_ptr < Instruction > ( swizzle )) ; 3685 3686return swizzle -> getResultId () ; 3687} 3688 3689// Comments in header 3690void Builder :: promoteScalar ( Decoration precision , Id & left , Id & right ) 3691{ 3692// choose direction of promotion (+1 for left to right, -1 for right to left) 3693int direction = ! isScalar ( right ) - ! isScalar ( left ) ; 3694 3695auto const & makeVec = [ & ]( Id component , Id other ) { 3696if ( isCooperativeVector ( other )) { 3697return makeCooperativeVectorTypeNV ( getTypeId ( component ) , getCooperativeVectorNumComponents ( getTypeId ( other ))) ; 3698} else { 3699return makeVectorType ( getTypeId ( component ) , getNumComponents ( other )) ; 3700} 3701} ; 3702 3703if ( direction > 0 ) 3704left = smearScalar ( precision , left , makeVec ( left , right )) ; 3705else if ( direction < 0 ) 3706right = smearScalar ( precision , right , makeVec ( right , left )) ; 3707 3708return ; 3709} 3710 3711// Comments in header 3712Id Builder :: smearScalar ( Decoration precision , Id scalar , Id vectorType ) 3713{ 3714assert ( getNumComponents ( scalar ) == 1 ) ; 3715assert ( getTypeId ( scalar ) == getScalarTypeId ( vectorType )) ; 3716 3717int numComponents = getNumTypeComponents ( vectorType ) ; 3718if ( numComponents == 1 && ! isCooperativeVectorType ( vectorType ) && ! isVectorType ( vectorType )) 3719return scalar ; 3720 3721Instruction * smear = nullptr ; 3722if ( generatingOpCodeForSpecConst ) { 3723auto members = std :: vector < spv :: Id > ( numComponents , scalar ) ; 3724// Sometime even in spec-constant-op mode, the temporary vector created by 3725// promoting a scalar might not be a spec constant. This should depend on 3726// the scalar. 3727// e.g.: 3728// const vec2 spec_const_result = a_spec_const_vec2 + a_front_end_const_scalar; 3729// In such cases, the temporary vector created from a_front_end_const_scalar 3730// is not a spec constant vector, even though the binary operation node is marked 3731// as 'specConstant' and we are in spec-constant-op mode. 3732auto result_id = makeCompositeConstant ( vectorType , members , isSpecConstant ( scalar )) ; 3733smear = module . getInstruction ( result_id ) ; 3734} else { 3735bool replicate = ( useReplicatedComposites || isCooperativeVectorType ( vectorType )) && ( numComponents > 0 ) ; 3736 3737if ( replicate ) { 3738numComponents = 1 ; 3739addCapability ( spv :: Capability :: ReplicatedCompositesEXT ) ; 3740addExtension ( spv :: E_SPV_EXT_replicated_composites ) ; 3741} 3742 3743Op opcode = replicate ? Op :: OpCompositeConstructReplicateEXT : Op :: OpCompositeConstruct ; 3744 3745smear = new Instruction ( getUniqueId () , vectorType , opcode ) ; 3746smear -> reserveOperands ( numComponents ) ; 3747for ( int c = 0 ; c < numComponents ; ++ c ) 3748smear -> addIdOperand ( scalar ) ; 3749addInstruction ( std :: unique_ptr < Instruction > ( smear )) ; 3750} 3751 3752return setPrecision ( smear -> getResultId () , precision ) ; 3753} 3754 3755// Comments in header 3756Id Builder :: createBuiltinCall ( Id resultType , Id builtins , int entryPoint , const std :: vector < Id >& args ) 3757{ 3758Instruction * inst = new Instruction ( getUniqueId () , resultType , Op :: OpExtInst ) ; 3759inst -> reserveOperands ( args . size () + 2 ) ; 3760inst -> addIdOperand ( builtins ) ; 3761inst -> addImmediateOperand ( entryPoint ) ; 3762for ( int arg = 0 ; arg < ( int ) args . size () ; ++ arg ) 3763inst -> addIdOperand ( args [ arg ]) ; 3764 3765addInstruction ( std :: unique_ptr < Instruction > ( inst )) ; 3766 3767return inst -> getResultId () ; 3768} 3769 3770// Accept all parameters needed to create a texture instruction. 3771// Create the correct instruction based on the inputs, and make the call. 3772Id Builder :: createTextureCall ( Decoration precision , Id resultType , bool sparse , bool fetch , bool proj , bool gather , 3773bool noImplicitLod , const TextureParameters & parameters , ImageOperandsMask signExtensionMask ) 3774{ 3775std :: vector < Id > texArgs ; 3776 3777// 3778// Set up the fixed arguments 3779// 3780bool explicitLod = false ; 3781texArgs . push_back ( parameters . sampler ) ; 3782texArgs . push_back ( parameters . coords ) ; 3783if ( parameters . Dref != NoResult ) 3784texArgs . push_back ( parameters . Dref ) ; 3785if ( parameters . component != NoResult ) 3786texArgs . push_back ( parameters . component ) ; 3787 3788if ( parameters . granularity != NoResult ) 3789texArgs . push_back ( parameters . granularity ) ; 3790if ( parameters . coarse != NoResult ) 3791texArgs . push_back ( parameters . coarse ) ; 3792 3793// 3794// Set up the optional arguments 3795// 3796size_t optArgNum = texArgs . size () ; // the position of the mask for the optional arguments, if any. 3797ImageOperandsMask mask = ImageOperandsMask :: MaskNone ; // the mask operand 3798if ( parameters . bias ) { 3799mask = ( ImageOperandsMask )( mask | ImageOperandsMask :: Bias ) ; 3800texArgs . push_back ( parameters . bias ) ; 3801} 3802if ( parameters . lod ) { 3803mask = ( ImageOperandsMask )( mask | ImageOperandsMask :: Lod ) ; 3804texArgs . push_back ( parameters . lod ) ; 3805explicitLod = true ; 3806} else if ( parameters . gradX ) { 3807mask = ( ImageOperandsMask )( mask | ImageOperandsMask :: Grad ) ; 3808texArgs . push_back ( parameters . gradX ) ; 3809texArgs . push_back ( parameters . gradY ) ; 3810explicitLod = true ; 3811} else if ( noImplicitLod && ! fetch && ! gather ) { 3812// have to explicitly use lod of 0 if not allowed to have them be implicit, and 3813// we would otherwise be about to issue an implicit instruction 3814mask = ( ImageOperandsMask )( mask | ImageOperandsMask :: Lod ) ; 3815texArgs . push_back ( makeFloatConstant ( 0.0 )) ; 3816explicitLod = true ; 3817} 3818if ( parameters . offset ) { 3819if ( isConstant ( parameters . offset )) 3820mask = ( ImageOperandsMask )( mask | ImageOperandsMask :: ConstOffset ) ; 3821else { 3822addCapability ( Capability :: ImageGatherExtended ) ; 3823mask = ( ImageOperandsMask )( mask | ImageOperandsMask :: Offset ) ; 3824} 3825texArgs . push_back ( parameters . offset ) ; 3826} 3827if ( parameters . offsets ) { 3828if ( ! isConstant ( parameters . offsets ) && sourceLang == spv :: SourceLanguage :: GLSL ) { 3829mask = ( ImageOperandsMask )( mask | ImageOperandsMask :: Offsets ) ; 3830} else { 3831addCapability ( Capability :: ImageGatherExtended ) ; 3832mask = ( ImageOperandsMask )( mask | ImageOperandsMask :: ConstOffsets ) ; 3833} 3834texArgs . push_back ( parameters . offsets ) ; 3835} 3836if ( parameters . sample ) { 3837mask = ( ImageOperandsMask )( mask | ImageOperandsMask :: Sample ) ; 3838texArgs . push_back ( parameters . sample ) ; 3839} 3840if ( parameters . lodClamp ) { 3841// capability if this bit is used 3842addCapability ( Capability :: MinLod ) ; 3843 3844mask = ( ImageOperandsMask )( mask | ImageOperandsMask :: MinLod ) ; 3845texArgs . push_back ( parameters . lodClamp ) ; 3846} 3847if ( parameters . nonprivate ) { 3848mask = mask | ImageOperandsMask :: NonPrivateTexelKHR ; 3849} 3850if ( parameters . volatil ) { 3851mask = mask | ImageOperandsMask :: VolatileTexelKHR ; 3852} 3853if ( parameters . nontemporal ) { 3854mask = mask | ImageOperandsMask :: Nontemporal ; 3855} 3856mask = mask | signExtensionMask ; 3857// insert the operand for the mask, if any bits were set. 3858if ( mask != ImageOperandsMask :: MaskNone ) 3859texArgs . insert ( texArgs . begin () + optArgNum , ( Id ) mask ) ; 3860 3861// 3862// Set up the instruction 3863// 3864Op opCode = Op :: OpNop ; // All paths below need to set this 3865if ( fetch ) { 3866if ( sparse ) 3867opCode = Op :: OpImageSparseFetch ; 3868else 3869opCode = Op :: OpImageFetch ; 3870} else if ( parameters . granularity && parameters . coarse ) { 3871opCode = Op :: OpImageSampleFootprintNV ; 3872} else if ( gather ) { 3873if ( parameters . Dref ) 3874if ( sparse ) 3875opCode = Op :: OpImageSparseDrefGather ; 3876else 3877opCode = Op :: OpImageDrefGather ; 3878else 3879if ( sparse ) 3880opCode = Op :: OpImageSparseGather ; 3881else 3882opCode = Op :: OpImageGather ; 3883} else if ( explicitLod ) { 3884if ( parameters . Dref ) { 3885if ( proj ) 3886if ( sparse ) 3887opCode = Op :: OpImageSparseSampleProjDrefExplicitLod ; 3888else 3889opCode = Op :: OpImageSampleProjDrefExplicitLod ; 3890else 3891if ( sparse ) 3892opCode = Op :: OpImageSparseSampleDrefExplicitLod ; 3893else 3894opCode = Op :: OpImageSampleDrefExplicitLod ; 3895} else { 3896if ( proj ) 3897if ( sparse ) 3898opCode = Op :: OpImageSparseSampleProjExplicitLod ; 3899else 3900opCode = Op :: OpImageSampleProjExplicitLod ; 3901else 3902if ( sparse ) 3903opCode = Op :: OpImageSparseSampleExplicitLod ; 3904else 3905opCode = Op :: OpImageSampleExplicitLod ; 3906} 3907} else { 3908if ( parameters . Dref ) { 3909if ( proj ) 3910if ( sparse ) 3911opCode = Op :: OpImageSparseSampleProjDrefImplicitLod ; 3912else 3913opCode = Op :: OpImageSampleProjDrefImplicitLod ; 3914else 3915if ( sparse ) 3916opCode = Op :: OpImageSparseSampleDrefImplicitLod ; 3917else 3918opCode = Op :: OpImageSampleDrefImplicitLod ; 3919} else { 3920if ( proj ) 3921if ( sparse ) 3922opCode = Op :: OpImageSparseSampleProjImplicitLod ; 3923else 3924opCode = Op :: OpImageSampleProjImplicitLod ; 3925else 3926if ( sparse ) 3927opCode = Op :: OpImageSparseSampleImplicitLod ; 3928else 3929opCode = Op :: OpImageSampleImplicitLod ; 3930} 3931} 3932 3933// See if the result type is expecting a smeared result. 3934// This happens when a legacy shadow*() call is made, which 3935// gets a vec4 back instead of a float. 3936Id smearedType = resultType ; 3937if ( ! isScalarType ( resultType )) { 3938switch ( opCode ) { 3939case Op :: OpImageSampleDrefImplicitLod : 3940case Op :: OpImageSampleDrefExplicitLod : 3941case Op :: OpImageSampleProjDrefImplicitLod : 3942case Op :: OpImageSampleProjDrefExplicitLod : 3943resultType = getScalarTypeId ( resultType ) ; 3944break ; 3945default : 3946break ; 3947} 3948} 3949 3950Id typeId0 = 0 ; 3951Id typeId1 = 0 ; 3952 3953if ( sparse ) { 3954typeId0 = resultType ; 3955typeId1 = getDerefTypeId ( parameters . texelOut ) ; 3956resultType = makeStructResultType ( typeId0 , typeId1 ) ; 3957} 3958 3959// Build the SPIR-V instruction 3960Instruction * textureInst = new Instruction ( getUniqueId () , resultType , opCode ) ; 3961textureInst -> reserveOperands ( optArgNum + ( texArgs . size () - ( optArgNum + 1 ))) ; 3962for ( size_t op = 0 ; op < optArgNum ; ++ op ) 3963textureInst -> addIdOperand ( texArgs [ op ]) ; 3964if ( optArgNum < texArgs . size ()) 3965textureInst -> addImmediateOperand ( texArgs [ optArgNum ]) ; 3966for ( size_t op = optArgNum + 1 ; op < texArgs . size () ; ++ op ) 3967textureInst -> addIdOperand ( texArgs [ op ]) ; 3968setPrecision ( textureInst -> getResultId () , precision ) ; 3969addInstruction ( std :: unique_ptr < Instruction > ( textureInst )) ; 3970 3971Id resultId = textureInst -> getResultId () ; 3972 3973if ( sparse ) { 3974// set capability 3975addCapability ( Capability :: SparseResidency ) ; 3976 3977// Decode the return type that was a special structure 3978createStore ( createCompositeExtract ( resultId , typeId1 , 1 ) , parameters . texelOut ) ; 3979resultId = createCompositeExtract ( resultId , typeId0 , 0 ) ; 3980setPrecision ( resultId , precision ) ; 3981} else { 3982// When a smear is needed, do it, as per what was computed 3983// above when resultType was changed to a scalar type. 3984if ( resultType != smearedType ) 3985resultId = smearScalar ( precision , resultId , smearedType ) ; 3986} 3987 3988return resultId ; 3989} 3990 3991// Comments in header 3992Id Builder :: createTextureQueryCall ( Op opCode , const TextureParameters & parameters , bool isUnsignedResult ) 3993{ 3994// Figure out the result type 3995Id resultType = 0 ; 3996switch ( opCode ) { 3997case Op :: OpImageQuerySize : 3998case Op :: OpImageQuerySizeLod : 3999{ 4000int numComponents = 0 ; 4001switch ( getTypeDimensionality ( getImageType ( parameters . sampler ))) { 4002case Dim :: Dim1D : 4003case Dim :: Buffer : 4004numComponents = 1 ; 4005break ; 4006case Dim :: Dim2D : 4007case Dim :: Cube : 4008case Dim :: Rect : 4009case Dim :: SubpassData : 4010numComponents = 2 ; 4011break ; 4012case Dim :: Dim3D : 4013numComponents = 3 ; 4014break ; 4015 4016default : 4017assert ( 0 ) ; 4018break ; 4019} 4020if ( isArrayedImageType ( getImageType ( parameters . sampler ))) 4021++ numComponents ; 4022 4023Id intType = isUnsignedResult ? makeUintType ( 32 ) : makeIntType ( 32 ) ; 4024if ( numComponents == 1 ) 4025resultType = intType ; 4026else 4027resultType = makeVectorType ( intType , numComponents ) ; 4028 4029break ; 4030} 4031case Op :: OpImageQueryLod : 4032resultType = makeVectorType ( getScalarTypeId ( getTypeId ( parameters . coords )) , 2 ) ; 4033break ; 4034case Op :: OpImageQueryLevels : 4035case Op :: OpImageQuerySamples : 4036resultType = isUnsignedResult ? makeUintType ( 32 ) : makeIntType ( 32 ) ; 4037break ; 4038default : 4039assert ( 0 ) ; 4040break ; 4041} 4042 4043Instruction * query = new Instruction ( getUniqueId () , resultType , opCode ) ; 4044query -> addIdOperand ( parameters . sampler ) ; 4045if ( parameters . coords ) 4046query -> addIdOperand ( parameters . coords ) ; 4047if ( parameters . lod ) 4048query -> addIdOperand ( parameters . lod ) ; 4049addInstruction ( std :: unique_ptr < Instruction > ( query )) ; 4050addCapability ( Capability :: ImageQuery ) ; 4051 4052return query -> getResultId () ; 4053} 4054 4055// External comments in header. 4056// Operates recursively to visit the composite's hierarchy. 4057Id Builder :: createCompositeCompare ( Decoration precision , Id value1 , Id value2 , bool equal ) 4058{ 4059Id boolType = makeBoolType () ; 4060Id valueType = getTypeId ( value1 ) ; 4061 4062Id resultId = NoResult ; 4063 4064int numConstituents = getNumTypeConstituents ( valueType ) ; 4065 4066// Scalars and Vectors 4067 4068if ( isScalarType ( valueType ) || isVectorType ( valueType )) { 4069assert ( valueType == getTypeId ( value2 )) ; 4070// These just need a single comparison, just have 4071// to figure out what it is. 4072Op op ; 4073switch ( getMostBasicTypeClass ( valueType )) { 4074case Op :: OpTypeFloat : 4075op = equal ? Op :: OpFOrdEqual : Op :: OpFUnordNotEqual ; 4076break ; 4077case Op :: OpTypeInt : 4078default : 4079op = equal ? Op :: OpIEqual : Op :: OpINotEqual ; 4080break ; 4081case Op :: OpTypeBool : 4082op = equal ? Op :: OpLogicalEqual : Op :: OpLogicalNotEqual ; 4083precision = NoPrecision ; 4084break ; 4085} 4086 4087if ( isScalarType ( valueType )) { 4088// scalar 4089resultId = createBinOp ( op , boolType , value1 , value2 ) ; 4090} else { 4091// vector 4092resultId = createBinOp ( op , makeVectorType ( boolType , numConstituents ) , value1 , value2 ) ; 4093setPrecision ( resultId , precision ) ; 4094// reduce vector compares... 4095resultId = createUnaryOp ( equal ? Op :: OpAll : Op :: OpAny , boolType , resultId ) ; 4096} 4097 4098return setPrecision ( resultId , precision ) ; 4099} 4100 4101// Only structs, arrays, and matrices should be left. 4102// They share in common the reduction operation across their constituents. 4103assert ( isAggregateType ( valueType ) || isMatrixType ( valueType )) ; 4104 4105// Compare each pair of constituents 4106for ( int constituent = 0 ; constituent < numConstituents ; ++ constituent ) { 4107std :: vector < unsigned > indexes ( 1 , constituent ) ; 4108Id constituentType1 = getContainedTypeId ( getTypeId ( value1 ) , constituent ) ; 4109Id constituentType2 = getContainedTypeId ( getTypeId ( value2 ) , constituent ) ; 4110Id constituent1 = createCompositeExtract ( value1 , constituentType1 , indexes ) ; 4111Id constituent2 = createCompositeExtract ( value2 , constituentType2 , indexes ) ; 4112 4113Id subResultId = createCompositeCompare ( precision , constituent1 , constituent2 , equal ) ; 4114 4115if ( constituent == 0 ) 4116resultId = subResultId ; 4117else 4118resultId = setPrecision ( createBinOp ( equal ? Op :: OpLogicalAnd : Op :: OpLogicalOr , boolType , resultId , subResultId ) , 4119precision ) ; 4120} 4121 4122return resultId ; 4123} 4124 4125// OpCompositeConstruct 4126Id Builder :: createCompositeConstruct ( Id typeId , const std :: vector < Id >& constituents ) 4127{ 4128assert ( isAggregateType ( typeId ) || ( getNumTypeConstituents ( typeId ) > 1 && 4129getNumTypeConstituents ( typeId ) == constituents . size ()) || 4130(( isCooperativeVectorType ( typeId ) || isVectorType ( typeId )) && constituents . size () == 1 )) ; 4131 4132if ( generatingOpCodeForSpecConst ) { 4133// Sometime, even in spec-constant-op mode, the constant composite to be 4134// constructed may not be a specialization constant. 4135// e.g.: 4136// const mat2 m2 = mat2(a_spec_const, a_front_end_const, another_front_end_const, third_front_end_const); 4137// The first column vector should be a spec constant one, as a_spec_const is a spec constant. 4138// The second column vector should NOT be spec constant, as it does not contain any spec constants. 4139// To handle such cases, we check the constituents of the constant vector to determine whether this 4140// vector should be created as a spec constant. 4141return makeCompositeConstant ( typeId , constituents , 4142std :: any_of ( constituents . begin () , constituents . end () , 4143[ & ]( spv :: Id id ) { return isSpecConstant ( id ) ; })) ; 4144} 4145 4146bool replicate = false ; 4147size_t numConstituents = constituents . size () ; 4148 4149if ( useReplicatedComposites || isCooperativeVectorType ( typeId )) { 4150replicate = numConstituents > 0 && 4151std :: equal ( constituents . begin () + 1 , constituents . end () , constituents . begin ()) ; 4152} 4153 4154if ( replicate ) { 4155numConstituents = 1 ; 4156addCapability ( spv :: Capability :: ReplicatedCompositesEXT ) ; 4157addExtension ( spv :: E_SPV_EXT_replicated_composites ) ; 4158} 4159 4160Op opcode = replicate ? Op :: OpCompositeConstructReplicateEXT : Op :: OpCompositeConstruct ; 4161 4162Instruction * op = new Instruction ( getUniqueId () , typeId , opcode ) ; 4163op -> reserveOperands ( constituents . size ()) ; 4164for ( size_t c = 0 ; c < numConstituents ; ++ c ) 4165op -> addIdOperand ( constituents [ c ]) ; 4166addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 4167 4168return op -> getResultId () ; 4169} 4170 4171// coopmat conversion 4172Id Builder :: createCooperativeMatrixConversion ( Id typeId , Id source ) 4173{ 4174Instruction * op = new Instruction ( getUniqueId () , typeId , Op :: OpCooperativeMatrixConvertNV ) ; 4175op -> addIdOperand ( source ) ; 4176addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 4177 4178return op -> getResultId () ; 4179} 4180 4181// coopmat reduce 4182Id Builder :: createCooperativeMatrixReduce ( Op opcode , Id typeId , Id source , unsigned int mask , Id func ) 4183{ 4184Instruction * op = new Instruction ( getUniqueId () , typeId , opcode ) ; 4185op -> addIdOperand ( source ) ; 4186op -> addImmediateOperand ( mask ) ; 4187op -> addIdOperand ( func ) ; 4188addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 4189 4190return op -> getResultId () ; 4191} 4192 4193// coopmat per-element operation 4194Id Builder :: createCooperativeMatrixPerElementOp ( Id typeId , const std :: vector < Id >& operands ) 4195{ 4196Instruction * op = new Instruction ( getUniqueId () , typeId , spv :: Op :: OpCooperativeMatrixPerElementOpNV ) ; 4197// skip operand[0], which is where the result is stored 4198for ( uint32_t i = 1 ; i < operands . size () ; ++ i ) { 4199op -> addIdOperand ( operands [ i ]) ; 4200} 4201addInstruction ( std :: unique_ptr < Instruction > ( op )) ; 4202 4203return op -> getResultId () ; 4204} 4205 4206// Vector or scalar constructor 4207Id Builder :: createConstructor ( Decoration precision , const std :: vector < Id >& sources , Id resultTypeId ) 4208{ 4209Id result = NoResult ; 4210unsigned int numTargetComponents = getNumTypeComponents ( resultTypeId ) ; 4211unsigned int targetComponent = 0 ; 4212 4213// Special case: when calling a vector constructor with a single scalar 4214// argument, smear the scalar 4215if ( sources . size () == 1 && isScalar ( sources [ 0 ]) && ( numTargetComponents > 1 || isCooperativeVectorType ( resultTypeId ))) 4216return smearScalar ( precision , sources [ 0 ] , resultTypeId ) ; 4217 4218// Special case: 2 vectors of equal size 4219if ( sources . size () == 1 && 4220( isVector ( sources [ 0 ]) || isCooperativeVector ( sources [ 0 ])) && 4221numTargetComponents == getNumComponents ( sources [ 0 ])) { 4222if ( isCooperativeVector ( sources [ 0 ]) != isCooperativeVectorType ( resultTypeId )) { 4223assert ( isVector ( sources [ 0 ]) != isVectorType ( resultTypeId )) ; 4224return createUnaryOp ( spv :: Op :: OpBitcast , resultTypeId , sources [ 0 ]) ; 4225} else { 4226assert ( resultTypeId == getTypeId ( sources [ 0 ])) ; 4227return sources [ 0 ] ; 4228} 4229} 4230 4231// accumulate the arguments for OpCompositeConstruct 4232std :: vector < Id > constituents ; 4233Id scalarTypeId = getScalarTypeId ( resultTypeId ) ; 4234 4235// lambda to store the result of visiting an argument component 4236const auto latchResult = [ & ]( Id comp ) { 4237if ( numTargetComponents > 1 || isVectorType ( resultTypeId )) 4238constituents . push_back ( comp ) ; 4239else 4240result = comp ; 4241++ targetComponent ; 4242} ; 4243 4244// lambda to visit a vector argument's components 4245const auto accumulateVectorConstituents = [ & ]( Id sourceArg ) { 4246unsigned int sourceSize = getNumComponents ( sourceArg ) ; 4247unsigned int sourcesToUse = sourceSize ; 4248if ( sourcesToUse + targetComponent > numTargetComponents ) 4249sourcesToUse = numTargetComponents - targetComponent ; 4250 4251for ( unsigned int s = 0 ; s < sourcesToUse ; ++ s ) { 4252std :: vector < unsigned > swiz ; 4253swiz . push_back ( s ) ; 4254latchResult ( createRvalueSwizzle ( precision , scalarTypeId , sourceArg , swiz )) ; 4255} 4256} ; 4257 4258// lambda to visit a matrix argument's components 4259const auto accumulateMatrixConstituents = [ & ]( Id sourceArg ) { 4260unsigned int sourceSize = getNumColumns ( sourceArg ) * getNumRows ( sourceArg ) ; 4261unsigned int sourcesToUse = sourceSize ; 4262if ( sourcesToUse + targetComponent > numTargetComponents ) 4263sourcesToUse = numTargetComponents - targetComponent ; 4264 4265unsigned int col = 0 ; 4266unsigned int row = 0 ; 4267for ( unsigned int s = 0 ; s < sourcesToUse ; ++ s ) { 4268if ( row >= getNumRows ( sourceArg )) { 4269row = 0 ; 4270col ++ ; 4271} 4272std :: vector < Id > indexes ; 4273indexes . push_back ( col ) ; 4274indexes . push_back ( row ) ; 4275latchResult ( createCompositeExtract ( sourceArg , scalarTypeId , indexes )) ; 4276row ++ ; 4277} 4278} ; 4279 4280// Go through the source arguments, each one could have either 4281// a single or multiple components to contribute. 4282for ( unsigned int i = 0 ; i < sources . size () ; ++ i ) { 4283 4284if ( isScalar ( sources [ i ]) || isPointer ( sources [ i ])) 4285latchResult ( sources [ i ]) ; 4286else if ( isVector ( sources [ i ]) || isCooperativeVector ( sources [ i ])) 4287accumulateVectorConstituents ( sources [ i ]) ; 4288else if ( isMatrix ( sources [ i ])) 4289accumulateMatrixConstituents ( sources [ i ]) ; 4290else 4291assert ( 0 ) ; 4292 4293if ( targetComponent >= numTargetComponents ) 4294break ; 4295} 4296 4297// If the result is a vector, make it from the gathered constituents. 4298if ( constituents . size () > 0 ) { 4299result = createCompositeConstruct ( resultTypeId , constituents ) ; 4300return setPrecision ( result , precision ) ; 4301} else { 4302// Precision was set when generating this component. 4303return result ; 4304} 4305} 4306 4307// Comments in header 4308Id Builder :: createMatrixConstructor ( Decoration precision , const std :: vector < Id >& sources , Id resultTypeId ) 4309{ 4310Id componentTypeId = getScalarTypeId ( resultTypeId ) ; 4311unsigned int numCols = getTypeNumColumns ( resultTypeId ) ; 4312unsigned int numRows = getTypeNumRows ( resultTypeId ) ; 4313 4314Instruction * instr = module . getInstruction ( componentTypeId ) ; 4315const unsigned bitCount = instr -> getImmediateOperand ( 0 ) ; 4316 4317// Optimize matrix constructed from a bigger matrix 4318if ( isMatrix ( sources [ 0 ]) && getNumColumns ( sources [ 0 ]) >= numCols && getNumRows ( sources [ 0 ]) >= numRows ) { 4319// To truncate the matrix to a smaller number of rows/columns, we need to: 4320// 1. For each column, extract the column and truncate it to the required size using shuffle 4321// 2. Assemble the resulting matrix from all columns 4322Id matrix = sources [ 0 ] ; 4323Id columnTypeId = getContainedTypeId ( resultTypeId ) ; 4324Id sourceColumnTypeId = getContainedTypeId ( getTypeId ( matrix )) ; 4325 4326std :: vector < unsigned > channels ; 4327for ( unsigned int row = 0 ; row < numRows ; ++ row ) 4328channels . push_back ( row ) ; 4329 4330std :: vector < Id > matrixColumns ; 4331for ( unsigned int col = 0 ; col < numCols ; ++ col ) { 4332std :: vector < unsigned > indexes ; 4333indexes . push_back ( col ) ; 4334Id colv = createCompositeExtract ( matrix , sourceColumnTypeId , indexes ) ; 4335setPrecision ( colv , precision ) ; 4336 4337if ( numRows != getNumRows ( matrix )) { 4338matrixColumns . push_back ( createRvalueSwizzle ( precision , columnTypeId , colv , channels )) ; 4339} else { 4340matrixColumns . push_back ( colv ) ; 4341} 4342} 4343 4344return setPrecision ( createCompositeConstruct ( resultTypeId , matrixColumns ) , precision ) ; 4345} 4346 4347// Detect a matrix being constructed from a repeated vector of the correct size. 4348// Create the composite directly from it. 4349if ( sources . size () == numCols && isVector ( sources [ 0 ]) && getNumComponents ( sources [ 0 ]) == numRows && 4350std :: equal ( sources . begin () + 1 , sources . end () , sources . begin ())) { 4351return setPrecision ( createCompositeConstruct ( resultTypeId , sources ) , precision ) ; 4352} 4353 4354// Otherwise, will use a two step process 4355// 1. make a compile-time 2D array of values 4356// 2. construct a matrix from that array 4357 4358// Step 1. 4359 4360// initialize the array to the identity matrix 4361Id ids [ maxMatrixSize ][ maxMatrixSize ] ; 4362Id one = ( bitCount == 64 ? makeDoubleConstant ( 1.0 ) : makeFloatConstant ( 1.0 )) ; 4363Id zero = ( bitCount == 64 ? makeDoubleConstant ( 0.0 ) : makeFloatConstant ( 0.0 )) ; 4364for ( int col = 0 ; col < 4 ; ++ col ) { 4365for ( int row = 0 ; row < 4 ; ++ row ) { 4366if ( col == row ) 4367ids [ col ][ row ] = one ; 4368else 4369ids [ col ][ row ] = zero ; 4370} 4371} 4372 4373// modify components as dictated by the arguments 4374if ( sources . size () == 1 && isScalar ( sources [ 0 ])) { 4375// a single scalar; resets the diagonals 4376for ( int col = 0 ; col < 4 ; ++ col ) 4377ids [ col ][ col ] = sources [ 0 ] ; 4378} else if ( isMatrix ( sources [ 0 ])) { 4379// constructing from another matrix; copy over the parts that exist in both the argument and constructee 4380Id matrix = sources [ 0 ] ; 4381unsigned int minCols = std :: min ( numCols , getNumColumns ( matrix )) ; 4382unsigned int minRows = std :: min ( numRows , getNumRows ( matrix )) ; 4383for ( unsigned int col = 0 ; col < minCols ; ++ col ) { 4384std :: vector < unsigned > indexes ; 4385indexes . push_back ( col ) ; 4386for ( unsigned int row = 0 ; row < minRows ; ++ row ) { 4387indexes . push_back ( row ) ; 4388ids [ col ][ row ] = createCompositeExtract ( matrix , componentTypeId , indexes ) ; 4389indexes . pop_back () ; 4390setPrecision ( ids [ col ][ row ] , precision ) ; 4391} 4392} 4393} else { 4394// fill in the matrix in column-major order with whatever argument components are available 4395unsigned int row = 0 ; 4396unsigned int col = 0 ; 4397 4398for ( unsigned int arg = 0 ; arg < sources . size () && col < numCols ; ++ arg ) { 4399Id argComp = sources [ arg ] ; 4400for ( unsigned int comp = 0 ; comp < getNumComponents ( sources [ arg ]) ; ++ comp ) { 4401if ( getNumComponents ( sources [ arg ]) > 1 ) { 4402argComp = createCompositeExtract ( sources [ arg ] , componentTypeId , comp ) ; 4403setPrecision ( argComp , precision ) ; 4404} 4405ids [ col ][ row ++ ] = argComp ; 4406if ( row == numRows ) { 4407row = 0 ; 4408col ++ ; 4409} 4410if ( col == numCols ) { 4411// If more components are provided than fit the matrix, discard the rest. 4412break ; 4413} 4414} 4415} 4416} 4417 4418// Step 2: Construct a matrix from that array. 4419// First make the column vectors, then make the matrix. 4420 4421// make the column vectors 4422Id columnTypeId = getContainedTypeId ( resultTypeId ) ; 4423std :: vector < Id > matrixColumns ; 4424for ( unsigned int col = 0 ; col < numCols ; ++ col ) { 4425std :: vector < Id > vectorComponents ; 4426for ( unsigned int row = 0 ; row < numRows ; ++ row ) 4427vectorComponents . push_back ( ids [ col ][ row ]) ; 4428Id column = createCompositeConstruct ( columnTypeId , vectorComponents ) ; 4429setPrecision ( column , precision ) ; 4430matrixColumns . push_back ( column ) ; 4431} 4432 4433// make the matrix 4434return setPrecision ( createCompositeConstruct ( resultTypeId , matrixColumns ) , precision ) ; 4435} 4436 4437// Comments in header 4438Builder :: If :: If ( Id cond , SelectionControlMask ctrl , Builder & gb ) : 4439builder ( gb ) , 4440condition ( cond ) , 4441control ( ctrl ) , 4442elseBlock ( nullptr ) 4443{ 4444function = & builder . getBuildPoint () -> getParent () ; 4445 4446// make the blocks, but only put the then-block into the function, 4447// the else-block and merge-block will be added later, in order, after 4448// earlier code is emitted 4449thenBlock = new Block ( builder . getUniqueId () , * function ) ; 4450mergeBlock = new Block ( builder . getUniqueId () , * function ) ; 4451 4452// Save the current block, so that we can add in the flow control split when 4453// makeEndIf is called. 4454headerBlock = builder . getBuildPoint () ; 4455builder . createSelectionMerge ( mergeBlock , control ) ; 4456 4457function -> addBlock ( thenBlock ) ; 4458builder . setBuildPoint ( thenBlock ) ; 4459} 4460 4461// Comments in header 4462void Builder :: If :: makeBeginElse () 4463{ 4464// Close out the "then" by having it jump to the mergeBlock 4465builder . createBranch ( true , mergeBlock ) ; 4466 4467// Make the first else block and add it to the function 4468elseBlock = new Block ( builder . getUniqueId () , * function ) ; 4469function -> addBlock ( elseBlock ) ; 4470 4471// Start building the else block 4472builder . setBuildPoint ( elseBlock ) ; 4473} 4474 4475// Comments in header 4476void Builder :: If :: makeEndIf () 4477{ 4478// jump to the merge block 4479builder . createBranch ( true , mergeBlock ) ; 4480 4481// Go back to the headerBlock and make the flow control split 4482builder . setBuildPoint ( headerBlock ) ; 4483if ( elseBlock ) 4484builder . createConditionalBranch ( condition , thenBlock , elseBlock ) ; 4485else 4486builder . createConditionalBranch ( condition , thenBlock , mergeBlock ) ; 4487 4488// add the merge block to the function 4489function -> addBlock ( mergeBlock ) ; 4490builder . setBuildPoint ( mergeBlock ) ; 4491} 4492 4493// Comments in header 4494void Builder :: makeSwitch ( Id selector , SelectionControlMask control , int numSegments , const std :: vector < int >& caseValues , 4495const std :: vector < int >& valueIndexToSegment , int defaultSegment , 4496std :: vector < Block *>& segmentBlocks ) 4497{ 4498Function & function = buildPoint -> getParent () ; 4499 4500// make all the blocks 4501for ( int s = 0 ; s < numSegments ; ++ s ) 4502segmentBlocks . push_back ( new Block ( getUniqueId () , function )) ; 4503 4504Block * mergeBlock = new Block ( getUniqueId () , function ) ; 4505 4506// make and insert the switch's selection-merge instruction 4507createSelectionMerge ( mergeBlock , control ) ; 4508 4509// make the switch instruction 4510Instruction * switchInst = new Instruction ( NoResult , NoType , Op :: OpSwitch ) ; 4511switchInst -> reserveOperands (( caseValues . size () * 2 ) + 2 ) ; 4512switchInst -> addIdOperand ( selector ) ; 4513auto defaultOrMerge = ( defaultSegment >= 0 ) ? segmentBlocks [ defaultSegment ] : mergeBlock ; 4514switchInst -> addIdOperand ( defaultOrMerge -> getId ()) ; 4515defaultOrMerge -> addPredecessor ( buildPoint ) ; 4516for ( int i = 0 ; i < ( int ) caseValues . size () ; ++ i ) { 4517switchInst -> addImmediateOperand ( caseValues [ i ]) ; 4518switchInst -> addIdOperand ( segmentBlocks [ valueIndexToSegment [ i ]] -> getId ()) ; 4519segmentBlocks [ valueIndexToSegment [ i ]] -> addPredecessor ( buildPoint ) ; 4520} 4521addInstruction ( std :: unique_ptr < Instruction > ( switchInst )) ; 4522 4523// push the merge block 4524switchMerges . push ( mergeBlock ) ; 4525} 4526 4527// Comments in header 4528void Builder :: addSwitchBreak ( bool implicit ) 4529{ 4530// branch to the top of the merge block stack 4531createBranch ( implicit , switchMerges . top ()) ; 4532createAndSetNoPredecessorBlock ( "post-switch-break" ) ; 4533} 4534 4535// Comments in header 4536void Builder :: nextSwitchSegment ( std :: vector < Block *>& segmentBlock , int nextSegment ) 4537{ 4538int lastSegment = nextSegment - 1 ; 4539if ( lastSegment >= 0 ) { 4540// Close out previous segment by jumping, if necessary, to next segment 4541if ( ! buildPoint -> isTerminated ()) 4542createBranch ( true , segmentBlock [ nextSegment ]) ; 4543} 4544Block * block = segmentBlock [ nextSegment ] ; 4545block -> getParent () . addBlock ( block ) ; 4546setBuildPoint ( block ) ; 4547} 4548 4549// Comments in header 4550void Builder :: endSwitch ( std :: vector < Block *>& /*segmentBlock*/ ) 4551{ 4552// Close out previous segment by jumping, if necessary, to next segment 4553if ( ! buildPoint -> isTerminated ()) 4554addSwitchBreak ( true ) ; 4555 4556switchMerges . top () -> getParent () . addBlock ( switchMerges . top ()) ; 4557setBuildPoint ( switchMerges . top ()) ; 4558 4559switchMerges . pop () ; 4560} 4561 4562Block & Builder :: makeNewBlock () 4563{ 4564Function & function = buildPoint -> getParent () ; 4565auto block = new Block ( getUniqueId () , function ) ; 4566function . addBlock ( block ) ; 4567return * block ; 4568} 4569 4570Builder :: LoopBlocks & Builder :: makeNewLoop () 4571{ 4572// This verbosity is needed to simultaneously get the same behavior 4573// everywhere (id's in the same order), have a syntax that works 4574// across lots of versions of C++, have no warnings from pedantic 4575// compilation modes, and leave the rest of the code alone. 4576Block & head = makeNewBlock () ; 4577Block & body = makeNewBlock () ; 4578Block & merge = makeNewBlock () ; 4579Block & continue_target = makeNewBlock () ; 4580LoopBlocks blocks ( head , body , merge , continue_target ) ; 4581loops . push ( blocks ) ; 4582return loops . top () ; 4583} 4584 4585void Builder :: createLoopContinue () 4586{ 4587createBranch ( false , & loops . top () . continue_target ) ; 4588// Set up a block for dead code. 4589createAndSetNoPredecessorBlock ( "post-loop-continue" ) ; 4590} 4591 4592void Builder :: createLoopExit () 4593{ 4594createBranch ( false , & loops . top () . merge ) ; 4595// Set up a block for dead code. 4596createAndSetNoPredecessorBlock ( "post-loop-break" ) ; 4597} 4598 4599void Builder :: closeLoop () 4600{ 4601loops . pop () ; 4602} 4603 4604void Builder :: clearAccessChain () 4605{ 4606accessChain . base = NoResult ; 4607accessChain . indexChain . clear () ; 4608accessChain . instr = NoResult ; 4609accessChain . swizzle . clear () ; 4610accessChain . component = NoResult ; 4611accessChain . preSwizzleBaseType = NoType ; 4612accessChain . isRValue = false ; 4613accessChain . coherentFlags . clear () ; 4614accessChain . alignment = 0 ; 4615accessChain . descHeapInfo . descHeapBaseTy = NoResult ; 4616accessChain . descHeapInfo . descHeapStorageClass = StorageClass :: Max ; 4617accessChain . descHeapInfo . descHeapInstId . clear () ; 4618accessChain . descHeapInfo . descHeapBaseArrayStride = NoResult ; 4619accessChain . descHeapInfo . structRemappedBase = NoResult ; 4620accessChain . descHeapInfo . structRsrcTyOffsetCount = 0 ; 4621accessChain . descHeapInfo . structRsrcTyFirstArrIndex = 0 ; 4622} 4623 4624// Comments in header 4625void Builder :: accessChainPushSwizzle ( std :: vector < unsigned >& swizzle , Id preSwizzleBaseType , 4626AccessChain :: CoherentFlags coherentFlags , unsigned int alignment ) 4627{ 4628accessChain . coherentFlags |= coherentFlags ; 4629accessChain . alignment |= alignment ; 4630 4631// swizzles can be stacked in GLSL, but simplified to a single 4632// one here; the base type doesn't change 4633if ( accessChain . preSwizzleBaseType == NoType ) 4634accessChain . preSwizzleBaseType = preSwizzleBaseType ; 4635 4636// if needed, propagate the swizzle for the current access chain 4637if ( accessChain . swizzle . size () > 0 ) { 4638std :: vector < unsigned > oldSwizzle = accessChain . swizzle ; 4639accessChain . swizzle . resize ( 0 ) ; 4640for ( unsigned int i = 0 ; i < swizzle . size () ; ++ i ) { 4641assert ( swizzle [ i ] < oldSwizzle . size ()) ; 4642accessChain . swizzle . push_back ( oldSwizzle [ swizzle [ i ]]) ; 4643} 4644} else 4645accessChain . swizzle = swizzle ; 4646 4647// determine if we need to track this swizzle anymore 4648simplifyAccessChainSwizzle () ; 4649} 4650 4651// Comments in header 4652void Builder :: accessChainStore ( Id rvalue , Decoration nonUniform , spv :: MemoryAccessMask memoryAccess , spv :: Scope scope , unsigned int alignment ) 4653{ 4654assert ( accessChain . isRValue == false ) ; 4655 4656transferAccessChainSwizzle ( true ) ; 4657 4658// MeshShadingEXT outputs don't support loads, so split swizzled stores 4659bool isMeshOutput = getStorageClass ( accessChain . base ) == StorageClass :: Output && 4660capabilities . find ( spv :: Capability :: MeshShadingEXT ) != capabilities . end () ; 4661 4662// If a swizzle exists and is not full and is not dynamic, then the swizzle will be broken into individual stores. 4663if ( accessChain . swizzle . size () > 0 && 4664(( getNumTypeComponents ( getResultingAccessChainType ()) != accessChain . swizzle . size () && accessChain . component == NoResult ) || isMeshOutput )) { 4665for ( unsigned int i = 0 ; i < accessChain . swizzle . size () ; ++ i ) { 4666accessChain . indexChain . push_back ( makeUintConstant ( accessChain . swizzle [ i ])) ; 4667accessChain . instr = NoResult ; 4668 4669Id base = collapseAccessChain () ; 4670addDecoration ( base , nonUniform ) ; 4671 4672accessChain . indexChain . pop_back () ; 4673accessChain . instr = NoResult ; 4674 4675// dynamic component should be gone 4676assert ( accessChain . component == NoResult ) ; 4677 4678Id source = createCompositeExtract ( rvalue , getContainedTypeId ( getTypeId ( rvalue )) , i ) ; 4679 4680// take LSB of alignment 4681alignment = alignment & ~ ( alignment & ( alignment - 1 )) ; 4682if ( getStorageClass ( base ) == StorageClass :: PhysicalStorageBufferEXT ) { 4683memoryAccess = ( spv :: MemoryAccessMask )( memoryAccess | spv :: MemoryAccessMask :: Aligned ) ; 4684} 4685 4686createStore ( source , base , memoryAccess , scope , alignment ) ; 4687} 4688} 4689else { 4690Id base = collapseAccessChain () ; 4691addDecoration ( base , nonUniform ) ; 4692 4693Id source = rvalue ; 4694 4695// dynamic component should be gone 4696assert ( accessChain . component == NoResult ) ; 4697 4698// If swizzle still exists, it may be out-of-order, we must load the target vector, 4699// extract and insert elements to perform writeMask and/or swizzle. 4700if ( accessChain . swizzle . size () > 0 ) { 4701Id tempBaseId = createLoad ( base , spv :: NoPrecision ) ; 4702source = createLvalueSwizzle ( getTypeId ( tempBaseId ) , tempBaseId , source , accessChain . swizzle ) ; 4703} 4704 4705// take LSB of alignment 4706alignment = alignment & ~ ( alignment & ( alignment - 1 )) ; 4707if ( getStorageClass ( base ) == StorageClass :: PhysicalStorageBufferEXT ) { 4708memoryAccess = ( spv :: MemoryAccessMask )( memoryAccess | spv :: MemoryAccessMask :: Aligned ) ; 4709} 4710 4711createStore ( source , base , memoryAccess , scope , alignment ) ; 4712} 4713} 4714 4715// Comments in header 4716Id Builder :: accessChainLoad ( Decoration precision , Decoration l_nonUniform , 4717Decoration r_nonUniform , Id resultType , spv :: MemoryAccessMask memoryAccess , 4718spv :: Scope scope , unsigned int alignment ) 4719{ 4720Id id ; 4721 4722if ( accessChain . isRValue ) { 4723// transfer access chain, but try to stay in registers 4724transferAccessChainSwizzle ( false ) ; 4725if ( accessChain . indexChain . size () > 0 ) { 4726Id swizzleBase = accessChain . preSwizzleBaseType != NoType ? accessChain . preSwizzleBaseType : resultType ; 4727 4728// if all the accesses are constants, we can use OpCompositeExtract 4729std :: vector < unsigned > indexes ; 4730bool constant = true ; 4731for ( int i = 0 ; i < ( int ) accessChain . indexChain . size () ; ++ i ) { 4732if ( isConstantScalar ( accessChain . indexChain [ i ])) 4733indexes . push_back ( getConstantScalar ( accessChain . indexChain [ i ])) ; 4734else { 4735constant = false ; 4736break ; 4737} 4738} 4739 4740if ( constant ) { 4741id = createCompositeExtract ( accessChain . base , swizzleBase , indexes ) ; 4742setPrecision ( id , precision ) ; 4743} else if ( isVector ( accessChain . base ) || isCooperativeVector ( accessChain . base )) { 4744assert ( accessChain . indexChain . size () == 1 ) ; 4745id = createVectorExtractDynamic ( accessChain . base , resultType , accessChain . indexChain [ 0 ]) ; 4746} else { 4747Id lValue = NoResult ; 4748if ( spvVersion >= Spv_1_4 && isValidInitializer ( accessChain . base )) { 4749// make a new function variable for this r-value, using an initializer, 4750// and mark it as NonWritable so that downstream it can be detected as a lookup 4751// table 4752lValue = createVariable ( NoPrecision , StorageClass :: Function , getTypeId ( accessChain . base ) , 4753"indexable" , accessChain . base ) ; 4754addDecoration ( lValue , Decoration :: NonWritable ) ; 4755} else { 4756lValue = createVariable ( NoPrecision , StorageClass :: Function , getTypeId ( accessChain . base ) , 4757"indexable" ) ; 4758// store into it 4759createStore ( accessChain . base , lValue ) ; 4760} 4761// move base to the new variable 4762accessChain . base = lValue ; 4763accessChain . isRValue = false ; 4764 4765// load through the access chain 4766id = createLoad ( collapseAccessChain () , precision ) ; 4767} 4768} else 4769id = accessChain . base ; // no precision, it was set when this was defined 4770} else { 4771transferAccessChainSwizzle ( true ) ; 4772 4773// take LSB of alignment 4774alignment = alignment & ~ ( alignment & ( alignment - 1 )) ; 4775if ( getStorageClass ( accessChain . base ) == StorageClass :: PhysicalStorageBufferEXT ) { 4776memoryAccess = ( spv :: MemoryAccessMask )( memoryAccess | spv :: MemoryAccessMask :: Aligned ) ; 4777} 4778 4779// load through the access chain 4780id = collapseAccessChain () ; 4781// Apply nonuniform both to the access chain and the loaded value. 4782// Buffer accesses need the access chain decorated, and this is where 4783// loaded image types get decorated. TODO: This should maybe move to 4784// createImageTextureFunctionCall. 4785addDecoration ( id , l_nonUniform ) ; 4786id = createLoad ( id , precision , memoryAccess , scope , alignment ) ; 4787addDecoration ( id , r_nonUniform ) ; 4788} 4789 4790// Done, unless there are swizzles to do 4791if ( accessChain . swizzle . size () == 0 && accessChain . component == NoResult ) 4792return id ; 4793 4794// Do remaining swizzling 4795 4796// Do the basic swizzle 4797if ( accessChain . swizzle . size () > 0 ) { 4798Id swizzledType = getScalarTypeId ( getTypeId ( id )) ; 4799if ( accessChain . swizzle . size () > 1 ) 4800swizzledType = makeVectorType ( swizzledType , ( int ) accessChain . swizzle . size ()) ; 4801id = createRvalueSwizzle ( precision , swizzledType , id , accessChain . swizzle ) ; 4802} 4803 4804// Do the dynamic component 4805if ( accessChain . component != NoResult ) 4806id = setPrecision ( createVectorExtractDynamic ( id , resultType , accessChain . component ) , precision ) ; 4807 4808addDecoration ( id , r_nonUniform ) ; 4809return id ; 4810} 4811 4812Id Builder :: accessChainGetLValue () 4813{ 4814assert ( accessChain . isRValue == false ) ; 4815 4816transferAccessChainSwizzle ( true ) ; 4817Id lvalue = collapseAccessChain () ; 4818 4819// If swizzle exists, it is out-of-order or not full, we must load the target vector, 4820// extract and insert elements to perform writeMask and/or swizzle. This does not 4821// go with getting a direct l-value pointer. 4822assert ( accessChain . swizzle . size () == 0 ) ; 4823assert ( accessChain . component == NoResult ) ; 4824 4825return lvalue ; 4826} 4827 4828// comment in header 4829Id Builder :: accessChainGetInferredType () 4830{ 4831// anything to operate on? 4832// for untyped pointer, it may be remapped to a descriptor heap. 4833// for descriptor heap, its base data type will be determined later, 4834// according to load/store results' types. 4835if ( accessChain . base == NoResult || isUntypedPointer ( accessChain . base ) || 4836isStructureHeapMember ( getTypeId ( accessChain . base ) , accessChain . indexChain , 0 ) != 0 ) 4837return NoType ; 4838Id type = getTypeId ( accessChain . base ) ; 4839// do initial dereference 4840if ( ! accessChain . isRValue ) 4841type = getContainedTypeId ( type ) ; 4842 4843// dereference each index 4844for ( auto it = accessChain . indexChain . cbegin () ; it != accessChain . indexChain . cend () ; ++ it ) { 4845if ( isStructType ( type )) 4846type = getContainedTypeId ( type , getConstantScalar ( * it )) ; 4847else 4848type = getContainedTypeId ( type ) ; 4849} 4850 4851// dereference swizzle 4852if ( accessChain . swizzle . size () == 1 ) 4853type = getContainedTypeId ( type ) ; 4854else if ( accessChain . swizzle . size () > 1 ) 4855type = makeVectorType ( getContainedTypeId ( type ) , ( int ) accessChain . swizzle . size ()) ; 4856 4857// dereference component selection 4858if ( accessChain . component ) 4859type = getContainedTypeId ( type ) ; 4860 4861return type ; 4862} 4863 4864void Builder :: dump ( std :: vector < unsigned int >& out ) const 4865{ 4866// Header, before first instructions: 4867out . push_back ( MagicNumber ) ; 4868out . push_back ( spvVersion ) ; 4869out . push_back ( builderNumber ) ; 4870out . push_back ( uniqueId + 1 ) ; 4871out . push_back ( 0 ) ; 4872 4873// Capabilities 4874for ( auto it = capabilities . cbegin () ; it != capabilities . cend () ; ++ it ) { 4875Instruction capInst ( 0 , 0 , Op :: OpCapability ) ; 4876capInst . addImmediateOperand ( * it ) ; 4877capInst . dump ( out ) ; 4878} 4879 4880for ( auto it = extensions . cbegin () ; it != extensions . cend () ; ++ it ) { 4881Instruction extInst ( 0 , 0 , Op :: OpExtension ) ; 4882extInst . addStringOperand ( it -> c_str ()) ; 4883extInst . dump ( out ) ; 4884} 4885 4886dumpInstructions ( out , imports ) ; 4887Instruction memInst ( 0 , 0 , Op :: OpMemoryModel ) ; 4888memInst . addImmediateOperand ( addressModel ) ; 4889memInst . addImmediateOperand ( memoryModel ) ; 4890memInst . dump ( out ) ; 4891 4892// Instructions saved up while building: 4893dumpInstructions ( out , entryPoints ) ; 4894dumpInstructions ( out , executionModes ) ; 4895 4896// Debug instructions 4897dumpInstructions ( out , strings ) ; 4898dumpSourceInstructions ( out ) ; 4899for ( int e = 0 ; e < ( int ) sourceExtensions . size () ; ++ e ) { 4900Instruction sourceExtInst ( 0 , 0 , Op :: OpSourceExtension ) ; 4901sourceExtInst . addStringOperand ( sourceExtensions [ e ]) ; 4902sourceExtInst . dump ( out ) ; 4903} 4904dumpInstructions ( out , names ) ; 4905dumpModuleProcesses ( out ) ; 4906 4907// Annotation instructions 4908dumpInstructions ( out , decorations ) ; 4909 4910dumpInstructions ( out , constantsTypesGlobals ) ; 4911dumpInstructions ( out , externals ) ; 4912 4913// The functions 4914module . dump ( out ) ; 4915} 4916 4917// 4918// Protected methods. 4919// 4920 4921// Turn the described access chain in 'accessChain' into an instruction(s) 4922// computing its address. This *cannot* include complex swizzles, which must 4923// be handled after this is called. 4924// 4925// Can generate code. 4926Id Builder :: collapseAccessChain () 4927{ 4928assert ( accessChain . isRValue == false ) ; 4929 4930// did we already emit an access chain for this? 4931if ( accessChain . instr != NoResult ) 4932return accessChain . instr ; 4933 4934// If we have a dynamic component, we can still transfer 4935// that into a final operand to the access chain. We need to remap the 4936// dynamic component through the swizzle to get a new dynamic component to 4937// update. 4938// 4939// This was not done in transferAccessChainSwizzle() because it might 4940// generate code. 4941remapDynamicSwizzle () ; 4942if ( accessChain . component != NoResult ) { 4943// transfer the dynamic component to the access chain 4944accessChain . indexChain . push_back ( accessChain . component ) ; 4945accessChain . component = NoResult ; 4946} 4947 4948// note that non-trivial swizzling is left pending 4949 4950// do we have an access chain? 4951if ( accessChain . indexChain . size () == 0 ) 4952return accessChain . base ; 4953 4954// emit the access chain 4955StorageClass storageClass = ( StorageClass ) module . getStorageClass ( getTypeId ( accessChain . base )) ; 4956// when descHeap info is set, use another access chain process. 4957if (( isUntypedPointer ( accessChain . base ) || accessChain . descHeapInfo . structRsrcTyOffsetCount != 0 ) && 4958accessChain . descHeapInfo . descHeapStorageClass != StorageClass :: Max ) { 4959accessChain . instr = createDescHeapAccessChain () ; 4960} else { 4961accessChain . instr = createAccessChain ( storageClass , accessChain . base , accessChain . indexChain ) ; 4962} 4963 4964return accessChain . instr ; 4965} 4966 4967// For a dynamic component selection of a swizzle. 4968// 4969// Turn the swizzle and dynamic component into just a dynamic component. 4970// 4971// Generates code. 4972void Builder :: remapDynamicSwizzle () 4973{ 4974// do we have a swizzle to remap a dynamic component through? 4975if ( accessChain . component != NoResult && accessChain . swizzle . size () > 1 ) { 4976// build a vector of the swizzle for the component to map into 4977std :: vector < Id > components ; 4978for ( int c = 0 ; c < ( int ) accessChain . swizzle . size () ; ++ c ) 4979components . push_back ( makeUintConstant ( accessChain . swizzle [ c ])) ; 4980Id mapType = makeVectorType ( makeUintType ( 32 ) , ( int ) accessChain . swizzle . size ()) ; 4981Id map = makeCompositeConstant ( mapType , components ) ; 4982 4983// use it 4984accessChain . component = createVectorExtractDynamic ( map , makeUintType ( 32 ) , accessChain . component ) ; 4985accessChain . swizzle . clear () ; 4986} 4987} 4988 4989// clear out swizzle if it is redundant, that is reselecting the same components 4990// that would be present without the swizzle. 4991void Builder :: simplifyAccessChainSwizzle () 4992{ 4993// If the swizzle has fewer components than the vector, it is subsetting, and must stay 4994// to preserve that fact. 4995if ( getNumTypeComponents ( accessChain . preSwizzleBaseType ) > accessChain . swizzle . size ()) 4996return ; 4997 4998// if components are out of order, it is a swizzle 4999for ( unsigned int i = 0 ; i < accessChain . swizzle . size () ; ++ i ) { 5000if ( i != accessChain . swizzle [ i ]) 5001return ; 5002} 5003 5004// otherwise, there is no need to track this swizzle 5005accessChain . swizzle . clear () ; 5006if ( accessChain . component == NoResult ) 5007accessChain . preSwizzleBaseType = NoType ; 5008} 5009 5010// To the extent any swizzling can become part of the chain 5011// of accesses instead of a post operation, make it so. 5012// If 'dynamic' is true, include transferring the dynamic component, 5013// otherwise, leave it pending. 5014// 5015// Does not generate code. just updates the access chain. 5016void Builder :: transferAccessChainSwizzle ( bool dynamic ) 5017{ 5018// non existent? 5019if ( accessChain . swizzle . size () == 0 && accessChain . component == NoResult ) 5020return ; 5021 5022// too complex? 5023// (this requires either a swizzle, or generating code for a dynamic component) 5024if ( accessChain . swizzle . size () > 1 ) 5025return ; 5026 5027// single component, either in the swizzle and/or dynamic component 5028if ( accessChain . swizzle . size () == 1 ) { 5029assert ( accessChain . component == NoResult ) ; 5030// handle static component selection 5031accessChain . indexChain . push_back ( makeUintConstant ( accessChain . swizzle . front ())) ; 5032accessChain . swizzle . clear () ; 5033accessChain . preSwizzleBaseType = NoType ; 5034} else if ( dynamic && accessChain . component != NoResult ) { 5035assert ( accessChain . swizzle . size () == 0 ) ; 5036// handle dynamic component 5037accessChain . indexChain . push_back ( accessChain . component ) ; 5038accessChain . preSwizzleBaseType = NoType ; 5039accessChain . component = NoResult ; 5040} 5041} 5042 5043// Utility method for creating a new block and setting the insert point to 5044// be in it. This is useful for flow-control operations that need a "dummy" 5045// block proceeding them (e.g. instructions after a discard, etc). 5046void Builder :: createAndSetNoPredecessorBlock ( const char * /*name*/ ) 5047{ 5048Block * block = new Block ( getUniqueId () , buildPoint -> getParent ()) ; 5049block -> setUnreachable () ; 5050buildPoint -> getParent () . addBlock ( block ) ; 5051setBuildPoint ( block ) ; 5052 5053// if (name) 5054// addName(block->getId(), name); 5055} 5056 5057// Comments in header 5058void Builder :: createBranch ( bool implicit , Block * block ) 5059{ 5060Instruction * branch = new Instruction ( Op :: OpBranch ) ; 5061branch -> addIdOperand ( block -> getId ()) ; 5062if ( implicit ) { 5063addInstructionNoDebugInfo ( std :: unique_ptr < Instruction > ( branch )) ; 5064} 5065else { 5066addInstruction ( std :: unique_ptr < Instruction > ( branch )) ; 5067} 5068block -> addPredecessor ( buildPoint ) ; 5069} 5070 5071// Create OpConstantSizeOfEXT 5072Id Builder :: createConstantSizeOfEXT ( Id typeId ) 5073{ 5074Instruction * inst = new Instruction ( getUniqueId () , makeIntType ( 32 ) , Op :: OpConstantSizeOfEXT ) ; 5075inst -> addIdOperand ( typeId ) ; 5076constantsTypesGlobals . push_back ( std :: unique_ptr < Instruction > ( inst )) ; 5077module . mapInstruction ( inst ) ; 5078return inst -> getResultId () ; 5079} 5080 5081void Builder :: createSelectionMerge ( Block * mergeBlock , SelectionControlMask control ) 5082{ 5083Instruction * merge = new Instruction ( Op :: OpSelectionMerge ) ; 5084merge -> reserveOperands ( 2 ) ; 5085merge -> addIdOperand ( mergeBlock -> getId ()) ; 5086merge -> addImmediateOperand ( control ) ; 5087addInstruction ( std :: unique_ptr < Instruction > ( merge )) ; 5088} 5089 5090void Builder :: createLoopMerge ( Block * mergeBlock , Block * continueBlock , LoopControlMask control , 5091const std :: vector < unsigned int >& operands ) 5092{ 5093Instruction * merge = new Instruction ( Op :: OpLoopMerge ) ; 5094merge -> reserveOperands ( operands . size () + 3 ) ; 5095merge -> addIdOperand ( mergeBlock -> getId ()) ; 5096merge -> addIdOperand ( continueBlock -> getId ()) ; 5097merge -> addImmediateOperand ( control ) ; 5098for ( int op = 0 ; op < ( int ) operands . size () ; ++ op ) 5099merge -> addImmediateOperand ( operands [ op ]) ; 5100addInstruction ( std :: unique_ptr < Instruction > ( merge )) ; 5101} 5102 5103void Builder :: createConditionalBranch ( Id condition , Block * thenBlock , Block * elseBlock ) 5104{ 5105Instruction * branch = new Instruction ( Op :: OpBranchConditional ) ; 5106branch -> reserveOperands ( 3 ) ; 5107branch -> addIdOperand ( condition ) ; 5108branch -> addIdOperand ( thenBlock -> getId ()) ; 5109branch -> addIdOperand ( elseBlock -> getId ()) ; 5110 5111// A conditional branch is always attached to a condition expression 5112addInstructionNoDebugInfo ( std :: unique_ptr < Instruction > ( branch )) ; 5113 5114thenBlock -> addPredecessor ( buildPoint ) ; 5115elseBlock -> addPredecessor ( buildPoint ) ; 5116} 5117 5118// OpSource 5119// [OpSourceContinued] 5120// ... 5121void Builder :: dumpSourceInstructions ( const spv :: Id fileId , const std :: string & text , 5122std :: vector < unsigned int >& out ) const 5123{ 5124const int maxWordCount = 0xFFFF ; 5125const int opSourceWordCount = 4 ; 5126const int nonNullBytesPerInstruction = 4 * ( maxWordCount - opSourceWordCount ) - 1 ; 5127 5128if ( sourceLang != SourceLanguage :: Unknown ) { 5129// OpSource Language Version File Source 5130Instruction sourceInst ( NoResult , NoType , Op :: OpSource ) ; 5131sourceInst . reserveOperands ( 3 ) ; 5132sourceInst . addImmediateOperand ( sourceLang ) ; 5133sourceInst . addImmediateOperand ( sourceVersion ) ; 5134// File operand 5135if ( fileId != NoResult ) { 5136sourceInst . addIdOperand ( fileId ) ; 5137// Source operand 5138if ( text . size () > 0 ) { 5139int nextByte = 0 ; 5140std :: string subString ; 5141while (( int ) text . size () - nextByte > 0 ) { 5142subString = text . substr ( nextByte , nonNullBytesPerInstruction ) ; 5143if ( nextByte == 0 ) { 5144// OpSource 5145sourceInst . addStringOperand ( subString . c_str ()) ; 5146sourceInst . dump ( out ) ; 5147} else { 5148// OpSourcContinued 5149Instruction sourceContinuedInst ( Op :: OpSourceContinued ) ; 5150sourceContinuedInst . addStringOperand ( subString . c_str ()) ; 5151sourceContinuedInst . dump ( out ) ; 5152} 5153nextByte += nonNullBytesPerInstruction ; 5154} 5155} else 5156sourceInst . dump ( out ) ; 5157} else 5158sourceInst . dump ( out ) ; 5159} 5160} 5161 5162// Dump an OpSource[Continued] sequence for the source and every include file 5163void Builder :: dumpSourceInstructions ( std :: vector < unsigned int >& out ) const 5164{ 5165if ( emitNonSemanticShaderDebugInfo ) return ; 5166dumpSourceInstructions ( mainFileId , sourceText , out ) ; 5167for ( auto iItr = includeFiles . begin () ; iItr != includeFiles . end () ; ++ iItr ) 5168dumpSourceInstructions ( iItr -> first , * iItr -> second , out ) ; 5169} 5170 5171template < class Range > void Builder :: dumpInstructions ( std :: vector < unsigned int >& out , const Range & instructions ) const 5172{ 5173for ( const auto & inst : instructions ) { 5174inst -> dump ( out ) ; 5175} 5176} 5177 5178void Builder :: dumpModuleProcesses ( std :: vector < unsigned int >& out ) const 5179{ 5180for ( int i = 0 ; i < ( int ) moduleProcesses . size () ; ++ i ) { 5181Instruction moduleProcessed ( Op :: OpModuleProcessed ) ; 5182moduleProcessed . addStringOperand ( moduleProcesses [ i ]) ; 5183moduleProcessed . dump ( out ) ; 5184} 5185} 5186 5187bool Builder :: DecorationInstructionLessThan :: operator ()( const std :: unique_ptr < Instruction >& lhs , 5188const std :: unique_ptr < Instruction >& rhs ) const 5189{ 5190// Order by the id to which the decoration applies first. This is more intuitive. 5191assert ( lhs -> isIdOperand ( 0 ) && rhs -> isIdOperand ( 0 )) ; 5192if ( lhs -> getIdOperand ( 0 ) != rhs -> getIdOperand ( 0 )) { 5193return lhs -> getIdOperand ( 0 ) < rhs -> getIdOperand ( 0 ) ; 5194} 5195 5196if ( lhs -> getOpCode () != rhs -> getOpCode ()) 5197return lhs -> getOpCode () < rhs -> getOpCode () ; 5198 5199// Now compare the operands. 5200int minSize = std :: min ( lhs -> getNumOperands () , rhs -> getNumOperands ()) ; 5201for ( int i = 1 ; i < minSize ; ++ i ) { 5202if ( lhs -> isIdOperand ( i ) != rhs -> isIdOperand ( i )) { 5203return lhs -> isIdOperand ( i ) < rhs -> isIdOperand ( i ) ; 5204} 5205 5206if ( lhs -> isIdOperand ( i )) { 5207if ( lhs -> getIdOperand ( i ) != rhs -> getIdOperand ( i )) { 5208return lhs -> getIdOperand ( i ) < rhs -> getIdOperand ( i ) ; 5209} 5210} else { 5211if ( lhs -> getImmediateOperand ( i ) != rhs -> getImmediateOperand ( i )) { 5212return lhs -> getImmediateOperand ( i ) < rhs -> getImmediateOperand ( i ) ; 5213} 5214} 5215} 5216 5217if ( lhs -> getNumOperands () != rhs -> getNumOperands ()) 5218return lhs -> getNumOperands () < rhs -> getNumOperands () ; 5219 5220// In this case they are equal. 5221return false ; 5222} 5223} // end spv namespace