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