• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
50 #ifndef GLSLANG_WEB
51 #include "hex_float.h"
52 #endif
53 
54 #ifndef _WIN32
55     #include <cstdio>
56 #endif
57 
58 namespace spv {
59 
Builder(unsigned int spvVersion,unsigned int magicNumber,SpvBuildLogger * buildLogger)60 Builder::Builder(unsigned int spvVersion, unsigned int magicNumber, SpvBuildLogger* buildLogger) :
61     spvVersion(spvVersion),
62     source(SourceLanguageUnknown),
63     sourceVersion(0),
64     sourceFileStringId(NoResult),
65     currentLine(0),
66     currentFile(nullptr),
67     emitOpLines(false),
68     addressModel(AddressingModelLogical),
69     memoryModel(MemoryModelGLSL450),
70     builderNumber(magicNumber),
71     buildPoint(0),
72     uniqueId(0),
73     entryPointFunction(0),
74     generatingOpCodeForSpecConst(false),
75     logger(buildLogger)
76 {
77     clearAccessChain();
78 }
79 
~Builder()80 Builder::~Builder()
81 {
82 }
83 
import(const char * name)84 Id Builder::import(const char* name)
85 {
86     Instruction* import = new Instruction(getUniqueId(), NoType, OpExtInstImport);
87     import->addStringOperand(name);
88     module.mapInstruction(import);
89 
90     imports.push_back(std::unique_ptr<Instruction>(import));
91     return import->getResultId();
92 }
93 
94 // Emit instruction for non-filename-based #line directives (ie. no filename
95 // seen yet): emit an OpLine if we've been asked to emit OpLines and the line
96 // number has changed since the last time, and is a valid line number.
setLine(int lineNum)97 void Builder::setLine(int lineNum)
98 {
99     if (lineNum != 0 && lineNum != currentLine) {
100         currentLine = lineNum;
101         if (emitOpLines)
102             addLine(sourceFileStringId, currentLine, 0);
103     }
104 }
105 
106 // If no filename, do non-filename-based #line emit. Else do filename-based emit.
107 // Emit OpLine if we've been asked to emit OpLines and the line number or filename
108 // has changed since the last time, and line number is valid.
setLine(int lineNum,const char * filename)109 void Builder::setLine(int lineNum, const char* filename)
110 {
111     if (filename == nullptr) {
112         setLine(lineNum);
113         return;
114     }
115     if ((lineNum != 0 && lineNum != currentLine) || currentFile == nullptr ||
116             strncmp(filename, currentFile, strlen(currentFile) + 1) != 0) {
117         currentLine = lineNum;
118         currentFile = filename;
119         if (emitOpLines) {
120             spv::Id strId = getStringId(filename);
121             addLine(strId, currentLine, 0);
122         }
123     }
124 }
125 
addLine(Id fileName,int lineNum,int column)126 void Builder::addLine(Id fileName, int lineNum, int column)
127 {
128     Instruction* line = new Instruction(OpLine);
129     line->addIdOperand(fileName);
130     line->addImmediateOperand(lineNum);
131     line->addImmediateOperand(column);
132     buildPoint->addInstruction(std::unique_ptr<Instruction>(line));
133 }
134 
135 // For creating new groupedTypes (will return old type if the requested one was already made).
makeVoidType()136 Id Builder::makeVoidType()
137 {
138     Instruction* type;
139     if (groupedTypes[OpTypeVoid].size() == 0) {
140         type = new Instruction(getUniqueId(), NoType, OpTypeVoid);
141         groupedTypes[OpTypeVoid].push_back(type);
142         constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
143         module.mapInstruction(type);
144     } else
145         type = groupedTypes[OpTypeVoid].back();
146 
147     return type->getResultId();
148 }
149 
makeBoolType()150 Id Builder::makeBoolType()
151 {
152     Instruction* type;
153     if (groupedTypes[OpTypeBool].size() == 0) {
154         type = new Instruction(getUniqueId(), NoType, OpTypeBool);
155         groupedTypes[OpTypeBool].push_back(type);
156         constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
157         module.mapInstruction(type);
158     } else
159         type = groupedTypes[OpTypeBool].back();
160 
161     return type->getResultId();
162 }
163 
makeSamplerType()164 Id Builder::makeSamplerType()
165 {
166     Instruction* type;
167     if (groupedTypes[OpTypeSampler].size() == 0) {
168         type = new Instruction(getUniqueId(), NoType, OpTypeSampler);
169         groupedTypes[OpTypeSampler].push_back(type);
170         constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
171         module.mapInstruction(type);
172     } else
173         type = groupedTypes[OpTypeSampler].back();
174 
175     return type->getResultId();
176 }
177 
makePointer(StorageClass storageClass,Id pointee)178 Id Builder::makePointer(StorageClass storageClass, Id pointee)
179 {
180     // try to find it
181     Instruction* type;
182     for (int t = 0; t < (int)groupedTypes[OpTypePointer].size(); ++t) {
183         type = groupedTypes[OpTypePointer][t];
184         if (type->getImmediateOperand(0) == (unsigned)storageClass &&
185             type->getIdOperand(1) == pointee)
186             return type->getResultId();
187     }
188 
189     // not found, make it
190     type = new Instruction(getUniqueId(), NoType, OpTypePointer);
191     type->addImmediateOperand(storageClass);
192     type->addIdOperand(pointee);
193     groupedTypes[OpTypePointer].push_back(type);
194     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
195     module.mapInstruction(type);
196 
197     return type->getResultId();
198 }
199 
makeForwardPointer(StorageClass storageClass)200 Id Builder::makeForwardPointer(StorageClass storageClass)
201 {
202     // Caching/uniquifying doesn't work here, because we don't know the
203     // pointee type and there can be multiple forward pointers of the same
204     // storage type. Somebody higher up in the stack must keep track.
205     Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeForwardPointer);
206     type->addImmediateOperand(storageClass);
207     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
208     module.mapInstruction(type);
209 
210     return type->getResultId();
211 }
212 
makePointerFromForwardPointer(StorageClass storageClass,Id forwardPointerType,Id pointee)213 Id Builder::makePointerFromForwardPointer(StorageClass storageClass, Id forwardPointerType, Id pointee)
214 {
215     // try to find it
216     Instruction* type;
217     for (int t = 0; t < (int)groupedTypes[OpTypePointer].size(); ++t) {
218         type = groupedTypes[OpTypePointer][t];
219         if (type->getImmediateOperand(0) == (unsigned)storageClass &&
220             type->getIdOperand(1) == pointee)
221             return type->getResultId();
222     }
223 
224     type = new Instruction(forwardPointerType, NoType, OpTypePointer);
225     type->addImmediateOperand(storageClass);
226     type->addIdOperand(pointee);
227     groupedTypes[OpTypePointer].push_back(type);
228     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
229     module.mapInstruction(type);
230 
231     return type->getResultId();
232 }
233 
makeIntegerType(int width,bool hasSign)234 Id Builder::makeIntegerType(int width, bool hasSign)
235 {
236 #ifdef GLSLANG_WEB
237     assert(width == 32);
238     width = 32;
239 #endif
240 
241     // try to find it
242     Instruction* type;
243     for (int t = 0; t < (int)groupedTypes[OpTypeInt].size(); ++t) {
244         type = groupedTypes[OpTypeInt][t];
245         if (type->getImmediateOperand(0) == (unsigned)width &&
246             type->getImmediateOperand(1) == (hasSign ? 1u : 0u))
247             return type->getResultId();
248     }
249 
250     // not found, make it
251     type = new Instruction(getUniqueId(), NoType, OpTypeInt);
252     type->addImmediateOperand(width);
253     type->addImmediateOperand(hasSign ? 1 : 0);
254     groupedTypes[OpTypeInt].push_back(type);
255     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
256     module.mapInstruction(type);
257 
258     // deal with capabilities
259     switch (width) {
260     case 8:
261     case 16:
262         // these are currently handled by storage-type declarations and post processing
263         break;
264     case 64:
265         addCapability(CapabilityInt64);
266         break;
267     default:
268         break;
269     }
270 
271     return type->getResultId();
272 }
273 
makeFloatType(int width)274 Id Builder::makeFloatType(int width)
275 {
276 #ifdef GLSLANG_WEB
277     assert(width == 32);
278     width = 32;
279 #endif
280 
281     // try to find it
282     Instruction* type;
283     for (int t = 0; t < (int)groupedTypes[OpTypeFloat].size(); ++t) {
284         type = groupedTypes[OpTypeFloat][t];
285         if (type->getImmediateOperand(0) == (unsigned)width)
286             return type->getResultId();
287     }
288 
289     // not found, make it
290     type = new Instruction(getUniqueId(), NoType, OpTypeFloat);
291     type->addImmediateOperand(width);
292     groupedTypes[OpTypeFloat].push_back(type);
293     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
294     module.mapInstruction(type);
295 
296     // deal with capabilities
297     switch (width) {
298     case 16:
299         // currently handled by storage-type declarations and post processing
300         break;
301     case 64:
302         addCapability(CapabilityFloat64);
303         break;
304     default:
305         break;
306     }
307 
308     return type->getResultId();
309 }
310 
311 // Make a struct without checking for duplication.
312 // See makeStructResultType() for non-decorated structs
313 // needed as the result of some instructions, which does
314 // check for duplicates.
makeStructType(const std::vector<Id> & members,const char * name)315 Id Builder::makeStructType(const std::vector<Id>& members, const char* name)
316 {
317     // Don't look for previous one, because in the general case,
318     // structs can be duplicated except for decorations.
319 
320     // not found, make it
321     Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeStruct);
322     for (int op = 0; op < (int)members.size(); ++op)
323         type->addIdOperand(members[op]);
324     groupedTypes[OpTypeStruct].push_back(type);
325     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
326     module.mapInstruction(type);
327     addName(type->getResultId(), name);
328 
329     return type->getResultId();
330 }
331 
332 // Make a struct for the simple results of several instructions,
333 // checking for duplication.
makeStructResultType(Id type0,Id type1)334 Id Builder::makeStructResultType(Id type0, Id type1)
335 {
336     // try to find it
337     Instruction* type;
338     for (int t = 0; t < (int)groupedTypes[OpTypeStruct].size(); ++t) {
339         type = groupedTypes[OpTypeStruct][t];
340         if (type->getNumOperands() != 2)
341             continue;
342         if (type->getIdOperand(0) != type0 ||
343             type->getIdOperand(1) != type1)
344             continue;
345         return type->getResultId();
346     }
347 
348     // not found, make it
349     std::vector<spv::Id> members;
350     members.push_back(type0);
351     members.push_back(type1);
352 
353     return makeStructType(members, "ResType");
354 }
355 
makeVectorType(Id component,int size)356 Id Builder::makeVectorType(Id component, int size)
357 {
358     // try to find it
359     Instruction* type;
360     for (int t = 0; t < (int)groupedTypes[OpTypeVector].size(); ++t) {
361         type = groupedTypes[OpTypeVector][t];
362         if (type->getIdOperand(0) == component &&
363             type->getImmediateOperand(1) == (unsigned)size)
364             return type->getResultId();
365     }
366 
367     // not found, make it
368     type = new Instruction(getUniqueId(), NoType, OpTypeVector);
369     type->addIdOperand(component);
370     type->addImmediateOperand(size);
371     groupedTypes[OpTypeVector].push_back(type);
372     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
373     module.mapInstruction(type);
374 
375     return type->getResultId();
376 }
377 
makeMatrixType(Id component,int cols,int rows)378 Id Builder::makeMatrixType(Id component, int cols, int rows)
379 {
380     assert(cols <= maxMatrixSize && rows <= maxMatrixSize);
381 
382     Id column = makeVectorType(component, rows);
383 
384     // try to find it
385     Instruction* type;
386     for (int t = 0; t < (int)groupedTypes[OpTypeMatrix].size(); ++t) {
387         type = groupedTypes[OpTypeMatrix][t];
388         if (type->getIdOperand(0) == column &&
389             type->getImmediateOperand(1) == (unsigned)cols)
390             return type->getResultId();
391     }
392 
393     // not found, make it
394     type = new Instruction(getUniqueId(), NoType, OpTypeMatrix);
395     type->addIdOperand(column);
396     type->addImmediateOperand(cols);
397     groupedTypes[OpTypeMatrix].push_back(type);
398     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
399     module.mapInstruction(type);
400 
401     return type->getResultId();
402 }
403 
makeCooperativeMatrixType(Id component,Id scope,Id rows,Id cols)404 Id Builder::makeCooperativeMatrixType(Id component, Id scope, Id rows, Id cols)
405 {
406     // try to find it
407     Instruction* type;
408     for (int t = 0; t < (int)groupedTypes[OpTypeCooperativeMatrixNV].size(); ++t) {
409         type = groupedTypes[OpTypeCooperativeMatrixNV][t];
410         if (type->getIdOperand(0) == component &&
411             type->getIdOperand(1) == scope &&
412             type->getIdOperand(2) == rows &&
413             type->getIdOperand(3) == cols)
414             return type->getResultId();
415     }
416 
417     // not found, make it
418     type = new Instruction(getUniqueId(), NoType, OpTypeCooperativeMatrixNV);
419     type->addIdOperand(component);
420     type->addIdOperand(scope);
421     type->addIdOperand(rows);
422     type->addIdOperand(cols);
423     groupedTypes[OpTypeCooperativeMatrixNV].push_back(type);
424     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
425     module.mapInstruction(type);
426 
427     return type->getResultId();
428 }
429 
430 
431 // TODO: performance: track arrays per stride
432 // If a stride is supplied (non-zero) make an array.
433 // If no stride (0), reuse previous array types.
434 // 'size' is an Id of a constant or specialization constant of the array size
makeArrayType(Id element,Id sizeId,int stride)435 Id Builder::makeArrayType(Id element, Id sizeId, int stride)
436 {
437     Instruction* type;
438     if (stride == 0) {
439         // try to find existing type
440         for (int t = 0; t < (int)groupedTypes[OpTypeArray].size(); ++t) {
441             type = groupedTypes[OpTypeArray][t];
442             if (type->getIdOperand(0) == element &&
443                 type->getIdOperand(1) == sizeId)
444                 return type->getResultId();
445         }
446     }
447 
448     // not found, make it
449     type = new Instruction(getUniqueId(), NoType, OpTypeArray);
450     type->addIdOperand(element);
451     type->addIdOperand(sizeId);
452     groupedTypes[OpTypeArray].push_back(type);
453     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
454     module.mapInstruction(type);
455 
456     return type->getResultId();
457 }
458 
makeRuntimeArray(Id element)459 Id Builder::makeRuntimeArray(Id element)
460 {
461     Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeRuntimeArray);
462     type->addIdOperand(element);
463     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
464     module.mapInstruction(type);
465 
466     return type->getResultId();
467 }
468 
makeFunctionType(Id returnType,const std::vector<Id> & paramTypes)469 Id Builder::makeFunctionType(Id returnType, const std::vector<Id>& paramTypes)
470 {
471     // try to find it
472     Instruction* type;
473     for (int t = 0; t < (int)groupedTypes[OpTypeFunction].size(); ++t) {
474         type = groupedTypes[OpTypeFunction][t];
475         if (type->getIdOperand(0) != returnType || (int)paramTypes.size() != type->getNumOperands() - 1)
476             continue;
477         bool mismatch = false;
478         for (int p = 0; p < (int)paramTypes.size(); ++p) {
479             if (paramTypes[p] != type->getIdOperand(p + 1)) {
480                 mismatch = true;
481                 break;
482             }
483         }
484         if (! mismatch)
485             return type->getResultId();
486     }
487 
488     // not found, make it
489     type = new Instruction(getUniqueId(), NoType, OpTypeFunction);
490     type->addIdOperand(returnType);
491     for (int p = 0; p < (int)paramTypes.size(); ++p)
492         type->addIdOperand(paramTypes[p]);
493     groupedTypes[OpTypeFunction].push_back(type);
494     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
495     module.mapInstruction(type);
496 
497     return type->getResultId();
498 }
499 
makeImageType(Id sampledType,Dim dim,bool depth,bool arrayed,bool ms,unsigned sampled,ImageFormat format)500 Id Builder::makeImageType(Id sampledType, Dim dim, bool depth, bool arrayed, bool ms, unsigned sampled,
501     ImageFormat format)
502 {
503     assert(sampled == 1 || sampled == 2);
504 
505     // try to find it
506     Instruction* type;
507     for (int t = 0; t < (int)groupedTypes[OpTypeImage].size(); ++t) {
508         type = groupedTypes[OpTypeImage][t];
509         if (type->getIdOperand(0) == sampledType &&
510             type->getImmediateOperand(1) == (unsigned int)dim &&
511             type->getImmediateOperand(2) == (  depth ? 1u : 0u) &&
512             type->getImmediateOperand(3) == (arrayed ? 1u : 0u) &&
513             type->getImmediateOperand(4) == (     ms ? 1u : 0u) &&
514             type->getImmediateOperand(5) == sampled &&
515             type->getImmediateOperand(6) == (unsigned int)format)
516             return type->getResultId();
517     }
518 
519     // not found, make it
520     type = new Instruction(getUniqueId(), NoType, OpTypeImage);
521     type->addIdOperand(sampledType);
522     type->addImmediateOperand(   dim);
523     type->addImmediateOperand(  depth ? 1 : 0);
524     type->addImmediateOperand(arrayed ? 1 : 0);
525     type->addImmediateOperand(     ms ? 1 : 0);
526     type->addImmediateOperand(sampled);
527     type->addImmediateOperand((unsigned int)format);
528 
529     groupedTypes[OpTypeImage].push_back(type);
530     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
531     module.mapInstruction(type);
532 
533 #ifndef GLSLANG_WEB
534     // deal with capabilities
535     switch (dim) {
536     case DimBuffer:
537         if (sampled == 1)
538             addCapability(CapabilitySampledBuffer);
539         else
540             addCapability(CapabilityImageBuffer);
541         break;
542     case Dim1D:
543         if (sampled == 1)
544             addCapability(CapabilitySampled1D);
545         else
546             addCapability(CapabilityImage1D);
547         break;
548     case DimCube:
549         if (arrayed) {
550             if (sampled == 1)
551                 addCapability(CapabilitySampledCubeArray);
552             else
553                 addCapability(CapabilityImageCubeArray);
554         }
555         break;
556     case DimRect:
557         if (sampled == 1)
558             addCapability(CapabilitySampledRect);
559         else
560             addCapability(CapabilityImageRect);
561         break;
562     case DimSubpassData:
563         addCapability(CapabilityInputAttachment);
564         break;
565     default:
566         break;
567     }
568 
569     if (ms) {
570         if (sampled == 2) {
571             // Images used with subpass data are not storage
572             // images, so don't require the capability for them.
573             if (dim != Dim::DimSubpassData)
574                 addCapability(CapabilityStorageImageMultisample);
575             if (arrayed)
576                 addCapability(CapabilityImageMSArray);
577         }
578     }
579 #endif
580 
581     return type->getResultId();
582 }
583 
makeSampledImageType(Id imageType)584 Id Builder::makeSampledImageType(Id imageType)
585 {
586     // try to find it
587     Instruction* type;
588     for (int t = 0; t < (int)groupedTypes[OpTypeSampledImage].size(); ++t) {
589         type = groupedTypes[OpTypeSampledImage][t];
590         if (type->getIdOperand(0) == imageType)
591             return type->getResultId();
592     }
593 
594     // not found, make it
595     type = new Instruction(getUniqueId(), NoType, OpTypeSampledImage);
596     type->addIdOperand(imageType);
597 
598     groupedTypes[OpTypeSampledImage].push_back(type);
599     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
600     module.mapInstruction(type);
601 
602     return type->getResultId();
603 }
604 
605 #ifndef GLSLANG_WEB
makeAccelerationStructureType()606 Id Builder::makeAccelerationStructureType()
607 {
608     Instruction *type;
609     if (groupedTypes[OpTypeAccelerationStructureKHR].size() == 0) {
610         type = new Instruction(getUniqueId(), NoType, OpTypeAccelerationStructureKHR);
611         groupedTypes[OpTypeAccelerationStructureKHR].push_back(type);
612         constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
613         module.mapInstruction(type);
614     } else {
615         type = groupedTypes[OpTypeAccelerationStructureKHR].back();
616     }
617 
618     return type->getResultId();
619 }
620 
makeRayQueryType()621 Id Builder::makeRayQueryType()
622 {
623     Instruction *type;
624     if (groupedTypes[OpTypeRayQueryProvisionalKHR].size() == 0) {
625         type = new Instruction(getUniqueId(), NoType, OpTypeRayQueryProvisionalKHR);
626         groupedTypes[OpTypeRayQueryProvisionalKHR].push_back(type);
627         constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
628         module.mapInstruction(type);
629     } else {
630         type = groupedTypes[OpTypeRayQueryProvisionalKHR].back();
631     }
632 
633     return type->getResultId();
634 }
635 #endif
636 
getDerefTypeId(Id resultId) const637 Id Builder::getDerefTypeId(Id resultId) const
638 {
639     Id typeId = getTypeId(resultId);
640     assert(isPointerType(typeId));
641 
642     return module.getInstruction(typeId)->getIdOperand(1);
643 }
644 
getMostBasicTypeClass(Id typeId) const645 Op Builder::getMostBasicTypeClass(Id typeId) const
646 {
647     Instruction* instr = module.getInstruction(typeId);
648 
649     Op typeClass = instr->getOpCode();
650     switch (typeClass)
651     {
652     case OpTypeVector:
653     case OpTypeMatrix:
654     case OpTypeArray:
655     case OpTypeRuntimeArray:
656         return getMostBasicTypeClass(instr->getIdOperand(0));
657     case OpTypePointer:
658         return getMostBasicTypeClass(instr->getIdOperand(1));
659     default:
660         return typeClass;
661     }
662 }
663 
getNumTypeConstituents(Id typeId) const664 int Builder::getNumTypeConstituents(Id typeId) const
665 {
666     Instruction* instr = module.getInstruction(typeId);
667 
668     switch (instr->getOpCode())
669     {
670     case OpTypeBool:
671     case OpTypeInt:
672     case OpTypeFloat:
673     case OpTypePointer:
674         return 1;
675     case OpTypeVector:
676     case OpTypeMatrix:
677         return instr->getImmediateOperand(1);
678     case OpTypeArray:
679     {
680         Id lengthId = instr->getIdOperand(1);
681         return module.getInstruction(lengthId)->getImmediateOperand(0);
682     }
683     case OpTypeStruct:
684         return instr->getNumOperands();
685     case OpTypeCooperativeMatrixNV:
686         // has only one constituent when used with OpCompositeConstruct.
687         return 1;
688     default:
689         assert(0);
690         return 1;
691     }
692 }
693 
694 // Return the lowest-level type of scalar that an homogeneous composite is made out of.
695 // Typically, this is just to find out if something is made out of ints or floats.
696 // However, it includes returning a structure, if say, it is an array of structure.
getScalarTypeId(Id typeId) const697 Id Builder::getScalarTypeId(Id typeId) const
698 {
699     Instruction* instr = module.getInstruction(typeId);
700 
701     Op typeClass = instr->getOpCode();
702     switch (typeClass)
703     {
704     case OpTypeVoid:
705     case OpTypeBool:
706     case OpTypeInt:
707     case OpTypeFloat:
708     case OpTypeStruct:
709         return instr->getResultId();
710     case OpTypeVector:
711     case OpTypeMatrix:
712     case OpTypeArray:
713     case OpTypeRuntimeArray:
714     case OpTypePointer:
715         return getScalarTypeId(getContainedTypeId(typeId));
716     default:
717         assert(0);
718         return NoResult;
719     }
720 }
721 
722 // Return the type of 'member' of a composite.
getContainedTypeId(Id typeId,int member) const723 Id Builder::getContainedTypeId(Id typeId, int member) const
724 {
725     Instruction* instr = module.getInstruction(typeId);
726 
727     Op typeClass = instr->getOpCode();
728     switch (typeClass)
729     {
730     case OpTypeVector:
731     case OpTypeMatrix:
732     case OpTypeArray:
733     case OpTypeRuntimeArray:
734     case OpTypeCooperativeMatrixNV:
735         return instr->getIdOperand(0);
736     case OpTypePointer:
737         return instr->getIdOperand(1);
738     case OpTypeStruct:
739         return instr->getIdOperand(member);
740     default:
741         assert(0);
742         return NoResult;
743     }
744 }
745 
746 // Return the immediately contained type of a given composite type.
getContainedTypeId(Id typeId) const747 Id Builder::getContainedTypeId(Id typeId) const
748 {
749     return getContainedTypeId(typeId, 0);
750 }
751 
752 // Returns true if 'typeId' is or contains a scalar type declared with 'typeOp'
753 // of width 'width'. The 'width' is only consumed for int and float types.
754 // Returns false otherwise.
containsType(Id typeId,spv::Op typeOp,unsigned int width) const755 bool Builder::containsType(Id typeId, spv::Op typeOp, unsigned int width) const
756 {
757     const Instruction& instr = *module.getInstruction(typeId);
758 
759     Op typeClass = instr.getOpCode();
760     switch (typeClass)
761     {
762     case OpTypeInt:
763     case OpTypeFloat:
764         return typeClass == typeOp && instr.getImmediateOperand(0) == width;
765     case OpTypeStruct:
766         for (int m = 0; m < instr.getNumOperands(); ++m) {
767             if (containsType(instr.getIdOperand(m), typeOp, width))
768                 return true;
769         }
770         return false;
771     case OpTypePointer:
772         return false;
773     case OpTypeVector:
774     case OpTypeMatrix:
775     case OpTypeArray:
776     case OpTypeRuntimeArray:
777         return containsType(getContainedTypeId(typeId), typeOp, width);
778     default:
779         return typeClass == typeOp;
780     }
781 }
782 
783 // return true if the type is a pointer to PhysicalStorageBufferEXT or an
784 // array of such pointers. These require restrict/aliased decorations.
containsPhysicalStorageBufferOrArray(Id typeId) const785 bool Builder::containsPhysicalStorageBufferOrArray(Id typeId) const
786 {
787     const Instruction& instr = *module.getInstruction(typeId);
788 
789     Op typeClass = instr.getOpCode();
790     switch (typeClass)
791     {
792     case OpTypePointer:
793         return getTypeStorageClass(typeId) == StorageClassPhysicalStorageBufferEXT;
794     case OpTypeArray:
795         return containsPhysicalStorageBufferOrArray(getContainedTypeId(typeId));
796     default:
797         return false;
798     }
799 }
800 
801 // See if a scalar constant of this type has already been created, so it
802 // can be reused rather than duplicated.  (Required by the specification).
findScalarConstant(Op typeClass,Op opcode,Id typeId,unsigned value)803 Id Builder::findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned value)
804 {
805     Instruction* constant;
806     for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
807         constant = groupedConstants[typeClass][i];
808         if (constant->getOpCode() == opcode &&
809             constant->getTypeId() == typeId &&
810             constant->getImmediateOperand(0) == value)
811             return constant->getResultId();
812     }
813 
814     return 0;
815 }
816 
817 // Version of findScalarConstant (see above) for scalars that take two operands (e.g. a 'double' or 'int64').
findScalarConstant(Op typeClass,Op opcode,Id typeId,unsigned v1,unsigned v2)818 Id Builder::findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned v1, unsigned v2)
819 {
820     Instruction* constant;
821     for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
822         constant = groupedConstants[typeClass][i];
823         if (constant->getOpCode() == opcode &&
824             constant->getTypeId() == typeId &&
825             constant->getImmediateOperand(0) == v1 &&
826             constant->getImmediateOperand(1) == v2)
827             return constant->getResultId();
828     }
829 
830     return 0;
831 }
832 
833 // Return true if consuming 'opcode' means consuming a constant.
834 // "constant" here means after final transform to executable code,
835 // the value consumed will be a constant, so includes specialization.
isConstantOpCode(Op opcode) const836 bool Builder::isConstantOpCode(Op opcode) const
837 {
838     switch (opcode) {
839     case OpUndef:
840     case OpConstantTrue:
841     case OpConstantFalse:
842     case OpConstant:
843     case OpConstantComposite:
844     case OpConstantSampler:
845     case OpConstantNull:
846     case OpSpecConstantTrue:
847     case OpSpecConstantFalse:
848     case OpSpecConstant:
849     case OpSpecConstantComposite:
850     case OpSpecConstantOp:
851         return true;
852     default:
853         return false;
854     }
855 }
856 
857 // Return true if consuming 'opcode' means consuming a specialization constant.
isSpecConstantOpCode(Op opcode) const858 bool Builder::isSpecConstantOpCode(Op opcode) const
859 {
860     switch (opcode) {
861     case OpSpecConstantTrue:
862     case OpSpecConstantFalse:
863     case OpSpecConstant:
864     case OpSpecConstantComposite:
865     case OpSpecConstantOp:
866         return true;
867     default:
868         return false;
869     }
870 }
871 
makeBoolConstant(bool b,bool specConstant)872 Id Builder::makeBoolConstant(bool b, bool specConstant)
873 {
874     Id typeId = makeBoolType();
875     Instruction* constant;
876     Op opcode = specConstant ? (b ? OpSpecConstantTrue : OpSpecConstantFalse) : (b ? OpConstantTrue : OpConstantFalse);
877 
878     // See if we already made it. Applies only to regular constants, because specialization constants
879     // must remain distinct for the purpose of applying a SpecId decoration.
880     if (! specConstant) {
881         Id existing = 0;
882         for (int i = 0; i < (int)groupedConstants[OpTypeBool].size(); ++i) {
883             constant = groupedConstants[OpTypeBool][i];
884             if (constant->getTypeId() == typeId && constant->getOpCode() == opcode)
885                 existing = constant->getResultId();
886         }
887 
888         if (existing)
889             return existing;
890     }
891 
892     // Make it
893     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
894     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
895     groupedConstants[OpTypeBool].push_back(c);
896     module.mapInstruction(c);
897 
898     return c->getResultId();
899 }
900 
makeIntConstant(Id typeId,unsigned value,bool specConstant)901 Id Builder::makeIntConstant(Id typeId, unsigned value, bool specConstant)
902 {
903     Op opcode = specConstant ? OpSpecConstant : OpConstant;
904 
905     // See if we already made it. Applies only to regular constants, because specialization constants
906     // must remain distinct for the purpose of applying a SpecId decoration.
907     if (! specConstant) {
908         Id existing = findScalarConstant(OpTypeInt, opcode, typeId, value);
909         if (existing)
910             return existing;
911     }
912 
913     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
914     c->addImmediateOperand(value);
915     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
916     groupedConstants[OpTypeInt].push_back(c);
917     module.mapInstruction(c);
918 
919     return c->getResultId();
920 }
921 
makeInt64Constant(Id typeId,unsigned long long value,bool specConstant)922 Id Builder::makeInt64Constant(Id typeId, unsigned long long value, bool specConstant)
923 {
924     Op opcode = specConstant ? OpSpecConstant : OpConstant;
925 
926     unsigned op1 = value & 0xFFFFFFFF;
927     unsigned op2 = value >> 32;
928 
929     // See if we already made it. Applies only to regular constants, because specialization constants
930     // must remain distinct for the purpose of applying a SpecId decoration.
931     if (! specConstant) {
932         Id existing = findScalarConstant(OpTypeInt, opcode, typeId, op1, op2);
933         if (existing)
934             return existing;
935     }
936 
937     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
938     c->addImmediateOperand(op1);
939     c->addImmediateOperand(op2);
940     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
941     groupedConstants[OpTypeInt].push_back(c);
942     module.mapInstruction(c);
943 
944     return c->getResultId();
945 }
946 
makeFloatConstant(float f,bool specConstant)947 Id Builder::makeFloatConstant(float f, bool specConstant)
948 {
949     Op opcode = specConstant ? OpSpecConstant : OpConstant;
950     Id typeId = makeFloatType(32);
951     union { float fl; unsigned int ui; } u;
952     u.fl = f;
953     unsigned value = u.ui;
954 
955     // See if we already made it. Applies only to regular constants, because specialization constants
956     // must remain distinct for the purpose of applying a SpecId decoration.
957     if (! specConstant) {
958         Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, value);
959         if (existing)
960             return existing;
961     }
962 
963     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
964     c->addImmediateOperand(value);
965     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
966     groupedConstants[OpTypeFloat].push_back(c);
967     module.mapInstruction(c);
968 
969     return c->getResultId();
970 }
971 
makeDoubleConstant(double d,bool specConstant)972 Id Builder::makeDoubleConstant(double d, bool specConstant)
973 {
974 #ifdef GLSLANG_WEB
975     assert(0);
976     return NoResult;
977 #else
978     Op opcode = specConstant ? OpSpecConstant : OpConstant;
979     Id typeId = makeFloatType(64);
980     union { double db; unsigned long long ull; } u;
981     u.db = d;
982     unsigned long long value = u.ull;
983     unsigned op1 = value & 0xFFFFFFFF;
984     unsigned op2 = value >> 32;
985 
986     // See if we already made it. Applies only to regular constants, because specialization constants
987     // must remain distinct for the purpose of applying a SpecId decoration.
988     if (! specConstant) {
989         Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, op1, op2);
990         if (existing)
991             return existing;
992     }
993 
994     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
995     c->addImmediateOperand(op1);
996     c->addImmediateOperand(op2);
997     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
998     groupedConstants[OpTypeFloat].push_back(c);
999     module.mapInstruction(c);
1000 
1001     return c->getResultId();
1002 #endif
1003 }
1004 
makeFloat16Constant(float f16,bool specConstant)1005 Id Builder::makeFloat16Constant(float f16, bool specConstant)
1006 {
1007 #ifdef GLSLANG_WEB
1008     assert(0);
1009     return NoResult;
1010 #else
1011     Op opcode = specConstant ? OpSpecConstant : OpConstant;
1012     Id typeId = makeFloatType(16);
1013 
1014     spvutils::HexFloat<spvutils::FloatProxy<float>> fVal(f16);
1015     spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>> f16Val(0);
1016     fVal.castTo(f16Val, spvutils::kRoundToZero);
1017 
1018     unsigned value = f16Val.value().getAsFloat().get_value();
1019 
1020     // See if we already made it. Applies only to regular constants, because specialization constants
1021     // must remain distinct for the purpose of applying a SpecId decoration.
1022     if (!specConstant) {
1023         Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, value);
1024         if (existing)
1025             return existing;
1026     }
1027 
1028     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
1029     c->addImmediateOperand(value);
1030     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
1031     groupedConstants[OpTypeFloat].push_back(c);
1032     module.mapInstruction(c);
1033 
1034     return c->getResultId();
1035 #endif
1036 }
1037 
makeFpConstant(Id type,double d,bool specConstant)1038 Id Builder::makeFpConstant(Id type, double d, bool specConstant)
1039 {
1040 #ifdef GLSLANG_WEB
1041     const int width = 32;
1042     assert(width == getScalarTypeWidth(type));
1043 #else
1044     const int width = getScalarTypeWidth(type);
1045 #endif
1046 
1047     assert(isFloatType(type));
1048 
1049     switch (width) {
1050     case 16:
1051             return makeFloat16Constant((float)d, specConstant);
1052     case 32:
1053             return makeFloatConstant((float)d, specConstant);
1054     case 64:
1055             return makeDoubleConstant(d, specConstant);
1056     default:
1057             break;
1058     }
1059 
1060     assert(false);
1061     return NoResult;
1062 }
1063 
findCompositeConstant(Op typeClass,Id typeId,const std::vector<Id> & comps)1064 Id Builder::findCompositeConstant(Op typeClass, Id typeId, const std::vector<Id>& comps)
1065 {
1066     Instruction* constant = 0;
1067     bool found = false;
1068     for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
1069         constant = groupedConstants[typeClass][i];
1070 
1071         if (constant->getTypeId() != typeId)
1072             continue;
1073 
1074         // same contents?
1075         bool mismatch = false;
1076         for (int op = 0; op < constant->getNumOperands(); ++op) {
1077             if (constant->getIdOperand(op) != comps[op]) {
1078                 mismatch = true;
1079                 break;
1080             }
1081         }
1082         if (! mismatch) {
1083             found = true;
1084             break;
1085         }
1086     }
1087 
1088     return found ? constant->getResultId() : NoResult;
1089 }
1090 
findStructConstant(Id typeId,const std::vector<Id> & comps)1091 Id Builder::findStructConstant(Id typeId, const std::vector<Id>& comps)
1092 {
1093     Instruction* constant = 0;
1094     bool found = false;
1095     for (int i = 0; i < (int)groupedStructConstants[typeId].size(); ++i) {
1096         constant = groupedStructConstants[typeId][i];
1097 
1098         // same contents?
1099         bool mismatch = false;
1100         for (int op = 0; op < constant->getNumOperands(); ++op) {
1101             if (constant->getIdOperand(op) != comps[op]) {
1102                 mismatch = true;
1103                 break;
1104             }
1105         }
1106         if (! mismatch) {
1107             found = true;
1108             break;
1109         }
1110     }
1111 
1112     return found ? constant->getResultId() : NoResult;
1113 }
1114 
1115 // Comments in header
makeCompositeConstant(Id typeId,const std::vector<Id> & members,bool specConstant)1116 Id Builder::makeCompositeConstant(Id typeId, const std::vector<Id>& members, bool specConstant)
1117 {
1118     Op opcode = specConstant ? OpSpecConstantComposite : OpConstantComposite;
1119     assert(typeId);
1120     Op typeClass = getTypeClass(typeId);
1121 
1122     switch (typeClass) {
1123     case OpTypeVector:
1124     case OpTypeArray:
1125     case OpTypeMatrix:
1126     case OpTypeCooperativeMatrixNV:
1127         if (! specConstant) {
1128             Id existing = findCompositeConstant(typeClass, typeId, members);
1129             if (existing)
1130                 return existing;
1131         }
1132         break;
1133     case OpTypeStruct:
1134         if (! specConstant) {
1135             Id existing = findStructConstant(typeId, members);
1136             if (existing)
1137                 return existing;
1138         }
1139         break;
1140     default:
1141         assert(0);
1142         return makeFloatConstant(0.0);
1143     }
1144 
1145     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
1146     for (int op = 0; op < (int)members.size(); ++op)
1147         c->addIdOperand(members[op]);
1148     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
1149     if (typeClass == OpTypeStruct)
1150         groupedStructConstants[typeId].push_back(c);
1151     else
1152         groupedConstants[typeClass].push_back(c);
1153     module.mapInstruction(c);
1154 
1155     return c->getResultId();
1156 }
1157 
addEntryPoint(ExecutionModel model,Function * function,const char * name)1158 Instruction* Builder::addEntryPoint(ExecutionModel model, Function* function, const char* name)
1159 {
1160     Instruction* entryPoint = new Instruction(OpEntryPoint);
1161     entryPoint->addImmediateOperand(model);
1162     entryPoint->addIdOperand(function->getId());
1163     entryPoint->addStringOperand(name);
1164 
1165     entryPoints.push_back(std::unique_ptr<Instruction>(entryPoint));
1166 
1167     return entryPoint;
1168 }
1169 
1170 // Currently relying on the fact that all 'value' of interest are small non-negative values.
addExecutionMode(Function * entryPoint,ExecutionMode mode,int value1,int value2,int value3)1171 void Builder::addExecutionMode(Function* entryPoint, ExecutionMode mode, int value1, int value2, int value3)
1172 {
1173     Instruction* instr = new Instruction(OpExecutionMode);
1174     instr->addIdOperand(entryPoint->getId());
1175     instr->addImmediateOperand(mode);
1176     if (value1 >= 0)
1177         instr->addImmediateOperand(value1);
1178     if (value2 >= 0)
1179         instr->addImmediateOperand(value2);
1180     if (value3 >= 0)
1181         instr->addImmediateOperand(value3);
1182 
1183     executionModes.push_back(std::unique_ptr<Instruction>(instr));
1184 }
1185 
addExecutionMode(Function * entryPoint,ExecutionMode mode,const std::vector<unsigned> & literals)1186 void Builder::addExecutionMode(Function* entryPoint, ExecutionMode mode, const std::vector<unsigned>& literals)
1187 {
1188     Instruction* instr = new Instruction(OpExecutionMode);
1189     instr->addIdOperand(entryPoint->getId());
1190     instr->addImmediateOperand(mode);
1191     for (auto literal : literals)
1192         instr->addImmediateOperand(literal);
1193 
1194     executionModes.push_back(std::unique_ptr<Instruction>(instr));
1195 }
1196 
addExecutionModeId(Function * entryPoint,ExecutionMode mode,const std::vector<Id> & operandIds)1197 void Builder::addExecutionModeId(Function* entryPoint, ExecutionMode mode, const std::vector<Id>& operandIds)
1198 {
1199     Instruction* instr = new Instruction(OpExecutionModeId);
1200     instr->addIdOperand(entryPoint->getId());
1201     instr->addImmediateOperand(mode);
1202     for (auto operandId : operandIds)
1203         instr->addIdOperand(operandId);
1204 
1205     executionModes.push_back(std::unique_ptr<Instruction>(instr));
1206 }
1207 
addName(Id id,const char * string)1208 void Builder::addName(Id id, const char* string)
1209 {
1210     Instruction* name = new Instruction(OpName);
1211     name->addIdOperand(id);
1212     name->addStringOperand(string);
1213 
1214     names.push_back(std::unique_ptr<Instruction>(name));
1215 }
1216 
addMemberName(Id id,int memberNumber,const char * string)1217 void Builder::addMemberName(Id id, int memberNumber, const char* string)
1218 {
1219     Instruction* name = new Instruction(OpMemberName);
1220     name->addIdOperand(id);
1221     name->addImmediateOperand(memberNumber);
1222     name->addStringOperand(string);
1223 
1224     names.push_back(std::unique_ptr<Instruction>(name));
1225 }
1226 
addDecoration(Id id,Decoration decoration,int num)1227 void Builder::addDecoration(Id id, Decoration decoration, int num)
1228 {
1229     if (decoration == spv::DecorationMax)
1230         return;
1231 
1232     Instruction* dec = new Instruction(OpDecorate);
1233     dec->addIdOperand(id);
1234     dec->addImmediateOperand(decoration);
1235     if (num >= 0)
1236         dec->addImmediateOperand(num);
1237 
1238     decorations.push_back(std::unique_ptr<Instruction>(dec));
1239 }
1240 
addDecoration(Id id,Decoration decoration,const char * s)1241 void Builder::addDecoration(Id id, Decoration decoration, const char* s)
1242 {
1243     if (decoration == spv::DecorationMax)
1244         return;
1245 
1246     Instruction* dec = new Instruction(OpDecorateString);
1247     dec->addIdOperand(id);
1248     dec->addImmediateOperand(decoration);
1249     dec->addStringOperand(s);
1250 
1251     decorations.push_back(std::unique_ptr<Instruction>(dec));
1252 }
1253 
addDecoration(Id id,Decoration decoration,const std::vector<unsigned> & literals)1254 void Builder::addDecoration(Id id, Decoration decoration, const std::vector<unsigned>& literals)
1255 {
1256     if (decoration == spv::DecorationMax)
1257         return;
1258 
1259     Instruction* dec = new Instruction(OpDecorate);
1260     dec->addIdOperand(id);
1261     dec->addImmediateOperand(decoration);
1262     for (auto literal : literals)
1263         dec->addImmediateOperand(literal);
1264 
1265     decorations.push_back(std::unique_ptr<Instruction>(dec));
1266 }
1267 
addDecoration(Id id,Decoration decoration,const std::vector<const char * > & strings)1268 void Builder::addDecoration(Id id, Decoration decoration, const std::vector<const char*>& strings)
1269 {
1270     if (decoration == spv::DecorationMax)
1271         return;
1272 
1273     Instruction* dec = new Instruction(OpDecorateString);
1274     dec->addIdOperand(id);
1275     dec->addImmediateOperand(decoration);
1276     for (auto string : strings)
1277         dec->addStringOperand(string);
1278 
1279     decorations.push_back(std::unique_ptr<Instruction>(dec));
1280 }
1281 
addDecorationId(Id id,Decoration decoration,Id idDecoration)1282 void Builder::addDecorationId(Id id, Decoration decoration, Id idDecoration)
1283 {
1284     if (decoration == spv::DecorationMax)
1285         return;
1286 
1287     Instruction* dec = new Instruction(OpDecorateId);
1288     dec->addIdOperand(id);
1289     dec->addImmediateOperand(decoration);
1290     dec->addIdOperand(idDecoration);
1291 
1292     decorations.push_back(std::unique_ptr<Instruction>(dec));
1293 }
1294 
addDecorationId(Id id,Decoration decoration,const std::vector<Id> & operandIds)1295 void Builder::addDecorationId(Id id, Decoration decoration, const std::vector<Id>& operandIds)
1296 {
1297     if(decoration == spv::DecorationMax)
1298         return;
1299 
1300     Instruction* dec = new Instruction(OpDecorateId);
1301     dec->addIdOperand(id);
1302     dec->addImmediateOperand(decoration);
1303 
1304     for (auto operandId : operandIds)
1305         dec->addIdOperand(operandId);
1306 
1307     decorations.push_back(std::unique_ptr<Instruction>(dec));
1308 }
1309 
addMemberDecoration(Id id,unsigned int member,Decoration decoration,int num)1310 void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, int num)
1311 {
1312     if (decoration == spv::DecorationMax)
1313         return;
1314 
1315     Instruction* dec = new Instruction(OpMemberDecorate);
1316     dec->addIdOperand(id);
1317     dec->addImmediateOperand(member);
1318     dec->addImmediateOperand(decoration);
1319     if (num >= 0)
1320         dec->addImmediateOperand(num);
1321 
1322     decorations.push_back(std::unique_ptr<Instruction>(dec));
1323 }
1324 
addMemberDecoration(Id id,unsigned int member,Decoration decoration,const char * s)1325 void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const char *s)
1326 {
1327     if (decoration == spv::DecorationMax)
1328         return;
1329 
1330     Instruction* dec = new Instruction(OpMemberDecorateStringGOOGLE);
1331     dec->addIdOperand(id);
1332     dec->addImmediateOperand(member);
1333     dec->addImmediateOperand(decoration);
1334     dec->addStringOperand(s);
1335 
1336     decorations.push_back(std::unique_ptr<Instruction>(dec));
1337 }
1338 
addMemberDecoration(Id id,unsigned int member,Decoration decoration,const std::vector<unsigned> & literals)1339 void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const std::vector<unsigned>& literals)
1340 {
1341     if (decoration == spv::DecorationMax)
1342         return;
1343 
1344     Instruction* dec = new Instruction(OpMemberDecorate);
1345     dec->addIdOperand(id);
1346     dec->addImmediateOperand(member);
1347     dec->addImmediateOperand(decoration);
1348     for (auto literal : literals)
1349         dec->addImmediateOperand(literal);
1350 
1351     decorations.push_back(std::unique_ptr<Instruction>(dec));
1352 }
1353 
addMemberDecoration(Id id,unsigned int member,Decoration decoration,const std::vector<const char * > & strings)1354 void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const std::vector<const char*>& strings)
1355 {
1356     if (decoration == spv::DecorationMax)
1357         return;
1358 
1359     Instruction* dec = new Instruction(OpMemberDecorateString);
1360     dec->addIdOperand(id);
1361     dec->addImmediateOperand(member);
1362     dec->addImmediateOperand(decoration);
1363     for (auto string : strings)
1364         dec->addStringOperand(string);
1365 
1366     decorations.push_back(std::unique_ptr<Instruction>(dec));
1367 }
1368 
1369 // Comments in header
makeEntryPoint(const char * entryPoint)1370 Function* Builder::makeEntryPoint(const char* entryPoint)
1371 {
1372     assert(! entryPointFunction);
1373 
1374     Block* entry;
1375     std::vector<Id> params;
1376     std::vector<std::vector<Decoration>> decorations;
1377 
1378     entryPointFunction = makeFunctionEntry(NoPrecision, makeVoidType(), entryPoint, params, decorations, &entry);
1379 
1380     return entryPointFunction;
1381 }
1382 
1383 // Comments in header
makeFunctionEntry(Decoration precision,Id returnType,const char * name,const std::vector<Id> & paramTypes,const std::vector<std::vector<Decoration>> & decorations,Block ** entry)1384 Function* Builder::makeFunctionEntry(Decoration precision, Id returnType, const char* name,
1385                                      const std::vector<Id>& paramTypes,
1386                                      const std::vector<std::vector<Decoration>>& decorations, Block **entry)
1387 {
1388     // Make the function and initial instructions in it
1389     Id typeId = makeFunctionType(returnType, paramTypes);
1390     Id firstParamId = paramTypes.size() == 0 ? 0 : getUniqueIds((int)paramTypes.size());
1391     Function* function = new Function(getUniqueId(), returnType, typeId, firstParamId, module);
1392 
1393     // Set up the precisions
1394     setPrecision(function->getId(), precision);
1395     function->setReturnPrecision(precision);
1396     for (unsigned p = 0; p < (unsigned)decorations.size(); ++p) {
1397         for (int d = 0; d < (int)decorations[p].size(); ++d) {
1398             addDecoration(firstParamId + p, decorations[p][d]);
1399             function->addParamPrecision(p, decorations[p][d]);
1400         }
1401     }
1402 
1403     // CFG
1404     if (entry) {
1405         *entry = new Block(getUniqueId(), *function);
1406         function->addBlock(*entry);
1407         setBuildPoint(*entry);
1408     }
1409 
1410     if (name)
1411         addName(function->getId(), name);
1412 
1413     functions.push_back(std::unique_ptr<Function>(function));
1414 
1415     return function;
1416 }
1417 
1418 // Comments in header
makeReturn(bool implicit,Id retVal)1419 void Builder::makeReturn(bool implicit, Id retVal)
1420 {
1421     if (retVal) {
1422         Instruction* inst = new Instruction(NoResult, NoType, OpReturnValue);
1423         inst->addIdOperand(retVal);
1424         buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
1425     } else
1426         buildPoint->addInstruction(std::unique_ptr<Instruction>(new Instruction(NoResult, NoType, OpReturn)));
1427 
1428     if (! implicit)
1429         createAndSetNoPredecessorBlock("post-return");
1430 }
1431 
1432 // Comments in header
leaveFunction()1433 void Builder::leaveFunction()
1434 {
1435     Block* block = buildPoint;
1436     Function& function = buildPoint->getParent();
1437     assert(block);
1438 
1439     // If our function did not contain a return, add a return void now.
1440     if (! block->isTerminated()) {
1441         if (function.getReturnType() == makeVoidType())
1442             makeReturn(true);
1443         else {
1444             makeReturn(true, createUndefined(function.getReturnType()));
1445         }
1446     }
1447 }
1448 
1449 // Comments in header
makeDiscard()1450 void Builder::makeDiscard()
1451 {
1452     buildPoint->addInstruction(std::unique_ptr<Instruction>(new Instruction(OpKill)));
1453     createAndSetNoPredecessorBlock("post-discard");
1454 }
1455 
1456 // Comments in header
createVariable(Decoration precision,StorageClass storageClass,Id type,const char * name,Id initializer)1457 Id Builder::createVariable(Decoration precision, StorageClass storageClass, Id type, const char* name, Id initializer)
1458 {
1459     Id pointerType = makePointer(storageClass, type);
1460     Instruction* inst = new Instruction(getUniqueId(), pointerType, OpVariable);
1461     inst->addImmediateOperand(storageClass);
1462     if (initializer != NoResult)
1463         inst->addIdOperand(initializer);
1464 
1465     switch (storageClass) {
1466     case StorageClassFunction:
1467         // Validation rules require the declaration in the entry block
1468         buildPoint->getParent().addLocalVariable(std::unique_ptr<Instruction>(inst));
1469         break;
1470 
1471     default:
1472         constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
1473         module.mapInstruction(inst);
1474         break;
1475     }
1476 
1477     if (name)
1478         addName(inst->getResultId(), name);
1479     setPrecision(inst->getResultId(), precision);
1480 
1481     return inst->getResultId();
1482 }
1483 
1484 // Comments in header
createUndefined(Id type)1485 Id Builder::createUndefined(Id type)
1486 {
1487   Instruction* inst = new Instruction(getUniqueId(), type, OpUndef);
1488   buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
1489   return inst->getResultId();
1490 }
1491 
1492 // av/vis/nonprivate are unnecessary and illegal for some storage classes.
sanitizeMemoryAccessForStorageClass(spv::MemoryAccessMask memoryAccess,StorageClass sc) const1493 spv::MemoryAccessMask Builder::sanitizeMemoryAccessForStorageClass(spv::MemoryAccessMask memoryAccess, StorageClass sc)
1494     const
1495 {
1496     switch (sc) {
1497     case spv::StorageClassUniform:
1498     case spv::StorageClassWorkgroup:
1499     case spv::StorageClassStorageBuffer:
1500     case spv::StorageClassPhysicalStorageBufferEXT:
1501         break;
1502     default:
1503         memoryAccess = spv::MemoryAccessMask(memoryAccess &
1504                         ~(spv::MemoryAccessMakePointerAvailableKHRMask |
1505                           spv::MemoryAccessMakePointerVisibleKHRMask |
1506                           spv::MemoryAccessNonPrivatePointerKHRMask));
1507         break;
1508     }
1509     return memoryAccess;
1510 }
1511 
1512 // Comments in header
createStore(Id rValue,Id lValue,spv::MemoryAccessMask memoryAccess,spv::Scope scope,unsigned int alignment)1513 void Builder::createStore(Id rValue, Id lValue, spv::MemoryAccessMask memoryAccess, spv::Scope scope,
1514     unsigned int alignment)
1515 {
1516     Instruction* store = new Instruction(OpStore);
1517     store->addIdOperand(lValue);
1518     store->addIdOperand(rValue);
1519 
1520     memoryAccess = sanitizeMemoryAccessForStorageClass(memoryAccess, getStorageClass(lValue));
1521 
1522     if (memoryAccess != MemoryAccessMaskNone) {
1523         store->addImmediateOperand(memoryAccess);
1524         if (memoryAccess & spv::MemoryAccessAlignedMask) {
1525             store->addImmediateOperand(alignment);
1526         }
1527         if (memoryAccess & spv::MemoryAccessMakePointerAvailableKHRMask) {
1528             store->addIdOperand(makeUintConstant(scope));
1529         }
1530     }
1531 
1532     buildPoint->addInstruction(std::unique_ptr<Instruction>(store));
1533 }
1534 
1535 // Comments in header
createLoad(Id lValue,spv::Decoration precision,spv::MemoryAccessMask memoryAccess,spv::Scope scope,unsigned int alignment)1536 Id Builder::createLoad(Id lValue, spv::Decoration precision, spv::MemoryAccessMask memoryAccess,
1537     spv::Scope scope, unsigned int alignment)
1538 {
1539     Instruction* load = new Instruction(getUniqueId(), getDerefTypeId(lValue), OpLoad);
1540     load->addIdOperand(lValue);
1541 
1542     memoryAccess = sanitizeMemoryAccessForStorageClass(memoryAccess, getStorageClass(lValue));
1543 
1544     if (memoryAccess != MemoryAccessMaskNone) {
1545         load->addImmediateOperand(memoryAccess);
1546         if (memoryAccess & spv::MemoryAccessAlignedMask) {
1547             load->addImmediateOperand(alignment);
1548         }
1549         if (memoryAccess & spv::MemoryAccessMakePointerVisibleKHRMask) {
1550             load->addIdOperand(makeUintConstant(scope));
1551         }
1552     }
1553 
1554     buildPoint->addInstruction(std::unique_ptr<Instruction>(load));
1555     setPrecision(load->getResultId(), precision);
1556 
1557     return load->getResultId();
1558 }
1559 
1560 // Comments in header
createAccessChain(StorageClass storageClass,Id base,const std::vector<Id> & offsets)1561 Id Builder::createAccessChain(StorageClass storageClass, Id base, const std::vector<Id>& offsets)
1562 {
1563     // Figure out the final resulting type.
1564     spv::Id typeId = getTypeId(base);
1565     assert(isPointerType(typeId) && offsets.size() > 0);
1566     typeId = getContainedTypeId(typeId);
1567     for (int i = 0; i < (int)offsets.size(); ++i) {
1568         if (isStructType(typeId)) {
1569             assert(isConstantScalar(offsets[i]));
1570             typeId = getContainedTypeId(typeId, getConstantScalar(offsets[i]));
1571         } else
1572             typeId = getContainedTypeId(typeId, offsets[i]);
1573     }
1574     typeId = makePointer(storageClass, typeId);
1575 
1576     // Make the instruction
1577     Instruction* chain = new Instruction(getUniqueId(), typeId, OpAccessChain);
1578     chain->addIdOperand(base);
1579     for (int i = 0; i < (int)offsets.size(); ++i)
1580         chain->addIdOperand(offsets[i]);
1581     buildPoint->addInstruction(std::unique_ptr<Instruction>(chain));
1582 
1583     return chain->getResultId();
1584 }
1585 
createArrayLength(Id base,unsigned int member)1586 Id Builder::createArrayLength(Id base, unsigned int member)
1587 {
1588     spv::Id intType = makeUintType(32);
1589     Instruction* length = new Instruction(getUniqueId(), intType, OpArrayLength);
1590     length->addIdOperand(base);
1591     length->addImmediateOperand(member);
1592     buildPoint->addInstruction(std::unique_ptr<Instruction>(length));
1593 
1594     return length->getResultId();
1595 }
1596 
createCooperativeMatrixLength(Id type)1597 Id Builder::createCooperativeMatrixLength(Id type)
1598 {
1599     spv::Id intType = makeUintType(32);
1600 
1601     // Generate code for spec constants if in spec constant operation
1602     // generation mode.
1603     if (generatingOpCodeForSpecConst) {
1604         return createSpecConstantOp(OpCooperativeMatrixLengthNV, intType, std::vector<Id>(1, type), std::vector<Id>());
1605     }
1606 
1607     Instruction* length = new Instruction(getUniqueId(), intType, OpCooperativeMatrixLengthNV);
1608     length->addIdOperand(type);
1609     buildPoint->addInstruction(std::unique_ptr<Instruction>(length));
1610 
1611     return length->getResultId();
1612 }
1613 
createCompositeExtract(Id composite,Id typeId,unsigned index)1614 Id Builder::createCompositeExtract(Id composite, Id typeId, unsigned index)
1615 {
1616     // Generate code for spec constants if in spec constant operation
1617     // generation mode.
1618     if (generatingOpCodeForSpecConst) {
1619         return createSpecConstantOp(OpCompositeExtract, typeId, std::vector<Id>(1, composite),
1620             std::vector<Id>(1, index));
1621     }
1622     Instruction* extract = new Instruction(getUniqueId(), typeId, OpCompositeExtract);
1623     extract->addIdOperand(composite);
1624     extract->addImmediateOperand(index);
1625     buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
1626 
1627     return extract->getResultId();
1628 }
1629 
createCompositeExtract(Id composite,Id typeId,const std::vector<unsigned> & indexes)1630 Id Builder::createCompositeExtract(Id composite, Id typeId, const std::vector<unsigned>& indexes)
1631 {
1632     // Generate code for spec constants if in spec constant operation
1633     // generation mode.
1634     if (generatingOpCodeForSpecConst) {
1635         return createSpecConstantOp(OpCompositeExtract, typeId, std::vector<Id>(1, composite), indexes);
1636     }
1637     Instruction* extract = new Instruction(getUniqueId(), typeId, OpCompositeExtract);
1638     extract->addIdOperand(composite);
1639     for (int i = 0; i < (int)indexes.size(); ++i)
1640         extract->addImmediateOperand(indexes[i]);
1641     buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
1642 
1643     return extract->getResultId();
1644 }
1645 
createCompositeInsert(Id object,Id composite,Id typeId,unsigned index)1646 Id Builder::createCompositeInsert(Id object, Id composite, Id typeId, unsigned index)
1647 {
1648     Instruction* insert = new Instruction(getUniqueId(), typeId, OpCompositeInsert);
1649     insert->addIdOperand(object);
1650     insert->addIdOperand(composite);
1651     insert->addImmediateOperand(index);
1652     buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
1653 
1654     return insert->getResultId();
1655 }
1656 
createCompositeInsert(Id object,Id composite,Id typeId,const std::vector<unsigned> & indexes)1657 Id Builder::createCompositeInsert(Id object, Id composite, Id typeId, const std::vector<unsigned>& indexes)
1658 {
1659     Instruction* insert = new Instruction(getUniqueId(), typeId, OpCompositeInsert);
1660     insert->addIdOperand(object);
1661     insert->addIdOperand(composite);
1662     for (int i = 0; i < (int)indexes.size(); ++i)
1663         insert->addImmediateOperand(indexes[i]);
1664     buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
1665 
1666     return insert->getResultId();
1667 }
1668 
createVectorExtractDynamic(Id vector,Id typeId,Id componentIndex)1669 Id Builder::createVectorExtractDynamic(Id vector, Id typeId, Id componentIndex)
1670 {
1671     Instruction* extract = new Instruction(getUniqueId(), typeId, OpVectorExtractDynamic);
1672     extract->addIdOperand(vector);
1673     extract->addIdOperand(componentIndex);
1674     buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
1675 
1676     return extract->getResultId();
1677 }
1678 
createVectorInsertDynamic(Id vector,Id typeId,Id component,Id componentIndex)1679 Id Builder::createVectorInsertDynamic(Id vector, Id typeId, Id component, Id componentIndex)
1680 {
1681     Instruction* insert = new Instruction(getUniqueId(), typeId, OpVectorInsertDynamic);
1682     insert->addIdOperand(vector);
1683     insert->addIdOperand(component);
1684     insert->addIdOperand(componentIndex);
1685     buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
1686 
1687     return insert->getResultId();
1688 }
1689 
1690 // An opcode that has no operands, no result id, and no type
createNoResultOp(Op opCode)1691 void Builder::createNoResultOp(Op opCode)
1692 {
1693     Instruction* op = new Instruction(opCode);
1694     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1695 }
1696 
1697 // An opcode that has one id operand, no result id, and no type
createNoResultOp(Op opCode,Id operand)1698 void Builder::createNoResultOp(Op opCode, Id operand)
1699 {
1700     Instruction* op = new Instruction(opCode);
1701     op->addIdOperand(operand);
1702     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1703 }
1704 
1705 // An opcode that has one or more operands, no result id, and no type
createNoResultOp(Op opCode,const std::vector<Id> & operands)1706 void Builder::createNoResultOp(Op opCode, const std::vector<Id>& operands)
1707 {
1708     Instruction* op = new Instruction(opCode);
1709     for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
1710         op->addIdOperand(*it);
1711     }
1712     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1713 }
1714 
1715 // An opcode that has multiple operands, no result id, and no type
createNoResultOp(Op opCode,const std::vector<IdImmediate> & operands)1716 void Builder::createNoResultOp(Op opCode, const std::vector<IdImmediate>& operands)
1717 {
1718     Instruction* op = new Instruction(opCode);
1719     for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
1720         if (it->isId)
1721             op->addIdOperand(it->word);
1722         else
1723             op->addImmediateOperand(it->word);
1724     }
1725     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1726 }
1727 
createControlBarrier(Scope execution,Scope memory,MemorySemanticsMask semantics)1728 void Builder::createControlBarrier(Scope execution, Scope memory, MemorySemanticsMask semantics)
1729 {
1730     Instruction* op = new Instruction(OpControlBarrier);
1731     op->addIdOperand(makeUintConstant(execution));
1732     op->addIdOperand(makeUintConstant(memory));
1733     op->addIdOperand(makeUintConstant(semantics));
1734     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1735 }
1736 
createMemoryBarrier(unsigned executionScope,unsigned memorySemantics)1737 void Builder::createMemoryBarrier(unsigned executionScope, unsigned memorySemantics)
1738 {
1739     Instruction* op = new Instruction(OpMemoryBarrier);
1740     op->addIdOperand(makeUintConstant(executionScope));
1741     op->addIdOperand(makeUintConstant(memorySemantics));
1742     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1743 }
1744 
1745 // An opcode that has one operands, a result id, and a type
createUnaryOp(Op opCode,Id typeId,Id operand)1746 Id Builder::createUnaryOp(Op opCode, Id typeId, Id operand)
1747 {
1748     // Generate code for spec constants if in spec constant operation
1749     // generation mode.
1750     if (generatingOpCodeForSpecConst) {
1751         return createSpecConstantOp(opCode, typeId, std::vector<Id>(1, operand), std::vector<Id>());
1752     }
1753     Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
1754     op->addIdOperand(operand);
1755     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1756 
1757     return op->getResultId();
1758 }
1759 
createBinOp(Op opCode,Id typeId,Id left,Id right)1760 Id Builder::createBinOp(Op opCode, Id typeId, Id left, Id right)
1761 {
1762     // Generate code for spec constants if in spec constant operation
1763     // generation mode.
1764     if (generatingOpCodeForSpecConst) {
1765         std::vector<Id> operands(2);
1766         operands[0] = left; operands[1] = right;
1767         return createSpecConstantOp(opCode, typeId, operands, std::vector<Id>());
1768     }
1769     Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
1770     op->addIdOperand(left);
1771     op->addIdOperand(right);
1772     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1773 
1774     return op->getResultId();
1775 }
1776 
createTriOp(Op opCode,Id typeId,Id op1,Id op2,Id op3)1777 Id Builder::createTriOp(Op opCode, Id typeId, Id op1, Id op2, Id op3)
1778 {
1779     // Generate code for spec constants if in spec constant operation
1780     // generation mode.
1781     if (generatingOpCodeForSpecConst) {
1782         std::vector<Id> operands(3);
1783         operands[0] = op1;
1784         operands[1] = op2;
1785         operands[2] = op3;
1786         return createSpecConstantOp(
1787             opCode, typeId, operands, std::vector<Id>());
1788     }
1789     Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
1790     op->addIdOperand(op1);
1791     op->addIdOperand(op2);
1792     op->addIdOperand(op3);
1793     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1794 
1795     return op->getResultId();
1796 }
1797 
createOp(Op opCode,Id typeId,const std::vector<Id> & operands)1798 Id Builder::createOp(Op opCode, Id typeId, const std::vector<Id>& operands)
1799 {
1800     Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
1801     for (auto it = operands.cbegin(); it != operands.cend(); ++it)
1802         op->addIdOperand(*it);
1803     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1804 
1805     return op->getResultId();
1806 }
1807 
createOp(Op opCode,Id typeId,const std::vector<IdImmediate> & operands)1808 Id Builder::createOp(Op opCode, Id typeId, const std::vector<IdImmediate>& operands)
1809 {
1810     Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
1811     for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
1812         if (it->isId)
1813             op->addIdOperand(it->word);
1814         else
1815             op->addImmediateOperand(it->word);
1816     }
1817     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1818 
1819     return op->getResultId();
1820 }
1821 
createSpecConstantOp(Op opCode,Id typeId,const std::vector<Id> & operands,const std::vector<unsigned> & literals)1822 Id Builder::createSpecConstantOp(Op opCode, Id typeId, const std::vector<Id>& operands,
1823     const std::vector<unsigned>& literals)
1824 {
1825     Instruction* op = new Instruction(getUniqueId(), typeId, OpSpecConstantOp);
1826     op->addImmediateOperand((unsigned) opCode);
1827     for (auto it = operands.cbegin(); it != operands.cend(); ++it)
1828         op->addIdOperand(*it);
1829     for (auto it = literals.cbegin(); it != literals.cend(); ++it)
1830         op->addImmediateOperand(*it);
1831     module.mapInstruction(op);
1832     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(op));
1833 
1834     return op->getResultId();
1835 }
1836 
createFunctionCall(spv::Function * function,const std::vector<spv::Id> & args)1837 Id Builder::createFunctionCall(spv::Function* function, const std::vector<spv::Id>& args)
1838 {
1839     Instruction* op = new Instruction(getUniqueId(), function->getReturnType(), OpFunctionCall);
1840     op->addIdOperand(function->getId());
1841     for (int a = 0; a < (int)args.size(); ++a)
1842         op->addIdOperand(args[a]);
1843     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1844 
1845     return op->getResultId();
1846 }
1847 
1848 // Comments in header
createRvalueSwizzle(Decoration precision,Id typeId,Id source,const std::vector<unsigned> & channels)1849 Id Builder::createRvalueSwizzle(Decoration precision, Id typeId, Id source, const std::vector<unsigned>& channels)
1850 {
1851     if (channels.size() == 1)
1852         return setPrecision(createCompositeExtract(source, typeId, channels.front()), precision);
1853 
1854     if (generatingOpCodeForSpecConst) {
1855         std::vector<Id> operands(2);
1856         operands[0] = operands[1] = source;
1857         return setPrecision(createSpecConstantOp(OpVectorShuffle, typeId, operands, channels), precision);
1858     }
1859     Instruction* swizzle = new Instruction(getUniqueId(), typeId, OpVectorShuffle);
1860     assert(isVector(source));
1861     swizzle->addIdOperand(source);
1862     swizzle->addIdOperand(source);
1863     for (int i = 0; i < (int)channels.size(); ++i)
1864         swizzle->addImmediateOperand(channels[i]);
1865     buildPoint->addInstruction(std::unique_ptr<Instruction>(swizzle));
1866 
1867     return setPrecision(swizzle->getResultId(), precision);
1868 }
1869 
1870 // Comments in header
createLvalueSwizzle(Id typeId,Id target,Id source,const std::vector<unsigned> & channels)1871 Id Builder::createLvalueSwizzle(Id typeId, Id target, Id source, const std::vector<unsigned>& channels)
1872 {
1873     if (channels.size() == 1 && getNumComponents(source) == 1)
1874         return createCompositeInsert(source, target, typeId, channels.front());
1875 
1876     Instruction* swizzle = new Instruction(getUniqueId(), typeId, OpVectorShuffle);
1877 
1878     assert(isVector(target));
1879     swizzle->addIdOperand(target);
1880 
1881     assert(getNumComponents(source) == (int)channels.size());
1882     assert(isVector(source));
1883     swizzle->addIdOperand(source);
1884 
1885     // Set up an identity shuffle from the base value to the result value
1886     unsigned int components[4];
1887     int numTargetComponents = getNumComponents(target);
1888     for (int i = 0; i < numTargetComponents; ++i)
1889         components[i] = i;
1890 
1891     // Punch in the l-value swizzle
1892     for (int i = 0; i < (int)channels.size(); ++i)
1893         components[channels[i]] = numTargetComponents + i;
1894 
1895     // finish the instruction with these components selectors
1896     for (int i = 0; i < numTargetComponents; ++i)
1897         swizzle->addImmediateOperand(components[i]);
1898     buildPoint->addInstruction(std::unique_ptr<Instruction>(swizzle));
1899 
1900     return swizzle->getResultId();
1901 }
1902 
1903 // Comments in header
promoteScalar(Decoration precision,Id & left,Id & right)1904 void Builder::promoteScalar(Decoration precision, Id& left, Id& right)
1905 {
1906     int direction = getNumComponents(right) - getNumComponents(left);
1907 
1908     if (direction > 0)
1909         left = smearScalar(precision, left, makeVectorType(getTypeId(left), getNumComponents(right)));
1910     else if (direction < 0)
1911         right = smearScalar(precision, right, makeVectorType(getTypeId(right), getNumComponents(left)));
1912 
1913     return;
1914 }
1915 
1916 // Comments in header
smearScalar(Decoration precision,Id scalar,Id vectorType)1917 Id Builder::smearScalar(Decoration precision, Id scalar, Id vectorType)
1918 {
1919     assert(getNumComponents(scalar) == 1);
1920     assert(getTypeId(scalar) == getScalarTypeId(vectorType));
1921 
1922     int numComponents = getNumTypeComponents(vectorType);
1923     if (numComponents == 1)
1924         return scalar;
1925 
1926     Instruction* smear = nullptr;
1927     if (generatingOpCodeForSpecConst) {
1928         auto members = std::vector<spv::Id>(numComponents, scalar);
1929         // Sometime even in spec-constant-op mode, the temporary vector created by
1930         // promoting a scalar might not be a spec constant. This should depend on
1931         // the scalar.
1932         // e.g.:
1933         //  const vec2 spec_const_result = a_spec_const_vec2 + a_front_end_const_scalar;
1934         // In such cases, the temporary vector created from a_front_end_const_scalar
1935         // is not a spec constant vector, even though the binary operation node is marked
1936         // as 'specConstant' and we are in spec-constant-op mode.
1937         auto result_id = makeCompositeConstant(vectorType, members, isSpecConstant(scalar));
1938         smear = module.getInstruction(result_id);
1939     } else {
1940         smear = new Instruction(getUniqueId(), vectorType, OpCompositeConstruct);
1941         for (int c = 0; c < numComponents; ++c)
1942             smear->addIdOperand(scalar);
1943         buildPoint->addInstruction(std::unique_ptr<Instruction>(smear));
1944     }
1945 
1946     return setPrecision(smear->getResultId(), precision);
1947 }
1948 
1949 // Comments in header
createBuiltinCall(Id resultType,Id builtins,int entryPoint,const std::vector<Id> & args)1950 Id Builder::createBuiltinCall(Id resultType, Id builtins, int entryPoint, const std::vector<Id>& args)
1951 {
1952     Instruction* inst = new Instruction(getUniqueId(), resultType, OpExtInst);
1953     inst->addIdOperand(builtins);
1954     inst->addImmediateOperand(entryPoint);
1955     for (int arg = 0; arg < (int)args.size(); ++arg)
1956         inst->addIdOperand(args[arg]);
1957 
1958     buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
1959 
1960     return inst->getResultId();
1961 }
1962 
1963 // Accept all parameters needed to create a texture instruction.
1964 // Create the correct instruction based on the inputs, and make the call.
createTextureCall(Decoration precision,Id resultType,bool sparse,bool fetch,bool proj,bool gather,bool noImplicitLod,const TextureParameters & parameters,ImageOperandsMask signExtensionMask)1965 Id Builder::createTextureCall(Decoration precision, Id resultType, bool sparse, bool fetch, bool proj, bool gather,
1966     bool noImplicitLod, const TextureParameters& parameters, ImageOperandsMask signExtensionMask)
1967 {
1968     static const int maxTextureArgs = 10;
1969     Id texArgs[maxTextureArgs] = {};
1970 
1971     //
1972     // Set up the fixed arguments
1973     //
1974     int numArgs = 0;
1975     bool explicitLod = false;
1976     texArgs[numArgs++] = parameters.sampler;
1977     texArgs[numArgs++] = parameters.coords;
1978     if (parameters.Dref != NoResult)
1979         texArgs[numArgs++] = parameters.Dref;
1980     if (parameters.component != NoResult)
1981         texArgs[numArgs++] = parameters.component;
1982 
1983 #ifndef GLSLANG_WEB
1984     if (parameters.granularity != NoResult)
1985         texArgs[numArgs++] = parameters.granularity;
1986     if (parameters.coarse != NoResult)
1987         texArgs[numArgs++] = parameters.coarse;
1988 #endif
1989 
1990     //
1991     // Set up the optional arguments
1992     //
1993     int optArgNum = numArgs;    // track which operand, if it exists, is the mask of optional arguments
1994     ++numArgs;                  // speculatively make room for the mask operand
1995     ImageOperandsMask mask = ImageOperandsMaskNone; // the mask operand
1996     if (parameters.bias) {
1997         mask = (ImageOperandsMask)(mask | ImageOperandsBiasMask);
1998         texArgs[numArgs++] = parameters.bias;
1999     }
2000     if (parameters.lod) {
2001         mask = (ImageOperandsMask)(mask | ImageOperandsLodMask);
2002         texArgs[numArgs++] = parameters.lod;
2003         explicitLod = true;
2004     } else if (parameters.gradX) {
2005         mask = (ImageOperandsMask)(mask | ImageOperandsGradMask);
2006         texArgs[numArgs++] = parameters.gradX;
2007         texArgs[numArgs++] = parameters.gradY;
2008         explicitLod = true;
2009     } else if (noImplicitLod && ! fetch && ! gather) {
2010         // have to explicitly use lod of 0 if not allowed to have them be implicit, and
2011         // we would otherwise be about to issue an implicit instruction
2012         mask = (ImageOperandsMask)(mask | ImageOperandsLodMask);
2013         texArgs[numArgs++] = makeFloatConstant(0.0);
2014         explicitLod = true;
2015     }
2016     if (parameters.offset) {
2017         if (isConstant(parameters.offset))
2018             mask = (ImageOperandsMask)(mask | ImageOperandsConstOffsetMask);
2019         else {
2020             addCapability(CapabilityImageGatherExtended);
2021             mask = (ImageOperandsMask)(mask | ImageOperandsOffsetMask);
2022         }
2023         texArgs[numArgs++] = parameters.offset;
2024     }
2025     if (parameters.offsets) {
2026         addCapability(CapabilityImageGatherExtended);
2027         mask = (ImageOperandsMask)(mask | ImageOperandsConstOffsetsMask);
2028         texArgs[numArgs++] = parameters.offsets;
2029     }
2030 #ifndef GLSLANG_WEB
2031     if (parameters.sample) {
2032         mask = (ImageOperandsMask)(mask | ImageOperandsSampleMask);
2033         texArgs[numArgs++] = parameters.sample;
2034     }
2035     if (parameters.lodClamp) {
2036         // capability if this bit is used
2037         addCapability(CapabilityMinLod);
2038 
2039         mask = (ImageOperandsMask)(mask | ImageOperandsMinLodMask);
2040         texArgs[numArgs++] = parameters.lodClamp;
2041     }
2042     if (parameters.nonprivate) {
2043         mask = mask | ImageOperandsNonPrivateTexelKHRMask;
2044     }
2045     if (parameters.volatil) {
2046         mask = mask | ImageOperandsVolatileTexelKHRMask;
2047     }
2048 #endif
2049     mask = mask | signExtensionMask;
2050     if (mask == ImageOperandsMaskNone)
2051         --numArgs;  // undo speculative reservation for the mask argument
2052     else
2053         texArgs[optArgNum] = mask;
2054 
2055     //
2056     // Set up the instruction
2057     //
2058     Op opCode = OpNop;  // All paths below need to set this
2059     if (fetch) {
2060         if (sparse)
2061             opCode = OpImageSparseFetch;
2062         else
2063             opCode = OpImageFetch;
2064 #ifndef GLSLANG_WEB
2065     } else if (parameters.granularity && parameters.coarse) {
2066         opCode = OpImageSampleFootprintNV;
2067     } else if (gather) {
2068         if (parameters.Dref)
2069             if (sparse)
2070                 opCode = OpImageSparseDrefGather;
2071             else
2072                 opCode = OpImageDrefGather;
2073         else
2074             if (sparse)
2075                 opCode = OpImageSparseGather;
2076             else
2077                 opCode = OpImageGather;
2078 #endif
2079     } else if (explicitLod) {
2080         if (parameters.Dref) {
2081             if (proj)
2082                 if (sparse)
2083                     opCode = OpImageSparseSampleProjDrefExplicitLod;
2084                 else
2085                     opCode = OpImageSampleProjDrefExplicitLod;
2086             else
2087                 if (sparse)
2088                     opCode = OpImageSparseSampleDrefExplicitLod;
2089                 else
2090                     opCode = OpImageSampleDrefExplicitLod;
2091         } else {
2092             if (proj)
2093                 if (sparse)
2094                     opCode = OpImageSparseSampleProjExplicitLod;
2095                 else
2096                     opCode = OpImageSampleProjExplicitLod;
2097             else
2098                 if (sparse)
2099                     opCode = OpImageSparseSampleExplicitLod;
2100                 else
2101                     opCode = OpImageSampleExplicitLod;
2102         }
2103     } else {
2104         if (parameters.Dref) {
2105             if (proj)
2106                 if (sparse)
2107                     opCode = OpImageSparseSampleProjDrefImplicitLod;
2108                 else
2109                     opCode = OpImageSampleProjDrefImplicitLod;
2110             else
2111                 if (sparse)
2112                     opCode = OpImageSparseSampleDrefImplicitLod;
2113                 else
2114                     opCode = OpImageSampleDrefImplicitLod;
2115         } else {
2116             if (proj)
2117                 if (sparse)
2118                     opCode = OpImageSparseSampleProjImplicitLod;
2119                 else
2120                     opCode = OpImageSampleProjImplicitLod;
2121             else
2122                 if (sparse)
2123                     opCode = OpImageSparseSampleImplicitLod;
2124                 else
2125                     opCode = OpImageSampleImplicitLod;
2126         }
2127     }
2128 
2129     // See if the result type is expecting a smeared result.
2130     // This happens when a legacy shadow*() call is made, which
2131     // gets a vec4 back instead of a float.
2132     Id smearedType = resultType;
2133     if (! isScalarType(resultType)) {
2134         switch (opCode) {
2135         case OpImageSampleDrefImplicitLod:
2136         case OpImageSampleDrefExplicitLod:
2137         case OpImageSampleProjDrefImplicitLod:
2138         case OpImageSampleProjDrefExplicitLod:
2139             resultType = getScalarTypeId(resultType);
2140             break;
2141         default:
2142             break;
2143         }
2144     }
2145 
2146     Id typeId0 = 0;
2147     Id typeId1 = 0;
2148 
2149     if (sparse) {
2150         typeId0 = resultType;
2151         typeId1 = getDerefTypeId(parameters.texelOut);
2152         resultType = makeStructResultType(typeId0, typeId1);
2153     }
2154 
2155     // Build the SPIR-V instruction
2156     Instruction* textureInst = new Instruction(getUniqueId(), resultType, opCode);
2157     for (int op = 0; op < optArgNum; ++op)
2158         textureInst->addIdOperand(texArgs[op]);
2159     if (optArgNum < numArgs)
2160         textureInst->addImmediateOperand(texArgs[optArgNum]);
2161     for (int op = optArgNum + 1; op < numArgs; ++op)
2162         textureInst->addIdOperand(texArgs[op]);
2163     setPrecision(textureInst->getResultId(), precision);
2164     buildPoint->addInstruction(std::unique_ptr<Instruction>(textureInst));
2165 
2166     Id resultId = textureInst->getResultId();
2167 
2168     if (sparse) {
2169         // set capability
2170         addCapability(CapabilitySparseResidency);
2171 
2172         // Decode the return type that was a special structure
2173         createStore(createCompositeExtract(resultId, typeId1, 1), parameters.texelOut);
2174         resultId = createCompositeExtract(resultId, typeId0, 0);
2175         setPrecision(resultId, precision);
2176     } else {
2177         // When a smear is needed, do it, as per what was computed
2178         // above when resultType was changed to a scalar type.
2179         if (resultType != smearedType)
2180             resultId = smearScalar(precision, resultId, smearedType);
2181     }
2182 
2183     return resultId;
2184 }
2185 
2186 // Comments in header
createTextureQueryCall(Op opCode,const TextureParameters & parameters,bool isUnsignedResult)2187 Id Builder::createTextureQueryCall(Op opCode, const TextureParameters& parameters, bool isUnsignedResult)
2188 {
2189     // Figure out the result type
2190     Id resultType = 0;
2191     switch (opCode) {
2192     case OpImageQuerySize:
2193     case OpImageQuerySizeLod:
2194     {
2195         int numComponents = 0;
2196         switch (getTypeDimensionality(getImageType(parameters.sampler))) {
2197         case Dim1D:
2198         case DimBuffer:
2199             numComponents = 1;
2200             break;
2201         case Dim2D:
2202         case DimCube:
2203         case DimRect:
2204         case DimSubpassData:
2205             numComponents = 2;
2206             break;
2207         case Dim3D:
2208             numComponents = 3;
2209             break;
2210 
2211         default:
2212             assert(0);
2213             break;
2214         }
2215         if (isArrayedImageType(getImageType(parameters.sampler)))
2216             ++numComponents;
2217 
2218         Id intType = isUnsignedResult ? makeUintType(32) : makeIntType(32);
2219         if (numComponents == 1)
2220             resultType = intType;
2221         else
2222             resultType = makeVectorType(intType, numComponents);
2223 
2224         break;
2225     }
2226     case OpImageQueryLod:
2227         resultType = makeVectorType(getScalarTypeId(getTypeId(parameters.coords)), 2);
2228         break;
2229     case OpImageQueryLevels:
2230     case OpImageQuerySamples:
2231         resultType = isUnsignedResult ? makeUintType(32) : makeIntType(32);
2232         break;
2233     default:
2234         assert(0);
2235         break;
2236     }
2237 
2238     Instruction* query = new Instruction(getUniqueId(), resultType, opCode);
2239     query->addIdOperand(parameters.sampler);
2240     if (parameters.coords)
2241         query->addIdOperand(parameters.coords);
2242     if (parameters.lod)
2243         query->addIdOperand(parameters.lod);
2244     buildPoint->addInstruction(std::unique_ptr<Instruction>(query));
2245     addCapability(CapabilityImageQuery);
2246 
2247     return query->getResultId();
2248 }
2249 
2250 // External comments in header.
2251 // Operates recursively to visit the composite's hierarchy.
createCompositeCompare(Decoration precision,Id value1,Id value2,bool equal)2252 Id Builder::createCompositeCompare(Decoration precision, Id value1, Id value2, bool equal)
2253 {
2254     Id boolType = makeBoolType();
2255     Id valueType = getTypeId(value1);
2256 
2257     Id resultId = NoResult;
2258 
2259     int numConstituents = getNumTypeConstituents(valueType);
2260 
2261     // Scalars and Vectors
2262 
2263     if (isScalarType(valueType) || isVectorType(valueType)) {
2264         assert(valueType == getTypeId(value2));
2265         // These just need a single comparison, just have
2266         // to figure out what it is.
2267         Op op;
2268         switch (getMostBasicTypeClass(valueType)) {
2269         case OpTypeFloat:
2270             op = equal ? OpFOrdEqual : OpFUnordNotEqual;
2271             break;
2272         case OpTypeInt:
2273         default:
2274             op = equal ? OpIEqual : OpINotEqual;
2275             break;
2276         case OpTypeBool:
2277             op = equal ? OpLogicalEqual : OpLogicalNotEqual;
2278             precision = NoPrecision;
2279             break;
2280         }
2281 
2282         if (isScalarType(valueType)) {
2283             // scalar
2284             resultId = createBinOp(op, boolType, value1, value2);
2285         } else {
2286             // vector
2287             resultId = createBinOp(op, makeVectorType(boolType, numConstituents), value1, value2);
2288             setPrecision(resultId, precision);
2289             // reduce vector compares...
2290             resultId = createUnaryOp(equal ? OpAll : OpAny, boolType, resultId);
2291         }
2292 
2293         return setPrecision(resultId, precision);
2294     }
2295 
2296     // Only structs, arrays, and matrices should be left.
2297     // They share in common the reduction operation across their constituents.
2298     assert(isAggregateType(valueType) || isMatrixType(valueType));
2299 
2300     // Compare each pair of constituents
2301     for (int constituent = 0; constituent < numConstituents; ++constituent) {
2302         std::vector<unsigned> indexes(1, constituent);
2303         Id constituentType1 = getContainedTypeId(getTypeId(value1), constituent);
2304         Id constituentType2 = getContainedTypeId(getTypeId(value2), constituent);
2305         Id constituent1 = createCompositeExtract(value1, constituentType1, indexes);
2306         Id constituent2 = createCompositeExtract(value2, constituentType2, indexes);
2307 
2308         Id subResultId = createCompositeCompare(precision, constituent1, constituent2, equal);
2309 
2310         if (constituent == 0)
2311             resultId = subResultId;
2312         else
2313             resultId = setPrecision(createBinOp(equal ? OpLogicalAnd : OpLogicalOr, boolType, resultId, subResultId),
2314                                     precision);
2315     }
2316 
2317     return resultId;
2318 }
2319 
2320 // OpCompositeConstruct
createCompositeConstruct(Id typeId,const std::vector<Id> & constituents)2321 Id Builder::createCompositeConstruct(Id typeId, const std::vector<Id>& constituents)
2322 {
2323     assert(isAggregateType(typeId) || (getNumTypeConstituents(typeId) > 1 &&
2324            getNumTypeConstituents(typeId) == (int)constituents.size()));
2325 
2326     if (generatingOpCodeForSpecConst) {
2327         // Sometime, even in spec-constant-op mode, the constant composite to be
2328         // constructed may not be a specialization constant.
2329         // e.g.:
2330         //  const mat2 m2 = mat2(a_spec_const, a_front_end_const, another_front_end_const, third_front_end_const);
2331         // The first column vector should be a spec constant one, as a_spec_const is a spec constant.
2332         // The second column vector should NOT be spec constant, as it does not contain any spec constants.
2333         // To handle such cases, we check the constituents of the constant vector to determine whether this
2334         // vector should be created as a spec constant.
2335         return makeCompositeConstant(typeId, constituents,
2336                                      std::any_of(constituents.begin(), constituents.end(),
2337                                                  [&](spv::Id id) { return isSpecConstant(id); }));
2338     }
2339 
2340     Instruction* op = new Instruction(getUniqueId(), typeId, OpCompositeConstruct);
2341     for (int c = 0; c < (int)constituents.size(); ++c)
2342         op->addIdOperand(constituents[c]);
2343     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
2344 
2345     return op->getResultId();
2346 }
2347 
2348 // Vector or scalar constructor
createConstructor(Decoration precision,const std::vector<Id> & sources,Id resultTypeId)2349 Id Builder::createConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId)
2350 {
2351     Id result = NoResult;
2352     unsigned int numTargetComponents = getNumTypeComponents(resultTypeId);
2353     unsigned int targetComponent = 0;
2354 
2355     // Special case: when calling a vector constructor with a single scalar
2356     // argument, smear the scalar
2357     if (sources.size() == 1 && isScalar(sources[0]) && numTargetComponents > 1)
2358         return smearScalar(precision, sources[0], resultTypeId);
2359 
2360     // accumulate the arguments for OpCompositeConstruct
2361     std::vector<Id> constituents;
2362     Id scalarTypeId = getScalarTypeId(resultTypeId);
2363 
2364     // lambda to store the result of visiting an argument component
2365     const auto latchResult = [&](Id comp) {
2366         if (numTargetComponents > 1)
2367             constituents.push_back(comp);
2368         else
2369             result = comp;
2370         ++targetComponent;
2371     };
2372 
2373     // lambda to visit a vector argument's components
2374     const auto accumulateVectorConstituents = [&](Id sourceArg) {
2375         unsigned int sourceSize = getNumComponents(sourceArg);
2376         unsigned int sourcesToUse = sourceSize;
2377         if (sourcesToUse + targetComponent > numTargetComponents)
2378             sourcesToUse = numTargetComponents - targetComponent;
2379 
2380         for (unsigned int s = 0; s < sourcesToUse; ++s) {
2381             std::vector<unsigned> swiz;
2382             swiz.push_back(s);
2383             latchResult(createRvalueSwizzle(precision, scalarTypeId, sourceArg, swiz));
2384         }
2385     };
2386 
2387     // lambda to visit a matrix argument's components
2388     const auto accumulateMatrixConstituents = [&](Id sourceArg) {
2389         unsigned int sourceSize = getNumColumns(sourceArg) * getNumRows(sourceArg);
2390         unsigned int sourcesToUse = sourceSize;
2391         if (sourcesToUse + targetComponent > numTargetComponents)
2392             sourcesToUse = numTargetComponents - targetComponent;
2393 
2394         int col = 0;
2395         int row = 0;
2396         for (unsigned int s = 0; s < sourcesToUse; ++s) {
2397             if (row >= getNumRows(sourceArg)) {
2398                 row = 0;
2399                 col++;
2400             }
2401             std::vector<Id> indexes;
2402             indexes.push_back(col);
2403             indexes.push_back(row);
2404             latchResult(createCompositeExtract(sourceArg, scalarTypeId, indexes));
2405             row++;
2406         }
2407     };
2408 
2409     // Go through the source arguments, each one could have either
2410     // a single or multiple components to contribute.
2411     for (unsigned int i = 0; i < sources.size(); ++i) {
2412 
2413         if (isScalar(sources[i]) || isPointer(sources[i]))
2414             latchResult(sources[i]);
2415         else if (isVector(sources[i]))
2416             accumulateVectorConstituents(sources[i]);
2417         else if (isMatrix(sources[i]))
2418             accumulateMatrixConstituents(sources[i]);
2419         else
2420             assert(0);
2421 
2422         if (targetComponent >= numTargetComponents)
2423             break;
2424     }
2425 
2426     // If the result is a vector, make it from the gathered constituents.
2427     if (constituents.size() > 0)
2428         result = createCompositeConstruct(resultTypeId, constituents);
2429 
2430     return setPrecision(result, precision);
2431 }
2432 
2433 // Comments in header
createMatrixConstructor(Decoration precision,const std::vector<Id> & sources,Id resultTypeId)2434 Id Builder::createMatrixConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId)
2435 {
2436     Id componentTypeId = getScalarTypeId(resultTypeId);
2437     int numCols = getTypeNumColumns(resultTypeId);
2438     int numRows = getTypeNumRows(resultTypeId);
2439 
2440     Instruction* instr = module.getInstruction(componentTypeId);
2441 #ifdef GLSLANG_WEB
2442     const unsigned bitCount = 32;
2443     assert(bitCount == instr->getImmediateOperand(0));
2444 #else
2445     const unsigned bitCount = instr->getImmediateOperand(0);
2446 #endif
2447 
2448     // Optimize matrix constructed from a bigger matrix
2449     if (isMatrix(sources[0]) && getNumColumns(sources[0]) >= numCols && getNumRows(sources[0]) >= numRows) {
2450         // To truncate the matrix to a smaller number of rows/columns, we need to:
2451         // 1. For each column, extract the column and truncate it to the required size using shuffle
2452         // 2. Assemble the resulting matrix from all columns
2453         Id matrix = sources[0];
2454         Id columnTypeId = getContainedTypeId(resultTypeId);
2455         Id sourceColumnTypeId = getContainedTypeId(getTypeId(matrix));
2456 
2457         std::vector<unsigned> channels;
2458         for (int row = 0; row < numRows; ++row)
2459             channels.push_back(row);
2460 
2461         std::vector<Id> matrixColumns;
2462         for (int col = 0; col < numCols; ++col) {
2463             std::vector<unsigned> indexes;
2464             indexes.push_back(col);
2465             Id colv = createCompositeExtract(matrix, sourceColumnTypeId, indexes);
2466             setPrecision(colv, precision);
2467 
2468             if (numRows != getNumRows(matrix)) {
2469                 matrixColumns.push_back(createRvalueSwizzle(precision, columnTypeId, colv, channels));
2470             } else {
2471                 matrixColumns.push_back(colv);
2472             }
2473         }
2474 
2475         return setPrecision(createCompositeConstruct(resultTypeId, matrixColumns), precision);
2476     }
2477 
2478     // Otherwise, will use a two step process
2479     // 1. make a compile-time 2D array of values
2480     // 2. construct a matrix from that array
2481 
2482     // Step 1.
2483 
2484     // initialize the array to the identity matrix
2485     Id ids[maxMatrixSize][maxMatrixSize];
2486     Id  one = (bitCount == 64 ? makeDoubleConstant(1.0) : makeFloatConstant(1.0));
2487     Id zero = (bitCount == 64 ? makeDoubleConstant(0.0) : makeFloatConstant(0.0));
2488     for (int col = 0; col < 4; ++col) {
2489         for (int row = 0; row < 4; ++row) {
2490             if (col == row)
2491                 ids[col][row] = one;
2492             else
2493                 ids[col][row] = zero;
2494         }
2495     }
2496 
2497     // modify components as dictated by the arguments
2498     if (sources.size() == 1 && isScalar(sources[0])) {
2499         // a single scalar; resets the diagonals
2500         for (int col = 0; col < 4; ++col)
2501             ids[col][col] = sources[0];
2502     } else if (isMatrix(sources[0])) {
2503         // constructing from another matrix; copy over the parts that exist in both the argument and constructee
2504         Id matrix = sources[0];
2505         int minCols = std::min(numCols, getNumColumns(matrix));
2506         int minRows = std::min(numRows, getNumRows(matrix));
2507         for (int col = 0; col < minCols; ++col) {
2508             std::vector<unsigned> indexes;
2509             indexes.push_back(col);
2510             for (int row = 0; row < minRows; ++row) {
2511                 indexes.push_back(row);
2512                 ids[col][row] = createCompositeExtract(matrix, componentTypeId, indexes);
2513                 indexes.pop_back();
2514                 setPrecision(ids[col][row], precision);
2515             }
2516         }
2517     } else {
2518         // fill in the matrix in column-major order with whatever argument components are available
2519         int row = 0;
2520         int col = 0;
2521 
2522         for (int arg = 0; arg < (int)sources.size(); ++arg) {
2523             Id argComp = sources[arg];
2524             for (int comp = 0; comp < getNumComponents(sources[arg]); ++comp) {
2525                 if (getNumComponents(sources[arg]) > 1) {
2526                     argComp = createCompositeExtract(sources[arg], componentTypeId, comp);
2527                     setPrecision(argComp, precision);
2528                 }
2529                 ids[col][row++] = argComp;
2530                 if (row == numRows) {
2531                     row = 0;
2532                     col++;
2533                 }
2534             }
2535         }
2536     }
2537 
2538     // Step 2:  Construct a matrix from that array.
2539     // First make the column vectors, then make the matrix.
2540 
2541     // make the column vectors
2542     Id columnTypeId = getContainedTypeId(resultTypeId);
2543     std::vector<Id> matrixColumns;
2544     for (int col = 0; col < numCols; ++col) {
2545         std::vector<Id> vectorComponents;
2546         for (int row = 0; row < numRows; ++row)
2547             vectorComponents.push_back(ids[col][row]);
2548         Id column = createCompositeConstruct(columnTypeId, vectorComponents);
2549         setPrecision(column, precision);
2550         matrixColumns.push_back(column);
2551     }
2552 
2553     // make the matrix
2554     return setPrecision(createCompositeConstruct(resultTypeId, matrixColumns), precision);
2555 }
2556 
2557 // Comments in header
If(Id cond,unsigned int ctrl,Builder & gb)2558 Builder::If::If(Id cond, unsigned int ctrl, Builder& gb) :
2559     builder(gb),
2560     condition(cond),
2561     control(ctrl),
2562     elseBlock(0)
2563 {
2564     function = &builder.getBuildPoint()->getParent();
2565 
2566     // make the blocks, but only put the then-block into the function,
2567     // the else-block and merge-block will be added later, in order, after
2568     // earlier code is emitted
2569     thenBlock = new Block(builder.getUniqueId(), *function);
2570     mergeBlock = new Block(builder.getUniqueId(), *function);
2571 
2572     // Save the current block, so that we can add in the flow control split when
2573     // makeEndIf is called.
2574     headerBlock = builder.getBuildPoint();
2575 
2576     function->addBlock(thenBlock);
2577     builder.setBuildPoint(thenBlock);
2578 }
2579 
2580 // Comments in header
makeBeginElse()2581 void Builder::If::makeBeginElse()
2582 {
2583     // Close out the "then" by having it jump to the mergeBlock
2584     builder.createBranch(mergeBlock);
2585 
2586     // Make the first else block and add it to the function
2587     elseBlock = new Block(builder.getUniqueId(), *function);
2588     function->addBlock(elseBlock);
2589 
2590     // Start building the else block
2591     builder.setBuildPoint(elseBlock);
2592 }
2593 
2594 // Comments in header
makeEndIf()2595 void Builder::If::makeEndIf()
2596 {
2597     // jump to the merge block
2598     builder.createBranch(mergeBlock);
2599 
2600     // Go back to the headerBlock and make the flow control split
2601     builder.setBuildPoint(headerBlock);
2602     builder.createSelectionMerge(mergeBlock, control);
2603     if (elseBlock)
2604         builder.createConditionalBranch(condition, thenBlock, elseBlock);
2605     else
2606         builder.createConditionalBranch(condition, thenBlock, mergeBlock);
2607 
2608     // add the merge block to the function
2609     function->addBlock(mergeBlock);
2610     builder.setBuildPoint(mergeBlock);
2611 }
2612 
2613 // Comments in header
makeSwitch(Id selector,unsigned int control,int numSegments,const std::vector<int> & caseValues,const std::vector<int> & valueIndexToSegment,int defaultSegment,std::vector<Block * > & segmentBlocks)2614 void Builder::makeSwitch(Id selector, unsigned int control, int numSegments, const std::vector<int>& caseValues,
2615                          const std::vector<int>& valueIndexToSegment, int defaultSegment,
2616                          std::vector<Block*>& segmentBlocks)
2617 {
2618     Function& function = buildPoint->getParent();
2619 
2620     // make all the blocks
2621     for (int s = 0; s < numSegments; ++s)
2622         segmentBlocks.push_back(new Block(getUniqueId(), function));
2623 
2624     Block* mergeBlock = new Block(getUniqueId(), function);
2625 
2626     // make and insert the switch's selection-merge instruction
2627     createSelectionMerge(mergeBlock, control);
2628 
2629     // make the switch instruction
2630     Instruction* switchInst = new Instruction(NoResult, NoType, OpSwitch);
2631     switchInst->addIdOperand(selector);
2632     auto defaultOrMerge = (defaultSegment >= 0) ? segmentBlocks[defaultSegment] : mergeBlock;
2633     switchInst->addIdOperand(defaultOrMerge->getId());
2634     defaultOrMerge->addPredecessor(buildPoint);
2635     for (int i = 0; i < (int)caseValues.size(); ++i) {
2636         switchInst->addImmediateOperand(caseValues[i]);
2637         switchInst->addIdOperand(segmentBlocks[valueIndexToSegment[i]]->getId());
2638         segmentBlocks[valueIndexToSegment[i]]->addPredecessor(buildPoint);
2639     }
2640     buildPoint->addInstruction(std::unique_ptr<Instruction>(switchInst));
2641 
2642     // push the merge block
2643     switchMerges.push(mergeBlock);
2644 }
2645 
2646 // Comments in header
addSwitchBreak()2647 void Builder::addSwitchBreak()
2648 {
2649     // branch to the top of the merge block stack
2650     createBranch(switchMerges.top());
2651     createAndSetNoPredecessorBlock("post-switch-break");
2652 }
2653 
2654 // Comments in header
nextSwitchSegment(std::vector<Block * > & segmentBlock,int nextSegment)2655 void Builder::nextSwitchSegment(std::vector<Block*>& segmentBlock, int nextSegment)
2656 {
2657     int lastSegment = nextSegment - 1;
2658     if (lastSegment >= 0) {
2659         // Close out previous segment by jumping, if necessary, to next segment
2660         if (! buildPoint->isTerminated())
2661             createBranch(segmentBlock[nextSegment]);
2662     }
2663     Block* block = segmentBlock[nextSegment];
2664     block->getParent().addBlock(block);
2665     setBuildPoint(block);
2666 }
2667 
2668 // Comments in header
endSwitch(std::vector<Block * > &)2669 void Builder::endSwitch(std::vector<Block*>& /*segmentBlock*/)
2670 {
2671     // Close out previous segment by jumping, if necessary, to next segment
2672     if (! buildPoint->isTerminated())
2673         addSwitchBreak();
2674 
2675     switchMerges.top()->getParent().addBlock(switchMerges.top());
2676     setBuildPoint(switchMerges.top());
2677 
2678     switchMerges.pop();
2679 }
2680 
makeNewBlock()2681 Block& Builder::makeNewBlock()
2682 {
2683     Function& function = buildPoint->getParent();
2684     auto block = new Block(getUniqueId(), function);
2685     function.addBlock(block);
2686     return *block;
2687 }
2688 
makeNewLoop()2689 Builder::LoopBlocks& Builder::makeNewLoop()
2690 {
2691     // This verbosity is needed to simultaneously get the same behavior
2692     // everywhere (id's in the same order), have a syntax that works
2693     // across lots of versions of C++, have no warnings from pedantic
2694     // compilation modes, and leave the rest of the code alone.
2695     Block& head            = makeNewBlock();
2696     Block& body            = makeNewBlock();
2697     Block& merge           = makeNewBlock();
2698     Block& continue_target = makeNewBlock();
2699     LoopBlocks blocks(head, body, merge, continue_target);
2700     loops.push(blocks);
2701     return loops.top();
2702 }
2703 
createLoopContinue()2704 void Builder::createLoopContinue()
2705 {
2706     createBranch(&loops.top().continue_target);
2707     // Set up a block for dead code.
2708     createAndSetNoPredecessorBlock("post-loop-continue");
2709 }
2710 
createLoopExit()2711 void Builder::createLoopExit()
2712 {
2713     createBranch(&loops.top().merge);
2714     // Set up a block for dead code.
2715     createAndSetNoPredecessorBlock("post-loop-break");
2716 }
2717 
closeLoop()2718 void Builder::closeLoop()
2719 {
2720     loops.pop();
2721 }
2722 
clearAccessChain()2723 void Builder::clearAccessChain()
2724 {
2725     accessChain.base = NoResult;
2726     accessChain.indexChain.clear();
2727     accessChain.instr = NoResult;
2728     accessChain.swizzle.clear();
2729     accessChain.component = NoResult;
2730     accessChain.preSwizzleBaseType = NoType;
2731     accessChain.isRValue = false;
2732     accessChain.coherentFlags.clear();
2733     accessChain.alignment = 0;
2734 }
2735 
2736 // Comments in header
accessChainPushSwizzle(std::vector<unsigned> & swizzle,Id preSwizzleBaseType,AccessChain::CoherentFlags coherentFlags,unsigned int alignment)2737 void Builder::accessChainPushSwizzle(std::vector<unsigned>& swizzle, Id preSwizzleBaseType,
2738     AccessChain::CoherentFlags coherentFlags, unsigned int alignment)
2739 {
2740     accessChain.coherentFlags |= coherentFlags;
2741     accessChain.alignment |= alignment;
2742 
2743     // swizzles can be stacked in GLSL, but simplified to a single
2744     // one here; the base type doesn't change
2745     if (accessChain.preSwizzleBaseType == NoType)
2746         accessChain.preSwizzleBaseType = preSwizzleBaseType;
2747 
2748     // if needed, propagate the swizzle for the current access chain
2749     if (accessChain.swizzle.size() > 0) {
2750         std::vector<unsigned> oldSwizzle = accessChain.swizzle;
2751         accessChain.swizzle.resize(0);
2752         for (unsigned int i = 0; i < swizzle.size(); ++i) {
2753             assert(swizzle[i] < oldSwizzle.size());
2754             accessChain.swizzle.push_back(oldSwizzle[swizzle[i]]);
2755         }
2756     } else
2757         accessChain.swizzle = swizzle;
2758 
2759     // determine if we need to track this swizzle anymore
2760     simplifyAccessChainSwizzle();
2761 }
2762 
2763 // Comments in header
accessChainStore(Id rvalue,spv::MemoryAccessMask memoryAccess,spv::Scope scope,unsigned int alignment)2764 void Builder::accessChainStore(Id rvalue, spv::MemoryAccessMask memoryAccess, spv::Scope scope, unsigned int alignment)
2765 {
2766     assert(accessChain.isRValue == false);
2767 
2768     transferAccessChainSwizzle(true);
2769     Id base = collapseAccessChain();
2770     Id source = rvalue;
2771 
2772     // dynamic component should be gone
2773     assert(accessChain.component == NoResult);
2774 
2775     // If swizzle still exists, it is out-of-order or not full, we must load the target vector,
2776     // extract and insert elements to perform writeMask and/or swizzle.
2777     if (accessChain.swizzle.size() > 0) {
2778         Id tempBaseId = createLoad(base, spv::NoPrecision);
2779         source = createLvalueSwizzle(getTypeId(tempBaseId), tempBaseId, source, accessChain.swizzle);
2780     }
2781 
2782     // take LSB of alignment
2783     alignment = alignment & ~(alignment & (alignment-1));
2784     if (getStorageClass(base) == StorageClassPhysicalStorageBufferEXT) {
2785         memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2786     }
2787 
2788     createStore(source, base, memoryAccess, scope, alignment);
2789 }
2790 
2791 // Comments in header
accessChainLoad(Decoration precision,Decoration nonUniform,Id resultType,spv::MemoryAccessMask memoryAccess,spv::Scope scope,unsigned int alignment)2792 Id Builder::accessChainLoad(Decoration precision, Decoration nonUniform, Id resultType,
2793     spv::MemoryAccessMask memoryAccess, spv::Scope scope, unsigned int alignment)
2794 {
2795     Id id;
2796 
2797     if (accessChain.isRValue) {
2798         // transfer access chain, but try to stay in registers
2799         transferAccessChainSwizzle(false);
2800         if (accessChain.indexChain.size() > 0) {
2801             Id swizzleBase = accessChain.preSwizzleBaseType != NoType ? accessChain.preSwizzleBaseType : resultType;
2802 
2803             // if all the accesses are constants, we can use OpCompositeExtract
2804             std::vector<unsigned> indexes;
2805             bool constant = true;
2806             for (int i = 0; i < (int)accessChain.indexChain.size(); ++i) {
2807                 if (isConstantScalar(accessChain.indexChain[i]))
2808                     indexes.push_back(getConstantScalar(accessChain.indexChain[i]));
2809                 else {
2810                     constant = false;
2811                     break;
2812                 }
2813             }
2814 
2815             if (constant) {
2816                 id = createCompositeExtract(accessChain.base, swizzleBase, indexes);
2817                 setPrecision(id, precision);
2818             } else {
2819                 Id lValue = NoResult;
2820                 if (spvVersion >= Spv_1_4 && isValidInitializer(accessChain.base)) {
2821                     // make a new function variable for this r-value, using an initializer,
2822                     // and mark it as NonWritable so that downstream it can be detected as a lookup
2823                     // table
2824                     lValue = createVariable(NoPrecision, StorageClassFunction, getTypeId(accessChain.base),
2825                         "indexable", accessChain.base);
2826                     addDecoration(lValue, DecorationNonWritable);
2827                 } else {
2828                     lValue = createVariable(NoPrecision, StorageClassFunction, getTypeId(accessChain.base),
2829                         "indexable");
2830                     // store into it
2831                     createStore(accessChain.base, lValue);
2832                 }
2833                 // move base to the new variable
2834                 accessChain.base = lValue;
2835                 accessChain.isRValue = false;
2836 
2837                 // load through the access chain
2838                 id = createLoad(collapseAccessChain(), precision);
2839             }
2840         } else
2841             id = accessChain.base;  // no precision, it was set when this was defined
2842     } else {
2843         transferAccessChainSwizzle(true);
2844 
2845         // take LSB of alignment
2846         alignment = alignment & ~(alignment & (alignment-1));
2847         if (getStorageClass(accessChain.base) == StorageClassPhysicalStorageBufferEXT) {
2848             memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2849         }
2850 
2851         // load through the access chain
2852         id = collapseAccessChain();
2853         // Apply nonuniform both to the access chain and the loaded value.
2854         // Buffer accesses need the access chain decorated, and this is where
2855         // loaded image types get decorated. TODO: This should maybe move to
2856         // createImageTextureFunctionCall.
2857         addDecoration(id, nonUniform);
2858         id = createLoad(id, precision, memoryAccess, scope, alignment);
2859         addDecoration(id, nonUniform);
2860     }
2861 
2862     // Done, unless there are swizzles to do
2863     if (accessChain.swizzle.size() == 0 && accessChain.component == NoResult)
2864         return id;
2865 
2866     // Do remaining swizzling
2867 
2868     // Do the basic swizzle
2869     if (accessChain.swizzle.size() > 0) {
2870         Id swizzledType = getScalarTypeId(getTypeId(id));
2871         if (accessChain.swizzle.size() > 1)
2872             swizzledType = makeVectorType(swizzledType, (int)accessChain.swizzle.size());
2873         id = createRvalueSwizzle(precision, swizzledType, id, accessChain.swizzle);
2874     }
2875 
2876     // Do the dynamic component
2877     if (accessChain.component != NoResult)
2878         id = setPrecision(createVectorExtractDynamic(id, resultType, accessChain.component), precision);
2879 
2880     addDecoration(id, nonUniform);
2881     return id;
2882 }
2883 
accessChainGetLValue()2884 Id Builder::accessChainGetLValue()
2885 {
2886     assert(accessChain.isRValue == false);
2887 
2888     transferAccessChainSwizzle(true);
2889     Id lvalue = collapseAccessChain();
2890 
2891     // If swizzle exists, it is out-of-order or not full, we must load the target vector,
2892     // extract and insert elements to perform writeMask and/or swizzle.  This does not
2893     // go with getting a direct l-value pointer.
2894     assert(accessChain.swizzle.size() == 0);
2895     assert(accessChain.component == NoResult);
2896 
2897     return lvalue;
2898 }
2899 
2900 // comment in header
accessChainGetInferredType()2901 Id Builder::accessChainGetInferredType()
2902 {
2903     // anything to operate on?
2904     if (accessChain.base == NoResult)
2905         return NoType;
2906     Id type = getTypeId(accessChain.base);
2907 
2908     // do initial dereference
2909     if (! accessChain.isRValue)
2910         type = getContainedTypeId(type);
2911 
2912     // dereference each index
2913     for (auto it = accessChain.indexChain.cbegin(); it != accessChain.indexChain.cend(); ++it) {
2914         if (isStructType(type))
2915             type = getContainedTypeId(type, getConstantScalar(*it));
2916         else
2917             type = getContainedTypeId(type);
2918     }
2919 
2920     // dereference swizzle
2921     if (accessChain.swizzle.size() == 1)
2922         type = getContainedTypeId(type);
2923     else if (accessChain.swizzle.size() > 1)
2924         type = makeVectorType(getContainedTypeId(type), (int)accessChain.swizzle.size());
2925 
2926     // dereference component selection
2927     if (accessChain.component)
2928         type = getContainedTypeId(type);
2929 
2930     return type;
2931 }
2932 
dump(std::vector<unsigned int> & out) const2933 void Builder::dump(std::vector<unsigned int>& out) const
2934 {
2935     // Header, before first instructions:
2936     out.push_back(MagicNumber);
2937     out.push_back(spvVersion);
2938     out.push_back(builderNumber);
2939     out.push_back(uniqueId + 1);
2940     out.push_back(0);
2941 
2942     // Capabilities
2943     for (auto it = capabilities.cbegin(); it != capabilities.cend(); ++it) {
2944         Instruction capInst(0, 0, OpCapability);
2945         capInst.addImmediateOperand(*it);
2946         capInst.dump(out);
2947     }
2948 
2949     for (auto it = extensions.cbegin(); it != extensions.cend(); ++it) {
2950         Instruction extInst(0, 0, OpExtension);
2951         extInst.addStringOperand(it->c_str());
2952         extInst.dump(out);
2953     }
2954 
2955     dumpInstructions(out, imports);
2956     Instruction memInst(0, 0, OpMemoryModel);
2957     memInst.addImmediateOperand(addressModel);
2958     memInst.addImmediateOperand(memoryModel);
2959     memInst.dump(out);
2960 
2961     // Instructions saved up while building:
2962     dumpInstructions(out, entryPoints);
2963     dumpInstructions(out, executionModes);
2964 
2965     // Debug instructions
2966     dumpInstructions(out, strings);
2967     dumpSourceInstructions(out);
2968     for (int e = 0; e < (int)sourceExtensions.size(); ++e) {
2969         Instruction sourceExtInst(0, 0, OpSourceExtension);
2970         sourceExtInst.addStringOperand(sourceExtensions[e]);
2971         sourceExtInst.dump(out);
2972     }
2973     dumpInstructions(out, names);
2974     dumpModuleProcesses(out);
2975 
2976     // Annotation instructions
2977     dumpInstructions(out, decorations);
2978 
2979     dumpInstructions(out, constantsTypesGlobals);
2980     dumpInstructions(out, externals);
2981 
2982     // The functions
2983     module.dump(out);
2984 }
2985 
2986 //
2987 // Protected methods.
2988 //
2989 
2990 // Turn the described access chain in 'accessChain' into an instruction(s)
2991 // computing its address.  This *cannot* include complex swizzles, which must
2992 // be handled after this is called.
2993 //
2994 // Can generate code.
collapseAccessChain()2995 Id Builder::collapseAccessChain()
2996 {
2997     assert(accessChain.isRValue == false);
2998 
2999     // did we already emit an access chain for this?
3000     if (accessChain.instr != NoResult)
3001         return accessChain.instr;
3002 
3003     // If we have a dynamic component, we can still transfer
3004     // that into a final operand to the access chain.  We need to remap the
3005     // dynamic component through the swizzle to get a new dynamic component to
3006     // update.
3007     //
3008     // This was not done in transferAccessChainSwizzle() because it might
3009     // generate code.
3010     remapDynamicSwizzle();
3011     if (accessChain.component != NoResult) {
3012         // transfer the dynamic component to the access chain
3013         accessChain.indexChain.push_back(accessChain.component);
3014         accessChain.component = NoResult;
3015     }
3016 
3017     // note that non-trivial swizzling is left pending
3018 
3019     // do we have an access chain?
3020     if (accessChain.indexChain.size() == 0)
3021         return accessChain.base;
3022 
3023     // emit the access chain
3024     StorageClass storageClass = (StorageClass)module.getStorageClass(getTypeId(accessChain.base));
3025     accessChain.instr = createAccessChain(storageClass, accessChain.base, accessChain.indexChain);
3026 
3027     return accessChain.instr;
3028 }
3029 
3030 // For a dynamic component selection of a swizzle.
3031 //
3032 // Turn the swizzle and dynamic component into just a dynamic component.
3033 //
3034 // Generates code.
remapDynamicSwizzle()3035 void Builder::remapDynamicSwizzle()
3036 {
3037     // do we have a swizzle to remap a dynamic component through?
3038     if (accessChain.component != NoResult && accessChain.swizzle.size() > 1) {
3039         // build a vector of the swizzle for the component to map into
3040         std::vector<Id> components;
3041         for (int c = 0; c < (int)accessChain.swizzle.size(); ++c)
3042             components.push_back(makeUintConstant(accessChain.swizzle[c]));
3043         Id mapType = makeVectorType(makeUintType(32), (int)accessChain.swizzle.size());
3044         Id map = makeCompositeConstant(mapType, components);
3045 
3046         // use it
3047         accessChain.component = createVectorExtractDynamic(map, makeUintType(32), accessChain.component);
3048         accessChain.swizzle.clear();
3049     }
3050 }
3051 
3052 // clear out swizzle if it is redundant, that is reselecting the same components
3053 // that would be present without the swizzle.
simplifyAccessChainSwizzle()3054 void Builder::simplifyAccessChainSwizzle()
3055 {
3056     // If the swizzle has fewer components than the vector, it is subsetting, and must stay
3057     // to preserve that fact.
3058     if (getNumTypeComponents(accessChain.preSwizzleBaseType) > (int)accessChain.swizzle.size())
3059         return;
3060 
3061     // if components are out of order, it is a swizzle
3062     for (unsigned int i = 0; i < accessChain.swizzle.size(); ++i) {
3063         if (i != accessChain.swizzle[i])
3064             return;
3065     }
3066 
3067     // otherwise, there is no need to track this swizzle
3068     accessChain.swizzle.clear();
3069     if (accessChain.component == NoResult)
3070         accessChain.preSwizzleBaseType = NoType;
3071 }
3072 
3073 // To the extent any swizzling can become part of the chain
3074 // of accesses instead of a post operation, make it so.
3075 // If 'dynamic' is true, include transferring the dynamic component,
3076 // otherwise, leave it pending.
3077 //
3078 // Does not generate code. just updates the access chain.
transferAccessChainSwizzle(bool dynamic)3079 void Builder::transferAccessChainSwizzle(bool dynamic)
3080 {
3081     // non existent?
3082     if (accessChain.swizzle.size() == 0 && accessChain.component == NoResult)
3083         return;
3084 
3085     // too complex?
3086     // (this requires either a swizzle, or generating code for a dynamic component)
3087     if (accessChain.swizzle.size() > 1)
3088         return;
3089 
3090     // single component, either in the swizzle and/or dynamic component
3091     if (accessChain.swizzle.size() == 1) {
3092         assert(accessChain.component == NoResult);
3093         // handle static component selection
3094         accessChain.indexChain.push_back(makeUintConstant(accessChain.swizzle.front()));
3095         accessChain.swizzle.clear();
3096         accessChain.preSwizzleBaseType = NoType;
3097     } else if (dynamic && accessChain.component != NoResult) {
3098         assert(accessChain.swizzle.size() == 0);
3099         // handle dynamic component
3100         accessChain.indexChain.push_back(accessChain.component);
3101         accessChain.preSwizzleBaseType = NoType;
3102         accessChain.component = NoResult;
3103     }
3104 }
3105 
3106 // Utility method for creating a new block and setting the insert point to
3107 // be in it. This is useful for flow-control operations that need a "dummy"
3108 // block proceeding them (e.g. instructions after a discard, etc).
createAndSetNoPredecessorBlock(const char *)3109 void Builder::createAndSetNoPredecessorBlock(const char* /*name*/)
3110 {
3111     Block* block = new Block(getUniqueId(), buildPoint->getParent());
3112     block->setUnreachable();
3113     buildPoint->getParent().addBlock(block);
3114     setBuildPoint(block);
3115 
3116     // if (name)
3117     //    addName(block->getId(), name);
3118 }
3119 
3120 // Comments in header
createBranch(Block * block)3121 void Builder::createBranch(Block* block)
3122 {
3123     Instruction* branch = new Instruction(OpBranch);
3124     branch->addIdOperand(block->getId());
3125     buildPoint->addInstruction(std::unique_ptr<Instruction>(branch));
3126     block->addPredecessor(buildPoint);
3127 }
3128 
createSelectionMerge(Block * mergeBlock,unsigned int control)3129 void Builder::createSelectionMerge(Block* mergeBlock, unsigned int control)
3130 {
3131     Instruction* merge = new Instruction(OpSelectionMerge);
3132     merge->addIdOperand(mergeBlock->getId());
3133     merge->addImmediateOperand(control);
3134     buildPoint->addInstruction(std::unique_ptr<Instruction>(merge));
3135 }
3136 
createLoopMerge(Block * mergeBlock,Block * continueBlock,unsigned int control,const std::vector<unsigned int> & operands)3137 void Builder::createLoopMerge(Block* mergeBlock, Block* continueBlock, unsigned int control,
3138                               const std::vector<unsigned int>& operands)
3139 {
3140     Instruction* merge = new Instruction(OpLoopMerge);
3141     merge->addIdOperand(mergeBlock->getId());
3142     merge->addIdOperand(continueBlock->getId());
3143     merge->addImmediateOperand(control);
3144     for (int op = 0; op < (int)operands.size(); ++op)
3145         merge->addImmediateOperand(operands[op]);
3146     buildPoint->addInstruction(std::unique_ptr<Instruction>(merge));
3147 }
3148 
createConditionalBranch(Id condition,Block * thenBlock,Block * elseBlock)3149 void Builder::createConditionalBranch(Id condition, Block* thenBlock, Block* elseBlock)
3150 {
3151     Instruction* branch = new Instruction(OpBranchConditional);
3152     branch->addIdOperand(condition);
3153     branch->addIdOperand(thenBlock->getId());
3154     branch->addIdOperand(elseBlock->getId());
3155     buildPoint->addInstruction(std::unique_ptr<Instruction>(branch));
3156     thenBlock->addPredecessor(buildPoint);
3157     elseBlock->addPredecessor(buildPoint);
3158 }
3159 
3160 // OpSource
3161 // [OpSourceContinued]
3162 // ...
dumpSourceInstructions(const spv::Id fileId,const std::string & text,std::vector<unsigned int> & out) const3163 void Builder::dumpSourceInstructions(const spv::Id fileId, const std::string& text,
3164                                      std::vector<unsigned int>& out) const
3165 {
3166     const int maxWordCount = 0xFFFF;
3167     const int opSourceWordCount = 4;
3168     const int nonNullBytesPerInstruction = 4 * (maxWordCount - opSourceWordCount) - 1;
3169 
3170     if (source != SourceLanguageUnknown) {
3171         // OpSource Language Version File Source
3172         Instruction sourceInst(NoResult, NoType, OpSource);
3173         sourceInst.addImmediateOperand(source);
3174         sourceInst.addImmediateOperand(sourceVersion);
3175         // File operand
3176         if (fileId != NoResult) {
3177             sourceInst.addIdOperand(fileId);
3178             // Source operand
3179             if (text.size() > 0) {
3180                 int nextByte = 0;
3181                 std::string subString;
3182                 while ((int)text.size() - nextByte > 0) {
3183                     subString = text.substr(nextByte, nonNullBytesPerInstruction);
3184                     if (nextByte == 0) {
3185                         // OpSource
3186                         sourceInst.addStringOperand(subString.c_str());
3187                         sourceInst.dump(out);
3188                     } else {
3189                         // OpSourcContinued
3190                         Instruction sourceContinuedInst(OpSourceContinued);
3191                         sourceContinuedInst.addStringOperand(subString.c_str());
3192                         sourceContinuedInst.dump(out);
3193                     }
3194                     nextByte += nonNullBytesPerInstruction;
3195                 }
3196             } else
3197                 sourceInst.dump(out);
3198         } else
3199             sourceInst.dump(out);
3200     }
3201 }
3202 
3203 // Dump an OpSource[Continued] sequence for the source and every include file
dumpSourceInstructions(std::vector<unsigned int> & out) const3204 void Builder::dumpSourceInstructions(std::vector<unsigned int>& out) const
3205 {
3206     dumpSourceInstructions(sourceFileStringId, sourceText, out);
3207     for (auto iItr = includeFiles.begin(); iItr != includeFiles.end(); ++iItr)
3208         dumpSourceInstructions(iItr->first, *iItr->second, out);
3209 }
3210 
dumpInstructions(std::vector<unsigned int> & out,const std::vector<std::unique_ptr<Instruction>> & instructions) const3211 void Builder::dumpInstructions(std::vector<unsigned int>& out,
3212     const std::vector<std::unique_ptr<Instruction> >& instructions) const
3213 {
3214     for (int i = 0; i < (int)instructions.size(); ++i) {
3215         instructions[i]->dump(out);
3216     }
3217 }
3218 
dumpModuleProcesses(std::vector<unsigned int> & out) const3219 void Builder::dumpModuleProcesses(std::vector<unsigned int>& out) const
3220 {
3221     for (int i = 0; i < (int)moduleProcesses.size(); ++i) {
3222         Instruction moduleProcessed(OpModuleProcessed);
3223         moduleProcessed.addStringOperand(moduleProcesses[i]);
3224         moduleProcessed.dump(out);
3225     }
3226 }
3227 
3228 }; // end spv namespace
3229