blob: b2a93cfe0d94ab8c8f99130763f7376e0738598d [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich56364b62020-03-01 04:51:40 -07003// Copyright (C) 2015-2020 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
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//
John Kessenich927608b2017-01-06 12:34:14 -070024// 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.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080050 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051}
John Kessenich140f3df2015-06-26 16:58:36 -060052
53// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020054#include "../glslang/MachineIndependent/localintermediate.h"
55#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060056#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050057#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060058
John Kessenich140f3df2015-06-26 16:58:36 -060059#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050060#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040061#include <list>
62#include <map>
63#include <stack>
64#include <string>
65#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060066
67namespace {
68
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
John Kessenichead86222018-03-28 18:01:20 -060088
89struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060090 public:
91 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
92 precision(precision)
93#ifndef GLSLANG_WEB
94 ,
95 noContraction(noContraction),
96 nonUniform(nonUniform)
97#endif
98 { }
99
John Kessenichead86222018-03-28 18:01:20 -0600100 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600101
102#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400103 void addNoContraction(spv::Builder&, spv::Id) const { }
104 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600105#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400106 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
107 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600108 protected:
109 spv::Decoration noContraction;
110 spv::Decoration nonUniform;
111#endif
112
John Kessenichead86222018-03-28 18:01:20 -0600113};
114
115} // namespace
qining4c912612016-04-01 10:35:16 -0400116
John Kessenich140f3df2015-06-26 16:58:36 -0600117//
118// The main holder of information for translating glslang to SPIR-V.
119//
120// Derives from the AST walking base class.
121//
122class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
123public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700124 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
125 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700126 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
129 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
130 void visitConstantUnion(glslang::TIntermConstantUnion*);
131 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
132 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
133 void visitSymbol(glslang::TIntermSymbol* symbol);
134 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
135 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
136 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
137
John Kessenichfca82622016-11-26 13:23:20 -0700138 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700139 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600140
141protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700142 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
143 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
144
Rex Xu17ff3432016-10-14 17:41:45 +0800145 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800146 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600147 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500148 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
149 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
150 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
151 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100152 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700153 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700154 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
155 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700156 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600157 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600158 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600159 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600160 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600161 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
162 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
163 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600164 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600165 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600166 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600167 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600168 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
169 glslang::TLayoutPacking, const glslang::TQualifier&);
170 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
171 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700172 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700173 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800174 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600175 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700176 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700177 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
178 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700179 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
180 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100181 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich6fccb3c2016-09-19 16:01:41 -0600183 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600184 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600185 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600186 void makeFunctions(const glslang::TIntermSequence&);
187 void makeGlobalInitializers(const glslang::TIntermSequence&);
188 void visitFunctions(const glslang::TIntermSequence&);
189 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500190 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600191 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
192 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600193 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
194
John Kessenichead86222018-03-28 18:01:20 -0600195 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
196 glslang::TBasicType typeProxy, bool reduceComparison = true);
197 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
198 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500199 glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600200 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
201 glslang::TBasicType typeProxy);
202 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
203 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600204 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600205 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500206 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
Rex Xu51596642016-09-21 18:56:12 +0800207 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800208 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700209 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600210 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800211 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600212 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700213 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400214 spv::Id createSpvConstant(const glslang::TIntermTyped&);
215 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600216 bool isTrivialLeaf(const glslang::TIntermTyped* node);
217 bool isTrivial(const glslang::TIntermTyped* node);
218 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800219 spv::Id getExtBuiltins(const char* name);
John Kessenich9c14f772019-06-17 08:38:35 -0600220 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
221 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500222 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600223
John Kessenich121853f2017-05-31 17:11:16 -0600224 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600225 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600226 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700227 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 int sequenceDepth;
229
Lei Zhang17535f72016-05-04 15:55:59 -0400230 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400231
John Kessenich140f3df2015-06-26 16:58:36 -0600232 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
233 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700234 bool inEntryPoint;
235 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700236 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700237 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600238 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600239 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600240 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800241 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600242
John Kessenich2f273362015-07-18 22:34:27 -0600243 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600244 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600245 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700246 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700247 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800248 std::unordered_map<int, std::vector<int>> memberRemapper;
249 // for mapping glslang symbol struct to symbol Id
250 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600251 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700252 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600253 // Map pointee types for EbtReference to their forward pointers
254 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600255 // Type forcing, for when SPIR-V wants a different type than the AST,
256 // requiring local translation to and from SPIR-V type on every access.
257 // Maps <builtin-variable-id -> AST-required-type-id>
258 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600259};
260
261//
262// Helper functions for translating glslang representations to SPIR-V enumerants.
263//
264
265// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700266spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600267{
John Kessenich155d3512019-08-08 23:29:20 -0600268#ifdef GLSLANG_WEB
269 return spv::SourceLanguageESSL;
270#endif
271
John Kessenich66e2faf2016-03-12 18:34:36 -0700272 switch (source) {
273 case glslang::EShSourceGlsl:
274 switch (profile) {
275 case ENoProfile:
276 case ECoreProfile:
277 case ECompatibilityProfile:
278 return spv::SourceLanguageGLSL;
279 case EEsProfile:
280 return spv::SourceLanguageESSL;
281 default:
282 return spv::SourceLanguageUnknown;
283 }
284 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600285 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 default:
287 return spv::SourceLanguageUnknown;
288 }
289}
290
291// Translate glslang language (stage) to SPIR-V execution model.
292spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
293{
294 switch (stage) {
295 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600296 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600297 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600298#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600299 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
300 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
301 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700302 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
303 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
304 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
305 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
306 case EShLangMissNV: return spv::ExecutionModelMissNV;
307 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700308 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
309 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
310#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600311 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700312 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600313 return spv::ExecutionModelFragment;
314 }
315}
316
John Kessenich140f3df2015-06-26 16:58:36 -0600317// Translate glslang sampler type to SPIR-V dimensionality.
318spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
319{
320 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700321 case glslang::Esd1D: return spv::Dim1D;
322 case glslang::Esd2D: return spv::Dim2D;
323 case glslang::Esd3D: return spv::Dim3D;
324 case glslang::EsdCube: return spv::DimCube;
325 case glslang::EsdRect: return spv::DimRect;
326 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700327 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700329 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600330 return spv::Dim2D;
331 }
332}
333
John Kessenichf6640762016-08-01 19:44:00 -0600334// Translate glslang precision to SPIR-V precision decorations.
335spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600336{
John Kessenichf6640762016-08-01 19:44:00 -0600337 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700338 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600339 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 default:
341 return spv::NoPrecision;
342 }
343}
344
John Kessenichf6640762016-08-01 19:44:00 -0600345// Translate glslang type to SPIR-V precision decorations.
346spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
347{
348 return TranslatePrecisionDecoration(type.getQualifier().precision);
349}
350
John Kessenich140f3df2015-06-26 16:58:36 -0600351// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600352spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600353{
354 if (type.getBasicType() == glslang::EbtBlock) {
355 switch (type.getQualifier().storage) {
356 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600357 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 case glslang::EvqVaryingIn: return spv::DecorationBlock;
359 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600360#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700361 case glslang::EvqPayloadNV: return spv::DecorationBlock;
362 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
363 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700364 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
365 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700366#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600367 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700368 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600369 break;
370 }
371 }
372
John Kessenich4016e382016-07-15 11:53:56 -0600373 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600374}
375
Rex Xu1da878f2016-02-21 20:59:01 +0800376// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500377void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800378{
Jeff Bolz36831c92018-09-05 10:11:41 -0500379 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600380 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500381 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600382 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500383 memory.push_back(spv::DecorationVolatile);
384 memory.push_back(spv::DecorationCoherent);
385 }
John Kessenich14b85d32018-06-04 15:36:03 -0600386 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600387 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800388 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600389 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800390 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600391 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800392 memory.push_back(spv::DecorationNonReadable);
393}
394
John Kessenich140f3df2015-06-26 16:58:36 -0600395// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700396spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600397{
398 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700399 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600400 case glslang::ElmRowMajor:
401 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700402 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700404 default:
405 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600406 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600407 }
408 } else {
409 switch (type.getBasicType()) {
410 default:
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600412 break;
413 case glslang::EbtBlock:
414 switch (type.getQualifier().storage) {
415 case glslang::EvqUniform:
416 case glslang::EvqBuffer:
417 switch (type.getQualifier().layoutPacking) {
418 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600419 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
420 default:
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422 }
423 case glslang::EvqVaryingIn:
424 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700425 if (type.getQualifier().isTaskMemory()) {
426 switch (type.getQualifier().layoutPacking) {
427 case glslang::ElpShared: return spv::DecorationGLSLShared;
428 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
429 default: break;
430 }
431 } else {
432 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
433 }
John Kessenich4016e382016-07-15 11:53:56 -0600434 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600435#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700436 case glslang::EvqPayloadNV:
437 case glslang::EvqPayloadInNV:
438 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700439 case glslang::EvqCallableDataNV:
440 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700441 return spv::DecorationMax;
442#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600443 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700444 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600445 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600446 }
447 }
448 }
449}
450
451// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600452// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700453// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800454spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600455{
Rex Xubbceed72016-05-21 09:40:44 +0800456 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700457 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600458 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600459 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700460 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700461 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600462 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600463 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800464 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800465 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800466 }
Rex Xubbceed72016-05-21 09:40:44 +0800467 else
John Kessenich4016e382016-07-15 11:53:56 -0600468 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800469}
470
471// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600472// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800473// should be applied.
474spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
475{
John Kessenichb9197c82019-08-11 07:41:45 -0600476 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600477 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600478#ifndef GLSLANG_WEB
479 else if (qualifier.patch)
480 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700481 else if (qualifier.sample) {
482 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600483 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600484 }
485#endif
486
487 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600488}
489
John Kessenich92187592016-02-01 13:45:25 -0700490// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700491spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600492{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700493 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600494 return spv::DecorationInvariant;
495 else
John Kessenich4016e382016-07-15 11:53:56 -0600496 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600497}
498
qining9220dbb2016-05-04 17:34:38 -0400499// If glslang type is noContraction, return SPIR-V NoContraction decoration.
500spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
501{
John Kessenichb9197c82019-08-11 07:41:45 -0600502#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600503 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400504 return spv::DecorationNoContraction;
505 else
John Kessenichb9197c82019-08-11 07:41:45 -0600506#endif
John Kessenich4016e382016-07-15 11:53:56 -0600507 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400508}
509
John Kessenich5611c6d2018-04-05 11:25:02 -0600510// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
511spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
512{
John Kessenichb9197c82019-08-11 07:41:45 -0600513#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600514 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600515 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600516 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
517 return spv::DecorationNonUniformEXT;
518 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600519#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600520 return spv::DecorationMax;
521}
522
John Kessenichb9197c82019-08-11 07:41:45 -0600523spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
524 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500525{
Jeff Bolz36831c92018-09-05 10:11:41 -0500526 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600527
528#ifndef GLSLANG_WEB
529 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
530 return mask;
531
Jeff Bolz36831c92018-09-05 10:11:41 -0500532 if (coherentFlags.volatil ||
533 coherentFlags.coherent ||
534 coherentFlags.devicecoherent ||
535 coherentFlags.queuefamilycoherent ||
536 coherentFlags.workgroupcoherent ||
537 coherentFlags.subgroupcoherent) {
538 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
539 spv::MemoryAccessMakePointerVisibleKHRMask;
540 }
541 if (coherentFlags.nonprivate) {
542 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
543 }
544 if (coherentFlags.volatil) {
545 mask = mask | spv::MemoryAccessVolatileMask;
546 }
547 if (mask != spv::MemoryAccessMaskNone) {
548 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
549 }
John Kessenichb9197c82019-08-11 07:41:45 -0600550#endif
551
Jeff Bolz36831c92018-09-05 10:11:41 -0500552 return mask;
553}
554
John Kessenichb9197c82019-08-11 07:41:45 -0600555spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
556 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500557{
Jeff Bolz36831c92018-09-05 10:11:41 -0500558 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600559
560#ifndef GLSLANG_WEB
561 if (!glslangIntermediate->usingVulkanMemoryModel())
562 return mask;
563
Jeff Bolz36831c92018-09-05 10:11:41 -0500564 if (coherentFlags.volatil ||
565 coherentFlags.coherent ||
566 coherentFlags.devicecoherent ||
567 coherentFlags.queuefamilycoherent ||
568 coherentFlags.workgroupcoherent ||
569 coherentFlags.subgroupcoherent) {
570 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
571 spv::ImageOperandsMakeTexelVisibleKHRMask;
572 }
573 if (coherentFlags.nonprivate) {
574 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
575 }
576 if (coherentFlags.volatil) {
577 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
578 }
579 if (mask != spv::ImageOperandsMaskNone) {
580 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
581 }
John Kessenichb9197c82019-08-11 07:41:45 -0600582#endif
583
Jeff Bolz36831c92018-09-05 10:11:41 -0500584 return mask;
585}
586
587spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
588{
John Kessenichb9197c82019-08-11 07:41:45 -0600589 spv::Builder::AccessChain::CoherentFlags flags = {};
590#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500591 flags.coherent = type.getQualifier().coherent;
592 flags.devicecoherent = type.getQualifier().devicecoherent;
593 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
594 // shared variables are implicitly workgroupcoherent in GLSL.
595 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
596 type.getQualifier().storage == glslang::EvqShared;
597 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600598 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500599 // *coherent variables are implicitly nonprivate in GLSL
600 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500601 flags.subgroupcoherent ||
602 flags.workgroupcoherent ||
603 flags.queuefamilycoherent ||
604 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600605 flags.coherent ||
606 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500607 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600608#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500609 return flags;
610}
611
John Kessenichb9197c82019-08-11 07:41:45 -0600612spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
613 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500614{
John Kessenichb9197c82019-08-11 07:41:45 -0600615 spv::Scope scope = spv::ScopeMax;
616
617#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600618 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500619 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
620 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
621 } else if (coherentFlags.devicecoherent) {
622 scope = spv::ScopeDevice;
623 } else if (coherentFlags.queuefamilycoherent) {
624 scope = spv::ScopeQueueFamilyKHR;
625 } else if (coherentFlags.workgroupcoherent) {
626 scope = spv::ScopeWorkgroup;
627 } else if (coherentFlags.subgroupcoherent) {
628 scope = spv::ScopeSubgroup;
Jeff Bolz36831c92018-09-05 10:11:41 -0500629 }
630 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
631 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
632 }
John Kessenichb9197c82019-08-11 07:41:45 -0600633#endif
634
Jeff Bolz36831c92018-09-05 10:11:41 -0500635 return scope;
636}
637
David Netoa901ffe2016-06-08 14:11:40 +0100638// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
639// associated capabilities when required. For some built-in variables, a capability
640// is generated only when using the variable in an executable instruction, but not when
641// just declaring a struct member variable with it. This is true for PointSize,
642// ClipDistance, and CullDistance.
643spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600644{
645 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700646 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600647#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600648 // Defer adding the capability until the built-in is actually used.
649 if (! memberDeclaration) {
650 switch (glslangIntermediate->getStage()) {
651 case EShLangGeometry:
652 builder.addCapability(spv::CapabilityGeometryPointSize);
653 break;
654 case EShLangTessControl:
655 case EShLangTessEvaluation:
656 builder.addCapability(spv::CapabilityTessellationPointSize);
657 break;
658 default:
659 break;
660 }
John Kessenich92187592016-02-01 13:45:25 -0700661 }
John Kessenich155d3512019-08-08 23:29:20 -0600662#endif
John Kessenich92187592016-02-01 13:45:25 -0700663 return spv::BuiltInPointSize;
664
John Kessenicha28f7a72019-08-06 07:00:58 -0600665 case glslang::EbvPosition: return spv::BuiltInPosition;
666 case glslang::EbvVertexId: return spv::BuiltInVertexId;
667 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
668 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
669 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
670
671 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
672 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
673 case glslang::EbvFace: return spv::BuiltInFrontFacing;
674 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
675
John Kessenich3dd1ce52019-10-17 07:08:40 -0600676 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
677 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
678 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
679 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
680 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
681 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
682
John Kessenicha28f7a72019-08-06 07:00:58 -0600683#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600684 // These *Distance capabilities logically belong here, but if the member is declared and
685 // then never used, consumers of SPIR-V prefer the capability not be declared.
686 // They are now generated when used, rather than here when declared.
687 // Potentially, the specification should be more clear what the minimum
688 // use needed is to trigger the capability.
689 //
John Kessenich92187592016-02-01 13:45:25 -0700690 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100691 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800692 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700693 return spv::BuiltInClipDistance;
694
695 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100696 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800697 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700698 return spv::BuiltInCullDistance;
699
700 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600701 builder.addCapability(spv::CapabilityMultiViewport);
702 if (glslangIntermediate->getStage() == EShLangVertex ||
703 glslangIntermediate->getStage() == EShLangTessControl ||
704 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800705
John Kessenich8317e6c2019-08-18 23:58:08 -0600706 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600707 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800708 }
John Kessenich92187592016-02-01 13:45:25 -0700709 return spv::BuiltInViewportIndex;
710
John Kessenich5e801132016-02-15 11:09:46 -0700711 case glslang::EbvSampleId:
712 builder.addCapability(spv::CapabilitySampleRateShading);
713 return spv::BuiltInSampleId;
714
715 case glslang::EbvSamplePosition:
716 builder.addCapability(spv::CapabilitySampleRateShading);
717 return spv::BuiltInSamplePosition;
718
719 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700720 return spv::BuiltInSampleMask;
721
John Kessenich78a45572016-07-08 14:05:15 -0600722 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700723 if (glslangIntermediate->getStage() == EShLangMeshNV) {
724 return spv::BuiltInLayer;
725 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600726 builder.addCapability(spv::CapabilityGeometry);
727 if (glslangIntermediate->getStage() == EShLangVertex ||
728 glslangIntermediate->getStage() == EShLangTessControl ||
729 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800730
John Kessenich8317e6c2019-08-18 23:58:08 -0600731 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600732 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800733 }
John Kessenich78a45572016-07-08 14:05:15 -0600734 return spv::BuiltInLayer;
735
John Kessenichda581a22015-10-14 14:10:30 -0600736 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600737 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800738 builder.addCapability(spv::CapabilityDrawParameters);
739 return spv::BuiltInBaseVertex;
740
John Kessenichda581a22015-10-14 14:10:30 -0600741 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600742 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800743 builder.addCapability(spv::CapabilityDrawParameters);
744 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200745
John Kessenichda581a22015-10-14 14:10:30 -0600746 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600747 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800748 builder.addCapability(spv::CapabilityDrawParameters);
749 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200750
751 case glslang::EbvPrimitiveId:
752 if (glslangIntermediate->getStage() == EShLangFragment)
753 builder.addCapability(spv::CapabilityGeometry);
754 return spv::BuiltInPrimitiveId;
755
Rex Xu37cdcee2017-06-29 17:46:34 +0800756 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800757 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
758 builder.addCapability(spv::CapabilityStencilExportEXT);
759 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800760
John Kessenich140f3df2015-06-26 16:58:36 -0600761 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600762 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
763 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
764 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
765 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600766 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800767
Rex Xu574ab042016-04-14 16:53:07 +0800768 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800769 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800770 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
771 return spv::BuiltInSubgroupSize;
772
Rex Xu574ab042016-04-14 16:53:07 +0800773 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800774 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800775 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
776 return spv::BuiltInSubgroupLocalInvocationId;
777
Rex Xu574ab042016-04-14 16:53:07 +0800778 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800779 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
780 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600781 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800782
Rex Xu574ab042016-04-14 16:53:07 +0800783 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800784 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
785 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600786 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800787
Rex Xu574ab042016-04-14 16:53:07 +0800788 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800789 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
790 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600791 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800792
Rex Xu574ab042016-04-14 16:53:07 +0800793 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800794 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
795 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600796 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800797
Rex Xu574ab042016-04-14 16:53:07 +0800798 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800799 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
800 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600801 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800802
John Kessenich66011cb2018-03-06 16:12:04 -0700803 case glslang::EbvNumSubgroups:
804 builder.addCapability(spv::CapabilityGroupNonUniform);
805 return spv::BuiltInNumSubgroups;
806
807 case glslang::EbvSubgroupID:
808 builder.addCapability(spv::CapabilityGroupNonUniform);
809 return spv::BuiltInSubgroupId;
810
811 case glslang::EbvSubgroupSize2:
812 builder.addCapability(spv::CapabilityGroupNonUniform);
813 return spv::BuiltInSubgroupSize;
814
815 case glslang::EbvSubgroupInvocation2:
816 builder.addCapability(spv::CapabilityGroupNonUniform);
817 return spv::BuiltInSubgroupLocalInvocationId;
818
819 case glslang::EbvSubgroupEqMask2:
820 builder.addCapability(spv::CapabilityGroupNonUniform);
821 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
822 return spv::BuiltInSubgroupEqMask;
823
824 case glslang::EbvSubgroupGeMask2:
825 builder.addCapability(spv::CapabilityGroupNonUniform);
826 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
827 return spv::BuiltInSubgroupGeMask;
828
829 case glslang::EbvSubgroupGtMask2:
830 builder.addCapability(spv::CapabilityGroupNonUniform);
831 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
832 return spv::BuiltInSubgroupGtMask;
833
834 case glslang::EbvSubgroupLeMask2:
835 builder.addCapability(spv::CapabilityGroupNonUniform);
836 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
837 return spv::BuiltInSubgroupLeMask;
838
839 case glslang::EbvSubgroupLtMask2:
840 builder.addCapability(spv::CapabilityGroupNonUniform);
841 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
842 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600843
Rex Xu17ff3432016-10-14 17:41:45 +0800844 case glslang::EbvBaryCoordNoPersp:
845 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
846 return spv::BuiltInBaryCoordNoPerspAMD;
847
848 case glslang::EbvBaryCoordNoPerspCentroid:
849 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
850 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
851
852 case glslang::EbvBaryCoordNoPerspSample:
853 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
854 return spv::BuiltInBaryCoordNoPerspSampleAMD;
855
856 case glslang::EbvBaryCoordSmooth:
857 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
858 return spv::BuiltInBaryCoordSmoothAMD;
859
860 case glslang::EbvBaryCoordSmoothCentroid:
861 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
862 return spv::BuiltInBaryCoordSmoothCentroidAMD;
863
864 case glslang::EbvBaryCoordSmoothSample:
865 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
866 return spv::BuiltInBaryCoordSmoothSampleAMD;
867
868 case glslang::EbvBaryCoordPullModel:
869 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
870 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800871
John Kessenich6c8aaac2017-02-27 01:20:51 -0700872 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600873 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700874 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700875 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700876
877 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600878 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700879 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700880 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700881
Daniel Koch5154db52018-11-26 10:01:58 -0500882 case glslang::EbvFragSizeEXT:
883 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
884 builder.addCapability(spv::CapabilityFragmentDensityEXT);
885 return spv::BuiltInFragSizeEXT;
886
887 case glslang::EbvFragInvocationCountEXT:
888 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
889 builder.addCapability(spv::CapabilityFragmentDensityEXT);
890 return spv::BuiltInFragInvocationCountEXT;
891
chaoc771d89f2017-01-13 01:10:53 -0800892 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800893 if (!memberDeclaration) {
894 builder.addExtension(spv::E_SPV_NV_viewport_array2);
895 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
896 }
chaoc771d89f2017-01-13 01:10:53 -0800897 return spv::BuiltInViewportMaskNV;
898 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800899 if (!memberDeclaration) {
900 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
901 builder.addCapability(spv::CapabilityShaderStereoViewNV);
902 }
chaoc771d89f2017-01-13 01:10:53 -0800903 return spv::BuiltInSecondaryPositionNV;
904 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800905 if (!memberDeclaration) {
906 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
907 builder.addCapability(spv::CapabilityShaderStereoViewNV);
908 }
chaoc771d89f2017-01-13 01:10:53 -0800909 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800910 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800911 if (!memberDeclaration) {
912 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
913 builder.addCapability(spv::CapabilityPerViewAttributesNV);
914 }
chaocdf3956c2017-02-14 14:52:34 -0800915 return spv::BuiltInPositionPerViewNV;
916 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800917 if (!memberDeclaration) {
918 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
919 builder.addCapability(spv::CapabilityPerViewAttributesNV);
920 }
chaocdf3956c2017-02-14 14:52:34 -0800921 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700922 case glslang::EbvFragFullyCoveredNV:
923 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
924 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
925 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700926 case glslang::EbvFragmentSizeNV:
927 builder.addExtension(spv::E_SPV_NV_shading_rate);
928 builder.addCapability(spv::CapabilityShadingRateNV);
929 return spv::BuiltInFragmentSizeNV;
930 case glslang::EbvInvocationsPerPixelNV:
931 builder.addExtension(spv::E_SPV_NV_shading_rate);
932 builder.addCapability(spv::CapabilityShadingRateNV);
933 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700934
Daniel Koch593a4e02019-05-27 16:46:31 -0400935 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700936 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700937 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700938 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700939 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700940 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700941 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700942 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700943 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700944 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700945 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700946 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700947 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700948 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700949 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700950 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700951 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700952 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700953 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700954 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700955 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700956 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700957 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700958 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700959 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700960 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700961 return spv::BuiltInWorldToObjectNV;
962 case glslang::EbvIncomingRayFlagsNV:
963 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400964
965 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700966 case glslang::EbvBaryCoordNV:
967 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
968 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
969 return spv::BuiltInBaryCoordNV;
970 case glslang::EbvBaryCoordNoPerspNV:
971 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
972 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
973 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400974
975 // mesh shaders
976 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700977 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400978 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700979 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400980 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700981 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400982 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700983 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400984 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700985 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400986 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700987 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400988 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700989 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400990 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700991 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -0400992
993 // sm builtins
994 case glslang::EbvWarpsPerSM:
995 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
996 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
997 return spv::BuiltInWarpsPerSMNV;
998 case glslang::EbvSMCount:
999 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1000 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1001 return spv::BuiltInSMCountNV;
1002 case glslang::EbvWarpID:
1003 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1004 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1005 return spv::BuiltInWarpIDNV;
1006 case glslang::EbvSMID:
1007 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1008 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1009 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001010#endif
1011
Rex Xu3e783f92017-02-22 16:44:48 +08001012 default:
1013 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001014 }
1015}
1016
Rex Xufc618912015-09-09 16:42:49 +08001017// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001018spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001019{
1020 assert(type.getBasicType() == glslang::EbtSampler);
1021
John Kessenichb9197c82019-08-11 07:41:45 -06001022#ifdef GLSLANG_WEB
1023 return spv::ImageFormatUnknown;
1024#endif
1025
John Kessenich5d0fa972016-02-15 11:57:00 -07001026 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001027 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001028 case glslang::ElfRg32f:
1029 case glslang::ElfRg16f:
1030 case glslang::ElfR11fG11fB10f:
1031 case glslang::ElfR16f:
1032 case glslang::ElfRgba16:
1033 case glslang::ElfRgb10A2:
1034 case glslang::ElfRg16:
1035 case glslang::ElfRg8:
1036 case glslang::ElfR16:
1037 case glslang::ElfR8:
1038 case glslang::ElfRgba16Snorm:
1039 case glslang::ElfRg16Snorm:
1040 case glslang::ElfRg8Snorm:
1041 case glslang::ElfR16Snorm:
1042 case glslang::ElfR8Snorm:
1043
1044 case glslang::ElfRg32i:
1045 case glslang::ElfRg16i:
1046 case glslang::ElfRg8i:
1047 case glslang::ElfR16i:
1048 case glslang::ElfR8i:
1049
1050 case glslang::ElfRgb10a2ui:
1051 case glslang::ElfRg32ui:
1052 case glslang::ElfRg16ui:
1053 case glslang::ElfRg8ui:
1054 case glslang::ElfR16ui:
1055 case glslang::ElfR8ui:
1056 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1057 break;
1058
1059 default:
1060 break;
1061 }
1062
1063 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001064 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001065 case glslang::ElfNone: return spv::ImageFormatUnknown;
1066 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1067 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1068 case glslang::ElfR32f: return spv::ImageFormatR32f;
1069 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1070 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1071 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1072 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1073 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1074 case glslang::ElfR16f: return spv::ImageFormatR16f;
1075 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1076 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1077 case glslang::ElfRg16: return spv::ImageFormatRg16;
1078 case glslang::ElfRg8: return spv::ImageFormatRg8;
1079 case glslang::ElfR16: return spv::ImageFormatR16;
1080 case glslang::ElfR8: return spv::ImageFormatR8;
1081 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1082 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1083 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1084 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1085 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1086 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1087 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1088 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1089 case glslang::ElfR32i: return spv::ImageFormatR32i;
1090 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1091 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1092 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1093 case glslang::ElfR16i: return spv::ImageFormatR16i;
1094 case glslang::ElfR8i: return spv::ImageFormatR8i;
1095 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1096 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1097 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1098 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1099 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1100 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1101 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1102 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1103 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1104 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001105 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001106 }
1107}
1108
John Kesseniche18fd202018-01-30 11:01:39 -07001109spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001110{
John Kesseniche18fd202018-01-30 11:01:39 -07001111 if (selectionNode.getFlatten())
1112 return spv::SelectionControlFlattenMask;
1113 if (selectionNode.getDontFlatten())
1114 return spv::SelectionControlDontFlattenMask;
1115 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001116}
1117
John Kesseniche18fd202018-01-30 11:01:39 -07001118spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001119{
John Kesseniche18fd202018-01-30 11:01:39 -07001120 if (switchNode.getFlatten())
1121 return spv::SelectionControlFlattenMask;
1122 if (switchNode.getDontFlatten())
1123 return spv::SelectionControlDontFlattenMask;
1124 return spv::SelectionControlMaskNone;
1125}
1126
John Kessenicha2858d92018-01-31 08:11:18 -07001127// return a non-0 dependency if the dependency argument must be set
1128spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001129 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001130{
1131 spv::LoopControlMask control = spv::LoopControlMaskNone;
1132
1133 if (loopNode.getDontUnroll())
1134 control = control | spv::LoopControlDontUnrollMask;
1135 if (loopNode.getUnroll())
1136 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001137 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001138 control = control | spv::LoopControlDependencyInfiniteMask;
1139 else if (loopNode.getLoopDependency() > 0) {
1140 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001141 operands.push_back((unsigned int)loopNode.getLoopDependency());
1142 }
1143 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1144 if (loopNode.getMinIterations() > 0) {
1145 control = control | spv::LoopControlMinIterationsMask;
1146 operands.push_back(loopNode.getMinIterations());
1147 }
1148 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1149 control = control | spv::LoopControlMaxIterationsMask;
1150 operands.push_back(loopNode.getMaxIterations());
1151 }
1152 if (loopNode.getIterationMultiple() > 1) {
1153 control = control | spv::LoopControlIterationMultipleMask;
1154 operands.push_back(loopNode.getIterationMultiple());
1155 }
1156 if (loopNode.getPeelCount() > 0) {
1157 control = control | spv::LoopControlPeelCountMask;
1158 operands.push_back(loopNode.getPeelCount());
1159 }
1160 if (loopNode.getPartialCount() > 0) {
1161 control = control | spv::LoopControlPartialCountMask;
1162 operands.push_back(loopNode.getPartialCount());
1163 }
John Kessenicha2858d92018-01-31 08:11:18 -07001164 }
John Kesseniche18fd202018-01-30 11:01:39 -07001165
1166 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001167}
1168
John Kessenicha5c5fb62017-05-05 05:09:58 -06001169// Translate glslang type to SPIR-V storage class.
1170spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1171{
1172 if (type.getQualifier().isPipeInput())
1173 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001174 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001175 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001176
1177 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001178 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001179 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001180 return spv::StorageClassAtomicCounter;
1181 if (type.containsOpaque())
1182 return spv::StorageClassUniformConstant;
1183 }
1184
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001185 if (type.getQualifier().isUniformOrBuffer() &&
John Kessenichdeec1932019-08-13 08:00:30 -06001186 type.getQualifier().isShaderRecordNV()) {
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001187 return spv::StorageClassShaderRecordBufferNV;
1188 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001189
John Kessenichbed4e4f2017-09-08 02:38:07 -06001190 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001191 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001192 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001193 }
1194
1195 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001196 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001197 return spv::StorageClassPushConstant;
1198 if (type.getBasicType() == glslang::EbtBlock)
1199 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001200 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001201 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001202
1203 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001204 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1205 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1206 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001207 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001208#ifndef GLSLANG_WEB
Ashwin Leleff1783d2018-10-22 16:41:44 -07001209 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1210 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1211 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1212 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1213 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001214#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001215 default:
1216 assert(0);
1217 break;
1218 }
1219
1220 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001221}
1222
John Kessenich5611c6d2018-04-05 11:25:02 -06001223// Add capabilities pertaining to how an array is indexed.
1224void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1225 const glslang::TType& indexType)
1226{
John Kessenichb9197c82019-08-11 07:41:45 -06001227#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001228 if (indexType.getQualifier().isNonUniform()) {
1229 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001230 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001231 if (baseType.getBasicType() == glslang::EbtSampler) {
1232 if (baseType.getQualifier().hasAttachment())
1233 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001234 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001235 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001236 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001237 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1238 else if (baseType.isImage())
1239 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1240 else if (baseType.isTexture())
1241 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1242 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1243 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1244 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1245 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1246 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1247 }
1248 } else {
1249 // assume a dynamically uniform index
1250 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001251 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001252 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001253 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001254 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001255 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001256 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001257 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001258 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001259 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001260 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001261 }
1262 }
John Kessenichb9197c82019-08-11 07:41:45 -06001263#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001264}
1265
qining25262b32016-05-06 17:25:16 -04001266// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001267// descriptor set.
1268bool IsDescriptorResource(const glslang::TType& type)
1269{
John Kessenichf7497e22016-03-08 21:36:22 -07001270 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001271 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001272 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001273 ! type.getQualifier().isShaderRecordNV() &&
1274 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001275
1276 // non block...
1277 // basically samplerXXX/subpass/sampler/texture are all included
1278 // if they are the global-scope-class, not the function parameter
1279 // (or local, if they ever exist) class.
1280 if (type.getBasicType() == glslang::EbtSampler)
1281 return type.getQualifier().isUniformOrBuffer();
1282
1283 // None of the above.
1284 return false;
1285}
1286
John Kesseniche0b6cad2015-12-24 10:30:13 -07001287void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1288{
1289 if (child.layoutMatrix == glslang::ElmNone)
1290 child.layoutMatrix = parent.layoutMatrix;
1291
1292 if (parent.invariant)
1293 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001294 if (parent.flat)
1295 child.flat = true;
1296 if (parent.centroid)
1297 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001298#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001299 if (parent.nopersp)
1300 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001301 if (parent.explicitInterp)
1302 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001303 if (parent.perPrimitiveNV)
1304 child.perPrimitiveNV = true;
1305 if (parent.perViewNV)
1306 child.perViewNV = true;
1307 if (parent.perTaskNV)
1308 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001309 if (parent.patch)
1310 child.patch = true;
1311 if (parent.sample)
1312 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001313 if (parent.coherent)
1314 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001315 if (parent.devicecoherent)
1316 child.devicecoherent = true;
1317 if (parent.queuefamilycoherent)
1318 child.queuefamilycoherent = true;
1319 if (parent.workgroupcoherent)
1320 child.workgroupcoherent = true;
1321 if (parent.subgroupcoherent)
1322 child.subgroupcoherent = true;
1323 if (parent.nonprivate)
1324 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001325 if (parent.volatil)
1326 child.volatil = true;
1327 if (parent.restrict)
1328 child.restrict = true;
1329 if (parent.readonly)
1330 child.readonly = true;
1331 if (parent.writeonly)
1332 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001333#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001334}
1335
John Kessenichf2b7f332016-09-01 17:05:23 -06001336bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001337{
John Kessenich7b9fa252016-01-21 18:56:57 -07001338 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001339 // - struct members might inherit from a struct declaration
1340 // (note that non-block structs don't explicitly inherit,
1341 // only implicitly, meaning no decoration involved)
1342 // - affect decorations on the struct members
1343 // (note smooth does not, and expecting something like volatile
1344 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001345 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001346 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001347}
1348
John Kessenich140f3df2015-06-26 16:58:36 -06001349//
1350// Implement the TGlslangToSpvTraverser class.
1351//
1352
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001353TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001354 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1355 : TIntermTraverser(true, false, true),
1356 options(options),
1357 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001358 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001359 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001360 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001361 glslangIntermediate(glslangIntermediate),
1362 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001363{
1364 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1365
1366 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001367 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1368 glslangIntermediate->getVersion());
1369
John Kessenich121853f2017-05-31 17:11:16 -06001370 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001371 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001372 builder.setSourceFile(glslangIntermediate->getSourceFile());
1373
1374 // Set the source shader's text. If for SPV version 1.0, include
1375 // a preamble in comments stating the OpModuleProcessed instructions.
1376 // Otherwise, emit those as actual instructions.
1377 std::string text;
1378 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1379 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001380 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001381 text.append("// OpModuleProcessed ");
1382 text.append(processes[p]);
1383 text.append("\n");
1384 } else
1385 builder.addModuleProcessed(processes[p]);
1386 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001387 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001388 text.append("#line 1\n");
1389 text.append(glslangIntermediate->getSourceText());
1390 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001391 // Pass name and text for all included files
1392 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1393 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1394 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001395 }
John Kessenich140f3df2015-06-26 16:58:36 -06001396 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001397
1398 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1399 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1400
1401 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1402 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001403 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001404 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1405 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001406 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001407 memoryModel = spv::MemoryModelVulkanKHR;
1408 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001409 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001410 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001411 builder.setMemoryModel(addressingModel, memoryModel);
1412
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001413 if (glslangIntermediate->usingVariablePointers()) {
1414 builder.addCapability(spv::CapabilityVariablePointers);
1415 }
1416
John Kessenicheee9d532016-09-19 18:09:30 -06001417 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1418 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001419
1420 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001421 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1422 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001423 builder.addSourceExtension(it->c_str());
1424
1425 // Add the top-level modes for this shader.
1426
John Kessenich92187592016-02-01 13:45:25 -07001427 if (glslangIntermediate->getXfbMode()) {
1428 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001429 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001430 }
John Kessenich140f3df2015-06-26 16:58:36 -06001431
1432 unsigned int mode;
1433 switch (glslangIntermediate->getStage()) {
1434 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001435 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001436 break;
1437
John Kessenicha28f7a72019-08-06 07:00:58 -06001438 case EShLangFragment:
1439 builder.addCapability(spv::CapabilityShader);
1440 if (glslangIntermediate->getPixelCenterInteger())
1441 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1442
1443 if (glslangIntermediate->getOriginUpperLeft())
1444 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1445 else
1446 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1447
1448 if (glslangIntermediate->getEarlyFragmentTests())
1449 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1450
1451 if (glslangIntermediate->getPostDepthCoverage()) {
1452 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1453 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1454 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1455 }
1456
John Kessenichb9197c82019-08-11 07:41:45 -06001457 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1458 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1459
1460#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001461 switch(glslangIntermediate->getDepth()) {
1462 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1463 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1464 default: mode = spv::ExecutionModeMax; break;
1465 }
1466 if (mode != spv::ExecutionModeMax)
1467 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001468 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001469 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1470 break;
1471 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1472 break;
1473 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1474 break;
1475 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1476 break;
1477 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1478 break;
1479 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1480 break;
1481 default: mode = spv::ExecutionModeMax;
1482 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001483 }
1484 if (mode != spv::ExecutionModeMax) {
1485 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1486 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1487 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1488 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1489 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1490 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1491 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1492 } else {
1493 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1494 }
1495 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1496 }
John Kessenichb9197c82019-08-11 07:41:45 -06001497#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001498 break;
1499
John Kessenicha28f7a72019-08-06 07:00:58 -06001500 case EShLangCompute:
1501 builder.addCapability(spv::CapabilityShader);
1502 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1503 glslangIntermediate->getLocalSize(1),
1504 glslangIntermediate->getLocalSize(2));
1505 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1506 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1507 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1508 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1509 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1510 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1511 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1512 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1513 }
1514 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001515#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001516 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001517 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001518 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001519
steve-lunarge7412492017-03-23 11:56:07 -06001520 glslang::TLayoutGeometry primitive;
1521
1522 if (glslangIntermediate->getStage() == EShLangTessControl) {
1523 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1524 primitive = glslangIntermediate->getOutputPrimitive();
1525 } else {
1526 primitive = glslangIntermediate->getInputPrimitive();
1527 }
1528
1529 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001530 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1531 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1532 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001533 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001534 }
John Kessenich4016e382016-07-15 11:53:56 -06001535 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001536 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1537
John Kesseniche6903322015-10-13 16:29:02 -06001538 switch (glslangIntermediate->getVertexSpacing()) {
1539 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1540 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1541 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001542 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001543 }
John Kessenich4016e382016-07-15 11:53:56 -06001544 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001545 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1546
1547 switch (glslangIntermediate->getVertexOrder()) {
1548 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1549 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001550 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001551 }
John Kessenich4016e382016-07-15 11:53:56 -06001552 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001553 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1554
1555 if (glslangIntermediate->getPointMode())
1556 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001557 break;
1558
1559 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001560 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001561 switch (glslangIntermediate->getInputPrimitive()) {
1562 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1563 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1564 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001565 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001566 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001567 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001568 }
John Kessenich4016e382016-07-15 11:53:56 -06001569 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001570 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001571
John Kessenich140f3df2015-06-26 16:58:36 -06001572 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1573
1574 switch (glslangIntermediate->getOutputPrimitive()) {
1575 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1576 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1577 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001578 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001579 }
John Kessenich4016e382016-07-15 11:53:56 -06001580 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001581 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1582 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1583 break;
1584
Chao Chenb50c02e2018-09-19 11:42:24 -07001585 case EShLangRayGenNV:
1586 case EShLangIntersectNV:
1587 case EShLangAnyHitNV:
1588 case EShLangClosestHitNV:
1589 case EShLangMissNV:
1590 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001591 builder.addCapability(spv::CapabilityRayTracingNV);
1592 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001593 break;
Chao Chen3c366992018-09-19 11:41:59 -07001594 case EShLangTaskNV:
1595 case EShLangMeshNV:
1596 builder.addCapability(spv::CapabilityMeshShadingNV);
1597 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1598 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1599 glslangIntermediate->getLocalSize(1),
1600 glslangIntermediate->getLocalSize(2));
1601 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1602 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1603 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1604
1605 switch (glslangIntermediate->getOutputPrimitive()) {
1606 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1607 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1608 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1609 default: mode = spv::ExecutionModeMax; break;
1610 }
1611 if (mode != spv::ExecutionModeMax)
1612 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1613 }
1614 break;
1615#endif
1616
John Kessenich140f3df2015-06-26 16:58:36 -06001617 default:
1618 break;
1619 }
John Kessenich140f3df2015-06-26 16:58:36 -06001620}
1621
John Kessenichfca82622016-11-26 13:23:20 -07001622// Finish creating SPV, after the traversal is complete.
1623void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001624{
John Kessenichf04c51b2018-08-03 15:56:12 -06001625 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001626 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001627 builder.setBuildPoint(shaderEntry->getLastBlock());
1628 builder.leaveFunction();
1629 }
1630
John Kessenich7ba63412015-12-20 17:37:07 -07001631 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001632 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1633 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001634
David Neto8c3d5b42019-10-21 14:50:31 -04001635 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001636 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001637 // Note: WebGPU code generation must have the opportunity to aggressively
1638 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001639 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001640}
1641
John Kessenichfca82622016-11-26 13:23:20 -07001642// Write the SPV into 'out'.
1643void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001644{
John Kessenichfca82622016-11-26 13:23:20 -07001645 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001646}
1647
1648//
1649// Implement the traversal functions.
1650//
1651// Return true from interior nodes to have the external traversal
1652// continue on to children. Return false if children were
1653// already processed.
1654//
1655
1656//
qining25262b32016-05-06 17:25:16 -04001657// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001658// - uniform/input reads
1659// - output writes
1660// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1661// - something simple that degenerates into the last bullet
1662//
1663void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1664{
qining75d1d802016-04-06 14:42:01 -04001665 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001666 if (symbol->getType().isStruct())
1667 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1668
qining75d1d802016-04-06 14:42:01 -04001669 if (symbol->getType().getQualifier().isSpecConstant())
1670 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1671
John Kessenich140f3df2015-06-26 16:58:36 -06001672 // getSymbolId() will set up all the IO decorations on the first call.
1673 // Formal function parameters were mapped during makeFunctions().
1674 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001675
John Kessenich7ba63412015-12-20 17:37:07 -07001676 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001677 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001678 // Consider adding to the OpEntryPoint interface list.
1679 // Only looking at structures if they have at least one member.
1680 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1681 spv::StorageClass sc = builder.getStorageClass(id);
1682 // Before SPIR-V 1.4, we only want to include Input and Output.
1683 // Starting with SPIR-V 1.4, we want all globals.
1684 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1685 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001686 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001687 }
John Kessenich5f77d862017-09-19 11:09:59 -06001688 }
John Kessenich9c14f772019-06-17 08:38:35 -06001689
1690 // If the SPIR-V type is required to be different than the AST type,
1691 // translate now from the SPIR-V type to the AST type, for the consuming
1692 // operation.
1693 // Note this turns it from an l-value to an r-value.
1694 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1695 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1696 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001697 }
1698
1699 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001700 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001701 // Prepare to generate code for the access
1702
1703 // L-value chains will be computed left to right. We're on the symbol now,
1704 // which is the left-most part of the access chain, so now is "clear" time,
1705 // followed by setting the base.
1706 builder.clearAccessChain();
1707
1708 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001709 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001710 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001711 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001712 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001713 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001714 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001715 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001716 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1717 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001718 builder.setAccessChainRValue(id);
1719 else
1720 builder.setAccessChainLValue(id);
1721 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001722
John Kessenichb9197c82019-08-11 07:41:45 -06001723#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001724 // Process linkage-only nodes for any special additional interface work.
1725 if (linkageOnly) {
1726 if (glslangIntermediate->getHlslFunctionality1()) {
1727 // Map implicit counter buffers to their originating buffers, which should have been
1728 // seen by now, given earlier pruning of unused counters, and preservation of order
1729 // of declaration.
1730 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1731 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1732 // Save possible originating buffers for counter buffers, keyed by
1733 // making the potential counter-buffer name.
1734 std::string keyName = symbol->getName().c_str();
1735 keyName = glslangIntermediate->addCounterBufferName(keyName);
1736 counterOriginator[keyName] = symbol;
1737 } else {
1738 // Handle a counter buffer, by finding the saved originating buffer.
1739 std::string keyName = symbol->getName().c_str();
1740 auto it = counterOriginator.find(keyName);
1741 if (it != counterOriginator.end()) {
1742 id = getSymbolId(it->second);
1743 if (id != spv::NoResult) {
1744 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001745 if (counterId != spv::NoResult) {
1746 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001747 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001748 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001749 }
1750 }
1751 }
1752 }
1753 }
1754 }
John Kessenich155d3512019-08-08 23:29:20 -06001755#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001756}
1757
1758bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1759{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001760 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001761 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1762 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1763 }
1764 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1765 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1766 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001767
qining40887662016-04-03 22:20:42 -04001768 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1769 if (node->getType().getQualifier().isSpecConstant())
1770 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1771
John Kessenich140f3df2015-06-26 16:58:36 -06001772 // First, handle special cases
1773 switch (node->getOp()) {
1774 case glslang::EOpAssign:
1775 case glslang::EOpAddAssign:
1776 case glslang::EOpSubAssign:
1777 case glslang::EOpMulAssign:
1778 case glslang::EOpVectorTimesMatrixAssign:
1779 case glslang::EOpVectorTimesScalarAssign:
1780 case glslang::EOpMatrixTimesScalarAssign:
1781 case glslang::EOpMatrixTimesMatrixAssign:
1782 case glslang::EOpDivAssign:
1783 case glslang::EOpModAssign:
1784 case glslang::EOpAndAssign:
1785 case glslang::EOpInclusiveOrAssign:
1786 case glslang::EOpExclusiveOrAssign:
1787 case glslang::EOpLeftShiftAssign:
1788 case glslang::EOpRightShiftAssign:
1789 // A bin-op assign "a += b" means the same thing as "a = a + b"
1790 // where a is evaluated before b. For a simple assignment, GLSL
1791 // says to evaluate the left before the right. So, always, left
1792 // node then right node.
1793 {
1794 // get the left l-value, save it away
1795 builder.clearAccessChain();
1796 node->getLeft()->traverse(this);
1797 spv::Builder::AccessChain lValue = builder.getAccessChain();
1798
1799 // evaluate the right
1800 builder.clearAccessChain();
1801 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001802 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001803
1804 if (node->getOp() != glslang::EOpAssign) {
1805 // the left is also an r-value
1806 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001807 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001808
1809 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001810 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001811 TranslateNoContractionDecoration(node->getType().getQualifier()),
1812 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001813 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001814 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1815 node->getType().getBasicType());
1816
1817 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001818 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001819 }
1820
1821 // store the result
1822 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001823 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001824
1825 // assignments are expressions having an rValue after they are evaluated...
1826 builder.clearAccessChain();
1827 builder.setAccessChainRValue(rValue);
1828 }
1829 return false;
1830 case glslang::EOpIndexDirect:
1831 case glslang::EOpIndexDirectStruct:
1832 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001833 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001834 // Get the left part of the access chain.
1835 node->getLeft()->traverse(this);
1836
1837 // Add the next element in the chain
1838
David Netoa901ffe2016-06-08 14:11:40 +01001839 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001840 if (! node->getLeft()->getType().isArray() &&
1841 node->getLeft()->getType().isVector() &&
1842 node->getOp() == glslang::EOpIndexDirect) {
1843 // This is essentially a hard-coded vector swizzle of size 1,
1844 // so short circuit the access-chain stuff with a swizzle.
1845 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001846 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001847 int dummySize;
1848 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1849 TranslateCoherent(node->getLeft()->getType()),
1850 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001851 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001852
1853 // Load through a block reference is performed with a dot operator that
1854 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1855 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001856 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001857 !node->getLeft()->getType().isArray() &&
1858 node->getOp() == glslang::EOpIndexDirectStruct)
1859 {
1860 spv::Id left = accessChainLoad(node->getLeft()->getType());
1861 builder.clearAccessChain();
1862 builder.setAccessChainLValue(left);
1863 }
1864
David Netoa901ffe2016-06-08 14:11:40 +01001865 int spvIndex = glslangIndex;
1866 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1867 node->getOp() == glslang::EOpIndexDirectStruct)
1868 {
1869 // This may be, e.g., an anonymous block-member selection, which generally need
1870 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001871 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1872 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1873 std::vector<int>& remapper = memberRemapper[glslangId];
1874 assert(remapper.size() > 0);
1875 spvIndex = remapper[glslangIndex];
1876 }
David Netoa901ffe2016-06-08 14:11:40 +01001877 }
John Kessenichebb50532016-05-16 19:22:05 -06001878
David Netoa901ffe2016-06-08 14:11:40 +01001879 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001880 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001881
1882 // Add capabilities here for accessing PointSize and clip/cull distance.
1883 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001884 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001885 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001886 }
1887 }
1888 return false;
1889 case glslang::EOpIndexIndirect:
1890 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001891 // Array, matrix, or vector indirection with variable index.
1892 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001893 // matrices are arrays of vectors, so will also work for a matrix.
1894 // Will use the access chain's 'component' for variable index into a vector.
1895
1896 // This adapter is building access chains left to right.
1897 // Set up the access chain to the left.
1898 node->getLeft()->traverse(this);
1899
1900 // save it so that computing the right side doesn't trash it
1901 spv::Builder::AccessChain partial = builder.getAccessChain();
1902
1903 // compute the next index in the chain
1904 builder.clearAccessChain();
1905 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001906 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001907
John Kessenich5611c6d2018-04-05 11:25:02 -06001908 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1909
John Kessenich140f3df2015-06-26 16:58:36 -06001910 // restore the saved access chain
1911 builder.setAccessChain(partial);
1912
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001913 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1914 int dummySize;
1915 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1916 TranslateCoherent(node->getLeft()->getType()),
1917 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1918 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001919 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001920 }
1921 return false;
1922 case glslang::EOpVectorSwizzle:
1923 {
1924 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001925 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001926 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001927 int dummySize;
1928 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1929 TranslateCoherent(node->getLeft()->getType()),
1930 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001931 }
1932 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001933 case glslang::EOpMatrixSwizzle:
1934 logger->missingFunctionality("matrix swizzle");
1935 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001936 case glslang::EOpLogicalOr:
1937 case glslang::EOpLogicalAnd:
1938 {
1939
1940 // These may require short circuiting, but can sometimes be done as straight
1941 // binary operations. The right operand must be short circuited if it has
1942 // side effects, and should probably be if it is complex.
1943 if (isTrivial(node->getRight()->getAsTyped()))
1944 break; // handle below as a normal binary operation
1945 // otherwise, we need to do dynamic short circuiting on the right operand
1946 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1947 builder.clearAccessChain();
1948 builder.setAccessChainRValue(result);
1949 }
1950 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001951 default:
1952 break;
1953 }
1954
1955 // Assume generic binary op...
1956
John Kessenich32cfd492016-02-02 12:37:46 -07001957 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001958 builder.clearAccessChain();
1959 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001960 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001961
John Kessenich32cfd492016-02-02 12:37:46 -07001962 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001963 builder.clearAccessChain();
1964 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001965 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001966
John Kessenich32cfd492016-02-02 12:37:46 -07001967 // get result
John Kessenichead86222018-03-28 18:01:20 -06001968 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001969 TranslateNoContractionDecoration(node->getType().getQualifier()),
1970 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001971 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001972 convertGlslangToSpvType(node->getType()), left, right,
1973 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001974
John Kessenich50e57562015-12-21 21:21:11 -07001975 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001976 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001977 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001978 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001979 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001980 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001981 return false;
1982 }
John Kessenich140f3df2015-06-26 16:58:36 -06001983}
1984
John Kessenich9c14f772019-06-17 08:38:35 -06001985// Figure out what, if any, type changes are needed when accessing a specific built-in.
1986// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1987// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1988std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1989 const glslang::TType& glslangType)
1990{
1991 switch(builtIn)
1992 {
1993 case spv::BuiltInSubgroupEqMask:
1994 case spv::BuiltInSubgroupGeMask:
1995 case spv::BuiltInSubgroupGtMask:
1996 case spv::BuiltInSubgroupLeMask:
1997 case spv::BuiltInSubgroupLtMask: {
1998 // these require changing a 64-bit scaler -> a vector of 32-bit components
1999 if (glslangType.isVector())
2000 break;
2001 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2002 builder.makeUintType(64));
2003 return ret;
2004 }
2005 default:
2006 break;
2007 }
2008
2009 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2010 return ret;
2011}
2012
2013// For an object previously identified (see getForcedType() and forceType)
2014// as needing type translations, do the translation needed for a load, turning
2015// an L-value into in R-value.
2016spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2017{
2018 const auto forceIt = forceType.find(object);
2019 if (forceIt == forceType.end())
2020 return object;
2021
2022 spv::Id desiredTypeId = forceIt->second;
2023 spv::Id objectTypeId = builder.getTypeId(object);
2024 assert(builder.isPointerType(objectTypeId));
2025 objectTypeId = builder.getContainedTypeId(objectTypeId);
2026 if (builder.isVectorType(objectTypeId) &&
2027 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2028 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2029 // handle 32-bit v.xy* -> 64-bit
2030 builder.clearAccessChain();
2031 builder.setAccessChainLValue(object);
2032 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2033 std::vector<spv::Id> components;
2034 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2035 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2036
2037 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2038 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2039 builder.createCompositeConstruct(vecType, components));
2040 } else {
2041 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2042 }
2043 } else {
2044 logger->missingFunctionality("forcing non 32-bit vector type");
2045 }
2046
2047 return object;
2048}
2049
John Kessenich140f3df2015-06-26 16:58:36 -06002050bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2051{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002052 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002053
qining40887662016-04-03 22:20:42 -04002054 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2055 if (node->getType().getQualifier().isSpecConstant())
2056 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2057
John Kessenichfc51d282015-08-19 13:34:18 -06002058 spv::Id result = spv::NoResult;
2059
2060 // try texturing first
2061 result = createImageTextureFunctionCall(node);
2062 if (result != spv::NoResult) {
2063 builder.clearAccessChain();
2064 builder.setAccessChainRValue(result);
2065
2066 return false; // done with this node
2067 }
2068
2069 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002070
2071 if (node->getOp() == glslang::EOpArrayLength) {
2072 // Quite special; won't want to evaluate the operand.
2073
John Kessenich5611c6d2018-04-05 11:25:02 -06002074 // Currently, the front-end does not allow .length() on an array until it is sized,
2075 // except for the last block membeor of an SSBO.
2076 // TODO: If this changes, link-time sized arrays might show up here, and need their
2077 // size extracted.
2078
John Kessenichc9a80832015-09-12 12:17:44 -06002079 // Normal .length() would have been constant folded by the front-end.
2080 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002081 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002082
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002083 spv::Id length;
2084 if (node->getOperand()->getType().isCoopMat()) {
2085 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2086
2087 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2088 assert(builder.isCooperativeMatrixType(typeId));
2089
2090 length = builder.createCooperativeMatrixLength(typeId);
2091 } else {
2092 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2093 block->traverse(this);
2094 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2095 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2096 }
John Kessenichc9a80832015-09-12 12:17:44 -06002097
John Kessenich8c869672018-11-28 07:01:37 -07002098 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2099 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2100 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002101 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2102 if (builder.isInSpecConstCodeGenMode()) {
2103 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2104 } else {
2105 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2106 }
2107 }
John Kessenich8c869672018-11-28 07:01:37 -07002108
John Kessenichc9a80832015-09-12 12:17:44 -06002109 builder.clearAccessChain();
2110 builder.setAccessChainRValue(length);
2111
2112 return false;
2113 }
2114
John Kessenichfc51d282015-08-19 13:34:18 -06002115 // Start by evaluating the operand
2116
John Kessenich8c8505c2016-07-26 12:50:38 -06002117 // Does it need a swizzle inversion? If so, evaluation is inverted;
2118 // operate first on the swizzle base, then apply the swizzle.
2119 spv::Id invertedType = spv::NoType;
2120 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2121 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2122 invertedType = getInvertedSwizzleType(*node->getOperand());
2123
John Kessenich140f3df2015-06-26 16:58:36 -06002124 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002125 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002126 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002127 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002128 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002129 operandNode = node->getOperand();
2130
2131 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002132
Rex Xufc618912015-09-09 16:42:49 +08002133 spv::Id operand = spv::NoResult;
2134
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002135 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2136
John Kessenichfb4f2332019-08-09 03:49:15 -06002137#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002138 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2139 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002140 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002141 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002142 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002143 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2144 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2145 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002146#endif
2147 {
John Kessenich32cfd492016-02-02 12:37:46 -07002148 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002149 }
John Kessenich140f3df2015-06-26 16:58:36 -06002150
John Kessenichead86222018-03-28 18:01:20 -06002151 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002152 TranslateNoContractionDecoration(node->getType().getQualifier()),
2153 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002154
2155 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002156 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002157 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002158
2159 // if not, then possibly an operation
2160 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002161 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002162
2163 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002164 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002165 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002166 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002167 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002168
John Kessenich140f3df2015-06-26 16:58:36 -06002169 builder.clearAccessChain();
2170 builder.setAccessChainRValue(result);
2171
2172 return false; // done with this node
2173 }
2174
2175 // it must be a special case, check...
2176 switch (node->getOp()) {
2177 case glslang::EOpPostIncrement:
2178 case glslang::EOpPostDecrement:
2179 case glslang::EOpPreIncrement:
2180 case glslang::EOpPreDecrement:
2181 {
2182 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002183 spv::Id one = 0;
2184 if (node->getBasicType() == glslang::EbtFloat)
2185 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002186#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002187 else if (node->getBasicType() == glslang::EbtDouble)
2188 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002189 else if (node->getBasicType() == glslang::EbtFloat16)
2190 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002191 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2192 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002193 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2194 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002195 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2196 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002197#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002198 else
2199 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002200 glslang::TOperator op;
2201 if (node->getOp() == glslang::EOpPreIncrement ||
2202 node->getOp() == glslang::EOpPostIncrement)
2203 op = glslang::EOpAdd;
2204 else
2205 op = glslang::EOpSub;
2206
John Kessenichead86222018-03-28 18:01:20 -06002207 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002208 convertGlslangToSpvType(node->getType()), operand, one,
2209 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002210 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002211
2212 // The result of operation is always stored, but conditionally the
2213 // consumed result. The consumed result is always an r-value.
2214 builder.accessChainStore(result);
2215 builder.clearAccessChain();
2216 if (node->getOp() == glslang::EOpPreIncrement ||
2217 node->getOp() == glslang::EOpPreDecrement)
2218 builder.setAccessChainRValue(result);
2219 else
2220 builder.setAccessChainRValue(operand);
2221 }
2222
2223 return false;
2224
John Kessenich155d3512019-08-08 23:29:20 -06002225#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002226 case glslang::EOpEmitStreamVertex:
2227 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2228 return false;
2229 case glslang::EOpEndStreamPrimitive:
2230 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2231 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002232#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002233
2234 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002235 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002236 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002237 }
John Kessenich140f3df2015-06-26 16:58:36 -06002238}
2239
Jeff Bolz53134492019-06-25 13:31:10 -05002240// Construct a composite object, recursively copying members if their types don't match
2241spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2242{
2243 for (int c = 0; c < (int)constituents.size(); ++c) {
2244 spv::Id& constituent = constituents[c];
2245 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2246 spv::Id rType = builder.getTypeId(constituent);
2247 if (lType != rType) {
2248 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2249 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2250 } else if (builder.isStructType(rType)) {
2251 std::vector<spv::Id> rTypeConstituents;
2252 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2253 for (int i = 0; i < numrTypeConstituents; ++i) {
2254 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2255 }
2256 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2257 } else {
2258 assert(builder.isArrayType(rType));
2259 std::vector<spv::Id> rTypeConstituents;
2260 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2261
2262 spv::Id elementRType = builder.getContainedTypeId(rType);
2263 for (int i = 0; i < numrTypeConstituents; ++i) {
2264 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2265 }
2266 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2267 }
2268 }
2269 }
2270 return builder.createCompositeConstruct(resultTypeId, constituents);
2271}
2272
John Kessenich140f3df2015-06-26 16:58:36 -06002273bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2274{
qining27e04a02016-04-14 16:40:20 -04002275 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2276 if (node->getType().getQualifier().isSpecConstant())
2277 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2278
John Kessenichfc51d282015-08-19 13:34:18 -06002279 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002280 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2281 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002282
2283 // try texturing
2284 result = createImageTextureFunctionCall(node);
2285 if (result != spv::NoResult) {
2286 builder.clearAccessChain();
2287 builder.setAccessChainRValue(result);
2288
2289 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002290 }
2291#ifndef GLSLANG_WEB
2292 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002293 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002294 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002295 // "imageStore" is a special case, which has no result
2296 return false;
2297 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002298#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002299
John Kessenich140f3df2015-06-26 16:58:36 -06002300 glslang::TOperator binOp = glslang::EOpNull;
2301 bool reduceComparison = true;
2302 bool isMatrix = false;
2303 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002304 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002305
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002306 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2307
John Kessenich140f3df2015-06-26 16:58:36 -06002308 assert(node->getOp());
2309
John Kessenichf6640762016-08-01 19:44:00 -06002310 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002311
2312 switch (node->getOp()) {
2313 case glslang::EOpSequence:
2314 {
2315 if (preVisit)
2316 ++sequenceDepth;
2317 else
2318 --sequenceDepth;
2319
2320 if (sequenceDepth == 1) {
2321 // If this is the parent node of all the functions, we want to see them
2322 // early, so all call points have actual SPIR-V functions to reference.
2323 // In all cases, still let the traverser visit the children for us.
2324 makeFunctions(node->getAsAggregate()->getSequence());
2325
John Kessenich6fccb3c2016-09-19 16:01:41 -06002326 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002327 // anything else gets there, so visit out of order, doing them all now.
2328 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2329
John Kessenich6a60c2f2016-12-08 21:01:59 -07002330 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06002331 // so do them manually.
2332 visitFunctions(node->getAsAggregate()->getSequence());
2333
2334 return false;
2335 }
2336
2337 return true;
2338 }
2339 case glslang::EOpLinkerObjects:
2340 {
2341 if (visit == glslang::EvPreVisit)
2342 linkageOnly = true;
2343 else
2344 linkageOnly = false;
2345
2346 return true;
2347 }
2348 case glslang::EOpComma:
2349 {
2350 // processing from left to right naturally leaves the right-most
2351 // lying around in the access chain
2352 glslang::TIntermSequence& glslangOperands = node->getSequence();
2353 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2354 glslangOperands[i]->traverse(this);
2355
2356 return false;
2357 }
2358 case glslang::EOpFunction:
2359 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002360 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002361 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002362 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002363 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002364 } else {
2365 handleFunctionEntry(node);
2366 }
2367 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002368 if (inEntryPoint)
2369 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002370 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002371 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002372 }
2373
2374 return true;
2375 case glslang::EOpParameters:
2376 // Parameters will have been consumed by EOpFunction processing, but not
2377 // the body, so we still visited the function node's children, making this
2378 // child redundant.
2379 return false;
2380 case glslang::EOpFunctionCall:
2381 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002382 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002383 if (node->isUserDefined())
2384 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002385 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07002386 if (result) {
2387 builder.clearAccessChain();
2388 builder.setAccessChainRValue(result);
2389 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002390 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002391
2392 return false;
2393 }
2394 case glslang::EOpConstructMat2x2:
2395 case glslang::EOpConstructMat2x3:
2396 case glslang::EOpConstructMat2x4:
2397 case glslang::EOpConstructMat3x2:
2398 case glslang::EOpConstructMat3x3:
2399 case glslang::EOpConstructMat3x4:
2400 case glslang::EOpConstructMat4x2:
2401 case glslang::EOpConstructMat4x3:
2402 case glslang::EOpConstructMat4x4:
2403 case glslang::EOpConstructDMat2x2:
2404 case glslang::EOpConstructDMat2x3:
2405 case glslang::EOpConstructDMat2x4:
2406 case glslang::EOpConstructDMat3x2:
2407 case glslang::EOpConstructDMat3x3:
2408 case glslang::EOpConstructDMat3x4:
2409 case glslang::EOpConstructDMat4x2:
2410 case glslang::EOpConstructDMat4x3:
2411 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002412 case glslang::EOpConstructIMat2x2:
2413 case glslang::EOpConstructIMat2x3:
2414 case glslang::EOpConstructIMat2x4:
2415 case glslang::EOpConstructIMat3x2:
2416 case glslang::EOpConstructIMat3x3:
2417 case glslang::EOpConstructIMat3x4:
2418 case glslang::EOpConstructIMat4x2:
2419 case glslang::EOpConstructIMat4x3:
2420 case glslang::EOpConstructIMat4x4:
2421 case glslang::EOpConstructUMat2x2:
2422 case glslang::EOpConstructUMat2x3:
2423 case glslang::EOpConstructUMat2x4:
2424 case glslang::EOpConstructUMat3x2:
2425 case glslang::EOpConstructUMat3x3:
2426 case glslang::EOpConstructUMat3x4:
2427 case glslang::EOpConstructUMat4x2:
2428 case glslang::EOpConstructUMat4x3:
2429 case glslang::EOpConstructUMat4x4:
2430 case glslang::EOpConstructBMat2x2:
2431 case glslang::EOpConstructBMat2x3:
2432 case glslang::EOpConstructBMat2x4:
2433 case glslang::EOpConstructBMat3x2:
2434 case glslang::EOpConstructBMat3x3:
2435 case glslang::EOpConstructBMat3x4:
2436 case glslang::EOpConstructBMat4x2:
2437 case glslang::EOpConstructBMat4x3:
2438 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002439 case glslang::EOpConstructF16Mat2x2:
2440 case glslang::EOpConstructF16Mat2x3:
2441 case glslang::EOpConstructF16Mat2x4:
2442 case glslang::EOpConstructF16Mat3x2:
2443 case glslang::EOpConstructF16Mat3x3:
2444 case glslang::EOpConstructF16Mat3x4:
2445 case glslang::EOpConstructF16Mat4x2:
2446 case glslang::EOpConstructF16Mat4x3:
2447 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002448 isMatrix = true;
2449 // fall through
2450 case glslang::EOpConstructFloat:
2451 case glslang::EOpConstructVec2:
2452 case glslang::EOpConstructVec3:
2453 case glslang::EOpConstructVec4:
2454 case glslang::EOpConstructDouble:
2455 case glslang::EOpConstructDVec2:
2456 case glslang::EOpConstructDVec3:
2457 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002458 case glslang::EOpConstructFloat16:
2459 case glslang::EOpConstructF16Vec2:
2460 case glslang::EOpConstructF16Vec3:
2461 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002462 case glslang::EOpConstructBool:
2463 case glslang::EOpConstructBVec2:
2464 case glslang::EOpConstructBVec3:
2465 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002466 case glslang::EOpConstructInt8:
2467 case glslang::EOpConstructI8Vec2:
2468 case glslang::EOpConstructI8Vec3:
2469 case glslang::EOpConstructI8Vec4:
2470 case glslang::EOpConstructUint8:
2471 case glslang::EOpConstructU8Vec2:
2472 case glslang::EOpConstructU8Vec3:
2473 case glslang::EOpConstructU8Vec4:
2474 case glslang::EOpConstructInt16:
2475 case glslang::EOpConstructI16Vec2:
2476 case glslang::EOpConstructI16Vec3:
2477 case glslang::EOpConstructI16Vec4:
2478 case glslang::EOpConstructUint16:
2479 case glslang::EOpConstructU16Vec2:
2480 case glslang::EOpConstructU16Vec3:
2481 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002482 case glslang::EOpConstructInt:
2483 case glslang::EOpConstructIVec2:
2484 case glslang::EOpConstructIVec3:
2485 case glslang::EOpConstructIVec4:
2486 case glslang::EOpConstructUint:
2487 case glslang::EOpConstructUVec2:
2488 case glslang::EOpConstructUVec3:
2489 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002490 case glslang::EOpConstructInt64:
2491 case glslang::EOpConstructI64Vec2:
2492 case glslang::EOpConstructI64Vec3:
2493 case glslang::EOpConstructI64Vec4:
2494 case glslang::EOpConstructUint64:
2495 case glslang::EOpConstructU64Vec2:
2496 case glslang::EOpConstructU64Vec3:
2497 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002498 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002499 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002500 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002501 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002502 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002503 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002504 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002505 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002506 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002507 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002508 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002509 else if (node->getOp() == glslang::EOpConstructStruct ||
2510 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2511 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002512 std::vector<spv::Id> constituents;
2513 for (int c = 0; c < (int)arguments.size(); ++c)
2514 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002515 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002516 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002517 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002518 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002519 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002520
2521 builder.clearAccessChain();
2522 builder.setAccessChainRValue(constructed);
2523
2524 return false;
2525 }
2526
2527 // These six are component-wise compares with component-wise results.
2528 // Forward on to createBinaryOperation(), requesting a vector result.
2529 case glslang::EOpLessThan:
2530 case glslang::EOpGreaterThan:
2531 case glslang::EOpLessThanEqual:
2532 case glslang::EOpGreaterThanEqual:
2533 case glslang::EOpVectorEqual:
2534 case glslang::EOpVectorNotEqual:
2535 {
2536 // Map the operation to a binary
2537 binOp = node->getOp();
2538 reduceComparison = false;
2539 switch (node->getOp()) {
2540 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2541 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2542 default: binOp = node->getOp(); break;
2543 }
2544
2545 break;
2546 }
2547 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002548 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002549 binOp = glslang::EOpMul;
2550 break;
2551 case glslang::EOpOuterProduct:
2552 // two vectors multiplied to make a matrix
2553 binOp = glslang::EOpOuterProduct;
2554 break;
2555 case glslang::EOpDot:
2556 {
qining25262b32016-05-06 17:25:16 -04002557 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002558 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002559 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002560 binOp = glslang::EOpMul;
2561 break;
2562 }
2563 case glslang::EOpMod:
2564 // when an aggregate, this is the floating-point mod built-in function,
2565 // which can be emitted by the one in createBinaryOperation()
2566 binOp = glslang::EOpMod;
2567 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002568
John Kessenich140f3df2015-06-26 16:58:36 -06002569 case glslang::EOpEmitVertex:
2570 case glslang::EOpEndPrimitive:
2571 case glslang::EOpBarrier:
2572 case glslang::EOpMemoryBarrier:
2573 case glslang::EOpMemoryBarrierAtomicCounter:
2574 case glslang::EOpMemoryBarrierBuffer:
2575 case glslang::EOpMemoryBarrierImage:
2576 case glslang::EOpMemoryBarrierShared:
2577 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002578 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002579 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002580 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002581 case glslang::EOpWorkgroupMemoryBarrier:
2582 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002583 case glslang::EOpSubgroupBarrier:
2584 case glslang::EOpSubgroupMemoryBarrier:
2585 case glslang::EOpSubgroupMemoryBarrierBuffer:
2586 case glslang::EOpSubgroupMemoryBarrierImage:
2587 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002588 noReturnValue = true;
2589 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2590 break;
2591
John Kessenich426394d2015-07-23 10:22:48 -06002592 case glslang::EOpAtomicAdd:
2593 case glslang::EOpAtomicMin:
2594 case glslang::EOpAtomicMax:
2595 case glslang::EOpAtomicAnd:
2596 case glslang::EOpAtomicOr:
2597 case glslang::EOpAtomicXor:
2598 case glslang::EOpAtomicExchange:
2599 case glslang::EOpAtomicCompSwap:
2600 atomic = true;
2601 break;
2602
John Kesseniche5eee8f2019-10-18 01:03:11 -06002603#ifndef GLSLANG_WEB
2604 case glslang::EOpAtomicStore:
2605 noReturnValue = true;
2606 // fallthrough
2607 case glslang::EOpAtomicLoad:
2608 atomic = true;
2609 break;
2610
John Kessenich0d0c6d32017-07-23 16:08:26 -06002611 case glslang::EOpAtomicCounterAdd:
2612 case glslang::EOpAtomicCounterSubtract:
2613 case glslang::EOpAtomicCounterMin:
2614 case glslang::EOpAtomicCounterMax:
2615 case glslang::EOpAtomicCounterAnd:
2616 case glslang::EOpAtomicCounterOr:
2617 case glslang::EOpAtomicCounterXor:
2618 case glslang::EOpAtomicCounterExchange:
2619 case glslang::EOpAtomicCounterCompSwap:
2620 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2621 builder.addCapability(spv::CapabilityAtomicStorageOps);
2622 atomic = true;
2623 break;
2624
Ian Romanickb3bd4022019-01-21 08:57:25 -08002625 case glslang::EOpAbsDifference:
2626 case glslang::EOpAddSaturate:
2627 case glslang::EOpSubSaturate:
2628 case glslang::EOpAverage:
2629 case glslang::EOpAverageRounded:
2630 case glslang::EOpMul32x16:
2631 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2632 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2633 binOp = node->getOp();
2634 break;
2635
Chao Chenb50c02e2018-09-19 11:42:24 -07002636 case glslang::EOpIgnoreIntersectionNV:
2637 case glslang::EOpTerminateRayNV:
2638 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002639 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002640 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2641 noReturnValue = true;
2642 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002643 case glslang::EOpCooperativeMatrixLoad:
2644 case glslang::EOpCooperativeMatrixStore:
2645 noReturnValue = true;
2646 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002647 case glslang::EOpBeginInvocationInterlock:
2648 case glslang::EOpEndInvocationInterlock:
2649 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2650 noReturnValue = true;
2651 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002652#endif
Chao Chen3c366992018-09-19 11:41:59 -07002653
John Kessenich140f3df2015-06-26 16:58:36 -06002654 default:
2655 break;
2656 }
2657
2658 //
2659 // See if it maps to a regular operation.
2660 //
John Kessenich140f3df2015-06-26 16:58:36 -06002661 if (binOp != glslang::EOpNull) {
2662 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2663 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2664 assert(left && right);
2665
2666 builder.clearAccessChain();
2667 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002668 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002669
2670 builder.clearAccessChain();
2671 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002672 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002673
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002674 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002675 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002676 TranslateNoContractionDecoration(node->getType().getQualifier()),
2677 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002678 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002679 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002680 left->getType().getBasicType(), reduceComparison);
2681
2682 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002683 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002684 builder.clearAccessChain();
2685 builder.setAccessChainRValue(result);
2686
2687 return false;
2688 }
2689
John Kessenich426394d2015-07-23 10:22:48 -06002690 //
2691 // Create the list of operands.
2692 //
John Kessenich140f3df2015-06-26 16:58:36 -06002693 glslang::TIntermSequence& glslangOperands = node->getSequence();
2694 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002695 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002696 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002697 // special case l-value operands; there are just a few
2698 bool lvalue = false;
2699 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002700 case glslang::EOpModf:
2701 if (arg == 1)
2702 lvalue = true;
2703 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002704
2705 case glslang::EOpAtomicAdd:
2706 case glslang::EOpAtomicMin:
2707 case glslang::EOpAtomicMax:
2708 case glslang::EOpAtomicAnd:
2709 case glslang::EOpAtomicOr:
2710 case glslang::EOpAtomicXor:
2711 case glslang::EOpAtomicExchange:
2712 case glslang::EOpAtomicCompSwap:
2713 if (arg == 0)
2714 lvalue = true;
2715 break;
2716
John Kessenicha28f7a72019-08-06 07:00:58 -06002717#ifndef GLSLANG_WEB
2718 case glslang::EOpFrexp:
2719 if (arg == 1)
2720 lvalue = true;
2721 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002722 case glslang::EOpInterpolateAtSample:
2723 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002724 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002725 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002726 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002727
2728 // Does it need a swizzle inversion? If so, evaluation is inverted;
2729 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002730 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002731 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2732 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2733 }
Rex Xu7a26c172015-12-08 17:12:09 +08002734 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002735 case glslang::EOpAtomicLoad:
2736 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002737 case glslang::EOpAtomicCounterAdd:
2738 case glslang::EOpAtomicCounterSubtract:
2739 case glslang::EOpAtomicCounterMin:
2740 case glslang::EOpAtomicCounterMax:
2741 case glslang::EOpAtomicCounterAnd:
2742 case glslang::EOpAtomicCounterOr:
2743 case glslang::EOpAtomicCounterXor:
2744 case glslang::EOpAtomicCounterExchange:
2745 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002746 if (arg == 0)
2747 lvalue = true;
2748 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002749 case glslang::EOpAddCarry:
2750 case glslang::EOpSubBorrow:
2751 if (arg == 2)
2752 lvalue = true;
2753 break;
2754 case glslang::EOpUMulExtended:
2755 case glslang::EOpIMulExtended:
2756 if (arg >= 2)
2757 lvalue = true;
2758 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002759 case glslang::EOpCooperativeMatrixLoad:
2760 if (arg == 0 || arg == 1)
2761 lvalue = true;
2762 break;
2763 case glslang::EOpCooperativeMatrixStore:
2764 if (arg == 1)
2765 lvalue = true;
2766 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002767#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002768 default:
2769 break;
2770 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002771 builder.clearAccessChain();
2772 if (invertedType != spv::NoType && arg == 0)
2773 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2774 else
2775 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002776
John Kessenichb9197c82019-08-11 07:41:45 -06002777#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002778 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2779 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2780
2781 if (arg == 1) {
2782 // fold "element" parameter into the access chain
2783 spv::Builder::AccessChain save = builder.getAccessChain();
2784 builder.clearAccessChain();
2785 glslangOperands[2]->traverse(this);
2786
2787 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2788
2789 builder.setAccessChain(save);
2790
2791 // Point to the first element of the array.
2792 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002793 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002794
2795 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2796 unsigned int alignment = builder.getAccessChain().alignment;
2797
2798 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2799 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2800 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2801 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2802 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2803 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2804 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2805 }
2806
2807 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2808
2809 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2810 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2811 }
2812
2813 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2814 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2815 }
2816 } else if (arg == 2) {
2817 continue;
2818 }
2819 }
John Kessenichb9197c82019-08-11 07:41:45 -06002820#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002821
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002822 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002823 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002824 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2825 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2826 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002827 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002828 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002829 }
John Kessenich140f3df2015-06-26 16:58:36 -06002830 }
John Kessenich426394d2015-07-23 10:22:48 -06002831
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002832 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002833#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002834 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2835 std::vector<spv::IdImmediate> idImmOps;
2836
2837 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2838 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2839 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2840 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2841 // get the pointee type
2842 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2843 assert(builder.isCooperativeMatrixType(typeId));
2844 // do the op
2845 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2846 // store the result to the pointer (out param 'm')
2847 builder.createStore(result, operands[0]);
2848 result = 0;
2849 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2850 std::vector<spv::IdImmediate> idImmOps;
2851
2852 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2853 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2854 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2855 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2856 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2857
2858 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2859 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06002860 } else
2861#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06002862 if (atomic) {
2863 // Handle all atomics
2864 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
2865 } else {
John Kessenich426394d2015-07-23 10:22:48 -06002866 // Pass through to generic operations.
2867 switch (glslangOperands.size()) {
2868 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002869 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002870 break;
2871 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002872 {
2873 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002874 TranslateNoContractionDecoration(node->getType().getQualifier()),
2875 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002876 result = createUnaryOperation(
2877 node->getOp(), decorations,
2878 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002879 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002880 }
John Kessenich426394d2015-07-23 10:22:48 -06002881 break;
2882 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002883 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002884 break;
2885 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002886 if (invertedType)
2887 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002888 }
2889
2890 if (noReturnValue)
2891 return false;
2892
2893 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002894 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002895 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002896 } else {
2897 builder.clearAccessChain();
2898 builder.setAccessChainRValue(result);
2899 return false;
2900 }
2901}
2902
John Kessenich433e9ff2017-01-26 20:31:11 -07002903// This path handles both if-then-else and ?:
2904// The if-then-else has a node type of void, while
2905// ?: has either a void or a non-void node type
2906//
2907// Leaving the result, when not void:
2908// GLSL only has r-values as the result of a :?, but
2909// if we have an l-value, that can be more efficient if it will
2910// become the base of a complex r-value expression, because the
2911// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002912bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2913{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002914 // see if OpSelect can handle it
2915 const auto isOpSelectable = [&]() {
2916 if (node->getBasicType() == glslang::EbtVoid)
2917 return false;
2918 // OpSelect can do all other types starting with SPV 1.4
2919 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2920 // pre-1.4, only scalars and vectors can be handled
2921 if ((!node->getType().isScalar() && !node->getType().isVector()))
2922 return false;
2923 }
2924 return true;
2925 };
2926
John Kessenich4bee5312018-02-20 21:29:05 -07002927 // See if it simple and safe, or required, to execute both sides.
2928 // Crucially, side effects must be either semantically required or avoided,
2929 // and there are performance trade-offs.
2930 // Return true if required or a good idea (and safe) to execute both sides,
2931 // false otherwise.
2932 const auto bothSidesPolicy = [&]() -> bool {
2933 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002934 if (node->getTrueBlock() == nullptr ||
2935 node->getFalseBlock() == nullptr)
2936 return false;
2937
John Kessenich4bee5312018-02-20 21:29:05 -07002938 // required? (unless we write additional code to look for side effects
2939 // and make performance trade-offs if none are present)
2940 if (!node->getShortCircuit())
2941 return true;
2942
2943 // if not required to execute both, decide based on performance/practicality...
2944
John Kessenich0c1e71a2019-01-10 18:23:06 +07002945 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002946 return false;
2947
John Kessenich433e9ff2017-01-26 20:31:11 -07002948 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2949 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2950
2951 // return true if a single operand to ? : is okay for OpSelect
2952 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002953 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002954 };
2955
2956 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2957 operandOkay(node->getFalseBlock()->getAsTyped());
2958 };
2959
John Kessenich4bee5312018-02-20 21:29:05 -07002960 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2961 // emit the condition before doing anything with selection
2962 node->getCondition()->traverse(this);
2963 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2964
2965 // Find a way of executing both sides and selecting the right result.
2966 const auto executeBothSides = [&]() -> void {
2967 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002968 node->getTrueBlock()->traverse(this);
2969 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2970 node->getFalseBlock()->traverse(this);
2971 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2972
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002973 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002974
John Kessenich4bee5312018-02-20 21:29:05 -07002975 // done if void
2976 if (node->getBasicType() == glslang::EbtVoid)
2977 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002978
John Kessenich4bee5312018-02-20 21:29:05 -07002979 // emit code to select between trueValue and falseValue
2980
2981 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002982 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002983 // Emit OpSelect for this selection.
2984
2985 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002986 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2987 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002988 condition = builder.smearScalar(spv::NoPrecision, condition,
2989 builder.makeVectorType(builder.makeBoolType(),
2990 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002991 }
John Kessenich4bee5312018-02-20 21:29:05 -07002992
2993 // OpSelect
2994 result = builder.createTriOp(spv::OpSelect,
2995 convertGlslangToSpvType(node->getType()), condition,
2996 trueValue, falseValue);
2997
2998 builder.clearAccessChain();
2999 builder.setAccessChainRValue(result);
3000 } else {
3001 // We need control flow to select the result.
3002 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3003 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3004
3005 // Selection control:
3006 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3007
3008 // make an "if" based on the value created by the condition
3009 spv::Builder::If ifBuilder(condition, control, builder);
3010
3011 // emit the "then" statement
3012 builder.createStore(trueValue, result);
3013 ifBuilder.makeBeginElse();
3014 // emit the "else" statement
3015 builder.createStore(falseValue, result);
3016
3017 // finish off the control flow
3018 ifBuilder.makeEndIf();
3019
3020 builder.clearAccessChain();
3021 builder.setAccessChainLValue(result);
3022 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003023 };
3024
John Kessenich4bee5312018-02-20 21:29:05 -07003025 // Execute the one side needed, as per the condition
3026 const auto executeOneSide = [&]() {
3027 // Always emit control flow.
3028 if (node->getBasicType() != glslang::EbtVoid)
3029 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003030
John Kessenich4bee5312018-02-20 21:29:05 -07003031 // Selection control:
3032 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3033
3034 // make an "if" based on the value created by the condition
3035 spv::Builder::If ifBuilder(condition, control, builder);
3036
3037 // emit the "then" statement
3038 if (node->getTrueBlock() != nullptr) {
3039 node->getTrueBlock()->traverse(this);
3040 if (result != spv::NoResult)
3041 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3042 }
3043
3044 if (node->getFalseBlock() != nullptr) {
3045 ifBuilder.makeBeginElse();
3046 // emit the "else" statement
3047 node->getFalseBlock()->traverse(this);
3048 if (result != spv::NoResult)
3049 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3050 }
3051
3052 // finish off the control flow
3053 ifBuilder.makeEndIf();
3054
3055 if (result != spv::NoResult) {
3056 builder.clearAccessChain();
3057 builder.setAccessChainLValue(result);
3058 }
3059 };
3060
3061 // Try for OpSelect (or a requirement to execute both sides)
3062 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003063 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3064 if (node->getType().getQualifier().isSpecConstant())
3065 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003066 executeBothSides();
3067 } else
3068 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003069
3070 return false;
3071}
3072
3073bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3074{
3075 // emit and get the condition before doing anything with switch
3076 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003077 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003078
Rex Xu57e65922017-07-04 23:23:40 +08003079 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003080 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003081
John Kessenich140f3df2015-06-26 16:58:36 -06003082 // browse the children to sort out code segments
3083 int defaultSegment = -1;
3084 std::vector<TIntermNode*> codeSegments;
3085 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3086 std::vector<int> caseValues;
3087 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3088 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3089 TIntermNode* child = *c;
3090 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003091 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003092 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003093 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003094 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3095 } else
3096 codeSegments.push_back(child);
3097 }
3098
qining25262b32016-05-06 17:25:16 -04003099 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003100 // statements between the last case and the end of the switch statement
3101 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3102 (int)codeSegments.size() == defaultSegment)
3103 codeSegments.push_back(nullptr);
3104
3105 // make the switch statement
3106 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003107 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003108
3109 // emit all the code in the segments
3110 breakForLoop.push(false);
3111 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3112 builder.nextSwitchSegment(segmentBlocks, s);
3113 if (codeSegments[s])
3114 codeSegments[s]->traverse(this);
3115 else
3116 builder.addSwitchBreak();
3117 }
3118 breakForLoop.pop();
3119
3120 builder.endSwitch(segmentBlocks);
3121
3122 return false;
3123}
3124
3125void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3126{
3127 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003128 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003129
3130 builder.clearAccessChain();
3131 builder.setAccessChainRValue(constant);
3132}
3133
3134bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3135{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003136 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003137 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003138
3139 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003140 std::vector<unsigned int> operands;
3141 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003142
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003143 // Spec requires back edges to target header blocks, and every header block
3144 // must dominate its merge block. Make a header block first to ensure these
3145 // conditions are met. By definition, it will contain OpLoopMerge, followed
3146 // by a block-ending branch. But we don't want to put any other body/test
3147 // instructions in it, since the body/test may have arbitrary instructions,
3148 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003149 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003150 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003151 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003152 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003153 spv::Block& test = builder.makeNewBlock();
3154 builder.createBranch(&test);
3155
3156 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003157 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003158 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003159 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3160
3161 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003162 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003163 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003164 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003165 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003166 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003167
3168 builder.setBuildPoint(&blocks.continue_target);
3169 if (node->getTerminal())
3170 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003171 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003172 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003173 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003174 builder.createBranch(&blocks.body);
3175
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003176 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003177 builder.setBuildPoint(&blocks.body);
3178 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003179 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003180 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003181 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003182
3183 builder.setBuildPoint(&blocks.continue_target);
3184 if (node->getTerminal())
3185 node->getTerminal()->traverse(this);
3186 if (node->getTest()) {
3187 node->getTest()->traverse(this);
3188 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003189 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003190 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003191 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003192 // TODO: unless there was a break/return/discard instruction
3193 // somewhere in the body, this is an infinite loop, so we should
3194 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003195 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003196 }
John Kessenich140f3df2015-06-26 16:58:36 -06003197 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003198 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003199 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003200 return false;
3201}
3202
3203bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3204{
3205 if (node->getExpression())
3206 node->getExpression()->traverse(this);
3207
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003208 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003209
John Kessenich140f3df2015-06-26 16:58:36 -06003210 switch (node->getFlowOp()) {
3211 case glslang::EOpKill:
3212 builder.makeDiscard();
3213 break;
3214 case glslang::EOpBreak:
3215 if (breakForLoop.top())
3216 builder.createLoopExit();
3217 else
3218 builder.addSwitchBreak();
3219 break;
3220 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003221 builder.createLoopContinue();
3222 break;
3223 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003224 if (node->getExpression()) {
3225 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3226 spv::Id returnId = accessChainLoad(glslangReturnType);
3227 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3228 builder.clearAccessChain();
3229 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3230 builder.setAccessChainLValue(copyId);
3231 multiTypeStore(glslangReturnType, returnId);
3232 returnId = builder.createLoad(copyId);
3233 }
3234 builder.makeReturn(false, returnId);
3235 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003236 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003237
3238 builder.clearAccessChain();
3239 break;
3240
John Kessenichb9197c82019-08-11 07:41:45 -06003241#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003242 case glslang::EOpDemote:
3243 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3244 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3245 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3246 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003247#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003248
John Kessenich140f3df2015-06-26 16:58:36 -06003249 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003250 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003251 break;
3252 }
3253
3254 return false;
3255}
3256
John Kessenich9c14f772019-06-17 08:38:35 -06003257spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003258{
qining25262b32016-05-06 17:25:16 -04003259 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003260 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003261 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003262 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003263 spv::Id result = createSpvConstant(*node);
3264 if (result != spv::NoResult)
3265 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003266 }
3267
3268 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003269 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003270 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3271 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003272
John Kessenichb9197c82019-08-11 07:41:45 -06003273 const bool contains16BitType = node->getType().contains16BitFloat() ||
3274 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003275 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003276 switch (storageClass) {
3277 case spv::StorageClassInput:
3278 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003279 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003280 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003281 break;
John Kessenich18310872018-05-14 22:08:53 -06003282 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003283 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003284 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3285 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003286 else
3287 builder.addCapability(spv::CapabilityStorageUniform16);
3288 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003289#ifndef GLSLANG_WEB
3290 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003291 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003292 builder.addCapability(spv::CapabilityStoragePushConstant16);
3293 break;
John Kessenich18310872018-05-14 22:08:53 -06003294 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003295 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003296 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003297 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3298 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003299#endif
John Kessenich18310872018-05-14 22:08:53 -06003300 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003301 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003302 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003303 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003304 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003305 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003306 }
3307 }
Rex Xuf89ad982017-04-07 23:22:33 +08003308
John Kessenichb9197c82019-08-11 07:41:45 -06003309 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003310 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003311 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003312 builder.addCapability(spv::CapabilityStoragePushConstant8);
3313 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003314 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003315 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003316 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003317 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003318 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003319 } else {
3320 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003321 }
3322 }
3323
John Kessenich140f3df2015-06-26 16:58:36 -06003324 const char* name = node->getName().c_str();
3325 if (glslang::IsAnonymous(name))
3326 name = "";
3327
3328 return builder.createVariable(storageClass, spvType, name);
3329}
3330
3331// Return type Id of the sampled type.
3332spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3333{
3334 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003335 case glslang::EbtInt: return builder.makeIntType(32);
3336 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003337 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003338#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003339 case glslang::EbtFloat16:
3340 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3341 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3342 return builder.makeFloatType(16);
3343#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003344 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003346 return builder.makeFloatType(32);
3347 }
3348}
3349
John Kessenich8c8505c2016-07-26 12:50:38 -06003350// If node is a swizzle operation, return the type that should be used if
3351// the swizzle base is first consumed by another operation, before the swizzle
3352// is applied.
3353spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3354{
John Kessenichecba76f2017-01-06 00:34:48 -07003355 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003356 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3357 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3358 else
3359 return spv::NoType;
3360}
3361
3362// When inverting a swizzle with a parent op, this function
3363// will apply the swizzle operation to a completed parent operation.
3364spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3365{
3366 std::vector<unsigned> swizzle;
3367 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3368 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3369}
3370
John Kessenich8c8505c2016-07-26 12:50:38 -06003371// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3372void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3373{
3374 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3375 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3376 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3377}
3378
John Kessenich3ac051e2015-12-20 11:29:16 -07003379// Convert from a glslang type to an SPV type, by calling into a
3380// recursive version of this function. This establishes the inherited
3381// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003382spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003383{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003384 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003385}
3386
3387// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003388// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003389// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003390spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003391 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3392 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003393{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003394 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003395
3396 switch (type.getBasicType()) {
3397 case glslang::EbtVoid:
3398 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003399 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003400 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003401 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003402 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3403 // a 32-bit int where non-0 means true.
3404 if (explicitLayout != glslang::ElpNone)
3405 spvType = builder.makeUintType(32);
3406 else
3407 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003408 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003409 case glslang::EbtInt:
3410 spvType = builder.makeIntType(32);
3411 break;
3412 case glslang::EbtUint:
3413 spvType = builder.makeUintType(32);
3414 break;
3415 case glslang::EbtFloat:
3416 spvType = builder.makeFloatType(32);
3417 break;
3418#ifndef GLSLANG_WEB
3419 case glslang::EbtDouble:
3420 spvType = builder.makeFloatType(64);
3421 break;
3422 case glslang::EbtFloat16:
3423 spvType = builder.makeFloatType(16);
3424 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003425 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003426 spvType = builder.makeIntType(8);
3427 break;
3428 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003429 spvType = builder.makeUintType(8);
3430 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003431 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003432 spvType = builder.makeIntType(16);
3433 break;
3434 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003435 spvType = builder.makeUintType(16);
3436 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003437 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003438 spvType = builder.makeIntType(64);
3439 break;
3440 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003441 spvType = builder.makeUintType(64);
3442 break;
John Kessenich426394d2015-07-23 10:22:48 -06003443 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003444 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003445 spvType = builder.makeUintType(32);
3446 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003447 case glslang::EbtAccStructNV:
3448 spvType = builder.makeAccelerationStructureNVType();
3449 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003450 case glslang::EbtReference:
3451 {
3452 // Make the forward pointer, then recurse to convert the structure type, then
3453 // patch up the forward pointer with a real pointer type.
3454 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3455 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3456 forwardPointers[type.getReferentType()] = forwardId;
3457 }
3458 spvType = forwardPointers[type.getReferentType()];
3459 if (!forwardReferenceOnly) {
3460 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3461 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3462 forwardPointers[type.getReferentType()],
3463 referentType);
3464 }
3465 }
3466 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003467#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003468 case glslang::EbtSampler:
3469 {
3470 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003471 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003472 spvType = builder.makeSamplerType();
3473 } else {
3474 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003475 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3476 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3477 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3478 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003479 // already has both image and sampler, make the combined type
3480 spvType = builder.makeSampledImageType(spvType);
3481 }
John Kessenich55e7d112015-11-15 21:33:39 -07003482 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003483 }
John Kessenich140f3df2015-06-26 16:58:36 -06003484 break;
3485 case glslang::EbtStruct:
3486 case glslang::EbtBlock:
3487 {
3488 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003489 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003490
3491 // Try to share structs for different layouts, but not yet for other
3492 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003493 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003494 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003495 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003496 break;
3497
3498 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003499 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003500 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003501 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003502 }
3503 break;
3504 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003505 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003506 break;
3507 }
3508
3509 if (type.isMatrix())
3510 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3511 else {
3512 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3513 if (type.getVectorSize() > 1)
3514 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3515 }
3516
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003517 if (type.isCoopMat()) {
3518 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3519 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3520 if (type.getBasicType() == glslang::EbtFloat16)
3521 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003522 if (type.getBasicType() == glslang::EbtUint8 ||
3523 type.getBasicType() == glslang::EbtInt8) {
3524 builder.addCapability(spv::CapabilityInt8);
3525 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003526
3527 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3528 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3529 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3530
3531 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3532 }
3533
John Kessenich140f3df2015-06-26 16:58:36 -06003534 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003535 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3536
John Kessenichc9a80832015-09-12 12:17:44 -06003537 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003538 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003539 // We need to decorate array strides for types needing explicit layout, except blocks.
3540 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003541 // Use a dummy glslang type for querying internal strides of
3542 // arrays of arrays, but using just a one-dimensional array.
3543 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003544 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3545 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003546
3547 // Will compute the higher-order strides here, rather than making a whole
3548 // pile of types and doing repetitive recursion on their contents.
3549 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3550 }
John Kessenichf8842e52016-01-04 19:22:56 -07003551
3552 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003553 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003554 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003555 if (stride > 0)
3556 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003557 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003558 }
3559 } else {
3560 // single-dimensional array, and don't yet have stride
3561
John Kessenichf8842e52016-01-04 19:22:56 -07003562 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003563 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3564 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003565 }
John Kessenich31ed4832015-09-09 17:51:38 -06003566
John Kessenichead86222018-03-28 18:01:20 -06003567 // Do the outer dimension, which might not be known for a runtime-sized array.
3568 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3569 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003570 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003571 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003572#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003573 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003574 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003575 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3576 }
John Kessenichb9197c82019-08-11 07:41:45 -06003577#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003578 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003579 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003580 if (stride > 0)
3581 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003582 }
3583
3584 return spvType;
3585}
3586
John Kessenich0e737842017-03-24 18:38:16 -06003587// TODO: this functionality should exist at a higher level, in creating the AST
3588//
3589// Identify interface members that don't have their required extension turned on.
3590//
3591bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3592{
John Kessenicha28f7a72019-08-06 07:00:58 -06003593#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003594 auto& extensions = glslangIntermediate->getRequestedExtensions();
3595
Rex Xubcf291a2017-03-29 23:01:36 +08003596 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3597 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3598 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003599 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3600 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3601 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003602
3603 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3604 if (member.getFieldName() == "gl_ViewportMask" &&
3605 extensions.find("GL_NV_viewport_array2") == extensions.end())
3606 return true;
3607 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3608 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3609 return true;
3610 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3611 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3612 return true;
3613 }
3614#endif
John Kessenich0e737842017-03-24 18:38:16 -06003615
3616 return false;
3617};
3618
John Kessenich6090df02016-06-30 21:18:02 -06003619// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3620// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3621// Mutually recursive with convertGlslangToSpvType().
3622spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3623 const glslang::TTypeList* glslangMembers,
3624 glslang::TLayoutPacking explicitLayout,
3625 const glslang::TQualifier& qualifier)
3626{
3627 // Create a vector of struct types for SPIR-V to consume
3628 std::vector<spv::Id> spvMembers;
3629 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003630 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003631 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3632 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3633 if (glslangMember.hiddenMember()) {
3634 ++memberDelta;
3635 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003636 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003637 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003638 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003639 if (filterMember(glslangMember)) {
3640 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003641 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003642 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003643 }
Roy05a5b532020-01-03 16:21:34 +08003644 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003645 }
John Kessenich6090df02016-06-30 21:18:02 -06003646 // modify just this child's view of the qualifier
3647 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3648 InheritQualifiers(memberQualifier, qualifier);
3649
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003650 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003651 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003652 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003653
3654 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003655 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3656 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003657
3658 // Make forward pointers for any pointer members, and create a list of members to
3659 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003660 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003661 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3662 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3663 }
3664 spvMembers.push_back(
3665 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3666 } else {
3667 spvMembers.push_back(
3668 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3669 }
John Kessenich6090df02016-06-30 21:18:02 -06003670 }
3671 }
3672
3673 // Make the SPIR-V type
3674 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003675 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003676 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3677
3678 // Decorate it
3679 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3680
John Kessenichd72f4882019-01-16 14:55:37 +07003681 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003682 auto it = deferredForwardPointers[i];
3683 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3684 }
3685
John Kessenich6090df02016-06-30 21:18:02 -06003686 return spvType;
3687}
3688
3689void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3690 const glslang::TTypeList* glslangMembers,
3691 glslang::TLayoutPacking explicitLayout,
3692 const glslang::TQualifier& qualifier,
3693 spv::Id spvType)
3694{
3695 // Name and decorate the non-hidden members
3696 int offset = -1;
3697 int locationOffset = 0; // for use within the members of this struct
3698 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3699 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3700 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003701 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003702 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003703 if (filterMember(glslangMember))
3704 continue;
3705 }
John Kessenich6090df02016-06-30 21:18:02 -06003706
3707 // modify just this child's view of the qualifier
3708 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3709 InheritQualifiers(memberQualifier, qualifier);
3710
3711 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003712 if (member < 0)
3713 continue;
3714
3715 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3716 builder.addMemberDecoration(spvType, member,
3717 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3718 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3719 // Add interpolation and auxiliary storage decorations only to
3720 // top-level members of Input and Output storage classes
3721 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3722 type.getQualifier().storage == glslang::EvqVaryingOut) {
3723 if (type.getBasicType() == glslang::EbtBlock ||
3724 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3725 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3726 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003727#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003728 addMeshNVDecoration(spvType, member, memberQualifier);
3729#endif
John Kessenich6090df02016-06-30 21:18:02 -06003730 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003731 }
3732 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003733
John Kessenichb9197c82019-08-11 07:41:45 -06003734#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003735 if (type.getBasicType() == glslang::EbtBlock &&
3736 qualifier.storage == glslang::EvqBuffer) {
3737 // Add memory decorations only to top-level members of shader storage block
3738 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003739 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003740 for (unsigned int i = 0; i < memory.size(); ++i)
3741 builder.addMemberDecoration(spvType, member, memory[i]);
3742 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003743
John Kessenichb9197c82019-08-11 07:41:45 -06003744#endif
John Kessenich6090df02016-06-30 21:18:02 -06003745
John Kessenich5d610ee2018-03-07 18:05:55 -07003746 // Location assignment was already completed correctly by the front end,
3747 // just track whether a member needs to be decorated.
3748 // Ignore member locations if the container is an array, as that's
3749 // ill-specified and decisions have been made to not allow this.
3750 if (! type.isArray() && memberQualifier.hasLocation())
3751 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003752
John Kessenich5d610ee2018-03-07 18:05:55 -07003753 if (qualifier.hasLocation()) // track for upcoming inheritance
3754 locationOffset += glslangIntermediate->computeTypeLocationSize(
3755 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003756
John Kessenich5d610ee2018-03-07 18:05:55 -07003757 // component, XFB, others
3758 if (glslangMember.getQualifier().hasComponent())
3759 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3760 glslangMember.getQualifier().layoutComponent);
3761 if (glslangMember.getQualifier().hasXfbOffset())
3762 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3763 glslangMember.getQualifier().layoutXfbOffset);
3764 else if (explicitLayout != glslang::ElpNone) {
3765 // figure out what to do with offset, which is accumulating
3766 int nextOffset;
3767 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3768 if (offset >= 0)
3769 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3770 offset = nextOffset;
3771 }
John Kessenich6090df02016-06-30 21:18:02 -06003772
John Kessenich5d610ee2018-03-07 18:05:55 -07003773 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3774 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3775 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003776
John Kessenich5d610ee2018-03-07 18:05:55 -07003777 // built-in variable decorations
3778 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3779 if (builtIn != spv::BuiltInMax)
3780 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003781
John Kessenichb9197c82019-08-11 07:41:45 -06003782#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003783 // nonuniform
3784 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3785
John Kessenichead86222018-03-28 18:01:20 -06003786 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3787 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3788 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3789 memberQualifier.semanticName);
3790 }
3791
John Kessenich5d610ee2018-03-07 18:05:55 -07003792 if (builtIn == spv::BuiltInLayer) {
3793 // SPV_NV_viewport_array2 extension
3794 if (glslangMember.getQualifier().layoutViewportRelative){
3795 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3796 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3797 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003798 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003799 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3800 builder.addMemberDecoration(spvType, member,
3801 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3802 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3803 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3804 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003805 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003806 }
3807 if (glslangMember.getQualifier().layoutPassthrough) {
3808 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3809 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3810 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3811 }
chaoc771d89f2017-01-13 01:10:53 -08003812#endif
John Kessenich6090df02016-06-30 21:18:02 -06003813 }
3814
3815 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003816 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3817 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003818}
3819
John Kessenich6c292d32016-02-15 20:58:50 -07003820// Turn the expression forming the array size into an id.
3821// This is not quite trivial, because of specialization constants.
3822// Sometimes, a raw constant is turned into an Id, and sometimes
3823// a specialization constant expression is.
3824spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3825{
3826 // First, see if this is sized with a node, meaning a specialization constant:
3827 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3828 if (specNode != nullptr) {
3829 builder.clearAccessChain();
3830 specNode->traverse(this);
3831 return accessChainLoad(specNode->getAsTyped()->getType());
3832 }
qining25262b32016-05-06 17:25:16 -04003833
John Kessenich6c292d32016-02-15 20:58:50 -07003834 // Otherwise, need a compile-time (front end) size, get it:
3835 int size = arraySizes.getDimSize(dim);
3836 assert(size > 0);
3837 return builder.makeUintConstant(size);
3838}
3839
John Kessenich103bef92016-02-08 21:38:15 -07003840// Wrap the builder's accessChainLoad to:
3841// - localize handling of RelaxedPrecision
3842// - use the SPIR-V inferred type instead of another conversion of the glslang type
3843// (avoids unnecessary work and possible type punning for structures)
3844// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003845spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3846{
John Kessenich103bef92016-02-08 21:38:15 -07003847 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003848
3849 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3850 coherentFlags |= TranslateCoherent(type);
3851
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003852 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003853 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003854
John Kessenich5611c6d2018-04-05 11:25:02 -06003855 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003856 TranslateNonUniformDecoration(type.getQualifier()),
3857 nominalTypeId,
3858 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003859 TranslateMemoryScope(coherentFlags),
3860 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003861
3862 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003863 if (type.getBasicType() == glslang::EbtBool) {
3864 if (builder.isScalarType(nominalTypeId)) {
3865 // Conversion for bool
3866 spv::Id boolType = builder.makeBoolType();
3867 if (nominalTypeId != boolType)
3868 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3869 } else if (builder.isVectorType(nominalTypeId)) {
3870 // Conversion for bvec
3871 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3872 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3873 if (nominalTypeId != bvecType)
3874 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3875 }
3876 }
John Kessenich103bef92016-02-08 21:38:15 -07003877
3878 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003879}
3880
Rex Xu27253232016-02-23 17:51:09 +08003881// Wrap the builder's accessChainStore to:
3882// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003883//
3884// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003885void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3886{
3887 // Need to convert to abstract types when necessary
3888 if (type.getBasicType() == glslang::EbtBool) {
3889 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3890
3891 if (builder.isScalarType(nominalTypeId)) {
3892 // Conversion for bool
3893 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003894 if (nominalTypeId != boolType) {
3895 // keep these outside arguments, for determinant order-of-evaluation
3896 spv::Id one = builder.makeUintConstant(1);
3897 spv::Id zero = builder.makeUintConstant(0);
3898 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3899 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003900 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003901 } else if (builder.isVectorType(nominalTypeId)) {
3902 // Conversion for bvec
3903 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3904 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003905 if (nominalTypeId != bvecType) {
3906 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003907 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3908 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3909 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003910 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003911 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3912 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003913 }
3914 }
3915
Jeff Bolz36831c92018-09-05 10:11:41 -05003916 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3917 coherentFlags |= TranslateCoherent(type);
3918
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003919 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003920 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003921
Jeff Bolz36831c92018-09-05 10:11:41 -05003922 builder.accessChainStore(rvalue,
3923 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003924 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003925}
3926
John Kessenich4bf71552016-09-02 11:20:21 -06003927// For storing when types match at the glslang level, but not might match at the
3928// SPIR-V level.
3929//
3930// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003931// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003932// as in a member-decorated way.
3933//
3934// NOTE: This function can handle any store request; if it's not special it
3935// simplifies to a simple OpStore.
3936//
3937// Implicitly uses the existing builder.accessChain as the storage target.
3938void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3939{
John Kessenichb3e24e42016-09-11 12:33:43 -06003940 // we only do the complex path here if it's an aggregate
3941 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003942 accessChainStore(type, rValue);
3943 return;
3944 }
3945
John Kessenichb3e24e42016-09-11 12:33:43 -06003946 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003947 spv::Id rType = builder.getTypeId(rValue);
3948 spv::Id lValue = builder.accessChainGetLValue();
3949 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3950 if (lType == rType) {
3951 accessChainStore(type, rValue);
3952 return;
3953 }
3954
John Kessenichb3e24e42016-09-11 12:33:43 -06003955 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003956 // where the two types were the same type in GLSL. This requires member
3957 // by member copy, recursively.
3958
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003959 // SPIR-V 1.4 added an instruction to do help do this.
3960 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3961 // However, bool in uniform space is changed to int, so
3962 // OpCopyLogical does not work for that.
3963 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3964 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3965 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3966 if (lBool == rBool) {
3967 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3968 accessChainStore(type, logicalCopy);
3969 return;
3970 }
3971 }
3972
John Kessenichb3e24e42016-09-11 12:33:43 -06003973 // If an array, copy element by element.
3974 if (type.isArray()) {
3975 glslang::TType glslangElementType(type, 0);
3976 spv::Id elementRType = builder.getContainedTypeId(rType);
3977 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3978 // get the source member
3979 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003980
John Kessenichb3e24e42016-09-11 12:33:43 -06003981 // set up the target storage
3982 builder.clearAccessChain();
3983 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003984 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003985
John Kessenichb3e24e42016-09-11 12:33:43 -06003986 // store the member
3987 multiTypeStore(glslangElementType, elementRValue);
3988 }
3989 } else {
3990 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003991
John Kessenichb3e24e42016-09-11 12:33:43 -06003992 // loop over structure members
3993 const glslang::TTypeList& members = *type.getStruct();
3994 for (int m = 0; m < (int)members.size(); ++m) {
3995 const glslang::TType& glslangMemberType = *members[m].type;
3996
3997 // get the source member
3998 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3999 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4000
4001 // set up the target storage
4002 builder.clearAccessChain();
4003 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06004004 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004005
4006 // store the member
4007 multiTypeStore(glslangMemberType, memberRValue);
4008 }
John Kessenich4bf71552016-09-02 11:20:21 -06004009 }
4010}
4011
John Kessenichf85e8062015-12-19 13:57:10 -07004012// Decide whether or not this type should be
4013// decorated with offsets and strides, and if so
4014// whether std140 or std430 rules should be applied.
4015glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004016{
John Kessenichf85e8062015-12-19 13:57:10 -07004017 // has to be a block
4018 if (type.getBasicType() != glslang::EbtBlock)
4019 return glslang::ElpNone;
4020
Chao Chen3c366992018-09-19 11:41:59 -07004021 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004022 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004023 type.getQualifier().storage != glslang::EvqBuffer &&
4024 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004025 return glslang::ElpNone;
4026
4027 // return the layout to use
4028 switch (type.getQualifier().layoutPacking) {
4029 case glslang::ElpStd140:
4030 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004031 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004032 return type.getQualifier().layoutPacking;
4033 default:
4034 return glslang::ElpNone;
4035 }
John Kessenich31ed4832015-09-09 17:51:38 -06004036}
4037
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004038// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07004039int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004040{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004041 int size;
John Kessenich49987892015-12-29 17:11:44 -07004042 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004043 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004044
4045 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004046}
4047
John Kessenich49987892015-12-29 17:11:44 -07004048// Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004049// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07004050int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004051{
John Kessenich49987892015-12-29 17:11:44 -07004052 glslang::TType elementType;
4053 elementType.shallowCopy(matrixType);
4054 elementType.clearArraySizes();
4055
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004056 int size;
John Kessenich49987892015-12-29 17:11:44 -07004057 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004058 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004059
4060 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004061}
4062
John Kessenich5e4b1242015-08-06 22:53:06 -06004063// Given a member type of a struct, realign the current offset for it, and compute
4064// the next (not yet aligned) offset for the next member, which will get aligned
4065// on the next call.
4066// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4067// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4068// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06004069void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07004070 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004071{
4072 // this will get a positive value when deemed necessary
4073 nextOffset = -1;
4074
John Kessenich5e4b1242015-08-06 22:53:06 -06004075 // override anything in currentOffset with user-set offset
4076 if (memberType.getQualifier().hasOffset())
4077 currentOffset = memberType.getQualifier().layoutOffset;
4078
4079 // It could be that current linker usage in glslang updated all the layoutOffset,
4080 // in which case the following code does not matter. But, that's not quite right
4081 // once cross-compilation unit GLSL validation is done, as the original user
4082 // settings are needed in layoutOffset, and then the following will come into play.
4083
John Kessenichf85e8062015-12-19 13:57:10 -07004084 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004085 if (! memberType.getQualifier().hasOffset())
4086 currentOffset = -1;
4087
4088 return;
4089 }
4090
John Kessenichf85e8062015-12-19 13:57:10 -07004091 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004092 if (currentOffset < 0)
4093 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004094
John Kessenich5e4b1242015-08-06 22:53:06 -06004095 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4096 // but possibly not yet correctly aligned.
4097
4098 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004099 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004100 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004101
4102 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004103 // TODO: make this consistent in early phases of code:
4104 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4105 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4106 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004107 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004108 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004109 int dummySize;
4110 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4111 if (componentAlignment <= 4)
4112 memberAlignment = componentAlignment;
4113 }
4114
4115 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004116 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004117
4118 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004119 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004120 glslang::RoundToPow2(currentOffset, 16);
4121
John Kessenich5e4b1242015-08-06 22:53:06 -06004122 nextOffset = currentOffset + memberSize;
4123}
4124
David Netoa901ffe2016-06-08 14:11:40 +01004125void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004126{
David Netoa901ffe2016-06-08 14:11:40 +01004127 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4128 switch (glslangBuiltIn)
4129 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004130 case glslang::EbvPointSize:
4131#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004132 case glslang::EbvClipDistance:
4133 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004134 case glslang::EbvViewportMaskNV:
4135 case glslang::EbvSecondaryPositionNV:
4136 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004137 case glslang::EbvPositionPerViewNV:
4138 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004139 case glslang::EbvTaskCountNV:
4140 case glslang::EbvPrimitiveCountNV:
4141 case glslang::EbvPrimitiveIndicesNV:
4142 case glslang::EbvClipDistancePerViewNV:
4143 case glslang::EbvCullDistancePerViewNV:
4144 case glslang::EbvLayerPerViewNV:
4145 case glslang::EbvMeshViewCountNV:
4146 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004147#endif
David Netoa901ffe2016-06-08 14:11:40 +01004148 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4149 // Alternately, we could just call this for any glslang built-in, since the
4150 // capability already guards against duplicates.
4151 TranslateBuiltInDecoration(glslangBuiltIn, false);
4152 break;
4153 default:
4154 // Capabilities were already generated when the struct was declared.
4155 break;
4156 }
John Kessenichebb50532016-05-16 19:22:05 -06004157}
4158
John Kessenich6fccb3c2016-09-19 16:01:41 -06004159bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004160{
John Kessenicheee9d532016-09-19 18:09:30 -06004161 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004162}
4163
John Kessenichd41993d2017-09-10 15:21:05 -06004164// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004165// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4166// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004167bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004168{
John Kessenich6a14f782017-12-04 02:48:10 -07004169 assert(qualifier == glslang::EvqIn ||
4170 qualifier == glslang::EvqOut ||
4171 qualifier == glslang::EvqInOut ||
4172 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004173 return qualifier != glslang::EvqConstReadOnly;
4174}
4175
4176// Is parameter pass-by-original?
4177bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4178 bool implicitThisParam)
4179{
4180 if (implicitThisParam) // implicit this
4181 return true;
4182 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004183 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004184 return paramType.containsOpaque() || // sampler, etc.
4185 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4186}
4187
John Kessenich140f3df2015-06-26 16:58:36 -06004188// Make all the functions, skeletally, without actually visiting their bodies.
4189void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4190{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004191 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004192 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4193 if (paramPrecision != spv::NoPrecision)
4194 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004195 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004196 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004197 // Original and non-writable params pass the pointer directly and
4198 // use restrict/aliased, others are stored to a pointer in Function
4199 // memory and use RestrictPointer/AliasedPointer.
4200 if (originalParam(type.getQualifier().storage, type, false) ||
4201 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004202 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4203 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004204 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004205 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4206 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004207 }
4208 }
John Kessenichfad62972017-07-18 02:35:46 -06004209 };
4210
John Kessenich140f3df2015-06-26 16:58:36 -06004211 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4212 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004213 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004214 continue;
4215
4216 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004217 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004218 //
qining25262b32016-05-06 17:25:16 -04004219 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004220 // function. What it is an address of varies:
4221 //
John Kessenich4bf71552016-09-02 11:20:21 -06004222 // - "in" parameters not marked as "const" can be written to without modifying the calling
4223 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004224 //
4225 // - "const in" parameters can just be the r-value, as no writes need occur.
4226 //
John Kessenich4bf71552016-09-02 11:20:21 -06004227 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4228 // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
John Kessenich140f3df2015-06-26 16:58:36 -06004229
4230 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004231 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004232 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4233
John Kessenich155d3512019-08-08 23:29:20 -06004234#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004235 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4236 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004237#else
4238 bool implicitThis = false;
4239#endif
John Kessenich37789792017-03-21 23:56:40 -06004240
John Kessenichfad62972017-07-18 02:35:46 -06004241 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004242 for (int p = 0; p < (int)parameters.size(); ++p) {
4243 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4244 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004245 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004246 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004247 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004248 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4249 else
John Kessenich4bf71552016-09-02 11:20:21 -06004250 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004251 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004252 paramTypes.push_back(typeId);
4253 }
4254
4255 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004256 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4257 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004258 glslFunction->getName().c_str(), paramTypes,
4259 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004260 if (implicitThis)
4261 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004262
4263 // Track function to emit/call later
4264 functionMap[glslFunction->getName().c_str()] = function;
4265
4266 // Set the parameter id's
4267 for (int p = 0; p < (int)parameters.size(); ++p) {
4268 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4269 // give a name too
4270 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004271
4272 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004273 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004274 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004275 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004276 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004277 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004278 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004279 }
4280 }
4281}
4282
4283// Process all the initializers, while skipping the functions and link objects
4284void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4285{
4286 builder.setBuildPoint(shaderEntry->getLastBlock());
4287 for (int i = 0; i < (int)initializers.size(); ++i) {
4288 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4289 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4290
4291 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004292 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004293 initializer->traverse(this);
4294 }
4295 }
4296}
4297
4298// Process all the functions, while skipping initializers.
4299void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4300{
4301 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4302 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004303 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004304 node->traverse(this);
4305 }
4306}
4307
4308void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4309{
qining25262b32016-05-06 17:25:16 -04004310 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004311 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004312 currentFunction = functionMap[node->getName().c_str()];
4313 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004314 builder.setBuildPoint(functionBlock);
4315}
4316
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004317void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004318{
Rex Xufc618912015-09-09 16:42:49 +08004319 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004320
4321 glslang::TSampler sampler = {};
4322 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004323#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004324 bool f16ShadowCompare = false;
4325#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004326 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004327 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4328 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004329#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004330 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4331#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004332 }
4333
John Kessenich140f3df2015-06-26 16:58:36 -06004334 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4335 builder.clearAccessChain();
4336 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004337
John Kessenicha28f7a72019-08-06 07:00:58 -06004338#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004339 // Special case l-value operands
4340 bool lvalue = false;
4341 switch (node.getOp()) {
4342 case glslang::EOpImageAtomicAdd:
4343 case glslang::EOpImageAtomicMin:
4344 case glslang::EOpImageAtomicMax:
4345 case glslang::EOpImageAtomicAnd:
4346 case glslang::EOpImageAtomicOr:
4347 case glslang::EOpImageAtomicXor:
4348 case glslang::EOpImageAtomicExchange:
4349 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004350 case glslang::EOpImageAtomicLoad:
4351 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004352 if (i == 0)
4353 lvalue = true;
4354 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004355 case glslang::EOpSparseImageLoad:
4356 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4357 lvalue = true;
4358 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004359 case glslang::EOpSparseTexture:
4360 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4361 lvalue = true;
4362 break;
4363 case glslang::EOpSparseTextureClamp:
4364 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4365 lvalue = true;
4366 break;
4367 case glslang::EOpSparseTextureLod:
4368 case glslang::EOpSparseTextureOffset:
4369 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4370 lvalue = true;
4371 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004372 case glslang::EOpSparseTextureFetch:
4373 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4374 lvalue = true;
4375 break;
4376 case glslang::EOpSparseTextureFetchOffset:
4377 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4378 lvalue = true;
4379 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004380 case glslang::EOpSparseTextureLodOffset:
4381 case glslang::EOpSparseTextureGrad:
4382 case glslang::EOpSparseTextureOffsetClamp:
4383 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4384 lvalue = true;
4385 break;
4386 case glslang::EOpSparseTextureGradOffset:
4387 case glslang::EOpSparseTextureGradClamp:
4388 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4389 lvalue = true;
4390 break;
4391 case glslang::EOpSparseTextureGradOffsetClamp:
4392 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4393 lvalue = true;
4394 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004395 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004396 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4397 lvalue = true;
4398 break;
4399 case glslang::EOpSparseTextureGatherOffset:
4400 case glslang::EOpSparseTextureGatherOffsets:
4401 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4402 lvalue = true;
4403 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004404 case glslang::EOpSparseTextureGatherLod:
4405 if (i == 3)
4406 lvalue = true;
4407 break;
4408 case glslang::EOpSparseTextureGatherLodOffset:
4409 case glslang::EOpSparseTextureGatherLodOffsets:
4410 if (i == 4)
4411 lvalue = true;
4412 break;
Rex Xu129799a2017-07-05 17:23:28 +08004413 case glslang::EOpSparseImageLoadLod:
4414 if (i == 3)
4415 lvalue = true;
4416 break;
Chao Chen3a137962018-09-19 11:41:27 -07004417 case glslang::EOpImageSampleFootprintNV:
4418 if (i == 4)
4419 lvalue = true;
4420 break;
4421 case glslang::EOpImageSampleFootprintClampNV:
4422 case glslang::EOpImageSampleFootprintLodNV:
4423 if (i == 5)
4424 lvalue = true;
4425 break;
4426 case glslang::EOpImageSampleFootprintGradNV:
4427 if (i == 6)
4428 lvalue = true;
4429 break;
4430 case glslang::EOpImageSampleFootprintGradClampNV:
4431 if (i == 7)
4432 lvalue = true;
4433 break;
Rex Xufc618912015-09-09 16:42:49 +08004434 default:
4435 break;
4436 }
4437
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004438 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004439 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004440 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4441 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4442 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004443#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004444 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004445 }
4446}
4447
John Kessenichfc51d282015-08-19 13:34:18 -06004448void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004449{
John Kessenichfc51d282015-08-19 13:34:18 -06004450 builder.clearAccessChain();
4451 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004452 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004453}
John Kessenich140f3df2015-06-26 16:58:36 -06004454
John Kessenichfc51d282015-08-19 13:34:18 -06004455spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4456{
John Kesseniche485c7a2017-05-31 18:50:53 -06004457 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004458 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004459
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004460 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004461
John Kessenichfc51d282015-08-19 13:34:18 -06004462 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004463
John Kessenichf43c7392019-03-31 10:51:57 -06004464 const glslang::TType &imageType = node->getAsAggregate()
4465 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4466 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004467 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004468#ifdef GLSLANG_WEB
4469 const bool f16ShadowCompare = false;
4470#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004471 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004472 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4473 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004474#endif
4475
John Kessenichf43c7392019-03-31 10:51:57 -06004476 const auto signExtensionMask = [&]() {
4477 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4478 if (sampler.type == glslang::EbtUint)
4479 return spv::ImageOperandsZeroExtendMask;
4480 else if (sampler.type == glslang::EbtInt)
4481 return spv::ImageOperandsSignExtendMask;
4482 }
4483 return spv::ImageOperandsMaskNone;
4484 };
4485
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004486 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4487
John Kessenichfc51d282015-08-19 13:34:18 -06004488 std::vector<spv::Id> arguments;
4489 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004490 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004491 else
4492 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004493 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004494
4495 spv::Builder::TextureParameters params = { };
4496 params.sampler = arguments[0];
4497
Rex Xu04db3f52015-09-16 11:44:02 +08004498 glslang::TCrackedTextureOp cracked;
4499 node->crackTexture(sampler, cracked);
4500
amhagan05506bb2017-06-13 16:53:02 -04004501 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004502
John Kessenichfc51d282015-08-19 13:34:18 -06004503 // Check for queries
4504 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004505 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4506 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004507 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004508
John Kessenichfc51d282015-08-19 13:34:18 -06004509 switch (node->getOp()) {
4510 case glslang::EOpImageQuerySize:
4511 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004512 if (arguments.size() > 1) {
4513 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004514 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004515 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004516 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004517#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004518 case glslang::EOpImageQuerySamples:
4519 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004520 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004521 case glslang::EOpTextureQueryLod:
4522 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004523 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004524 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004525 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004526 case glslang::EOpSparseTexelsResident:
4527 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004528#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004529 default:
4530 assert(0);
4531 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004532 }
John Kessenich140f3df2015-06-26 16:58:36 -06004533 }
4534
LoopDawg4425f242018-02-18 11:40:01 -07004535 int components = node->getType().getVectorSize();
4536
4537 if (node->getOp() == glslang::EOpTextureFetch) {
4538 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4539 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4540 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4541 // here around e.g. which ones return scalars or other types.
4542 components = 4;
4543 }
4544
4545 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4546
4547 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4548
Rex Xufc618912015-09-09 16:42:49 +08004549 // Check for image functions other than queries
4550 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004551 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004552 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004553 spv::IdImmediate image = { true, *(opIt++) };
4554 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004555
4556 // Handle subpass operations
4557 // TODO: GLSL should change to have the "MS" only on the type rather than the
4558 // built-in function.
4559 if (cracked.subpass) {
4560 // add on the (0,0) coordinate
4561 spv::Id zero = builder.makeIntConstant(0);
4562 std::vector<spv::Id> comps;
4563 comps.push_back(zero);
4564 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004565 spv::IdImmediate coord = { true,
4566 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4567 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004568 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4569 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004570 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004571 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4572 }
4573 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004574 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004575 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004576 spv::IdImmediate imageOperand = { true, *(opIt++) };
4577 operands.push_back(imageOperand);
4578 }
John Kessenich6c292d32016-02-15 20:58:50 -07004579 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004580 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4581 builder.setPrecision(result, precision);
4582 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004583 }
4584
John Kessenich149afc32018-08-14 13:31:43 -06004585 spv::IdImmediate coord = { true, *(opIt++) };
4586 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004587 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004588 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004589 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004590 mask = mask | spv::ImageOperandsSampleMask;
4591 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004592 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004593 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4594 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004595 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004596 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004597 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4598 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004599 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004600 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004601 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4602 operands.push_back(imageOperands);
4603 }
4604 if (mask & spv::ImageOperandsSampleMask) {
4605 spv::IdImmediate imageOperand = { true, *opIt++ };
4606 operands.push_back(imageOperand);
4607 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004608 if (mask & spv::ImageOperandsLodMask) {
4609 spv::IdImmediate imageOperand = { true, *opIt++ };
4610 operands.push_back(imageOperand);
4611 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004612 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004613 spv::IdImmediate imageOperand = { true,
4614 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004615 operands.push_back(imageOperand);
4616 }
4617
John Kessenich149afc32018-08-14 13:31:43 -06004618 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004619 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004620
John Kessenich149afc32018-08-14 13:31:43 -06004621 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004622 builder.setPrecision(result[0], precision);
4623
4624 // If needed, add a conversion constructor to the proper size.
4625 if (components != node->getType().getVectorSize())
4626 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4627
4628 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004629 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004630
Jeff Bolz36831c92018-09-05 10:11:41 -05004631 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004632 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004633 spv::IdImmediate texel = { true, *(opIt + 1) };
4634 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004635 } else {
4636 spv::IdImmediate texel = { true, *opIt };
4637 operands.push_back(texel);
4638 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004639
4640 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004641 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004642 mask = mask | spv::ImageOperandsSampleMask;
4643 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004644 if (cracked.lod) {
4645 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4646 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4647 mask = mask | spv::ImageOperandsLodMask;
4648 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004649 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4650 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004651 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004652 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004653 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4654 operands.push_back(imageOperands);
4655 }
4656 if (mask & spv::ImageOperandsSampleMask) {
4657 spv::IdImmediate imageOperand = { true, *opIt++ };
4658 operands.push_back(imageOperand);
4659 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004660 if (mask & spv::ImageOperandsLodMask) {
4661 spv::IdImmediate imageOperand = { true, *opIt++ };
4662 operands.push_back(imageOperand);
4663 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004664 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004665 spv::IdImmediate imageOperand = { true,
4666 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004667 operands.push_back(imageOperand);
4668 }
4669
John Kessenich56bab042015-09-16 10:54:31 -06004670 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004671 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004672 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004673 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004674 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4675 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004676 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004677 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004678 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4679
Jeff Bolz36831c92018-09-05 10:11:41 -05004680 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004681 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004682 mask = mask | spv::ImageOperandsSampleMask;
4683 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004684 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004685 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4686 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4687
Jeff Bolz36831c92018-09-05 10:11:41 -05004688 mask = mask | spv::ImageOperandsLodMask;
4689 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004690 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4691 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004692 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004693 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004694 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004695 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004696 }
4697 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004698 spv::IdImmediate imageOperand = { true, *opIt++ };
4699 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004700 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004701 if (mask & spv::ImageOperandsLodMask) {
4702 spv::IdImmediate imageOperand = { true, *opIt++ };
4703 operands.push_back(imageOperand);
4704 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004705 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4706 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4707 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004708 }
4709
4710 // Create the return type that was a special structure
4711 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004712 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004713 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4714 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4715
4716 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4717
4718 // Decode the return type
4719 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4720 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004721 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004722 // Process image atomic operations
4723
4724 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4725 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004726 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004727 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004728 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004729
Jeff Bolz36831c92018-09-05 10:11:41 -05004730 spv::Id resultTypeId;
4731 // imageAtomicStore has a void return type so base the pointer type on
4732 // the type of the value operand.
4733 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004734 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004735 } else {
4736 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4737 }
John Kessenich56bab042015-09-16 10:54:31 -06004738 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004739
4740 std::vector<spv::Id> operands;
4741 operands.push_back(pointer);
4742 for (; opIt != arguments.end(); ++opIt)
4743 operands.push_back(*opIt);
4744
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004745 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004746 }
4747 }
4748
John Kessenicha28f7a72019-08-06 07:00:58 -06004749#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004750 // Check for fragment mask functions other than queries
4751 if (cracked.fragMask) {
4752 assert(sampler.ms);
4753
4754 auto opIt = arguments.begin();
4755 std::vector<spv::Id> operands;
4756
4757 // Extract the image if necessary
4758 if (builder.isSampledImage(params.sampler))
4759 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4760
4761 operands.push_back(params.sampler);
4762 ++opIt;
4763
4764 if (sampler.isSubpass()) {
4765 // add on the (0,0) coordinate
4766 spv::Id zero = builder.makeIntConstant(0);
4767 std::vector<spv::Id> comps;
4768 comps.push_back(zero);
4769 comps.push_back(zero);
4770 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4771 }
4772
4773 for (; opIt != arguments.end(); ++opIt)
4774 operands.push_back(*opIt);
4775
4776 spv::Op fragMaskOp = spv::OpNop;
4777 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4778 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4779 else if (node->getOp() == glslang::EOpFragmentFetch)
4780 fragMaskOp = spv::OpFragmentFetchAMD;
4781
4782 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4783 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4784 return builder.createOp(fragMaskOp, resultType(), operands);
4785 }
4786#endif
4787
Rex Xufc618912015-09-09 16:42:49 +08004788 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004789 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004790 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004791 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004792
John Kessenichfc51d282015-08-19 13:34:18 -06004793 // check for bias argument
4794 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004795 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004796 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004797 if (cracked.gather)
4798 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004799
4800 if (f16ShadowCompare)
4801 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004802 if (cracked.offset)
4803 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004804 else if (cracked.offsets)
4805 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004806 if (cracked.grad)
4807 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004808 if (cracked.lodClamp)
4809 ++nonBiasArgCount;
4810 if (sparse)
4811 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004812 if (imageFootprint)
4813 //Following three extra arguments
4814 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4815 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004816 if ((int)arguments.size() > nonBiasArgCount)
4817 bias = true;
4818 }
4819
John Kessenicha5c33d62016-06-02 23:45:21 -06004820 // See if the sampler param should really be just the SPV image part
4821 if (cracked.fetch) {
4822 // a fetch needs to have the image extracted first
4823 if (builder.isSampledImage(params.sampler))
4824 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4825 }
4826
John Kessenicha28f7a72019-08-06 07:00:58 -06004827#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004828 if (cracked.gather) {
4829 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4830 if (bias || cracked.lod ||
4831 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4832 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004833 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004834 }
4835 }
4836#endif
4837
John Kessenichfc51d282015-08-19 13:34:18 -06004838 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004839
John Kessenichfc51d282015-08-19 13:34:18 -06004840 params.coords = arguments[1];
4841 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004842 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004843
4844 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004845 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004846 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004847 ++extraArgs;
4848 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004849 params.Dref = arguments[2];
4850 ++extraArgs;
4851 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004852 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004853 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004854 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004855 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004856 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004857 dRefComp = builder.getNumComponents(params.coords) - 1;
4858 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004859 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4860 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004861
4862 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004863 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004864 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004865 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004866 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4867 !(glslangIntermediate->getStage() == EShLangCompute &&
4868 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004869 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4870 noImplicitLod = true;
4871 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004872
4873 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004874 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004875 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004876 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004877 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004878
4879 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004880 if (cracked.grad) {
4881 params.gradX = arguments[2 + extraArgs];
4882 params.gradY = arguments[3 + extraArgs];
4883 extraArgs += 2;
4884 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004885
4886 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004887 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004888 params.offset = arguments[2 + extraArgs];
4889 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004890 } else if (cracked.offsets) {
4891 params.offsets = arguments[2 + extraArgs];
4892 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004893 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004894
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004895#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004896 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004897 if (cracked.lodClamp) {
4898 params.lodClamp = arguments[2 + extraArgs];
4899 ++extraArgs;
4900 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004901 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004902 if (sparse) {
4903 params.texelOut = arguments[2 + extraArgs];
4904 ++extraArgs;
4905 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004906 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004907 if (cracked.gather && ! sampler.shadow) {
4908 // default component is 0, if missing, otherwise an argument
4909 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004910 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004911 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004912 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004913 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004914 }
Chao Chen3a137962018-09-19 11:41:27 -07004915 spv::Id resultStruct = spv::NoResult;
4916 if (imageFootprint) {
4917 //Following three extra arguments
4918 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4919 params.granularity = arguments[2 + extraArgs];
4920 params.coarse = arguments[3 + extraArgs];
4921 resultStruct = arguments[4 + extraArgs];
4922 extraArgs += 3;
4923 }
4924#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004925 // bias
4926 if (bias) {
4927 params.bias = arguments[2 + extraArgs];
4928 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004929 }
John Kessenichfc51d282015-08-19 13:34:18 -06004930
John Kessenicha28f7a72019-08-06 07:00:58 -06004931#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004932 if (imageFootprint) {
4933 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4934 builder.addCapability(spv::CapabilityImageFootprintNV);
4935
4936
4937 //resultStructType(OpenGL type) contains 5 elements:
4938 //struct gl_TextureFootprint2DNV {
4939 // uvec2 anchor;
4940 // uvec2 offset;
4941 // uvec2 mask;
4942 // uint lod;
4943 // uint granularity;
4944 //};
4945 //or
4946 //struct gl_TextureFootprint3DNV {
4947 // uvec3 anchor;
4948 // uvec3 offset;
4949 // uvec2 mask;
4950 // uint lod;
4951 // uint granularity;
4952 //};
4953 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4954 assert(builder.isStructType(resultStructType));
4955
4956 //resType (SPIR-V type) contains 6 elements:
4957 //Member 0 must be a Boolean type scalar(LOD),
4958 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4959 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4960 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4961 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4962 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4963 std::vector<spv::Id> members;
4964 members.push_back(resultType());
4965 for (int i = 0; i < 5; i++) {
4966 members.push_back(builder.getContainedTypeId(resultStructType, i));
4967 }
4968 spv::Id resType = builder.makeStructType(members, "ResType");
4969
4970 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004971 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4972 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004973
4974 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4975 for (int i = 0; i < 5; i++) {
4976 builder.clearAccessChain();
4977 builder.setAccessChainLValue(resultStruct);
4978
4979 //Accessing to a struct we created, no coherent flag is set
4980 spv::Builder::AccessChain::CoherentFlags flags;
4981 flags.clear();
4982
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004983 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004984 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4985 }
4986 return builder.createCompositeExtract(res, resultType(), 0);
4987 }
4988#endif
4989
John Kessenich65336482016-06-16 14:06:26 -06004990 // projective component (might not to move)
4991 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4992 // are divided by the last component of P."
4993 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4994 // unused components will appear after all used components."
4995 if (cracked.proj) {
4996 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4997 int projTargetComp;
4998 switch (sampler.dim) {
4999 case glslang::Esd1D: projTargetComp = 1; break;
5000 case glslang::Esd2D: projTargetComp = 2; break;
5001 case glslang::EsdRect: projTargetComp = 2; break;
5002 default: projTargetComp = projSourceComp; break;
5003 }
5004 // copy the projective coordinate if we have to
5005 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005006 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06005007 builder.getScalarTypeId(builder.getTypeId(params.coords)),
5008 projSourceComp);
5009 params.coords = builder.createCompositeInsert(projComp, params.coords,
5010 builder.getTypeId(params.coords), projTargetComp);
5011 }
5012 }
5013
John Kessenichf8d1d742019-10-21 06:55:11 -06005014#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005015 // nonprivate
5016 if (imageType.getQualifier().nonprivate) {
5017 params.nonprivate = true;
5018 }
5019
5020 // volatile
5021 if (imageType.getQualifier().volatil) {
5022 params.volatil = true;
5023 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005024#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005025
St0fFa1184dd2018-04-09 21:08:14 +02005026 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005027 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5028 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005029 );
LoopDawg4425f242018-02-18 11:40:01 -07005030
5031 if (components != node->getType().getVectorSize())
5032 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5033
5034 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005035}
5036
5037spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5038{
5039 // Grab the function's pointer from the previously created function
5040 spv::Function* function = functionMap[node->getName().c_str()];
5041 if (! function)
5042 return 0;
5043
5044 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5045 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5046
5047 // See comments in makeFunctions() for details about the semantics for parameter passing.
5048 //
5049 // These imply we need a four step process:
5050 // 1. Evaluate the arguments
5051 // 2. Allocate and make copies of in, out, and inout arguments
5052 // 3. Make the call
5053 // 4. Copy back the results
5054
John Kessenichd3ed90b2018-05-04 11:43:03 -06005055 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005056 std::vector<spv::Builder::AccessChain> lValues;
5057 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005058 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005059 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005060 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005061 // build l-value
5062 builder.clearAccessChain();
5063 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005064 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005065 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005066 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005067 // save l-value
5068 lValues.push_back(builder.getAccessChain());
5069 } else {
5070 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005071 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005072 }
5073 }
5074
5075 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5076 // copy the original into that space.
5077 //
5078 // Also, build up the list of actual arguments to pass in for the call
5079 int lValueCount = 0;
5080 int rValueCount = 0;
5081 std::vector<spv::Id> spvArgs;
5082 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5083 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005084 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005085 builder.setAccessChain(lValues[lValueCount]);
5086 arg = builder.accessChainGetLValue();
5087 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005088 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005089 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005090 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005091 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5092 // need to copy the input into output space
5093 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005094 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005095 builder.clearAccessChain();
5096 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005097 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005098 }
5099 ++lValueCount;
5100 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005101 // process r-value, which involves a copy for a type mismatch
5102 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5103 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5104 builder.clearAccessChain();
5105 builder.setAccessChainLValue(argCopy);
5106 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5107 arg = builder.createLoad(argCopy);
5108 } else
5109 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005110 ++rValueCount;
5111 }
5112 spvArgs.push_back(arg);
5113 }
5114
5115 // 3. Make the call.
5116 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005117 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005118
5119 // 4. Copy back out an "out" arguments.
5120 lValueCount = 0;
5121 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005122 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005123 ++lValueCount;
5124 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005125 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5126 spv::Id copy = builder.createLoad(spvArgs[a]);
5127 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005128 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005129 }
5130 ++lValueCount;
5131 }
5132 }
5133
5134 return result;
5135}
5136
5137// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005138spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005139 spv::Id typeId, spv::Id left, spv::Id right,
5140 glslang::TBasicType typeProxy, bool reduceComparison)
5141{
John Kessenich66011cb2018-03-06 16:12:04 -07005142 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5143 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005144 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005145
5146 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005147 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005148 bool comparison = false;
5149
5150 switch (op) {
5151 case glslang::EOpAdd:
5152 case glslang::EOpAddAssign:
5153 if (isFloat)
5154 binOp = spv::OpFAdd;
5155 else
5156 binOp = spv::OpIAdd;
5157 break;
5158 case glslang::EOpSub:
5159 case glslang::EOpSubAssign:
5160 if (isFloat)
5161 binOp = spv::OpFSub;
5162 else
5163 binOp = spv::OpISub;
5164 break;
5165 case glslang::EOpMul:
5166 case glslang::EOpMulAssign:
5167 if (isFloat)
5168 binOp = spv::OpFMul;
5169 else
5170 binOp = spv::OpIMul;
5171 break;
5172 case glslang::EOpVectorTimesScalar:
5173 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005174 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005175 if (builder.isVector(right))
5176 std::swap(left, right);
5177 assert(builder.isScalar(right));
5178 needMatchingVectors = false;
5179 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005180 } else if (isFloat)
5181 binOp = spv::OpFMul;
5182 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005183 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005184 break;
5185 case glslang::EOpVectorTimesMatrix:
5186 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005187 binOp = spv::OpVectorTimesMatrix;
5188 break;
5189 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005190 binOp = spv::OpMatrixTimesVector;
5191 break;
5192 case glslang::EOpMatrixTimesScalar:
5193 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005194 binOp = spv::OpMatrixTimesScalar;
5195 break;
5196 case glslang::EOpMatrixTimesMatrix:
5197 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005198 binOp = spv::OpMatrixTimesMatrix;
5199 break;
5200 case glslang::EOpOuterProduct:
5201 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005202 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005203 break;
5204
5205 case glslang::EOpDiv:
5206 case glslang::EOpDivAssign:
5207 if (isFloat)
5208 binOp = spv::OpFDiv;
5209 else if (isUnsigned)
5210 binOp = spv::OpUDiv;
5211 else
5212 binOp = spv::OpSDiv;
5213 break;
5214 case glslang::EOpMod:
5215 case glslang::EOpModAssign:
5216 if (isFloat)
5217 binOp = spv::OpFMod;
5218 else if (isUnsigned)
5219 binOp = spv::OpUMod;
5220 else
5221 binOp = spv::OpSMod;
5222 break;
5223 case glslang::EOpRightShift:
5224 case glslang::EOpRightShiftAssign:
5225 if (isUnsigned)
5226 binOp = spv::OpShiftRightLogical;
5227 else
5228 binOp = spv::OpShiftRightArithmetic;
5229 break;
5230 case glslang::EOpLeftShift:
5231 case glslang::EOpLeftShiftAssign:
5232 binOp = spv::OpShiftLeftLogical;
5233 break;
5234 case glslang::EOpAnd:
5235 case glslang::EOpAndAssign:
5236 binOp = spv::OpBitwiseAnd;
5237 break;
5238 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005239 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005240 binOp = spv::OpLogicalAnd;
5241 break;
5242 case glslang::EOpInclusiveOr:
5243 case glslang::EOpInclusiveOrAssign:
5244 binOp = spv::OpBitwiseOr;
5245 break;
5246 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005247 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005248 binOp = spv::OpLogicalOr;
5249 break;
5250 case glslang::EOpExclusiveOr:
5251 case glslang::EOpExclusiveOrAssign:
5252 binOp = spv::OpBitwiseXor;
5253 break;
5254 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005255 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005256 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005257 break;
5258
Ian Romanickb3bd4022019-01-21 08:57:25 -08005259 case glslang::EOpAbsDifference:
5260 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5261 break;
5262
5263 case glslang::EOpAddSaturate:
5264 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5265 break;
5266
5267 case glslang::EOpSubSaturate:
5268 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5269 break;
5270
5271 case glslang::EOpAverage:
5272 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5273 break;
5274
5275 case glslang::EOpAverageRounded:
5276 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5277 break;
5278
5279 case glslang::EOpMul32x16:
5280 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5281 break;
5282
John Kessenich140f3df2015-06-26 16:58:36 -06005283 case glslang::EOpLessThan:
5284 case glslang::EOpGreaterThan:
5285 case glslang::EOpLessThanEqual:
5286 case glslang::EOpGreaterThanEqual:
5287 case glslang::EOpEqual:
5288 case glslang::EOpNotEqual:
5289 case glslang::EOpVectorEqual:
5290 case glslang::EOpVectorNotEqual:
5291 comparison = true;
5292 break;
5293 default:
5294 break;
5295 }
5296
John Kessenich7c1aa102015-10-15 13:29:11 -06005297 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005298 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005299 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005300 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5301 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005302 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005303
5304 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005305 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005306 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005307
qining25262b32016-05-06 17:25:16 -04005308 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005309 decorations.addNoContraction(builder, result);
5310 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005311 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005312 }
5313
5314 if (! comparison)
5315 return 0;
5316
John Kessenich7c1aa102015-10-15 13:29:11 -06005317 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005318
John Kessenich4583b612016-08-07 19:14:22 -06005319 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005320 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5321 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005322 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005323 return result;
5324 }
John Kessenich140f3df2015-06-26 16:58:36 -06005325
5326 switch (op) {
5327 case glslang::EOpLessThan:
5328 if (isFloat)
5329 binOp = spv::OpFOrdLessThan;
5330 else if (isUnsigned)
5331 binOp = spv::OpULessThan;
5332 else
5333 binOp = spv::OpSLessThan;
5334 break;
5335 case glslang::EOpGreaterThan:
5336 if (isFloat)
5337 binOp = spv::OpFOrdGreaterThan;
5338 else if (isUnsigned)
5339 binOp = spv::OpUGreaterThan;
5340 else
5341 binOp = spv::OpSGreaterThan;
5342 break;
5343 case glslang::EOpLessThanEqual:
5344 if (isFloat)
5345 binOp = spv::OpFOrdLessThanEqual;
5346 else if (isUnsigned)
5347 binOp = spv::OpULessThanEqual;
5348 else
5349 binOp = spv::OpSLessThanEqual;
5350 break;
5351 case glslang::EOpGreaterThanEqual:
5352 if (isFloat)
5353 binOp = spv::OpFOrdGreaterThanEqual;
5354 else if (isUnsigned)
5355 binOp = spv::OpUGreaterThanEqual;
5356 else
5357 binOp = spv::OpSGreaterThanEqual;
5358 break;
5359 case glslang::EOpEqual:
5360 case glslang::EOpVectorEqual:
5361 if (isFloat)
5362 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005363 else if (isBool)
5364 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005365 else
5366 binOp = spv::OpIEqual;
5367 break;
5368 case glslang::EOpNotEqual:
5369 case glslang::EOpVectorNotEqual:
5370 if (isFloat)
5371 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005372 else if (isBool)
5373 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005374 else
5375 binOp = spv::OpINotEqual;
5376 break;
5377 default:
5378 break;
5379 }
5380
qining25262b32016-05-06 17:25:16 -04005381 if (binOp != spv::OpNop) {
5382 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005383 decorations.addNoContraction(builder, result);
5384 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005385 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005386 }
John Kessenich140f3df2015-06-26 16:58:36 -06005387
5388 return 0;
5389}
5390
John Kessenich04bb8a02015-12-12 12:28:14 -07005391//
5392// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5393// These can be any of:
5394//
5395// matrix * scalar
5396// scalar * matrix
5397// matrix * matrix linear algebraic
5398// matrix * vector
5399// vector * matrix
5400// matrix * matrix componentwise
5401// matrix op matrix op in {+, -, /}
5402// matrix op scalar op in {+, -, /}
5403// scalar op matrix op in {+, -, /}
5404//
John Kessenichead86222018-03-28 18:01:20 -06005405spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5406 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005407{
5408 bool firstClass = true;
5409
5410 // First, handle first-class matrix operations (* and matrix/scalar)
5411 switch (op) {
5412 case spv::OpFDiv:
5413 if (builder.isMatrix(left) && builder.isScalar(right)) {
5414 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005415 spv::Id resultType = builder.getTypeId(right);
5416 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005417 op = spv::OpMatrixTimesScalar;
5418 } else
5419 firstClass = false;
5420 break;
5421 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005422 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005423 std::swap(left, right);
5424 assert(builder.isScalar(right));
5425 break;
5426 case spv::OpVectorTimesMatrix:
5427 assert(builder.isVector(left));
5428 assert(builder.isMatrix(right));
5429 break;
5430 case spv::OpMatrixTimesVector:
5431 assert(builder.isMatrix(left));
5432 assert(builder.isVector(right));
5433 break;
5434 case spv::OpMatrixTimesMatrix:
5435 assert(builder.isMatrix(left));
5436 assert(builder.isMatrix(right));
5437 break;
5438 default:
5439 firstClass = false;
5440 break;
5441 }
5442
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005443 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5444 firstClass = true;
5445
qining25262b32016-05-06 17:25:16 -04005446 if (firstClass) {
5447 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005448 decorations.addNoContraction(builder, result);
5449 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005450 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005451 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005452
LoopDawg592860c2016-06-09 08:57:35 -06005453 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005454 // The result type of all of them is the same type as the (a) matrix operand.
5455 // The algorithm is to:
5456 // - break the matrix(es) into vectors
5457 // - smear any scalar to a vector
5458 // - do vector operations
5459 // - make a matrix out the vector results
5460 switch (op) {
5461 case spv::OpFAdd:
5462 case spv::OpFSub:
5463 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005464 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005465 case spv::OpFMul:
5466 {
5467 // one time set up...
5468 bool leftMat = builder.isMatrix(left);
5469 bool rightMat = builder.isMatrix(right);
5470 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5471 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5472 spv::Id scalarType = builder.getScalarTypeId(typeId);
5473 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5474 std::vector<spv::Id> results;
5475 spv::Id smearVec = spv::NoResult;
5476 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005477 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005478 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005479 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005480
5481 // do each vector op
5482 for (unsigned int c = 0; c < numCols; ++c) {
5483 std::vector<unsigned int> indexes;
5484 indexes.push_back(c);
5485 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5486 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005487 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005488 decorations.addNoContraction(builder, result);
5489 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005490 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005491 }
5492
5493 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005494 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005495 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005496 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005497 }
5498 default:
5499 assert(0);
5500 return spv::NoResult;
5501 }
5502}
5503
John Kessenichead86222018-03-28 18:01:20 -06005504spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005505 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005506{
5507 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005508 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005509 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005510 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5511 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005512
5513 switch (op) {
5514 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005515 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005516 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005517 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005518 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005519 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005520 unaryOp = spv::OpSNegate;
5521 break;
5522
5523 case glslang::EOpLogicalNot:
5524 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005525 unaryOp = spv::OpLogicalNot;
5526 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005527 case glslang::EOpBitwiseNot:
5528 unaryOp = spv::OpNot;
5529 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005530
John Kessenich140f3df2015-06-26 16:58:36 -06005531 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005532 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005533 break;
5534 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005535 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005536 break;
5537 case glslang::EOpTranspose:
5538 unaryOp = spv::OpTranspose;
5539 break;
5540
5541 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005542 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005543 break;
5544 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005545 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005546 break;
5547 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005548 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005549 break;
5550 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005551 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005552 break;
5553 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005554 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005555 break;
5556 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005557 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005558 break;
5559 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005560 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005561 break;
5562 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005563 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005564 break;
5565
5566 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005567 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005568 break;
5569 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005570 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005571 break;
5572 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005573 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005574 break;
5575 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005576 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005577 break;
5578 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005579 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005580 break;
5581 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005582 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005583 break;
5584
5585 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005586 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005587 break;
5588 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005589 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005590 break;
5591
5592 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005593 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005594 break;
5595 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005596 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005597 break;
5598 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005599 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005600 break;
5601 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005602 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005603 break;
5604 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005605 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005606 break;
5607 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005608 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005609 break;
5610
5611 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005612 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005613 break;
5614 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005615 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005616 break;
5617 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005618 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005619 break;
5620 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005621 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005622 break;
5623 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005624 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005625 break;
5626 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005627 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005628 break;
5629
5630 case glslang::EOpIsNan:
5631 unaryOp = spv::OpIsNan;
5632 break;
5633 case glslang::EOpIsInf:
5634 unaryOp = spv::OpIsInf;
5635 break;
LoopDawg592860c2016-06-09 08:57:35 -06005636 case glslang::EOpIsFinite:
5637 unaryOp = spv::OpIsFinite;
5638 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005639
Rex Xucbc426e2015-12-15 16:03:10 +08005640 case glslang::EOpFloatBitsToInt:
5641 case glslang::EOpFloatBitsToUint:
5642 case glslang::EOpIntBitsToFloat:
5643 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005644 case glslang::EOpDoubleBitsToInt64:
5645 case glslang::EOpDoubleBitsToUint64:
5646 case glslang::EOpInt64BitsToDouble:
5647 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005648 case glslang::EOpFloat16BitsToInt16:
5649 case glslang::EOpFloat16BitsToUint16:
5650 case glslang::EOpInt16BitsToFloat16:
5651 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005652 unaryOp = spv::OpBitcast;
5653 break;
5654
John Kessenich140f3df2015-06-26 16:58:36 -06005655 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005656 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005657 break;
5658 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005659 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005660 break;
5661 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005662 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005663 break;
5664 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005665 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005666 break;
5667 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005668 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005669 break;
5670 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005671 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005672 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005673#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005674 case glslang::EOpPackSnorm4x8:
5675 libCall = spv::GLSLstd450PackSnorm4x8;
5676 break;
5677 case glslang::EOpUnpackSnorm4x8:
5678 libCall = spv::GLSLstd450UnpackSnorm4x8;
5679 break;
5680 case glslang::EOpPackUnorm4x8:
5681 libCall = spv::GLSLstd450PackUnorm4x8;
5682 break;
5683 case glslang::EOpUnpackUnorm4x8:
5684 libCall = spv::GLSLstd450UnpackUnorm4x8;
5685 break;
5686 case glslang::EOpPackDouble2x32:
5687 libCall = spv::GLSLstd450PackDouble2x32;
5688 break;
5689 case glslang::EOpUnpackDouble2x32:
5690 libCall = spv::GLSLstd450UnpackDouble2x32;
5691 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005692#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005693
Rex Xu8ff43de2016-04-22 16:51:45 +08005694 case glslang::EOpPackInt2x32:
5695 case glslang::EOpUnpackInt2x32:
5696 case glslang::EOpPackUint2x32:
5697 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005698 case glslang::EOpPack16:
5699 case glslang::EOpPack32:
5700 case glslang::EOpPack64:
5701 case glslang::EOpUnpack32:
5702 case glslang::EOpUnpack16:
5703 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005704 case glslang::EOpPackInt2x16:
5705 case glslang::EOpUnpackInt2x16:
5706 case glslang::EOpPackUint2x16:
5707 case glslang::EOpUnpackUint2x16:
5708 case glslang::EOpPackInt4x16:
5709 case glslang::EOpUnpackInt4x16:
5710 case glslang::EOpPackUint4x16:
5711 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005712 case glslang::EOpPackFloat2x16:
5713 case glslang::EOpUnpackFloat2x16:
5714 unaryOp = spv::OpBitcast;
5715 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005716
John Kessenich140f3df2015-06-26 16:58:36 -06005717 case glslang::EOpDPdx:
5718 unaryOp = spv::OpDPdx;
5719 break;
5720 case glslang::EOpDPdy:
5721 unaryOp = spv::OpDPdy;
5722 break;
5723 case glslang::EOpFwidth:
5724 unaryOp = spv::OpFwidth;
5725 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005726
John Kessenich140f3df2015-06-26 16:58:36 -06005727 case glslang::EOpAny:
5728 unaryOp = spv::OpAny;
5729 break;
5730 case glslang::EOpAll:
5731 unaryOp = spv::OpAll;
5732 break;
5733
5734 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005735 if (isFloat)
5736 libCall = spv::GLSLstd450FAbs;
5737 else
5738 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005739 break;
5740 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005741 if (isFloat)
5742 libCall = spv::GLSLstd450FSign;
5743 else
5744 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005745 break;
5746
John Kessenicha28f7a72019-08-06 07:00:58 -06005747#ifndef GLSLANG_WEB
5748 case glslang::EOpDPdxFine:
5749 unaryOp = spv::OpDPdxFine;
5750 break;
5751 case glslang::EOpDPdyFine:
5752 unaryOp = spv::OpDPdyFine;
5753 break;
5754 case glslang::EOpFwidthFine:
5755 unaryOp = spv::OpFwidthFine;
5756 break;
5757 case glslang::EOpDPdxCoarse:
5758 unaryOp = spv::OpDPdxCoarse;
5759 break;
5760 case glslang::EOpDPdyCoarse:
5761 unaryOp = spv::OpDPdyCoarse;
5762 break;
5763 case glslang::EOpFwidthCoarse:
5764 unaryOp = spv::OpFwidthCoarse;
5765 break;
5766 case glslang::EOpInterpolateAtCentroid:
5767 if (typeProxy == glslang::EbtFloat16)
5768 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5769 libCall = spv::GLSLstd450InterpolateAtCentroid;
5770 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005771 case glslang::EOpAtomicCounterIncrement:
5772 case glslang::EOpAtomicCounterDecrement:
5773 case glslang::EOpAtomicCounter:
5774 {
5775 // Handle all of the atomics in one place, in createAtomicOperation()
5776 std::vector<spv::Id> operands;
5777 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005778 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005779 }
5780
John Kessenichfc51d282015-08-19 13:34:18 -06005781 case glslang::EOpBitFieldReverse:
5782 unaryOp = spv::OpBitReverse;
5783 break;
5784 case glslang::EOpBitCount:
5785 unaryOp = spv::OpBitCount;
5786 break;
5787 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005788 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005789 break;
5790 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005791 if (isUnsigned)
5792 libCall = spv::GLSLstd450FindUMsb;
5793 else
5794 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005795 break;
5796
Ian Romanickb3bd4022019-01-21 08:57:25 -08005797 case glslang::EOpCountLeadingZeros:
5798 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5799 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5800 unaryOp = spv::OpUCountLeadingZerosINTEL;
5801 break;
5802
5803 case glslang::EOpCountTrailingZeros:
5804 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5805 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5806 unaryOp = spv::OpUCountTrailingZerosINTEL;
5807 break;
5808
Rex Xu574ab042016-04-14 16:53:07 +08005809 case glslang::EOpBallot:
5810 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005811 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005812 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005813 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005814 case glslang::EOpMinInvocations:
5815 case glslang::EOpMaxInvocations:
5816 case glslang::EOpAddInvocations:
5817 case glslang::EOpMinInvocationsNonUniform:
5818 case glslang::EOpMaxInvocationsNonUniform:
5819 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005820 case glslang::EOpMinInvocationsInclusiveScan:
5821 case glslang::EOpMaxInvocationsInclusiveScan:
5822 case glslang::EOpAddInvocationsInclusiveScan:
5823 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5824 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5825 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5826 case glslang::EOpMinInvocationsExclusiveScan:
5827 case glslang::EOpMaxInvocationsExclusiveScan:
5828 case glslang::EOpAddInvocationsExclusiveScan:
5829 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5830 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5831 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005832 {
5833 std::vector<spv::Id> operands;
5834 operands.push_back(operand);
5835 return createInvocationsOperation(op, typeId, operands, typeProxy);
5836 }
John Kessenich66011cb2018-03-06 16:12:04 -07005837 case glslang::EOpSubgroupAll:
5838 case glslang::EOpSubgroupAny:
5839 case glslang::EOpSubgroupAllEqual:
5840 case glslang::EOpSubgroupBroadcastFirst:
5841 case glslang::EOpSubgroupBallot:
5842 case glslang::EOpSubgroupInverseBallot:
5843 case glslang::EOpSubgroupBallotBitCount:
5844 case glslang::EOpSubgroupBallotInclusiveBitCount:
5845 case glslang::EOpSubgroupBallotExclusiveBitCount:
5846 case glslang::EOpSubgroupBallotFindLSB:
5847 case glslang::EOpSubgroupBallotFindMSB:
5848 case glslang::EOpSubgroupAdd:
5849 case glslang::EOpSubgroupMul:
5850 case glslang::EOpSubgroupMin:
5851 case glslang::EOpSubgroupMax:
5852 case glslang::EOpSubgroupAnd:
5853 case glslang::EOpSubgroupOr:
5854 case glslang::EOpSubgroupXor:
5855 case glslang::EOpSubgroupInclusiveAdd:
5856 case glslang::EOpSubgroupInclusiveMul:
5857 case glslang::EOpSubgroupInclusiveMin:
5858 case glslang::EOpSubgroupInclusiveMax:
5859 case glslang::EOpSubgroupInclusiveAnd:
5860 case glslang::EOpSubgroupInclusiveOr:
5861 case glslang::EOpSubgroupInclusiveXor:
5862 case glslang::EOpSubgroupExclusiveAdd:
5863 case glslang::EOpSubgroupExclusiveMul:
5864 case glslang::EOpSubgroupExclusiveMin:
5865 case glslang::EOpSubgroupExclusiveMax:
5866 case glslang::EOpSubgroupExclusiveAnd:
5867 case glslang::EOpSubgroupExclusiveOr:
5868 case glslang::EOpSubgroupExclusiveXor:
5869 case glslang::EOpSubgroupQuadSwapHorizontal:
5870 case glslang::EOpSubgroupQuadSwapVertical:
5871 case glslang::EOpSubgroupQuadSwapDiagonal: {
5872 std::vector<spv::Id> operands;
5873 operands.push_back(operand);
5874 return createSubgroupOperation(op, typeId, operands, typeProxy);
5875 }
Rex Xu9d93a232016-05-05 12:30:44 +08005876 case glslang::EOpMbcnt:
5877 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5878 libCall = spv::MbcntAMD;
5879 break;
5880
5881 case glslang::EOpCubeFaceIndex:
5882 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5883 libCall = spv::CubeFaceIndexAMD;
5884 break;
5885
5886 case glslang::EOpCubeFaceCoord:
5887 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5888 libCall = spv::CubeFaceCoordAMD;
5889 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005890 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005891 unaryOp = spv::OpGroupNonUniformPartitionNV;
5892 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005893 case glslang::EOpConstructReference:
5894 unaryOp = spv::OpBitcast;
5895 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005896#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005897
5898 case glslang::EOpCopyObject:
5899 unaryOp = spv::OpCopyObject;
5900 break;
5901
John Kessenich140f3df2015-06-26 16:58:36 -06005902 default:
5903 return 0;
5904 }
5905
5906 spv::Id id;
5907 if (libCall >= 0) {
5908 std::vector<spv::Id> args;
5909 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005910 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005911 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005912 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005913 }
John Kessenich140f3df2015-06-26 16:58:36 -06005914
John Kessenichb9197c82019-08-11 07:41:45 -06005915 decorations.addNoContraction(builder, id);
5916 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06005917 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005918}
5919
John Kessenich7a53f762016-01-20 11:19:27 -07005920// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005921spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5922 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005923{
5924 // Handle unary operations vector by vector.
5925 // The result type is the same type as the original type.
5926 // The algorithm is to:
5927 // - break the matrix into vectors
5928 // - apply the operation to each vector
5929 // - make a matrix out the vector results
5930
5931 // get the types sorted out
5932 int numCols = builder.getNumColumns(operand);
5933 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005934 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5935 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005936 std::vector<spv::Id> results;
5937
5938 // do each vector op
5939 for (int c = 0; c < numCols; ++c) {
5940 std::vector<unsigned int> indexes;
5941 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005942 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5943 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005944 decorations.addNoContraction(builder, destVec);
5945 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06005946 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005947 }
5948
5949 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005950 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005951 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005952 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005953}
5954
John Kessenichad7645f2018-06-04 19:11:25 -06005955// For converting integers where both the bitwidth and the signedness could
5956// change, but only do the width change here. The caller is still responsible
5957// for the signedness conversion.
5958spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005959{
John Kessenichad7645f2018-06-04 19:11:25 -06005960 // Get the result type width, based on the type to convert to.
5961 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005962 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005963 case glslang::EOpConvInt16ToUint8:
5964 case glslang::EOpConvIntToUint8:
5965 case glslang::EOpConvInt64ToUint8:
5966 case glslang::EOpConvUint16ToInt8:
5967 case glslang::EOpConvUintToInt8:
5968 case glslang::EOpConvUint64ToInt8:
5969 width = 8;
5970 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005971 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005972 case glslang::EOpConvIntToUint16:
5973 case glslang::EOpConvInt64ToUint16:
5974 case glslang::EOpConvUint8ToInt16:
5975 case glslang::EOpConvUintToInt16:
5976 case glslang::EOpConvUint64ToInt16:
5977 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005978 break;
5979 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005980 case glslang::EOpConvInt16ToUint:
5981 case glslang::EOpConvInt64ToUint:
5982 case glslang::EOpConvUint8ToInt:
5983 case glslang::EOpConvUint16ToInt:
5984 case glslang::EOpConvUint64ToInt:
5985 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005986 break;
5987 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005988 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005989 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005990 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005991 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005992 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005993 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005994 break;
5995
5996 default:
5997 assert(false && "Default missing");
5998 break;
5999 }
6000
John Kessenichad7645f2018-06-04 19:11:25 -06006001 // Get the conversion operation and result type,
6002 // based on the target width, but the source type.
6003 spv::Id type = spv::NoType;
6004 spv::Op convOp = spv::OpNop;
6005 switch(op) {
6006 case glslang::EOpConvInt8ToUint16:
6007 case glslang::EOpConvInt8ToUint:
6008 case glslang::EOpConvInt8ToUint64:
6009 case glslang::EOpConvInt16ToUint8:
6010 case glslang::EOpConvInt16ToUint:
6011 case glslang::EOpConvInt16ToUint64:
6012 case glslang::EOpConvIntToUint8:
6013 case glslang::EOpConvIntToUint16:
6014 case glslang::EOpConvIntToUint64:
6015 case glslang::EOpConvInt64ToUint8:
6016 case glslang::EOpConvInt64ToUint16:
6017 case glslang::EOpConvInt64ToUint:
6018 convOp = spv::OpSConvert;
6019 type = builder.makeIntType(width);
6020 break;
6021 default:
6022 convOp = spv::OpUConvert;
6023 type = builder.makeUintType(width);
6024 break;
6025 }
6026
John Kessenich66011cb2018-03-06 16:12:04 -07006027 if (vectorSize > 0)
6028 type = builder.makeVectorType(type, vectorSize);
6029
John Kessenichad7645f2018-06-04 19:11:25 -06006030 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006031}
6032
John Kessenichead86222018-03-28 18:01:20 -06006033spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6034 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006035{
6036 spv::Op convOp = spv::OpNop;
6037 spv::Id zero = 0;
6038 spv::Id one = 0;
6039
6040 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6041
6042 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006043 case glslang::EOpConvIntToBool:
6044 case glslang::EOpConvUintToBool:
6045 zero = builder.makeUintConstant(0);
6046 zero = makeSmearedConstant(zero, vectorSize);
6047 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006048 case glslang::EOpConvFloatToBool:
6049 zero = builder.makeFloatConstant(0.0F);
6050 zero = makeSmearedConstant(zero, vectorSize);
6051 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006052 case glslang::EOpConvBoolToFloat:
6053 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006054 zero = builder.makeFloatConstant(0.0F);
6055 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006056 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006057
John Kessenich140f3df2015-06-26 16:58:36 -06006058 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006059 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006060#ifndef GLSLANG_WEB
6061 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006062 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006063 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006064 } else
6065#endif
6066 {
6067 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006068 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006069 }
Rex Xucabbb782017-03-24 13:41:14 +08006070
John Kessenich140f3df2015-06-26 16:58:36 -06006071 convOp = spv::OpSelect;
6072 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006073
John Kessenich140f3df2015-06-26 16:58:36 -06006074 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006075 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006076#ifndef GLSLANG_WEB
6077 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006078 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006079 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006080 } else
6081#endif
6082 {
6083 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006084 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006085 }
Rex Xucabbb782017-03-24 13:41:14 +08006086
John Kessenich140f3df2015-06-26 16:58:36 -06006087 convOp = spv::OpSelect;
6088 break;
6089
John Kessenich66011cb2018-03-06 16:12:04 -07006090 case glslang::EOpConvInt8ToFloat16:
6091 case glslang::EOpConvInt8ToFloat:
6092 case glslang::EOpConvInt8ToDouble:
6093 case glslang::EOpConvInt16ToFloat16:
6094 case glslang::EOpConvInt16ToFloat:
6095 case glslang::EOpConvInt16ToDouble:
6096 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006097 case glslang::EOpConvIntToFloat:
6098 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006099 case glslang::EOpConvInt64ToFloat:
6100 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006101 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006102 convOp = spv::OpConvertSToF;
6103 break;
6104
John Kessenich66011cb2018-03-06 16:12:04 -07006105 case glslang::EOpConvUint8ToFloat16:
6106 case glslang::EOpConvUint8ToFloat:
6107 case glslang::EOpConvUint8ToDouble:
6108 case glslang::EOpConvUint16ToFloat16:
6109 case glslang::EOpConvUint16ToFloat:
6110 case glslang::EOpConvUint16ToDouble:
6111 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006112 case glslang::EOpConvUintToFloat:
6113 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006114 case glslang::EOpConvUint64ToFloat:
6115 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006116 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006117 convOp = spv::OpConvertUToF;
6118 break;
6119
John Kessenich66011cb2018-03-06 16:12:04 -07006120 case glslang::EOpConvFloat16ToInt8:
6121 case glslang::EOpConvFloatToInt8:
6122 case glslang::EOpConvDoubleToInt8:
6123 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006124 case glslang::EOpConvFloatToInt16:
6125 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006126 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006127 case glslang::EOpConvFloatToInt:
6128 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006129 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006130 case glslang::EOpConvFloatToInt64:
6131 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006132 convOp = spv::OpConvertFToS;
6133 break;
6134
John Kessenich66011cb2018-03-06 16:12:04 -07006135 case glslang::EOpConvUint8ToInt8:
6136 case glslang::EOpConvInt8ToUint8:
6137 case glslang::EOpConvUint16ToInt16:
6138 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006139 case glslang::EOpConvUintToInt:
6140 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006141 case glslang::EOpConvUint64ToInt64:
6142 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006143 if (builder.isInSpecConstCodeGenMode()) {
6144 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006145#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006146 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6147 zero = builder.makeUint8Constant(0);
6148 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006149 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006150 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6151 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006152 } else
6153#endif
6154 {
Rex Xucabbb782017-03-24 13:41:14 +08006155 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006156 }
qining189b2032016-04-12 23:16:20 -04006157 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006158 // Use OpIAdd, instead of OpBitcast to do the conversion when
6159 // generating for OpSpecConstantOp instruction.
6160 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6161 }
6162 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006163 convOp = spv::OpBitcast;
6164 break;
6165
John Kessenich66011cb2018-03-06 16:12:04 -07006166 case glslang::EOpConvFloat16ToUint8:
6167 case glslang::EOpConvFloatToUint8:
6168 case glslang::EOpConvDoubleToUint8:
6169 case glslang::EOpConvFloat16ToUint16:
6170 case glslang::EOpConvFloatToUint16:
6171 case glslang::EOpConvDoubleToUint16:
6172 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006173 case glslang::EOpConvFloatToUint:
6174 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006175 case glslang::EOpConvFloatToUint64:
6176 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006177 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006178 convOp = spv::OpConvertFToU;
6179 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006180
John Kessenich39697cd2019-08-08 10:35:51 -06006181#ifndef GLSLANG_WEB
6182 case glslang::EOpConvInt8ToBool:
6183 case glslang::EOpConvUint8ToBool:
6184 zero = builder.makeUint8Constant(0);
6185 zero = makeSmearedConstant(zero, vectorSize);
6186 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6187 case glslang::EOpConvInt16ToBool:
6188 case glslang::EOpConvUint16ToBool:
6189 zero = builder.makeUint16Constant(0);
6190 zero = makeSmearedConstant(zero, vectorSize);
6191 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6192 case glslang::EOpConvInt64ToBool:
6193 case glslang::EOpConvUint64ToBool:
6194 zero = builder.makeUint64Constant(0);
6195 zero = makeSmearedConstant(zero, vectorSize);
6196 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6197 case glslang::EOpConvDoubleToBool:
6198 zero = builder.makeDoubleConstant(0.0);
6199 zero = makeSmearedConstant(zero, vectorSize);
6200 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6201 case glslang::EOpConvFloat16ToBool:
6202 zero = builder.makeFloat16Constant(0.0F);
6203 zero = makeSmearedConstant(zero, vectorSize);
6204 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6205 case glslang::EOpConvBoolToDouble:
6206 convOp = spv::OpSelect;
6207 zero = builder.makeDoubleConstant(0.0);
6208 one = builder.makeDoubleConstant(1.0);
6209 break;
6210 case glslang::EOpConvBoolToFloat16:
6211 convOp = spv::OpSelect;
6212 zero = builder.makeFloat16Constant(0.0F);
6213 one = builder.makeFloat16Constant(1.0F);
6214 break;
6215 case glslang::EOpConvBoolToInt8:
6216 zero = builder.makeInt8Constant(0);
6217 one = builder.makeInt8Constant(1);
6218 convOp = spv::OpSelect;
6219 break;
6220 case glslang::EOpConvBoolToUint8:
6221 zero = builder.makeUint8Constant(0);
6222 one = builder.makeUint8Constant(1);
6223 convOp = spv::OpSelect;
6224 break;
6225 case glslang::EOpConvBoolToInt16:
6226 zero = builder.makeInt16Constant(0);
6227 one = builder.makeInt16Constant(1);
6228 convOp = spv::OpSelect;
6229 break;
6230 case glslang::EOpConvBoolToUint16:
6231 zero = builder.makeUint16Constant(0);
6232 one = builder.makeUint16Constant(1);
6233 convOp = spv::OpSelect;
6234 break;
6235 case glslang::EOpConvDoubleToFloat:
6236 case glslang::EOpConvFloatToDouble:
6237 case glslang::EOpConvDoubleToFloat16:
6238 case glslang::EOpConvFloat16ToDouble:
6239 case glslang::EOpConvFloatToFloat16:
6240 case glslang::EOpConvFloat16ToFloat:
6241 convOp = spv::OpFConvert;
6242 if (builder.isMatrixType(destType))
6243 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6244 break;
6245
John Kessenich66011cb2018-03-06 16:12:04 -07006246 case glslang::EOpConvInt8ToInt16:
6247 case glslang::EOpConvInt8ToInt:
6248 case glslang::EOpConvInt8ToInt64:
6249 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006250 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006251 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006252 case glslang::EOpConvIntToInt8:
6253 case glslang::EOpConvIntToInt16:
6254 case glslang::EOpConvIntToInt64:
6255 case glslang::EOpConvInt64ToInt8:
6256 case glslang::EOpConvInt64ToInt16:
6257 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006258 convOp = spv::OpSConvert;
6259 break;
6260
John Kessenich66011cb2018-03-06 16:12:04 -07006261 case glslang::EOpConvUint8ToUint16:
6262 case glslang::EOpConvUint8ToUint:
6263 case glslang::EOpConvUint8ToUint64:
6264 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006265 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006266 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006267 case glslang::EOpConvUintToUint8:
6268 case glslang::EOpConvUintToUint16:
6269 case glslang::EOpConvUintToUint64:
6270 case glslang::EOpConvUint64ToUint8:
6271 case glslang::EOpConvUint64ToUint16:
6272 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006273 convOp = spv::OpUConvert;
6274 break;
6275
John Kessenich66011cb2018-03-06 16:12:04 -07006276 case glslang::EOpConvInt8ToUint16:
6277 case glslang::EOpConvInt8ToUint:
6278 case glslang::EOpConvInt8ToUint64:
6279 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006280 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006281 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006282 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006283 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006284 case glslang::EOpConvIntToUint64:
6285 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006286 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006287 case glslang::EOpConvInt64ToUint:
6288 case glslang::EOpConvUint8ToInt16:
6289 case glslang::EOpConvUint8ToInt:
6290 case glslang::EOpConvUint8ToInt64:
6291 case glslang::EOpConvUint16ToInt8:
6292 case glslang::EOpConvUint16ToInt:
6293 case glslang::EOpConvUint16ToInt64:
6294 case glslang::EOpConvUintToInt8:
6295 case glslang::EOpConvUintToInt16:
6296 case glslang::EOpConvUintToInt64:
6297 case glslang::EOpConvUint64ToInt8:
6298 case glslang::EOpConvUint64ToInt16:
6299 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006300 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006301 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006302
6303 if (builder.isInSpecConstCodeGenMode()) {
6304 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006305 switch(op) {
6306 case glslang::EOpConvInt16ToUint8:
6307 case glslang::EOpConvIntToUint8:
6308 case glslang::EOpConvInt64ToUint8:
6309 case glslang::EOpConvUint16ToInt8:
6310 case glslang::EOpConvUintToInt8:
6311 case glslang::EOpConvUint64ToInt8:
6312 zero = builder.makeUint8Constant(0);
6313 break;
6314 case glslang::EOpConvInt8ToUint16:
6315 case glslang::EOpConvIntToUint16:
6316 case glslang::EOpConvInt64ToUint16:
6317 case glslang::EOpConvUint8ToInt16:
6318 case glslang::EOpConvUintToInt16:
6319 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006320 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006321 break;
6322 case glslang::EOpConvInt8ToUint:
6323 case glslang::EOpConvInt16ToUint:
6324 case glslang::EOpConvInt64ToUint:
6325 case glslang::EOpConvUint8ToInt:
6326 case glslang::EOpConvUint16ToInt:
6327 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006328 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006329 break;
6330 case glslang::EOpConvInt8ToUint64:
6331 case glslang::EOpConvInt16ToUint64:
6332 case glslang::EOpConvIntToUint64:
6333 case glslang::EOpConvUint8ToInt64:
6334 case glslang::EOpConvUint16ToInt64:
6335 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006336 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006337 break;
6338 default:
6339 assert(false && "Default missing");
6340 break;
6341 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006342 zero = makeSmearedConstant(zero, vectorSize);
6343 // Use OpIAdd, instead of OpBitcast to do the conversion when
6344 // generating for OpSpecConstantOp instruction.
6345 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6346 }
6347 // For normal run-time conversion instruction, use OpBitcast.
6348 convOp = spv::OpBitcast;
6349 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006350 case glslang::EOpConvUint64ToPtr:
6351 convOp = spv::OpConvertUToPtr;
6352 break;
6353 case glslang::EOpConvPtrToUint64:
6354 convOp = spv::OpConvertPtrToU;
6355 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006356 case glslang::EOpConvPtrToUvec2:
6357 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006358 if (builder.isVector(operand))
6359 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6360 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006361 convOp = spv::OpBitcast;
6362 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006363#endif
6364
John Kessenich140f3df2015-06-26 16:58:36 -06006365 default:
6366 break;
6367 }
6368
6369 spv::Id result = 0;
6370 if (convOp == spv::OpNop)
6371 return result;
6372
6373 if (convOp == spv::OpSelect) {
6374 zero = makeSmearedConstant(zero, vectorSize);
6375 one = makeSmearedConstant(one, vectorSize);
6376 result = builder.createTriOp(convOp, destType, operand, one, zero);
6377 } else
6378 result = builder.createUnaryOp(convOp, destType, operand);
6379
John Kessenichead86222018-03-28 18:01:20 -06006380 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006381 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006382 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006383}
6384
6385spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6386{
6387 if (vectorSize == 0)
6388 return constant;
6389
6390 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6391 std::vector<spv::Id> components;
6392 for (int c = 0; c < vectorSize; ++c)
6393 components.push_back(constant);
6394 return builder.makeCompositeConstant(vectorTypeId, components);
6395}
6396
John Kessenich426394d2015-07-23 10:22:48 -06006397// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006398spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006399{
6400 spv::Op opCode = spv::OpNop;
6401
6402 switch (op) {
6403 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006404 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006405 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006406 opCode = spv::OpAtomicIAdd;
6407 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006408 case glslang::EOpAtomicCounterSubtract:
6409 opCode = spv::OpAtomicISub;
6410 break;
John Kessenich426394d2015-07-23 10:22:48 -06006411 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006412 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006413 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006414 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006415 break;
6416 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006417 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006418 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006419 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006420 break;
6421 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006422 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006423 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006424 opCode = spv::OpAtomicAnd;
6425 break;
6426 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006427 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006428 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006429 opCode = spv::OpAtomicOr;
6430 break;
6431 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006432 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006433 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006434 opCode = spv::OpAtomicXor;
6435 break;
6436 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006437 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006438 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006439 opCode = spv::OpAtomicExchange;
6440 break;
6441 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006442 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006443 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006444 opCode = spv::OpAtomicCompareExchange;
6445 break;
6446 case glslang::EOpAtomicCounterIncrement:
6447 opCode = spv::OpAtomicIIncrement;
6448 break;
6449 case glslang::EOpAtomicCounterDecrement:
6450 opCode = spv::OpAtomicIDecrement;
6451 break;
6452 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006453 case glslang::EOpImageAtomicLoad:
6454 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006455 opCode = spv::OpAtomicLoad;
6456 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006457 case glslang::EOpAtomicStore:
6458 case glslang::EOpImageAtomicStore:
6459 opCode = spv::OpAtomicStore;
6460 break;
John Kessenich426394d2015-07-23 10:22:48 -06006461 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006462 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006463 break;
6464 }
6465
Rex Xue8fe8b02017-09-26 15:42:56 +08006466 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6467 builder.addCapability(spv::CapabilityInt64Atomics);
6468
John Kessenich426394d2015-07-23 10:22:48 -06006469 // Sort out the operands
6470 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006471 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006472 // - compare-exchange swaps the value and comparator
6473 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006474 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006475 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6476 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6477 spv::Id scopeId;
6478 if (glslangIntermediate->usingVulkanMemoryModel()) {
6479 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6480 } else {
6481 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6482 }
6483 // semantics default to relaxed
Jeff Bolz016ddee2019-10-17 11:22:57 -05006484 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() && glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006485 spv::MemorySemanticsVolatileMask :
6486 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006487 spv::Id semanticsId2 = semanticsId;
6488
6489 pointerId = operands[0];
6490 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6491 // no additional operands
6492 } else if (opCode == spv::OpAtomicCompareExchange) {
6493 compareId = operands[1];
6494 valueId = operands[2];
6495 if (operands.size() > 3) {
6496 scopeId = operands[3];
6497 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6498 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6499 }
6500 } else if (opCode == spv::OpAtomicLoad) {
6501 if (operands.size() > 1) {
6502 scopeId = operands[1];
6503 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6504 }
6505 } else {
6506 // atomic store or RMW
6507 valueId = operands[1];
6508 if (operands.size() > 2) {
6509 scopeId = operands[2];
6510 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6511 }
Rex Xu04db3f52015-09-16 11:44:02 +08006512 }
John Kessenich426394d2015-07-23 10:22:48 -06006513
Jeff Bolz36831c92018-09-05 10:11:41 -05006514 // Check for capabilities
6515 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006516 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6517 spv::MemorySemanticsMakeVisibleKHRMask |
6518 spv::MemorySemanticsOutputMemoryKHRMask |
6519 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006520 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6521 }
John Kessenich426394d2015-07-23 10:22:48 -06006522
Jeff Bolz36831c92018-09-05 10:11:41 -05006523 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6524 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6525 }
John Kessenich48d6e792017-10-06 21:21:48 -06006526
Jeff Bolz36831c92018-09-05 10:11:41 -05006527 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6528 spvAtomicOperands.push_back(pointerId);
6529 spvAtomicOperands.push_back(scopeId);
6530 spvAtomicOperands.push_back(semanticsId);
6531 if (opCode == spv::OpAtomicCompareExchange) {
6532 spvAtomicOperands.push_back(semanticsId2);
6533 spvAtomicOperands.push_back(valueId);
6534 spvAtomicOperands.push_back(compareId);
6535 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6536 spvAtomicOperands.push_back(valueId);
6537 }
John Kessenich48d6e792017-10-06 21:21:48 -06006538
Jeff Bolz36831c92018-09-05 10:11:41 -05006539 if (opCode == spv::OpAtomicStore) {
6540 builder.createNoResultOp(opCode, spvAtomicOperands);
6541 return 0;
6542 } else {
6543 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6544
6545 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6546 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6547 if (op == glslang::EOpAtomicCounterDecrement)
6548 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6549
6550 return resultId;
6551 }
John Kessenich426394d2015-07-23 10:22:48 -06006552}
6553
John Kessenich91cef522016-05-05 16:45:40 -06006554// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006555spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006556{
John Kessenich66011cb2018-03-06 16:12:04 -07006557 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6558 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006559
Rex Xu51596642016-09-21 18:56:12 +08006560 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006561 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006562 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6563
chaocf200da82016-12-20 12:44:35 -08006564 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6565 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006566 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6567 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006568 } else if (op == glslang::EOpAnyInvocation ||
6569 op == glslang::EOpAllInvocations ||
6570 op == glslang::EOpAllInvocationsEqual) {
6571 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6572 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006573 } else {
6574 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006575 if (op == glslang::EOpMinInvocationsNonUniform ||
6576 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006577 op == glslang::EOpAddInvocationsNonUniform ||
6578 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6579 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6580 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6581 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6582 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6583 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006584 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006585
Rex Xu430ef402016-10-14 17:22:23 +08006586 switch (op) {
6587 case glslang::EOpMinInvocations:
6588 case glslang::EOpMaxInvocations:
6589 case glslang::EOpAddInvocations:
6590 case glslang::EOpMinInvocationsNonUniform:
6591 case glslang::EOpMaxInvocationsNonUniform:
6592 case glslang::EOpAddInvocationsNonUniform:
6593 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006594 break;
6595 case glslang::EOpMinInvocationsInclusiveScan:
6596 case glslang::EOpMaxInvocationsInclusiveScan:
6597 case glslang::EOpAddInvocationsInclusiveScan:
6598 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6599 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6600 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6601 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006602 break;
6603 case glslang::EOpMinInvocationsExclusiveScan:
6604 case glslang::EOpMaxInvocationsExclusiveScan:
6605 case glslang::EOpAddInvocationsExclusiveScan:
6606 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6607 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6608 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6609 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006610 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006611 default:
6612 break;
Rex Xu430ef402016-10-14 17:22:23 +08006613 }
John Kessenich149afc32018-08-14 13:31:43 -06006614 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6615 spvGroupOperands.push_back(scope);
6616 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006617 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006618 spvGroupOperands.push_back(groupOp);
6619 }
Rex Xu51596642016-09-21 18:56:12 +08006620 }
6621
John Kessenich149afc32018-08-14 13:31:43 -06006622 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6623 spv::IdImmediate op = { true, *opIt };
6624 spvGroupOperands.push_back(op);
6625 }
John Kessenich91cef522016-05-05 16:45:40 -06006626
6627 switch (op) {
6628 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006629 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006630 break;
John Kessenich91cef522016-05-05 16:45:40 -06006631 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006632 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006633 break;
John Kessenich91cef522016-05-05 16:45:40 -06006634 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006635 opCode = spv::OpSubgroupAllEqualKHR;
6636 break;
Rex Xu51596642016-09-21 18:56:12 +08006637 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006638 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006639 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006640 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006641 break;
6642 case glslang::EOpReadFirstInvocation:
6643 opCode = spv::OpSubgroupFirstInvocationKHR;
6644 break;
6645 case glslang::EOpBallot:
6646 {
6647 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6648 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6649 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6650 //
6651 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6652 //
6653 spv::Id uintType = builder.makeUintType(32);
6654 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6655 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6656
6657 std::vector<spv::Id> components;
6658 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6659 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6660
6661 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6662 return builder.createUnaryOp(spv::OpBitcast, typeId,
6663 builder.createCompositeConstruct(uvec2Type, components));
6664 }
6665
Rex Xu9d93a232016-05-05 12:30:44 +08006666 case glslang::EOpMinInvocations:
6667 case glslang::EOpMaxInvocations:
6668 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006669 case glslang::EOpMinInvocationsInclusiveScan:
6670 case glslang::EOpMaxInvocationsInclusiveScan:
6671 case glslang::EOpAddInvocationsInclusiveScan:
6672 case glslang::EOpMinInvocationsExclusiveScan:
6673 case glslang::EOpMaxInvocationsExclusiveScan:
6674 case glslang::EOpAddInvocationsExclusiveScan:
6675 if (op == glslang::EOpMinInvocations ||
6676 op == glslang::EOpMinInvocationsInclusiveScan ||
6677 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006678 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006679 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006680 else {
6681 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006682 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006683 else
Rex Xu51596642016-09-21 18:56:12 +08006684 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006685 }
Rex Xu430ef402016-10-14 17:22:23 +08006686 } else if (op == glslang::EOpMaxInvocations ||
6687 op == glslang::EOpMaxInvocationsInclusiveScan ||
6688 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006689 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006690 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006691 else {
6692 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006693 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006694 else
Rex Xu51596642016-09-21 18:56:12 +08006695 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006696 }
6697 } else {
6698 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006699 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006700 else
Rex Xu51596642016-09-21 18:56:12 +08006701 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006702 }
6703
Rex Xu2bbbe062016-08-23 15:41:05 +08006704 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006705 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006706
6707 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006708 case glslang::EOpMinInvocationsNonUniform:
6709 case glslang::EOpMaxInvocationsNonUniform:
6710 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006711 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6712 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6713 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6714 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6715 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6716 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6717 if (op == glslang::EOpMinInvocationsNonUniform ||
6718 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6719 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006720 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006721 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006722 else {
6723 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006724 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006725 else
Rex Xu51596642016-09-21 18:56:12 +08006726 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006727 }
6728 }
Rex Xu430ef402016-10-14 17:22:23 +08006729 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6730 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6731 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006732 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006733 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006734 else {
6735 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006736 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006737 else
Rex Xu51596642016-09-21 18:56:12 +08006738 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006739 }
6740 }
6741 else {
6742 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006743 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006744 else
Rex Xu51596642016-09-21 18:56:12 +08006745 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006746 }
6747
Rex Xu2bbbe062016-08-23 15:41:05 +08006748 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006749 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006750
6751 break;
John Kessenich91cef522016-05-05 16:45:40 -06006752 default:
6753 logger->missingFunctionality("invocation operation");
6754 return spv::NoResult;
6755 }
Rex Xu51596642016-09-21 18:56:12 +08006756
6757 assert(opCode != spv::OpNop);
6758 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006759}
6760
Rex Xu2bbbe062016-08-23 15:41:05 +08006761// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006762spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6763 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006764{
6765 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6766 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006767 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006768 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006769 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6770 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6771 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6772
6773 // Handle group invocation operations scalar by scalar.
6774 // The result type is the same type as the original type.
6775 // The algorithm is to:
6776 // - break the vector into scalars
6777 // - apply the operation to each scalar
6778 // - make a vector out the scalar results
6779
6780 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006781 int numComponents = builder.getNumComponents(operands[0]);
6782 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006783 std::vector<spv::Id> results;
6784
6785 // do each scalar op
6786 for (int comp = 0; comp < numComponents; ++comp) {
6787 std::vector<unsigned int> indexes;
6788 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006789 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6790 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006791 if (op == spv::OpSubgroupReadInvocationKHR) {
6792 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006793 spv::IdImmediate operand = { true, operands[1] };
6794 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006795 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006796 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6797 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006798 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006799 spv::IdImmediate operand = { true, operands[1] };
6800 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006801 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006802 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6803 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006804 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006805 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006806 spvGroupOperands.push_back(scalar);
6807 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006808
Rex Xub7072052016-09-26 15:53:40 +08006809 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006810 }
6811
6812 // put the pieces together
6813 return builder.createCompositeConstruct(typeId, results);
6814}
Rex Xu2bbbe062016-08-23 15:41:05 +08006815
John Kessenich66011cb2018-03-06 16:12:04 -07006816// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006817spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6818 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006819{
6820 // Add the required capabilities.
6821 switch (op) {
6822 case glslang::EOpSubgroupElect:
6823 builder.addCapability(spv::CapabilityGroupNonUniform);
6824 break;
6825 case glslang::EOpSubgroupAll:
6826 case glslang::EOpSubgroupAny:
6827 case glslang::EOpSubgroupAllEqual:
6828 builder.addCapability(spv::CapabilityGroupNonUniform);
6829 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6830 break;
6831 case glslang::EOpSubgroupBroadcast:
6832 case glslang::EOpSubgroupBroadcastFirst:
6833 case glslang::EOpSubgroupBallot:
6834 case glslang::EOpSubgroupInverseBallot:
6835 case glslang::EOpSubgroupBallotBitExtract:
6836 case glslang::EOpSubgroupBallotBitCount:
6837 case glslang::EOpSubgroupBallotInclusiveBitCount:
6838 case glslang::EOpSubgroupBallotExclusiveBitCount:
6839 case glslang::EOpSubgroupBallotFindLSB:
6840 case glslang::EOpSubgroupBallotFindMSB:
6841 builder.addCapability(spv::CapabilityGroupNonUniform);
6842 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6843 break;
6844 case glslang::EOpSubgroupShuffle:
6845 case glslang::EOpSubgroupShuffleXor:
6846 builder.addCapability(spv::CapabilityGroupNonUniform);
6847 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6848 break;
6849 case glslang::EOpSubgroupShuffleUp:
6850 case glslang::EOpSubgroupShuffleDown:
6851 builder.addCapability(spv::CapabilityGroupNonUniform);
6852 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6853 break;
6854 case glslang::EOpSubgroupAdd:
6855 case glslang::EOpSubgroupMul:
6856 case glslang::EOpSubgroupMin:
6857 case glslang::EOpSubgroupMax:
6858 case glslang::EOpSubgroupAnd:
6859 case glslang::EOpSubgroupOr:
6860 case glslang::EOpSubgroupXor:
6861 case glslang::EOpSubgroupInclusiveAdd:
6862 case glslang::EOpSubgroupInclusiveMul:
6863 case glslang::EOpSubgroupInclusiveMin:
6864 case glslang::EOpSubgroupInclusiveMax:
6865 case glslang::EOpSubgroupInclusiveAnd:
6866 case glslang::EOpSubgroupInclusiveOr:
6867 case glslang::EOpSubgroupInclusiveXor:
6868 case glslang::EOpSubgroupExclusiveAdd:
6869 case glslang::EOpSubgroupExclusiveMul:
6870 case glslang::EOpSubgroupExclusiveMin:
6871 case glslang::EOpSubgroupExclusiveMax:
6872 case glslang::EOpSubgroupExclusiveAnd:
6873 case glslang::EOpSubgroupExclusiveOr:
6874 case glslang::EOpSubgroupExclusiveXor:
6875 builder.addCapability(spv::CapabilityGroupNonUniform);
6876 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6877 break;
6878 case glslang::EOpSubgroupClusteredAdd:
6879 case glslang::EOpSubgroupClusteredMul:
6880 case glslang::EOpSubgroupClusteredMin:
6881 case glslang::EOpSubgroupClusteredMax:
6882 case glslang::EOpSubgroupClusteredAnd:
6883 case glslang::EOpSubgroupClusteredOr:
6884 case glslang::EOpSubgroupClusteredXor:
6885 builder.addCapability(spv::CapabilityGroupNonUniform);
6886 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6887 break;
6888 case glslang::EOpSubgroupQuadBroadcast:
6889 case glslang::EOpSubgroupQuadSwapHorizontal:
6890 case glslang::EOpSubgroupQuadSwapVertical:
6891 case glslang::EOpSubgroupQuadSwapDiagonal:
6892 builder.addCapability(spv::CapabilityGroupNonUniform);
6893 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6894 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006895 case glslang::EOpSubgroupPartitionedAdd:
6896 case glslang::EOpSubgroupPartitionedMul:
6897 case glslang::EOpSubgroupPartitionedMin:
6898 case glslang::EOpSubgroupPartitionedMax:
6899 case glslang::EOpSubgroupPartitionedAnd:
6900 case glslang::EOpSubgroupPartitionedOr:
6901 case glslang::EOpSubgroupPartitionedXor:
6902 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6903 case glslang::EOpSubgroupPartitionedInclusiveMul:
6904 case glslang::EOpSubgroupPartitionedInclusiveMin:
6905 case glslang::EOpSubgroupPartitionedInclusiveMax:
6906 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6907 case glslang::EOpSubgroupPartitionedInclusiveOr:
6908 case glslang::EOpSubgroupPartitionedInclusiveXor:
6909 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6910 case glslang::EOpSubgroupPartitionedExclusiveMul:
6911 case glslang::EOpSubgroupPartitionedExclusiveMin:
6912 case glslang::EOpSubgroupPartitionedExclusiveMax:
6913 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6914 case glslang::EOpSubgroupPartitionedExclusiveOr:
6915 case glslang::EOpSubgroupPartitionedExclusiveXor:
6916 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6917 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6918 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006919 default: assert(0 && "Unhandled subgroup operation!");
6920 }
6921
Jeff Bolzc5b669e2019-09-08 08:49:18 -05006922
6923 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
6924 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07006925 const bool isBool = typeProxy == glslang::EbtBool;
6926
6927 spv::Op opCode = spv::OpNop;
6928
6929 // Figure out which opcode to use.
6930 switch (op) {
6931 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6932 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6933 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6934 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6935 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6936 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6937 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6938 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6939 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6940 case glslang::EOpSubgroupBallotBitCount:
6941 case glslang::EOpSubgroupBallotInclusiveBitCount:
6942 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6943 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6944 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6945 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6946 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6947 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6948 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6949 case glslang::EOpSubgroupAdd:
6950 case glslang::EOpSubgroupInclusiveAdd:
6951 case glslang::EOpSubgroupExclusiveAdd:
6952 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006953 case glslang::EOpSubgroupPartitionedAdd:
6954 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6955 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006956 if (isFloat) {
6957 opCode = spv::OpGroupNonUniformFAdd;
6958 } else {
6959 opCode = spv::OpGroupNonUniformIAdd;
6960 }
6961 break;
6962 case glslang::EOpSubgroupMul:
6963 case glslang::EOpSubgroupInclusiveMul:
6964 case glslang::EOpSubgroupExclusiveMul:
6965 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006966 case glslang::EOpSubgroupPartitionedMul:
6967 case glslang::EOpSubgroupPartitionedInclusiveMul:
6968 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006969 if (isFloat) {
6970 opCode = spv::OpGroupNonUniformFMul;
6971 } else {
6972 opCode = spv::OpGroupNonUniformIMul;
6973 }
6974 break;
6975 case glslang::EOpSubgroupMin:
6976 case glslang::EOpSubgroupInclusiveMin:
6977 case glslang::EOpSubgroupExclusiveMin:
6978 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006979 case glslang::EOpSubgroupPartitionedMin:
6980 case glslang::EOpSubgroupPartitionedInclusiveMin:
6981 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006982 if (isFloat) {
6983 opCode = spv::OpGroupNonUniformFMin;
6984 } else if (isUnsigned) {
6985 opCode = spv::OpGroupNonUniformUMin;
6986 } else {
6987 opCode = spv::OpGroupNonUniformSMin;
6988 }
6989 break;
6990 case glslang::EOpSubgroupMax:
6991 case glslang::EOpSubgroupInclusiveMax:
6992 case glslang::EOpSubgroupExclusiveMax:
6993 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006994 case glslang::EOpSubgroupPartitionedMax:
6995 case glslang::EOpSubgroupPartitionedInclusiveMax:
6996 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006997 if (isFloat) {
6998 opCode = spv::OpGroupNonUniformFMax;
6999 } else if (isUnsigned) {
7000 opCode = spv::OpGroupNonUniformUMax;
7001 } else {
7002 opCode = spv::OpGroupNonUniformSMax;
7003 }
7004 break;
7005 case glslang::EOpSubgroupAnd:
7006 case glslang::EOpSubgroupInclusiveAnd:
7007 case glslang::EOpSubgroupExclusiveAnd:
7008 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007009 case glslang::EOpSubgroupPartitionedAnd:
7010 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7011 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007012 if (isBool) {
7013 opCode = spv::OpGroupNonUniformLogicalAnd;
7014 } else {
7015 opCode = spv::OpGroupNonUniformBitwiseAnd;
7016 }
7017 break;
7018 case glslang::EOpSubgroupOr:
7019 case glslang::EOpSubgroupInclusiveOr:
7020 case glslang::EOpSubgroupExclusiveOr:
7021 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007022 case glslang::EOpSubgroupPartitionedOr:
7023 case glslang::EOpSubgroupPartitionedInclusiveOr:
7024 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007025 if (isBool) {
7026 opCode = spv::OpGroupNonUniformLogicalOr;
7027 } else {
7028 opCode = spv::OpGroupNonUniformBitwiseOr;
7029 }
7030 break;
7031 case glslang::EOpSubgroupXor:
7032 case glslang::EOpSubgroupInclusiveXor:
7033 case glslang::EOpSubgroupExclusiveXor:
7034 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007035 case glslang::EOpSubgroupPartitionedXor:
7036 case glslang::EOpSubgroupPartitionedInclusiveXor:
7037 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007038 if (isBool) {
7039 opCode = spv::OpGroupNonUniformLogicalXor;
7040 } else {
7041 opCode = spv::OpGroupNonUniformBitwiseXor;
7042 }
7043 break;
7044 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7045 case glslang::EOpSubgroupQuadSwapHorizontal:
7046 case glslang::EOpSubgroupQuadSwapVertical:
7047 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7048 default: assert(0 && "Unhandled subgroup operation!");
7049 }
7050
John Kessenich149afc32018-08-14 13:31:43 -06007051 // get the right Group Operation
7052 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007053 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007054 default:
7055 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007056 case glslang::EOpSubgroupBallotBitCount:
7057 case glslang::EOpSubgroupAdd:
7058 case glslang::EOpSubgroupMul:
7059 case glslang::EOpSubgroupMin:
7060 case glslang::EOpSubgroupMax:
7061 case glslang::EOpSubgroupAnd:
7062 case glslang::EOpSubgroupOr:
7063 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007064 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007065 break;
7066 case glslang::EOpSubgroupBallotInclusiveBitCount:
7067 case glslang::EOpSubgroupInclusiveAdd:
7068 case glslang::EOpSubgroupInclusiveMul:
7069 case glslang::EOpSubgroupInclusiveMin:
7070 case glslang::EOpSubgroupInclusiveMax:
7071 case glslang::EOpSubgroupInclusiveAnd:
7072 case glslang::EOpSubgroupInclusiveOr:
7073 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007074 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007075 break;
7076 case glslang::EOpSubgroupBallotExclusiveBitCount:
7077 case glslang::EOpSubgroupExclusiveAdd:
7078 case glslang::EOpSubgroupExclusiveMul:
7079 case glslang::EOpSubgroupExclusiveMin:
7080 case glslang::EOpSubgroupExclusiveMax:
7081 case glslang::EOpSubgroupExclusiveAnd:
7082 case glslang::EOpSubgroupExclusiveOr:
7083 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007084 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007085 break;
7086 case glslang::EOpSubgroupClusteredAdd:
7087 case glslang::EOpSubgroupClusteredMul:
7088 case glslang::EOpSubgroupClusteredMin:
7089 case glslang::EOpSubgroupClusteredMax:
7090 case glslang::EOpSubgroupClusteredAnd:
7091 case glslang::EOpSubgroupClusteredOr:
7092 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007093 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007094 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007095 case glslang::EOpSubgroupPartitionedAdd:
7096 case glslang::EOpSubgroupPartitionedMul:
7097 case glslang::EOpSubgroupPartitionedMin:
7098 case glslang::EOpSubgroupPartitionedMax:
7099 case glslang::EOpSubgroupPartitionedAnd:
7100 case glslang::EOpSubgroupPartitionedOr:
7101 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007102 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007103 break;
7104 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7105 case glslang::EOpSubgroupPartitionedInclusiveMul:
7106 case glslang::EOpSubgroupPartitionedInclusiveMin:
7107 case glslang::EOpSubgroupPartitionedInclusiveMax:
7108 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7109 case glslang::EOpSubgroupPartitionedInclusiveOr:
7110 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007111 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007112 break;
7113 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7114 case glslang::EOpSubgroupPartitionedExclusiveMul:
7115 case glslang::EOpSubgroupPartitionedExclusiveMin:
7116 case glslang::EOpSubgroupPartitionedExclusiveMax:
7117 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7118 case glslang::EOpSubgroupPartitionedExclusiveOr:
7119 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007120 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007121 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007122 }
7123
John Kessenich149afc32018-08-14 13:31:43 -06007124 // build the instruction
7125 std::vector<spv::IdImmediate> spvGroupOperands;
7126
7127 // Every operation begins with the Execution Scope operand.
7128 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7129 spvGroupOperands.push_back(executionScope);
7130
7131 // Next, for all operations that use a Group Operation, push that as an operand.
7132 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007133 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007134 spvGroupOperands.push_back(groupOperand);
7135 }
7136
John Kessenich66011cb2018-03-06 16:12:04 -07007137 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007138 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7139 spv::IdImmediate operand = { true, *opIt };
7140 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007141 }
7142
7143 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007144 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007145 switch (op) {
7146 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007147 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7148 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7149 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7150 }
7151 if (directionId != spv::NoResult) {
7152 spv::IdImmediate direction = { true, directionId };
7153 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007154 }
7155
7156 return builder.createOp(opCode, typeId, spvGroupOperands);
7157}
7158
John Kessenich5e4b1242015-08-06 22:53:06 -06007159spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007160{
John Kessenich66011cb2018-03-06 16:12:04 -07007161 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7162 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007163
John Kessenich140f3df2015-06-26 16:58:36 -06007164 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007165 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007166 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007167 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007168 spv::Id typeId0 = 0;
7169 if (consumedOperands > 0)
7170 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007171 spv::Id typeId1 = 0;
7172 if (consumedOperands > 1)
7173 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007174 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007175
7176 switch (op) {
7177 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007178 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007179 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007180 else if (isUnsigned)
7181 libCall = spv::GLSLstd450UMin;
7182 else
7183 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007184 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007185 break;
7186 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007187 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007188 break;
7189 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007190 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007191 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007192 else if (isUnsigned)
7193 libCall = spv::GLSLstd450UMax;
7194 else
7195 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007196 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007197 break;
7198 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007199 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007200 break;
7201 case glslang::EOpDot:
7202 opCode = spv::OpDot;
7203 break;
7204 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007205 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007206 break;
7207
7208 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007209 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007210 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007211 else if (isUnsigned)
7212 libCall = spv::GLSLstd450UClamp;
7213 else
7214 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007215 builder.promoteScalar(precision, operands.front(), operands[1]);
7216 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007217 break;
7218 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007219 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7220 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007221 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007222 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007223 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007224 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007225 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007226 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007227 break;
7228 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007229 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007230 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007231 break;
7232 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007233 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007234 builder.promoteScalar(precision, operands[0], operands[2]);
7235 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007236 break;
7237
7238 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007239 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007240 break;
7241 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007242 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007243 break;
7244 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007245 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007246 break;
7247 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007248 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007249 break;
7250 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007251 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007252 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007253 case glslang::EOpBarrier:
7254 {
7255 // This is for the extended controlBarrier function, with four operands.
7256 // The unextended barrier() goes through createNoArgOperation.
7257 assert(operands.size() == 4);
7258 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7259 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7260 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7261 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7262 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7263 spv::MemorySemanticsMakeVisibleKHRMask |
7264 spv::MemorySemanticsOutputMemoryKHRMask |
7265 spv::MemorySemanticsVolatileMask)) {
7266 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7267 }
7268 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7269 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7270 }
7271 return 0;
7272 }
7273 break;
7274 case glslang::EOpMemoryBarrier:
7275 {
7276 // This is for the extended memoryBarrier function, with three operands.
7277 // The unextended memoryBarrier() goes through createNoArgOperation.
7278 assert(operands.size() == 3);
7279 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7280 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7281 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7282 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7283 spv::MemorySemanticsMakeVisibleKHRMask |
7284 spv::MemorySemanticsOutputMemoryKHRMask |
7285 spv::MemorySemanticsVolatileMask)) {
7286 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7287 }
7288 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7289 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7290 }
7291 return 0;
7292 }
7293 break;
7294
John Kessenicha28f7a72019-08-06 07:00:58 -06007295#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007296 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007297 if (typeProxy == glslang::EbtFloat16)
7298 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007299 libCall = spv::GLSLstd450InterpolateAtSample;
7300 break;
7301 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007302 if (typeProxy == glslang::EbtFloat16)
7303 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007304 libCall = spv::GLSLstd450InterpolateAtOffset;
7305 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007306 case glslang::EOpAddCarry:
7307 opCode = spv::OpIAddCarry;
7308 typeId = builder.makeStructResultType(typeId0, typeId0);
7309 consumedOperands = 2;
7310 break;
7311 case glslang::EOpSubBorrow:
7312 opCode = spv::OpISubBorrow;
7313 typeId = builder.makeStructResultType(typeId0, typeId0);
7314 consumedOperands = 2;
7315 break;
7316 case glslang::EOpUMulExtended:
7317 opCode = spv::OpUMulExtended;
7318 typeId = builder.makeStructResultType(typeId0, typeId0);
7319 consumedOperands = 2;
7320 break;
7321 case glslang::EOpIMulExtended:
7322 opCode = spv::OpSMulExtended;
7323 typeId = builder.makeStructResultType(typeId0, typeId0);
7324 consumedOperands = 2;
7325 break;
7326 case glslang::EOpBitfieldExtract:
7327 if (isUnsigned)
7328 opCode = spv::OpBitFieldUExtract;
7329 else
7330 opCode = spv::OpBitFieldSExtract;
7331 break;
7332 case glslang::EOpBitfieldInsert:
7333 opCode = spv::OpBitFieldInsert;
7334 break;
7335
7336 case glslang::EOpFma:
7337 libCall = spv::GLSLstd450Fma;
7338 break;
7339 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007340 {
7341 libCall = spv::GLSLstd450FrexpStruct;
7342 assert(builder.isPointerType(typeId1));
7343 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007344 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007345 if (width == 16)
7346 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7347 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007348 if (builder.getNumComponents(operands[0]) == 1)
7349 frexpIntType = builder.makeIntegerType(width, true);
7350 else
7351 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7352 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7353 consumedOperands = 1;
7354 }
John Kessenich55e7d112015-11-15 21:33:39 -07007355 break;
7356 case glslang::EOpLdexp:
7357 libCall = spv::GLSLstd450Ldexp;
7358 break;
7359
Rex Xu574ab042016-04-14 16:53:07 +08007360 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007361 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007362
John Kessenich66011cb2018-03-06 16:12:04 -07007363 case glslang::EOpSubgroupBroadcast:
7364 case glslang::EOpSubgroupBallotBitExtract:
7365 case glslang::EOpSubgroupShuffle:
7366 case glslang::EOpSubgroupShuffleXor:
7367 case glslang::EOpSubgroupShuffleUp:
7368 case glslang::EOpSubgroupShuffleDown:
7369 case glslang::EOpSubgroupClusteredAdd:
7370 case glslang::EOpSubgroupClusteredMul:
7371 case glslang::EOpSubgroupClusteredMin:
7372 case glslang::EOpSubgroupClusteredMax:
7373 case glslang::EOpSubgroupClusteredAnd:
7374 case glslang::EOpSubgroupClusteredOr:
7375 case glslang::EOpSubgroupClusteredXor:
7376 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007377 case glslang::EOpSubgroupPartitionedAdd:
7378 case glslang::EOpSubgroupPartitionedMul:
7379 case glslang::EOpSubgroupPartitionedMin:
7380 case glslang::EOpSubgroupPartitionedMax:
7381 case glslang::EOpSubgroupPartitionedAnd:
7382 case glslang::EOpSubgroupPartitionedOr:
7383 case glslang::EOpSubgroupPartitionedXor:
7384 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7385 case glslang::EOpSubgroupPartitionedInclusiveMul:
7386 case glslang::EOpSubgroupPartitionedInclusiveMin:
7387 case glslang::EOpSubgroupPartitionedInclusiveMax:
7388 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7389 case glslang::EOpSubgroupPartitionedInclusiveOr:
7390 case glslang::EOpSubgroupPartitionedInclusiveXor:
7391 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7392 case glslang::EOpSubgroupPartitionedExclusiveMul:
7393 case glslang::EOpSubgroupPartitionedExclusiveMin:
7394 case glslang::EOpSubgroupPartitionedExclusiveMax:
7395 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7396 case glslang::EOpSubgroupPartitionedExclusiveOr:
7397 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007398 return createSubgroupOperation(op, typeId, operands, typeProxy);
7399
Rex Xu9d93a232016-05-05 12:30:44 +08007400 case glslang::EOpSwizzleInvocations:
7401 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7402 libCall = spv::SwizzleInvocationsAMD;
7403 break;
7404 case glslang::EOpSwizzleInvocationsMasked:
7405 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7406 libCall = spv::SwizzleInvocationsMaskedAMD;
7407 break;
7408 case glslang::EOpWriteInvocation:
7409 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7410 libCall = spv::WriteInvocationAMD;
7411 break;
7412
7413 case glslang::EOpMin3:
7414 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7415 if (isFloat)
7416 libCall = spv::FMin3AMD;
7417 else {
7418 if (isUnsigned)
7419 libCall = spv::UMin3AMD;
7420 else
7421 libCall = spv::SMin3AMD;
7422 }
7423 break;
7424 case glslang::EOpMax3:
7425 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7426 if (isFloat)
7427 libCall = spv::FMax3AMD;
7428 else {
7429 if (isUnsigned)
7430 libCall = spv::UMax3AMD;
7431 else
7432 libCall = spv::SMax3AMD;
7433 }
7434 break;
7435 case glslang::EOpMid3:
7436 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7437 if (isFloat)
7438 libCall = spv::FMid3AMD;
7439 else {
7440 if (isUnsigned)
7441 libCall = spv::UMid3AMD;
7442 else
7443 libCall = spv::SMid3AMD;
7444 }
7445 break;
7446
7447 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007448 if (typeProxy == glslang::EbtFloat16)
7449 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007450 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7451 libCall = spv::InterpolateAtVertexAMD;
7452 break;
Chao Chen3c366992018-09-19 11:41:59 -07007453
Chao Chenb50c02e2018-09-19 11:42:24 -07007454 case glslang::EOpReportIntersectionNV:
7455 {
7456 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007457 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007458 }
7459 break;
7460 case glslang::EOpTraceNV:
7461 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007462 builder.createNoResultOp(spv::OpTraceNV, operands);
7463 return 0;
7464 }
7465 break;
7466 case glslang::EOpExecuteCallableNV:
7467 {
7468 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007469 return 0;
7470 }
7471 break;
Chao Chen3c366992018-09-19 11:41:59 -07007472 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7473 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7474 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007475 case glslang::EOpCooperativeMatrixMulAdd:
7476 opCode = spv::OpCooperativeMatrixMulAddNV;
7477 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007478#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007479 default:
7480 return 0;
7481 }
7482
7483 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007484 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007485 // Use an extended instruction from the standard library.
7486 // Construct the call arguments, without modifying the original operands vector.
7487 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7488 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007489 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007490 } else if (opCode == spv::OpDot && !isFloat) {
7491 // int dot(int, int)
7492 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7493 const int componentCount = builder.getNumComponents(operands[0]);
7494 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7495 builder.setPrecision(mulOp, precision);
7496 id = builder.createCompositeExtract(mulOp, typeId, 0);
7497 for (int i = 1; i < componentCount; ++i) {
7498 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007499 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007500 }
John Kessenich2359bd02015-12-06 19:29:11 -07007501 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007502 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007503 case 0:
7504 // should all be handled by visitAggregate and createNoArgOperation
7505 assert(0);
7506 return 0;
7507 case 1:
7508 // should all be handled by createUnaryOperation
7509 assert(0);
7510 return 0;
7511 case 2:
7512 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7513 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007514 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007515 // anything 3 or over doesn't have l-value operands, so all should be consumed
7516 assert(consumedOperands == operands.size());
7517 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007518 break;
7519 }
7520 }
7521
John Kessenichb9197c82019-08-11 07:41:45 -06007522#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007523 // Decode the return types that were structures
7524 switch (op) {
7525 case glslang::EOpAddCarry:
7526 case glslang::EOpSubBorrow:
7527 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7528 id = builder.createCompositeExtract(id, typeId0, 0);
7529 break;
7530 case glslang::EOpUMulExtended:
7531 case glslang::EOpIMulExtended:
7532 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7533 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7534 break;
7535 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007536 {
7537 assert(operands.size() == 2);
7538 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7539 // "exp" is floating-point type (from HLSL intrinsic)
7540 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7541 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7542 builder.createStore(member1, operands[1]);
7543 } else
7544 // "exp" is integer type (from GLSL built-in function)
7545 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7546 id = builder.createCompositeExtract(id, typeId0, 0);
7547 }
John Kessenich55e7d112015-11-15 21:33:39 -07007548 break;
7549 default:
7550 break;
7551 }
John Kessenichb9197c82019-08-11 07:41:45 -06007552#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007553
John Kessenich32cfd492016-02-02 12:37:46 -07007554 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007555}
7556
Rex Xu9d93a232016-05-05 12:30:44 +08007557// Intrinsics with no arguments (or no return value, and no precision).
7558spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007559{
Jeff Bolz36831c92018-09-05 10:11:41 -05007560 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7561 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007562
7563 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007564 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007565 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007566 if (glslangIntermediate->usingVulkanMemoryModel()) {
7567 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7568 spv::MemorySemanticsOutputMemoryKHRMask |
7569 spv::MemorySemanticsAcquireReleaseMask);
7570 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7571 } else {
7572 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7573 }
John Kessenich82979362017-12-11 04:02:24 -07007574 } else {
7575 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7576 spv::MemorySemanticsWorkgroupMemoryMask |
7577 spv::MemorySemanticsAcquireReleaseMask);
7578 }
John Kessenich140f3df2015-06-26 16:58:36 -06007579 return 0;
7580 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007581 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7582 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007583 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007584 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007585 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7586 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007587 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007588 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007589 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7590 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007591 return 0;
7592 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007593 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7594 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007595 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007596#ifndef GLSLANG_WEB
7597 case glslang::EOpMemoryBarrierAtomicCounter:
7598 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7599 spv::MemorySemanticsAcquireReleaseMask);
7600 return 0;
7601 case glslang::EOpMemoryBarrierImage:
7602 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7603 spv::MemorySemanticsAcquireReleaseMask);
7604 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007605 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007606 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007607 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007608 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007609 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007610 case glslang::EOpDeviceMemoryBarrier:
7611 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7612 spv::MemorySemanticsImageMemoryMask |
7613 spv::MemorySemanticsAcquireReleaseMask);
7614 return 0;
7615 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7616 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7617 spv::MemorySemanticsImageMemoryMask |
7618 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007619 return 0;
7620 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007621 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7622 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007623 return 0;
7624 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007625 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7626 spv::MemorySemanticsWorkgroupMemoryMask |
7627 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007628 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007629 case glslang::EOpSubgroupBarrier:
7630 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7631 spv::MemorySemanticsAcquireReleaseMask);
7632 return spv::NoResult;
7633 case glslang::EOpSubgroupMemoryBarrier:
7634 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7635 spv::MemorySemanticsAcquireReleaseMask);
7636 return spv::NoResult;
7637 case glslang::EOpSubgroupMemoryBarrierBuffer:
7638 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7639 spv::MemorySemanticsAcquireReleaseMask);
7640 return spv::NoResult;
7641 case glslang::EOpSubgroupMemoryBarrierImage:
7642 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7643 spv::MemorySemanticsAcquireReleaseMask);
7644 return spv::NoResult;
7645 case glslang::EOpSubgroupMemoryBarrierShared:
7646 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7647 spv::MemorySemanticsAcquireReleaseMask);
7648 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007649
7650 case glslang::EOpEmitVertex:
7651 builder.createNoResultOp(spv::OpEmitVertex);
7652 return 0;
7653 case glslang::EOpEndPrimitive:
7654 builder.createNoResultOp(spv::OpEndPrimitive);
7655 return 0;
7656
John Kessenich66011cb2018-03-06 16:12:04 -07007657 case glslang::EOpSubgroupElect: {
7658 std::vector<spv::Id> operands;
7659 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7660 }
Rex Xu9d93a232016-05-05 12:30:44 +08007661 case glslang::EOpTime:
7662 {
7663 std::vector<spv::Id> args; // Dummy arguments
7664 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7665 return builder.setPrecision(id, precision);
7666 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007667 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007668 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007669 return 0;
7670 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007671 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007672 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007673
7674 case glslang::EOpBeginInvocationInterlock:
7675 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7676 return 0;
7677 case glslang::EOpEndInvocationInterlock:
7678 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7679 return 0;
7680
Jeff Bolzba6170b2019-07-01 09:23:23 -05007681 case glslang::EOpIsHelperInvocation:
7682 {
7683 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007684 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7685 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7686 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007687 }
7688
amhagan91fb0092019-07-10 21:14:38 -04007689 case glslang::EOpReadClockSubgroupKHR: {
7690 std::vector<spv::Id> args;
7691 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7692 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7693 builder.addCapability(spv::CapabilityShaderClockKHR);
7694 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7695 }
7696
7697 case glslang::EOpReadClockDeviceKHR: {
7698 std::vector<spv::Id> args;
7699 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7700 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7701 builder.addCapability(spv::CapabilityShaderClockKHR);
7702 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7703 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06007704#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007705 default:
John Kessenich155d3512019-08-08 23:29:20 -06007706 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007707 }
John Kessenich155d3512019-08-08 23:29:20 -06007708
7709 logger->missingFunctionality("unknown operation with no arguments");
7710
7711 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007712}
7713
7714spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7715{
John Kessenich2f273362015-07-18 22:34:27 -06007716 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007717 spv::Id id;
7718 if (symbolValues.end() != iter) {
7719 id = iter->second;
7720 return id;
7721 }
7722
7723 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007724 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7725 auto forcedType = getForcedType(builtIn, symbol->getType());
7726 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007727 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007728 if (forcedType.second != spv::NoType)
7729 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007730
Rex Xuc884b4a2016-06-29 15:03:44 +08007731 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007732 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7733 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7734 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007735#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007736 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007737 if (symbol->getQualifier().hasComponent())
7738 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7739 if (symbol->getQualifier().hasIndex())
7740 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007741#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007742 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007743 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007744 // atomic counters use this:
7745 if (symbol->getQualifier().hasOffset())
7746 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007747 }
7748
scygan2c864272016-05-18 18:09:17 +02007749 if (symbol->getQualifier().hasLocation())
7750 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007751 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007752 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007753 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007754 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007755 }
John Kessenich140f3df2015-06-26 16:58:36 -06007756 if (symbol->getQualifier().hasSet())
7757 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007758 else if (IsDescriptorResource(symbol->getType())) {
7759 // default to 0
7760 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7761 }
John Kessenich140f3df2015-06-26 16:58:36 -06007762 if (symbol->getQualifier().hasBinding())
7763 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007764 else if (IsDescriptorResource(symbol->getType())) {
7765 // default to 0
7766 builder.addDecoration(id, spv::DecorationBinding, 0);
7767 }
John Kessenich6c292d32016-02-15 20:58:50 -07007768 if (symbol->getQualifier().hasAttachment())
7769 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007770 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007771 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007772 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007773 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007774 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7775 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7776 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7777 }
7778 if (symbol->getQualifier().hasXfbOffset())
7779 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007780 }
7781
John Kessenichb9197c82019-08-11 07:41:45 -06007782 // add built-in variable decoration
7783 if (builtIn != spv::BuiltInMax) {
7784 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7785 }
7786
7787#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007788 if (symbol->getType().isImage()) {
7789 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007790 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007791 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007792 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007793 }
7794
John Kessenich5611c6d2018-04-05 11:25:02 -06007795 // nonuniform
7796 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7797
chaoc0ad6a4e2016-12-19 16:29:34 -08007798 if (builtIn == spv::BuiltInSampleMask) {
7799 spv::Decoration decoration;
7800 // GL_NV_sample_mask_override_coverage extension
7801 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007802 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007803 else
7804 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007805 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007806 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007807 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007808 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7809 }
7810 }
chaoc771d89f2017-01-13 01:10:53 -08007811 else if (builtIn == spv::BuiltInLayer) {
7812 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007813 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007814 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007815 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7816 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7817 }
John Kessenichb41bff62017-08-11 13:07:17 -06007818 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007819 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7820 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007821 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7822 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7823 }
7824 }
7825
chaoc6e5acae2016-12-20 13:28:52 -08007826 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007827 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007828 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007829 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7830 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007831 if (symbol->getQualifier().pervertexNV) {
7832 builder.addDecoration(id, spv::DecorationPerVertexNV);
7833 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7834 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7835 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007836
John Kessenich5d610ee2018-03-07 18:05:55 -07007837 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7838 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7839 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7840 symbol->getType().getQualifier().semanticName);
7841 }
7842
John Kessenich7015bd62019-08-01 03:28:08 -06007843 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007844 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7845 }
John Kessenichb9197c82019-08-11 07:41:45 -06007846#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007847
John Kessenich140f3df2015-06-26 16:58:36 -06007848 return id;
7849}
7850
John Kessenicha28f7a72019-08-06 07:00:58 -06007851#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007852// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7853void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7854{
7855 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007856 if (qualifier.perPrimitiveNV) {
7857 // Need to add capability/extension for fragment shader.
7858 // Mesh shader already adds this by default.
7859 if (glslangIntermediate->getStage() == EShLangFragment) {
7860 builder.addCapability(spv::CapabilityMeshShadingNV);
7861 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7862 }
Chao Chen3c366992018-09-19 11:41:59 -07007863 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007864 }
Chao Chen3c366992018-09-19 11:41:59 -07007865 if (qualifier.perViewNV)
7866 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7867 if (qualifier.perTaskNV)
7868 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7869 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007870 if (qualifier.perPrimitiveNV) {
7871 // Need to add capability/extension for fragment shader.
7872 // Mesh shader already adds this by default.
7873 if (glslangIntermediate->getStage() == EShLangFragment) {
7874 builder.addCapability(spv::CapabilityMeshShadingNV);
7875 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7876 }
Chao Chen3c366992018-09-19 11:41:59 -07007877 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007878 }
Chao Chen3c366992018-09-19 11:41:59 -07007879 if (qualifier.perViewNV)
7880 builder.addDecoration(id, spv::DecorationPerViewNV);
7881 if (qualifier.perTaskNV)
7882 builder.addDecoration(id, spv::DecorationPerTaskNV);
7883 }
7884}
7885#endif
7886
John Kessenich55e7d112015-11-15 21:33:39 -07007887// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007888// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007889//
7890// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7891//
7892// Recursively walk the nodes. The nodes form a tree whose leaves are
7893// regular constants, which themselves are trees that createSpvConstant()
7894// recursively walks. So, this function walks the "top" of the tree:
7895// - emit specialization constant-building instructions for specConstant
7896// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007897spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007898{
John Kessenich7cc0e282016-03-20 00:46:02 -06007899 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007900
qining4f4bb812016-04-03 23:55:17 -04007901 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007902 if (! node.getQualifier().specConstant) {
7903 // hand off to the non-spec-constant path
7904 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7905 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007906 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007907 nextConst, false);
7908 }
7909
7910 // We now know we have a specialization constant to build
7911
John Kessenichd94c0032016-05-30 19:29:40 -06007912 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007913 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7914 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7915 std::vector<spv::Id> dimConstId;
7916 for (int dim = 0; dim < 3; ++dim) {
7917 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7918 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007919 if (specConst) {
7920 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7921 glslangIntermediate->getLocalSizeSpecId(dim));
7922 }
qining4f4bb812016-04-03 23:55:17 -04007923 }
7924 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7925 }
7926
7927 // An AST node labelled as specialization constant should be a symbol node.
7928 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7929 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007930 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007931 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007932 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7933 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7934 // will set the builder into spec constant op instruction generating mode.
7935 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007936 result = accessChainLoad(sub_tree->getType());
7937 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007938 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007939 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007940 } else {
7941 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007942 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007943 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007944 builder.addName(result, sn->getName().c_str());
7945 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007946 }
qining4f4bb812016-04-03 23:55:17 -04007947
7948 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7949 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007950 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007951 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007952}
7953
John Kessenich140f3df2015-06-26 16:58:36 -06007954// Use 'consts' as the flattened glslang source of scalar constants to recursively
7955// build the aggregate SPIR-V constant.
7956//
7957// If there are not enough elements present in 'consts', 0 will be substituted;
7958// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7959//
qining08408382016-03-21 09:51:37 -04007960spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007961{
7962 // vector of constants for SPIR-V
7963 std::vector<spv::Id> spvConsts;
7964
7965 // Type is used for struct and array constants
7966 spv::Id typeId = convertGlslangToSpvType(glslangType);
7967
7968 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007969 glslang::TType elementType(glslangType, 0);
7970 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007971 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007972 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007973 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007974 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007975 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007976 } else if (glslangType.isCoopMat()) {
7977 glslang::TType componentType(glslangType.getBasicType());
7978 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007979 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007980 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7981 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007982 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007983 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007984 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7985 bool zero = nextConst >= consts.size();
7986 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007987 case glslang::EbtInt:
7988 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7989 break;
7990 case glslang::EbtUint:
7991 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7992 break;
7993 case glslang::EbtFloat:
7994 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7995 break;
7996 case glslang::EbtBool:
7997 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7998 break;
7999#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008000 case glslang::EbtInt8:
8001 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8002 break;
8003 case glslang::EbtUint8:
8004 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8005 break;
8006 case glslang::EbtInt16:
8007 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8008 break;
8009 case glslang::EbtUint16:
8010 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8011 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008012 case glslang::EbtInt64:
8013 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8014 break;
8015 case glslang::EbtUint64:
8016 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8017 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008018 case glslang::EbtDouble:
8019 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8020 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008021 case glslang::EbtFloat16:
8022 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8023 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008024#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008025 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008026 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008027 break;
8028 }
8029 ++nextConst;
8030 }
8031 } else {
8032 // we have a non-aggregate (scalar) constant
8033 bool zero = nextConst >= consts.size();
8034 spv::Id scalar = 0;
8035 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008036 case glslang::EbtInt:
8037 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8038 break;
8039 case glslang::EbtUint:
8040 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8041 break;
8042 case glslang::EbtFloat:
8043 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8044 break;
8045 case glslang::EbtBool:
8046 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8047 break;
8048#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008049 case glslang::EbtInt8:
8050 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8051 break;
8052 case glslang::EbtUint8:
8053 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8054 break;
8055 case glslang::EbtInt16:
8056 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8057 break;
8058 case glslang::EbtUint16:
8059 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8060 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008061 case glslang::EbtInt64:
8062 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8063 break;
8064 case glslang::EbtUint64:
8065 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8066 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008067 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008068 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008069 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008070 case glslang::EbtFloat16:
8071 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8072 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008073 case glslang::EbtReference:
8074 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8075 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8076 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008077#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008078 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008079 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008080 break;
8081 }
8082 ++nextConst;
8083 return scalar;
8084 }
8085
8086 return builder.makeCompositeConstant(typeId, spvConsts);
8087}
8088
John Kessenich7c1aa102015-10-15 13:29:11 -06008089// Return true if the node is a constant or symbol whose reading has no
8090// non-trivial observable cost or effect.
8091bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8092{
8093 // don't know what this is
8094 if (node == nullptr)
8095 return false;
8096
8097 // a constant is safe
8098 if (node->getAsConstantUnion() != nullptr)
8099 return true;
8100
8101 // not a symbol means non-trivial
8102 if (node->getAsSymbolNode() == nullptr)
8103 return false;
8104
8105 // a symbol, depends on what's being read
8106 switch (node->getType().getQualifier().storage) {
8107 case glslang::EvqTemporary:
8108 case glslang::EvqGlobal:
8109 case glslang::EvqIn:
8110 case glslang::EvqInOut:
8111 case glslang::EvqConst:
8112 case glslang::EvqConstReadOnly:
8113 case glslang::EvqUniform:
8114 return true;
8115 default:
8116 return false;
8117 }
qining25262b32016-05-06 17:25:16 -04008118}
John Kessenich7c1aa102015-10-15 13:29:11 -06008119
8120// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008121// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008122// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008123// Return true if trivial.
8124bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8125{
8126 if (node == nullptr)
8127 return false;
8128
John Kessenich84cc15f2017-05-24 16:44:47 -06008129 // count non scalars as trivial, as well as anything coming from HLSL
8130 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008131 return true;
8132
John Kessenich7c1aa102015-10-15 13:29:11 -06008133 // symbols and constants are trivial
8134 if (isTrivialLeaf(node))
8135 return true;
8136
8137 // otherwise, it needs to be a simple operation or one or two leaf nodes
8138
8139 // not a simple operation
8140 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8141 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8142 if (binaryNode == nullptr && unaryNode == nullptr)
8143 return false;
8144
8145 // not on leaf nodes
8146 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8147 return false;
8148
8149 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8150 return false;
8151 }
8152
8153 switch (node->getAsOperator()->getOp()) {
8154 case glslang::EOpLogicalNot:
8155 case glslang::EOpConvIntToBool:
8156 case glslang::EOpConvUintToBool:
8157 case glslang::EOpConvFloatToBool:
8158 case glslang::EOpConvDoubleToBool:
8159 case glslang::EOpEqual:
8160 case glslang::EOpNotEqual:
8161 case glslang::EOpLessThan:
8162 case glslang::EOpGreaterThan:
8163 case glslang::EOpLessThanEqual:
8164 case glslang::EOpGreaterThanEqual:
8165 case glslang::EOpIndexDirect:
8166 case glslang::EOpIndexDirectStruct:
8167 case glslang::EOpLogicalXor:
8168 case glslang::EOpAny:
8169 case glslang::EOpAll:
8170 return true;
8171 default:
8172 return false;
8173 }
8174}
8175
8176// Emit short-circuiting code, where 'right' is never evaluated unless
8177// the left side is true (for &&) or false (for ||).
8178spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8179{
8180 spv::Id boolTypeId = builder.makeBoolType();
8181
8182 // emit left operand
8183 builder.clearAccessChain();
8184 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008185 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008186
8187 // Operands to accumulate OpPhi operands
8188 std::vector<spv::Id> phiOperands;
8189 // accumulate left operand's phi information
8190 phiOperands.push_back(leftId);
8191 phiOperands.push_back(builder.getBuildPoint()->getId());
8192
8193 // Make the two kinds of operation symmetric with a "!"
8194 // || => emit "if (! left) result = right"
8195 // && => emit "if ( left) result = right"
8196 //
8197 // TODO: this runtime "not" for || could be avoided by adding functionality
8198 // to 'builder' to have an "else" without an "then"
8199 if (op == glslang::EOpLogicalOr)
8200 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8201
8202 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008203 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008204
8205 // emit right operand as the "then" part of the "if"
8206 builder.clearAccessChain();
8207 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008208 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008209
8210 // accumulate left operand's phi information
8211 phiOperands.push_back(rightId);
8212 phiOperands.push_back(builder.getBuildPoint()->getId());
8213
8214 // finish the "if"
8215 ifBuilder.makeEndIf();
8216
8217 // phi together the two results
8218 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8219}
8220
John Kessenicha28f7a72019-08-06 07:00:58 -06008221#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008222// Return type Id of the imported set of extended instructions corresponds to the name.
8223// Import this set if it has not been imported yet.
8224spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8225{
8226 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8227 return extBuiltinMap[name];
8228 else {
Rex Xu51596642016-09-21 18:56:12 +08008229 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008230 spv::Id extBuiltins = builder.import(name);
8231 extBuiltinMap[name] = extBuiltins;
8232 return extBuiltins;
8233 }
8234}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008235#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008236
John Kessenich140f3df2015-06-26 16:58:36 -06008237}; // end anonymous namespace
8238
8239namespace glslang {
8240
John Kessenich68d78fd2015-07-12 19:28:10 -06008241void GetSpirvVersion(std::string& version)
8242{
John Kessenich9e55f632015-07-15 10:03:39 -06008243 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008244 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008245 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008246 version = buf;
8247}
8248
John Kessenicha372a3e2017-11-02 22:32:14 -06008249// For low-order part of the generator's magic number. Bump up
8250// when there is a change in the style (e.g., if SSA form changes,
8251// or a different instruction sequence to do something gets used).
8252int GetSpirvGeneratorVersion()
8253{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008254 // return 1; // start
8255 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008256 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008257 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008258 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008259 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8260 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008261 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8262 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008263}
8264
John Kessenich140f3df2015-06-26 16:58:36 -06008265// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008266void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008267{
8268 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008269 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008270 if (out.fail())
8271 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008272 for (int i = 0; i < (int)spirv.size(); ++i) {
8273 unsigned int word = spirv[i];
8274 out.write((const char*)&word, 4);
8275 }
8276 out.close();
8277}
8278
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008279// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008280void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008281{
John Kessenich155d3512019-08-08 23:29:20 -06008282#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008283 std::ofstream out;
8284 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008285 if (out.fail())
8286 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008287 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008288 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008289 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008290 if (varName != nullptr) {
8291 out << "\t #pragma once" << std::endl;
8292 out << "const uint32_t " << varName << "[] = {" << std::endl;
8293 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008294 const int WORDS_PER_LINE = 8;
8295 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8296 out << "\t";
8297 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8298 const unsigned int word = spirv[i + j];
8299 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8300 if (i + j + 1 < (int)spirv.size()) {
8301 out << ",";
8302 }
8303 }
8304 out << std::endl;
8305 }
Flavio15017db2017-02-15 14:29:33 -08008306 if (varName != nullptr) {
8307 out << "};";
8308 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008309 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008310#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008311}
8312
John Kessenich140f3df2015-06-26 16:58:36 -06008313//
8314// Set up the glslang traversal
8315//
John Kessenich4e11b612018-08-30 16:56:59 -06008316void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008317{
Lei Zhang17535f72016-05-04 15:55:59 -04008318 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008319 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008320}
8321
John Kessenich4e11b612018-08-30 16:56:59 -06008322void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008323 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008324{
John Kessenich140f3df2015-06-26 16:58:36 -06008325 TIntermNode* root = intermediate.getTreeRoot();
8326
8327 if (root == 0)
8328 return;
8329
John Kessenich4e11b612018-08-30 16:56:59 -06008330 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008331 if (options == nullptr)
8332 options = &defaultOptions;
8333
John Kessenich4e11b612018-08-30 16:56:59 -06008334 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008335
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008336 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008337 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008338 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008339 it.dumpSpv(spirv);
8340
GregFfb03a552018-03-29 11:49:14 -06008341#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008342 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8343 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008344 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8345 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008346 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008347 prelegalization = false;
8348 }
John Kessenich717c80a2018-08-23 15:17:10 -06008349
John Kessenich4e11b612018-08-30 16:56:59 -06008350 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008351 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008352
John Kessenich717c80a2018-08-23 15:17:10 -06008353 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008354 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008355
GregFcd1f1692017-09-21 18:40:22 -06008356#endif
8357
John Kessenich4e11b612018-08-30 16:56:59 -06008358 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008359}
8360
8361}; // end namespace glslang