yum-mirror/glslang

git clone https://git.yummers.dev/yum-mirror/glslang

Wooyoung KimGLSL_EXT_split_barrier / SPV_EXT_split_barrierb8a8b3ed

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