blob: c3808c487cfc01cdfebda518231993790f298077 [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.
Torosdagli06c2eee2020-03-19 11:09:57 -04005// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06008//
John Kessenich927608b2017-01-06 12:34:14 -07009// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions
11// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060012//
13// Redistributions of source code must retain the above copyright
14// notice, this list of conditions and the following disclaimer.
15//
16// Redistributions in binary form must reproduce the above
17// copyright notice, this list of conditions and the following
18// disclaimer in the documentation and/or other materials provided
19// with the distribution.
20//
21// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22// contributors may be used to endorse or promote products derived
23// from this software without specific prior written permission.
24//
John Kessenich927608b2017-01-06 12:34:14 -070025// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060037
38//
John Kessenich140f3df2015-06-26 16:58:36 -060039// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080047 #include "GLSL.std.450.h"
48 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070049 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080051 #include "GLSL.ext.NV.h"
Jeff Bolz04d73732019-05-31 13:06:01 -050052 #include "NonSemanticDebugPrintf.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060092 public:
93 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
94 precision(precision)
95#ifndef GLSLANG_WEB
96 ,
97 noContraction(noContraction),
98 nonUniform(nonUniform)
99#endif
100 { }
101
John Kessenichead86222018-03-28 18:01:20 -0600102 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600103
104#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400105 void addNoContraction(spv::Builder&, spv::Id) const { }
106 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600107#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400108 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
109 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600110 protected:
111 spv::Decoration noContraction;
112 spv::Decoration nonUniform;
113#endif
114
John Kessenichead86222018-03-28 18:01:20 -0600115};
116
117} // namespace
qining4c912612016-04-01 10:35:16 -0400118
John Kessenich140f3df2015-06-26 16:58:36 -0600119//
120// The main holder of information for translating glslang to SPIR-V.
121//
122// Derives from the AST walking base class.
123//
124class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
125public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700126 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
127 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700128 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600129
130 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
131 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
132 void visitConstantUnion(glslang::TIntermConstantUnion*);
133 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
134 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
135 void visitSymbol(glslang::TIntermSymbol* symbol);
136 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
137 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
138 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
139
John Kessenichfca82622016-11-26 13:23:20 -0700140 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700141 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600142
143protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700144 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
145 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
146
Rex Xu17ff3432016-10-14 17:41:45 +0800147 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800148 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600149 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500150 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
151 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
152 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
153 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100154 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700155 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700156 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
157 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700158 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600159 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600160 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600161 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600163 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
164 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
165 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600166 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600167 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600168 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600169 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600170 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
171 glslang::TLayoutPacking, const glslang::TQualifier&);
172 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
173 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700174 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700175 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800176 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600177 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700178 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700179 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
180 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700181 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
182 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100183 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600184
John Kessenich6fccb3c2016-09-19 16:01:41 -0600185 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600186 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600187 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600188 void makeFunctions(const glslang::TIntermSequence&);
189 void makeGlobalInitializers(const glslang::TIntermSequence&);
190 void visitFunctions(const glslang::TIntermSequence&);
191 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700192 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
193 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600194 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
195 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
197
John Kessenichead86222018-03-28 18:01:20 -0600198 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
199 glslang::TBasicType typeProxy, bool reduceComparison = true);
200 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
201 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700202 glslang::TBasicType typeProxy,
203 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600204 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
205 glslang::TBasicType typeProxy);
206 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
207 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600208 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600209 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700210 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
211 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
212 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
213 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
214 glslang::TBasicType typeProxy);
215 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
216 spv::Id typeId, std::vector<spv::Id>& operands);
217 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
218 glslang::TBasicType typeProxy);
219 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
220 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800221 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600222 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700223 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400224 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700225 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
226 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600227 bool isTrivialLeaf(const glslang::TIntermTyped* node);
228 bool isTrivial(const glslang::TIntermTyped* node);
229 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800230 spv::Id getExtBuiltins(const char* name);
Daniel Kochdb32b242020-03-17 20:42:47 -0400231 std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
John Kessenich9c14f772019-06-17 08:38:35 -0600232 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500233 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600234
John Kessenich121853f2017-05-31 17:11:16 -0600235 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600237 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700238 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600239 int sequenceDepth;
240
Lei Zhang17535f72016-05-04 15:55:59 -0400241 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400242
John Kessenich140f3df2015-06-26 16:58:36 -0600243 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
244 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700245 bool inEntryPoint;
246 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700247 bool linkageOnly; // true when visiting the set of objects in the AST present only for
248 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700249 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600250 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600251 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600252 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500253 spv::Id nonSemanticDebugPrintf;
Rex Xu9d93a232016-05-05 12:30:44 +0800254 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600255
John Kessenich2f273362015-07-18 22:34:27 -0600256 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700257 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
258 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600259 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700260 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700261 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800262 std::unordered_map<int, std::vector<int>> memberRemapper;
263 // for mapping glslang symbol struct to symbol Id
264 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700266 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600267 // Map pointee types for EbtReference to their forward pointers
268 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600269 // Type forcing, for when SPIR-V wants a different type than the AST,
270 // requiring local translation to and from SPIR-V type on every access.
271 // Maps <builtin-variable-id -> AST-required-type-id>
272 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600273};
274
275//
276// Helper functions for translating glslang representations to SPIR-V enumerants.
277//
278
279// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700280spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600281{
John Kessenich155d3512019-08-08 23:29:20 -0600282#ifdef GLSLANG_WEB
283 return spv::SourceLanguageESSL;
284#endif
285
John Kessenich66e2faf2016-03-12 18:34:36 -0700286 switch (source) {
287 case glslang::EShSourceGlsl:
288 switch (profile) {
289 case ENoProfile:
290 case ECoreProfile:
291 case ECompatibilityProfile:
292 return spv::SourceLanguageGLSL;
293 case EEsProfile:
294 return spv::SourceLanguageESSL;
295 default:
296 return spv::SourceLanguageUnknown;
297 }
298 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600299 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600300 default:
301 return spv::SourceLanguageUnknown;
302 }
303}
304
305// Translate glslang language (stage) to SPIR-V execution model.
306spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
307{
308 switch (stage) {
309 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600310 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600311 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600312#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600313 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
314 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
315 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400316 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
317 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
318 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
319 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
320 case EShLangMiss: return spv::ExecutionModelMissKHR;
321 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700322 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
323 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
324#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600325 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700326 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600327 return spv::ExecutionModelFragment;
328 }
329}
330
John Kessenich140f3df2015-06-26 16:58:36 -0600331// Translate glslang sampler type to SPIR-V dimensionality.
332spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
333{
334 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700335 case glslang::Esd1D: return spv::Dim1D;
336 case glslang::Esd2D: return spv::Dim2D;
337 case glslang::Esd3D: return spv::Dim3D;
338 case glslang::EsdCube: return spv::DimCube;
339 case glslang::EsdRect: return spv::DimRect;
340 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700341 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700343 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600344 return spv::Dim2D;
345 }
346}
347
John Kessenichf6640762016-08-01 19:44:00 -0600348// Translate glslang precision to SPIR-V precision decorations.
349spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600350{
John Kessenichf6640762016-08-01 19:44:00 -0600351 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700352 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600353 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 default:
355 return spv::NoPrecision;
356 }
357}
358
John Kessenichf6640762016-08-01 19:44:00 -0600359// Translate glslang type to SPIR-V precision decorations.
360spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
361{
362 return TranslatePrecisionDecoration(type.getQualifier().precision);
363}
364
John Kessenich140f3df2015-06-26 16:58:36 -0600365// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600366spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600367{
368 if (type.getBasicType() == glslang::EbtBlock) {
369 switch (type.getQualifier().storage) {
370 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600371 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 case glslang::EvqVaryingIn: return spv::DecorationBlock;
373 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600374#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400375 case glslang::EvqPayload: return spv::DecorationBlock;
376 case glslang::EvqPayloadIn: return spv::DecorationBlock;
377 case glslang::EvqHitAttr: return spv::DecorationBlock;
378 case glslang::EvqCallableData: return spv::DecorationBlock;
379 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700380#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600381 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700382 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600383 break;
384 }
385 }
386
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600388}
389
Rex Xu1da878f2016-02-21 20:59:01 +0800390// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700391void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
392 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800393{
Jeff Bolz36831c92018-09-05 10:11:41 -0500394 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600395 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500396 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600397 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500398 memory.push_back(spv::DecorationVolatile);
399 memory.push_back(spv::DecorationCoherent);
400 }
John Kessenich14b85d32018-06-04 15:36:03 -0600401 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600402 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800403 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600404 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800405 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600406 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800407 memory.push_back(spv::DecorationNonReadable);
408}
409
John Kessenich140f3df2015-06-26 16:58:36 -0600410// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700411spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600412{
413 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700414 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600415 case glslang::ElmRowMajor:
416 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700417 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700419 default:
420 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422 }
423 } else {
424 switch (type.getBasicType()) {
425 default:
John Kessenich4016e382016-07-15 11:53:56 -0600426 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600427 break;
428 case glslang::EbtBlock:
429 switch (type.getQualifier().storage) {
430 case glslang::EvqUniform:
431 case glslang::EvqBuffer:
432 switch (type.getQualifier().layoutPacking) {
433 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600434 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
435 default:
John Kessenich4016e382016-07-15 11:53:56 -0600436 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600437 }
438 case glslang::EvqVaryingIn:
439 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700440 if (type.getQualifier().isTaskMemory()) {
441 switch (type.getQualifier().layoutPacking) {
442 case glslang::ElpShared: return spv::DecorationGLSLShared;
443 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
444 default: break;
445 }
446 } else {
447 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
448 }
John Kessenich4016e382016-07-15 11:53:56 -0600449 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600450#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400451 case glslang::EvqPayload:
452 case glslang::EvqPayloadIn:
453 case glslang::EvqHitAttr:
454 case glslang::EvqCallableData:
455 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700456 return spv::DecorationMax;
457#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600458 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700459 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600460 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600461 }
462 }
463 }
464}
465
466// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600467// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700468// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800469spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600470{
Rex Xubbceed72016-05-21 09:40:44 +0800471 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700472 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600473 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600474 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700475 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700476 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600477 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600478 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800479 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800480 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800481 }
Rex Xubbceed72016-05-21 09:40:44 +0800482 else
John Kessenich4016e382016-07-15 11:53:56 -0600483 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800484}
485
486// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600487// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800488// should be applied.
489spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
490{
John Kessenichb9197c82019-08-11 07:41:45 -0600491 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600492 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600493#ifndef GLSLANG_WEB
494 else if (qualifier.patch)
495 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700496 else if (qualifier.sample) {
497 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600498 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600499 }
500#endif
501
502 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600503}
504
John Kessenich92187592016-02-01 13:45:25 -0700505// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700506spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600507{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700508 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600509 return spv::DecorationInvariant;
510 else
John Kessenich4016e382016-07-15 11:53:56 -0600511 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600512}
513
qining9220dbb2016-05-04 17:34:38 -0400514// If glslang type is noContraction, return SPIR-V NoContraction decoration.
515spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
516{
John Kessenichb9197c82019-08-11 07:41:45 -0600517#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600518 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400519 return spv::DecorationNoContraction;
520 else
John Kessenichb9197c82019-08-11 07:41:45 -0600521#endif
John Kessenich4016e382016-07-15 11:53:56 -0600522 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400523}
524
John Kessenich5611c6d2018-04-05 11:25:02 -0600525// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
526spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
527{
John Kessenichb9197c82019-08-11 07:41:45 -0600528#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600529 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600530 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600531 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
532 return spv::DecorationNonUniformEXT;
533 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600534#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600535 return spv::DecorationMax;
536}
537
John Kessenichb9197c82019-08-11 07:41:45 -0600538spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
539 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500540{
Jeff Bolz36831c92018-09-05 10:11:41 -0500541 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600542
543#ifndef GLSLANG_WEB
544 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
545 return mask;
546
Daniel Kochdb32b242020-03-17 20:42:47 -0400547 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500548 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
549 spv::MemoryAccessMakePointerVisibleKHRMask;
550 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400551
Jeff Bolz36831c92018-09-05 10:11:41 -0500552 if (coherentFlags.nonprivate) {
553 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
554 }
555 if (coherentFlags.volatil) {
556 mask = mask | spv::MemoryAccessVolatileMask;
557 }
558 if (mask != spv::MemoryAccessMaskNone) {
559 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
560 }
John Kessenichb9197c82019-08-11 07:41:45 -0600561#endif
562
Jeff Bolz36831c92018-09-05 10:11:41 -0500563 return mask;
564}
565
John Kessenichb9197c82019-08-11 07:41:45 -0600566spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
567 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500568{
Jeff Bolz36831c92018-09-05 10:11:41 -0500569 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600570
571#ifndef GLSLANG_WEB
572 if (!glslangIntermediate->usingVulkanMemoryModel())
573 return mask;
574
Jeff Bolz36831c92018-09-05 10:11:41 -0500575 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400576 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500577 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
578 spv::ImageOperandsMakeTexelVisibleKHRMask;
579 }
580 if (coherentFlags.nonprivate) {
581 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
582 }
583 if (coherentFlags.volatil) {
584 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
585 }
586 if (mask != spv::ImageOperandsMaskNone) {
587 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
588 }
John Kessenichb9197c82019-08-11 07:41:45 -0600589#endif
590
Jeff Bolz36831c92018-09-05 10:11:41 -0500591 return mask;
592}
593
594spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
595{
John Kessenichb9197c82019-08-11 07:41:45 -0600596 spv::Builder::AccessChain::CoherentFlags flags = {};
597#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500598 flags.coherent = type.getQualifier().coherent;
599 flags.devicecoherent = type.getQualifier().devicecoherent;
600 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
601 // shared variables are implicitly workgroupcoherent in GLSL.
602 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
603 type.getQualifier().storage == glslang::EvqShared;
604 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400605 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600606 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500607 // *coherent variables are implicitly nonprivate in GLSL
608 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400609 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600610 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500611 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600612#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500613 return flags;
614}
615
John Kessenichb9197c82019-08-11 07:41:45 -0600616spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
617 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500618{
John Kessenichb9197c82019-08-11 07:41:45 -0600619 spv::Scope scope = spv::ScopeMax;
620
621#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600622 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500623 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
624 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
625 } else if (coherentFlags.devicecoherent) {
626 scope = spv::ScopeDevice;
627 } else if (coherentFlags.queuefamilycoherent) {
628 scope = spv::ScopeQueueFamilyKHR;
629 } else if (coherentFlags.workgroupcoherent) {
630 scope = spv::ScopeWorkgroup;
631 } else if (coherentFlags.subgroupcoherent) {
632 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400633 } else if (coherentFlags.shadercallcoherent) {
634 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500635 }
636 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
637 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
638 }
John Kessenichb9197c82019-08-11 07:41:45 -0600639#endif
640
Jeff Bolz36831c92018-09-05 10:11:41 -0500641 return scope;
642}
643
David Netoa901ffe2016-06-08 14:11:40 +0100644// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
645// associated capabilities when required. For some built-in variables, a capability
646// is generated only when using the variable in an executable instruction, but not when
647// just declaring a struct member variable with it. This is true for PointSize,
648// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700649spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
650 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600651{
652 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700653 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600654#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600655 // Defer adding the capability until the built-in is actually used.
656 if (! memberDeclaration) {
657 switch (glslangIntermediate->getStage()) {
658 case EShLangGeometry:
659 builder.addCapability(spv::CapabilityGeometryPointSize);
660 break;
661 case EShLangTessControl:
662 case EShLangTessEvaluation:
663 builder.addCapability(spv::CapabilityTessellationPointSize);
664 break;
665 default:
666 break;
667 }
John Kessenich92187592016-02-01 13:45:25 -0700668 }
John Kessenich155d3512019-08-08 23:29:20 -0600669#endif
John Kessenich92187592016-02-01 13:45:25 -0700670 return spv::BuiltInPointSize;
671
John Kessenicha28f7a72019-08-06 07:00:58 -0600672 case glslang::EbvPosition: return spv::BuiltInPosition;
673 case glslang::EbvVertexId: return spv::BuiltInVertexId;
674 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
675 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
676 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
677
678 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
679 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
680 case glslang::EbvFace: return spv::BuiltInFrontFacing;
681 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
682
John Kessenich3dd1ce52019-10-17 07:08:40 -0600683 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
684 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
685 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
686 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
687 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
688 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
689
John Kessenicha28f7a72019-08-06 07:00:58 -0600690#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600691 // These *Distance capabilities logically belong here, but if the member is declared and
692 // then never used, consumers of SPIR-V prefer the capability not be declared.
693 // They are now generated when used, rather than here when declared.
694 // Potentially, the specification should be more clear what the minimum
695 // use needed is to trigger the capability.
696 //
John Kessenich92187592016-02-01 13:45:25 -0700697 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100698 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800699 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700700 return spv::BuiltInClipDistance;
701
702 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100703 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800704 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700705 return spv::BuiltInCullDistance;
706
707 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600708 builder.addCapability(spv::CapabilityMultiViewport);
709 if (glslangIntermediate->getStage() == EShLangVertex ||
710 glslangIntermediate->getStage() == EShLangTessControl ||
711 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800712
John Kessenich8317e6c2019-08-18 23:58:08 -0600713 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600714 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800715 }
John Kessenich92187592016-02-01 13:45:25 -0700716 return spv::BuiltInViewportIndex;
717
John Kessenich5e801132016-02-15 11:09:46 -0700718 case glslang::EbvSampleId:
719 builder.addCapability(spv::CapabilitySampleRateShading);
720 return spv::BuiltInSampleId;
721
722 case glslang::EbvSamplePosition:
723 builder.addCapability(spv::CapabilitySampleRateShading);
724 return spv::BuiltInSamplePosition;
725
726 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700727 return spv::BuiltInSampleMask;
728
John Kessenich78a45572016-07-08 14:05:15 -0600729 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700730 if (glslangIntermediate->getStage() == EShLangMeshNV) {
731 return spv::BuiltInLayer;
732 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600733 builder.addCapability(spv::CapabilityGeometry);
734 if (glslangIntermediate->getStage() == EShLangVertex ||
735 glslangIntermediate->getStage() == EShLangTessControl ||
736 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800737
John Kessenich8317e6c2019-08-18 23:58:08 -0600738 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600739 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800740 }
John Kessenich78a45572016-07-08 14:05:15 -0600741 return spv::BuiltInLayer;
742
John Kessenichda581a22015-10-14 14:10:30 -0600743 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600744 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800745 builder.addCapability(spv::CapabilityDrawParameters);
746 return spv::BuiltInBaseVertex;
747
John Kessenichda581a22015-10-14 14:10:30 -0600748 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600749 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800750 builder.addCapability(spv::CapabilityDrawParameters);
751 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200752
John Kessenichda581a22015-10-14 14:10:30 -0600753 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600754 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800755 builder.addCapability(spv::CapabilityDrawParameters);
756 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200757
758 case glslang::EbvPrimitiveId:
759 if (glslangIntermediate->getStage() == EShLangFragment)
760 builder.addCapability(spv::CapabilityGeometry);
761 return spv::BuiltInPrimitiveId;
762
Rex Xu37cdcee2017-06-29 17:46:34 +0800763 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800764 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
765 builder.addCapability(spv::CapabilityStencilExportEXT);
766 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800767
John Kessenich140f3df2015-06-26 16:58:36 -0600768 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600769 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
770 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
771 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
772 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600773 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800774
Rex Xu574ab042016-04-14 16:53:07 +0800775 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800776 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800777 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
778 return spv::BuiltInSubgroupSize;
779
Rex Xu574ab042016-04-14 16:53:07 +0800780 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800781 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800782 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
783 return spv::BuiltInSubgroupLocalInvocationId;
784
Rex Xu574ab042016-04-14 16:53:07 +0800785 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800786 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
787 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600788 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800789
Rex Xu574ab042016-04-14 16:53:07 +0800790 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800791 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
792 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600793 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800794
Rex Xu574ab042016-04-14 16:53:07 +0800795 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800796 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
797 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600798 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800799
Rex Xu574ab042016-04-14 16:53:07 +0800800 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800801 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
802 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600803 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800804
Rex Xu574ab042016-04-14 16:53:07 +0800805 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800806 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
807 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600808 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800809
John Kessenich66011cb2018-03-06 16:12:04 -0700810 case glslang::EbvNumSubgroups:
811 builder.addCapability(spv::CapabilityGroupNonUniform);
812 return spv::BuiltInNumSubgroups;
813
814 case glslang::EbvSubgroupID:
815 builder.addCapability(spv::CapabilityGroupNonUniform);
816 return spv::BuiltInSubgroupId;
817
818 case glslang::EbvSubgroupSize2:
819 builder.addCapability(spv::CapabilityGroupNonUniform);
820 return spv::BuiltInSubgroupSize;
821
822 case glslang::EbvSubgroupInvocation2:
823 builder.addCapability(spv::CapabilityGroupNonUniform);
824 return spv::BuiltInSubgroupLocalInvocationId;
825
826 case glslang::EbvSubgroupEqMask2:
827 builder.addCapability(spv::CapabilityGroupNonUniform);
828 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
829 return spv::BuiltInSubgroupEqMask;
830
831 case glslang::EbvSubgroupGeMask2:
832 builder.addCapability(spv::CapabilityGroupNonUniform);
833 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
834 return spv::BuiltInSubgroupGeMask;
835
836 case glslang::EbvSubgroupGtMask2:
837 builder.addCapability(spv::CapabilityGroupNonUniform);
838 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
839 return spv::BuiltInSubgroupGtMask;
840
841 case glslang::EbvSubgroupLeMask2:
842 builder.addCapability(spv::CapabilityGroupNonUniform);
843 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
844 return spv::BuiltInSubgroupLeMask;
845
846 case glslang::EbvSubgroupLtMask2:
847 builder.addCapability(spv::CapabilityGroupNonUniform);
848 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
849 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600850
Rex Xu17ff3432016-10-14 17:41:45 +0800851 case glslang::EbvBaryCoordNoPersp:
852 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
853 return spv::BuiltInBaryCoordNoPerspAMD;
854
855 case glslang::EbvBaryCoordNoPerspCentroid:
856 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
857 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
858
859 case glslang::EbvBaryCoordNoPerspSample:
860 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
861 return spv::BuiltInBaryCoordNoPerspSampleAMD;
862
863 case glslang::EbvBaryCoordSmooth:
864 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
865 return spv::BuiltInBaryCoordSmoothAMD;
866
867 case glslang::EbvBaryCoordSmoothCentroid:
868 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
869 return spv::BuiltInBaryCoordSmoothCentroidAMD;
870
871 case glslang::EbvBaryCoordSmoothSample:
872 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
873 return spv::BuiltInBaryCoordSmoothSampleAMD;
874
875 case glslang::EbvBaryCoordPullModel:
876 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
877 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800878
John Kessenich6c8aaac2017-02-27 01:20:51 -0700879 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600880 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700881 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700882 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700883
884 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600885 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700886 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700887 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700888
Daniel Koch5154db52018-11-26 10:01:58 -0500889 case glslang::EbvFragSizeEXT:
890 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
891 builder.addCapability(spv::CapabilityFragmentDensityEXT);
892 return spv::BuiltInFragSizeEXT;
893
894 case glslang::EbvFragInvocationCountEXT:
895 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
896 builder.addCapability(spv::CapabilityFragmentDensityEXT);
897 return spv::BuiltInFragInvocationCountEXT;
898
chaoc771d89f2017-01-13 01:10:53 -0800899 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800900 if (!memberDeclaration) {
901 builder.addExtension(spv::E_SPV_NV_viewport_array2);
902 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
903 }
chaoc771d89f2017-01-13 01:10:53 -0800904 return spv::BuiltInViewportMaskNV;
905 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800906 if (!memberDeclaration) {
907 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
908 builder.addCapability(spv::CapabilityShaderStereoViewNV);
909 }
chaoc771d89f2017-01-13 01:10:53 -0800910 return spv::BuiltInSecondaryPositionNV;
911 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800912 if (!memberDeclaration) {
913 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
914 builder.addCapability(spv::CapabilityShaderStereoViewNV);
915 }
chaoc771d89f2017-01-13 01:10:53 -0800916 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800917 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800918 if (!memberDeclaration) {
919 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
920 builder.addCapability(spv::CapabilityPerViewAttributesNV);
921 }
chaocdf3956c2017-02-14 14:52:34 -0800922 return spv::BuiltInPositionPerViewNV;
923 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800924 if (!memberDeclaration) {
925 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
926 builder.addCapability(spv::CapabilityPerViewAttributesNV);
927 }
chaocdf3956c2017-02-14 14:52:34 -0800928 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700929 case glslang::EbvFragFullyCoveredNV:
930 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
931 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
932 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700933 case glslang::EbvFragmentSizeNV:
934 builder.addExtension(spv::E_SPV_NV_shading_rate);
935 builder.addCapability(spv::CapabilityShadingRateNV);
936 return spv::BuiltInFragmentSizeNV;
937 case glslang::EbvInvocationsPerPixelNV:
938 builder.addExtension(spv::E_SPV_NV_shading_rate);
939 builder.addCapability(spv::CapabilityShadingRateNV);
940 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700941
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400943 case glslang::EbvLaunchId:
944 return spv::BuiltInLaunchIdKHR;
945 case glslang::EbvLaunchSize:
946 return spv::BuiltInLaunchSizeKHR;
947 case glslang::EbvWorldRayOrigin:
948 return spv::BuiltInWorldRayOriginKHR;
949 case glslang::EbvWorldRayDirection:
950 return spv::BuiltInWorldRayDirectionKHR;
951 case glslang::EbvObjectRayOrigin:
952 return spv::BuiltInObjectRayOriginKHR;
953 case glslang::EbvObjectRayDirection:
954 return spv::BuiltInObjectRayDirectionKHR;
955 case glslang::EbvRayTmin:
956 return spv::BuiltInRayTminKHR;
957 case glslang::EbvRayTmax:
958 return spv::BuiltInRayTmaxKHR;
959 case glslang::EbvInstanceCustomIndex:
960 return spv::BuiltInInstanceCustomIndexKHR;
961 case glslang::EbvHitT:
962 return spv::BuiltInHitTKHR;
963 case glslang::EbvHitKind:
964 return spv::BuiltInHitKindKHR;
965 case glslang::EbvObjectToWorld:
966 case glslang::EbvObjectToWorld3x4:
967 return spv::BuiltInObjectToWorldKHR;
968 case glslang::EbvWorldToObject:
969 case glslang::EbvWorldToObject3x4:
970 return spv::BuiltInWorldToObjectKHR;
971 case glslang::EbvIncomingRayFlags:
972 return spv::BuiltInIncomingRayFlagsKHR;
973 case glslang::EbvGeometryIndex:
974 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400975
976 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700977 case glslang::EbvBaryCoordNV:
978 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
979 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
980 return spv::BuiltInBaryCoordNV;
981 case glslang::EbvBaryCoordNoPerspNV:
982 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
983 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
984 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400985
986 // mesh shaders
987 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700988 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400989 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700990 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400991 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700992 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400993 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700994 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400995 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700996 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400997 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700998 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400999 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001000 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001001 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001002 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001003
1004 // sm builtins
1005 case glslang::EbvWarpsPerSM:
1006 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1007 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1008 return spv::BuiltInWarpsPerSMNV;
1009 case glslang::EbvSMCount:
1010 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1011 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1012 return spv::BuiltInSMCountNV;
1013 case glslang::EbvWarpID:
1014 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1015 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1016 return spv::BuiltInWarpIDNV;
1017 case glslang::EbvSMID:
1018 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1019 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1020 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001021#endif
1022
Rex Xu3e783f92017-02-22 16:44:48 +08001023 default:
1024 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001025 }
1026}
1027
Rex Xufc618912015-09-09 16:42:49 +08001028// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001029spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001030{
1031 assert(type.getBasicType() == glslang::EbtSampler);
1032
John Kessenichb9197c82019-08-11 07:41:45 -06001033#ifdef GLSLANG_WEB
1034 return spv::ImageFormatUnknown;
1035#endif
1036
John Kessenich5d0fa972016-02-15 11:57:00 -07001037 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001038 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001039 case glslang::ElfRg32f:
1040 case glslang::ElfRg16f:
1041 case glslang::ElfR11fG11fB10f:
1042 case glslang::ElfR16f:
1043 case glslang::ElfRgba16:
1044 case glslang::ElfRgb10A2:
1045 case glslang::ElfRg16:
1046 case glslang::ElfRg8:
1047 case glslang::ElfR16:
1048 case glslang::ElfR8:
1049 case glslang::ElfRgba16Snorm:
1050 case glslang::ElfRg16Snorm:
1051 case glslang::ElfRg8Snorm:
1052 case glslang::ElfR16Snorm:
1053 case glslang::ElfR8Snorm:
1054
1055 case glslang::ElfRg32i:
1056 case glslang::ElfRg16i:
1057 case glslang::ElfRg8i:
1058 case glslang::ElfR16i:
1059 case glslang::ElfR8i:
1060
1061 case glslang::ElfRgb10a2ui:
1062 case glslang::ElfRg32ui:
1063 case glslang::ElfRg16ui:
1064 case glslang::ElfRg8ui:
1065 case glslang::ElfR16ui:
1066 case glslang::ElfR8ui:
1067 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1068 break;
1069
1070 default:
1071 break;
1072 }
1073
1074 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001075 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001076 case glslang::ElfNone: return spv::ImageFormatUnknown;
1077 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1078 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1079 case glslang::ElfR32f: return spv::ImageFormatR32f;
1080 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1081 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1082 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1083 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1084 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1085 case glslang::ElfR16f: return spv::ImageFormatR16f;
1086 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1087 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1088 case glslang::ElfRg16: return spv::ImageFormatRg16;
1089 case glslang::ElfRg8: return spv::ImageFormatRg8;
1090 case glslang::ElfR16: return spv::ImageFormatR16;
1091 case glslang::ElfR8: return spv::ImageFormatR8;
1092 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1093 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1094 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1095 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1096 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1097 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1098 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1099 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1100 case glslang::ElfR32i: return spv::ImageFormatR32i;
1101 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1102 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1103 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1104 case glslang::ElfR16i: return spv::ImageFormatR16i;
1105 case glslang::ElfR8i: return spv::ImageFormatR8i;
1106 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1107 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1108 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1109 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1110 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1111 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1112 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1113 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1114 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1115 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001116 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001117 }
1118}
1119
John Kessenich8985fc92020-03-03 10:25:07 -07001120spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1121 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001122{
John Kesseniche18fd202018-01-30 11:01:39 -07001123 if (selectionNode.getFlatten())
1124 return spv::SelectionControlFlattenMask;
1125 if (selectionNode.getDontFlatten())
1126 return spv::SelectionControlDontFlattenMask;
1127 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001128}
1129
John Kessenich8985fc92020-03-03 10:25:07 -07001130spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1131 const
steve-lunargf1709e72017-05-02 20:14:50 -06001132{
John Kesseniche18fd202018-01-30 11:01:39 -07001133 if (switchNode.getFlatten())
1134 return spv::SelectionControlFlattenMask;
1135 if (switchNode.getDontFlatten())
1136 return spv::SelectionControlDontFlattenMask;
1137 return spv::SelectionControlMaskNone;
1138}
1139
John Kessenicha2858d92018-01-31 08:11:18 -07001140// return a non-0 dependency if the dependency argument must be set
1141spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001142 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001143{
1144 spv::LoopControlMask control = spv::LoopControlMaskNone;
1145
1146 if (loopNode.getDontUnroll())
1147 control = control | spv::LoopControlDontUnrollMask;
1148 if (loopNode.getUnroll())
1149 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001150 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001151 control = control | spv::LoopControlDependencyInfiniteMask;
1152 else if (loopNode.getLoopDependency() > 0) {
1153 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001154 operands.push_back((unsigned int)loopNode.getLoopDependency());
1155 }
1156 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1157 if (loopNode.getMinIterations() > 0) {
1158 control = control | spv::LoopControlMinIterationsMask;
1159 operands.push_back(loopNode.getMinIterations());
1160 }
1161 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1162 control = control | spv::LoopControlMaxIterationsMask;
1163 operands.push_back(loopNode.getMaxIterations());
1164 }
1165 if (loopNode.getIterationMultiple() > 1) {
1166 control = control | spv::LoopControlIterationMultipleMask;
1167 operands.push_back(loopNode.getIterationMultiple());
1168 }
1169 if (loopNode.getPeelCount() > 0) {
1170 control = control | spv::LoopControlPeelCountMask;
1171 operands.push_back(loopNode.getPeelCount());
1172 }
1173 if (loopNode.getPartialCount() > 0) {
1174 control = control | spv::LoopControlPartialCountMask;
1175 operands.push_back(loopNode.getPartialCount());
1176 }
John Kessenicha2858d92018-01-31 08:11:18 -07001177 }
John Kesseniche18fd202018-01-30 11:01:39 -07001178
1179 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001180}
1181
John Kessenicha5c5fb62017-05-05 05:09:58 -06001182// Translate glslang type to SPIR-V storage class.
1183spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1184{
Torosdagli06c2eee2020-03-19 11:09:57 -04001185 if (type.getBasicType() == glslang::EbtRayQuery)
1186 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001187 if (type.getQualifier().isPipeInput())
1188 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001189 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001190 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001191
1192 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001193 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001194 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001195 return spv::StorageClassAtomicCounter;
1196 if (type.containsOpaque())
1197 return spv::StorageClassUniformConstant;
1198 }
1199
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001200 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001201 type.getQualifier().isShaderRecord()) {
1202 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001203 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001204
John Kessenichbed4e4f2017-09-08 02:38:07 -06001205 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001206 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001207 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001208 }
1209
1210 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001211 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001212 return spv::StorageClassPushConstant;
1213 if (type.getBasicType() == glslang::EbtBlock)
1214 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001215 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001216 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001217
1218 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001219 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1220 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1221 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001222 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001223#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001224 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1225 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1226 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1227 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1228 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001229#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001230 default:
1231 assert(0);
1232 break;
1233 }
1234
1235 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001236}
1237
John Kessenich5611c6d2018-04-05 11:25:02 -06001238// Add capabilities pertaining to how an array is indexed.
1239void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1240 const glslang::TType& indexType)
1241{
John Kessenichb9197c82019-08-11 07:41:45 -06001242#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001243 if (indexType.getQualifier().isNonUniform()) {
1244 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001245 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001246 if (baseType.getBasicType() == glslang::EbtSampler) {
1247 if (baseType.getQualifier().hasAttachment())
1248 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001249 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001250 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001251 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001252 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1253 else if (baseType.isImage())
1254 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1255 else if (baseType.isTexture())
1256 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1257 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1258 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1259 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1260 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1261 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1262 }
1263 } else {
1264 // assume a dynamically uniform index
1265 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001266 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001267 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001268 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001269 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001270 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001271 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001272 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001273 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001274 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001275 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001276 }
1277 }
John Kessenichb9197c82019-08-11 07:41:45 -06001278#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001279}
1280
qining25262b32016-05-06 17:25:16 -04001281// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001282// descriptor set.
1283bool IsDescriptorResource(const glslang::TType& type)
1284{
John Kessenichf7497e22016-03-08 21:36:22 -07001285 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001286 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001287 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001288 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001289 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001290
1291 // non block...
1292 // basically samplerXXX/subpass/sampler/texture are all included
1293 // if they are the global-scope-class, not the function parameter
1294 // (or local, if they ever exist) class.
1295 if (type.getBasicType() == glslang::EbtSampler)
1296 return type.getQualifier().isUniformOrBuffer();
1297
1298 // None of the above.
1299 return false;
1300}
1301
John Kesseniche0b6cad2015-12-24 10:30:13 -07001302void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1303{
1304 if (child.layoutMatrix == glslang::ElmNone)
1305 child.layoutMatrix = parent.layoutMatrix;
1306
1307 if (parent.invariant)
1308 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001309 if (parent.flat)
1310 child.flat = true;
1311 if (parent.centroid)
1312 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001313#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001314 if (parent.nopersp)
1315 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001316 if (parent.explicitInterp)
1317 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001318 if (parent.perPrimitiveNV)
1319 child.perPrimitiveNV = true;
1320 if (parent.perViewNV)
1321 child.perViewNV = true;
1322 if (parent.perTaskNV)
1323 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001324 if (parent.patch)
1325 child.patch = true;
1326 if (parent.sample)
1327 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001328 if (parent.coherent)
1329 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001330 if (parent.devicecoherent)
1331 child.devicecoherent = true;
1332 if (parent.queuefamilycoherent)
1333 child.queuefamilycoherent = true;
1334 if (parent.workgroupcoherent)
1335 child.workgroupcoherent = true;
1336 if (parent.subgroupcoherent)
1337 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001338 if (parent.shadercallcoherent)
1339 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001340 if (parent.nonprivate)
1341 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001342 if (parent.volatil)
1343 child.volatil = true;
1344 if (parent.restrict)
1345 child.restrict = true;
1346 if (parent.readonly)
1347 child.readonly = true;
1348 if (parent.writeonly)
1349 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001350#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001351}
1352
John Kessenichf2b7f332016-09-01 17:05:23 -06001353bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001354{
John Kessenich7b9fa252016-01-21 18:56:57 -07001355 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001356 // - struct members might inherit from a struct declaration
1357 // (note that non-block structs don't explicitly inherit,
1358 // only implicitly, meaning no decoration involved)
1359 // - affect decorations on the struct members
1360 // (note smooth does not, and expecting something like volatile
1361 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001362 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001363 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001364}
1365
John Kessenich140f3df2015-06-26 16:58:36 -06001366//
1367// Implement the TGlslangToSpvTraverser class.
1368//
1369
John Kessenich8985fc92020-03-03 10:25:07 -07001370TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1371 const glslang::TIntermediate* glslangIntermediate,
1372 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1373 TIntermTraverser(true, false, true),
1374 options(options),
1375 shaderEntry(nullptr), currentFunction(nullptr),
1376 sequenceDepth(0), logger(buildLogger),
1377 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1378 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1379 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001380 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1381 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001382{
1383 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1384
1385 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001386 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1387 glslangIntermediate->getVersion());
1388
John Kessenich121853f2017-05-31 17:11:16 -06001389 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001390 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001391 builder.setSourceFile(glslangIntermediate->getSourceFile());
1392
1393 // Set the source shader's text. If for SPV version 1.0, include
1394 // a preamble in comments stating the OpModuleProcessed instructions.
1395 // Otherwise, emit those as actual instructions.
1396 std::string text;
1397 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1398 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001399 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001400 text.append("// OpModuleProcessed ");
1401 text.append(processes[p]);
1402 text.append("\n");
1403 } else
1404 builder.addModuleProcessed(processes[p]);
1405 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001406 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001407 text.append("#line 1\n");
1408 text.append(glslangIntermediate->getSourceText());
1409 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001410 // Pass name and text for all included files
1411 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1412 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1413 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001414 }
John Kessenich140f3df2015-06-26 16:58:36 -06001415 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001416
1417 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1418 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1419
1420 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1421 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001422 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001423 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001424 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001425 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001426 memoryModel = spv::MemoryModelVulkanKHR;
1427 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001428 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001429 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001430 builder.setMemoryModel(addressingModel, memoryModel);
1431
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001432 if (glslangIntermediate->usingVariablePointers()) {
1433 builder.addCapability(spv::CapabilityVariablePointers);
1434 }
1435
John Kessenicheee9d532016-09-19 18:09:30 -06001436 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1437 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001438
1439 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001440 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1441 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001442 builder.addSourceExtension(it->c_str());
1443
1444 // Add the top-level modes for this shader.
1445
John Kessenich92187592016-02-01 13:45:25 -07001446 if (glslangIntermediate->getXfbMode()) {
1447 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001449 }
John Kessenich140f3df2015-06-26 16:58:36 -06001450
1451 unsigned int mode;
1452 switch (glslangIntermediate->getStage()) {
1453 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001454 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001455 break;
1456
John Kessenicha28f7a72019-08-06 07:00:58 -06001457 case EShLangFragment:
1458 builder.addCapability(spv::CapabilityShader);
1459 if (glslangIntermediate->getPixelCenterInteger())
1460 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1461
1462 if (glslangIntermediate->getOriginUpperLeft())
1463 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1464 else
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1466
1467 if (glslangIntermediate->getEarlyFragmentTests())
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1469
1470 if (glslangIntermediate->getPostDepthCoverage()) {
1471 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1473 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1474 }
1475
John Kessenichb9197c82019-08-11 07:41:45 -06001476 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1478
1479#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001480 switch(glslangIntermediate->getDepth()) {
1481 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1482 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1483 default: mode = spv::ExecutionModeMax; break;
1484 }
1485 if (mode != spv::ExecutionModeMax)
1486 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001487 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001488 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1489 break;
1490 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1491 break;
1492 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1493 break;
1494 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1495 break;
1496 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1497 break;
1498 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1499 break;
1500 default: mode = spv::ExecutionModeMax;
1501 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001502 }
1503 if (mode != spv::ExecutionModeMax) {
1504 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1505 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1506 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1507 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1508 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1509 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1510 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1511 } else {
1512 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1513 }
1514 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1515 }
John Kessenichb9197c82019-08-11 07:41:45 -06001516#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001517 break;
1518
John Kessenicha28f7a72019-08-06 07:00:58 -06001519 case EShLangCompute:
1520 builder.addCapability(spv::CapabilityShader);
1521 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1522 glslangIntermediate->getLocalSize(1),
1523 glslangIntermediate->getLocalSize(2));
1524 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1525 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1526 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1527 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1528 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1529 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1530 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1531 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1532 }
1533 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001534#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001535 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001536 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001537 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001538
steve-lunarge7412492017-03-23 11:56:07 -06001539 glslang::TLayoutGeometry primitive;
1540
1541 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001542 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1543 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001544 primitive = glslangIntermediate->getOutputPrimitive();
1545 } else {
1546 primitive = glslangIntermediate->getInputPrimitive();
1547 }
1548
1549 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001550 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1551 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1552 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001553 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001554 }
John Kessenich4016e382016-07-15 11:53:56 -06001555 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001556 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1557
John Kesseniche6903322015-10-13 16:29:02 -06001558 switch (glslangIntermediate->getVertexSpacing()) {
1559 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1560 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1561 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001562 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001563 }
John Kessenich4016e382016-07-15 11:53:56 -06001564 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001565 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1566
1567 switch (glslangIntermediate->getVertexOrder()) {
1568 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1569 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001570 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001571 }
John Kessenich4016e382016-07-15 11:53:56 -06001572 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001573 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1574
1575 if (glslangIntermediate->getPointMode())
1576 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001577 break;
1578
1579 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001580 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001581 switch (glslangIntermediate->getInputPrimitive()) {
1582 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1583 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1584 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001585 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001586 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001587 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001588 }
John Kessenich4016e382016-07-15 11:53:56 -06001589 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001590 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001591
John Kessenich140f3df2015-06-26 16:58:36 -06001592 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1593
1594 switch (glslangIntermediate->getOutputPrimitive()) {
1595 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1596 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1597 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001598 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001599 }
John Kessenich4016e382016-07-15 11:53:56 -06001600 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001601 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1602 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1603 break;
1604
Daniel Kochdb32b242020-03-17 20:42:47 -04001605 case EShLangRayGen:
1606 case EShLangIntersect:
1607 case EShLangAnyHit:
1608 case EShLangClosestHit:
1609 case EShLangMiss:
1610 case EShLangCallable:
1611 {
1612 auto& extensions = glslangIntermediate->getRequestedExtensions();
1613 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1614 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1615 builder.addExtension("SPV_KHR_ray_tracing");
1616 }
1617 else {
1618 builder.addCapability(spv::CapabilityRayTracingNV);
1619 builder.addExtension("SPV_NV_ray_tracing");
1620 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001621 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001622 }
Chao Chen3c366992018-09-19 11:41:59 -07001623 case EShLangTaskNV:
1624 case EShLangMeshNV:
1625 builder.addCapability(spv::CapabilityMeshShadingNV);
1626 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1627 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1628 glslangIntermediate->getLocalSize(1),
1629 glslangIntermediate->getLocalSize(2));
1630 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001631 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1632 glslangIntermediate->getVertices());
1633 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1634 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001635
1636 switch (glslangIntermediate->getOutputPrimitive()) {
1637 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1638 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1639 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1640 default: mode = spv::ExecutionModeMax; break;
1641 }
1642 if (mode != spv::ExecutionModeMax)
1643 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1644 }
1645 break;
1646#endif
1647
John Kessenich140f3df2015-06-26 16:58:36 -06001648 default:
1649 break;
1650 }
John Kessenich140f3df2015-06-26 16:58:36 -06001651}
1652
John Kessenichfca82622016-11-26 13:23:20 -07001653// Finish creating SPV, after the traversal is complete.
1654void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001655{
John Kessenichf04c51b2018-08-03 15:56:12 -06001656 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001657 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001658 builder.setBuildPoint(shaderEntry->getLastBlock());
1659 builder.leaveFunction();
1660 }
1661
John Kessenich7ba63412015-12-20 17:37:07 -07001662 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001663 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1664 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001665
David Neto8c3d5b42019-10-21 14:50:31 -04001666 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001667 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001668 // Note: WebGPU code generation must have the opportunity to aggressively
1669 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001670 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001671}
1672
John Kessenichfca82622016-11-26 13:23:20 -07001673// Write the SPV into 'out'.
1674void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001675{
John Kessenichfca82622016-11-26 13:23:20 -07001676 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001677}
1678
1679//
1680// Implement the traversal functions.
1681//
1682// Return true from interior nodes to have the external traversal
1683// continue on to children. Return false if children were
1684// already processed.
1685//
1686
1687//
qining25262b32016-05-06 17:25:16 -04001688// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001689// - uniform/input reads
1690// - output writes
1691// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1692// - something simple that degenerates into the last bullet
1693//
1694void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1695{
qining75d1d802016-04-06 14:42:01 -04001696 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001697 if (symbol->getType().isStruct())
1698 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1699
qining75d1d802016-04-06 14:42:01 -04001700 if (symbol->getType().getQualifier().isSpecConstant())
1701 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1702
John Kessenich140f3df2015-06-26 16:58:36 -06001703 // getSymbolId() will set up all the IO decorations on the first call.
1704 // Formal function parameters were mapped during makeFunctions().
1705 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001706
John Kessenich7ba63412015-12-20 17:37:07 -07001707 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001708 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001709 // Consider adding to the OpEntryPoint interface list.
1710 // Only looking at structures if they have at least one member.
1711 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1712 spv::StorageClass sc = builder.getStorageClass(id);
1713 // Before SPIR-V 1.4, we only want to include Input and Output.
1714 // Starting with SPIR-V 1.4, we want all globals.
1715 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1716 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001717 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001718 }
John Kessenich5f77d862017-09-19 11:09:59 -06001719 }
John Kessenich9c14f772019-06-17 08:38:35 -06001720
Daniel Kochdb32b242020-03-17 20:42:47 -04001721 // If the SPIR-V type is required to be different than the AST type
1722 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001723 // translate now from the SPIR-V type to the AST type, for the consuming
1724 // operation.
1725 // Note this turns it from an l-value to an r-value.
1726 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1727 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1728 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001729 }
1730
1731 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001732 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001733 // Prepare to generate code for the access
1734
1735 // L-value chains will be computed left to right. We're on the symbol now,
1736 // which is the left-most part of the access chain, so now is "clear" time,
1737 // followed by setting the base.
1738 builder.clearAccessChain();
1739
1740 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001741 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001742 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001743 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001744 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001745 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001746 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001747 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001748 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1749 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001750 builder.setAccessChainRValue(id);
1751 else
1752 builder.setAccessChainLValue(id);
1753 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001754
John Kessenichb9197c82019-08-11 07:41:45 -06001755#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001756 // Process linkage-only nodes for any special additional interface work.
1757 if (linkageOnly) {
1758 if (glslangIntermediate->getHlslFunctionality1()) {
1759 // Map implicit counter buffers to their originating buffers, which should have been
1760 // seen by now, given earlier pruning of unused counters, and preservation of order
1761 // of declaration.
1762 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1763 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1764 // Save possible originating buffers for counter buffers, keyed by
1765 // making the potential counter-buffer name.
1766 std::string keyName = symbol->getName().c_str();
1767 keyName = glslangIntermediate->addCounterBufferName(keyName);
1768 counterOriginator[keyName] = symbol;
1769 } else {
1770 // Handle a counter buffer, by finding the saved originating buffer.
1771 std::string keyName = symbol->getName().c_str();
1772 auto it = counterOriginator.find(keyName);
1773 if (it != counterOriginator.end()) {
1774 id = getSymbolId(it->second);
1775 if (id != spv::NoResult) {
1776 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001777 if (counterId != spv::NoResult) {
1778 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001779 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001780 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001781 }
1782 }
1783 }
1784 }
1785 }
1786 }
John Kessenich155d3512019-08-08 23:29:20 -06001787#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001788}
1789
1790bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1791{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001792 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001793 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1794 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1795 }
1796 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1797 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1798 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001799
qining40887662016-04-03 22:20:42 -04001800 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1801 if (node->getType().getQualifier().isSpecConstant())
1802 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1803
John Kessenich140f3df2015-06-26 16:58:36 -06001804 // First, handle special cases
1805 switch (node->getOp()) {
1806 case glslang::EOpAssign:
1807 case glslang::EOpAddAssign:
1808 case glslang::EOpSubAssign:
1809 case glslang::EOpMulAssign:
1810 case glslang::EOpVectorTimesMatrixAssign:
1811 case glslang::EOpVectorTimesScalarAssign:
1812 case glslang::EOpMatrixTimesScalarAssign:
1813 case glslang::EOpMatrixTimesMatrixAssign:
1814 case glslang::EOpDivAssign:
1815 case glslang::EOpModAssign:
1816 case glslang::EOpAndAssign:
1817 case glslang::EOpInclusiveOrAssign:
1818 case glslang::EOpExclusiveOrAssign:
1819 case glslang::EOpLeftShiftAssign:
1820 case glslang::EOpRightShiftAssign:
1821 // A bin-op assign "a += b" means the same thing as "a = a + b"
1822 // where a is evaluated before b. For a simple assignment, GLSL
1823 // says to evaluate the left before the right. So, always, left
1824 // node then right node.
1825 {
1826 // get the left l-value, save it away
1827 builder.clearAccessChain();
1828 node->getLeft()->traverse(this);
1829 spv::Builder::AccessChain lValue = builder.getAccessChain();
1830
1831 // evaluate the right
1832 builder.clearAccessChain();
1833 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001834 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001835
1836 if (node->getOp() != glslang::EOpAssign) {
1837 // the left is also an r-value
1838 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001839 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001840
1841 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001842 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001843 TranslateNoContractionDecoration(node->getType().getQualifier()),
1844 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001845 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001846 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1847 node->getType().getBasicType());
1848
1849 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001850 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001851 }
1852
1853 // store the result
1854 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001855 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001856
1857 // assignments are expressions having an rValue after they are evaluated...
1858 builder.clearAccessChain();
1859 builder.setAccessChainRValue(rValue);
1860 }
1861 return false;
1862 case glslang::EOpIndexDirect:
1863 case glslang::EOpIndexDirectStruct:
1864 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001865 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001866 // Get the left part of the access chain.
1867 node->getLeft()->traverse(this);
1868
1869 // Add the next element in the chain
1870
David Netoa901ffe2016-06-08 14:11:40 +01001871 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001872 if (! node->getLeft()->getType().isArray() &&
1873 node->getLeft()->getType().isVector() &&
1874 node->getOp() == glslang::EOpIndexDirect) {
1875 // This is essentially a hard-coded vector swizzle of size 1,
1876 // so short circuit the access-chain stuff with a swizzle.
1877 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001878 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001879 int dummySize;
1880 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1881 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001882 glslangIntermediate->getBaseAlignmentScalar(
1883 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001884 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001885
1886 // Load through a block reference is performed with a dot operator that
1887 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1888 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001889 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001890 !node->getLeft()->getType().isArray() &&
1891 node->getOp() == glslang::EOpIndexDirectStruct)
1892 {
1893 spv::Id left = accessChainLoad(node->getLeft()->getType());
1894 builder.clearAccessChain();
1895 builder.setAccessChainLValue(left);
1896 }
1897
David Netoa901ffe2016-06-08 14:11:40 +01001898 int spvIndex = glslangIndex;
1899 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1900 node->getOp() == glslang::EOpIndexDirectStruct)
1901 {
1902 // This may be, e.g., an anonymous block-member selection, which generally need
1903 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001904 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1905 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1906 std::vector<int>& remapper = memberRemapper[glslangId];
1907 assert(remapper.size() > 0);
1908 spvIndex = remapper[glslangIndex];
1909 }
David Netoa901ffe2016-06-08 14:11:40 +01001910 }
John Kessenichebb50532016-05-16 19:22:05 -06001911
David Netoa901ffe2016-06-08 14:11:40 +01001912 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001913 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1914 TranslateCoherent(node->getLeft()->getType()),
1915 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001916
1917 // Add capabilities here for accessing PointSize and clip/cull distance.
1918 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001919 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001920 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001921 }
1922 }
1923 return false;
1924 case glslang::EOpIndexIndirect:
1925 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001926 // Array, matrix, or vector indirection with variable index.
1927 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001928 // matrices are arrays of vectors, so will also work for a matrix.
1929 // Will use the access chain's 'component' for variable index into a vector.
1930
1931 // This adapter is building access chains left to right.
1932 // Set up the access chain to the left.
1933 node->getLeft()->traverse(this);
1934
1935 // save it so that computing the right side doesn't trash it
1936 spv::Builder::AccessChain partial = builder.getAccessChain();
1937
1938 // compute the next index in the chain
1939 builder.clearAccessChain();
1940 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001941 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001942
John Kessenich5611c6d2018-04-05 11:25:02 -06001943 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1944
John Kessenich140f3df2015-06-26 16:58:36 -06001945 // restore the saved access chain
1946 builder.setAccessChain(partial);
1947
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001948 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1949 int dummySize;
1950 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1951 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001952 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1953 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001954 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001955 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1956 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001957 }
1958 return false;
1959 case glslang::EOpVectorSwizzle:
1960 {
1961 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001962 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001963 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001964 int dummySize;
1965 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1966 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001967 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1968 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001969 }
1970 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001971 case glslang::EOpMatrixSwizzle:
1972 logger->missingFunctionality("matrix swizzle");
1973 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001974 case glslang::EOpLogicalOr:
1975 case glslang::EOpLogicalAnd:
1976 {
1977
1978 // These may require short circuiting, but can sometimes be done as straight
1979 // binary operations. The right operand must be short circuited if it has
1980 // side effects, and should probably be if it is complex.
1981 if (isTrivial(node->getRight()->getAsTyped()))
1982 break; // handle below as a normal binary operation
1983 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001984 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1985 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001986 builder.clearAccessChain();
1987 builder.setAccessChainRValue(result);
1988 }
1989 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001990 default:
1991 break;
1992 }
1993
1994 // Assume generic binary op...
1995
John Kessenich32cfd492016-02-02 12:37:46 -07001996 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001997 builder.clearAccessChain();
1998 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001999 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002000
John Kessenich32cfd492016-02-02 12:37:46 -07002001 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002002 builder.clearAccessChain();
2003 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002004 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002005
John Kessenich32cfd492016-02-02 12:37:46 -07002006 // get result
John Kessenichead86222018-03-28 18:01:20 -06002007 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002008 TranslateNoContractionDecoration(node->getType().getQualifier()),
2009 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002010 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002011 convertGlslangToSpvType(node->getType()), left, right,
2012 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002013
John Kessenich50e57562015-12-21 21:21:11 -07002014 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002015 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002016 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002017 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002018 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002019 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002020 return false;
2021 }
John Kessenich140f3df2015-06-26 16:58:36 -06002022}
2023
John Kessenich9c14f772019-06-17 08:38:35 -06002024// Figure out what, if any, type changes are needed when accessing a specific built-in.
2025// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2026// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002027std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002028 const glslang::TType& glslangType)
2029{
Daniel Kochdb32b242020-03-17 20:42:47 -04002030 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002031 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002032 case glslang::EbvSubGroupEqMask:
2033 case glslang::EbvSubGroupGeMask:
2034 case glslang::EbvSubGroupGtMask:
2035 case glslang::EbvSubGroupLeMask:
2036 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002037 // these require changing a 64-bit scaler -> a vector of 32-bit components
2038 if (glslangType.isVector())
2039 break;
2040 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2041 builder.makeUintType(64));
2042 return ret;
2043 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002044 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2045 // builtins. During visitBinary we insert a transpose
2046 case glslang::EbvWorldToObject3x4:
2047 case glslang::EbvObjectToWorld3x4: {
2048 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2049 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2050 );
2051 return ret;
2052 }
John Kessenich9c14f772019-06-17 08:38:35 -06002053 default:
2054 break;
2055 }
2056
2057 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2058 return ret;
2059}
2060
2061// For an object previously identified (see getForcedType() and forceType)
2062// as needing type translations, do the translation needed for a load, turning
2063// an L-value into in R-value.
2064spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2065{
2066 const auto forceIt = forceType.find(object);
2067 if (forceIt == forceType.end())
2068 return object;
2069
2070 spv::Id desiredTypeId = forceIt->second;
2071 spv::Id objectTypeId = builder.getTypeId(object);
2072 assert(builder.isPointerType(objectTypeId));
2073 objectTypeId = builder.getContainedTypeId(objectTypeId);
2074 if (builder.isVectorType(objectTypeId) &&
2075 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2076 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2077 // handle 32-bit v.xy* -> 64-bit
2078 builder.clearAccessChain();
2079 builder.setAccessChainLValue(object);
2080 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2081 std::vector<spv::Id> components;
2082 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2083 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2084
2085 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2086 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2087 builder.createCompositeConstruct(vecType, components));
2088 } else {
2089 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2090 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002091 } else if (builder.isMatrixType(objectTypeId)) {
2092 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2093 // and we insert a transpose after loading the original non-transposed builtins
2094 builder.clearAccessChain();
2095 builder.setAccessChainLValue(object);
2096 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2097 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2098
2099 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002100 logger->missingFunctionality("forcing non 32-bit vector type");
2101 }
2102
2103 return object;
2104}
2105
John Kessenich140f3df2015-06-26 16:58:36 -06002106bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2107{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002108 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002109
qining40887662016-04-03 22:20:42 -04002110 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2111 if (node->getType().getQualifier().isSpecConstant())
2112 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2113
John Kessenichfc51d282015-08-19 13:34:18 -06002114 spv::Id result = spv::NoResult;
2115
2116 // try texturing first
2117 result = createImageTextureFunctionCall(node);
2118 if (result != spv::NoResult) {
2119 builder.clearAccessChain();
2120 builder.setAccessChainRValue(result);
2121
2122 return false; // done with this node
2123 }
2124
2125 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002126
2127 if (node->getOp() == glslang::EOpArrayLength) {
2128 // Quite special; won't want to evaluate the operand.
2129
John Kessenich5611c6d2018-04-05 11:25:02 -06002130 // Currently, the front-end does not allow .length() on an array until it is sized,
2131 // except for the last block membeor of an SSBO.
2132 // TODO: If this changes, link-time sized arrays might show up here, and need their
2133 // size extracted.
2134
John Kessenichc9a80832015-09-12 12:17:44 -06002135 // Normal .length() would have been constant folded by the front-end.
2136 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002137 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002138
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002139 spv::Id length;
2140 if (node->getOperand()->getType().isCoopMat()) {
2141 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2142
2143 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2144 assert(builder.isCooperativeMatrixType(typeId));
2145
2146 length = builder.createCooperativeMatrixLength(typeId);
2147 } else {
2148 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2149 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002150 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2151 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002152 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2153 }
John Kessenichc9a80832015-09-12 12:17:44 -06002154
John Kessenich8c869672018-11-28 07:01:37 -07002155 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2156 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2157 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002158 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2159 if (builder.isInSpecConstCodeGenMode()) {
2160 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2161 } else {
2162 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2163 }
2164 }
John Kessenich8c869672018-11-28 07:01:37 -07002165
John Kessenichc9a80832015-09-12 12:17:44 -06002166 builder.clearAccessChain();
2167 builder.setAccessChainRValue(length);
2168
2169 return false;
2170 }
2171
John Kessenichfc51d282015-08-19 13:34:18 -06002172 // Start by evaluating the operand
2173
John Kessenich8c8505c2016-07-26 12:50:38 -06002174 // Does it need a swizzle inversion? If so, evaluation is inverted;
2175 // operate first on the swizzle base, then apply the swizzle.
2176 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002177 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2178 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002179 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2180 invertedType = getInvertedSwizzleType(*node->getOperand());
2181
John Kessenich140f3df2015-06-26 16:58:36 -06002182 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002183 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002184 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002185 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002186 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002187 operandNode = node->getOperand();
2188
2189 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002190
Rex Xufc618912015-09-09 16:42:49 +08002191 spv::Id operand = spv::NoResult;
2192
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002193 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2194
John Kessenichfb4f2332019-08-09 03:49:15 -06002195#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002196 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2197 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002198 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002199 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002200 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002201 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2202 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2203 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002204#endif
2205 {
John Kessenich32cfd492016-02-02 12:37:46 -07002206 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002207 }
John Kessenich140f3df2015-06-26 16:58:36 -06002208
John Kessenichead86222018-03-28 18:01:20 -06002209 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002210 TranslateNoContractionDecoration(node->getType().getQualifier()),
2211 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002212
2213 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002214 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002215 result = createConversion(node->getOp(), decorations, resultType(), operand,
2216 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002217
2218 // if not, then possibly an operation
2219 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002220 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2221 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002222
2223 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002224 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002225 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002226 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002227 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002228
John Kessenich140f3df2015-06-26 16:58:36 -06002229 builder.clearAccessChain();
2230 builder.setAccessChainRValue(result);
2231
2232 return false; // done with this node
2233 }
2234
2235 // it must be a special case, check...
2236 switch (node->getOp()) {
2237 case glslang::EOpPostIncrement:
2238 case glslang::EOpPostDecrement:
2239 case glslang::EOpPreIncrement:
2240 case glslang::EOpPreDecrement:
2241 {
2242 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002243 spv::Id one = 0;
2244 if (node->getBasicType() == glslang::EbtFloat)
2245 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002246#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002247 else if (node->getBasicType() == glslang::EbtDouble)
2248 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002249 else if (node->getBasicType() == glslang::EbtFloat16)
2250 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002251 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2252 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002253 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2254 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002255 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2256 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002257#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002258 else
2259 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002260 glslang::TOperator op;
2261 if (node->getOp() == glslang::EOpPreIncrement ||
2262 node->getOp() == glslang::EOpPostIncrement)
2263 op = glslang::EOpAdd;
2264 else
2265 op = glslang::EOpSub;
2266
John Kessenichead86222018-03-28 18:01:20 -06002267 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002268 convertGlslangToSpvType(node->getType()), operand, one,
2269 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002270 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002271
2272 // The result of operation is always stored, but conditionally the
2273 // consumed result. The consumed result is always an r-value.
2274 builder.accessChainStore(result);
2275 builder.clearAccessChain();
2276 if (node->getOp() == glslang::EOpPreIncrement ||
2277 node->getOp() == glslang::EOpPreDecrement)
2278 builder.setAccessChainRValue(result);
2279 else
2280 builder.setAccessChainRValue(operand);
2281 }
2282
2283 return false;
2284
John Kessenich155d3512019-08-08 23:29:20 -06002285#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002286 case glslang::EOpEmitStreamVertex:
2287 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2288 return false;
2289 case glslang::EOpEndStreamPrimitive:
2290 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2291 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002292#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002293
2294 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002295 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002296 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002297 }
John Kessenich140f3df2015-06-26 16:58:36 -06002298}
2299
Jeff Bolz53134492019-06-25 13:31:10 -05002300// Construct a composite object, recursively copying members if their types don't match
2301spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2302{
2303 for (int c = 0; c < (int)constituents.size(); ++c) {
2304 spv::Id& constituent = constituents[c];
2305 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2306 spv::Id rType = builder.getTypeId(constituent);
2307 if (lType != rType) {
2308 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2309 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2310 } else if (builder.isStructType(rType)) {
2311 std::vector<spv::Id> rTypeConstituents;
2312 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2313 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002314 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2315 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002316 }
2317 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2318 } else {
2319 assert(builder.isArrayType(rType));
2320 std::vector<spv::Id> rTypeConstituents;
2321 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2322
2323 spv::Id elementRType = builder.getContainedTypeId(rType);
2324 for (int i = 0; i < numrTypeConstituents; ++i) {
2325 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2326 }
2327 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2328 }
2329 }
2330 }
2331 return builder.createCompositeConstruct(resultTypeId, constituents);
2332}
2333
John Kessenich140f3df2015-06-26 16:58:36 -06002334bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2335{
qining27e04a02016-04-14 16:40:20 -04002336 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2337 if (node->getType().getQualifier().isSpecConstant())
2338 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2339
John Kessenichfc51d282015-08-19 13:34:18 -06002340 spv::Id result = spv::NoResult;
John Kessenichbbbd9a22020-03-03 07:21:37 -07002341 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
John Kessenich8985fc92020-03-03 10:25:07 -07002342 spv::Builder::AccessChain complexLvalue; // for holding swizzling l-values too complex for SPIR-V,
2343 // for at out parameter
John Kessenichbbbd9a22020-03-03 07:21:37 -07002344 spv::Id temporaryLvalue = spv::NoResult; // temporary to pass, as proxy for complexLValue
2345
John Kessenich8985fc92020-03-03 10:25:07 -07002346 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2347 invertedType :
2348 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002349
2350 // try texturing
2351 result = createImageTextureFunctionCall(node);
2352 if (result != spv::NoResult) {
2353 builder.clearAccessChain();
2354 builder.setAccessChainRValue(result);
2355
2356 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002357 }
2358#ifndef GLSLANG_WEB
2359 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002360 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002361 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002362 // "imageStore" is a special case, which has no result
2363 return false;
2364 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002365#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002366
John Kessenich140f3df2015-06-26 16:58:36 -06002367 glslang::TOperator binOp = glslang::EOpNull;
2368 bool reduceComparison = true;
2369 bool isMatrix = false;
2370 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002371 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002372
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002373 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2374
John Kessenich140f3df2015-06-26 16:58:36 -06002375 assert(node->getOp());
2376
John Kessenichf6640762016-08-01 19:44:00 -06002377 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002378
2379 switch (node->getOp()) {
2380 case glslang::EOpSequence:
2381 {
2382 if (preVisit)
2383 ++sequenceDepth;
2384 else
2385 --sequenceDepth;
2386
2387 if (sequenceDepth == 1) {
2388 // If this is the parent node of all the functions, we want to see them
2389 // early, so all call points have actual SPIR-V functions to reference.
2390 // In all cases, still let the traverser visit the children for us.
2391 makeFunctions(node->getAsAggregate()->getSequence());
2392
John Kessenich6fccb3c2016-09-19 16:01:41 -06002393 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002394 // anything else gets there, so visit out of order, doing them all now.
2395 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2396
John Kessenich6a60c2f2016-12-08 21:01:59 -07002397 // 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 -06002398 // so do them manually.
2399 visitFunctions(node->getAsAggregate()->getSequence());
2400
2401 return false;
2402 }
2403
2404 return true;
2405 }
2406 case glslang::EOpLinkerObjects:
2407 {
2408 if (visit == glslang::EvPreVisit)
2409 linkageOnly = true;
2410 else
2411 linkageOnly = false;
2412
2413 return true;
2414 }
2415 case glslang::EOpComma:
2416 {
2417 // processing from left to right naturally leaves the right-most
2418 // lying around in the access chain
2419 glslang::TIntermSequence& glslangOperands = node->getSequence();
2420 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2421 glslangOperands[i]->traverse(this);
2422
2423 return false;
2424 }
2425 case glslang::EOpFunction:
2426 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002427 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002428 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002429 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002430 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002431 } else {
2432 handleFunctionEntry(node);
2433 }
2434 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002435 if (inEntryPoint)
2436 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002437 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002438 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002439 }
2440
2441 return true;
2442 case glslang::EOpParameters:
2443 // Parameters will have been consumed by EOpFunction processing, but not
2444 // the body, so we still visited the function node's children, making this
2445 // child redundant.
2446 return false;
2447 case glslang::EOpFunctionCall:
2448 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002449 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002450 if (node->isUserDefined())
2451 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002452 if (result) {
2453 builder.clearAccessChain();
2454 builder.setAccessChainRValue(result);
2455 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002456 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002457
2458 return false;
2459 }
2460 case glslang::EOpConstructMat2x2:
2461 case glslang::EOpConstructMat2x3:
2462 case glslang::EOpConstructMat2x4:
2463 case glslang::EOpConstructMat3x2:
2464 case glslang::EOpConstructMat3x3:
2465 case glslang::EOpConstructMat3x4:
2466 case glslang::EOpConstructMat4x2:
2467 case glslang::EOpConstructMat4x3:
2468 case glslang::EOpConstructMat4x4:
2469 case glslang::EOpConstructDMat2x2:
2470 case glslang::EOpConstructDMat2x3:
2471 case glslang::EOpConstructDMat2x4:
2472 case glslang::EOpConstructDMat3x2:
2473 case glslang::EOpConstructDMat3x3:
2474 case glslang::EOpConstructDMat3x4:
2475 case glslang::EOpConstructDMat4x2:
2476 case glslang::EOpConstructDMat4x3:
2477 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002478 case glslang::EOpConstructIMat2x2:
2479 case glslang::EOpConstructIMat2x3:
2480 case glslang::EOpConstructIMat2x4:
2481 case glslang::EOpConstructIMat3x2:
2482 case glslang::EOpConstructIMat3x3:
2483 case glslang::EOpConstructIMat3x4:
2484 case glslang::EOpConstructIMat4x2:
2485 case glslang::EOpConstructIMat4x3:
2486 case glslang::EOpConstructIMat4x4:
2487 case glslang::EOpConstructUMat2x2:
2488 case glslang::EOpConstructUMat2x3:
2489 case glslang::EOpConstructUMat2x4:
2490 case glslang::EOpConstructUMat3x2:
2491 case glslang::EOpConstructUMat3x3:
2492 case glslang::EOpConstructUMat3x4:
2493 case glslang::EOpConstructUMat4x2:
2494 case glslang::EOpConstructUMat4x3:
2495 case glslang::EOpConstructUMat4x4:
2496 case glslang::EOpConstructBMat2x2:
2497 case glslang::EOpConstructBMat2x3:
2498 case glslang::EOpConstructBMat2x4:
2499 case glslang::EOpConstructBMat3x2:
2500 case glslang::EOpConstructBMat3x3:
2501 case glslang::EOpConstructBMat3x4:
2502 case glslang::EOpConstructBMat4x2:
2503 case glslang::EOpConstructBMat4x3:
2504 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002505 case glslang::EOpConstructF16Mat2x2:
2506 case glslang::EOpConstructF16Mat2x3:
2507 case glslang::EOpConstructF16Mat2x4:
2508 case glslang::EOpConstructF16Mat3x2:
2509 case glslang::EOpConstructF16Mat3x3:
2510 case glslang::EOpConstructF16Mat3x4:
2511 case glslang::EOpConstructF16Mat4x2:
2512 case glslang::EOpConstructF16Mat4x3:
2513 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002514 isMatrix = true;
2515 // fall through
2516 case glslang::EOpConstructFloat:
2517 case glslang::EOpConstructVec2:
2518 case glslang::EOpConstructVec3:
2519 case glslang::EOpConstructVec4:
2520 case glslang::EOpConstructDouble:
2521 case glslang::EOpConstructDVec2:
2522 case glslang::EOpConstructDVec3:
2523 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002524 case glslang::EOpConstructFloat16:
2525 case glslang::EOpConstructF16Vec2:
2526 case glslang::EOpConstructF16Vec3:
2527 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002528 case glslang::EOpConstructBool:
2529 case glslang::EOpConstructBVec2:
2530 case glslang::EOpConstructBVec3:
2531 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002532 case glslang::EOpConstructInt8:
2533 case glslang::EOpConstructI8Vec2:
2534 case glslang::EOpConstructI8Vec3:
2535 case glslang::EOpConstructI8Vec4:
2536 case glslang::EOpConstructUint8:
2537 case glslang::EOpConstructU8Vec2:
2538 case glslang::EOpConstructU8Vec3:
2539 case glslang::EOpConstructU8Vec4:
2540 case glslang::EOpConstructInt16:
2541 case glslang::EOpConstructI16Vec2:
2542 case glslang::EOpConstructI16Vec3:
2543 case glslang::EOpConstructI16Vec4:
2544 case glslang::EOpConstructUint16:
2545 case glslang::EOpConstructU16Vec2:
2546 case glslang::EOpConstructU16Vec3:
2547 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002548 case glslang::EOpConstructInt:
2549 case glslang::EOpConstructIVec2:
2550 case glslang::EOpConstructIVec3:
2551 case glslang::EOpConstructIVec4:
2552 case glslang::EOpConstructUint:
2553 case glslang::EOpConstructUVec2:
2554 case glslang::EOpConstructUVec3:
2555 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002556 case glslang::EOpConstructInt64:
2557 case glslang::EOpConstructI64Vec2:
2558 case glslang::EOpConstructI64Vec3:
2559 case glslang::EOpConstructI64Vec4:
2560 case glslang::EOpConstructUint64:
2561 case glslang::EOpConstructU64Vec2:
2562 case glslang::EOpConstructU64Vec3:
2563 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002564 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002565 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002566 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002567 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002568 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002569 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002570 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002571 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002572 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002573 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002574 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002575 else if (node->getOp() == glslang::EOpConstructStruct ||
2576 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2577 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002578 std::vector<spv::Id> constituents;
2579 for (int c = 0; c < (int)arguments.size(); ++c)
2580 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002581 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002582 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002583 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002584 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002585 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002586
2587 builder.clearAccessChain();
2588 builder.setAccessChainRValue(constructed);
2589
2590 return false;
2591 }
2592
2593 // These six are component-wise compares with component-wise results.
2594 // Forward on to createBinaryOperation(), requesting a vector result.
2595 case glslang::EOpLessThan:
2596 case glslang::EOpGreaterThan:
2597 case glslang::EOpLessThanEqual:
2598 case glslang::EOpGreaterThanEqual:
2599 case glslang::EOpVectorEqual:
2600 case glslang::EOpVectorNotEqual:
2601 {
2602 // Map the operation to a binary
2603 binOp = node->getOp();
2604 reduceComparison = false;
2605 switch (node->getOp()) {
2606 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2607 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2608 default: binOp = node->getOp(); break;
2609 }
2610
2611 break;
2612 }
2613 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002614 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002615 binOp = glslang::EOpMul;
2616 break;
2617 case glslang::EOpOuterProduct:
2618 // two vectors multiplied to make a matrix
2619 binOp = glslang::EOpOuterProduct;
2620 break;
2621 case glslang::EOpDot:
2622 {
qining25262b32016-05-06 17:25:16 -04002623 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002624 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002625 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002626 binOp = glslang::EOpMul;
2627 break;
2628 }
2629 case glslang::EOpMod:
2630 // when an aggregate, this is the floating-point mod built-in function,
2631 // which can be emitted by the one in createBinaryOperation()
2632 binOp = glslang::EOpMod;
2633 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002634
John Kessenich140f3df2015-06-26 16:58:36 -06002635 case glslang::EOpEmitVertex:
2636 case glslang::EOpEndPrimitive:
2637 case glslang::EOpBarrier:
2638 case glslang::EOpMemoryBarrier:
2639 case glslang::EOpMemoryBarrierAtomicCounter:
2640 case glslang::EOpMemoryBarrierBuffer:
2641 case glslang::EOpMemoryBarrierImage:
2642 case glslang::EOpMemoryBarrierShared:
2643 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002644 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002645 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002646 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002647 case glslang::EOpWorkgroupMemoryBarrier:
2648 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002649 case glslang::EOpSubgroupBarrier:
2650 case glslang::EOpSubgroupMemoryBarrier:
2651 case glslang::EOpSubgroupMemoryBarrierBuffer:
2652 case glslang::EOpSubgroupMemoryBarrierImage:
2653 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002654 noReturnValue = true;
2655 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2656 break;
2657
John Kessenich426394d2015-07-23 10:22:48 -06002658 case glslang::EOpAtomicAdd:
2659 case glslang::EOpAtomicMin:
2660 case glslang::EOpAtomicMax:
2661 case glslang::EOpAtomicAnd:
2662 case glslang::EOpAtomicOr:
2663 case glslang::EOpAtomicXor:
2664 case glslang::EOpAtomicExchange:
2665 case glslang::EOpAtomicCompSwap:
2666 atomic = true;
2667 break;
2668
John Kesseniche5eee8f2019-10-18 01:03:11 -06002669#ifndef GLSLANG_WEB
2670 case glslang::EOpAtomicStore:
2671 noReturnValue = true;
2672 // fallthrough
2673 case glslang::EOpAtomicLoad:
2674 atomic = true;
2675 break;
2676
John Kessenich0d0c6d32017-07-23 16:08:26 -06002677 case glslang::EOpAtomicCounterAdd:
2678 case glslang::EOpAtomicCounterSubtract:
2679 case glslang::EOpAtomicCounterMin:
2680 case glslang::EOpAtomicCounterMax:
2681 case glslang::EOpAtomicCounterAnd:
2682 case glslang::EOpAtomicCounterOr:
2683 case glslang::EOpAtomicCounterXor:
2684 case glslang::EOpAtomicCounterExchange:
2685 case glslang::EOpAtomicCounterCompSwap:
2686 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2687 builder.addCapability(spv::CapabilityAtomicStorageOps);
2688 atomic = true;
2689 break;
2690
Ian Romanickb3bd4022019-01-21 08:57:25 -08002691 case glslang::EOpAbsDifference:
2692 case glslang::EOpAddSaturate:
2693 case glslang::EOpSubSaturate:
2694 case glslang::EOpAverage:
2695 case glslang::EOpAverageRounded:
2696 case glslang::EOpMul32x16:
2697 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2698 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2699 binOp = node->getOp();
2700 break;
2701
Daniel Kochdb32b242020-03-17 20:42:47 -04002702 case glslang::EOpIgnoreIntersection:
2703 case glslang::EOpTerminateRay:
2704 case glslang::EOpTrace:
2705 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002706 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2707 noReturnValue = true;
2708 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002709 case glslang::EOpRayQueryInitialize:
2710 case glslang::EOpRayQueryTerminate:
2711 case glslang::EOpRayQueryGenerateIntersection:
2712 case glslang::EOpRayQueryConfirmIntersection:
2713 noReturnValue = true;
2714 break;
2715
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002716 case glslang::EOpCooperativeMatrixLoad:
2717 case glslang::EOpCooperativeMatrixStore:
2718 noReturnValue = true;
2719 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002720 case glslang::EOpBeginInvocationInterlock:
2721 case glslang::EOpEndInvocationInterlock:
2722 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2723 noReturnValue = true;
2724 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002725#endif
Chao Chen3c366992018-09-19 11:41:59 -07002726
Jeff Bolz04d73732019-05-31 13:06:01 -05002727 case glslang::EOpDebugPrintf:
2728 noReturnValue = true;
2729 break;
2730
John Kessenich140f3df2015-06-26 16:58:36 -06002731 default:
2732 break;
2733 }
2734
2735 //
2736 // See if it maps to a regular operation.
2737 //
John Kessenich140f3df2015-06-26 16:58:36 -06002738 if (binOp != glslang::EOpNull) {
2739 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2740 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2741 assert(left && right);
2742
2743 builder.clearAccessChain();
2744 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002745 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002746
2747 builder.clearAccessChain();
2748 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002749 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002750
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002751 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002752 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002753 TranslateNoContractionDecoration(node->getType().getQualifier()),
2754 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002755 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002756 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002757 left->getType().getBasicType(), reduceComparison);
2758
2759 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002760 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002761 builder.clearAccessChain();
2762 builder.setAccessChainRValue(result);
2763
2764 return false;
2765 }
2766
John Kessenich426394d2015-07-23 10:22:48 -06002767 //
2768 // Create the list of operands.
2769 //
John Kessenich140f3df2015-06-26 16:58:36 -06002770 glslang::TIntermSequence& glslangOperands = node->getSequence();
2771 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002772 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002773 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002774 // special case l-value operands; there are just a few
2775 bool lvalue = false;
2776 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002777 case glslang::EOpModf:
2778 if (arg == 1)
2779 lvalue = true;
2780 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002781
Torosdagli06c2eee2020-03-19 11:09:57 -04002782 case glslang::EOpRayQueryInitialize:
2783 case glslang::EOpRayQueryGenerateIntersection:
2784 case glslang::EOpRayQueryGetIntersectionType:
2785 case glslang::EOpRayQueryGetIntersectionT:
2786 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2787 case glslang::EOpRayQueryGetIntersectionInstanceId:
2788 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2789 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2790 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2791 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2792 case glslang::EOpRayQueryGetIntersectionFrontFace:
2793 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2794 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2795 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2796 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2797 if (arg == 0)
2798 lvalue = true;
2799 break;
2800
John Kesseniche5eee8f2019-10-18 01:03:11 -06002801 case glslang::EOpAtomicAdd:
2802 case glslang::EOpAtomicMin:
2803 case glslang::EOpAtomicMax:
2804 case glslang::EOpAtomicAnd:
2805 case glslang::EOpAtomicOr:
2806 case glslang::EOpAtomicXor:
2807 case glslang::EOpAtomicExchange:
2808 case glslang::EOpAtomicCompSwap:
2809 if (arg == 0)
2810 lvalue = true;
2811 break;
2812
John Kessenicha28f7a72019-08-06 07:00:58 -06002813#ifndef GLSLANG_WEB
2814 case glslang::EOpFrexp:
2815 if (arg == 1)
2816 lvalue = true;
2817 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002818 case glslang::EOpInterpolateAtSample:
2819 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002820 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002821 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002822 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002823
2824 // Does it need a swizzle inversion? If so, evaluation is inverted;
2825 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002826 // That is, we transform
2827 //
2828 // interpolate(v.zy) -> interpolate(v).zy
2829 //
John Kessenichecba76f2017-01-06 00:34:48 -07002830 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002831 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002832 invertedType = convertGlslangToSpvType(
2833 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002834 }
Rex Xu7a26c172015-12-08 17:12:09 +08002835 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002836 case glslang::EOpAtomicLoad:
2837 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002838 case glslang::EOpAtomicCounterAdd:
2839 case glslang::EOpAtomicCounterSubtract:
2840 case glslang::EOpAtomicCounterMin:
2841 case glslang::EOpAtomicCounterMax:
2842 case glslang::EOpAtomicCounterAnd:
2843 case glslang::EOpAtomicCounterOr:
2844 case glslang::EOpAtomicCounterXor:
2845 case glslang::EOpAtomicCounterExchange:
2846 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002847 if (arg == 0)
2848 lvalue = true;
2849 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002850 case glslang::EOpAddCarry:
2851 case glslang::EOpSubBorrow:
2852 if (arg == 2)
2853 lvalue = true;
2854 break;
2855 case glslang::EOpUMulExtended:
2856 case glslang::EOpIMulExtended:
2857 if (arg >= 2)
2858 lvalue = true;
2859 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002860 case glslang::EOpCooperativeMatrixLoad:
2861 if (arg == 0 || arg == 1)
2862 lvalue = true;
2863 break;
2864 case glslang::EOpCooperativeMatrixStore:
2865 if (arg == 1)
2866 lvalue = true;
2867 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002868#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002869 default:
2870 break;
2871 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002872 builder.clearAccessChain();
2873 if (invertedType != spv::NoType && arg == 0)
2874 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2875 else
2876 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002877
John Kessenichb9197c82019-08-11 07:41:45 -06002878#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002879 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2880 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2881
2882 if (arg == 1) {
2883 // fold "element" parameter into the access chain
2884 spv::Builder::AccessChain save = builder.getAccessChain();
2885 builder.clearAccessChain();
2886 glslangOperands[2]->traverse(this);
2887
2888 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2889
2890 builder.setAccessChain(save);
2891
2892 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002893 builder.accessChainPush(elementId,
2894 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2895 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002896
2897 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2898 unsigned int alignment = builder.getAccessChain().alignment;
2899
2900 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2901 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2902 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2903 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2904 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002905 if (builder.getStorageClass(builder.getAccessChain().base) ==
2906 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002907 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2908 }
2909
2910 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2911
2912 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2913 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2914 }
2915
John Kessenich8985fc92020-03-03 10:25:07 -07002916 if (memoryAccess &
2917 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2918 memoryAccessOperands.push_back(spv::IdImmediate(true,
2919 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002920 }
2921 } else if (arg == 2) {
2922 continue;
2923 }
2924 }
John Kessenichb9197c82019-08-11 07:41:45 -06002925#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002926
John Kessenichbbbd9a22020-03-03 07:21:37 -07002927 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002928 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002929 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2930 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2931 // reduce to a simple access chain. So, we need a temporary vector to
2932 // receive the result, and must later swizzle that into the original
2933 // l-value.
2934 complexLvalue = builder.getAccessChain();
John Kessenich8985fc92020-03-03 10:25:07 -07002935 temporaryLvalue = builder.createVariable(spv::StorageClassFunction,
2936 builder.accessChainGetInferredType(), "swizzleTemp");
John Kessenichbbbd9a22020-03-03 07:21:37 -07002937 operands.push_back(temporaryLvalue);
2938 } else {
2939 operands.push_back(builder.accessChainGetLValue());
2940 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002941 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2942 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2943 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002944 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04002945 glslang::TOperator glslangOp = node->getOp();
2946 if (arg == 1 &&
2947 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
2948 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
2949 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
2950 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
2951 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
2952 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
2953 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
2954 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
2955 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
2956 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
2957 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
2958 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
2959 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
2960 )) {
2961 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
2962 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
2963 }
2964 else {
2965 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
2966 }
2967
John Kesseniche485c7a2017-05-31 18:50:53 -06002968 }
John Kessenich140f3df2015-06-26 16:58:36 -06002969 }
John Kessenich426394d2015-07-23 10:22:48 -06002970
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002971 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002972#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002973 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2974 std::vector<spv::IdImmediate> idImmOps;
2975
2976 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2977 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2978 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2979 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2980 // get the pointee type
2981 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2982 assert(builder.isCooperativeMatrixType(typeId));
2983 // do the op
2984 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2985 // store the result to the pointer (out param 'm')
2986 builder.createStore(result, operands[0]);
2987 result = 0;
2988 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2989 std::vector<spv::IdImmediate> idImmOps;
2990
2991 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2992 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2993 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2994 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2995 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2996
2997 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2998 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06002999 } else
3000#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003001 if (atomic) {
3002 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003003 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3004 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003005 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3006 if (!nonSemanticDebugPrintf) {
3007 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3008 }
3009 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3010 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003011 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003012 // Pass through to generic operations.
3013 switch (glslangOperands.size()) {
3014 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003015 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003016 break;
3017 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003018 {
3019 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003020 TranslateNoContractionDecoration(node->getType().getQualifier()),
3021 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003022 result = createUnaryOperation(
3023 node->getOp(), decorations,
3024 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003025 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003026 }
John Kessenich426394d2015-07-23 10:22:48 -06003027 break;
3028 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003029 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003030 break;
3031 }
John Kessenichbbbd9a22020-03-03 07:21:37 -07003032 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003033 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenichbbbd9a22020-03-03 07:21:37 -07003034 else if (temporaryLvalue != spv::NoResult) {
3035 builder.setAccessChain(complexLvalue);
3036 builder.accessChainStore(builder.createLoad(temporaryLvalue));
3037 }
John Kessenich140f3df2015-06-26 16:58:36 -06003038 }
3039
3040 if (noReturnValue)
3041 return false;
3042
3043 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003044 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003045 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003046 } else {
3047 builder.clearAccessChain();
3048 builder.setAccessChainRValue(result);
3049 return false;
3050 }
3051}
3052
John Kessenich433e9ff2017-01-26 20:31:11 -07003053// This path handles both if-then-else and ?:
3054// The if-then-else has a node type of void, while
3055// ?: has either a void or a non-void node type
3056//
3057// Leaving the result, when not void:
3058// GLSL only has r-values as the result of a :?, but
3059// if we have an l-value, that can be more efficient if it will
3060// become the base of a complex r-value expression, because the
3061// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003062bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3063{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003064 // see if OpSelect can handle it
3065 const auto isOpSelectable = [&]() {
3066 if (node->getBasicType() == glslang::EbtVoid)
3067 return false;
3068 // OpSelect can do all other types starting with SPV 1.4
3069 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3070 // pre-1.4, only scalars and vectors can be handled
3071 if ((!node->getType().isScalar() && !node->getType().isVector()))
3072 return false;
3073 }
3074 return true;
3075 };
3076
John Kessenich4bee5312018-02-20 21:29:05 -07003077 // See if it simple and safe, or required, to execute both sides.
3078 // Crucially, side effects must be either semantically required or avoided,
3079 // and there are performance trade-offs.
3080 // Return true if required or a good idea (and safe) to execute both sides,
3081 // false otherwise.
3082 const auto bothSidesPolicy = [&]() -> bool {
3083 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003084 if (node->getTrueBlock() == nullptr ||
3085 node->getFalseBlock() == nullptr)
3086 return false;
3087
John Kessenich4bee5312018-02-20 21:29:05 -07003088 // required? (unless we write additional code to look for side effects
3089 // and make performance trade-offs if none are present)
3090 if (!node->getShortCircuit())
3091 return true;
3092
3093 // if not required to execute both, decide based on performance/practicality...
3094
John Kessenich0c1e71a2019-01-10 18:23:06 +07003095 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003096 return false;
3097
John Kessenich433e9ff2017-01-26 20:31:11 -07003098 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3099 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3100
3101 // return true if a single operand to ? : is okay for OpSelect
3102 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003103 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003104 };
3105
3106 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3107 operandOkay(node->getFalseBlock()->getAsTyped());
3108 };
3109
John Kessenich4bee5312018-02-20 21:29:05 -07003110 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3111 // emit the condition before doing anything with selection
3112 node->getCondition()->traverse(this);
3113 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3114
3115 // Find a way of executing both sides and selecting the right result.
3116 const auto executeBothSides = [&]() -> void {
3117 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003118 node->getTrueBlock()->traverse(this);
3119 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3120 node->getFalseBlock()->traverse(this);
3121 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3122
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003123 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003124
John Kessenich4bee5312018-02-20 21:29:05 -07003125 // done if void
3126 if (node->getBasicType() == glslang::EbtVoid)
3127 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003128
John Kessenich4bee5312018-02-20 21:29:05 -07003129 // emit code to select between trueValue and falseValue
3130
3131 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003132 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003133 // Emit OpSelect for this selection.
3134
3135 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003136 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3137 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003138 condition = builder.smearScalar(spv::NoPrecision, condition,
3139 builder.makeVectorType(builder.makeBoolType(),
3140 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003141 }
John Kessenich4bee5312018-02-20 21:29:05 -07003142
3143 // OpSelect
3144 result = builder.createTriOp(spv::OpSelect,
3145 convertGlslangToSpvType(node->getType()), condition,
3146 trueValue, falseValue);
3147
3148 builder.clearAccessChain();
3149 builder.setAccessChainRValue(result);
3150 } else {
3151 // We need control flow to select the result.
3152 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3153 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3154
3155 // Selection control:
3156 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3157
3158 // make an "if" based on the value created by the condition
3159 spv::Builder::If ifBuilder(condition, control, builder);
3160
3161 // emit the "then" statement
3162 builder.createStore(trueValue, result);
3163 ifBuilder.makeBeginElse();
3164 // emit the "else" statement
3165 builder.createStore(falseValue, result);
3166
3167 // finish off the control flow
3168 ifBuilder.makeEndIf();
3169
3170 builder.clearAccessChain();
3171 builder.setAccessChainLValue(result);
3172 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003173 };
3174
John Kessenich4bee5312018-02-20 21:29:05 -07003175 // Execute the one side needed, as per the condition
3176 const auto executeOneSide = [&]() {
3177 // Always emit control flow.
3178 if (node->getBasicType() != glslang::EbtVoid)
3179 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003180
John Kessenich4bee5312018-02-20 21:29:05 -07003181 // Selection control:
3182 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3183
3184 // make an "if" based on the value created by the condition
3185 spv::Builder::If ifBuilder(condition, control, builder);
3186
3187 // emit the "then" statement
3188 if (node->getTrueBlock() != nullptr) {
3189 node->getTrueBlock()->traverse(this);
3190 if (result != spv::NoResult)
3191 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3192 }
3193
3194 if (node->getFalseBlock() != nullptr) {
3195 ifBuilder.makeBeginElse();
3196 // emit the "else" statement
3197 node->getFalseBlock()->traverse(this);
3198 if (result != spv::NoResult)
3199 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3200 }
3201
3202 // finish off the control flow
3203 ifBuilder.makeEndIf();
3204
3205 if (result != spv::NoResult) {
3206 builder.clearAccessChain();
3207 builder.setAccessChainLValue(result);
3208 }
3209 };
3210
3211 // Try for OpSelect (or a requirement to execute both sides)
3212 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003213 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3214 if (node->getType().getQualifier().isSpecConstant())
3215 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003216 executeBothSides();
3217 } else
3218 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003219
3220 return false;
3221}
3222
3223bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3224{
3225 // emit and get the condition before doing anything with switch
3226 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003227 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003228
Rex Xu57e65922017-07-04 23:23:40 +08003229 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003230 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003231
John Kessenich140f3df2015-06-26 16:58:36 -06003232 // browse the children to sort out code segments
3233 int defaultSegment = -1;
3234 std::vector<TIntermNode*> codeSegments;
3235 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3236 std::vector<int> caseValues;
3237 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3238 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3239 TIntermNode* child = *c;
3240 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003241 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003242 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003243 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003244 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3245 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003246 } else
3247 codeSegments.push_back(child);
3248 }
3249
qining25262b32016-05-06 17:25:16 -04003250 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003251 // statements between the last case and the end of the switch statement
3252 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3253 (int)codeSegments.size() == defaultSegment)
3254 codeSegments.push_back(nullptr);
3255
3256 // make the switch statement
3257 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003258 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3259 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003260
3261 // emit all the code in the segments
3262 breakForLoop.push(false);
3263 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3264 builder.nextSwitchSegment(segmentBlocks, s);
3265 if (codeSegments[s])
3266 codeSegments[s]->traverse(this);
3267 else
3268 builder.addSwitchBreak();
3269 }
3270 breakForLoop.pop();
3271
3272 builder.endSwitch(segmentBlocks);
3273
3274 return false;
3275}
3276
3277void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3278{
3279 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003280 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003281
3282 builder.clearAccessChain();
3283 builder.setAccessChainRValue(constant);
3284}
3285
3286bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3287{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003288 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003289 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003290
3291 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003292 std::vector<unsigned int> operands;
3293 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003294
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003295 // Spec requires back edges to target header blocks, and every header block
3296 // must dominate its merge block. Make a header block first to ensure these
3297 // conditions are met. By definition, it will contain OpLoopMerge, followed
3298 // by a block-ending branch. But we don't want to put any other body/test
3299 // instructions in it, since the body/test may have arbitrary instructions,
3300 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003301 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003302 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003303 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003304 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003305 spv::Block& test = builder.makeNewBlock();
3306 builder.createBranch(&test);
3307
3308 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003309 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003310 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003311 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3312
3313 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003314 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003315 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003316 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003317 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003318 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003319
3320 builder.setBuildPoint(&blocks.continue_target);
3321 if (node->getTerminal())
3322 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003323 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003324 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003325 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003326 builder.createBranch(&blocks.body);
3327
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003328 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003329 builder.setBuildPoint(&blocks.body);
3330 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003331 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003332 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003333 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003334
3335 builder.setBuildPoint(&blocks.continue_target);
3336 if (node->getTerminal())
3337 node->getTerminal()->traverse(this);
3338 if (node->getTest()) {
3339 node->getTest()->traverse(this);
3340 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003341 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003342 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003343 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003344 // TODO: unless there was a break/return/discard instruction
3345 // somewhere in the body, this is an infinite loop, so we should
3346 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003347 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003348 }
John Kessenich140f3df2015-06-26 16:58:36 -06003349 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003350 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003351 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003352 return false;
3353}
3354
3355bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3356{
3357 if (node->getExpression())
3358 node->getExpression()->traverse(this);
3359
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003360 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003361
John Kessenich140f3df2015-06-26 16:58:36 -06003362 switch (node->getFlowOp()) {
3363 case glslang::EOpKill:
3364 builder.makeDiscard();
3365 break;
3366 case glslang::EOpBreak:
3367 if (breakForLoop.top())
3368 builder.createLoopExit();
3369 else
3370 builder.addSwitchBreak();
3371 break;
3372 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003373 builder.createLoopContinue();
3374 break;
3375 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003376 if (node->getExpression()) {
3377 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3378 spv::Id returnId = accessChainLoad(glslangReturnType);
3379 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3380 builder.clearAccessChain();
3381 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3382 builder.setAccessChainLValue(copyId);
3383 multiTypeStore(glslangReturnType, returnId);
3384 returnId = builder.createLoad(copyId);
3385 }
3386 builder.makeReturn(false, returnId);
3387 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003388 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003389
3390 builder.clearAccessChain();
3391 break;
3392
John Kessenichb9197c82019-08-11 07:41:45 -06003393#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003394 case glslang::EOpDemote:
3395 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3396 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3397 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3398 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003399#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003400
John Kessenich140f3df2015-06-26 16:58:36 -06003401 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003402 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003403 break;
3404 }
3405
3406 return false;
3407}
3408
John Kessenich9c14f772019-06-17 08:38:35 -06003409spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003410{
qining25262b32016-05-06 17:25:16 -04003411 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003412 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003413 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003414 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003415 spv::Id result = createSpvConstant(*node);
3416 if (result != spv::NoResult)
3417 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003418 }
3419
3420 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003421 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003422 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3423 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003424
John Kessenichb9197c82019-08-11 07:41:45 -06003425 const bool contains16BitType = node->getType().contains16BitFloat() ||
3426 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003427 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003428 switch (storageClass) {
3429 case spv::StorageClassInput:
3430 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003431 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003432 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003433 break;
John Kessenich18310872018-05-14 22:08:53 -06003434 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003435 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003436 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3437 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003438 else
3439 builder.addCapability(spv::CapabilityStorageUniform16);
3440 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003441#ifndef GLSLANG_WEB
3442 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003443 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003444 builder.addCapability(spv::CapabilityStoragePushConstant16);
3445 break;
John Kessenich18310872018-05-14 22:08:53 -06003446 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003447 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003448 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003449 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3450 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003451#endif
John Kessenich18310872018-05-14 22:08:53 -06003452 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003453 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003454 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003455 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003456 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003457 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003458 }
3459 }
Rex Xuf89ad982017-04-07 23:22:33 +08003460
John Kessenichb9197c82019-08-11 07:41:45 -06003461 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003462 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003463 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003464 builder.addCapability(spv::CapabilityStoragePushConstant8);
3465 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003466 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003467 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003468 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003469 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003470 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003471 } else {
3472 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003473 }
3474 }
3475
John Kessenich140f3df2015-06-26 16:58:36 -06003476 const char* name = node->getName().c_str();
3477 if (glslang::IsAnonymous(name))
3478 name = "";
3479
3480 return builder.createVariable(storageClass, spvType, name);
3481}
3482
3483// Return type Id of the sampled type.
3484spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3485{
3486 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003487 case glslang::EbtInt: return builder.makeIntType(32);
3488 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003489 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003490#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003491 case glslang::EbtFloat16:
3492 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3493 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3494 return builder.makeFloatType(16);
3495#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003496 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003497 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003498 return builder.makeFloatType(32);
3499 }
3500}
3501
John Kessenich8c8505c2016-07-26 12:50:38 -06003502// If node is a swizzle operation, return the type that should be used if
3503// the swizzle base is first consumed by another operation, before the swizzle
3504// is applied.
3505spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3506{
John Kessenichecba76f2017-01-06 00:34:48 -07003507 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003508 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3509 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3510 else
3511 return spv::NoType;
3512}
3513
3514// When inverting a swizzle with a parent op, this function
3515// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003516spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3517 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003518{
3519 std::vector<unsigned> swizzle;
3520 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3521 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3522}
3523
John Kessenich8c8505c2016-07-26 12:50:38 -06003524// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3525void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3526{
3527 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3528 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3529 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3530}
3531
John Kessenich3ac051e2015-12-20 11:29:16 -07003532// Convert from a glslang type to an SPV type, by calling into a
3533// recursive version of this function. This establishes the inherited
3534// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003535spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003536{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003537 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003538}
3539
3540// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003541// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003542// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003543spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003544 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3545 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003546{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003547 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003548
3549 switch (type.getBasicType()) {
3550 case glslang::EbtVoid:
3551 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003552 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003553 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003554 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003555 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3556 // a 32-bit int where non-0 means true.
3557 if (explicitLayout != glslang::ElpNone)
3558 spvType = builder.makeUintType(32);
3559 else
3560 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003561 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003562 case glslang::EbtInt:
3563 spvType = builder.makeIntType(32);
3564 break;
3565 case glslang::EbtUint:
3566 spvType = builder.makeUintType(32);
3567 break;
3568 case glslang::EbtFloat:
3569 spvType = builder.makeFloatType(32);
3570 break;
3571#ifndef GLSLANG_WEB
3572 case glslang::EbtDouble:
3573 spvType = builder.makeFloatType(64);
3574 break;
3575 case glslang::EbtFloat16:
3576 spvType = builder.makeFloatType(16);
3577 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003578 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003579 spvType = builder.makeIntType(8);
3580 break;
3581 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003582 spvType = builder.makeUintType(8);
3583 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003584 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003585 spvType = builder.makeIntType(16);
3586 break;
3587 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003588 spvType = builder.makeUintType(16);
3589 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003590 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003591 spvType = builder.makeIntType(64);
3592 break;
3593 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003594 spvType = builder.makeUintType(64);
3595 break;
John Kessenich426394d2015-07-23 10:22:48 -06003596 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003597 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003598 spvType = builder.makeUintType(32);
3599 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003600 case glslang::EbtAccStruct:
3601 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003602 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003603 case glslang::EbtRayQuery:
3604 spvType = builder.makeRayQueryType();
3605 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003606 case glslang::EbtReference:
3607 {
3608 // Make the forward pointer, then recurse to convert the structure type, then
3609 // patch up the forward pointer with a real pointer type.
3610 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3611 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3612 forwardPointers[type.getReferentType()] = forwardId;
3613 }
3614 spvType = forwardPointers[type.getReferentType()];
3615 if (!forwardReferenceOnly) {
3616 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3617 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3618 forwardPointers[type.getReferentType()],
3619 referentType);
3620 }
3621 }
3622 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003623#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003624 case glslang::EbtSampler:
3625 {
3626 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003627 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003628 spvType = builder.makeSamplerType();
3629 } else {
3630 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003631 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3632 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3633 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3634 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003635 // already has both image and sampler, make the combined type
3636 spvType = builder.makeSampledImageType(spvType);
3637 }
John Kessenich55e7d112015-11-15 21:33:39 -07003638 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003639 }
John Kessenich140f3df2015-06-26 16:58:36 -06003640 break;
3641 case glslang::EbtStruct:
3642 case glslang::EbtBlock:
3643 {
3644 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003645 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003646
3647 // Try to share structs for different layouts, but not yet for other
3648 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003649 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003650 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003651 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003652 break;
3653
3654 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003655 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003656 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003657 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003658 }
3659 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003660 case glslang::EbtString:
3661 // no type used for OpString
3662 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003663 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003664 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003665 break;
3666 }
3667
3668 if (type.isMatrix())
3669 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3670 else {
3671 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3672 if (type.getVectorSize() > 1)
3673 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3674 }
3675
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003676 if (type.isCoopMat()) {
3677 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3678 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3679 if (type.getBasicType() == glslang::EbtFloat16)
3680 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003681 if (type.getBasicType() == glslang::EbtUint8 ||
3682 type.getBasicType() == glslang::EbtInt8) {
3683 builder.addCapability(spv::CapabilityInt8);
3684 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003685
3686 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3687 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3688 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3689
3690 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3691 }
3692
John Kessenich140f3df2015-06-26 16:58:36 -06003693 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003694 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3695
John Kessenichc9a80832015-09-12 12:17:44 -06003696 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003697 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003698 // We need to decorate array strides for types needing explicit layout, except blocks.
3699 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003700 // Use a dummy glslang type for querying internal strides of
3701 // arrays of arrays, but using just a one-dimensional array.
3702 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003703 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3704 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003705
3706 // Will compute the higher-order strides here, rather than making a whole
3707 // pile of types and doing repetitive recursion on their contents.
3708 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3709 }
John Kessenichf8842e52016-01-04 19:22:56 -07003710
3711 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003712 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003713 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003714 if (stride > 0)
3715 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003716 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003717 }
3718 } else {
3719 // single-dimensional array, and don't yet have stride
3720
John Kessenichf8842e52016-01-04 19:22:56 -07003721 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003722 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3723 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003724 }
John Kessenich31ed4832015-09-09 17:51:38 -06003725
John Kessenichead86222018-03-28 18:01:20 -06003726 // Do the outer dimension, which might not be known for a runtime-sized array.
3727 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3728 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003729 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003730 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003731#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003732 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003733 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003734 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3735 }
John Kessenichb9197c82019-08-11 07:41:45 -06003736#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003737 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003738 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003739 if (stride > 0)
3740 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003741 }
3742
3743 return spvType;
3744}
3745
John Kessenich0e737842017-03-24 18:38:16 -06003746// TODO: this functionality should exist at a higher level, in creating the AST
3747//
3748// Identify interface members that don't have their required extension turned on.
3749//
3750bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3751{
John Kessenicha28f7a72019-08-06 07:00:58 -06003752#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003753 auto& extensions = glslangIntermediate->getRequestedExtensions();
3754
Rex Xubcf291a2017-03-29 23:01:36 +08003755 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3756 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3757 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003758 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3759 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3760 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003761
3762 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3763 if (member.getFieldName() == "gl_ViewportMask" &&
3764 extensions.find("GL_NV_viewport_array2") == extensions.end())
3765 return true;
3766 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3767 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3768 return true;
3769 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3770 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3771 return true;
3772 }
3773#endif
John Kessenich0e737842017-03-24 18:38:16 -06003774
3775 return false;
3776};
3777
John Kessenich6090df02016-06-30 21:18:02 -06003778// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3779// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3780// Mutually recursive with convertGlslangToSpvType().
3781spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3782 const glslang::TTypeList* glslangMembers,
3783 glslang::TLayoutPacking explicitLayout,
3784 const glslang::TQualifier& qualifier)
3785{
3786 // Create a vector of struct types for SPIR-V to consume
3787 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003788 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3789 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003790 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003791 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3792 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3793 if (glslangMember.hiddenMember()) {
3794 ++memberDelta;
3795 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003796 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003797 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003798 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003799 if (filterMember(glslangMember)) {
3800 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003801 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003802 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003803 }
Roy05a5b532020-01-03 16:21:34 +08003804 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003805 }
John Kessenich6090df02016-06-30 21:18:02 -06003806 // modify just this child's view of the qualifier
3807 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3808 InheritQualifiers(memberQualifier, qualifier);
3809
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003810 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003811 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003812 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003813
3814 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003815 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3816 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003817
3818 // Make forward pointers for any pointer members, and create a list of members to
3819 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003820 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003821 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3822 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3823 }
3824 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003825 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3826 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003827 } else {
3828 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003829 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3830 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003831 }
John Kessenich6090df02016-06-30 21:18:02 -06003832 }
3833 }
3834
3835 // Make the SPIR-V type
3836 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003837 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003838 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3839
3840 // Decorate it
3841 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3842
John Kessenichd72f4882019-01-16 14:55:37 +07003843 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003844 auto it = deferredForwardPointers[i];
3845 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3846 }
3847
John Kessenich6090df02016-06-30 21:18:02 -06003848 return spvType;
3849}
3850
3851void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3852 const glslang::TTypeList* glslangMembers,
3853 glslang::TLayoutPacking explicitLayout,
3854 const glslang::TQualifier& qualifier,
3855 spv::Id spvType)
3856{
3857 // Name and decorate the non-hidden members
3858 int offset = -1;
3859 int locationOffset = 0; // for use within the members of this struct
3860 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3861 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3862 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003863 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003864 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003865 if (filterMember(glslangMember))
3866 continue;
3867 }
John Kessenich6090df02016-06-30 21:18:02 -06003868
3869 // modify just this child's view of the qualifier
3870 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3871 InheritQualifiers(memberQualifier, qualifier);
3872
3873 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003874 if (member < 0)
3875 continue;
3876
3877 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3878 builder.addMemberDecoration(spvType, member,
3879 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3880 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3881 // Add interpolation and auxiliary storage decorations only to
3882 // top-level members of Input and Output storage classes
3883 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3884 type.getQualifier().storage == glslang::EvqVaryingOut) {
3885 if (type.getBasicType() == glslang::EbtBlock ||
3886 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3887 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3888 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003889#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003890 addMeshNVDecoration(spvType, member, memberQualifier);
3891#endif
John Kessenich6090df02016-06-30 21:18:02 -06003892 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003893 }
3894 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003895
John Kessenichb9197c82019-08-11 07:41:45 -06003896#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003897 if (type.getBasicType() == glslang::EbtBlock &&
3898 qualifier.storage == glslang::EvqBuffer) {
3899 // Add memory decorations only to top-level members of shader storage block
3900 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003901 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003902 for (unsigned int i = 0; i < memory.size(); ++i)
3903 builder.addMemberDecoration(spvType, member, memory[i]);
3904 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003905
John Kessenichb9197c82019-08-11 07:41:45 -06003906#endif
John Kessenich6090df02016-06-30 21:18:02 -06003907
John Kessenich5d610ee2018-03-07 18:05:55 -07003908 // Location assignment was already completed correctly by the front end,
3909 // just track whether a member needs to be decorated.
3910 // Ignore member locations if the container is an array, as that's
3911 // ill-specified and decisions have been made to not allow this.
3912 if (! type.isArray() && memberQualifier.hasLocation())
3913 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003914
John Kessenich5d610ee2018-03-07 18:05:55 -07003915 if (qualifier.hasLocation()) // track for upcoming inheritance
3916 locationOffset += glslangIntermediate->computeTypeLocationSize(
3917 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003918
John Kessenich5d610ee2018-03-07 18:05:55 -07003919 // component, XFB, others
3920 if (glslangMember.getQualifier().hasComponent())
3921 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3922 glslangMember.getQualifier().layoutComponent);
3923 if (glslangMember.getQualifier().hasXfbOffset())
3924 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3925 glslangMember.getQualifier().layoutXfbOffset);
3926 else if (explicitLayout != glslang::ElpNone) {
3927 // figure out what to do with offset, which is accumulating
3928 int nextOffset;
3929 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3930 if (offset >= 0)
3931 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3932 offset = nextOffset;
3933 }
John Kessenich6090df02016-06-30 21:18:02 -06003934
John Kessenich5d610ee2018-03-07 18:05:55 -07003935 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3936 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3937 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003938
John Kessenich5d610ee2018-03-07 18:05:55 -07003939 // built-in variable decorations
3940 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3941 if (builtIn != spv::BuiltInMax)
3942 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003943
John Kessenichb9197c82019-08-11 07:41:45 -06003944#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003945 // nonuniform
3946 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3947
John Kessenichead86222018-03-28 18:01:20 -06003948 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3949 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3950 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3951 memberQualifier.semanticName);
3952 }
3953
John Kessenich5d610ee2018-03-07 18:05:55 -07003954 if (builtIn == spv::BuiltInLayer) {
3955 // SPV_NV_viewport_array2 extension
3956 if (glslangMember.getQualifier().layoutViewportRelative){
3957 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3958 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3959 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003960 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003961 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3962 builder.addMemberDecoration(spvType, member,
3963 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3964 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3965 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3966 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003967 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003968 }
3969 if (glslangMember.getQualifier().layoutPassthrough) {
3970 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3971 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3972 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3973 }
chaoc771d89f2017-01-13 01:10:53 -08003974#endif
John Kessenich6090df02016-06-30 21:18:02 -06003975 }
3976
3977 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003978 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3979 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003980}
3981
John Kessenich6c292d32016-02-15 20:58:50 -07003982// Turn the expression forming the array size into an id.
3983// This is not quite trivial, because of specialization constants.
3984// Sometimes, a raw constant is turned into an Id, and sometimes
3985// a specialization constant expression is.
3986spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3987{
3988 // First, see if this is sized with a node, meaning a specialization constant:
3989 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3990 if (specNode != nullptr) {
3991 builder.clearAccessChain();
3992 specNode->traverse(this);
3993 return accessChainLoad(specNode->getAsTyped()->getType());
3994 }
qining25262b32016-05-06 17:25:16 -04003995
John Kessenich6c292d32016-02-15 20:58:50 -07003996 // Otherwise, need a compile-time (front end) size, get it:
3997 int size = arraySizes.getDimSize(dim);
3998 assert(size > 0);
3999 return builder.makeUintConstant(size);
4000}
4001
John Kessenich103bef92016-02-08 21:38:15 -07004002// Wrap the builder's accessChainLoad to:
4003// - localize handling of RelaxedPrecision
4004// - use the SPIR-V inferred type instead of another conversion of the glslang type
4005// (avoids unnecessary work and possible type punning for structures)
4006// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004007spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4008{
John Kessenich103bef92016-02-08 21:38:15 -07004009 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004010
4011 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4012 coherentFlags |= TranslateCoherent(type);
4013
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004014 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004015 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004016
John Kessenich5611c6d2018-04-05 11:25:02 -06004017 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004018 TranslateNonUniformDecoration(type.getQualifier()),
4019 nominalTypeId,
4020 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4021 TranslateMemoryScope(coherentFlags),
4022 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004023
4024 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004025 if (type.getBasicType() == glslang::EbtBool) {
4026 if (builder.isScalarType(nominalTypeId)) {
4027 // Conversion for bool
4028 spv::Id boolType = builder.makeBoolType();
4029 if (nominalTypeId != boolType)
4030 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4031 } else if (builder.isVectorType(nominalTypeId)) {
4032 // Conversion for bvec
4033 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4034 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4035 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004036 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4037 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004038 }
4039 }
John Kessenich103bef92016-02-08 21:38:15 -07004040
4041 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004042}
4043
Rex Xu27253232016-02-23 17:51:09 +08004044// Wrap the builder's accessChainStore to:
4045// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004046//
4047// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004048void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4049{
4050 // Need to convert to abstract types when necessary
4051 if (type.getBasicType() == glslang::EbtBool) {
4052 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4053
4054 if (builder.isScalarType(nominalTypeId)) {
4055 // Conversion for bool
4056 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004057 if (nominalTypeId != boolType) {
4058 // keep these outside arguments, for determinant order-of-evaluation
4059 spv::Id one = builder.makeUintConstant(1);
4060 spv::Id zero = builder.makeUintConstant(0);
4061 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4062 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004063 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004064 } else if (builder.isVectorType(nominalTypeId)) {
4065 // Conversion for bvec
4066 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4067 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004068 if (nominalTypeId != bvecType) {
4069 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004070 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4071 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4072 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004073 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004074 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4075 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004076 }
4077 }
4078
Jeff Bolz36831c92018-09-05 10:11:41 -05004079 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4080 coherentFlags |= TranslateCoherent(type);
4081
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004082 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004083 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004084
Jeff Bolz36831c92018-09-05 10:11:41 -05004085 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004086 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4087 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004088 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004089}
4090
John Kessenich4bf71552016-09-02 11:20:21 -06004091// For storing when types match at the glslang level, but not might match at the
4092// SPIR-V level.
4093//
4094// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004095// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004096// as in a member-decorated way.
4097//
4098// NOTE: This function can handle any store request; if it's not special it
4099// simplifies to a simple OpStore.
4100//
4101// Implicitly uses the existing builder.accessChain as the storage target.
4102void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4103{
John Kessenichb3e24e42016-09-11 12:33:43 -06004104 // we only do the complex path here if it's an aggregate
4105 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004106 accessChainStore(type, rValue);
4107 return;
4108 }
4109
John Kessenichb3e24e42016-09-11 12:33:43 -06004110 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004111 spv::Id rType = builder.getTypeId(rValue);
4112 spv::Id lValue = builder.accessChainGetLValue();
4113 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4114 if (lType == rType) {
4115 accessChainStore(type, rValue);
4116 return;
4117 }
4118
John Kessenichb3e24e42016-09-11 12:33:43 -06004119 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004120 // where the two types were the same type in GLSL. This requires member
4121 // by member copy, recursively.
4122
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004123 // SPIR-V 1.4 added an instruction to do help do this.
4124 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4125 // However, bool in uniform space is changed to int, so
4126 // OpCopyLogical does not work for that.
4127 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4128 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4129 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4130 if (lBool == rBool) {
4131 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4132 accessChainStore(type, logicalCopy);
4133 return;
4134 }
4135 }
4136
John Kessenichb3e24e42016-09-11 12:33:43 -06004137 // If an array, copy element by element.
4138 if (type.isArray()) {
4139 glslang::TType glslangElementType(type, 0);
4140 spv::Id elementRType = builder.getContainedTypeId(rType);
4141 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4142 // get the source member
4143 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004144
John Kessenichb3e24e42016-09-11 12:33:43 -06004145 // set up the target storage
4146 builder.clearAccessChain();
4147 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004148 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4149 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004150
John Kessenichb3e24e42016-09-11 12:33:43 -06004151 // store the member
4152 multiTypeStore(glslangElementType, elementRValue);
4153 }
4154 } else {
4155 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004156
John Kessenichb3e24e42016-09-11 12:33:43 -06004157 // loop over structure members
4158 const glslang::TTypeList& members = *type.getStruct();
4159 for (int m = 0; m < (int)members.size(); ++m) {
4160 const glslang::TType& glslangMemberType = *members[m].type;
4161
4162 // get the source member
4163 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4164 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4165
4166 // set up the target storage
4167 builder.clearAccessChain();
4168 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004169 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4170 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004171
4172 // store the member
4173 multiTypeStore(glslangMemberType, memberRValue);
4174 }
John Kessenich4bf71552016-09-02 11:20:21 -06004175 }
4176}
4177
John Kessenichf85e8062015-12-19 13:57:10 -07004178// Decide whether or not this type should be
4179// decorated with offsets and strides, and if so
4180// whether std140 or std430 rules should be applied.
4181glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004182{
John Kessenichf85e8062015-12-19 13:57:10 -07004183 // has to be a block
4184 if (type.getBasicType() != glslang::EbtBlock)
4185 return glslang::ElpNone;
4186
Chao Chen3c366992018-09-19 11:41:59 -07004187 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004188 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004189 type.getQualifier().storage != glslang::EvqBuffer &&
4190 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004191 return glslang::ElpNone;
4192
4193 // return the layout to use
4194 switch (type.getQualifier().layoutPacking) {
4195 case glslang::ElpStd140:
4196 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004197 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004198 return type.getQualifier().layoutPacking;
4199 default:
4200 return glslang::ElpNone;
4201 }
John Kessenich31ed4832015-09-09 17:51:38 -06004202}
4203
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004204// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004205int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4206 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004207{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004208 int size;
John Kessenich49987892015-12-29 17:11:44 -07004209 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004210 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4211 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004212
4213 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004214}
4215
John Kessenich49987892015-12-29 17:11:44 -07004216// 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 -07004217// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004218int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4219 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004220{
John Kessenich49987892015-12-29 17:11:44 -07004221 glslang::TType elementType;
4222 elementType.shallowCopy(matrixType);
4223 elementType.clearArraySizes();
4224
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004225 int size;
John Kessenich49987892015-12-29 17:11:44 -07004226 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004227 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4228 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004229
4230 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004231}
4232
John Kessenich5e4b1242015-08-06 22:53:06 -06004233// Given a member type of a struct, realign the current offset for it, and compute
4234// the next (not yet aligned) offset for the next member, which will get aligned
4235// on the next call.
4236// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4237// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4238// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004239void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4240 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004241{
4242 // this will get a positive value when deemed necessary
4243 nextOffset = -1;
4244
John Kessenich5e4b1242015-08-06 22:53:06 -06004245 // override anything in currentOffset with user-set offset
4246 if (memberType.getQualifier().hasOffset())
4247 currentOffset = memberType.getQualifier().layoutOffset;
4248
4249 // It could be that current linker usage in glslang updated all the layoutOffset,
4250 // in which case the following code does not matter. But, that's not quite right
4251 // once cross-compilation unit GLSL validation is done, as the original user
4252 // settings are needed in layoutOffset, and then the following will come into play.
4253
John Kessenichf85e8062015-12-19 13:57:10 -07004254 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004255 if (! memberType.getQualifier().hasOffset())
4256 currentOffset = -1;
4257
4258 return;
4259 }
4260
John Kessenichf85e8062015-12-19 13:57:10 -07004261 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004262 if (currentOffset < 0)
4263 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004264
John Kessenich5e4b1242015-08-06 22:53:06 -06004265 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4266 // but possibly not yet correctly aligned.
4267
4268 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004269 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004270 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4271 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004272
4273 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004274 // TODO: make this consistent in early phases of code:
4275 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4276 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4277 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004278 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004279 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004280 int dummySize;
4281 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4282 if (componentAlignment <= 4)
4283 memberAlignment = componentAlignment;
4284 }
4285
4286 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004287 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004288
4289 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004290 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4291 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004292 glslang::RoundToPow2(currentOffset, 16);
4293
John Kessenich5e4b1242015-08-06 22:53:06 -06004294 nextOffset = currentOffset + memberSize;
4295}
4296
David Netoa901ffe2016-06-08 14:11:40 +01004297void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004298{
David Netoa901ffe2016-06-08 14:11:40 +01004299 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4300 switch (glslangBuiltIn)
4301 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004302 case glslang::EbvPointSize:
4303#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004304 case glslang::EbvClipDistance:
4305 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004306 case glslang::EbvViewportMaskNV:
4307 case glslang::EbvSecondaryPositionNV:
4308 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004309 case glslang::EbvPositionPerViewNV:
4310 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004311 case glslang::EbvTaskCountNV:
4312 case glslang::EbvPrimitiveCountNV:
4313 case glslang::EbvPrimitiveIndicesNV:
4314 case glslang::EbvClipDistancePerViewNV:
4315 case glslang::EbvCullDistancePerViewNV:
4316 case glslang::EbvLayerPerViewNV:
4317 case glslang::EbvMeshViewCountNV:
4318 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004319#endif
David Netoa901ffe2016-06-08 14:11:40 +01004320 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4321 // Alternately, we could just call this for any glslang built-in, since the
4322 // capability already guards against duplicates.
4323 TranslateBuiltInDecoration(glslangBuiltIn, false);
4324 break;
4325 default:
4326 // Capabilities were already generated when the struct was declared.
4327 break;
4328 }
John Kessenichebb50532016-05-16 19:22:05 -06004329}
4330
John Kessenich6fccb3c2016-09-19 16:01:41 -06004331bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004332{
John Kessenicheee9d532016-09-19 18:09:30 -06004333 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004334}
4335
John Kessenichd41993d2017-09-10 15:21:05 -06004336// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004337// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4338// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004339bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004340{
John Kessenich6a14f782017-12-04 02:48:10 -07004341 assert(qualifier == glslang::EvqIn ||
4342 qualifier == glslang::EvqOut ||
4343 qualifier == glslang::EvqInOut ||
4344 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004345 return qualifier != glslang::EvqConstReadOnly;
4346}
4347
4348// Is parameter pass-by-original?
4349bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4350 bool implicitThisParam)
4351{
4352 if (implicitThisParam) // implicit this
4353 return true;
4354 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004355 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004356 return paramType.containsOpaque() || // sampler, etc.
4357 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4358}
4359
John Kessenich140f3df2015-06-26 16:58:36 -06004360// Make all the functions, skeletally, without actually visiting their bodies.
4361void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4362{
John Kessenich8985fc92020-03-03 10:25:07 -07004363 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4364 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004365 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4366 if (paramPrecision != spv::NoPrecision)
4367 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004368 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004369 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004370 // Original and non-writable params pass the pointer directly and
4371 // use restrict/aliased, others are stored to a pointer in Function
4372 // memory and use RestrictPointer/AliasedPointer.
4373 if (originalParam(type.getQualifier().storage, type, false) ||
4374 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004375 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4376 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004377 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004378 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4379 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004380 }
4381 }
John Kessenichfad62972017-07-18 02:35:46 -06004382 };
4383
John Kessenich140f3df2015-06-26 16:58:36 -06004384 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4385 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004386 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004387 continue;
4388
4389 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004390 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004391 //
qining25262b32016-05-06 17:25:16 -04004392 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004393 // function. What it is an address of varies:
4394 //
John Kessenich4bf71552016-09-02 11:20:21 -06004395 // - "in" parameters not marked as "const" can be written to without modifying the calling
4396 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004397 //
4398 // - "const in" parameters can just be the r-value, as no writes need occur.
4399 //
John Kessenich4bf71552016-09-02 11:20:21 -06004400 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4401 // 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 -06004402
4403 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004404 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004405 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4406
John Kessenich155d3512019-08-08 23:29:20 -06004407#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004408 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4409 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004410#else
4411 bool implicitThis = false;
4412#endif
John Kessenich37789792017-03-21 23:56:40 -06004413
John Kessenichfad62972017-07-18 02:35:46 -06004414 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004415 for (int p = 0; p < (int)parameters.size(); ++p) {
4416 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4417 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004418 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004419 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004420 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004421 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4422 else
John Kessenich4bf71552016-09-02 11:20:21 -06004423 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004424 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004425 paramTypes.push_back(typeId);
4426 }
4427
4428 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004429 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4430 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004431 glslFunction->getName().c_str(), paramTypes,
4432 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004433 if (implicitThis)
4434 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004435
4436 // Track function to emit/call later
4437 functionMap[glslFunction->getName().c_str()] = function;
4438
4439 // Set the parameter id's
4440 for (int p = 0; p < (int)parameters.size(); ++p) {
4441 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4442 // give a name too
4443 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004444
4445 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004446 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004447 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004448 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004449 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004450 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004451 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004452 }
4453 }
4454}
4455
4456// Process all the initializers, while skipping the functions and link objects
4457void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4458{
4459 builder.setBuildPoint(shaderEntry->getLastBlock());
4460 for (int i = 0; i < (int)initializers.size(); ++i) {
4461 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004462 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4463 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004464
4465 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004466 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004467 initializer->traverse(this);
4468 }
4469 }
4470}
4471
4472// Process all the functions, while skipping initializers.
4473void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4474{
4475 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4476 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004477 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004478 node->traverse(this);
4479 }
4480}
4481
4482void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4483{
qining25262b32016-05-06 17:25:16 -04004484 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004485 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004486 currentFunction = functionMap[node->getName().c_str()];
4487 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004488 builder.setBuildPoint(functionBlock);
4489}
4490
John Kessenich8985fc92020-03-03 10:25:07 -07004491void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4492 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004493{
Rex Xufc618912015-09-09 16:42:49 +08004494 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004495
4496 glslang::TSampler sampler = {};
4497 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004498#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004499 bool f16ShadowCompare = false;
4500#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004501 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004502 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4503 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004504#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004505 f16ShadowCompare = sampler.shadow &&
4506 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004507#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004508 }
4509
John Kessenich140f3df2015-06-26 16:58:36 -06004510 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4511 builder.clearAccessChain();
4512 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004513
John Kessenicha28f7a72019-08-06 07:00:58 -06004514#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004515 // Special case l-value operands
4516 bool lvalue = false;
4517 switch (node.getOp()) {
4518 case glslang::EOpImageAtomicAdd:
4519 case glslang::EOpImageAtomicMin:
4520 case glslang::EOpImageAtomicMax:
4521 case glslang::EOpImageAtomicAnd:
4522 case glslang::EOpImageAtomicOr:
4523 case glslang::EOpImageAtomicXor:
4524 case glslang::EOpImageAtomicExchange:
4525 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004526 case glslang::EOpImageAtomicLoad:
4527 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004528 if (i == 0)
4529 lvalue = true;
4530 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004531 case glslang::EOpSparseImageLoad:
4532 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4533 lvalue = true;
4534 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004535 case glslang::EOpSparseTexture:
4536 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4537 lvalue = true;
4538 break;
4539 case glslang::EOpSparseTextureClamp:
4540 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4541 lvalue = true;
4542 break;
4543 case glslang::EOpSparseTextureLod:
4544 case glslang::EOpSparseTextureOffset:
4545 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4546 lvalue = true;
4547 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004548 case glslang::EOpSparseTextureFetch:
4549 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4550 lvalue = true;
4551 break;
4552 case glslang::EOpSparseTextureFetchOffset:
4553 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4554 lvalue = true;
4555 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004556 case glslang::EOpSparseTextureLodOffset:
4557 case glslang::EOpSparseTextureGrad:
4558 case glslang::EOpSparseTextureOffsetClamp:
4559 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4560 lvalue = true;
4561 break;
4562 case glslang::EOpSparseTextureGradOffset:
4563 case glslang::EOpSparseTextureGradClamp:
4564 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4565 lvalue = true;
4566 break;
4567 case glslang::EOpSparseTextureGradOffsetClamp:
4568 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4569 lvalue = true;
4570 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004571 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004572 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4573 lvalue = true;
4574 break;
4575 case glslang::EOpSparseTextureGatherOffset:
4576 case glslang::EOpSparseTextureGatherOffsets:
4577 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4578 lvalue = true;
4579 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004580 case glslang::EOpSparseTextureGatherLod:
4581 if (i == 3)
4582 lvalue = true;
4583 break;
4584 case glslang::EOpSparseTextureGatherLodOffset:
4585 case glslang::EOpSparseTextureGatherLodOffsets:
4586 if (i == 4)
4587 lvalue = true;
4588 break;
Rex Xu129799a2017-07-05 17:23:28 +08004589 case glslang::EOpSparseImageLoadLod:
4590 if (i == 3)
4591 lvalue = true;
4592 break;
Chao Chen3a137962018-09-19 11:41:27 -07004593 case glslang::EOpImageSampleFootprintNV:
4594 if (i == 4)
4595 lvalue = true;
4596 break;
4597 case glslang::EOpImageSampleFootprintClampNV:
4598 case glslang::EOpImageSampleFootprintLodNV:
4599 if (i == 5)
4600 lvalue = true;
4601 break;
4602 case glslang::EOpImageSampleFootprintGradNV:
4603 if (i == 6)
4604 lvalue = true;
4605 break;
4606 case glslang::EOpImageSampleFootprintGradClampNV:
4607 if (i == 7)
4608 lvalue = true;
4609 break;
Rex Xufc618912015-09-09 16:42:49 +08004610 default:
4611 break;
4612 }
4613
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004614 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004615 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004616 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4617 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4618 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004619#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004620 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004621 }
4622}
4623
John Kessenichfc51d282015-08-19 13:34:18 -06004624void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004625{
John Kessenichfc51d282015-08-19 13:34:18 -06004626 builder.clearAccessChain();
4627 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004628 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004629}
John Kessenich140f3df2015-06-26 16:58:36 -06004630
John Kessenichfc51d282015-08-19 13:34:18 -06004631spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4632{
John Kesseniche485c7a2017-05-31 18:50:53 -06004633 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004634 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004635
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004636 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004637
John Kessenichfc51d282015-08-19 13:34:18 -06004638 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004639
John Kessenichf43c7392019-03-31 10:51:57 -06004640 const glslang::TType &imageType = node->getAsAggregate()
4641 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4642 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004643 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004644#ifdef GLSLANG_WEB
4645 const bool f16ShadowCompare = false;
4646#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004647 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004648 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4649 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004650#endif
4651
John Kessenichf43c7392019-03-31 10:51:57 -06004652 const auto signExtensionMask = [&]() {
4653 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4654 if (sampler.type == glslang::EbtUint)
4655 return spv::ImageOperandsZeroExtendMask;
4656 else if (sampler.type == glslang::EbtInt)
4657 return spv::ImageOperandsSignExtendMask;
4658 }
4659 return spv::ImageOperandsMaskNone;
4660 };
4661
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004662 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4663
John Kessenichfc51d282015-08-19 13:34:18 -06004664 std::vector<spv::Id> arguments;
4665 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004666 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004667 else
4668 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004669 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004670
4671 spv::Builder::TextureParameters params = { };
4672 params.sampler = arguments[0];
4673
Rex Xu04db3f52015-09-16 11:44:02 +08004674 glslang::TCrackedTextureOp cracked;
4675 node->crackTexture(sampler, cracked);
4676
amhagan05506bb2017-06-13 16:53:02 -04004677 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004678
John Kessenichfc51d282015-08-19 13:34:18 -06004679 // Check for queries
4680 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004681 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4682 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004683 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004684
John Kessenichfc51d282015-08-19 13:34:18 -06004685 switch (node->getOp()) {
4686 case glslang::EOpImageQuerySize:
4687 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004688 if (arguments.size() > 1) {
4689 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004690 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004691 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004692 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004693#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004694 case glslang::EOpImageQuerySamples:
4695 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004696 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004697 case glslang::EOpTextureQueryLod:
4698 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004699 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004700 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004701 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004702 case glslang::EOpSparseTexelsResident:
4703 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004704#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004705 default:
4706 assert(0);
4707 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004708 }
John Kessenich140f3df2015-06-26 16:58:36 -06004709 }
4710
LoopDawg4425f242018-02-18 11:40:01 -07004711 int components = node->getType().getVectorSize();
4712
4713 if (node->getOp() == glslang::EOpTextureFetch) {
4714 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4715 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4716 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4717 // here around e.g. which ones return scalars or other types.
4718 components = 4;
4719 }
4720
4721 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4722
4723 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4724
Rex Xufc618912015-09-09 16:42:49 +08004725 // Check for image functions other than queries
4726 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004727 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004728 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004729 spv::IdImmediate image = { true, *(opIt++) };
4730 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004731
4732 // Handle subpass operations
4733 // TODO: GLSL should change to have the "MS" only on the type rather than the
4734 // built-in function.
4735 if (cracked.subpass) {
4736 // add on the (0,0) coordinate
4737 spv::Id zero = builder.makeIntConstant(0);
4738 std::vector<spv::Id> comps;
4739 comps.push_back(zero);
4740 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004741 spv::IdImmediate coord = { true,
4742 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4743 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004744 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4745 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004746 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004747 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4748 }
4749 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004750 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004751 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004752 spv::IdImmediate imageOperand = { true, *(opIt++) };
4753 operands.push_back(imageOperand);
4754 }
John Kessenich6c292d32016-02-15 20:58:50 -07004755 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004756 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4757 builder.setPrecision(result, precision);
4758 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004759 }
4760
John Kessenich149afc32018-08-14 13:31:43 -06004761 spv::IdImmediate coord = { true, *(opIt++) };
4762 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004763 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004764 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004765 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004766 mask = mask | spv::ImageOperandsSampleMask;
4767 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004768 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004769 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4770 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004771 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004772 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004773 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4774 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004775 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004776 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004777 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4778 operands.push_back(imageOperands);
4779 }
4780 if (mask & spv::ImageOperandsSampleMask) {
4781 spv::IdImmediate imageOperand = { true, *opIt++ };
4782 operands.push_back(imageOperand);
4783 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004784 if (mask & spv::ImageOperandsLodMask) {
4785 spv::IdImmediate imageOperand = { true, *opIt++ };
4786 operands.push_back(imageOperand);
4787 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004788 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004789 spv::IdImmediate imageOperand = { true,
4790 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004791 operands.push_back(imageOperand);
4792 }
4793
John Kessenich149afc32018-08-14 13:31:43 -06004794 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004795 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004796
John Kessenich149afc32018-08-14 13:31:43 -06004797 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004798 builder.setPrecision(result[0], precision);
4799
4800 // If needed, add a conversion constructor to the proper size.
4801 if (components != node->getType().getVectorSize())
4802 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4803
4804 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004805 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004806
Jeff Bolz36831c92018-09-05 10:11:41 -05004807 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004808 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004809 spv::IdImmediate texel = { true, *(opIt + 1) };
4810 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004811 } else {
4812 spv::IdImmediate texel = { true, *opIt };
4813 operands.push_back(texel);
4814 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004815
4816 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004817 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004818 mask = mask | spv::ImageOperandsSampleMask;
4819 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004820 if (cracked.lod) {
4821 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4822 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4823 mask = mask | spv::ImageOperandsLodMask;
4824 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004825 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4826 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004827 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004828 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004829 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4830 operands.push_back(imageOperands);
4831 }
4832 if (mask & spv::ImageOperandsSampleMask) {
4833 spv::IdImmediate imageOperand = { true, *opIt++ };
4834 operands.push_back(imageOperand);
4835 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004836 if (mask & spv::ImageOperandsLodMask) {
4837 spv::IdImmediate imageOperand = { true, *opIt++ };
4838 operands.push_back(imageOperand);
4839 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004840 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004841 spv::IdImmediate imageOperand = { true,
4842 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004843 operands.push_back(imageOperand);
4844 }
4845
John Kessenich56bab042015-09-16 10:54:31 -06004846 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004847 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004848 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004849 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004850 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4851 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004852 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004853 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004854 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4855
Jeff Bolz36831c92018-09-05 10:11:41 -05004856 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004857 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004858 mask = mask | spv::ImageOperandsSampleMask;
4859 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004860 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004861 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4862 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4863
Jeff Bolz36831c92018-09-05 10:11:41 -05004864 mask = mask | spv::ImageOperandsLodMask;
4865 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004866 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4867 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004868 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004869 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004870 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004871 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004872 }
4873 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004874 spv::IdImmediate imageOperand = { true, *opIt++ };
4875 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004876 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004877 if (mask & spv::ImageOperandsLodMask) {
4878 spv::IdImmediate imageOperand = { true, *opIt++ };
4879 operands.push_back(imageOperand);
4880 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004881 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004882 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4883 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004884 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004885 }
4886
4887 // Create the return type that was a special structure
4888 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004889 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004890 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4891 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4892
4893 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4894
4895 // Decode the return type
4896 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4897 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004898 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004899 // Process image atomic operations
4900
4901 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4902 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004903 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004904 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004905 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004906
Jeff Bolz36831c92018-09-05 10:11:41 -05004907 spv::Id resultTypeId;
4908 // imageAtomicStore has a void return type so base the pointer type on
4909 // the type of the value operand.
4910 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004911 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004912 } else {
4913 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4914 }
John Kessenich56bab042015-09-16 10:54:31 -06004915 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004916 if (imageType.getQualifier().nonUniform) {
4917 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4918 }
Rex Xufc618912015-09-09 16:42:49 +08004919
4920 std::vector<spv::Id> operands;
4921 operands.push_back(pointer);
4922 for (; opIt != arguments.end(); ++opIt)
4923 operands.push_back(*opIt);
4924
John Kessenich8985fc92020-03-03 10:25:07 -07004925 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4926 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004927 }
4928 }
4929
John Kessenicha28f7a72019-08-06 07:00:58 -06004930#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004931 // Check for fragment mask functions other than queries
4932 if (cracked.fragMask) {
4933 assert(sampler.ms);
4934
4935 auto opIt = arguments.begin();
4936 std::vector<spv::Id> operands;
4937
4938 // Extract the image if necessary
4939 if (builder.isSampledImage(params.sampler))
4940 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4941
4942 operands.push_back(params.sampler);
4943 ++opIt;
4944
4945 if (sampler.isSubpass()) {
4946 // add on the (0,0) coordinate
4947 spv::Id zero = builder.makeIntConstant(0);
4948 std::vector<spv::Id> comps;
4949 comps.push_back(zero);
4950 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07004951 operands.push_back(builder.makeCompositeConstant(
4952 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04004953 }
4954
4955 for (; opIt != arguments.end(); ++opIt)
4956 operands.push_back(*opIt);
4957
4958 spv::Op fragMaskOp = spv::OpNop;
4959 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4960 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4961 else if (node->getOp() == glslang::EOpFragmentFetch)
4962 fragMaskOp = spv::OpFragmentFetchAMD;
4963
4964 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4965 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4966 return builder.createOp(fragMaskOp, resultType(), operands);
4967 }
4968#endif
4969
Rex Xufc618912015-09-09 16:42:49 +08004970 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004971 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004972 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004973 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004974
John Kessenichfc51d282015-08-19 13:34:18 -06004975 // check for bias argument
4976 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004977 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004978 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004979 if (cracked.gather)
4980 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004981
4982 if (f16ShadowCompare)
4983 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004984 if (cracked.offset)
4985 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004986 else if (cracked.offsets)
4987 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004988 if (cracked.grad)
4989 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004990 if (cracked.lodClamp)
4991 ++nonBiasArgCount;
4992 if (sparse)
4993 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004994 if (imageFootprint)
4995 //Following three extra arguments
4996 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4997 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004998 if ((int)arguments.size() > nonBiasArgCount)
4999 bias = true;
5000 }
5001
John Kessenicha5c33d62016-06-02 23:45:21 -06005002 // See if the sampler param should really be just the SPV image part
5003 if (cracked.fetch) {
5004 // a fetch needs to have the image extracted first
5005 if (builder.isSampledImage(params.sampler))
5006 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5007 }
5008
John Kessenicha28f7a72019-08-06 07:00:58 -06005009#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005010 if (cracked.gather) {
5011 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5012 if (bias || cracked.lod ||
5013 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5014 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005015 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005016 }
5017 }
5018#endif
5019
John Kessenichfc51d282015-08-19 13:34:18 -06005020 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005021
John Kessenichfc51d282015-08-19 13:34:18 -06005022 params.coords = arguments[1];
5023 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005024 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005025
5026 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005027 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005028 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005029 ++extraArgs;
5030 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005031 params.Dref = arguments[2];
5032 ++extraArgs;
5033 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005034 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005035 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005036 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005037 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005038 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005039 dRefComp = builder.getNumComponents(params.coords) - 1;
5040 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005041 params.Dref = builder.createCompositeExtract(params.coords,
5042 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005043 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005044
5045 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005046 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005047 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005048 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005049 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5050 !(glslangIntermediate->getStage() == EShLangCompute &&
5051 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005052 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5053 noImplicitLod = true;
5054 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005055
5056 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005057 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005058 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005059 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005060 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005061
5062 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005063 if (cracked.grad) {
5064 params.gradX = arguments[2 + extraArgs];
5065 params.gradY = arguments[3 + extraArgs];
5066 extraArgs += 2;
5067 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005068
5069 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005070 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005071 params.offset = arguments[2 + extraArgs];
5072 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005073 } else if (cracked.offsets) {
5074 params.offsets = arguments[2 + extraArgs];
5075 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005076 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005077
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005078#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005079 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005080 if (cracked.lodClamp) {
5081 params.lodClamp = arguments[2 + extraArgs];
5082 ++extraArgs;
5083 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005084 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005085 if (sparse) {
5086 params.texelOut = arguments[2 + extraArgs];
5087 ++extraArgs;
5088 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005089 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005090 if (cracked.gather && ! sampler.shadow) {
5091 // default component is 0, if missing, otherwise an argument
5092 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005093 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005094 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005095 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005096 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005097 }
Chao Chen3a137962018-09-19 11:41:27 -07005098 spv::Id resultStruct = spv::NoResult;
5099 if (imageFootprint) {
5100 //Following three extra arguments
5101 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5102 params.granularity = arguments[2 + extraArgs];
5103 params.coarse = arguments[3 + extraArgs];
5104 resultStruct = arguments[4 + extraArgs];
5105 extraArgs += 3;
5106 }
5107#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005108 // bias
5109 if (bias) {
5110 params.bias = arguments[2 + extraArgs];
5111 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005112 }
John Kessenichfc51d282015-08-19 13:34:18 -06005113
John Kessenicha28f7a72019-08-06 07:00:58 -06005114#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005115 if (imageFootprint) {
5116 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5117 builder.addCapability(spv::CapabilityImageFootprintNV);
5118
5119
5120 //resultStructType(OpenGL type) contains 5 elements:
5121 //struct gl_TextureFootprint2DNV {
5122 // uvec2 anchor;
5123 // uvec2 offset;
5124 // uvec2 mask;
5125 // uint lod;
5126 // uint granularity;
5127 //};
5128 //or
5129 //struct gl_TextureFootprint3DNV {
5130 // uvec3 anchor;
5131 // uvec3 offset;
5132 // uvec2 mask;
5133 // uint lod;
5134 // uint granularity;
5135 //};
5136 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5137 assert(builder.isStructType(resultStructType));
5138
5139 //resType (SPIR-V type) contains 6 elements:
5140 //Member 0 must be a Boolean type scalar(LOD),
5141 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5142 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5143 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5144 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5145 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5146 std::vector<spv::Id> members;
5147 members.push_back(resultType());
5148 for (int i = 0; i < 5; i++) {
5149 members.push_back(builder.getContainedTypeId(resultStructType, i));
5150 }
5151 spv::Id resType = builder.makeStructType(members, "ResType");
5152
5153 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005154 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5155 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005156
5157 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5158 for (int i = 0; i < 5; i++) {
5159 builder.clearAccessChain();
5160 builder.setAccessChainLValue(resultStruct);
5161
5162 //Accessing to a struct we created, no coherent flag is set
5163 spv::Builder::AccessChain::CoherentFlags flags;
5164 flags.clear();
5165
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005166 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005167 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5168 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005169 }
5170 return builder.createCompositeExtract(res, resultType(), 0);
5171 }
5172#endif
5173
John Kessenich65336482016-06-16 14:06:26 -06005174 // projective component (might not to move)
5175 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5176 // are divided by the last component of P."
5177 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5178 // unused components will appear after all used components."
5179 if (cracked.proj) {
5180 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5181 int projTargetComp;
5182 switch (sampler.dim) {
5183 case glslang::Esd1D: projTargetComp = 1; break;
5184 case glslang::Esd2D: projTargetComp = 2; break;
5185 case glslang::EsdRect: projTargetComp = 2; break;
5186 default: projTargetComp = projSourceComp; break;
5187 }
5188 // copy the projective coordinate if we have to
5189 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005190 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005191 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005192 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005193 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005194 }
5195 }
5196
John Kessenichf8d1d742019-10-21 06:55:11 -06005197#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005198 // nonprivate
5199 if (imageType.getQualifier().nonprivate) {
5200 params.nonprivate = true;
5201 }
5202
5203 // volatile
5204 if (imageType.getQualifier().volatil) {
5205 params.volatil = true;
5206 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005207#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005208
St0fFa1184dd2018-04-09 21:08:14 +02005209 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005210 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5211 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005212 );
LoopDawg4425f242018-02-18 11:40:01 -07005213
5214 if (components != node->getType().getVectorSize())
5215 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5216
5217 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005218}
5219
5220spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5221{
5222 // Grab the function's pointer from the previously created function
5223 spv::Function* function = functionMap[node->getName().c_str()];
5224 if (! function)
5225 return 0;
5226
5227 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5228 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5229
5230 // See comments in makeFunctions() for details about the semantics for parameter passing.
5231 //
5232 // These imply we need a four step process:
5233 // 1. Evaluate the arguments
5234 // 2. Allocate and make copies of in, out, and inout arguments
5235 // 3. Make the call
5236 // 4. Copy back the results
5237
John Kessenichd3ed90b2018-05-04 11:43:03 -06005238 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005239 std::vector<spv::Builder::AccessChain> lValues;
5240 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005241 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005242 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005243 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005244 // build l-value
5245 builder.clearAccessChain();
5246 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005247 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005248 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005249 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005250 // save l-value
5251 lValues.push_back(builder.getAccessChain());
5252 } else {
5253 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005254 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005255 }
5256 }
5257
5258 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5259 // copy the original into that space.
5260 //
5261 // Also, build up the list of actual arguments to pass in for the call
5262 int lValueCount = 0;
5263 int rValueCount = 0;
5264 std::vector<spv::Id> spvArgs;
5265 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5266 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005267 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005268 builder.setAccessChain(lValues[lValueCount]);
5269 arg = builder.accessChainGetLValue();
5270 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005271 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005272 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005273 arg = builder.createVariable(spv::StorageClassFunction,
5274 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005275 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5276 // need to copy the input into output space
5277 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005278 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005279 builder.clearAccessChain();
5280 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005281 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005282 }
5283 ++lValueCount;
5284 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005285 // process r-value, which involves a copy for a type mismatch
5286 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5287 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5288 builder.clearAccessChain();
5289 builder.setAccessChainLValue(argCopy);
5290 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5291 arg = builder.createLoad(argCopy);
5292 } else
5293 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005294 ++rValueCount;
5295 }
5296 spvArgs.push_back(arg);
5297 }
5298
5299 // 3. Make the call.
5300 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005301 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005302
5303 // 4. Copy back out an "out" arguments.
5304 lValueCount = 0;
5305 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005306 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005307 ++lValueCount;
5308 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005309 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5310 spv::Id copy = builder.createLoad(spvArgs[a]);
5311 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005312 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005313 }
5314 ++lValueCount;
5315 }
5316 }
5317
5318 return result;
5319}
5320
5321// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005322spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005323 spv::Id typeId, spv::Id left, spv::Id right,
5324 glslang::TBasicType typeProxy, bool reduceComparison)
5325{
John Kessenich66011cb2018-03-06 16:12:04 -07005326 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5327 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005328 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005329
5330 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005331 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005332 bool comparison = false;
5333
5334 switch (op) {
5335 case glslang::EOpAdd:
5336 case glslang::EOpAddAssign:
5337 if (isFloat)
5338 binOp = spv::OpFAdd;
5339 else
5340 binOp = spv::OpIAdd;
5341 break;
5342 case glslang::EOpSub:
5343 case glslang::EOpSubAssign:
5344 if (isFloat)
5345 binOp = spv::OpFSub;
5346 else
5347 binOp = spv::OpISub;
5348 break;
5349 case glslang::EOpMul:
5350 case glslang::EOpMulAssign:
5351 if (isFloat)
5352 binOp = spv::OpFMul;
5353 else
5354 binOp = spv::OpIMul;
5355 break;
5356 case glslang::EOpVectorTimesScalar:
5357 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005358 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005359 if (builder.isVector(right))
5360 std::swap(left, right);
5361 assert(builder.isScalar(right));
5362 needMatchingVectors = false;
5363 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005364 } else if (isFloat)
5365 binOp = spv::OpFMul;
5366 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005367 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005368 break;
5369 case glslang::EOpVectorTimesMatrix:
5370 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005371 binOp = spv::OpVectorTimesMatrix;
5372 break;
5373 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005374 binOp = spv::OpMatrixTimesVector;
5375 break;
5376 case glslang::EOpMatrixTimesScalar:
5377 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005378 binOp = spv::OpMatrixTimesScalar;
5379 break;
5380 case glslang::EOpMatrixTimesMatrix:
5381 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005382 binOp = spv::OpMatrixTimesMatrix;
5383 break;
5384 case glslang::EOpOuterProduct:
5385 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005386 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005387 break;
5388
5389 case glslang::EOpDiv:
5390 case glslang::EOpDivAssign:
5391 if (isFloat)
5392 binOp = spv::OpFDiv;
5393 else if (isUnsigned)
5394 binOp = spv::OpUDiv;
5395 else
5396 binOp = spv::OpSDiv;
5397 break;
5398 case glslang::EOpMod:
5399 case glslang::EOpModAssign:
5400 if (isFloat)
5401 binOp = spv::OpFMod;
5402 else if (isUnsigned)
5403 binOp = spv::OpUMod;
5404 else
5405 binOp = spv::OpSMod;
5406 break;
5407 case glslang::EOpRightShift:
5408 case glslang::EOpRightShiftAssign:
5409 if (isUnsigned)
5410 binOp = spv::OpShiftRightLogical;
5411 else
5412 binOp = spv::OpShiftRightArithmetic;
5413 break;
5414 case glslang::EOpLeftShift:
5415 case glslang::EOpLeftShiftAssign:
5416 binOp = spv::OpShiftLeftLogical;
5417 break;
5418 case glslang::EOpAnd:
5419 case glslang::EOpAndAssign:
5420 binOp = spv::OpBitwiseAnd;
5421 break;
5422 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005423 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005424 binOp = spv::OpLogicalAnd;
5425 break;
5426 case glslang::EOpInclusiveOr:
5427 case glslang::EOpInclusiveOrAssign:
5428 binOp = spv::OpBitwiseOr;
5429 break;
5430 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005431 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005432 binOp = spv::OpLogicalOr;
5433 break;
5434 case glslang::EOpExclusiveOr:
5435 case glslang::EOpExclusiveOrAssign:
5436 binOp = spv::OpBitwiseXor;
5437 break;
5438 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005439 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005440 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005441 break;
5442
Ian Romanickb3bd4022019-01-21 08:57:25 -08005443 case glslang::EOpAbsDifference:
5444 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5445 break;
5446
5447 case glslang::EOpAddSaturate:
5448 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5449 break;
5450
5451 case glslang::EOpSubSaturate:
5452 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5453 break;
5454
5455 case glslang::EOpAverage:
5456 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5457 break;
5458
5459 case glslang::EOpAverageRounded:
5460 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5461 break;
5462
5463 case glslang::EOpMul32x16:
5464 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5465 break;
5466
John Kessenich140f3df2015-06-26 16:58:36 -06005467 case glslang::EOpLessThan:
5468 case glslang::EOpGreaterThan:
5469 case glslang::EOpLessThanEqual:
5470 case glslang::EOpGreaterThanEqual:
5471 case glslang::EOpEqual:
5472 case glslang::EOpNotEqual:
5473 case glslang::EOpVectorEqual:
5474 case glslang::EOpVectorNotEqual:
5475 comparison = true;
5476 break;
5477 default:
5478 break;
5479 }
5480
John Kessenich7c1aa102015-10-15 13:29:11 -06005481 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005482 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005483 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005484 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5485 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005486 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005487
5488 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005489 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005490 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005491
qining25262b32016-05-06 17:25:16 -04005492 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005493 decorations.addNoContraction(builder, result);
5494 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005495 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005496 }
5497
5498 if (! comparison)
5499 return 0;
5500
John Kessenich7c1aa102015-10-15 13:29:11 -06005501 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005502
John Kessenich4583b612016-08-07 19:14:22 -06005503 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005504 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5505 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005506 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005507 return result;
5508 }
John Kessenich140f3df2015-06-26 16:58:36 -06005509
5510 switch (op) {
5511 case glslang::EOpLessThan:
5512 if (isFloat)
5513 binOp = spv::OpFOrdLessThan;
5514 else if (isUnsigned)
5515 binOp = spv::OpULessThan;
5516 else
5517 binOp = spv::OpSLessThan;
5518 break;
5519 case glslang::EOpGreaterThan:
5520 if (isFloat)
5521 binOp = spv::OpFOrdGreaterThan;
5522 else if (isUnsigned)
5523 binOp = spv::OpUGreaterThan;
5524 else
5525 binOp = spv::OpSGreaterThan;
5526 break;
5527 case glslang::EOpLessThanEqual:
5528 if (isFloat)
5529 binOp = spv::OpFOrdLessThanEqual;
5530 else if (isUnsigned)
5531 binOp = spv::OpULessThanEqual;
5532 else
5533 binOp = spv::OpSLessThanEqual;
5534 break;
5535 case glslang::EOpGreaterThanEqual:
5536 if (isFloat)
5537 binOp = spv::OpFOrdGreaterThanEqual;
5538 else if (isUnsigned)
5539 binOp = spv::OpUGreaterThanEqual;
5540 else
5541 binOp = spv::OpSGreaterThanEqual;
5542 break;
5543 case glslang::EOpEqual:
5544 case glslang::EOpVectorEqual:
5545 if (isFloat)
5546 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005547 else if (isBool)
5548 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005549 else
5550 binOp = spv::OpIEqual;
5551 break;
5552 case glslang::EOpNotEqual:
5553 case glslang::EOpVectorNotEqual:
5554 if (isFloat)
5555 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005556 else if (isBool)
5557 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005558 else
5559 binOp = spv::OpINotEqual;
5560 break;
5561 default:
5562 break;
5563 }
5564
qining25262b32016-05-06 17:25:16 -04005565 if (binOp != spv::OpNop) {
5566 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005567 decorations.addNoContraction(builder, result);
5568 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005569 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005570 }
John Kessenich140f3df2015-06-26 16:58:36 -06005571
5572 return 0;
5573}
5574
John Kessenich04bb8a02015-12-12 12:28:14 -07005575//
5576// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5577// These can be any of:
5578//
5579// matrix * scalar
5580// scalar * matrix
5581// matrix * matrix linear algebraic
5582// matrix * vector
5583// vector * matrix
5584// matrix * matrix componentwise
5585// matrix op matrix op in {+, -, /}
5586// matrix op scalar op in {+, -, /}
5587// scalar op matrix op in {+, -, /}
5588//
John Kessenichead86222018-03-28 18:01:20 -06005589spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5590 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005591{
5592 bool firstClass = true;
5593
5594 // First, handle first-class matrix operations (* and matrix/scalar)
5595 switch (op) {
5596 case spv::OpFDiv:
5597 if (builder.isMatrix(left) && builder.isScalar(right)) {
5598 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005599 spv::Id resultType = builder.getTypeId(right);
5600 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005601 op = spv::OpMatrixTimesScalar;
5602 } else
5603 firstClass = false;
5604 break;
5605 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005606 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005607 std::swap(left, right);
5608 assert(builder.isScalar(right));
5609 break;
5610 case spv::OpVectorTimesMatrix:
5611 assert(builder.isVector(left));
5612 assert(builder.isMatrix(right));
5613 break;
5614 case spv::OpMatrixTimesVector:
5615 assert(builder.isMatrix(left));
5616 assert(builder.isVector(right));
5617 break;
5618 case spv::OpMatrixTimesMatrix:
5619 assert(builder.isMatrix(left));
5620 assert(builder.isMatrix(right));
5621 break;
5622 default:
5623 firstClass = false;
5624 break;
5625 }
5626
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005627 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5628 firstClass = true;
5629
qining25262b32016-05-06 17:25:16 -04005630 if (firstClass) {
5631 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005632 decorations.addNoContraction(builder, result);
5633 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005634 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005635 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005636
LoopDawg592860c2016-06-09 08:57:35 -06005637 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005638 // The result type of all of them is the same type as the (a) matrix operand.
5639 // The algorithm is to:
5640 // - break the matrix(es) into vectors
5641 // - smear any scalar to a vector
5642 // - do vector operations
5643 // - make a matrix out the vector results
5644 switch (op) {
5645 case spv::OpFAdd:
5646 case spv::OpFSub:
5647 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005648 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005649 case spv::OpFMul:
5650 {
5651 // one time set up...
5652 bool leftMat = builder.isMatrix(left);
5653 bool rightMat = builder.isMatrix(right);
5654 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5655 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5656 spv::Id scalarType = builder.getScalarTypeId(typeId);
5657 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5658 std::vector<spv::Id> results;
5659 spv::Id smearVec = spv::NoResult;
5660 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005661 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005662 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005663 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005664
5665 // do each vector op
5666 for (unsigned int c = 0; c < numCols; ++c) {
5667 std::vector<unsigned int> indexes;
5668 indexes.push_back(c);
5669 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5670 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005671 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005672 decorations.addNoContraction(builder, result);
5673 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005674 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005675 }
5676
5677 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005678 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005679 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005680 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005681 }
5682 default:
5683 assert(0);
5684 return spv::NoResult;
5685 }
5686}
5687
John Kessenichead86222018-03-28 18:01:20 -06005688spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005689 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005690{
5691 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005692 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005693 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005694 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5695 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005696
5697 switch (op) {
5698 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005699 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005700 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005701 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005702 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005703 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005704 unaryOp = spv::OpSNegate;
5705 break;
5706
5707 case glslang::EOpLogicalNot:
5708 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005709 unaryOp = spv::OpLogicalNot;
5710 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005711 case glslang::EOpBitwiseNot:
5712 unaryOp = spv::OpNot;
5713 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005714
John Kessenich140f3df2015-06-26 16:58:36 -06005715 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005716 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005717 break;
5718 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005719 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005720 break;
5721 case glslang::EOpTranspose:
5722 unaryOp = spv::OpTranspose;
5723 break;
5724
5725 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005726 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005727 break;
5728 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005729 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005730 break;
5731 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005732 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005733 break;
5734 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005735 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005736 break;
5737 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005738 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005739 break;
5740 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005741 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005742 break;
5743 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005744 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005745 break;
5746 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005747 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005748 break;
5749
5750 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005751 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005752 break;
5753 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005754 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005755 break;
5756 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005757 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005758 break;
5759 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005760 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005761 break;
5762 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005763 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005764 break;
5765 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005766 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005767 break;
5768
5769 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005770 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005771 break;
5772 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005773 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005774 break;
5775
5776 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005777 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005778 break;
5779 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005780 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005781 break;
5782 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005783 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005784 break;
5785 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005786 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005787 break;
5788 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005789 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005790 break;
5791 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005792 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005793 break;
5794
5795 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005796 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005797 break;
5798 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005799 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005800 break;
5801 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005802 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005803 break;
5804 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005805 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005806 break;
5807 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005808 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005809 break;
5810 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005811 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005812 break;
5813
5814 case glslang::EOpIsNan:
5815 unaryOp = spv::OpIsNan;
5816 break;
5817 case glslang::EOpIsInf:
5818 unaryOp = spv::OpIsInf;
5819 break;
LoopDawg592860c2016-06-09 08:57:35 -06005820 case glslang::EOpIsFinite:
5821 unaryOp = spv::OpIsFinite;
5822 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005823
Rex Xucbc426e2015-12-15 16:03:10 +08005824 case glslang::EOpFloatBitsToInt:
5825 case glslang::EOpFloatBitsToUint:
5826 case glslang::EOpIntBitsToFloat:
5827 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005828 case glslang::EOpDoubleBitsToInt64:
5829 case glslang::EOpDoubleBitsToUint64:
5830 case glslang::EOpInt64BitsToDouble:
5831 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005832 case glslang::EOpFloat16BitsToInt16:
5833 case glslang::EOpFloat16BitsToUint16:
5834 case glslang::EOpInt16BitsToFloat16:
5835 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005836 unaryOp = spv::OpBitcast;
5837 break;
5838
John Kessenich140f3df2015-06-26 16:58:36 -06005839 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005840 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005841 break;
5842 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005843 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005844 break;
5845 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005846 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005847 break;
5848 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005849 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005850 break;
5851 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005852 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005853 break;
5854 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005855 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005856 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005857#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005858 case glslang::EOpPackSnorm4x8:
5859 libCall = spv::GLSLstd450PackSnorm4x8;
5860 break;
5861 case glslang::EOpUnpackSnorm4x8:
5862 libCall = spv::GLSLstd450UnpackSnorm4x8;
5863 break;
5864 case glslang::EOpPackUnorm4x8:
5865 libCall = spv::GLSLstd450PackUnorm4x8;
5866 break;
5867 case glslang::EOpUnpackUnorm4x8:
5868 libCall = spv::GLSLstd450UnpackUnorm4x8;
5869 break;
5870 case glslang::EOpPackDouble2x32:
5871 libCall = spv::GLSLstd450PackDouble2x32;
5872 break;
5873 case glslang::EOpUnpackDouble2x32:
5874 libCall = spv::GLSLstd450UnpackDouble2x32;
5875 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005876#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005877
Rex Xu8ff43de2016-04-22 16:51:45 +08005878 case glslang::EOpPackInt2x32:
5879 case glslang::EOpUnpackInt2x32:
5880 case glslang::EOpPackUint2x32:
5881 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005882 case glslang::EOpPack16:
5883 case glslang::EOpPack32:
5884 case glslang::EOpPack64:
5885 case glslang::EOpUnpack32:
5886 case glslang::EOpUnpack16:
5887 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005888 case glslang::EOpPackInt2x16:
5889 case glslang::EOpUnpackInt2x16:
5890 case glslang::EOpPackUint2x16:
5891 case glslang::EOpUnpackUint2x16:
5892 case glslang::EOpPackInt4x16:
5893 case glslang::EOpUnpackInt4x16:
5894 case glslang::EOpPackUint4x16:
5895 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005896 case glslang::EOpPackFloat2x16:
5897 case glslang::EOpUnpackFloat2x16:
5898 unaryOp = spv::OpBitcast;
5899 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005900
John Kessenich140f3df2015-06-26 16:58:36 -06005901 case glslang::EOpDPdx:
5902 unaryOp = spv::OpDPdx;
5903 break;
5904 case glslang::EOpDPdy:
5905 unaryOp = spv::OpDPdy;
5906 break;
5907 case glslang::EOpFwidth:
5908 unaryOp = spv::OpFwidth;
5909 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005910
John Kessenich140f3df2015-06-26 16:58:36 -06005911 case glslang::EOpAny:
5912 unaryOp = spv::OpAny;
5913 break;
5914 case glslang::EOpAll:
5915 unaryOp = spv::OpAll;
5916 break;
5917
5918 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005919 if (isFloat)
5920 libCall = spv::GLSLstd450FAbs;
5921 else
5922 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005923 break;
5924 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005925 if (isFloat)
5926 libCall = spv::GLSLstd450FSign;
5927 else
5928 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005929 break;
5930
John Kessenicha28f7a72019-08-06 07:00:58 -06005931#ifndef GLSLANG_WEB
5932 case glslang::EOpDPdxFine:
5933 unaryOp = spv::OpDPdxFine;
5934 break;
5935 case glslang::EOpDPdyFine:
5936 unaryOp = spv::OpDPdyFine;
5937 break;
5938 case glslang::EOpFwidthFine:
5939 unaryOp = spv::OpFwidthFine;
5940 break;
5941 case glslang::EOpDPdxCoarse:
5942 unaryOp = spv::OpDPdxCoarse;
5943 break;
5944 case glslang::EOpDPdyCoarse:
5945 unaryOp = spv::OpDPdyCoarse;
5946 break;
5947 case glslang::EOpFwidthCoarse:
5948 unaryOp = spv::OpFwidthCoarse;
5949 break;
5950 case glslang::EOpInterpolateAtCentroid:
5951 if (typeProxy == glslang::EbtFloat16)
5952 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5953 libCall = spv::GLSLstd450InterpolateAtCentroid;
5954 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005955 case glslang::EOpAtomicCounterIncrement:
5956 case glslang::EOpAtomicCounterDecrement:
5957 case glslang::EOpAtomicCounter:
5958 {
5959 // Handle all of the atomics in one place, in createAtomicOperation()
5960 std::vector<spv::Id> operands;
5961 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005962 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005963 }
5964
John Kessenichfc51d282015-08-19 13:34:18 -06005965 case glslang::EOpBitFieldReverse:
5966 unaryOp = spv::OpBitReverse;
5967 break;
5968 case glslang::EOpBitCount:
5969 unaryOp = spv::OpBitCount;
5970 break;
5971 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005972 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005973 break;
5974 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005975 if (isUnsigned)
5976 libCall = spv::GLSLstd450FindUMsb;
5977 else
5978 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005979 break;
5980
Ian Romanickb3bd4022019-01-21 08:57:25 -08005981 case glslang::EOpCountLeadingZeros:
5982 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5983 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5984 unaryOp = spv::OpUCountLeadingZerosINTEL;
5985 break;
5986
5987 case glslang::EOpCountTrailingZeros:
5988 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5989 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5990 unaryOp = spv::OpUCountTrailingZerosINTEL;
5991 break;
5992
Rex Xu574ab042016-04-14 16:53:07 +08005993 case glslang::EOpBallot:
5994 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005995 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005996 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005997 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005998 case glslang::EOpMinInvocations:
5999 case glslang::EOpMaxInvocations:
6000 case glslang::EOpAddInvocations:
6001 case glslang::EOpMinInvocationsNonUniform:
6002 case glslang::EOpMaxInvocationsNonUniform:
6003 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006004 case glslang::EOpMinInvocationsInclusiveScan:
6005 case glslang::EOpMaxInvocationsInclusiveScan:
6006 case glslang::EOpAddInvocationsInclusiveScan:
6007 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6008 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6009 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6010 case glslang::EOpMinInvocationsExclusiveScan:
6011 case glslang::EOpMaxInvocationsExclusiveScan:
6012 case glslang::EOpAddInvocationsExclusiveScan:
6013 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6014 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6015 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006016 {
6017 std::vector<spv::Id> operands;
6018 operands.push_back(operand);
6019 return createInvocationsOperation(op, typeId, operands, typeProxy);
6020 }
John Kessenich66011cb2018-03-06 16:12:04 -07006021 case glslang::EOpSubgroupAll:
6022 case glslang::EOpSubgroupAny:
6023 case glslang::EOpSubgroupAllEqual:
6024 case glslang::EOpSubgroupBroadcastFirst:
6025 case glslang::EOpSubgroupBallot:
6026 case glslang::EOpSubgroupInverseBallot:
6027 case glslang::EOpSubgroupBallotBitCount:
6028 case glslang::EOpSubgroupBallotInclusiveBitCount:
6029 case glslang::EOpSubgroupBallotExclusiveBitCount:
6030 case glslang::EOpSubgroupBallotFindLSB:
6031 case glslang::EOpSubgroupBallotFindMSB:
6032 case glslang::EOpSubgroupAdd:
6033 case glslang::EOpSubgroupMul:
6034 case glslang::EOpSubgroupMin:
6035 case glslang::EOpSubgroupMax:
6036 case glslang::EOpSubgroupAnd:
6037 case glslang::EOpSubgroupOr:
6038 case glslang::EOpSubgroupXor:
6039 case glslang::EOpSubgroupInclusiveAdd:
6040 case glslang::EOpSubgroupInclusiveMul:
6041 case glslang::EOpSubgroupInclusiveMin:
6042 case glslang::EOpSubgroupInclusiveMax:
6043 case glslang::EOpSubgroupInclusiveAnd:
6044 case glslang::EOpSubgroupInclusiveOr:
6045 case glslang::EOpSubgroupInclusiveXor:
6046 case glslang::EOpSubgroupExclusiveAdd:
6047 case glslang::EOpSubgroupExclusiveMul:
6048 case glslang::EOpSubgroupExclusiveMin:
6049 case glslang::EOpSubgroupExclusiveMax:
6050 case glslang::EOpSubgroupExclusiveAnd:
6051 case glslang::EOpSubgroupExclusiveOr:
6052 case glslang::EOpSubgroupExclusiveXor:
6053 case glslang::EOpSubgroupQuadSwapHorizontal:
6054 case glslang::EOpSubgroupQuadSwapVertical:
6055 case glslang::EOpSubgroupQuadSwapDiagonal: {
6056 std::vector<spv::Id> operands;
6057 operands.push_back(operand);
6058 return createSubgroupOperation(op, typeId, operands, typeProxy);
6059 }
Rex Xu9d93a232016-05-05 12:30:44 +08006060 case glslang::EOpMbcnt:
6061 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6062 libCall = spv::MbcntAMD;
6063 break;
6064
6065 case glslang::EOpCubeFaceIndex:
6066 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6067 libCall = spv::CubeFaceIndexAMD;
6068 break;
6069
6070 case glslang::EOpCubeFaceCoord:
6071 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6072 libCall = spv::CubeFaceCoordAMD;
6073 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006074 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006075 unaryOp = spv::OpGroupNonUniformPartitionNV;
6076 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006077 case glslang::EOpConstructReference:
6078 unaryOp = spv::OpBitcast;
6079 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006080#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006081
6082 case glslang::EOpCopyObject:
6083 unaryOp = spv::OpCopyObject;
6084 break;
6085
John Kessenich140f3df2015-06-26 16:58:36 -06006086 default:
6087 return 0;
6088 }
6089
6090 spv::Id id;
6091 if (libCall >= 0) {
6092 std::vector<spv::Id> args;
6093 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006094 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006095 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006096 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006097 }
John Kessenich140f3df2015-06-26 16:58:36 -06006098
John Kessenichb9197c82019-08-11 07:41:45 -06006099 decorations.addNoContraction(builder, id);
6100 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006101 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006102}
6103
John Kessenich7a53f762016-01-20 11:19:27 -07006104// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006105spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6106 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006107{
6108 // Handle unary operations vector by vector.
6109 // The result type is the same type as the original type.
6110 // The algorithm is to:
6111 // - break the matrix into vectors
6112 // - apply the operation to each vector
6113 // - make a matrix out the vector results
6114
6115 // get the types sorted out
6116 int numCols = builder.getNumColumns(operand);
6117 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006118 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6119 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006120 std::vector<spv::Id> results;
6121
6122 // do each vector op
6123 for (int c = 0; c < numCols; ++c) {
6124 std::vector<unsigned int> indexes;
6125 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006126 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6127 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006128 decorations.addNoContraction(builder, destVec);
6129 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006130 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006131 }
6132
6133 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006134 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006135 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006136 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006137}
6138
John Kessenichad7645f2018-06-04 19:11:25 -06006139// For converting integers where both the bitwidth and the signedness could
6140// change, but only do the width change here. The caller is still responsible
6141// for the signedness conversion.
6142spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006143{
John Kessenichad7645f2018-06-04 19:11:25 -06006144 // Get the result type width, based on the type to convert to.
6145 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006146 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006147 case glslang::EOpConvInt16ToUint8:
6148 case glslang::EOpConvIntToUint8:
6149 case glslang::EOpConvInt64ToUint8:
6150 case glslang::EOpConvUint16ToInt8:
6151 case glslang::EOpConvUintToInt8:
6152 case glslang::EOpConvUint64ToInt8:
6153 width = 8;
6154 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006155 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006156 case glslang::EOpConvIntToUint16:
6157 case glslang::EOpConvInt64ToUint16:
6158 case glslang::EOpConvUint8ToInt16:
6159 case glslang::EOpConvUintToInt16:
6160 case glslang::EOpConvUint64ToInt16:
6161 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006162 break;
6163 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006164 case glslang::EOpConvInt16ToUint:
6165 case glslang::EOpConvInt64ToUint:
6166 case glslang::EOpConvUint8ToInt:
6167 case glslang::EOpConvUint16ToInt:
6168 case glslang::EOpConvUint64ToInt:
6169 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006170 break;
6171 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006172 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006173 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006174 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006175 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006176 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006177 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006178 break;
6179
6180 default:
6181 assert(false && "Default missing");
6182 break;
6183 }
6184
John Kessenichad7645f2018-06-04 19:11:25 -06006185 // Get the conversion operation and result type,
6186 // based on the target width, but the source type.
6187 spv::Id type = spv::NoType;
6188 spv::Op convOp = spv::OpNop;
6189 switch(op) {
6190 case glslang::EOpConvInt8ToUint16:
6191 case glslang::EOpConvInt8ToUint:
6192 case glslang::EOpConvInt8ToUint64:
6193 case glslang::EOpConvInt16ToUint8:
6194 case glslang::EOpConvInt16ToUint:
6195 case glslang::EOpConvInt16ToUint64:
6196 case glslang::EOpConvIntToUint8:
6197 case glslang::EOpConvIntToUint16:
6198 case glslang::EOpConvIntToUint64:
6199 case glslang::EOpConvInt64ToUint8:
6200 case glslang::EOpConvInt64ToUint16:
6201 case glslang::EOpConvInt64ToUint:
6202 convOp = spv::OpSConvert;
6203 type = builder.makeIntType(width);
6204 break;
6205 default:
6206 convOp = spv::OpUConvert;
6207 type = builder.makeUintType(width);
6208 break;
6209 }
6210
John Kessenich66011cb2018-03-06 16:12:04 -07006211 if (vectorSize > 0)
6212 type = builder.makeVectorType(type, vectorSize);
6213
John Kessenichad7645f2018-06-04 19:11:25 -06006214 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006215}
6216
John Kessenichead86222018-03-28 18:01:20 -06006217spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6218 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006219{
6220 spv::Op convOp = spv::OpNop;
6221 spv::Id zero = 0;
6222 spv::Id one = 0;
6223
6224 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6225
6226 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006227 case glslang::EOpConvIntToBool:
6228 case glslang::EOpConvUintToBool:
6229 zero = builder.makeUintConstant(0);
6230 zero = makeSmearedConstant(zero, vectorSize);
6231 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006232 case glslang::EOpConvFloatToBool:
6233 zero = builder.makeFloatConstant(0.0F);
6234 zero = makeSmearedConstant(zero, vectorSize);
6235 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006236 case glslang::EOpConvBoolToFloat:
6237 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006238 zero = builder.makeFloatConstant(0.0F);
6239 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006240 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006241
John Kessenich140f3df2015-06-26 16:58:36 -06006242 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006243 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006244#ifndef GLSLANG_WEB
6245 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006246 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006247 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006248 } else
6249#endif
6250 {
6251 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006252 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006253 }
Rex Xucabbb782017-03-24 13:41:14 +08006254
John Kessenich140f3df2015-06-26 16:58:36 -06006255 convOp = spv::OpSelect;
6256 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006257
John Kessenich140f3df2015-06-26 16:58:36 -06006258 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006259 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006260#ifndef GLSLANG_WEB
6261 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006262 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006263 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006264 } else
6265#endif
6266 {
6267 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006268 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006269 }
Rex Xucabbb782017-03-24 13:41:14 +08006270
John Kessenich140f3df2015-06-26 16:58:36 -06006271 convOp = spv::OpSelect;
6272 break;
6273
John Kessenich66011cb2018-03-06 16:12:04 -07006274 case glslang::EOpConvInt8ToFloat16:
6275 case glslang::EOpConvInt8ToFloat:
6276 case glslang::EOpConvInt8ToDouble:
6277 case glslang::EOpConvInt16ToFloat16:
6278 case glslang::EOpConvInt16ToFloat:
6279 case glslang::EOpConvInt16ToDouble:
6280 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006281 case glslang::EOpConvIntToFloat:
6282 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006283 case glslang::EOpConvInt64ToFloat:
6284 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006285 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006286 convOp = spv::OpConvertSToF;
6287 break;
6288
John Kessenich66011cb2018-03-06 16:12:04 -07006289 case glslang::EOpConvUint8ToFloat16:
6290 case glslang::EOpConvUint8ToFloat:
6291 case glslang::EOpConvUint8ToDouble:
6292 case glslang::EOpConvUint16ToFloat16:
6293 case glslang::EOpConvUint16ToFloat:
6294 case glslang::EOpConvUint16ToDouble:
6295 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006296 case glslang::EOpConvUintToFloat:
6297 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006298 case glslang::EOpConvUint64ToFloat:
6299 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006300 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006301 convOp = spv::OpConvertUToF;
6302 break;
6303
John Kessenich66011cb2018-03-06 16:12:04 -07006304 case glslang::EOpConvFloat16ToInt8:
6305 case glslang::EOpConvFloatToInt8:
6306 case glslang::EOpConvDoubleToInt8:
6307 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006308 case glslang::EOpConvFloatToInt16:
6309 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006310 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006311 case glslang::EOpConvFloatToInt:
6312 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006313 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006314 case glslang::EOpConvFloatToInt64:
6315 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006316 convOp = spv::OpConvertFToS;
6317 break;
6318
John Kessenich66011cb2018-03-06 16:12:04 -07006319 case glslang::EOpConvUint8ToInt8:
6320 case glslang::EOpConvInt8ToUint8:
6321 case glslang::EOpConvUint16ToInt16:
6322 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006323 case glslang::EOpConvUintToInt:
6324 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006325 case glslang::EOpConvUint64ToInt64:
6326 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006327 if (builder.isInSpecConstCodeGenMode()) {
6328 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006329#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006330 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6331 zero = builder.makeUint8Constant(0);
6332 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006333 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006334 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6335 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006336 } else
6337#endif
6338 {
Rex Xucabbb782017-03-24 13:41:14 +08006339 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006340 }
qining189b2032016-04-12 23:16:20 -04006341 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006342 // Use OpIAdd, instead of OpBitcast to do the conversion when
6343 // generating for OpSpecConstantOp instruction.
6344 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6345 }
6346 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006347 convOp = spv::OpBitcast;
6348 break;
6349
John Kessenich66011cb2018-03-06 16:12:04 -07006350 case glslang::EOpConvFloat16ToUint8:
6351 case glslang::EOpConvFloatToUint8:
6352 case glslang::EOpConvDoubleToUint8:
6353 case glslang::EOpConvFloat16ToUint16:
6354 case glslang::EOpConvFloatToUint16:
6355 case glslang::EOpConvDoubleToUint16:
6356 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006357 case glslang::EOpConvFloatToUint:
6358 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006359 case glslang::EOpConvFloatToUint64:
6360 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006361 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006362 convOp = spv::OpConvertFToU;
6363 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006364
John Kessenich39697cd2019-08-08 10:35:51 -06006365#ifndef GLSLANG_WEB
6366 case glslang::EOpConvInt8ToBool:
6367 case glslang::EOpConvUint8ToBool:
6368 zero = builder.makeUint8Constant(0);
6369 zero = makeSmearedConstant(zero, vectorSize);
6370 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6371 case glslang::EOpConvInt16ToBool:
6372 case glslang::EOpConvUint16ToBool:
6373 zero = builder.makeUint16Constant(0);
6374 zero = makeSmearedConstant(zero, vectorSize);
6375 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6376 case glslang::EOpConvInt64ToBool:
6377 case glslang::EOpConvUint64ToBool:
6378 zero = builder.makeUint64Constant(0);
6379 zero = makeSmearedConstant(zero, vectorSize);
6380 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6381 case glslang::EOpConvDoubleToBool:
6382 zero = builder.makeDoubleConstant(0.0);
6383 zero = makeSmearedConstant(zero, vectorSize);
6384 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6385 case glslang::EOpConvFloat16ToBool:
6386 zero = builder.makeFloat16Constant(0.0F);
6387 zero = makeSmearedConstant(zero, vectorSize);
6388 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6389 case glslang::EOpConvBoolToDouble:
6390 convOp = spv::OpSelect;
6391 zero = builder.makeDoubleConstant(0.0);
6392 one = builder.makeDoubleConstant(1.0);
6393 break;
6394 case glslang::EOpConvBoolToFloat16:
6395 convOp = spv::OpSelect;
6396 zero = builder.makeFloat16Constant(0.0F);
6397 one = builder.makeFloat16Constant(1.0F);
6398 break;
6399 case glslang::EOpConvBoolToInt8:
6400 zero = builder.makeInt8Constant(0);
6401 one = builder.makeInt8Constant(1);
6402 convOp = spv::OpSelect;
6403 break;
6404 case glslang::EOpConvBoolToUint8:
6405 zero = builder.makeUint8Constant(0);
6406 one = builder.makeUint8Constant(1);
6407 convOp = spv::OpSelect;
6408 break;
6409 case glslang::EOpConvBoolToInt16:
6410 zero = builder.makeInt16Constant(0);
6411 one = builder.makeInt16Constant(1);
6412 convOp = spv::OpSelect;
6413 break;
6414 case glslang::EOpConvBoolToUint16:
6415 zero = builder.makeUint16Constant(0);
6416 one = builder.makeUint16Constant(1);
6417 convOp = spv::OpSelect;
6418 break;
6419 case glslang::EOpConvDoubleToFloat:
6420 case glslang::EOpConvFloatToDouble:
6421 case glslang::EOpConvDoubleToFloat16:
6422 case glslang::EOpConvFloat16ToDouble:
6423 case glslang::EOpConvFloatToFloat16:
6424 case glslang::EOpConvFloat16ToFloat:
6425 convOp = spv::OpFConvert;
6426 if (builder.isMatrixType(destType))
6427 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6428 break;
6429
John Kessenich66011cb2018-03-06 16:12:04 -07006430 case glslang::EOpConvInt8ToInt16:
6431 case glslang::EOpConvInt8ToInt:
6432 case glslang::EOpConvInt8ToInt64:
6433 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006434 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006435 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006436 case glslang::EOpConvIntToInt8:
6437 case glslang::EOpConvIntToInt16:
6438 case glslang::EOpConvIntToInt64:
6439 case glslang::EOpConvInt64ToInt8:
6440 case glslang::EOpConvInt64ToInt16:
6441 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006442 convOp = spv::OpSConvert;
6443 break;
6444
John Kessenich66011cb2018-03-06 16:12:04 -07006445 case glslang::EOpConvUint8ToUint16:
6446 case glslang::EOpConvUint8ToUint:
6447 case glslang::EOpConvUint8ToUint64:
6448 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006449 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006450 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006451 case glslang::EOpConvUintToUint8:
6452 case glslang::EOpConvUintToUint16:
6453 case glslang::EOpConvUintToUint64:
6454 case glslang::EOpConvUint64ToUint8:
6455 case glslang::EOpConvUint64ToUint16:
6456 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006457 convOp = spv::OpUConvert;
6458 break;
6459
John Kessenich66011cb2018-03-06 16:12:04 -07006460 case glslang::EOpConvInt8ToUint16:
6461 case glslang::EOpConvInt8ToUint:
6462 case glslang::EOpConvInt8ToUint64:
6463 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006464 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006465 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006466 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006467 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006468 case glslang::EOpConvIntToUint64:
6469 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006470 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006471 case glslang::EOpConvInt64ToUint:
6472 case glslang::EOpConvUint8ToInt16:
6473 case glslang::EOpConvUint8ToInt:
6474 case glslang::EOpConvUint8ToInt64:
6475 case glslang::EOpConvUint16ToInt8:
6476 case glslang::EOpConvUint16ToInt:
6477 case glslang::EOpConvUint16ToInt64:
6478 case glslang::EOpConvUintToInt8:
6479 case glslang::EOpConvUintToInt16:
6480 case glslang::EOpConvUintToInt64:
6481 case glslang::EOpConvUint64ToInt8:
6482 case glslang::EOpConvUint64ToInt16:
6483 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006484 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006485 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006486
6487 if (builder.isInSpecConstCodeGenMode()) {
6488 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006489 switch(op) {
6490 case glslang::EOpConvInt16ToUint8:
6491 case glslang::EOpConvIntToUint8:
6492 case glslang::EOpConvInt64ToUint8:
6493 case glslang::EOpConvUint16ToInt8:
6494 case glslang::EOpConvUintToInt8:
6495 case glslang::EOpConvUint64ToInt8:
6496 zero = builder.makeUint8Constant(0);
6497 break;
6498 case glslang::EOpConvInt8ToUint16:
6499 case glslang::EOpConvIntToUint16:
6500 case glslang::EOpConvInt64ToUint16:
6501 case glslang::EOpConvUint8ToInt16:
6502 case glslang::EOpConvUintToInt16:
6503 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006504 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006505 break;
6506 case glslang::EOpConvInt8ToUint:
6507 case glslang::EOpConvInt16ToUint:
6508 case glslang::EOpConvInt64ToUint:
6509 case glslang::EOpConvUint8ToInt:
6510 case glslang::EOpConvUint16ToInt:
6511 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006512 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006513 break;
6514 case glslang::EOpConvInt8ToUint64:
6515 case glslang::EOpConvInt16ToUint64:
6516 case glslang::EOpConvIntToUint64:
6517 case glslang::EOpConvUint8ToInt64:
6518 case glslang::EOpConvUint16ToInt64:
6519 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006520 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006521 break;
6522 default:
6523 assert(false && "Default missing");
6524 break;
6525 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006526 zero = makeSmearedConstant(zero, vectorSize);
6527 // Use OpIAdd, instead of OpBitcast to do the conversion when
6528 // generating for OpSpecConstantOp instruction.
6529 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6530 }
6531 // For normal run-time conversion instruction, use OpBitcast.
6532 convOp = spv::OpBitcast;
6533 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006534 case glslang::EOpConvUint64ToPtr:
6535 convOp = spv::OpConvertUToPtr;
6536 break;
6537 case glslang::EOpConvPtrToUint64:
6538 convOp = spv::OpConvertPtrToU;
6539 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006540 case glslang::EOpConvPtrToUvec2:
6541 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006542 if (builder.isVector(operand))
6543 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6544 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006545 convOp = spv::OpBitcast;
6546 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006547#endif
6548
John Kessenich140f3df2015-06-26 16:58:36 -06006549 default:
6550 break;
6551 }
6552
6553 spv::Id result = 0;
6554 if (convOp == spv::OpNop)
6555 return result;
6556
6557 if (convOp == spv::OpSelect) {
6558 zero = makeSmearedConstant(zero, vectorSize);
6559 one = makeSmearedConstant(one, vectorSize);
6560 result = builder.createTriOp(convOp, destType, operand, one, zero);
6561 } else
6562 result = builder.createUnaryOp(convOp, destType, operand);
6563
John Kessenichead86222018-03-28 18:01:20 -06006564 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006565 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006566 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006567}
6568
6569spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6570{
6571 if (vectorSize == 0)
6572 return constant;
6573
6574 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6575 std::vector<spv::Id> components;
6576 for (int c = 0; c < vectorSize; ++c)
6577 components.push_back(constant);
6578 return builder.makeCompositeConstant(vectorTypeId, components);
6579}
6580
John Kessenich426394d2015-07-23 10:22:48 -06006581// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006582spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6583 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6584 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006585{
6586 spv::Op opCode = spv::OpNop;
6587
6588 switch (op) {
6589 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006590 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006591 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006592 opCode = spv::OpAtomicIAdd;
6593 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006594 case glslang::EOpAtomicCounterSubtract:
6595 opCode = spv::OpAtomicISub;
6596 break;
John Kessenich426394d2015-07-23 10:22:48 -06006597 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006598 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006599 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006600 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6601 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006602 break;
6603 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006604 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006605 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006606 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6607 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006608 break;
6609 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006610 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006611 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006612 opCode = spv::OpAtomicAnd;
6613 break;
6614 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006615 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006616 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006617 opCode = spv::OpAtomicOr;
6618 break;
6619 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006620 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006621 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006622 opCode = spv::OpAtomicXor;
6623 break;
6624 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006625 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006626 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006627 opCode = spv::OpAtomicExchange;
6628 break;
6629 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006630 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006631 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006632 opCode = spv::OpAtomicCompareExchange;
6633 break;
6634 case glslang::EOpAtomicCounterIncrement:
6635 opCode = spv::OpAtomicIIncrement;
6636 break;
6637 case glslang::EOpAtomicCounterDecrement:
6638 opCode = spv::OpAtomicIDecrement;
6639 break;
6640 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006641 case glslang::EOpImageAtomicLoad:
6642 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006643 opCode = spv::OpAtomicLoad;
6644 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006645 case glslang::EOpAtomicStore:
6646 case glslang::EOpImageAtomicStore:
6647 opCode = spv::OpAtomicStore;
6648 break;
John Kessenich426394d2015-07-23 10:22:48 -06006649 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006650 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006651 break;
6652 }
6653
Rex Xue8fe8b02017-09-26 15:42:56 +08006654 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6655 builder.addCapability(spv::CapabilityInt64Atomics);
6656
John Kessenich426394d2015-07-23 10:22:48 -06006657 // Sort out the operands
6658 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006659 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006660 // - compare-exchange swaps the value and comparator
6661 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006662 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006663 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6664 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6665 spv::Id scopeId;
6666 if (glslangIntermediate->usingVulkanMemoryModel()) {
6667 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6668 } else {
6669 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6670 }
6671 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006672 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6673 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006674 spv::MemorySemanticsVolatileMask :
6675 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006676 spv::Id semanticsId2 = semanticsId;
6677
6678 pointerId = operands[0];
6679 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6680 // no additional operands
6681 } else if (opCode == spv::OpAtomicCompareExchange) {
6682 compareId = operands[1];
6683 valueId = operands[2];
6684 if (operands.size() > 3) {
6685 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006686 semanticsId = builder.makeUintConstant(
6687 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6688 semanticsId2 = builder.makeUintConstant(
6689 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006690 }
6691 } else if (opCode == spv::OpAtomicLoad) {
6692 if (operands.size() > 1) {
6693 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006694 semanticsId = builder.makeUintConstant(
6695 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006696 }
6697 } else {
6698 // atomic store or RMW
6699 valueId = operands[1];
6700 if (operands.size() > 2) {
6701 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006702 semanticsId = builder.makeUintConstant
6703 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006704 }
Rex Xu04db3f52015-09-16 11:44:02 +08006705 }
John Kessenich426394d2015-07-23 10:22:48 -06006706
Jeff Bolz36831c92018-09-05 10:11:41 -05006707 // Check for capabilities
6708 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006709 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6710 spv::MemorySemanticsMakeVisibleKHRMask |
6711 spv::MemorySemanticsOutputMemoryKHRMask |
6712 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006713 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6714 }
John Kessenich426394d2015-07-23 10:22:48 -06006715
Jeff Bolz36831c92018-09-05 10:11:41 -05006716 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6717 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6718 }
John Kessenich48d6e792017-10-06 21:21:48 -06006719
Jeff Bolz36831c92018-09-05 10:11:41 -05006720 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6721 spvAtomicOperands.push_back(pointerId);
6722 spvAtomicOperands.push_back(scopeId);
6723 spvAtomicOperands.push_back(semanticsId);
6724 if (opCode == spv::OpAtomicCompareExchange) {
6725 spvAtomicOperands.push_back(semanticsId2);
6726 spvAtomicOperands.push_back(valueId);
6727 spvAtomicOperands.push_back(compareId);
6728 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6729 spvAtomicOperands.push_back(valueId);
6730 }
John Kessenich48d6e792017-10-06 21:21:48 -06006731
Jeff Bolz36831c92018-09-05 10:11:41 -05006732 if (opCode == spv::OpAtomicStore) {
6733 builder.createNoResultOp(opCode, spvAtomicOperands);
6734 return 0;
6735 } else {
6736 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6737
6738 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6739 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6740 if (op == glslang::EOpAtomicCounterDecrement)
6741 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6742
6743 return resultId;
6744 }
John Kessenich426394d2015-07-23 10:22:48 -06006745}
6746
John Kessenich91cef522016-05-05 16:45:40 -06006747// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006748spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6749 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006750{
John Kessenich66011cb2018-03-06 16:12:04 -07006751 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6752 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006753
Rex Xu51596642016-09-21 18:56:12 +08006754 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006755 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006756 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6757
chaocf200da82016-12-20 12:44:35 -08006758 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6759 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006760 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6761 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006762 } else if (op == glslang::EOpAnyInvocation ||
6763 op == glslang::EOpAllInvocations ||
6764 op == glslang::EOpAllInvocationsEqual) {
6765 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6766 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006767 } else {
6768 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006769 if (op == glslang::EOpMinInvocationsNonUniform ||
6770 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006771 op == glslang::EOpAddInvocationsNonUniform ||
6772 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6773 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6774 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6775 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6776 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6777 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006778 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006779
Rex Xu430ef402016-10-14 17:22:23 +08006780 switch (op) {
6781 case glslang::EOpMinInvocations:
6782 case glslang::EOpMaxInvocations:
6783 case glslang::EOpAddInvocations:
6784 case glslang::EOpMinInvocationsNonUniform:
6785 case glslang::EOpMaxInvocationsNonUniform:
6786 case glslang::EOpAddInvocationsNonUniform:
6787 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006788 break;
6789 case glslang::EOpMinInvocationsInclusiveScan:
6790 case glslang::EOpMaxInvocationsInclusiveScan:
6791 case glslang::EOpAddInvocationsInclusiveScan:
6792 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6793 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6794 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6795 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006796 break;
6797 case glslang::EOpMinInvocationsExclusiveScan:
6798 case glslang::EOpMaxInvocationsExclusiveScan:
6799 case glslang::EOpAddInvocationsExclusiveScan:
6800 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6801 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6802 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6803 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006804 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006805 default:
6806 break;
Rex Xu430ef402016-10-14 17:22:23 +08006807 }
John Kessenich149afc32018-08-14 13:31:43 -06006808 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6809 spvGroupOperands.push_back(scope);
6810 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006811 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006812 spvGroupOperands.push_back(groupOp);
6813 }
Rex Xu51596642016-09-21 18:56:12 +08006814 }
6815
John Kessenich149afc32018-08-14 13:31:43 -06006816 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6817 spv::IdImmediate op = { true, *opIt };
6818 spvGroupOperands.push_back(op);
6819 }
John Kessenich91cef522016-05-05 16:45:40 -06006820
6821 switch (op) {
6822 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006823 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006824 break;
John Kessenich91cef522016-05-05 16:45:40 -06006825 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006826 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006827 break;
John Kessenich91cef522016-05-05 16:45:40 -06006828 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006829 opCode = spv::OpSubgroupAllEqualKHR;
6830 break;
Rex Xu51596642016-09-21 18:56:12 +08006831 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006832 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006833 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006834 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006835 break;
6836 case glslang::EOpReadFirstInvocation:
6837 opCode = spv::OpSubgroupFirstInvocationKHR;
6838 break;
6839 case glslang::EOpBallot:
6840 {
6841 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6842 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6843 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6844 //
6845 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6846 //
6847 spv::Id uintType = builder.makeUintType(32);
6848 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6849 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6850
6851 std::vector<spv::Id> components;
6852 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6853 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6854
6855 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6856 return builder.createUnaryOp(spv::OpBitcast, typeId,
6857 builder.createCompositeConstruct(uvec2Type, components));
6858 }
6859
Rex Xu9d93a232016-05-05 12:30:44 +08006860 case glslang::EOpMinInvocations:
6861 case glslang::EOpMaxInvocations:
6862 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006863 case glslang::EOpMinInvocationsInclusiveScan:
6864 case glslang::EOpMaxInvocationsInclusiveScan:
6865 case glslang::EOpAddInvocationsInclusiveScan:
6866 case glslang::EOpMinInvocationsExclusiveScan:
6867 case glslang::EOpMaxInvocationsExclusiveScan:
6868 case glslang::EOpAddInvocationsExclusiveScan:
6869 if (op == glslang::EOpMinInvocations ||
6870 op == glslang::EOpMinInvocationsInclusiveScan ||
6871 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006872 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006873 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006874 else {
6875 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006876 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006877 else
Rex Xu51596642016-09-21 18:56:12 +08006878 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006879 }
Rex Xu430ef402016-10-14 17:22:23 +08006880 } else if (op == glslang::EOpMaxInvocations ||
6881 op == glslang::EOpMaxInvocationsInclusiveScan ||
6882 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006883 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006884 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006885 else {
6886 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006887 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006888 else
Rex Xu51596642016-09-21 18:56:12 +08006889 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006890 }
6891 } else {
6892 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006893 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006894 else
Rex Xu51596642016-09-21 18:56:12 +08006895 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006896 }
6897
Rex Xu2bbbe062016-08-23 15:41:05 +08006898 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006899 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006900
6901 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006902 case glslang::EOpMinInvocationsNonUniform:
6903 case glslang::EOpMaxInvocationsNonUniform:
6904 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006905 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6906 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6907 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6908 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6909 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6910 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6911 if (op == glslang::EOpMinInvocationsNonUniform ||
6912 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6913 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006914 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006915 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006916 else {
6917 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006918 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006919 else
Rex Xu51596642016-09-21 18:56:12 +08006920 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006921 }
6922 }
Rex Xu430ef402016-10-14 17:22:23 +08006923 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6924 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6925 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006926 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006927 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006928 else {
6929 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006930 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006931 else
Rex Xu51596642016-09-21 18:56:12 +08006932 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006933 }
6934 }
6935 else {
6936 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006937 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006938 else
Rex Xu51596642016-09-21 18:56:12 +08006939 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006940 }
6941
Rex Xu2bbbe062016-08-23 15:41:05 +08006942 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006943 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006944
6945 break;
John Kessenich91cef522016-05-05 16:45:40 -06006946 default:
6947 logger->missingFunctionality("invocation operation");
6948 return spv::NoResult;
6949 }
Rex Xu51596642016-09-21 18:56:12 +08006950
6951 assert(opCode != spv::OpNop);
6952 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006953}
6954
Rex Xu2bbbe062016-08-23 15:41:05 +08006955// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006956spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6957 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006958{
6959 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6960 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006961 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006962 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07006963 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
6964 op == spv::OpGroupSMinNonUniformAMD ||
6965 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
6966 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006967 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6968
6969 // Handle group invocation operations scalar by scalar.
6970 // The result type is the same type as the original type.
6971 // The algorithm is to:
6972 // - break the vector into scalars
6973 // - apply the operation to each scalar
6974 // - make a vector out the scalar results
6975
6976 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006977 int numComponents = builder.getNumComponents(operands[0]);
6978 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006979 std::vector<spv::Id> results;
6980
6981 // do each scalar op
6982 for (int comp = 0; comp < numComponents; ++comp) {
6983 std::vector<unsigned int> indexes;
6984 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006985 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6986 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006987 if (op == spv::OpSubgroupReadInvocationKHR) {
6988 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006989 spv::IdImmediate operand = { true, operands[1] };
6990 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006991 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006992 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6993 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006994 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006995 spv::IdImmediate operand = { true, operands[1] };
6996 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006997 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006998 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6999 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007000 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007001 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007002 spvGroupOperands.push_back(scalar);
7003 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007004
Rex Xub7072052016-09-26 15:53:40 +08007005 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007006 }
7007
7008 // put the pieces together
7009 return builder.createCompositeConstruct(typeId, results);
7010}
Rex Xu2bbbe062016-08-23 15:41:05 +08007011
John Kessenich66011cb2018-03-06 16:12:04 -07007012// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007013spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7014 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007015{
7016 // Add the required capabilities.
7017 switch (op) {
7018 case glslang::EOpSubgroupElect:
7019 builder.addCapability(spv::CapabilityGroupNonUniform);
7020 break;
7021 case glslang::EOpSubgroupAll:
7022 case glslang::EOpSubgroupAny:
7023 case glslang::EOpSubgroupAllEqual:
7024 builder.addCapability(spv::CapabilityGroupNonUniform);
7025 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7026 break;
7027 case glslang::EOpSubgroupBroadcast:
7028 case glslang::EOpSubgroupBroadcastFirst:
7029 case glslang::EOpSubgroupBallot:
7030 case glslang::EOpSubgroupInverseBallot:
7031 case glslang::EOpSubgroupBallotBitExtract:
7032 case glslang::EOpSubgroupBallotBitCount:
7033 case glslang::EOpSubgroupBallotInclusiveBitCount:
7034 case glslang::EOpSubgroupBallotExclusiveBitCount:
7035 case glslang::EOpSubgroupBallotFindLSB:
7036 case glslang::EOpSubgroupBallotFindMSB:
7037 builder.addCapability(spv::CapabilityGroupNonUniform);
7038 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7039 break;
7040 case glslang::EOpSubgroupShuffle:
7041 case glslang::EOpSubgroupShuffleXor:
7042 builder.addCapability(spv::CapabilityGroupNonUniform);
7043 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7044 break;
7045 case glslang::EOpSubgroupShuffleUp:
7046 case glslang::EOpSubgroupShuffleDown:
7047 builder.addCapability(spv::CapabilityGroupNonUniform);
7048 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7049 break;
7050 case glslang::EOpSubgroupAdd:
7051 case glslang::EOpSubgroupMul:
7052 case glslang::EOpSubgroupMin:
7053 case glslang::EOpSubgroupMax:
7054 case glslang::EOpSubgroupAnd:
7055 case glslang::EOpSubgroupOr:
7056 case glslang::EOpSubgroupXor:
7057 case glslang::EOpSubgroupInclusiveAdd:
7058 case glslang::EOpSubgroupInclusiveMul:
7059 case glslang::EOpSubgroupInclusiveMin:
7060 case glslang::EOpSubgroupInclusiveMax:
7061 case glslang::EOpSubgroupInclusiveAnd:
7062 case glslang::EOpSubgroupInclusiveOr:
7063 case glslang::EOpSubgroupInclusiveXor:
7064 case glslang::EOpSubgroupExclusiveAdd:
7065 case glslang::EOpSubgroupExclusiveMul:
7066 case glslang::EOpSubgroupExclusiveMin:
7067 case glslang::EOpSubgroupExclusiveMax:
7068 case glslang::EOpSubgroupExclusiveAnd:
7069 case glslang::EOpSubgroupExclusiveOr:
7070 case glslang::EOpSubgroupExclusiveXor:
7071 builder.addCapability(spv::CapabilityGroupNonUniform);
7072 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7073 break;
7074 case glslang::EOpSubgroupClusteredAdd:
7075 case glslang::EOpSubgroupClusteredMul:
7076 case glslang::EOpSubgroupClusteredMin:
7077 case glslang::EOpSubgroupClusteredMax:
7078 case glslang::EOpSubgroupClusteredAnd:
7079 case glslang::EOpSubgroupClusteredOr:
7080 case glslang::EOpSubgroupClusteredXor:
7081 builder.addCapability(spv::CapabilityGroupNonUniform);
7082 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7083 break;
7084 case glslang::EOpSubgroupQuadBroadcast:
7085 case glslang::EOpSubgroupQuadSwapHorizontal:
7086 case glslang::EOpSubgroupQuadSwapVertical:
7087 case glslang::EOpSubgroupQuadSwapDiagonal:
7088 builder.addCapability(spv::CapabilityGroupNonUniform);
7089 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7090 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007091 case glslang::EOpSubgroupPartitionedAdd:
7092 case glslang::EOpSubgroupPartitionedMul:
7093 case glslang::EOpSubgroupPartitionedMin:
7094 case glslang::EOpSubgroupPartitionedMax:
7095 case glslang::EOpSubgroupPartitionedAnd:
7096 case glslang::EOpSubgroupPartitionedOr:
7097 case glslang::EOpSubgroupPartitionedXor:
7098 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7099 case glslang::EOpSubgroupPartitionedInclusiveMul:
7100 case glslang::EOpSubgroupPartitionedInclusiveMin:
7101 case glslang::EOpSubgroupPartitionedInclusiveMax:
7102 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7103 case glslang::EOpSubgroupPartitionedInclusiveOr:
7104 case glslang::EOpSubgroupPartitionedInclusiveXor:
7105 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7106 case glslang::EOpSubgroupPartitionedExclusiveMul:
7107 case glslang::EOpSubgroupPartitionedExclusiveMin:
7108 case glslang::EOpSubgroupPartitionedExclusiveMax:
7109 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7110 case glslang::EOpSubgroupPartitionedExclusiveOr:
7111 case glslang::EOpSubgroupPartitionedExclusiveXor:
7112 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7113 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7114 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007115 default: assert(0 && "Unhandled subgroup operation!");
7116 }
7117
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007118
7119 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7120 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007121 const bool isBool = typeProxy == glslang::EbtBool;
7122
7123 spv::Op opCode = spv::OpNop;
7124
7125 // Figure out which opcode to use.
7126 switch (op) {
7127 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7128 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7129 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7130 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7131 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7132 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7133 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7134 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7135 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7136 case glslang::EOpSubgroupBallotBitCount:
7137 case glslang::EOpSubgroupBallotInclusiveBitCount:
7138 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7139 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7140 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7141 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7142 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7143 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7144 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7145 case glslang::EOpSubgroupAdd:
7146 case glslang::EOpSubgroupInclusiveAdd:
7147 case glslang::EOpSubgroupExclusiveAdd:
7148 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007149 case glslang::EOpSubgroupPartitionedAdd:
7150 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7151 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007152 if (isFloat) {
7153 opCode = spv::OpGroupNonUniformFAdd;
7154 } else {
7155 opCode = spv::OpGroupNonUniformIAdd;
7156 }
7157 break;
7158 case glslang::EOpSubgroupMul:
7159 case glslang::EOpSubgroupInclusiveMul:
7160 case glslang::EOpSubgroupExclusiveMul:
7161 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007162 case glslang::EOpSubgroupPartitionedMul:
7163 case glslang::EOpSubgroupPartitionedInclusiveMul:
7164 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007165 if (isFloat) {
7166 opCode = spv::OpGroupNonUniformFMul;
7167 } else {
7168 opCode = spv::OpGroupNonUniformIMul;
7169 }
7170 break;
7171 case glslang::EOpSubgroupMin:
7172 case glslang::EOpSubgroupInclusiveMin:
7173 case glslang::EOpSubgroupExclusiveMin:
7174 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007175 case glslang::EOpSubgroupPartitionedMin:
7176 case glslang::EOpSubgroupPartitionedInclusiveMin:
7177 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007178 if (isFloat) {
7179 opCode = spv::OpGroupNonUniformFMin;
7180 } else if (isUnsigned) {
7181 opCode = spv::OpGroupNonUniformUMin;
7182 } else {
7183 opCode = spv::OpGroupNonUniformSMin;
7184 }
7185 break;
7186 case glslang::EOpSubgroupMax:
7187 case glslang::EOpSubgroupInclusiveMax:
7188 case glslang::EOpSubgroupExclusiveMax:
7189 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007190 case glslang::EOpSubgroupPartitionedMax:
7191 case glslang::EOpSubgroupPartitionedInclusiveMax:
7192 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007193 if (isFloat) {
7194 opCode = spv::OpGroupNonUniformFMax;
7195 } else if (isUnsigned) {
7196 opCode = spv::OpGroupNonUniformUMax;
7197 } else {
7198 opCode = spv::OpGroupNonUniformSMax;
7199 }
7200 break;
7201 case glslang::EOpSubgroupAnd:
7202 case glslang::EOpSubgroupInclusiveAnd:
7203 case glslang::EOpSubgroupExclusiveAnd:
7204 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007205 case glslang::EOpSubgroupPartitionedAnd:
7206 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7207 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007208 if (isBool) {
7209 opCode = spv::OpGroupNonUniformLogicalAnd;
7210 } else {
7211 opCode = spv::OpGroupNonUniformBitwiseAnd;
7212 }
7213 break;
7214 case glslang::EOpSubgroupOr:
7215 case glslang::EOpSubgroupInclusiveOr:
7216 case glslang::EOpSubgroupExclusiveOr:
7217 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007218 case glslang::EOpSubgroupPartitionedOr:
7219 case glslang::EOpSubgroupPartitionedInclusiveOr:
7220 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007221 if (isBool) {
7222 opCode = spv::OpGroupNonUniformLogicalOr;
7223 } else {
7224 opCode = spv::OpGroupNonUniformBitwiseOr;
7225 }
7226 break;
7227 case glslang::EOpSubgroupXor:
7228 case glslang::EOpSubgroupInclusiveXor:
7229 case glslang::EOpSubgroupExclusiveXor:
7230 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007231 case glslang::EOpSubgroupPartitionedXor:
7232 case glslang::EOpSubgroupPartitionedInclusiveXor:
7233 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007234 if (isBool) {
7235 opCode = spv::OpGroupNonUniformLogicalXor;
7236 } else {
7237 opCode = spv::OpGroupNonUniformBitwiseXor;
7238 }
7239 break;
7240 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7241 case glslang::EOpSubgroupQuadSwapHorizontal:
7242 case glslang::EOpSubgroupQuadSwapVertical:
7243 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7244 default: assert(0 && "Unhandled subgroup operation!");
7245 }
7246
John Kessenich149afc32018-08-14 13:31:43 -06007247 // get the right Group Operation
7248 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007249 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007250 default:
7251 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007252 case glslang::EOpSubgroupBallotBitCount:
7253 case glslang::EOpSubgroupAdd:
7254 case glslang::EOpSubgroupMul:
7255 case glslang::EOpSubgroupMin:
7256 case glslang::EOpSubgroupMax:
7257 case glslang::EOpSubgroupAnd:
7258 case glslang::EOpSubgroupOr:
7259 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007260 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007261 break;
7262 case glslang::EOpSubgroupBallotInclusiveBitCount:
7263 case glslang::EOpSubgroupInclusiveAdd:
7264 case glslang::EOpSubgroupInclusiveMul:
7265 case glslang::EOpSubgroupInclusiveMin:
7266 case glslang::EOpSubgroupInclusiveMax:
7267 case glslang::EOpSubgroupInclusiveAnd:
7268 case glslang::EOpSubgroupInclusiveOr:
7269 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007270 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007271 break;
7272 case glslang::EOpSubgroupBallotExclusiveBitCount:
7273 case glslang::EOpSubgroupExclusiveAdd:
7274 case glslang::EOpSubgroupExclusiveMul:
7275 case glslang::EOpSubgroupExclusiveMin:
7276 case glslang::EOpSubgroupExclusiveMax:
7277 case glslang::EOpSubgroupExclusiveAnd:
7278 case glslang::EOpSubgroupExclusiveOr:
7279 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007280 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007281 break;
7282 case glslang::EOpSubgroupClusteredAdd:
7283 case glslang::EOpSubgroupClusteredMul:
7284 case glslang::EOpSubgroupClusteredMin:
7285 case glslang::EOpSubgroupClusteredMax:
7286 case glslang::EOpSubgroupClusteredAnd:
7287 case glslang::EOpSubgroupClusteredOr:
7288 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007289 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007290 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007291 case glslang::EOpSubgroupPartitionedAdd:
7292 case glslang::EOpSubgroupPartitionedMul:
7293 case glslang::EOpSubgroupPartitionedMin:
7294 case glslang::EOpSubgroupPartitionedMax:
7295 case glslang::EOpSubgroupPartitionedAnd:
7296 case glslang::EOpSubgroupPartitionedOr:
7297 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007298 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007299 break;
7300 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7301 case glslang::EOpSubgroupPartitionedInclusiveMul:
7302 case glslang::EOpSubgroupPartitionedInclusiveMin:
7303 case glslang::EOpSubgroupPartitionedInclusiveMax:
7304 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7305 case glslang::EOpSubgroupPartitionedInclusiveOr:
7306 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007307 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007308 break;
7309 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7310 case glslang::EOpSubgroupPartitionedExclusiveMul:
7311 case glslang::EOpSubgroupPartitionedExclusiveMin:
7312 case glslang::EOpSubgroupPartitionedExclusiveMax:
7313 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7314 case glslang::EOpSubgroupPartitionedExclusiveOr:
7315 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007316 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007317 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007318 }
7319
John Kessenich149afc32018-08-14 13:31:43 -06007320 // build the instruction
7321 std::vector<spv::IdImmediate> spvGroupOperands;
7322
7323 // Every operation begins with the Execution Scope operand.
7324 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7325 spvGroupOperands.push_back(executionScope);
7326
7327 // Next, for all operations that use a Group Operation, push that as an operand.
7328 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007329 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007330 spvGroupOperands.push_back(groupOperand);
7331 }
7332
John Kessenich66011cb2018-03-06 16:12:04 -07007333 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007334 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7335 spv::IdImmediate operand = { true, *opIt };
7336 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007337 }
7338
7339 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007340 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007341 switch (op) {
7342 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007343 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7344 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7345 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7346 }
7347 if (directionId != spv::NoResult) {
7348 spv::IdImmediate direction = { true, directionId };
7349 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007350 }
7351
7352 return builder.createOp(opCode, typeId, spvGroupOperands);
7353}
7354
John Kessenich8985fc92020-03-03 10:25:07 -07007355spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7356 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007357{
John Kessenich66011cb2018-03-06 16:12:04 -07007358 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7359 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007360
John Kessenich140f3df2015-06-26 16:58:36 -06007361 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007362 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007363 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007364 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007365 spv::Id typeId0 = 0;
7366 if (consumedOperands > 0)
7367 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007368 spv::Id typeId1 = 0;
7369 if (consumedOperands > 1)
7370 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007371 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007372
7373 switch (op) {
7374 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007375 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007376 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007377 else if (isUnsigned)
7378 libCall = spv::GLSLstd450UMin;
7379 else
7380 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007381 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007382 break;
7383 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007384 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007385 break;
7386 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007387 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007388 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007389 else if (isUnsigned)
7390 libCall = spv::GLSLstd450UMax;
7391 else
7392 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007393 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007394 break;
7395 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007396 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007397 break;
7398 case glslang::EOpDot:
7399 opCode = spv::OpDot;
7400 break;
7401 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007402 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007403 break;
7404
7405 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007406 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007407 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007408 else if (isUnsigned)
7409 libCall = spv::GLSLstd450UClamp;
7410 else
7411 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007412 builder.promoteScalar(precision, operands.front(), operands[1]);
7413 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007414 break;
7415 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007416 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7417 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007418 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007419 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007420 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007421 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007422 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007423 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007424 break;
7425 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007426 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007427 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007428 break;
7429 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007430 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007431 builder.promoteScalar(precision, operands[0], operands[2]);
7432 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007433 break;
7434
7435 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007436 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007437 break;
7438 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007439 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007440 break;
7441 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007442 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007443 break;
7444 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007445 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007446 break;
7447 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007448 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007449 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007450 case glslang::EOpBarrier:
7451 {
7452 // This is for the extended controlBarrier function, with four operands.
7453 // The unextended barrier() goes through createNoArgOperation.
7454 assert(operands.size() == 4);
7455 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7456 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7457 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007458 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7459 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007460 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7461 spv::MemorySemanticsMakeVisibleKHRMask |
7462 spv::MemorySemanticsOutputMemoryKHRMask |
7463 spv::MemorySemanticsVolatileMask)) {
7464 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7465 }
John Kessenich8985fc92020-03-03 10:25:07 -07007466 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7467 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007468 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7469 }
7470 return 0;
7471 }
7472 break;
7473 case glslang::EOpMemoryBarrier:
7474 {
7475 // This is for the extended memoryBarrier function, with three operands.
7476 // The unextended memoryBarrier() goes through createNoArgOperation.
7477 assert(operands.size() == 3);
7478 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7479 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7480 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7481 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7482 spv::MemorySemanticsMakeVisibleKHRMask |
7483 spv::MemorySemanticsOutputMemoryKHRMask |
7484 spv::MemorySemanticsVolatileMask)) {
7485 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7486 }
7487 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7488 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7489 }
7490 return 0;
7491 }
7492 break;
7493
John Kessenicha28f7a72019-08-06 07:00:58 -06007494#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007495 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007496 if (typeProxy == glslang::EbtFloat16)
7497 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007498 libCall = spv::GLSLstd450InterpolateAtSample;
7499 break;
7500 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007501 if (typeProxy == glslang::EbtFloat16)
7502 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007503 libCall = spv::GLSLstd450InterpolateAtOffset;
7504 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007505 case glslang::EOpAddCarry:
7506 opCode = spv::OpIAddCarry;
7507 typeId = builder.makeStructResultType(typeId0, typeId0);
7508 consumedOperands = 2;
7509 break;
7510 case glslang::EOpSubBorrow:
7511 opCode = spv::OpISubBorrow;
7512 typeId = builder.makeStructResultType(typeId0, typeId0);
7513 consumedOperands = 2;
7514 break;
7515 case glslang::EOpUMulExtended:
7516 opCode = spv::OpUMulExtended;
7517 typeId = builder.makeStructResultType(typeId0, typeId0);
7518 consumedOperands = 2;
7519 break;
7520 case glslang::EOpIMulExtended:
7521 opCode = spv::OpSMulExtended;
7522 typeId = builder.makeStructResultType(typeId0, typeId0);
7523 consumedOperands = 2;
7524 break;
7525 case glslang::EOpBitfieldExtract:
7526 if (isUnsigned)
7527 opCode = spv::OpBitFieldUExtract;
7528 else
7529 opCode = spv::OpBitFieldSExtract;
7530 break;
7531 case glslang::EOpBitfieldInsert:
7532 opCode = spv::OpBitFieldInsert;
7533 break;
7534
7535 case glslang::EOpFma:
7536 libCall = spv::GLSLstd450Fma;
7537 break;
7538 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007539 {
7540 libCall = spv::GLSLstd450FrexpStruct;
7541 assert(builder.isPointerType(typeId1));
7542 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007543 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007544 if (width == 16)
7545 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7546 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007547 if (builder.getNumComponents(operands[0]) == 1)
7548 frexpIntType = builder.makeIntegerType(width, true);
7549 else
John Kessenich8985fc92020-03-03 10:25:07 -07007550 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7551 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007552 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7553 consumedOperands = 1;
7554 }
John Kessenich55e7d112015-11-15 21:33:39 -07007555 break;
7556 case glslang::EOpLdexp:
7557 libCall = spv::GLSLstd450Ldexp;
7558 break;
7559
Rex Xu574ab042016-04-14 16:53:07 +08007560 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007561 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007562
John Kessenich66011cb2018-03-06 16:12:04 -07007563 case glslang::EOpSubgroupBroadcast:
7564 case glslang::EOpSubgroupBallotBitExtract:
7565 case glslang::EOpSubgroupShuffle:
7566 case glslang::EOpSubgroupShuffleXor:
7567 case glslang::EOpSubgroupShuffleUp:
7568 case glslang::EOpSubgroupShuffleDown:
7569 case glslang::EOpSubgroupClusteredAdd:
7570 case glslang::EOpSubgroupClusteredMul:
7571 case glslang::EOpSubgroupClusteredMin:
7572 case glslang::EOpSubgroupClusteredMax:
7573 case glslang::EOpSubgroupClusteredAnd:
7574 case glslang::EOpSubgroupClusteredOr:
7575 case glslang::EOpSubgroupClusteredXor:
7576 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007577 case glslang::EOpSubgroupPartitionedAdd:
7578 case glslang::EOpSubgroupPartitionedMul:
7579 case glslang::EOpSubgroupPartitionedMin:
7580 case glslang::EOpSubgroupPartitionedMax:
7581 case glslang::EOpSubgroupPartitionedAnd:
7582 case glslang::EOpSubgroupPartitionedOr:
7583 case glslang::EOpSubgroupPartitionedXor:
7584 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7585 case glslang::EOpSubgroupPartitionedInclusiveMul:
7586 case glslang::EOpSubgroupPartitionedInclusiveMin:
7587 case glslang::EOpSubgroupPartitionedInclusiveMax:
7588 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7589 case glslang::EOpSubgroupPartitionedInclusiveOr:
7590 case glslang::EOpSubgroupPartitionedInclusiveXor:
7591 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7592 case glslang::EOpSubgroupPartitionedExclusiveMul:
7593 case glslang::EOpSubgroupPartitionedExclusiveMin:
7594 case glslang::EOpSubgroupPartitionedExclusiveMax:
7595 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7596 case glslang::EOpSubgroupPartitionedExclusiveOr:
7597 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007598 return createSubgroupOperation(op, typeId, operands, typeProxy);
7599
Rex Xu9d93a232016-05-05 12:30:44 +08007600 case glslang::EOpSwizzleInvocations:
7601 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7602 libCall = spv::SwizzleInvocationsAMD;
7603 break;
7604 case glslang::EOpSwizzleInvocationsMasked:
7605 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7606 libCall = spv::SwizzleInvocationsMaskedAMD;
7607 break;
7608 case glslang::EOpWriteInvocation:
7609 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7610 libCall = spv::WriteInvocationAMD;
7611 break;
7612
7613 case glslang::EOpMin3:
7614 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7615 if (isFloat)
7616 libCall = spv::FMin3AMD;
7617 else {
7618 if (isUnsigned)
7619 libCall = spv::UMin3AMD;
7620 else
7621 libCall = spv::SMin3AMD;
7622 }
7623 break;
7624 case glslang::EOpMax3:
7625 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7626 if (isFloat)
7627 libCall = spv::FMax3AMD;
7628 else {
7629 if (isUnsigned)
7630 libCall = spv::UMax3AMD;
7631 else
7632 libCall = spv::SMax3AMD;
7633 }
7634 break;
7635 case glslang::EOpMid3:
7636 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7637 if (isFloat)
7638 libCall = spv::FMid3AMD;
7639 else {
7640 if (isUnsigned)
7641 libCall = spv::UMid3AMD;
7642 else
7643 libCall = spv::SMid3AMD;
7644 }
7645 break;
7646
7647 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007648 if (typeProxy == glslang::EbtFloat16)
7649 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007650 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7651 libCall = spv::InterpolateAtVertexAMD;
7652 break;
Chao Chen3c366992018-09-19 11:41:59 -07007653
Daniel Kochdb32b242020-03-17 20:42:47 -04007654 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007655 {
7656 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007657 opCode = spv::OpReportIntersectionKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07007658 }
7659 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007660 case glslang::EOpTrace:
Chao Chenb50c02e2018-09-19 11:42:24 -07007661 {
Daniel Kochdb32b242020-03-17 20:42:47 -04007662 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007663 return 0;
7664 }
7665 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007666 case glslang::EOpExecuteCallable:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007667 {
Daniel Kochdb32b242020-03-17 20:42:47 -04007668 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007669 return 0;
7670 }
7671 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04007672 case glslang::EOpRayQueryInitialize: {
7673 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7674 return 0;
7675 } break;
7676 case glslang::EOpRayQueryTerminate: {
7677 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7678 return 0;
7679 } break;
7680 case glslang::EOpRayQueryGenerateIntersection: {
7681 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7682 return 0;
7683 } break;
7684 case glslang::EOpRayQueryConfirmIntersection: {
7685 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7686 return 0;
7687 } break;
7688 case glslang::EOpRayQueryProceed: {
7689 typeId = builder.makeBoolType();
7690 opCode = spv::OpRayQueryProceedKHR;
7691 }
7692 break;
7693 case glslang::EOpRayQueryGetIntersectionType: {
7694 typeId = builder.makeIntType(32);
7695 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
7696 } break;
7697 case glslang::EOpRayQueryGetRayTMin: {
7698 typeId = builder.makeFloatType(32);
7699 opCode = spv::OpRayQueryGetRayTMinKHR;
7700 } break;
7701 case glslang::EOpRayQueryGetRayFlags: {
7702 typeId = builder.makeIntType(32);
7703 opCode = spv::OpRayQueryGetRayFlagsKHR;
7704 } break;
7705 case glslang::EOpRayQueryGetIntersectionT: {
7706 typeId = builder.makeIntType(32);
7707 opCode = spv::OpRayQueryGetIntersectionTKHR;
7708 } break;
7709 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex: {
7710 typeId = builder.makeIntType(32);
7711 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
7712 } break;
7713 case glslang::EOpRayQueryGetIntersectionInstanceId: {
7714 typeId = builder.makeIntType(32);
7715 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
7716 } break;
7717 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset: {
7718 typeId = builder.makeIntType(32);
7719 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
7720 } break;
7721 case glslang::EOpRayQueryGetIntersectionGeometryIndex: {
7722 typeId = builder.makeIntType(32);
7723 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
7724 } break;
7725 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex: {
7726 typeId = builder.makeIntType(32);
7727 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
7728 } break;
7729 case glslang::EOpRayQueryGetIntersectionBarycentrics: {
7730 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7731 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
7732 } break;
7733 case glslang::EOpRayQueryGetIntersectionFrontFace: {
7734 typeId = builder.makeBoolType();
7735 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
7736 } break;
7737 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque: {
7738 typeId = builder.makeBoolType();
7739 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
7740 } break;
7741 case glslang::EOpRayQueryGetIntersectionObjectRayDirection: {
7742 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7743 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
7744 } break;
7745 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin: {
7746 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7747 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
7748 } break;
7749 case glslang::EOpRayQueryGetWorldRayDirection: {
7750 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7751 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
7752 } break;
7753 case glslang::EOpRayQueryGetWorldRayOrigin: {
7754 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7755 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
7756 } break;
7757 case glslang::EOpRayQueryGetIntersectionObjectToWorld: {
7758 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
7759 // https://gitlab.khronos.org/spirv/spirv-extensions/blob/cdf44fd4b854a5297bf2191d4f57f9bccbc49098/SPV_KHR_ray_query.asciidoc#ray_query_candidate_intersection_type
7760 // or per description is it typeId = builder.makeVectorType(builder.makeVectorType(builder.makeFloatType(32), 3), 4);
7761 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
7762 } break;
7763 case glslang::EOpRayQueryGetIntersectionWorldToObject: {
7764 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
7765 // https://gitlab.khronos.org/spirv/spirv-extensions/blob/cdf44fd4b854a5297bf2191d4f57f9bccbc49098/SPV_KHR_ray_query.asciidoc#ray_query_candidate_intersection_type
7766 // or per description is it typeId = builder.makeVectorType(builder.makeVectorType(builder.makeFloatType(32), 3), 4);
7767 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
7768 } break;
Chao Chen3c366992018-09-19 11:41:59 -07007769 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7770 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7771 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007772 case glslang::EOpCooperativeMatrixMulAdd:
7773 opCode = spv::OpCooperativeMatrixMulAddNV;
7774 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007775#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007776 default:
7777 return 0;
7778 }
7779
7780 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007781 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007782 // Use an extended instruction from the standard library.
7783 // Construct the call arguments, without modifying the original operands vector.
7784 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7785 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007786 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007787 } else if (opCode == spv::OpDot && !isFloat) {
7788 // int dot(int, int)
7789 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7790 const int componentCount = builder.getNumComponents(operands[0]);
7791 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7792 builder.setPrecision(mulOp, precision);
7793 id = builder.createCompositeExtract(mulOp, typeId, 0);
7794 for (int i = 1; i < componentCount; ++i) {
7795 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007796 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007797 }
John Kessenich2359bd02015-12-06 19:29:11 -07007798 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007799 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007800 case 0:
7801 // should all be handled by visitAggregate and createNoArgOperation
7802 assert(0);
7803 return 0;
7804 case 1:
7805 // should all be handled by createUnaryOperation
7806 assert(0);
7807 return 0;
7808 case 2:
7809 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7810 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007811 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007812 // anything 3 or over doesn't have l-value operands, so all should be consumed
7813 assert(consumedOperands == operands.size());
7814 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007815 break;
7816 }
7817 }
7818
John Kessenichb9197c82019-08-11 07:41:45 -06007819#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007820 // Decode the return types that were structures
7821 switch (op) {
7822 case glslang::EOpAddCarry:
7823 case glslang::EOpSubBorrow:
7824 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7825 id = builder.createCompositeExtract(id, typeId0, 0);
7826 break;
7827 case glslang::EOpUMulExtended:
7828 case glslang::EOpIMulExtended:
7829 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7830 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7831 break;
7832 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007833 {
7834 assert(operands.size() == 2);
7835 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7836 // "exp" is floating-point type (from HLSL intrinsic)
7837 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7838 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7839 builder.createStore(member1, operands[1]);
7840 } else
7841 // "exp" is integer type (from GLSL built-in function)
7842 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7843 id = builder.createCompositeExtract(id, typeId0, 0);
7844 }
John Kessenich55e7d112015-11-15 21:33:39 -07007845 break;
7846 default:
7847 break;
7848 }
John Kessenichb9197c82019-08-11 07:41:45 -06007849#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007850
John Kessenich32cfd492016-02-02 12:37:46 -07007851 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007852}
7853
Rex Xu9d93a232016-05-05 12:30:44 +08007854// Intrinsics with no arguments (or no return value, and no precision).
7855spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007856{
Jeff Bolz36831c92018-09-05 10:11:41 -05007857 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007858 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7859 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007860
7861 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007862 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007863 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007864 if (glslangIntermediate->usingVulkanMemoryModel()) {
7865 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7866 spv::MemorySemanticsOutputMemoryKHRMask |
7867 spv::MemorySemanticsAcquireReleaseMask);
7868 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7869 } else {
7870 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7871 }
John Kessenich82979362017-12-11 04:02:24 -07007872 } else {
7873 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7874 spv::MemorySemanticsWorkgroupMemoryMask |
7875 spv::MemorySemanticsAcquireReleaseMask);
7876 }
John Kessenich140f3df2015-06-26 16:58:36 -06007877 return 0;
7878 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007879 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7880 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007881 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007882 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007883 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7884 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007885 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007886 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007887 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7888 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007889 return 0;
7890 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007891 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7892 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007893 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007894#ifndef GLSLANG_WEB
7895 case glslang::EOpMemoryBarrierAtomicCounter:
7896 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7897 spv::MemorySemanticsAcquireReleaseMask);
7898 return 0;
7899 case glslang::EOpMemoryBarrierImage:
7900 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7901 spv::MemorySemanticsAcquireReleaseMask);
7902 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007903 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007904 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007905 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007906 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007907 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007908 case glslang::EOpDeviceMemoryBarrier:
7909 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7910 spv::MemorySemanticsImageMemoryMask |
7911 spv::MemorySemanticsAcquireReleaseMask);
7912 return 0;
7913 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7914 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7915 spv::MemorySemanticsImageMemoryMask |
7916 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007917 return 0;
7918 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007919 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7920 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007921 return 0;
7922 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007923 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7924 spv::MemorySemanticsWorkgroupMemoryMask |
7925 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007926 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007927 case glslang::EOpSubgroupBarrier:
7928 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7929 spv::MemorySemanticsAcquireReleaseMask);
7930 return spv::NoResult;
7931 case glslang::EOpSubgroupMemoryBarrier:
7932 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7933 spv::MemorySemanticsAcquireReleaseMask);
7934 return spv::NoResult;
7935 case glslang::EOpSubgroupMemoryBarrierBuffer:
7936 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7937 spv::MemorySemanticsAcquireReleaseMask);
7938 return spv::NoResult;
7939 case glslang::EOpSubgroupMemoryBarrierImage:
7940 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7941 spv::MemorySemanticsAcquireReleaseMask);
7942 return spv::NoResult;
7943 case glslang::EOpSubgroupMemoryBarrierShared:
7944 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7945 spv::MemorySemanticsAcquireReleaseMask);
7946 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007947
7948 case glslang::EOpEmitVertex:
7949 builder.createNoResultOp(spv::OpEmitVertex);
7950 return 0;
7951 case glslang::EOpEndPrimitive:
7952 builder.createNoResultOp(spv::OpEndPrimitive);
7953 return 0;
7954
John Kessenich66011cb2018-03-06 16:12:04 -07007955 case glslang::EOpSubgroupElect: {
7956 std::vector<spv::Id> operands;
7957 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7958 }
Rex Xu9d93a232016-05-05 12:30:44 +08007959 case glslang::EOpTime:
7960 {
7961 std::vector<spv::Id> args; // Dummy arguments
7962 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7963 return builder.setPrecision(id, precision);
7964 }
Daniel Kochdb32b242020-03-17 20:42:47 -04007965 case glslang::EOpIgnoreIntersection:
7966 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07007967 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007968 case glslang::EOpTerminateRay:
7969 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07007970 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04007971 case glslang::EOpRayQueryInitialize:
7972 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
7973 return 0;
7974 case glslang::EOpRayQueryTerminate:
7975 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
7976 return 0;
7977 case glslang::EOpRayQueryGenerateIntersection:
7978 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
7979 return 0;
7980 case glslang::EOpRayQueryConfirmIntersection:
7981 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
7982 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007983 case glslang::EOpBeginInvocationInterlock:
7984 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7985 return 0;
7986 case glslang::EOpEndInvocationInterlock:
7987 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7988 return 0;
7989
Jeff Bolzba6170b2019-07-01 09:23:23 -05007990 case glslang::EOpIsHelperInvocation:
7991 {
7992 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007993 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7994 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7995 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007996 }
7997
amhagan91fb0092019-07-10 21:14:38 -04007998 case glslang::EOpReadClockSubgroupKHR: {
7999 std::vector<spv::Id> args;
8000 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8001 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8002 builder.addCapability(spv::CapabilityShaderClockKHR);
8003 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8004 }
8005
8006 case glslang::EOpReadClockDeviceKHR: {
8007 std::vector<spv::Id> args;
8008 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8009 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8010 builder.addCapability(spv::CapabilityShaderClockKHR);
8011 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8012 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008013#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008014 default:
John Kessenich155d3512019-08-08 23:29:20 -06008015 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008016 }
John Kessenich155d3512019-08-08 23:29:20 -06008017
8018 logger->missingFunctionality("unknown operation with no arguments");
8019
8020 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008021}
8022
8023spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8024{
John Kessenich2f273362015-07-18 22:34:27 -06008025 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008026 spv::Id id;
8027 if (symbolValues.end() != iter) {
8028 id = iter->second;
8029 return id;
8030 }
8031
8032 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008033 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008034 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008035 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008036 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008037 if (forcedType.second != spv::NoType)
8038 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008039
Rex Xuc884b4a2016-06-29 15:03:44 +08008040 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008041 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8042 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8043 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008044#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008045 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008046 if (symbol->getQualifier().hasComponent())
8047 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8048 if (symbol->getQualifier().hasIndex())
8049 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008050#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008051 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008052 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008053 // atomic counters use this:
8054 if (symbol->getQualifier().hasOffset())
8055 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008056 }
8057
scygan2c864272016-05-18 18:09:17 +02008058 if (symbol->getQualifier().hasLocation())
8059 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008060 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008061 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008062 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008063 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008064 }
John Kessenich140f3df2015-06-26 16:58:36 -06008065 if (symbol->getQualifier().hasSet())
8066 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008067 else if (IsDescriptorResource(symbol->getType())) {
8068 // default to 0
8069 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8070 }
John Kessenich140f3df2015-06-26 16:58:36 -06008071 if (symbol->getQualifier().hasBinding())
8072 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008073 else if (IsDescriptorResource(symbol->getType())) {
8074 // default to 0
8075 builder.addDecoration(id, spv::DecorationBinding, 0);
8076 }
John Kessenich6c292d32016-02-15 20:58:50 -07008077 if (symbol->getQualifier().hasAttachment())
8078 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008079 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008080 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008081 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008082 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008083 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8084 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8085 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8086 }
8087 if (symbol->getQualifier().hasXfbOffset())
8088 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008089 }
8090
John Kessenichb9197c82019-08-11 07:41:45 -06008091 // add built-in variable decoration
8092 if (builtIn != spv::BuiltInMax) {
8093 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8094 }
8095
8096#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008097 if (symbol->getType().isImage()) {
8098 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008099 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8100 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008101 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008102 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008103 }
8104
John Kessenich5611c6d2018-04-05 11:25:02 -06008105 // nonuniform
8106 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8107
chaoc0ad6a4e2016-12-19 16:29:34 -08008108 if (builtIn == spv::BuiltInSampleMask) {
8109 spv::Decoration decoration;
8110 // GL_NV_sample_mask_override_coverage extension
8111 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008112 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008113 else
8114 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008115 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008116 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008117 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008118 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8119 }
8120 }
chaoc771d89f2017-01-13 01:10:53 -08008121 else if (builtIn == spv::BuiltInLayer) {
8122 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008123 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008124 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008125 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8126 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8127 }
John Kessenichb41bff62017-08-11 13:07:17 -06008128 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008129 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8130 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008131 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8132 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8133 }
8134 }
8135
chaoc6e5acae2016-12-20 13:28:52 -08008136 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008137 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008138 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008139 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8140 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008141 if (symbol->getQualifier().pervertexNV) {
8142 builder.addDecoration(id, spv::DecorationPerVertexNV);
8143 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8144 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8145 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008146
John Kessenich5d610ee2018-03-07 18:05:55 -07008147 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8148 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8149 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8150 symbol->getType().getQualifier().semanticName);
8151 }
8152
John Kessenich7015bd62019-08-01 03:28:08 -06008153 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008154 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8155 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008156 }
John Kessenichb9197c82019-08-11 07:41:45 -06008157#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008158
John Kessenich140f3df2015-06-26 16:58:36 -06008159 return id;
8160}
8161
John Kessenicha28f7a72019-08-06 07:00:58 -06008162#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008163// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8164void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8165{
8166 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008167 if (qualifier.perPrimitiveNV) {
8168 // Need to add capability/extension for fragment shader.
8169 // Mesh shader already adds this by default.
8170 if (glslangIntermediate->getStage() == EShLangFragment) {
8171 builder.addCapability(spv::CapabilityMeshShadingNV);
8172 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8173 }
Chao Chen3c366992018-09-19 11:41:59 -07008174 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008175 }
Chao Chen3c366992018-09-19 11:41:59 -07008176 if (qualifier.perViewNV)
8177 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8178 if (qualifier.perTaskNV)
8179 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8180 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008181 if (qualifier.perPrimitiveNV) {
8182 // Need to add capability/extension for fragment shader.
8183 // Mesh shader already adds this by default.
8184 if (glslangIntermediate->getStage() == EShLangFragment) {
8185 builder.addCapability(spv::CapabilityMeshShadingNV);
8186 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8187 }
Chao Chen3c366992018-09-19 11:41:59 -07008188 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008189 }
Chao Chen3c366992018-09-19 11:41:59 -07008190 if (qualifier.perViewNV)
8191 builder.addDecoration(id, spv::DecorationPerViewNV);
8192 if (qualifier.perTaskNV)
8193 builder.addDecoration(id, spv::DecorationPerTaskNV);
8194 }
8195}
8196#endif
8197
John Kessenich55e7d112015-11-15 21:33:39 -07008198// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008199// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008200//
8201// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8202//
8203// Recursively walk the nodes. The nodes form a tree whose leaves are
8204// regular constants, which themselves are trees that createSpvConstant()
8205// recursively walks. So, this function walks the "top" of the tree:
8206// - emit specialization constant-building instructions for specConstant
8207// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008208spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008209{
John Kessenich7cc0e282016-03-20 00:46:02 -06008210 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008211
qining4f4bb812016-04-03 23:55:17 -04008212 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008213 if (! node.getQualifier().specConstant) {
8214 // hand off to the non-spec-constant path
8215 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8216 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008217 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8218 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8219 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008220 }
8221
8222 // We now know we have a specialization constant to build
8223
John Kessenichd94c0032016-05-30 19:29:40 -06008224 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008225 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8226 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8227 std::vector<spv::Id> dimConstId;
8228 for (int dim = 0; dim < 3; ++dim) {
8229 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8230 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008231 if (specConst) {
8232 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8233 glslangIntermediate->getLocalSizeSpecId(dim));
8234 }
qining4f4bb812016-04-03 23:55:17 -04008235 }
8236 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8237 }
8238
8239 // An AST node labelled as specialization constant should be a symbol node.
8240 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8241 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008242 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008243 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008244 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8245 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8246 // will set the builder into spec constant op instruction generating mode.
8247 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008248 result = accessChainLoad(sub_tree->getType());
8249 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008250 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008251 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008252 } else {
8253 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008254 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008255 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008256 builder.addName(result, sn->getName().c_str());
8257 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008258 }
qining4f4bb812016-04-03 23:55:17 -04008259
8260 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8261 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008262 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008263 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008264}
8265
John Kessenich140f3df2015-06-26 16:58:36 -06008266// Use 'consts' as the flattened glslang source of scalar constants to recursively
8267// build the aggregate SPIR-V constant.
8268//
8269// If there are not enough elements present in 'consts', 0 will be substituted;
8270// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8271//
John Kessenich8985fc92020-03-03 10:25:07 -07008272spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8273 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008274{
8275 // vector of constants for SPIR-V
8276 std::vector<spv::Id> spvConsts;
8277
8278 // Type is used for struct and array constants
8279 spv::Id typeId = convertGlslangToSpvType(glslangType);
8280
8281 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008282 glslang::TType elementType(glslangType, 0);
8283 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008284 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008285 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008286 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008287 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008288 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008289 } else if (glslangType.isCoopMat()) {
8290 glslang::TType componentType(glslangType.getBasicType());
8291 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008292 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008293 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8294 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008295 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008296 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008297 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8298 bool zero = nextConst >= consts.size();
8299 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008300 case glslang::EbtInt:
8301 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8302 break;
8303 case glslang::EbtUint:
8304 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8305 break;
8306 case glslang::EbtFloat:
8307 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8308 break;
8309 case glslang::EbtBool:
8310 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8311 break;
8312#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008313 case glslang::EbtInt8:
8314 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8315 break;
8316 case glslang::EbtUint8:
8317 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8318 break;
8319 case glslang::EbtInt16:
8320 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8321 break;
8322 case glslang::EbtUint16:
8323 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8324 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008325 case glslang::EbtInt64:
8326 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8327 break;
8328 case glslang::EbtUint64:
8329 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8330 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008331 case glslang::EbtDouble:
8332 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8333 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008334 case glslang::EbtFloat16:
8335 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8336 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008337#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008338 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008339 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008340 break;
8341 }
8342 ++nextConst;
8343 }
8344 } else {
8345 // we have a non-aggregate (scalar) constant
8346 bool zero = nextConst >= consts.size();
8347 spv::Id scalar = 0;
8348 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008349 case glslang::EbtInt:
8350 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8351 break;
8352 case glslang::EbtUint:
8353 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8354 break;
8355 case glslang::EbtFloat:
8356 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8357 break;
8358 case glslang::EbtBool:
8359 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8360 break;
8361#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008362 case glslang::EbtInt8:
8363 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8364 break;
8365 case glslang::EbtUint8:
8366 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8367 break;
8368 case glslang::EbtInt16:
8369 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8370 break;
8371 case glslang::EbtUint16:
8372 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8373 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008374 case glslang::EbtInt64:
8375 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8376 break;
8377 case glslang::EbtUint64:
8378 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8379 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008380 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008381 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008382 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008383 case glslang::EbtFloat16:
8384 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8385 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008386 case glslang::EbtReference:
8387 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8388 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8389 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008390#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008391 case glslang::EbtString:
8392 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8393 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008394 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008395 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008396 break;
8397 }
8398 ++nextConst;
8399 return scalar;
8400 }
8401
8402 return builder.makeCompositeConstant(typeId, spvConsts);
8403}
8404
John Kessenich7c1aa102015-10-15 13:29:11 -06008405// Return true if the node is a constant or symbol whose reading has no
8406// non-trivial observable cost or effect.
8407bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8408{
8409 // don't know what this is
8410 if (node == nullptr)
8411 return false;
8412
8413 // a constant is safe
8414 if (node->getAsConstantUnion() != nullptr)
8415 return true;
8416
8417 // not a symbol means non-trivial
8418 if (node->getAsSymbolNode() == nullptr)
8419 return false;
8420
8421 // a symbol, depends on what's being read
8422 switch (node->getType().getQualifier().storage) {
8423 case glslang::EvqTemporary:
8424 case glslang::EvqGlobal:
8425 case glslang::EvqIn:
8426 case glslang::EvqInOut:
8427 case glslang::EvqConst:
8428 case glslang::EvqConstReadOnly:
8429 case glslang::EvqUniform:
8430 return true;
8431 default:
8432 return false;
8433 }
qining25262b32016-05-06 17:25:16 -04008434}
John Kessenich7c1aa102015-10-15 13:29:11 -06008435
8436// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008437// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008438// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008439// Return true if trivial.
8440bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8441{
8442 if (node == nullptr)
8443 return false;
8444
John Kessenich84cc15f2017-05-24 16:44:47 -06008445 // count non scalars as trivial, as well as anything coming from HLSL
8446 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008447 return true;
8448
John Kessenich7c1aa102015-10-15 13:29:11 -06008449 // symbols and constants are trivial
8450 if (isTrivialLeaf(node))
8451 return true;
8452
8453 // otherwise, it needs to be a simple operation or one or two leaf nodes
8454
8455 // not a simple operation
8456 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8457 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8458 if (binaryNode == nullptr && unaryNode == nullptr)
8459 return false;
8460
8461 // not on leaf nodes
8462 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8463 return false;
8464
8465 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8466 return false;
8467 }
8468
8469 switch (node->getAsOperator()->getOp()) {
8470 case glslang::EOpLogicalNot:
8471 case glslang::EOpConvIntToBool:
8472 case glslang::EOpConvUintToBool:
8473 case glslang::EOpConvFloatToBool:
8474 case glslang::EOpConvDoubleToBool:
8475 case glslang::EOpEqual:
8476 case glslang::EOpNotEqual:
8477 case glslang::EOpLessThan:
8478 case glslang::EOpGreaterThan:
8479 case glslang::EOpLessThanEqual:
8480 case glslang::EOpGreaterThanEqual:
8481 case glslang::EOpIndexDirect:
8482 case glslang::EOpIndexDirectStruct:
8483 case glslang::EOpLogicalXor:
8484 case glslang::EOpAny:
8485 case glslang::EOpAll:
8486 return true;
8487 default:
8488 return false;
8489 }
8490}
8491
8492// Emit short-circuiting code, where 'right' is never evaluated unless
8493// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008494spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8495 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008496{
8497 spv::Id boolTypeId = builder.makeBoolType();
8498
8499 // emit left operand
8500 builder.clearAccessChain();
8501 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008502 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008503
8504 // Operands to accumulate OpPhi operands
8505 std::vector<spv::Id> phiOperands;
8506 // accumulate left operand's phi information
8507 phiOperands.push_back(leftId);
8508 phiOperands.push_back(builder.getBuildPoint()->getId());
8509
8510 // Make the two kinds of operation symmetric with a "!"
8511 // || => emit "if (! left) result = right"
8512 // && => emit "if ( left) result = right"
8513 //
8514 // TODO: this runtime "not" for || could be avoided by adding functionality
8515 // to 'builder' to have an "else" without an "then"
8516 if (op == glslang::EOpLogicalOr)
8517 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8518
8519 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008520 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008521
8522 // emit right operand as the "then" part of the "if"
8523 builder.clearAccessChain();
8524 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008525 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008526
8527 // accumulate left operand's phi information
8528 phiOperands.push_back(rightId);
8529 phiOperands.push_back(builder.getBuildPoint()->getId());
8530
8531 // finish the "if"
8532 ifBuilder.makeEndIf();
8533
8534 // phi together the two results
8535 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8536}
8537
John Kessenicha28f7a72019-08-06 07:00:58 -06008538#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008539// Return type Id of the imported set of extended instructions corresponds to the name.
8540// Import this set if it has not been imported yet.
8541spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8542{
8543 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8544 return extBuiltinMap[name];
8545 else {
Rex Xu51596642016-09-21 18:56:12 +08008546 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008547 spv::Id extBuiltins = builder.import(name);
8548 extBuiltinMap[name] = extBuiltins;
8549 return extBuiltins;
8550 }
8551}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008552#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008553
John Kessenich140f3df2015-06-26 16:58:36 -06008554}; // end anonymous namespace
8555
8556namespace glslang {
8557
John Kessenich68d78fd2015-07-12 19:28:10 -06008558void GetSpirvVersion(std::string& version)
8559{
John Kessenich9e55f632015-07-15 10:03:39 -06008560 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008561 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008562 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008563 version = buf;
8564}
8565
John Kessenicha372a3e2017-11-02 22:32:14 -06008566// For low-order part of the generator's magic number. Bump up
8567// when there is a change in the style (e.g., if SSA form changes,
8568// or a different instruction sequence to do something gets used).
8569int GetSpirvGeneratorVersion()
8570{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008571 // return 1; // start
8572 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008573 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008574 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008575 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008576 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8577 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008578 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8579 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008580}
8581
John Kessenich140f3df2015-06-26 16:58:36 -06008582// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008583void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008584{
8585 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008586 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008587 if (out.fail())
8588 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008589 for (int i = 0; i < (int)spirv.size(); ++i) {
8590 unsigned int word = spirv[i];
8591 out.write((const char*)&word, 4);
8592 }
8593 out.close();
8594}
8595
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008596// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008597void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008598{
John Kessenich155d3512019-08-08 23:29:20 -06008599#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008600 std::ofstream out;
8601 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008602 if (out.fail())
8603 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008604 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008605 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008606 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008607 if (varName != nullptr) {
8608 out << "\t #pragma once" << std::endl;
8609 out << "const uint32_t " << varName << "[] = {" << std::endl;
8610 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008611 const int WORDS_PER_LINE = 8;
8612 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8613 out << "\t";
8614 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8615 const unsigned int word = spirv[i + j];
8616 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8617 if (i + j + 1 < (int)spirv.size()) {
8618 out << ",";
8619 }
8620 }
8621 out << std::endl;
8622 }
Flavio15017db2017-02-15 14:29:33 -08008623 if (varName != nullptr) {
8624 out << "};";
8625 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008626 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008627#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008628}
8629
John Kessenich140f3df2015-06-26 16:58:36 -06008630//
8631// Set up the glslang traversal
8632//
John Kessenich4e11b612018-08-30 16:56:59 -06008633void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008634{
Lei Zhang17535f72016-05-04 15:55:59 -04008635 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008636 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008637}
8638
John Kessenich4e11b612018-08-30 16:56:59 -06008639void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008640 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008641{
John Kessenich140f3df2015-06-26 16:58:36 -06008642 TIntermNode* root = intermediate.getTreeRoot();
8643
8644 if (root == 0)
8645 return;
8646
John Kessenich4e11b612018-08-30 16:56:59 -06008647 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008648 if (options == nullptr)
8649 options = &defaultOptions;
8650
John Kessenich4e11b612018-08-30 16:56:59 -06008651 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008652
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008653 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008654 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008655 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008656 it.dumpSpv(spirv);
8657
GregFfb03a552018-03-29 11:49:14 -06008658#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008659 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8660 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008661 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8662 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008663 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008664 prelegalization = false;
8665 }
John Kessenich717c80a2018-08-23 15:17:10 -06008666
John Kessenich4e11b612018-08-30 16:56:59 -06008667 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008668 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008669
John Kessenich717c80a2018-08-23 15:17:10 -06008670 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008671 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008672
GregFcd1f1692017-09-21 18:40:22 -06008673#endif
8674
John Kessenich4e11b612018-08-30 16:56:59 -06008675 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008676}
8677
8678}; // end namespace glslang